momentic-mobile 0.4.0 → 0.4.1

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,42 +1,42 @@
1
1
  #!/usr/bin/env node
2
- var qC=Object.defineProperty;var Be=(r,e)=>()=>(r&&(e=r(r=0)),e);var KC=(r,e)=>{for(var t in e)qC(r,t,{get:e[t],enumerable:!0})};var db,pb=Be(()=>{"use strict";db=typeof globalThis=="object"?globalThis:global});var mb=Be(()=>{"use strict";pb()});var gb=Be(()=>{"use strict";mb()});var jr,Jd=Be(()=>{"use strict";jr="1.9.0"});function $O(r){var e=new Set([r]),t=new Set,n=r.match(hb);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(hb);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 hb,fb,Sb=Be(()=>{"use strict";Jd();hb=/^(\d+)\.(\d+)\.(\d+)(-(.+))?$/;fb=$O(jr)});function Wo(r,e,t,n){var o;n===void 0&&(n=!1);var i=ba[ya]=(o=ba[ya])!==null&&o!==void 0?o:{version:jr};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!==jr){var a=new Error("@opentelemetry/api: Registration of version v"+i.version+" for "+r+" does not match previously registered API v"+jr);return t.error(a.stack||a.message),!1}return i[r]=e,t.debug("@opentelemetry/api: Registered a global for "+r+" v"+jr+"."),!0}function Wr(r){var e,t,n=(e=ba[ya])===null||e===void 0?void 0:e.version;if(!(!n||!fb(n)))return(t=ba[ya])===null||t===void 0?void 0:t[r]}function $o(r,e){e.debug("@opentelemetry/api: Unregistering a global for "+r+" v"+jr+".");var t=ba[ya];t&&delete t[r]}var qO,ya,ba,Ea=Be(()=>{"use strict";gb();Jd();Sb();qO=jr.split(".")[0],ya=Symbol.for("opentelemetry.js.api."+qO),ba=db});function Ta(r,e,t){var n=Wr("diag");if(n)return t.unshift(e),n[r].apply(n,YO([],KO(t),!1))}var KO,YO,yb,bb=Be(()=>{"use strict";Ea();KO=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},YO=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))},yb=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 Ta("debug",this._namespace,e)},r.prototype.error=function(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];return Ta("error",this._namespace,e)},r.prototype.info=function(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];return Ta("info",this._namespace,e)},r.prototype.warn=function(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];return Ta("warn",this._namespace,e)},r.prototype.verbose=function(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];return Ta("verbose",this._namespace,e)},r}()});var Le,Sl=Be(()=>{"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"})(Le||(Le={}))});function Eb(r,e){r<Le.NONE?r=Le.NONE:r>Le.ALL&&(r=Le.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",Le.ERROR),warn:t("warn",Le.WARN),info:t("info",Le.INFO),debug:t("debug",Le.DEBUG),verbose:t("verbose",Le.VERBOSE)}}var Tb=Be(()=>{"use strict";Sl()});var XO,JO,ZO,Mr,va=Be(()=>{"use strict";bb();Tb();Sl();Ea();XO=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},JO=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))},ZO="diag",Mr=function(){function r(){function e(o){return function(){for(var i=[],a=0;a<arguments.length;a++)i[a]=arguments[a];var l=Wr("diag");if(l)return l[o].apply(l,JO([],XO(i),!1))}}var t=this,n=function(o,i){var a,l,c;if(i===void 0&&(i={logLevel:Le.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=Wr("diag"),d=Eb((l=i.logLevel)!==null&&l!==void 0?l:Le.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 Wo("diag",d,t,!0)};t.setLogger=n,t.disable=function(){$o(ZO,t)},t.createComponentLogger=function(o){return new yb(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 vb,Ab=Be(()=>{"use strict";vb=Symbol("BaggageEntryMetadata")});function Zd(r){return typeof r!="string"&&(QO.error("Cannot create baggage metadata from unknown type: "+typeof r),r=""),{__TYPE__:vb,toString:function(){return r}}}var QO,wb=Be(()=>{"use strict";va();Ab();QO=Mr.instance()});function Qd(r){return Symbol.for(r)}var eL,ep,tp=Be(()=>{"use strict";eL=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}(),ep=new eL});function op(){return np}var Wn,tL,yl,rL,nL,oL,iL,rp,aL,sL,lL,np,cL,uL,dL,pL,mL,gL,hL,ip=Be(()=>{"use strict";Wn=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)}}(),tL=function(){function r(){}return r.prototype.createGauge=function(e,t){return uL},r.prototype.createHistogram=function(e,t){return dL},r.prototype.createCounter=function(e,t){return cL},r.prototype.createUpDownCounter=function(e,t){return pL},r.prototype.createObservableGauge=function(e,t){return gL},r.prototype.createObservableCounter=function(e,t){return mL},r.prototype.createObservableUpDownCounter=function(e,t){return hL},r.prototype.addBatchObservableCallback=function(e,t){},r.prototype.removeBatchObservableCallback=function(e){},r}(),yl=function(){function r(){}return r}(),rL=function(r){Wn(e,r);function e(){return r!==null&&r.apply(this,arguments)||this}return e.prototype.add=function(t,n){},e}(yl),nL=function(r){Wn(e,r);function e(){return r!==null&&r.apply(this,arguments)||this}return e.prototype.add=function(t,n){},e}(yl),oL=function(r){Wn(e,r);function e(){return r!==null&&r.apply(this,arguments)||this}return e.prototype.record=function(t,n){},e}(yl),iL=function(r){Wn(e,r);function e(){return r!==null&&r.apply(this,arguments)||this}return e.prototype.record=function(t,n){},e}(yl),rp=function(){function r(){}return r.prototype.addCallback=function(e){},r.prototype.removeCallback=function(e){},r}(),aL=function(r){Wn(e,r);function e(){return r!==null&&r.apply(this,arguments)||this}return e}(rp),sL=function(r){Wn(e,r);function e(){return r!==null&&r.apply(this,arguments)||this}return e}(rp),lL=function(r){Wn(e,r);function e(){return r!==null&&r.apply(this,arguments)||this}return e}(rp),np=new tL,cL=new rL,uL=new oL,dL=new iL,pL=new nL,mL=new aL,gL=new sL,hL=new lL});var Ht,Rb=Be(()=>{"use strict";(function(r){r[r.INT=0]="INT",r[r.DOUBLE=1]="DOUBLE"})(Ht||(Ht={}))});var fL,SL,Cb,xb=Be(()=>{"use strict";tp();fL=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},SL=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))},Cb=function(){function r(){}return r.prototype.active=function(){return ep},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,SL([n],fL(o),!1))},r.prototype.bind=function(e,t){return t},r.prototype.enable=function(){return this},r.prototype.disable=function(){return this},r}()});var yL,bL,ap,EL,Mb,_b=Be(()=>{"use strict";xb();Ea();va();yL=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},bL=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))},ap="context",EL=new Cb,Mb=function(){function r(){}return r.getInstance=function(){return this._instance||(this._instance=new r),this._instance},r.prototype.setGlobalContextManager=function(e){return Wo(ap,e,Mr.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,bL([e,t,n],yL(i),!1))},r.prototype.bind=function(e,t){return this._getContextManager().bind(e,t)},r.prototype._getContextManager=function(){return Wr(ap)||EL},r.prototype.disable=function(){this._getContextManager().disable(),$o(ap,Mr.instance())},r}()});var qo,Pb=Be(()=>{"use strict";_b();qo=Mb.getInstance()});var H,Ib=Be(()=>{"use strict";va();H=Mr.instance()});var TL,Ob,Lb=Be(()=>{"use strict";ip();TL=function(){function r(){}return r.prototype.getMeter=function(e,t,n){return np},r}(),Ob=new TL});var sp,Nb,Db=Be(()=>{"use strict";Lb();Ea();va();sp="metrics",Nb=function(){function r(){}return r.getInstance=function(){return this._instance||(this._instance=new r),this._instance},r.prototype.setGlobalMeterProvider=function(e){return Wo(sp,e,Mr.instance())},r.prototype.getMeterProvider=function(){return Wr(sp)||Ob},r.prototype.getMeter=function(e,t,n){return this.getMeterProvider().getMeter(e,t,n)},r.prototype.disable=function(){$o(sp,Mr.instance())},r}()});var bl,kb=Be(()=>{"use strict";Db();bl=Nb.getInstance()});var Ce=Be(()=>{"use strict";wb();tp();Sl();ip();Rb();Pb();Ib();kb()});import{Argument as $g,Command as Xz,Option as Jz}from"@commander-js/extra-typings";import d0 from"appium";import{execSync as p0}from"child_process";import{z as yu}from"zod";var sH=yu.object({input:yu.string(),agentConfigVersion:yu.string().optional()});import{z as rt}from"zod";var uH=rt.object({srcs:rt.array(rt.string()),urls:rt.array(rt.string()),desiredSrc:rt.string().optional(),desiredUrl:rt.string().optional()}),Yg=rt.object({srcRegex:rt.string().optional(),urlRegex:rt.string().optional()}),Xg=rt.object({x:rt.number(),y:rt.number(),correlation:rt.number()}),dH=rt.object({searchImageBase64String:rt.string(),pageImageBase64String:rt.string(),id:rt.string().uuid(),timeoutMs:rt.number().max(1e4).min(0).optional()});import{z as I}from"zod";import*as L from"zod";import{extendZodWithOpenApi as YC}from"zod-openapi";YC(L);var Jr=(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))(Jr||{}),XC=L.object({mPathSelectorTokens:L.string().array(),frameSrcRegex:L.string().optional(),frameUrlRegex:L.string().optional(),indices:L.number().array()}),bu=L.object({result:L.number(),traceId:L.string()}).array(),ms=L.object({type:L.literal("GCS_TRACES"),traces:bu}),Xr=(o=>(o.Precise="precise",o.Narrow="narrow",o.Unspecific="broad",o.Irrelevant="irrelevant",o))(Xr||{}),Jg=L.object({attributes:L.record(L.string(),L.string()).optional(),text:L.string().optional(),position:L.object({x1:L.number(),y1:L.number(),x2:L.number(),y2:L.number(),tolerance:L.nativeEnum(Xr)}).optional(),shape:L.object({width:L.number(),height:L.number(),tolerance:L.nativeEnum(Xr)}).optional(),boundingBox:L.object({x:L.number(),y:L.number(),width:L.number(),height:L.number()}).optional()}),JC=L.object({selectors:L.string().array(),requirements:Jg.optional()}),Zr=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().optional()),tagName:L.string(),expandShadowRoot:L.boolean().optional(),classNames:L.string().array(),nthChild:L.number()}).array().optional(),generatedSelectors:L.string().array().optional(),requirements:Jg.optional(),additionalElements:JC.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:XC.optional(),inputDescription:L.string().optional().describe("the description that generated this cache"),targetSource:L.nativeEnum(Jr).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:ms.optional()}).openapi({ref:"ElementTargetCache"});function gs(r){return!!(r.serializedHtml||r.screenshotUrl||r.generatedSelectors||r.hybridSelector)}var ZC=L.object({type:L.literal("description"),elementDescriptor:L.string().describe("Description of the element.")}).openapi({ref:"DescriptionTarget"}),QC=L.object({x:L.number(),y:L.number()}),ex=L.object({type:L.literal("coordinates"),pixels:QC}).openapi({ref:"CoordinatesTarget"});function Qr(r){return r.type==="description"}function Er(r){return r.type==="coordinates"}var ht=L.discriminatedUnion("type",[ZC,ex]).openapi({ref:"ElementTarget"});function Eu(r){if(!r)return!1;switch(r.type){case"description":return!!r.elementDescriptor}return!0}function Zg(r){return ms.safeParse(r).success}import{v4 as fe}from"uuid";import*as y from"zod";import{extendZodWithOpenApi as lx}from"zod-openapi";import{z as ee}from"zod";import{extendZodWithOpenApi as tx}from"zod-openapi";import{z as Oi}from"zod";import Qg from"zod";var Ii=Qg.object({updatedAt:Qg.coerce.date().optional()});var Tu=Oi.object({result:Oi.boolean(),traceId:Oi.string()}).array(),vu=Oi.object({type:Oi.literal("GCS_TRACES"),traces:Tu}),Au=Ii.extend({memory:vu.optional()});tx(ee);var eh=ee.object({plan:ee.string().optional(),evidence:ee.string().optional(),thoughts:ee.string(),result:ee.boolean(),relevantElements:ee.array(ee.number()).optional(),updatedMemory:Tu.optional()}),zr=(o=>(o.CONTAINS="CONTAINS",o.STARTS_WITH="STARTS_WITH",o.EQUALS="EQUALS",o.EXISTS="EXISTS",o))(zr||{});var rx=ee.object({type:ee.literal("ELEMENT_NAME"),negated:ee.boolean().optional(),operation:ee.nativeEnum(zr),value:ee.string()}).openapi({ref:"ElementNameAssertion"}),nx=ee.object({type:ee.literal("ELEMENT_STYLE"),negated:ee.boolean().optional(),operation:ee.nativeEnum(zr),property:ee.string(),value:ee.string()}).openapi({ref:"ElementStyleAssertion"}),ox=ee.object({type:ee.literal("ELEMENT_CONTENT"),negated:ee.boolean().optional(),operation:ee.nativeEnum(zr),value:ee.string()}).openapi({ref:"ElementContentAssertion"}),ix=ee.object({type:ee.literal("ELEMENT_ATTRIBUTE"),negated:ee.boolean().optional(),operation:ee.nativeEnum(zr),attr:ee.string(),value:ee.string()}).openapi({ref:"ElementAttributeValueAssertion"}),_n=(i=>(i.EXISTS="EXISTS",i.VISIBLE="VISIBLE",i.ENABLED="ENABLED",i.EDITABLE="EDITABLE",i.FOCUSED="FOCUSED",i))(_n||{}),ax=ee.object({type:ee.literal("ELEMENT_EXISTENCE"),negated:ee.boolean().optional(),condition:ee.nativeEnum(_n).describe("Treated as the element exists AND is also ...")}).openapi({ref:"ElementExistenceAssertion"}),th=ee.discriminatedUnion("type",[ox,ix,ax,rx,nx]).openapi({ref:"ManualElementAssertion"});var sx=ee.object({type:ee.literal("CONTENT"),negated:ee.boolean().optional(),value:ee.string()}).openapi({ref:"PageContentAssertion"}),rh=ee.discriminatedUnion("type",[sx]).openapi({ref:"ManualPageAssertion"});import Ct from"zod";var wu=Ct.discriminatedUnion("type",[Ct.object({type:Ct.literal("SUBSTRING"),url:Ct.string()}),Ct.object({type:Ct.literal("GLOB"),glob:Ct.string()}),Ct.object({type:Ct.literal("REGEX"),regex:Ct.string()}),Ct.object({type:Ct.literal("DOMAIN"),domain:Ct.string()})]),Li=Ct.object({urlMatcher:wu,method:Ct.string().optional()});import{z as he}from"zod";var yo=he.object({url:he.string(),method:he.union([he.literal("GET"),he.literal("POST"),he.literal("PUT"),he.literal("DELETE"),he.literal("PATCH")]),headers:he.record(he.string(),he.string()).optional(),params:he.record(he.string(),he.string()).optional(),body:he.string().optional(),timeout:he.number().int().optional().describe("Max seconds to wait for the request to complete")}),nh=he.object({url:he.string(),headers:he.record(he.string(),he.string()).optional(),query:he.string(),variables:he.string().optional(),timeout:he.number().int().optional().describe("Max seconds to wait for the request to complete")}),hs=he.object({code:he.string(),fragment:he.boolean().optional().describe("Agents should not touch this unless explicitly told to"),environment:he.union([he.literal("NODE"),he.literal("BROWSER")]).optional().describe("default NODE, Agents default to using node unless it is necessary to use browser"),timeout:he.number().int().max(60).optional().describe("Max seconds for the code to complete")});var nt=(V=>(V.AI_EXTRACT="AI_EXTRACT",V.AI_ASSERTION="AI_ASSERTION",V.AUTH_LOAD="AUTH_LOAD",V.AUTH_SAVE="AUTH_SAVE",V.BLUR="BLUR",V.CAPTCHA="CAPTCHA",V.CLICK="CLICK",V.COOKIE="COOKIE",V.COPY="COPY",V.DIALOG="DIALOG",V.DRAG="DRAG",V.ELEMENT_CHECK="ELEMENT_CHECK",V.FILE_UPLOAD="FILE_UPLOAD",V.FOCUS="FOCUS",V.GO_BACK="GO_BACK",V.GO_FORWARD="GO_FORWARD",V.HOVER="HOVER",V.JAVASCRIPT="JAVASCRIPT",V.LOCAL_STORAGE="LOCAL_STORAGE",V.MOUSE_DRAG="MOUSE_DRAG",V.NAVIGATE="NAVIGATE",V.NEW_TAB="NEW_TAB",V.PAGE_CHECK="PAGE_CHECK",V.PASTE="PASTE",V.PRESS="PRESS",V.KEY_DOWN="KEY_DOWN",V.KEY_UP="KEY_UP",V.REFRESH="REFRESH",V.REQUEST="REQUEST",V.GRAPHQL_REQUEST="GRAPHQL_REQUEST",V.SCROLL_DOWN="SCROLL_DOWN",V.SCROLL_UP="SCROLL_UP",V.SCROLL_LEFT="SCROLL_LEFT",V.SCROLL_RIGHT="SCROLL_RIGHT",V.SELECT_OPTION="SELECT_OPTION",V.SWITCH_TAB="TAB",V.TYPE="TYPE",V.VISUAL_DIFF="VISUAL_DIFF",V.WAIT="WAIT",V.WAIT_FOR_URL="WAIT_FOR_URL",V.REGISTER_REQUEST_LISTENER="REGISTER_REQUEST_LISTENER",V.AWAIT_LISTENER="AWAIT_LISTENER",V.RECORD_REQUESTS="RECORD_REQUESTS",V.GET_RECORDED_REQUESTS="GET_RECORDED_REQUESTS",V.SET_HEADER="SET_HEADER",V.MOCK_ROUTE="MOCK_ROUTE",V.REMOVE_ROUTE_MOCK="REMOVE_ROUTE_MOCK",V.OFFLINE_MODE="OFFLINE_MODE",V.SUCCESS="SUCCESS",V))(nt||{});lx(y);var q=y.object({thoughts:y.string().optional(),id:y.string().uuid().describe("unique identifier to this step, used for step cache")}),jt=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"}),Wt=Ii.extend({target:Zr}).optional().openapi({ref:"SingleTargetCache"});function oh(r){return Wt.safeParse(r).success}var fs=y.object({loadTimeout:y.number().int().max(60).optional().describe("Max seconds for the page to load")}),cx=q.merge(fs).merge(y.object({type:y.literal("NAVIGATE"),url:y.string()})).openapi({ref:"NavigateCommand"}),Ss=jt.merge(y.object({cache:Wt})),bo=q.merge(Ss.merge(y.object({target:ht.optional(),type:y.literal("SCROLL_UP"),deltaY:y.number().optional()}))).openapi({ref:"ScrollUpCommand"}),Eo=q.merge(Ss.merge(y.object({target:ht.optional(),type:y.literal("SCROLL_DOWN"),deltaY:y.number().optional()}))).openapi({ref:"ScrollDownCommand"}),To=q.merge(Ss.merge(y.object({target:ht.optional(),type:y.literal("SCROLL_LEFT"),deltaX:y.number().optional()}))).openapi({ref:"ScrollLeftCommand"}),vo=q.merge(Ss.merge(y.object({target:ht.optional(),type:y.literal("SCROLL_RIGHT"),deltaX:y.number().optional()}))).openapi({ref:"ScrollRightCommand"}),HH=y.discriminatedUnion("type",[bo,Eo,To,vo]).openapi({ref:"AllScrollCommands"}),ux=q.merge(y.object({type:y.literal("DIALOG"),action:y.union([y.literal("ACCEPT"),y.literal("DISMISS")])})).openapi({ref:"DialogCommand"}),dx=q.merge(y.object({type:y.literal("WAIT"),delay:y.number()})).openapi({ref:"WaitCommand"}),px=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")}),ih=q.extend({type:y.literal("WAIT_FOR_URL"),matcher:wu}).merge(px).openapi({ref:"WaitUrlCommand"}),ah=q.merge(fs).merge(y.object({type:y.literal("REFRESH")})).openapi({ref:"RefreshCommand"}),mx=q.merge(y.object({type:y.literal("GO_BACK")})).openapi({ref:"GoBackCommand"}),sh=q.merge(y.object({type:y.literal("GO_FORWARD")})).openapi({ref:"GoForwardCommand"}),gx=q.extend({type:y.literal("AUTH_SAVE")}).openapi({ref:"AuthSaveCommand"}),hx=q.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"}),Cu=q.merge(jt).extend({type:y.literal("CAPTCHA")}).openapi({ref:"CaptchaCommand"}),lh=q.extend({type:y.literal("COPY"),value:y.string()}).openapi({ref:"CopyCommand"}),ch=q.extend({type:y.literal("PASTE")}).openapi({ref:"PasteCommand"}),uh=q.merge(hs).extend({type:y.literal("JAVASCRIPT")}).openapi({ref:"JavaScriptCommand"}),Di=q.merge(jt).extend({type:y.literal("CLICK"),target:ht,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:Wt,relativePosition:y.object({x:y.number(),y:y.number()}).optional()}).openapi({ref:"ClickCommand"}),dh=Ii.extend({fromTarget:Zr.optional(),toTarget:Zr.optional()}),Ao=q.merge(jt).merge(y.object({type:y.literal("DRAG"),fromTarget:ht,toTarget:ht,steps:y.number().optional(),hoverSeconds:y.number().optional().describe("Seconds to hover the object before dropping"),cache:dh.optional()})).openapi({ref:"DragCommand"}),wo=q.merge(jt).merge(y.object({type:y.literal("MOUSE_DRAG"),target:ht.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:Wt})).openapi({ref:"MouseDragCommand"}),ki=q.merge(jt).merge(y.object({type:y.literal("HOVER"),target:ht,cache:Wt})).openapi({ref:"HoverCommand"}),Ui=q.merge(jt).merge(y.object({type:y.literal("FOCUS"),target:ht,cache:Wt})).openapi({ref:"FocusCommand"}),Fi=q.merge(jt).extend({type:y.literal("BLUR"),target:ht.optional(),cache:Wt}).openapi({ref:"BlurCommand"}),fx=y.object({type:y.literal("URL"),url:y.string()}).describe("Accessible link to the file, either public http or local file://").openapi({ref:"UrlSource"}),Sx=y.object({type:y.literal("USER_FILE"),name:y.string()}).describe("Accessible link to the file, references the google cloud file").openapi({ref:"UploadedFileSource"}),yx=q.extend({type:y.literal("FILE_UPLOAD"),fileSource:y.discriminatedUnion("type",[fx,Sx]),filename:y.string().optional()}).openapi({ref:"FileUploadCommand"}),ph=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()})]),Bi=q.merge(jt).extend({type:y.literal("SELECT_OPTION"),target:ht,cache:Wt,choice:ph.describe("new field for selecting options, optional for backcompat")}).openapi({ref:"SelectOptionCommand"}),xu=y.union([y.literal("MULTIMODAL"),y.literal("VISION_ONLY")]),ys=q.merge(y.object({type:y.literal("AI_ASSERTION"),assertion:y.string(),disableCache:y.boolean().optional(),iframeUrl:y.string().optional(),contextChoice:xu.optional(),timeout:y.number().int().optional().describe("Max seconds to wait for assertion to be true"),cache:Au.optional()})).openapi({ref:"AIAssertionCommand"}),en=5,Mu=600,Ro=q.merge(jt).extend({type:y.literal("ELEMENT_CHECK"),target:ht,assertion:th,cache:Wt.or(Au).optional(),timeout:y.number().int().min(0).max(Mu).optional().describe("max seconds to wait for the assertion to be true")}).openapi({ref:"ElementAssertionCommand"}),mh=q.extend({type:y.literal("PAGE_CHECK"),assertion:rh,iframeUrl:y.string().optional().describe("url or url regex for the iframe"),timeout:y.number().int().min(0).max(Mu).optional().describe("max seconds to wait for the assertion to be true")}).openapi({ref:"PageAssertionCommand"}),gh=q.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"}),bx=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(),relativePosition:y.object({x:y.number(),y:y.number()}).optional()}),hh=25,zi=q.merge(jt).merge(bx).extend({type:y.literal("TYPE"),target:ht.optional(),value:y.string(),cache:Wt}).openapi({ref:"TypeCommand"}),Ex=q.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"}),Tx=q.merge(y.object({type:y.literal("KEY_DOWN"),value:y.string(),convertMeta:y.boolean().optional()})).openapi({ref:"KeyDownCommand"}),vx=q.merge(y.object({type:y.literal("KEY_UP"),value:y.string(),convertMeta:y.boolean().optional()})).openapi({ref:"KeyUpCommand"}),Ax=y.object({type:y.literal("SUBSTRING"),substring:y.string()}),wx=y.object({type:y.literal("REGEX"),pattern:y.string()}),Rx=y.object({type:y.literal("INDEX"),index:y.coerce.string()}),Cx=y.discriminatedUnion("type",[Ax,wx,Rx]),xx=q.merge(fs).merge(y.object({type:y.literal("TAB"),action:Cx})).openapi({ref:"TabCommand"}),fh=q.merge(fs).merge(y.object({type:y.literal("NEW_TAB"),url:y.string()})).openapi({ref:"NewTabCommand"}),Mx=q.merge(y.object({type:y.literal("COOKIE"),value:y.string()})).openapi({ref:"CookieCommand"}),Sh=q.merge(y.object({type:y.literal("LOCAL_STORAGE"),key:y.string(),value:y.string()})).openapi({ref:"LocalStorageCommand"}),yh=q.extend({type:y.literal("REQUEST")}).merge(yo).openapi({ref:"RequestCommand"}),_x=q.extend({type:y.literal("GRAPHQL_REQUEST")}).merge(nh).openapi({ref:"GraphQLRequestCommand"}),Px=q.merge(y.object({type:y.literal("SUCCESS"),condition:ys.optional()})).openapi({ref:"SuccessCommand"}),bh=q.merge(y.object({type:y.literal("FAILURE")})).openapi({ref:"FailureCommand"}),Ix=y.object({data:y.string().describe("location at which to find a jpg"),width:y.number(),height:y.number()}),Hi=q.merge(jt).merge(y.object({type:y.literal("VISUAL_DIFF"),threshold:y.number().optional().describe("default 0.1"),target:ht.optional(),screenshot:Ix.optional(),cache:Wt})).openapi({ref:"VisualDiffCommand"}),Ox=q.merge(y.object({type:y.literal("REGISTER_REQUEST_LISTENER"),requestMatcher:Li,key:y.string()})).openapi({ref:"RegisterRequestListenerCommand"}),Lx=q.merge(y.object({type:y.literal("AWAIT_LISTENER"),key:y.string(),timeout:y.number().optional().describe("timeout")})).openapi({ref:"WaitForListenerCommand"}),Nx=q.merge(y.object({type:y.literal("RECORD_REQUESTS"),requestMatcher:Li,key:y.string()})).openapi({ref:"RecordRequestsCommand"}),Dx=q.merge(y.object({type:y.literal("GET_RECORDED_REQUESTS"),key:y.string()})).openapi({ref:"GetRecordedRequestsCommand"}),kx=q.merge(y.object({type:y.literal("SET_HEADER"),name:y.string(),value:y.string(),requestMatcher:Li.optional()})).openapi({ref:"SetHeaderCommand"}),Ux=q.merge(y.object({type:y.literal("MOCK_ROUTE"),requestMatcher:Li,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"})),Fx=q.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"})),Bx=q.merge(y.object({type:y.literal("OFFLINE_MODE"),enable:y.boolean()})).openapi({ref:"OfflineModeCommand"}),zx=y.discriminatedUnion("type",[Di,zi,Ex,Tx,vx,Bi,cx,Eo,bo,ys,mx,ki,dx]),_u=y.discriminatedUnion("type",[...zx.options,Px]),Pu=y.discriminatedUnion("type",[..._u.options,Ao,uh,Ro,mh,fh,ih,gh,lh,sh,Sh,wo,ch,ah,yh]),Hx=y.discriminatedUnion("type",[gh,hx,gx,Cu,Mx,lh,ux,Ao,Ro,yx,sh,uh,Sh,wo,fh,mh,ch,ah,yh,_x,To,vo,xx,Hi,Ui,Fi,ih,Ox,Lx,Nx,Dx,kx,Ux,Fx,Bx]),Co=y.discriminatedUnion("type",[..._u.options,...Hx.options]).openapi({ref:"Command"}),bs=y.discriminatedUnion("type",[..._u.options,bh]),GH=y.discriminatedUnion("type",[...Pu.options,bh]);function Hr(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:fe(),type:r};break;case"AUTH_LOAD":{e={id:fe(),type:r,storageState:""};break}case"AI_EXTRACT":e={id:fe(),type:r,goal:""};break;case"DIALOG":e={id:fe(),type:r,action:"DISMISS"};break;case"DRAG":e={id:fe(),type:r,fromTarget:{type:"description",elementDescriptor:""},toTarget:{type:"description",elementDescriptor:""}};break;case"MOUSE_DRAG":e={id:fe(),type:r,deltaX:"0",deltaY:"0",steps:1};break;case"WAIT_FOR_URL":e={id:fe(),type:r,matcher:{type:"SUBSTRING",url:""}};break;case"WAIT":e={id:fe(),type:r,delay:1};break;case"BLUR":e={id:fe(),type:r};break;case"HOVER":case"FOCUS":case"CLICK":e={id:fe(),type:r,target:{type:"description",elementDescriptor:""}};break;case"COOKIE":case"PRESS":case"COPY":case"TYPE":e={id:fe(),type:r,value:"",clearContent:!0};break;case"KEY_DOWN":case"KEY_UP":e={id:fe(),type:r,value:""};break;case"SELECT_OPTION":e={id:fe(),type:r,target:{type:"description",elementDescriptor:""},choice:{type:"VALUE",value:""}};break;case"NAVIGATE":case"NEW_TAB":return{id:fe(),type:r,url:""};case"TAB":e={id:fe(),type:r,action:{type:"SUBSTRING",substring:""}};break;case"REQUEST":e={id:fe(),type:r,url:"",method:"GET"};break;case"GRAPHQL_REQUEST":e={id:fe(),type:r,url:"",query:""};break;case"LOCAL_STORAGE":e={id:fe(),type:r,key:"",value:""};break;case"JAVASCRIPT":e={id:fe(),type:r,code:""};break;case"AI_ASSERTION":e={id:fe(),type:r,assertion:""};break;case"FILE_UPLOAD":{e={id:fe(),type:r,fileSource:{type:"URL",url:""}};break}case"ELEMENT_CHECK":{e={id:fe(),type:r,target:{type:"description",elementDescriptor:""},assertion:{type:"ELEMENT_EXISTENCE",condition:"EXISTS"}};break}case"PAGE_CHECK":{e={id:fe(),type:r,assertion:{type:"CONTENT",value:""}};break}case"REGISTER_REQUEST_LISTENER":{e={id:fe(),type:r,requestMatcher:{urlMatcher:{type:"REGEX",regex:""}},key:""};break}case"AWAIT_LISTENER":{e={id:fe(),type:r,key:""};break}case"RECORD_REQUESTS":{e={id:fe(),type:r,requestMatcher:{urlMatcher:{type:"REGEX",regex:""}},key:""};break}case"GET_RECORDED_REQUESTS":{e={id:fe(),type:r,key:""};break}case"SET_HEADER":{e={id:fe(),type:r,name:"",value:""};break}case"MOCK_ROUTE":{e={id:fe(),type:r,requestMatcher:{urlMatcher:{type:"REGEX",regex:""}},responseGenerator:""};break}case"REMOVE_ROUTE_MOCK":{e={id:fe(),type:r};break}case"OFFLINE_MODE":{e={id:fe(),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 Eh(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 Gx}from"zod";var qH=Gx.discriminatedUnion("type",[Fi,Cu,Di,Ao,Ui,ki,wo,bo,Eo,To,vo,Bi,zi,Hi,Ro]);import{z as Vx}from"zod";import{z as tn}from"zod";function Gi(r){return tn.object({key:tn.string(),testId:tn.string().optional(),moduleId:tn.string().optional(),organizationId:tn.string(),value:r})}function Vi(r){return Gi(r).extend({uniqueKey:tn.string()})}function Es(r){return tn.record(tn.string(),Vi(r))}var xt={type:!0,cache:!0},xo=Vx.discriminatedUnion("type",[ys.pick(xt),Fi.pick(xt),Di.pick(xt),Ao.pick(xt),Ro.pick(xt),Ui.pick(xt),ki.pick(xt),wo.pick(xt),bo.pick(xt),Eo.pick(xt),To.pick(xt),vo.pick(xt),Bi.pick(xt),zi.pick(xt),Hi.pick(xt)]),Iu=Object.values(nt).filter(r=>xo.options.some(e=>e.shape.type.safeParse(r).success));Co.options.forEach(r=>{if("target"in r.shape&&!Iu.includes(r.shape.type.value))throw new Error(`Command ${r.shape.type.value} has a target but no cache`)});function Th(r){return Iu.includes(r.type)}var vh=Gi(xo),Ah=Vi(xo),tG=Es(xo);import{v4 as tW}from"uuid";import{z as T}from"zod";var Rh=Symbol("Let zodToJsonSchema decide on which parser to use");var wh={name:void 0,$refStrategy:"root",basePath:["#"],effectStrategy:"input",pipeStrategy:"all",dateStrategy:"format:date-time",mapStrategy:"entries",removeAdditionalStrategy:"passthrough",allowedAdditionalProperties:!0,rejectedAdditionalProperties:!1,definitionPath:"definitions",target:"jsonSchema7",strictUnions:!1,definitions:{},errorMessages:!1,markdownDescription:!1,patternStrategy:"escape",applyRegexFlags:!1,emailStrategy:"format:email",base64Strategy:"contentEncoding:base64",nameStrategy:"ref",openAiAnyTypeName:"OpenAiAnyType"},Ch=r=>typeof r=="string"?{...wh,name:r}:{...wh,...r};var xh=r=>{let e=Ch(r),t=e.name!==void 0?[...e.basePath,e.definitionPath,e.name]:e.basePath;return{...e,flags:{hasReferencedOpenAiAnyType:!1},currentPath:t,propertyPath:void 0,seen:new Map(Object.entries(e.definitions).map(([n,o])=>[o._def,{def:o._def,path:[...e.basePath,e.definitionPath,n],jsonSchema:void 0}]))}};function Ou(r,e,t,n){n?.errorMessages&&t&&(r.errorMessage={...r.errorMessage,[e]:t})}function ce(r,e,t,n,o){r[e]=t,Ou(r,e,n,o)}var Ts=(r,e)=>{let t=0;for(;t<r.length&&t<e.length&&r[t]===e[t];t++);return[(r.length-t).toString(),...e.slice(t)].join("/")};import{ZodFirstPartyTypeKind as se}from"zod";function Ne(r){if(r.target!=="openAi")return{};let e=[...r.basePath,r.definitionPath,r.openAiAnyTypeName];return r.flags.hasReferencedOpenAiAnyType=!0,{$ref:r.$refStrategy==="relative"?Ts(e,r.currentPath):e.join("/")}}import{ZodFirstPartyTypeKind as jx}from"zod";function Mh(r,e){let t={type:"array"};return r.type?._def&&r.type?._def?.typeName!==jx.ZodAny&&(t.items=K(r.type._def,{...e,currentPath:[...e.currentPath,"items"]})),r.minLength&&ce(t,"minItems",r.minLength.value,r.minLength.message,e),r.maxLength&&ce(t,"maxItems",r.maxLength.value,r.maxLength.message,e),r.exactLength&&(ce(t,"minItems",r.exactLength.value,r.exactLength.message,e),ce(t,"maxItems",r.exactLength.value,r.exactLength.message,e)),t}function _h(r,e){let t={type:"integer",format:"int64"};if(!r.checks)return t;for(let n of r.checks)switch(n.kind){case"min":e.target==="jsonSchema7"?n.inclusive?ce(t,"minimum",n.value,n.message,e):ce(t,"exclusiveMinimum",n.value,n.message,e):(n.inclusive||(t.exclusiveMinimum=!0),ce(t,"minimum",n.value,n.message,e));break;case"max":e.target==="jsonSchema7"?n.inclusive?ce(t,"maximum",n.value,n.message,e):ce(t,"exclusiveMaximum",n.value,n.message,e):(n.inclusive||(t.exclusiveMaximum=!0),ce(t,"maximum",n.value,n.message,e));break;case"multipleOf":ce(t,"multipleOf",n.value,n.message,e);break}return t}function Ph(){return{type:"boolean"}}function vs(r,e){return K(r.type._def,e)}var Ih=(r,e)=>K(r.innerType._def,e);function Lu(r,e,t){let n=t??e.dateStrategy;if(Array.isArray(n))return{anyOf:n.map((o,i)=>Lu(r,e,o))};switch(n){case"string":case"format:date-time":return{type:"string",format:"date-time"};case"format:date":return{type:"string",format:"date"};case"integer":return Wx(r,e)}}var Wx=(r,e)=>{let t={type:"integer",format:"unix-time"};if(e.target==="openApi3")return t;for(let n of r.checks)switch(n.kind){case"min":ce(t,"minimum",n.value,n.message,e);break;case"max":ce(t,"maximum",n.value,n.message,e);break}return t};function Oh(r,e){return{...K(r.innerType._def,e),default:r.defaultValue()}}function Lh(r,e){return e.effectStrategy==="input"?K(r.schema._def,e):Ne(e)}function Nh(r){return{type:"string",enum:Array.from(r.values)}}var $x=r=>"type"in r&&r.type==="string"?!1:"allOf"in r;function Dh(r,e){let t=[K(r.left._def,{...e,currentPath:[...e.currentPath,"allOf","0"]}),K(r.right._def,{...e,currentPath:[...e.currentPath,"allOf","1"]})].filter(i=>!!i),n=e.target==="jsonSchema2019-09"?{unevaluatedProperties:!1}:void 0,o=[];return t.forEach(i=>{if($x(i))o.push(...i.allOf),i.unevaluatedProperties===void 0&&(n=void 0);else{let a=i;if("additionalProperties"in i&&i.additionalProperties===!1){let{additionalProperties:l,...c}=i;a=c}else n=void 0;o.push(a)}}),o.length?{allOf:o,...n}:void 0}function kh(r,e){let t=typeof r.value;return t!=="bigint"&&t!=="number"&&t!=="boolean"&&t!=="string"?{type:Array.isArray(r.value)?"array":"object"}:e.target==="openApi3"?{type:t==="bigint"?"integer":t,enum:[r.value]}:{type:t==="bigint"?"integer":t,const:r.value}}import{ZodFirstPartyTypeKind as ji}from"zod";var Nu,ur={cuid:/^[cC][^\s-]{8,}$/,cuid2:/^[0-9a-z]+$/,ulid:/^[0-9A-HJKMNP-TV-Z]{26}$/,email:/^(?!\.)(?!.*\.\.)([a-zA-Z0-9_'+\-\.]*)[a-zA-Z0-9_+-]@([a-zA-Z0-9][a-zA-Z0-9\-]*\.)+[a-zA-Z]{2,}$/,emoji:()=>(Nu===void 0&&(Nu=RegExp("^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$","u")),Nu),uuid:/^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/,ipv4:/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,ipv4Cidr:/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/(3[0-2]|[12]?[0-9])$/,ipv6:/^(([a-f0-9]{1,4}:){7}|::([a-f0-9]{1,4}:){0,6}|([a-f0-9]{1,4}:){1}:([a-f0-9]{1,4}:){0,5}|([a-f0-9]{1,4}:){2}:([a-f0-9]{1,4}:){0,4}|([a-f0-9]{1,4}:){3}:([a-f0-9]{1,4}:){0,3}|([a-f0-9]{1,4}:){4}:([a-f0-9]{1,4}:){0,2}|([a-f0-9]{1,4}:){5}:([a-f0-9]{1,4}:){0,1})([a-f0-9]{1,4}|(((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))\.){3}((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2})))$/,ipv6Cidr:/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,base64:/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,base64url:/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,nanoid:/^[a-zA-Z0-9_-]{21}$/,jwt:/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/};function As(r,e){let t={type:"string"};if(r.checks)for(let n of r.checks)switch(n.kind){case"min":ce(t,"minLength",typeof t.minLength=="number"?Math.max(t.minLength,n.value):n.value,n.message,e);break;case"max":ce(t,"maxLength",typeof t.maxLength=="number"?Math.min(t.maxLength,n.value):n.value,n.message,e);break;case"email":switch(e.emailStrategy){case"format:email":dr(t,"email",n.message,e);break;case"format:idn-email":dr(t,"idn-email",n.message,e);break;case"pattern:zod":Mt(t,ur.email,n.message,e);break}break;case"url":dr(t,"uri",n.message,e);break;case"uuid":dr(t,"uuid",n.message,e);break;case"regex":Mt(t,n.regex,n.message,e);break;case"cuid":Mt(t,ur.cuid,n.message,e);break;case"cuid2":Mt(t,ur.cuid2,n.message,e);break;case"startsWith":Mt(t,RegExp(`^${Du(n.value,e)}`),n.message,e);break;case"endsWith":Mt(t,RegExp(`${Du(n.value,e)}$`),n.message,e);break;case"datetime":dr(t,"date-time",n.message,e);break;case"date":dr(t,"date",n.message,e);break;case"time":dr(t,"time",n.message,e);break;case"duration":dr(t,"duration",n.message,e);break;case"length":ce(t,"minLength",typeof t.minLength=="number"?Math.max(t.minLength,n.value):n.value,n.message,e),ce(t,"maxLength",typeof t.maxLength=="number"?Math.min(t.maxLength,n.value):n.value,n.message,e);break;case"includes":{Mt(t,RegExp(Du(n.value,e)),n.message,e);break}case"ip":{n.version!=="v6"&&dr(t,"ipv4",n.message,e),n.version!=="v4"&&dr(t,"ipv6",n.message,e);break}case"base64url":Mt(t,ur.base64url,n.message,e);break;case"jwt":Mt(t,ur.jwt,n.message,e);break;case"cidr":{n.version!=="v6"&&Mt(t,ur.ipv4Cidr,n.message,e),n.version!=="v4"&&Mt(t,ur.ipv6Cidr,n.message,e);break}case"emoji":Mt(t,ur.emoji(),n.message,e);break;case"ulid":{Mt(t,ur.ulid,n.message,e);break}case"base64":{switch(e.base64Strategy){case"format:binary":{dr(t,"binary",n.message,e);break}case"contentEncoding:base64":{ce(t,"contentEncoding","base64",n.message,e);break}case"pattern:zod":{Mt(t,ur.base64,n.message,e);break}}break}case"nanoid":Mt(t,ur.nanoid,n.message,e);case"toLowerCase":case"toUpperCase":case"trim":break;default:}return t}function Du(r,e){return e.patternStrategy==="escape"?Kx(r):r}var qx=new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789");function Kx(r){let e="";for(let t=0;t<r.length;t++)qx.has(r[t])||(e+="\\"),e+=r[t];return e}function dr(r,e,t,n){r.format||r.anyOf?.some(o=>o.format)?(r.anyOf||(r.anyOf=[]),r.format&&(r.anyOf.push({format:r.format,...r.errorMessage&&n.errorMessages&&{errorMessage:{format:r.errorMessage.format}}}),delete r.format,r.errorMessage&&(delete r.errorMessage.format,Object.keys(r.errorMessage).length===0&&delete r.errorMessage)),r.anyOf.push({format:e,...t&&n.errorMessages&&{errorMessage:{format:t}}})):ce(r,"format",e,t,n)}function Mt(r,e,t,n){r.pattern||r.allOf?.some(o=>o.pattern)?(r.allOf||(r.allOf=[]),r.pattern&&(r.allOf.push({pattern:r.pattern,...r.errorMessage&&n.errorMessages&&{errorMessage:{pattern:r.errorMessage.pattern}}}),delete r.pattern,r.errorMessage&&(delete r.errorMessage.pattern,Object.keys(r.errorMessage).length===0&&delete r.errorMessage)),r.allOf.push({pattern:Uh(e,n),...t&&n.errorMessages&&{errorMessage:{pattern:t}}})):ce(r,"pattern",Uh(e,n),t,n)}function Uh(r,e){if(!e.applyRegexFlags||!r.flags)return r.source;let t={i:r.flags.includes("i"),m:r.flags.includes("m"),s:r.flags.includes("s")},n=t.i?r.source.toLowerCase():r.source,o="",i=!1,a=!1,l=!1;for(let c=0;c<n.length;c++){if(i){o+=n[c],i=!1;continue}if(t.i){if(a){if(n[c].match(/[a-z]/)){l?(o+=n[c],o+=`${n[c-2]}-${n[c]}`.toUpperCase(),l=!1):n[c+1]==="-"&&n[c+2]?.match(/[a-z]/)?(o+=n[c],l=!0):o+=`${n[c]}${n[c].toUpperCase()}`;continue}}else if(n[c].match(/[a-z]/)){o+=`[${n[c]}${n[c].toUpperCase()}]`;continue}}if(t.m){if(n[c]==="^"){o+=`(^|(?<=[\r
2
+ var JC=Object.defineProperty;var Be=(r,e)=>()=>(r&&(e=r(r=0)),e);var ZC=(r,e)=>{for(var t in e)JC(r,t,{get:e[t],enumerable:!0})};var gb,hb=Be(()=>{"use strict";gb=typeof globalThis=="object"?globalThis:global});var fb=Be(()=>{"use strict";hb()});var Sb=Be(()=>{"use strict";fb()});var $r,ep=Be(()=>{"use strict";$r="1.9.0"});function ZO(r){var e=new Set([r]),t=new Set,n=r.match(yb);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(yb);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 yb,bb,Eb=Be(()=>{"use strict";ep();yb=/^(\d+)\.(\d+)\.(\d+)(-(.+))?$/;bb=ZO($r)});function $o(r,e,t,n){var o;n===void 0&&(n=!1);var i=Ea[ba]=(o=Ea[ba])!==null&&o!==void 0?o:{version:$r};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!==$r){var a=new Error("@opentelemetry/api: Registration of version v"+i.version+" for "+r+" does not match previously registered API v"+$r);return t.error(a.stack||a.message),!1}return i[r]=e,t.debug("@opentelemetry/api: Registered a global for "+r+" v"+$r+"."),!0}function qr(r){var e,t,n=(e=Ea[ba])===null||e===void 0?void 0:e.version;if(!(!n||!bb(n)))return(t=Ea[ba])===null||t===void 0?void 0:t[r]}function qo(r,e){e.debug("@opentelemetry/api: Unregistering a global for "+r+" v"+$r+".");var t=Ea[ba];t&&delete t[r]}var QO,ba,Ea,Ta=Be(()=>{"use strict";Sb();ep();Eb();QO=$r.split(".")[0],ba=Symbol.for("opentelemetry.js.api."+QO),Ea=gb});function va(r,e,t){var n=qr("diag");if(n)return t.unshift(e),n[r].apply(n,tL([],eL(t),!1))}var eL,tL,Tb,vb=Be(()=>{"use strict";Ta();eL=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(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))},Tb=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 va("debug",this._namespace,e)},r.prototype.error=function(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];return va("error",this._namespace,e)},r.prototype.info=function(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];return va("info",this._namespace,e)},r.prototype.warn=function(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];return va("warn",this._namespace,e)},r.prototype.verbose=function(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];return va("verbose",this._namespace,e)},r}()});var Le,bl=Be(()=>{"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"})(Le||(Le={}))});function Ab(r,e){r<Le.NONE?r=Le.NONE:r>Le.ALL&&(r=Le.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",Le.ERROR),warn:t("warn",Le.WARN),info:t("info",Le.INFO),debug:t("debug",Le.DEBUG),verbose:t("verbose",Le.VERBOSE)}}var wb=Be(()=>{"use strict";bl()});var rL,nL,oL,Pr,Aa=Be(()=>{"use strict";vb();wb();bl();Ta();rL=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(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))},oL="diag",Pr=function(){function r(){function e(o){return function(){for(var i=[],a=0;a<arguments.length;a++)i[a]=arguments[a];var l=qr("diag");if(l)return l[o].apply(l,nL([],rL(i),!1))}}var t=this,n=function(o,i){var a,l,c;if(i===void 0&&(i={logLevel:Le.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=qr("diag"),d=Ab((l=i.logLevel)!==null&&l!==void 0?l:Le.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 $o("diag",d,t,!0)};t.setLogger=n,t.disable=function(){qo(oL,t)},t.createComponentLogger=function(o){return new Tb(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 Rb,Cb=Be(()=>{"use strict";Rb=Symbol("BaggageEntryMetadata")});function tp(r){return typeof r!="string"&&(iL.error("Cannot create baggage metadata from unknown type: "+typeof r),r=""),{__TYPE__:Rb,toString:function(){return r}}}var iL,xb=Be(()=>{"use strict";Aa();Cb();iL=Pr.instance()});function rp(r){return Symbol.for(r)}var aL,np,op=Be(()=>{"use strict";aL=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}(),np=new aL});function sp(){return ap}var $n,sL,El,lL,cL,uL,dL,ip,pL,mL,gL,ap,hL,fL,SL,yL,bL,EL,TL,lp=Be(()=>{"use strict";$n=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)}}(),sL=function(){function r(){}return r.prototype.createGauge=function(e,t){return fL},r.prototype.createHistogram=function(e,t){return SL},r.prototype.createCounter=function(e,t){return hL},r.prototype.createUpDownCounter=function(e,t){return yL},r.prototype.createObservableGauge=function(e,t){return EL},r.prototype.createObservableCounter=function(e,t){return bL},r.prototype.createObservableUpDownCounter=function(e,t){return TL},r.prototype.addBatchObservableCallback=function(e,t){},r.prototype.removeBatchObservableCallback=function(e){},r}(),El=function(){function r(){}return r}(),lL=function(r){$n(e,r);function e(){return r!==null&&r.apply(this,arguments)||this}return e.prototype.add=function(t,n){},e}(El),cL=function(r){$n(e,r);function e(){return r!==null&&r.apply(this,arguments)||this}return e.prototype.add=function(t,n){},e}(El),uL=function(r){$n(e,r);function e(){return r!==null&&r.apply(this,arguments)||this}return e.prototype.record=function(t,n){},e}(El),dL=function(r){$n(e,r);function e(){return r!==null&&r.apply(this,arguments)||this}return e.prototype.record=function(t,n){},e}(El),ip=function(){function r(){}return r.prototype.addCallback=function(e){},r.prototype.removeCallback=function(e){},r}(),pL=function(r){$n(e,r);function e(){return r!==null&&r.apply(this,arguments)||this}return e}(ip),mL=function(r){$n(e,r);function e(){return r!==null&&r.apply(this,arguments)||this}return e}(ip),gL=function(r){$n(e,r);function e(){return r!==null&&r.apply(this,arguments)||this}return e}(ip),ap=new sL,hL=new lL,fL=new uL,SL=new dL,yL=new cL,bL=new pL,EL=new mL,TL=new gL});var Ht,Mb=Be(()=>{"use strict";(function(r){r[r.INT=0]="INT",r[r.DOUBLE=1]="DOUBLE"})(Ht||(Ht={}))});var vL,AL,_b,Pb=Be(()=>{"use strict";op();vL=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},AL=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))},_b=function(){function r(){}return r.prototype.active=function(){return np},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,AL([n],vL(o),!1))},r.prototype.bind=function(e,t){return t},r.prototype.enable=function(){return this},r.prototype.disable=function(){return this},r}()});var wL,RL,cp,CL,Ib,Ob=Be(()=>{"use strict";Pb();Ta();Aa();wL=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},RL=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="context",CL=new _b,Ib=function(){function r(){}return r.getInstance=function(){return this._instance||(this._instance=new r),this._instance},r.prototype.setGlobalContextManager=function(e){return $o(cp,e,Pr.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,RL([e,t,n],wL(i),!1))},r.prototype.bind=function(e,t){return this._getContextManager().bind(e,t)},r.prototype._getContextManager=function(){return qr(cp)||CL},r.prototype.disable=function(){this._getContextManager().disable(),qo(cp,Pr.instance())},r}()});var Ko,Lb=Be(()=>{"use strict";Ob();Ko=Ib.getInstance()});var H,Nb=Be(()=>{"use strict";Aa();H=Pr.instance()});var xL,Db,kb=Be(()=>{"use strict";lp();xL=function(){function r(){}return r.prototype.getMeter=function(e,t,n){return ap},r}(),Db=new xL});var up,Ub,Fb=Be(()=>{"use strict";kb();Ta();Aa();up="metrics",Ub=function(){function r(){}return r.getInstance=function(){return this._instance||(this._instance=new r),this._instance},r.prototype.setGlobalMeterProvider=function(e){return $o(up,e,Pr.instance())},r.prototype.getMeterProvider=function(){return qr(up)||Db},r.prototype.getMeter=function(e,t,n){return this.getMeterProvider().getMeter(e,t,n)},r.prototype.disable=function(){qo(up,Pr.instance())},r}()});var Tl,Bb=Be(()=>{"use strict";Fb();Tl=Ub.getInstance()});var xe=Be(()=>{"use strict";xb();op();bl();lp();Mb();Lb();Nb();Bb()});import{Argument as qg,Command as iH,Option as aH}from"@commander-js/extra-typings";import S0 from"appium";import{execSync as y0}from"child_process";import{z as Tu}from"zod";var fH=Tu.object({input:Tu.string(),agentConfigVersion:Tu.string().optional()});import{z as rt}from"zod";var bH=rt.object({srcs:rt.array(rt.string()),urls:rt.array(rt.string()),desiredSrc:rt.string().optional(),desiredUrl:rt.string().optional()}),Xg=rt.object({srcRegex:rt.string().optional(),urlRegex:rt.string().optional()}),Jg=rt.object({x:rt.number(),y:rt.number(),correlation:rt.number()}),EH=rt.object({searchImageBase64String:rt.string(),pageImageBase64String:rt.string(),id:rt.string().uuid(),timeoutMs:rt.number().max(1e4).min(0).optional()});import{z as I}from"zod";import*as L from"zod";import{extendZodWithOpenApi as QC}from"zod-openapi";QC(L);var Zr=(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))(Zr||{}),ex=L.object({mPathSelectorTokens:L.string().array(),frameSrcRegex:L.string().optional(),frameUrlRegex:L.string().optional(),indices:L.number().array()}),vu=L.object({result:L.number(),traceId:L.string()}).array(),hs=L.object({type:L.literal("GCS_TRACES"),traces:vu}),Jr=(o=>(o.Precise="precise",o.Narrow="narrow",o.Unspecific="broad",o.Irrelevant="irrelevant",o))(Jr||{}),Zg=L.object({attributes:L.record(L.string(),L.string()).optional(),text:L.string().optional(),position:L.object({x1:L.number(),y1:L.number(),x2:L.number(),y2:L.number(),tolerance:L.nativeEnum(Jr)}).optional(),shape:L.object({width:L.number(),height:L.number(),tolerance:L.nativeEnum(Jr)}).optional(),boundingBox:L.object({x:L.number(),y:L.number(),width:L.number(),height:L.number()}).optional()}),tx=L.object({selectors:L.string().array(),requirements:Zg.optional()}),Qr=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().optional()),tagName:L.string(),expandShadowRoot:L.boolean().optional(),classNames:L.string().array(),nthChild:L.number()}).array().optional(),generatedSelectors:L.string().array().optional(),requirements:Zg.optional(),additionalElements:tx.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:ex.optional(),inputDescription:L.string().optional().describe("the description that generated this cache"),targetSource:L.nativeEnum(Zr).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:hs.optional()}).openapi({ref:"ElementTargetCache"});function fs(r){return!!(r.serializedHtml||r.screenshotUrl||r.generatedSelectors||r.hybridSelector)}var rx=L.object({type:L.literal("description"),elementDescriptor:L.string().describe("Description of the element.")}).openapi({ref:"DescriptionTarget"}),nx=L.object({x:L.number(),y:L.number()}),ox=L.object({type:L.literal("coordinates"),pixels:nx}).openapi({ref:"CoordinatesTarget"});function en(r){return r.type==="description"}function vr(r){return r.type==="coordinates"}var ft=L.discriminatedUnion("type",[rx,ox]).openapi({ref:"ElementTarget"});function Au(r){if(!r)return!1;switch(r.type){case"description":return!!r.elementDescriptor}return!0}function Qg(r){return hs.safeParse(r).success}import{v4 as fe}from"uuid";import*as y from"zod";import{extendZodWithOpenApi as px}from"zod-openapi";import{z as ee}from"zod";import{extendZodWithOpenApi as ix}from"zod-openapi";import{z as Li}from"zod";import eh from"zod";var Oi=eh.object({updatedAt:eh.coerce.date().optional()});var wu=Li.object({result:Li.boolean(),traceId:Li.string()}).array(),Ru=Li.object({type:Li.literal("GCS_TRACES"),traces:wu}),Cu=Oi.extend({memory:Ru.optional()});ix(ee);var th=ee.object({plan:ee.string().optional(),evidence:ee.string().optional(),thoughts:ee.string(),result:ee.boolean(),relevantElements:ee.array(ee.number()).optional(),updatedMemory:wu.optional()}),Gr=(o=>(o.CONTAINS="CONTAINS",o.STARTS_WITH="STARTS_WITH",o.EQUALS="EQUALS",o.EXISTS="EXISTS",o))(Gr||{});var ax=ee.object({type:ee.literal("ELEMENT_NAME"),negated:ee.boolean().optional(),operation:ee.nativeEnum(Gr),value:ee.string()}).openapi({ref:"ElementNameAssertion"}),sx=ee.object({type:ee.literal("ELEMENT_STYLE"),negated:ee.boolean().optional(),operation:ee.nativeEnum(Gr),property:ee.string(),value:ee.string()}).openapi({ref:"ElementStyleAssertion"}),lx=ee.object({type:ee.literal("ELEMENT_CONTENT"),negated:ee.boolean().optional(),operation:ee.nativeEnum(Gr),value:ee.string()}).openapi({ref:"ElementContentAssertion"}),cx=ee.object({type:ee.literal("ELEMENT_ATTRIBUTE"),negated:ee.boolean().optional(),operation:ee.nativeEnum(Gr),attr:ee.string(),value:ee.string()}).openapi({ref:"ElementAttributeValueAssertion"}),Pn=(i=>(i.EXISTS="EXISTS",i.VISIBLE="VISIBLE",i.ENABLED="ENABLED",i.EDITABLE="EDITABLE",i.FOCUSED="FOCUSED",i))(Pn||{}),ux=ee.object({type:ee.literal("ELEMENT_EXISTENCE"),negated:ee.boolean().optional(),condition:ee.nativeEnum(Pn).describe("Treated as the element exists AND is also ...")}).openapi({ref:"ElementExistenceAssertion"}),rh=ee.discriminatedUnion("type",[lx,cx,ux,ax,sx]).openapi({ref:"ManualElementAssertion"});var dx=ee.object({type:ee.literal("CONTENT"),negated:ee.boolean().optional(),value:ee.string()}).openapi({ref:"PageContentAssertion"}),nh=ee.discriminatedUnion("type",[dx]).openapi({ref:"ManualPageAssertion"});import Ct from"zod";var xu=Ct.discriminatedUnion("type",[Ct.object({type:Ct.literal("SUBSTRING"),url:Ct.string()}),Ct.object({type:Ct.literal("GLOB"),glob:Ct.string()}),Ct.object({type:Ct.literal("REGEX"),regex:Ct.string()}),Ct.object({type:Ct.literal("DOMAIN"),domain:Ct.string()})]),Ni=Ct.object({urlMatcher:xu,method:Ct.string().optional()});import{z as he}from"zod";var bo=he.object({url:he.string(),method:he.union([he.literal("GET"),he.literal("POST"),he.literal("PUT"),he.literal("DELETE"),he.literal("PATCH")]),headers:he.record(he.string(),he.string()).optional(),params:he.record(he.string(),he.string()).optional(),body:he.string().optional(),timeout:he.number().int().optional().describe("Max seconds to wait for the request to complete")}),oh=he.object({url:he.string(),headers:he.record(he.string(),he.string()).optional(),query:he.string(),variables:he.string().optional(),timeout:he.number().int().optional().describe("Max seconds to wait for the request to complete")}),Ss=he.object({code:he.string(),fragment:he.boolean().optional().describe("Agents should not touch this unless explicitly told to"),environment:he.union([he.literal("NODE"),he.literal("BROWSER")]).optional().describe("default NODE, Agents default to using node unless it is necessary to use browser"),timeout:he.number().int().max(60).optional().describe("Max seconds for the code to complete")});var nt=(V=>(V.AI_EXTRACT="AI_EXTRACT",V.AI_ASSERTION="AI_ASSERTION",V.AUTH_LOAD="AUTH_LOAD",V.AUTH_SAVE="AUTH_SAVE",V.BLUR="BLUR",V.CAPTCHA="CAPTCHA",V.CLICK="CLICK",V.COOKIE="COOKIE",V.COPY="COPY",V.DIALOG="DIALOG",V.DRAG="DRAG",V.ELEMENT_CHECK="ELEMENT_CHECK",V.FILE_UPLOAD="FILE_UPLOAD",V.FOCUS="FOCUS",V.GO_BACK="GO_BACK",V.GO_FORWARD="GO_FORWARD",V.HOVER="HOVER",V.JAVASCRIPT="JAVASCRIPT",V.LOCAL_STORAGE="LOCAL_STORAGE",V.MOUSE_DRAG="MOUSE_DRAG",V.NAVIGATE="NAVIGATE",V.NEW_TAB="NEW_TAB",V.PAGE_CHECK="PAGE_CHECK",V.PASTE="PASTE",V.PRESS="PRESS",V.KEY_DOWN="KEY_DOWN",V.KEY_UP="KEY_UP",V.REFRESH="REFRESH",V.REQUEST="REQUEST",V.GRAPHQL_REQUEST="GRAPHQL_REQUEST",V.SCROLL_DOWN="SCROLL_DOWN",V.SCROLL_UP="SCROLL_UP",V.SCROLL_LEFT="SCROLL_LEFT",V.SCROLL_RIGHT="SCROLL_RIGHT",V.SELECT_OPTION="SELECT_OPTION",V.SWITCH_TAB="TAB",V.TYPE="TYPE",V.VISUAL_DIFF="VISUAL_DIFF",V.WAIT="WAIT",V.WAIT_FOR_URL="WAIT_FOR_URL",V.REGISTER_REQUEST_LISTENER="REGISTER_REQUEST_LISTENER",V.AWAIT_LISTENER="AWAIT_LISTENER",V.RECORD_REQUESTS="RECORD_REQUESTS",V.GET_RECORDED_REQUESTS="GET_RECORDED_REQUESTS",V.SET_HEADER="SET_HEADER",V.MOCK_ROUTE="MOCK_ROUTE",V.REMOVE_ROUTE_MOCK="REMOVE_ROUTE_MOCK",V.OFFLINE_MODE="OFFLINE_MODE",V.SUCCESS="SUCCESS",V))(nt||{});px(y);var q=y.object({thoughts:y.string().optional(),id:y.string().uuid().describe("unique identifier to this step, used for step cache")}),jt=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"}),Wt=Oi.extend({target:Qr}).optional().openapi({ref:"SingleTargetCache"});function ih(r){return Wt.safeParse(r).success}var ys=y.object({loadTimeout:y.number().int().max(60).optional().describe("Max seconds for the page to load")}),mx=q.merge(ys).merge(y.object({type:y.literal("NAVIGATE"),url:y.string()})).openapi({ref:"NavigateCommand"}),bs=jt.merge(y.object({cache:Wt})),Eo=q.merge(bs.merge(y.object({target:ft.optional(),type:y.literal("SCROLL_UP"),deltaY:y.number().optional()}))).openapi({ref:"ScrollUpCommand"}),To=q.merge(bs.merge(y.object({target:ft.optional(),type:y.literal("SCROLL_DOWN"),deltaY:y.number().optional()}))).openapi({ref:"ScrollDownCommand"}),vo=q.merge(bs.merge(y.object({target:ft.optional(),type:y.literal("SCROLL_LEFT"),deltaX:y.number().optional()}))).openapi({ref:"ScrollLeftCommand"}),Ao=q.merge(bs.merge(y.object({target:ft.optional(),type:y.literal("SCROLL_RIGHT"),deltaX:y.number().optional()}))).openapi({ref:"ScrollRightCommand"}),XH=y.discriminatedUnion("type",[Eo,To,vo,Ao]).openapi({ref:"AllScrollCommands"}),gx=q.merge(y.object({type:y.literal("DIALOG"),action:y.union([y.literal("ACCEPT"),y.literal("DISMISS")])})).openapi({ref:"DialogCommand"}),hx=q.merge(y.object({type:y.literal("WAIT"),delay:y.number()})).openapi({ref:"WaitCommand"}),fx=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")}),ah=q.extend({type:y.literal("WAIT_FOR_URL"),matcher:xu}).merge(fx).openapi({ref:"WaitUrlCommand"}),sh=q.merge(ys).merge(y.object({type:y.literal("REFRESH")})).openapi({ref:"RefreshCommand"}),Sx=q.merge(y.object({type:y.literal("GO_BACK")})).openapi({ref:"GoBackCommand"}),lh=q.merge(y.object({type:y.literal("GO_FORWARD")})).openapi({ref:"GoForwardCommand"}),yx=q.extend({type:y.literal("AUTH_SAVE")}).openapi({ref:"AuthSaveCommand"}),bx=q.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"}),_u=q.merge(jt).extend({type:y.literal("CAPTCHA")}).openapi({ref:"CaptchaCommand"}),ch=q.extend({type:y.literal("COPY"),value:y.string()}).openapi({ref:"CopyCommand"}),uh=q.extend({type:y.literal("PASTE")}).openapi({ref:"PasteCommand"}),dh=q.merge(Ss).extend({type:y.literal("JAVASCRIPT")}).openapi({ref:"JavaScriptCommand"}),ki=q.merge(jt).extend({type:y.literal("CLICK"),target:ft,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:Wt,relativePosition:y.object({x:y.number(),y:y.number()}).optional()}).openapi({ref:"ClickCommand"}),ph=Oi.extend({fromTarget:Qr.optional(),toTarget:Qr.optional()}),wo=q.merge(jt).merge(y.object({type:y.literal("DRAG"),fromTarget:ft,toTarget:ft,steps:y.number().optional(),hoverSeconds:y.number().optional().describe("Seconds to hover the object before dropping"),cache:ph.optional()})).openapi({ref:"DragCommand"}),Ro=q.merge(jt).merge(y.object({type:y.literal("MOUSE_DRAG"),target:ft.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:Wt})).openapi({ref:"MouseDragCommand"}),Ui=q.merge(jt).merge(y.object({type:y.literal("HOVER"),target:ft,cache:Wt})).openapi({ref:"HoverCommand"}),Fi=q.merge(jt).merge(y.object({type:y.literal("FOCUS"),target:ft,cache:Wt})).openapi({ref:"FocusCommand"}),Bi=q.merge(jt).extend({type:y.literal("BLUR"),target:ft.optional(),cache:Wt}).openapi({ref:"BlurCommand"}),Ex=y.object({type:y.literal("URL"),url:y.string()}).describe("Accessible link to the file, either public http or local file://").openapi({ref:"UrlSource"}),Tx=y.object({type:y.literal("USER_FILE"),name:y.string()}).describe("Accessible link to the file, references the google cloud file").openapi({ref:"UploadedFileSource"}),vx=q.extend({type:y.literal("FILE_UPLOAD"),fileSource:y.discriminatedUnion("type",[Ex,Tx]),filename:y.string().optional()}).openapi({ref:"FileUploadCommand"}),mh=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()})]),zi=q.merge(jt).extend({type:y.literal("SELECT_OPTION"),target:ft,cache:Wt,choice:mh.describe("new field for selecting options, optional for backcompat")}).openapi({ref:"SelectOptionCommand"}),Pu=y.union([y.literal("MULTIMODAL"),y.literal("VISION_ONLY")]),Es=q.merge(y.object({type:y.literal("AI_ASSERTION"),assertion:y.string(),disableCache:y.boolean().optional(),iframeUrl:y.string().optional(),contextChoice:Pu.optional(),timeout:y.number().int().optional().describe("Max seconds to wait for assertion to be true"),cache:Cu.optional()})).openapi({ref:"AIAssertionCommand"}),tn=5,Iu=600,Co=q.merge(jt).extend({type:y.literal("ELEMENT_CHECK"),target:ft,assertion:rh,cache:Wt.or(Cu).optional(),timeout:y.number().int().min(0).max(Iu).optional().describe("max seconds to wait for the assertion to be true")}).openapi({ref:"ElementAssertionCommand"}),gh=q.extend({type:y.literal("PAGE_CHECK"),assertion:nh,iframeUrl:y.string().optional().describe("url or url regex for the iframe"),timeout:y.number().int().min(0).max(Iu).optional().describe("max seconds to wait for the assertion to be true")}).openapi({ref:"PageAssertionCommand"}),hh=q.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"}),Ax=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(),relativePosition:y.object({x:y.number(),y:y.number()}).optional()}),fh=25,Hi=q.merge(jt).merge(Ax).extend({type:y.literal("TYPE"),target:ft.optional(),value:y.string(),cache:Wt}).openapi({ref:"TypeCommand"}),wx=q.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"}),Rx=q.merge(y.object({type:y.literal("KEY_DOWN"),value:y.string(),convertMeta:y.boolean().optional()})).openapi({ref:"KeyDownCommand"}),Cx=q.merge(y.object({type:y.literal("KEY_UP"),value:y.string(),convertMeta:y.boolean().optional()})).openapi({ref:"KeyUpCommand"}),xx=y.object({type:y.literal("SUBSTRING"),substring:y.string()}),Mx=y.object({type:y.literal("REGEX"),pattern:y.string()}),_x=y.object({type:y.literal("INDEX"),index:y.coerce.string()}),Px=y.discriminatedUnion("type",[xx,Mx,_x]),Ix=q.merge(ys).merge(y.object({type:y.literal("TAB"),action:Px})).openapi({ref:"TabCommand"}),Sh=q.merge(ys).merge(y.object({type:y.literal("NEW_TAB"),url:y.string()})).openapi({ref:"NewTabCommand"}),Ox=q.merge(y.object({type:y.literal("COOKIE"),value:y.string()})).openapi({ref:"CookieCommand"}),yh=q.merge(y.object({type:y.literal("LOCAL_STORAGE"),key:y.string(),value:y.string()})).openapi({ref:"LocalStorageCommand"}),bh=q.extend({type:y.literal("REQUEST")}).merge(bo).openapi({ref:"RequestCommand"}),Lx=q.extend({type:y.literal("GRAPHQL_REQUEST")}).merge(oh).openapi({ref:"GraphQLRequestCommand"}),Nx=q.merge(y.object({type:y.literal("SUCCESS"),condition:Es.optional()})).openapi({ref:"SuccessCommand"}),Eh=q.merge(y.object({type:y.literal("FAILURE")})).openapi({ref:"FailureCommand"}),Dx=y.object({data:y.string().describe("location at which to find a jpg"),width:y.number(),height:y.number()}),Gi=q.merge(jt).merge(y.object({type:y.literal("VISUAL_DIFF"),threshold:y.number().optional().describe("default 0.1"),target:ft.optional(),screenshot:Dx.optional(),cache:Wt})).openapi({ref:"VisualDiffCommand"}),kx=q.merge(y.object({type:y.literal("REGISTER_REQUEST_LISTENER"),requestMatcher:Ni,key:y.string()})).openapi({ref:"RegisterRequestListenerCommand"}),Ux=q.merge(y.object({type:y.literal("AWAIT_LISTENER"),key:y.string(),timeout:y.number().optional().describe("timeout")})).openapi({ref:"WaitForListenerCommand"}),Fx=q.merge(y.object({type:y.literal("RECORD_REQUESTS"),requestMatcher:Ni,key:y.string()})).openapi({ref:"RecordRequestsCommand"}),Bx=q.merge(y.object({type:y.literal("GET_RECORDED_REQUESTS"),key:y.string()})).openapi({ref:"GetRecordedRequestsCommand"}),zx=q.merge(y.object({type:y.literal("SET_HEADER"),name:y.string(),value:y.string(),requestMatcher:Ni.optional()})).openapi({ref:"SetHeaderCommand"}),Hx=q.merge(y.object({type:y.literal("MOCK_ROUTE"),requestMatcher:Ni,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"})),Gx=q.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"})),Vx=q.merge(y.object({type:y.literal("OFFLINE_MODE"),enable:y.boolean()})).openapi({ref:"OfflineModeCommand"}),jx=y.discriminatedUnion("type",[ki,Hi,wx,Rx,Cx,zi,mx,To,Eo,Es,Sx,Ui,hx]),Ou=y.discriminatedUnion("type",[...jx.options,Nx]),Lu=y.discriminatedUnion("type",[...Ou.options,wo,dh,Co,gh,Sh,ah,hh,ch,lh,yh,Ro,uh,sh,bh]),Wx=y.discriminatedUnion("type",[hh,bx,yx,_u,Ox,ch,gx,wo,Co,vx,lh,dh,yh,Ro,Sh,gh,uh,sh,bh,Lx,vo,Ao,Ix,Gi,Fi,Bi,ah,kx,Ux,Fx,Bx,zx,Hx,Gx,Vx]),xo=y.discriminatedUnion("type",[...Ou.options,...Wx.options]).openapi({ref:"Command"}),Ts=y.discriminatedUnion("type",[...Ou.options,Eh]),JH=y.discriminatedUnion("type",[...Lu.options,Eh]);function Vr(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:fe(),type:r};break;case"AUTH_LOAD":{e={id:fe(),type:r,storageState:""};break}case"AI_EXTRACT":e={id:fe(),type:r,goal:""};break;case"DIALOG":e={id:fe(),type:r,action:"DISMISS"};break;case"DRAG":e={id:fe(),type:r,fromTarget:{type:"description",elementDescriptor:""},toTarget:{type:"description",elementDescriptor:""}};break;case"MOUSE_DRAG":e={id:fe(),type:r,deltaX:"0",deltaY:"0",steps:1};break;case"WAIT_FOR_URL":e={id:fe(),type:r,matcher:{type:"SUBSTRING",url:""}};break;case"WAIT":e={id:fe(),type:r,delay:1};break;case"BLUR":e={id:fe(),type:r};break;case"HOVER":case"FOCUS":case"CLICK":e={id:fe(),type:r,target:{type:"description",elementDescriptor:""}};break;case"COOKIE":case"PRESS":case"COPY":case"TYPE":e={id:fe(),type:r,value:"",clearContent:!0};break;case"KEY_DOWN":case"KEY_UP":e={id:fe(),type:r,value:""};break;case"SELECT_OPTION":e={id:fe(),type:r,target:{type:"description",elementDescriptor:""},choice:{type:"VALUE",value:""}};break;case"NAVIGATE":case"NEW_TAB":return{id:fe(),type:r,url:""};case"TAB":e={id:fe(),type:r,action:{type:"SUBSTRING",substring:""}};break;case"REQUEST":e={id:fe(),type:r,url:"",method:"GET"};break;case"GRAPHQL_REQUEST":e={id:fe(),type:r,url:"",query:""};break;case"LOCAL_STORAGE":e={id:fe(),type:r,key:"",value:""};break;case"JAVASCRIPT":e={id:fe(),type:r,code:""};break;case"AI_ASSERTION":e={id:fe(),type:r,assertion:""};break;case"FILE_UPLOAD":{e={id:fe(),type:r,fileSource:{type:"URL",url:""}};break}case"ELEMENT_CHECK":{e={id:fe(),type:r,target:{type:"description",elementDescriptor:""},assertion:{type:"ELEMENT_EXISTENCE",condition:"EXISTS"}};break}case"PAGE_CHECK":{e={id:fe(),type:r,assertion:{type:"CONTENT",value:""}};break}case"REGISTER_REQUEST_LISTENER":{e={id:fe(),type:r,requestMatcher:{urlMatcher:{type:"REGEX",regex:""}},key:""};break}case"AWAIT_LISTENER":{e={id:fe(),type:r,key:""};break}case"RECORD_REQUESTS":{e={id:fe(),type:r,requestMatcher:{urlMatcher:{type:"REGEX",regex:""}},key:""};break}case"GET_RECORDED_REQUESTS":{e={id:fe(),type:r,key:""};break}case"SET_HEADER":{e={id:fe(),type:r,name:"",value:""};break}case"MOCK_ROUTE":{e={id:fe(),type:r,requestMatcher:{urlMatcher:{type:"REGEX",regex:""}},responseGenerator:""};break}case"REMOVE_ROUTE_MOCK":{e={id:fe(),type:r};break}case"OFFLINE_MODE":{e={id:fe(),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 Th(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 $x}from"zod";var rG=$x.discriminatedUnion("type",[Bi,_u,ki,wo,Fi,Ui,Ro,Eo,To,vo,Ao,zi,Hi,Gi,Co]);import{z as qx}from"zod";import{z as rn}from"zod";function Vi(r){return rn.object({key:rn.string(),testId:rn.string().optional(),moduleId:rn.string().optional(),organizationId:rn.string(),value:r})}function ji(r){return Vi(r).extend({uniqueKey:rn.string()})}function vs(r){return rn.record(rn.string(),ji(r))}var xt={type:!0,cache:!0},Mo=qx.discriminatedUnion("type",[Es.pick(xt),Bi.pick(xt),ki.pick(xt),wo.pick(xt),Co.pick(xt),Fi.pick(xt),Ui.pick(xt),Ro.pick(xt),Eo.pick(xt),To.pick(xt),vo.pick(xt),Ao.pick(xt),zi.pick(xt),Hi.pick(xt),Gi.pick(xt)]),Nu=Object.values(nt).filter(r=>Mo.options.some(e=>e.shape.type.safeParse(r).success));xo.options.forEach(r=>{if("target"in r.shape&&!Nu.includes(r.shape.type.value))throw new Error(`Command ${r.shape.type.value} has a target but no cache`)});function Du(r){return Nu.includes(r.type)}var vh=Vi(Mo),Ah=ji(Mo),uG=vs(Mo);import{v4 as uW}from"uuid";import{z as T}from"zod";var Rh=Symbol("Let zodToJsonSchema decide on which parser to use");var wh={name:void 0,$refStrategy:"root",basePath:["#"],effectStrategy:"input",pipeStrategy:"all",dateStrategy:"format:date-time",mapStrategy:"entries",removeAdditionalStrategy:"passthrough",allowedAdditionalProperties:!0,rejectedAdditionalProperties:!1,definitionPath:"definitions",target:"jsonSchema7",strictUnions:!1,definitions:{},errorMessages:!1,markdownDescription:!1,patternStrategy:"escape",applyRegexFlags:!1,emailStrategy:"format:email",base64Strategy:"contentEncoding:base64",nameStrategy:"ref",openAiAnyTypeName:"OpenAiAnyType"},Ch=r=>typeof r=="string"?{...wh,name:r}:{...wh,...r};var xh=r=>{let e=Ch(r),t=e.name!==void 0?[...e.basePath,e.definitionPath,e.name]:e.basePath;return{...e,flags:{hasReferencedOpenAiAnyType:!1},currentPath:t,propertyPath:void 0,seen:new Map(Object.entries(e.definitions).map(([n,o])=>[o._def,{def:o._def,path:[...e.basePath,e.definitionPath,n],jsonSchema:void 0}]))}};function ku(r,e,t,n){n?.errorMessages&&t&&(r.errorMessage={...r.errorMessage,[e]:t})}function ce(r,e,t,n,o){r[e]=t,ku(r,e,n,o)}var As=(r,e)=>{let t=0;for(;t<r.length&&t<e.length&&r[t]===e[t];t++);return[(r.length-t).toString(),...e.slice(t)].join("/")};import{ZodFirstPartyTypeKind as se}from"zod";function Ne(r){if(r.target!=="openAi")return{};let e=[...r.basePath,r.definitionPath,r.openAiAnyTypeName];return r.flags.hasReferencedOpenAiAnyType=!0,{$ref:r.$refStrategy==="relative"?As(e,r.currentPath):e.join("/")}}import{ZodFirstPartyTypeKind as Kx}from"zod";function Mh(r,e){let t={type:"array"};return r.type?._def&&r.type?._def?.typeName!==Kx.ZodAny&&(t.items=K(r.type._def,{...e,currentPath:[...e.currentPath,"items"]})),r.minLength&&ce(t,"minItems",r.minLength.value,r.minLength.message,e),r.maxLength&&ce(t,"maxItems",r.maxLength.value,r.maxLength.message,e),r.exactLength&&(ce(t,"minItems",r.exactLength.value,r.exactLength.message,e),ce(t,"maxItems",r.exactLength.value,r.exactLength.message,e)),t}function _h(r,e){let t={type:"integer",format:"int64"};if(!r.checks)return t;for(let n of r.checks)switch(n.kind){case"min":e.target==="jsonSchema7"?n.inclusive?ce(t,"minimum",n.value,n.message,e):ce(t,"exclusiveMinimum",n.value,n.message,e):(n.inclusive||(t.exclusiveMinimum=!0),ce(t,"minimum",n.value,n.message,e));break;case"max":e.target==="jsonSchema7"?n.inclusive?ce(t,"maximum",n.value,n.message,e):ce(t,"exclusiveMaximum",n.value,n.message,e):(n.inclusive||(t.exclusiveMaximum=!0),ce(t,"maximum",n.value,n.message,e));break;case"multipleOf":ce(t,"multipleOf",n.value,n.message,e);break}return t}function Ph(){return{type:"boolean"}}function ws(r,e){return K(r.type._def,e)}var Ih=(r,e)=>K(r.innerType._def,e);function Uu(r,e,t){let n=t??e.dateStrategy;if(Array.isArray(n))return{anyOf:n.map((o,i)=>Uu(r,e,o))};switch(n){case"string":case"format:date-time":return{type:"string",format:"date-time"};case"format:date":return{type:"string",format:"date"};case"integer":return Yx(r,e)}}var Yx=(r,e)=>{let t={type:"integer",format:"unix-time"};if(e.target==="openApi3")return t;for(let n of r.checks)switch(n.kind){case"min":ce(t,"minimum",n.value,n.message,e);break;case"max":ce(t,"maximum",n.value,n.message,e);break}return t};function Oh(r,e){return{...K(r.innerType._def,e),default:r.defaultValue()}}function Lh(r,e){return e.effectStrategy==="input"?K(r.schema._def,e):Ne(e)}function Nh(r){return{type:"string",enum:Array.from(r.values)}}var Xx=r=>"type"in r&&r.type==="string"?!1:"allOf"in r;function Dh(r,e){let t=[K(r.left._def,{...e,currentPath:[...e.currentPath,"allOf","0"]}),K(r.right._def,{...e,currentPath:[...e.currentPath,"allOf","1"]})].filter(i=>!!i),n=e.target==="jsonSchema2019-09"?{unevaluatedProperties:!1}:void 0,o=[];return t.forEach(i=>{if(Xx(i))o.push(...i.allOf),i.unevaluatedProperties===void 0&&(n=void 0);else{let a=i;if("additionalProperties"in i&&i.additionalProperties===!1){let{additionalProperties:l,...c}=i;a=c}else n=void 0;o.push(a)}}),o.length?{allOf:o,...n}:void 0}function kh(r,e){let t=typeof r.value;return t!=="bigint"&&t!=="number"&&t!=="boolean"&&t!=="string"?{type:Array.isArray(r.value)?"array":"object"}:e.target==="openApi3"?{type:t==="bigint"?"integer":t,enum:[r.value]}:{type:t==="bigint"?"integer":t,const:r.value}}import{ZodFirstPartyTypeKind as Wi}from"zod";var Fu,dr={cuid:/^[cC][^\s-]{8,}$/,cuid2:/^[0-9a-z]+$/,ulid:/^[0-9A-HJKMNP-TV-Z]{26}$/,email:/^(?!\.)(?!.*\.\.)([a-zA-Z0-9_'+\-\.]*)[a-zA-Z0-9_+-]@([a-zA-Z0-9][a-zA-Z0-9\-]*\.)+[a-zA-Z]{2,}$/,emoji:()=>(Fu===void 0&&(Fu=RegExp("^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$","u")),Fu),uuid:/^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/,ipv4:/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,ipv4Cidr:/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/(3[0-2]|[12]?[0-9])$/,ipv6:/^(([a-f0-9]{1,4}:){7}|::([a-f0-9]{1,4}:){0,6}|([a-f0-9]{1,4}:){1}:([a-f0-9]{1,4}:){0,5}|([a-f0-9]{1,4}:){2}:([a-f0-9]{1,4}:){0,4}|([a-f0-9]{1,4}:){3}:([a-f0-9]{1,4}:){0,3}|([a-f0-9]{1,4}:){4}:([a-f0-9]{1,4}:){0,2}|([a-f0-9]{1,4}:){5}:([a-f0-9]{1,4}:){0,1})([a-f0-9]{1,4}|(((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))\.){3}((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2})))$/,ipv6Cidr:/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,base64:/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,base64url:/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,nanoid:/^[a-zA-Z0-9_-]{21}$/,jwt:/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/};function Rs(r,e){let t={type:"string"};if(r.checks)for(let n of r.checks)switch(n.kind){case"min":ce(t,"minLength",typeof t.minLength=="number"?Math.max(t.minLength,n.value):n.value,n.message,e);break;case"max":ce(t,"maxLength",typeof t.maxLength=="number"?Math.min(t.maxLength,n.value):n.value,n.message,e);break;case"email":switch(e.emailStrategy){case"format:email":pr(t,"email",n.message,e);break;case"format:idn-email":pr(t,"idn-email",n.message,e);break;case"pattern:zod":Mt(t,dr.email,n.message,e);break}break;case"url":pr(t,"uri",n.message,e);break;case"uuid":pr(t,"uuid",n.message,e);break;case"regex":Mt(t,n.regex,n.message,e);break;case"cuid":Mt(t,dr.cuid,n.message,e);break;case"cuid2":Mt(t,dr.cuid2,n.message,e);break;case"startsWith":Mt(t,RegExp(`^${Bu(n.value,e)}`),n.message,e);break;case"endsWith":Mt(t,RegExp(`${Bu(n.value,e)}$`),n.message,e);break;case"datetime":pr(t,"date-time",n.message,e);break;case"date":pr(t,"date",n.message,e);break;case"time":pr(t,"time",n.message,e);break;case"duration":pr(t,"duration",n.message,e);break;case"length":ce(t,"minLength",typeof t.minLength=="number"?Math.max(t.minLength,n.value):n.value,n.message,e),ce(t,"maxLength",typeof t.maxLength=="number"?Math.min(t.maxLength,n.value):n.value,n.message,e);break;case"includes":{Mt(t,RegExp(Bu(n.value,e)),n.message,e);break}case"ip":{n.version!=="v6"&&pr(t,"ipv4",n.message,e),n.version!=="v4"&&pr(t,"ipv6",n.message,e);break}case"base64url":Mt(t,dr.base64url,n.message,e);break;case"jwt":Mt(t,dr.jwt,n.message,e);break;case"cidr":{n.version!=="v6"&&Mt(t,dr.ipv4Cidr,n.message,e),n.version!=="v4"&&Mt(t,dr.ipv6Cidr,n.message,e);break}case"emoji":Mt(t,dr.emoji(),n.message,e);break;case"ulid":{Mt(t,dr.ulid,n.message,e);break}case"base64":{switch(e.base64Strategy){case"format:binary":{pr(t,"binary",n.message,e);break}case"contentEncoding:base64":{ce(t,"contentEncoding","base64",n.message,e);break}case"pattern:zod":{Mt(t,dr.base64,n.message,e);break}}break}case"nanoid":Mt(t,dr.nanoid,n.message,e);case"toLowerCase":case"toUpperCase":case"trim":break;default:}return t}function Bu(r,e){return e.patternStrategy==="escape"?Zx(r):r}var Jx=new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789");function Zx(r){let e="";for(let t=0;t<r.length;t++)Jx.has(r[t])||(e+="\\"),e+=r[t];return e}function pr(r,e,t,n){r.format||r.anyOf?.some(o=>o.format)?(r.anyOf||(r.anyOf=[]),r.format&&(r.anyOf.push({format:r.format,...r.errorMessage&&n.errorMessages&&{errorMessage:{format:r.errorMessage.format}}}),delete r.format,r.errorMessage&&(delete r.errorMessage.format,Object.keys(r.errorMessage).length===0&&delete r.errorMessage)),r.anyOf.push({format:e,...t&&n.errorMessages&&{errorMessage:{format:t}}})):ce(r,"format",e,t,n)}function Mt(r,e,t,n){r.pattern||r.allOf?.some(o=>o.pattern)?(r.allOf||(r.allOf=[]),r.pattern&&(r.allOf.push({pattern:r.pattern,...r.errorMessage&&n.errorMessages&&{errorMessage:{pattern:r.errorMessage.pattern}}}),delete r.pattern,r.errorMessage&&(delete r.errorMessage.pattern,Object.keys(r.errorMessage).length===0&&delete r.errorMessage)),r.allOf.push({pattern:Uh(e,n),...t&&n.errorMessages&&{errorMessage:{pattern:t}}})):ce(r,"pattern",Uh(e,n),t,n)}function Uh(r,e){if(!e.applyRegexFlags||!r.flags)return r.source;let t={i:r.flags.includes("i"),m:r.flags.includes("m"),s:r.flags.includes("s")},n=t.i?r.source.toLowerCase():r.source,o="",i=!1,a=!1,l=!1;for(let c=0;c<n.length;c++){if(i){o+=n[c],i=!1;continue}if(t.i){if(a){if(n[c].match(/[a-z]/)){l?(o+=n[c],o+=`${n[c-2]}-${n[c]}`.toUpperCase(),l=!1):n[c+1]==="-"&&n[c+2]?.match(/[a-z]/)?(o+=n[c],l=!0):o+=`${n[c]}${n[c].toUpperCase()}`;continue}}else if(n[c].match(/[a-z]/)){o+=`[${n[c]}${n[c].toUpperCase()}]`;continue}}if(t.m){if(n[c]==="^"){o+=`(^|(?<=[\r
3
3
  ]))`;continue}else if(n[c]==="$"){o+=`($|(?=[\r
4
4
  ]))`;continue}}if(t.s&&n[c]==="."){o+=a?`${n[c]}\r
5
5
  `:`[${n[c]}\r
6
- ]`;continue}o+=n[c],n[c]==="\\"?i=!0:a&&n[c]==="]"?a=!1:!a&&n[c]==="["&&(a=!0)}try{new RegExp(o)}catch{return console.warn(`Could not convert regex pattern at ${e.currentPath.join("/")} to a flag-independent form! Falling back to the flag-ignorant source`),r.source}return o}function ws(r,e){if(e.target==="openAi"&&console.warn("Warning: OpenAI may not support records in schemas! Try an array of key-value pairs instead."),e.target==="openApi3"&&r.keyType?._def.typeName===ji.ZodEnum)return{type:"object",required:r.keyType._def.values,properties:r.keyType._def.values.reduce((n,o)=>({...n,[o]:K(r.valueType._def,{...e,currentPath:[...e.currentPath,"properties",o]})??Ne(e)}),{}),additionalProperties:e.rejectedAdditionalProperties};let t={type:"object",additionalProperties:K(r.valueType._def,{...e,currentPath:[...e.currentPath,"additionalProperties"]})??e.allowedAdditionalProperties};if(e.target==="openApi3")return t;if(r.keyType?._def.typeName===ji.ZodString&&r.keyType._def.checks?.length){let{type:n,...o}=As(r.keyType._def,e);return{...t,propertyNames:o}}else{if(r.keyType?._def.typeName===ji.ZodEnum)return{...t,propertyNames:{enum:r.keyType._def.values}};if(r.keyType?._def.typeName===ji.ZodBranded&&r.keyType._def.type._def.typeName===ji.ZodString&&r.keyType._def.type._def.checks?.length){let{type:n,...o}=vs(r.keyType._def,e);return{...t,propertyNames:o}}}return t}function Fh(r,e){if(e.mapStrategy==="record")return ws(r,e);let t=K(r.keyType._def,{...e,currentPath:[...e.currentPath,"items","items","0"]})||Ne(e),n=K(r.valueType._def,{...e,currentPath:[...e.currentPath,"items","items","1"]})||Ne(e);return{type:"array",maxItems:125,items:{type:"array",items:[t,n],minItems:2,maxItems:2}}}function Bh(r){let e=r.values,n=Object.keys(r.values).filter(i=>typeof e[e[i]]!="number").map(i=>e[i]),o=Array.from(new Set(n.map(i=>typeof i)));return{type:o.length===1?o[0]==="string"?"string":"number":["string","number"],enum:n}}function zh(r){return r.target==="openAi"?void 0:{not:Ne({...r,currentPath:[...r.currentPath,"not"]})}}function Hh(r){return r.target==="openApi3"?{enum:["null"],nullable:!0}:{type:"null"}}var Wi={ZodString:"string",ZodNumber:"number",ZodBigInt:"integer",ZodBoolean:"boolean",ZodNull:"null"};function Vh(r,e){if(e.target==="openApi3")return Gh(r,e);let t=r.options instanceof Map?Array.from(r.options.values()):r.options;if(t.every(n=>n._def.typeName in Wi&&(!n._def.checks||!n._def.checks.length))){let n=t.reduce((o,i)=>{let a=Wi[i._def.typeName];return a&&!o.includes(a)?[...o,a]:o},[]);return{type:n.length>1?n:n[0]}}else if(t.every(n=>n._def.typeName==="ZodLiteral"&&!n.description)){let n=t.reduce((o,i)=>{let a=typeof i._def.value;switch(a){case"string":case"number":case"boolean":return[...o,a];case"bigint":return[...o,"integer"];case"object":if(i._def.value===null)return[...o,"null"];case"symbol":case"undefined":case"function":default:return o}},[]);if(n.length===t.length){let o=n.filter((i,a,l)=>l.indexOf(i)===a);return{type:o.length>1?o:o[0],enum:t.reduce((i,a)=>i.includes(a._def.value)?i:[...i,a._def.value],[])}}}else if(t.every(n=>n._def.typeName==="ZodEnum"))return{type:"string",enum:t.reduce((n,o)=>[...n,...o._def.values.filter(i=>!n.includes(i))],[])};return Gh(r,e)}var Gh=(r,e)=>{let t=(r.options instanceof Map?Array.from(r.options.values()):r.options).map((n,o)=>K(n._def,{...e,currentPath:[...e.currentPath,"anyOf",`${o}`]})).filter(n=>!!n&&(!e.strictUnions||typeof n=="object"&&Object.keys(n).length>0));return t.length?{anyOf:t}:void 0};function jh(r,e){if(["ZodString","ZodNumber","ZodBigInt","ZodBoolean","ZodNull"].includes(r.innerType._def.typeName)&&(!r.innerType._def.checks||!r.innerType._def.checks.length))return e.target==="openApi3"?{type:Wi[r.innerType._def.typeName],nullable:!0}:{type:[Wi[r.innerType._def.typeName],"null"]};if(e.target==="openApi3"){let n=K(r.innerType._def,{...e,currentPath:[...e.currentPath]});return n&&"$ref"in n?{allOf:[n],nullable:!0}:n&&{...n,nullable:!0}}let t=K(r.innerType._def,{...e,currentPath:[...e.currentPath,"anyOf","0"]});return t&&{anyOf:[t,{type:"null"}]}}function Wh(r,e){let t={type:"number"};if(!r.checks)return t;for(let n of r.checks)switch(n.kind){case"int":t.type="integer",Ou(t,"type",n.message,e);break;case"min":e.target==="jsonSchema7"?n.inclusive?ce(t,"minimum",n.value,n.message,e):ce(t,"exclusiveMinimum",n.value,n.message,e):(n.inclusive||(t.exclusiveMinimum=!0),ce(t,"minimum",n.value,n.message,e));break;case"max":e.target==="jsonSchema7"?n.inclusive?ce(t,"maximum",n.value,n.message,e):ce(t,"exclusiveMaximum",n.value,n.message,e):(n.inclusive||(t.exclusiveMaximum=!0),ce(t,"maximum",n.value,n.message,e));break;case"multipleOf":ce(t,"multipleOf",n.value,n.message,e);break}return t}function $h(r,e){let t=e.target==="openAi",n={type:"object",properties:{}},o=[],i=r.shape();for(let l in i){let c=i[l];if(c===void 0||c._def===void 0)continue;let s=Xx(c);s&&t&&(c._def.typeName==="ZodOptional"&&(c=c._def.innerType),c.isNullable()||(c=c.nullable()),s=!1);let u=K(c._def,{...e,currentPath:[...e.currentPath,"properties",l],propertyPath:[...e.currentPath,"properties",l]});u!==void 0&&(n.properties[l]=u,s||o.push(l))}o.length&&(n.required=o);let a=Yx(r,e);return a!==void 0&&(n.additionalProperties=a),n}function Yx(r,e){if(r.catchall._def.typeName!=="ZodNever")return K(r.catchall._def,{...e,currentPath:[...e.currentPath,"additionalProperties"]});switch(r.unknownKeys){case"passthrough":return e.allowedAdditionalProperties;case"strict":return e.rejectedAdditionalProperties;case"strip":return e.removeAdditionalStrategy==="strict"?e.allowedAdditionalProperties:e.rejectedAdditionalProperties}}function Xx(r){try{return r.isOptional()}catch{return!0}}var qh=(r,e)=>{if(e.currentPath.toString()===e.propertyPath?.toString())return K(r.innerType._def,e);let t=K(r.innerType._def,{...e,currentPath:[...e.currentPath,"anyOf","1"]});return t?{anyOf:[{not:Ne(e)},t]}:Ne(e)};var Kh=(r,e)=>{if(e.pipeStrategy==="input")return K(r.in._def,e);if(e.pipeStrategy==="output")return K(r.out._def,e);let t=K(r.in._def,{...e,currentPath:[...e.currentPath,"allOf","0"]}),n=K(r.out._def,{...e,currentPath:[...e.currentPath,"allOf",t?"1":"0"]});return{allOf:[t,n].filter(o=>o!==void 0)}};function Yh(r,e){return K(r.type._def,e)}function Xh(r,e){let n={type:"array",uniqueItems:!0,items:K(r.valueType._def,{...e,currentPath:[...e.currentPath,"items"]})};return r.minSize&&ce(n,"minItems",r.minSize.value,r.minSize.message,e),r.maxSize&&ce(n,"maxItems",r.maxSize.value,r.maxSize.message,e),n}function Jh(r,e){return r.rest?{type:"array",minItems:r.items.length,items:r.items.map((t,n)=>K(t._def,{...e,currentPath:[...e.currentPath,"items",`${n}`]})).reduce((t,n)=>n===void 0?t:[...t,n],[]),additionalItems:K(r.rest._def,{...e,currentPath:[...e.currentPath,"additionalItems"]})}:{type:"array",minItems:r.items.length,maxItems:r.items.length,items:r.items.map((t,n)=>K(t._def,{...e,currentPath:[...e.currentPath,"items",`${n}`]})).reduce((t,n)=>n===void 0?t:[...t,n],[])}}function Zh(r){return{not:Ne(r)}}function Qh(r){return Ne(r)}var ef=(r,e)=>K(r.innerType._def,e);var tf=(r,e,t)=>{switch(e){case se.ZodString:return As(r,t);case se.ZodNumber:return Wh(r,t);case se.ZodObject:return $h(r,t);case se.ZodBigInt:return _h(r,t);case se.ZodBoolean:return Ph();case se.ZodDate:return Lu(r,t);case se.ZodUndefined:return Zh(t);case se.ZodNull:return Hh(t);case se.ZodArray:return Mh(r,t);case se.ZodUnion:case se.ZodDiscriminatedUnion:return Vh(r,t);case se.ZodIntersection:return Dh(r,t);case se.ZodTuple:return Jh(r,t);case se.ZodRecord:return ws(r,t);case se.ZodLiteral:return kh(r,t);case se.ZodEnum:return Nh(r);case se.ZodNativeEnum:return Bh(r);case se.ZodNullable:return jh(r,t);case se.ZodOptional:return qh(r,t);case se.ZodMap:return Fh(r,t);case se.ZodSet:return Xh(r,t);case se.ZodLazy:return()=>r.getter()._def;case se.ZodPromise:return Yh(r,t);case se.ZodNaN:case se.ZodNever:return zh(t);case se.ZodEffects:return Lh(r,t);case se.ZodAny:return Ne(t);case se.ZodUnknown:return Qh(t);case se.ZodDefault:return Oh(r,t);case se.ZodBranded:return vs(r,t);case se.ZodReadonly:return ef(r,t);case se.ZodCatch:return Ih(r,t);case se.ZodPipeline:return Kh(r,t);case se.ZodFunction:case se.ZodVoid:case se.ZodSymbol:return;default:return(n=>{})(e)}};function K(r,e,t=!1){let n=e.seen.get(r);if(e.override){let l=e.override?.(r,e,n,t);if(l!==Rh)return l}if(n&&!t){let l=Jx(n,e);if(l!==void 0)return l}let o={def:r,path:e.currentPath,jsonSchema:void 0};e.seen.set(r,o);let i=tf(r,r.typeName,e),a=typeof i=="function"?K(i(),e):i;if(a&&Zx(r,e,a),e.postProcess){let l=e.postProcess(a,r,e);return o.jsonSchema=a,l}return o.jsonSchema=a,a}var Jx=(r,e)=>{switch(e.$refStrategy){case"root":return{$ref:r.path.join("/")};case"relative":return{$ref:Ts(e.currentPath,r.path)};case"none":case"seen":return r.path.length<e.currentPath.length&&r.path.every((t,n)=>e.currentPath[n]===t)?(console.warn(`Recursive reference detected at ${e.currentPath.join("/")}! Defaulting to any`),Ne(e)):e.$refStrategy==="seen"?Ne(e):void 0}},Zx=(r,e,t)=>(r.description&&(t.description=r.description,e.markdownDescription&&(t.markdownDescription=r.description)),t);var Pn=(r,e)=>{let t=xh(e),n=typeof e=="object"&&e.definitions?Object.entries(e.definitions).reduce((c,[s,u])=>({...c,[s]:K(u._def,{...t,currentPath:[...t.basePath,t.definitionPath,s]},!0)??Ne(t)}),{}):void 0,o=typeof e=="string"?e:e?.nameStrategy==="title"?void 0:e?.name,i=K(r._def,o===void 0?t:{...t,currentPath:[...t.basePath,t.definitionPath,o]},!1)??Ne(t),a=typeof e=="object"&&e.name!==void 0&&e.nameStrategy==="title"?e.name:void 0;a!==void 0&&(i.title=a),t.flags.hasReferencedOpenAiAnyType&&(n||(n={}),n[t.openAiAnyTypeName]||(n[t.openAiAnyTypeName]={type:["string","number","integer","boolean","array","null"],items:{$ref:t.$refStrategy==="relative"?"1":[...t.basePath,t.definitionPath,t.openAiAnyTypeName].join("/")}}));let l=o===void 0?n?{...i,[t.definitionPath]:n}:i:{$ref:[...t.$refStrategy==="relative"?[]:t.basePath,t.definitionPath,o].join("/"),[t.definitionPath]:{...n,[o]:i}};return t.target==="jsonSchema7"?l.$schema="http://json-schema.org/draft-07/schema#":(t.target==="jsonSchema2019-09"||t.target==="openAi")&&(l.$schema="https://json-schema.org/draft/2019-09/schema#"),t.target==="openAi"&&("anyOf"in l||"oneOf"in l||"allOf"in l||"type"in l&&Array.isArray(l.type))&&console.warn("Warning: OpenAI may not support schemas with unions as roots! Try wrapping it in an object property."),l};import{z as Tr}from"zod";import{extendZodWithOpenApi as Qx}from"zod-openapi";Qx(Tr);var Ae=(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))(Ae||{});var ku=Tr.object({reason:Tr.nativeEnum(Ae),previousStepsDescription:Tr.array(Tr.string()).optional(),summary:Tr.string(),rootCause:Tr.string().optional()}).openapi({ref:"TestResultClassification"}),Rs=Tr.object({errorMessage:Tr.string(),errorStack:Tr.string().optional(),classification:ku.optional()}).openapi({ref:"TestFailureDetails"});var x=class extends Error{reason;constructor(e,t,n){let o=!1;for(let i of Object.values(Ae))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}}},Mo=class extends Error{updatedLocatorMemory;constructor(e,t,n={}){super(e,n),this.updatedLocatorMemory=t,this.name="NoElementsFoundUsingAIError"}},rn=class extends Error{decisions;constructor(e,t,n={}){super(e,n),this.decisions=t,this.name="NoElementsFoundUsingCacheError"}toString(){return`${this.message}
6
+ ]`;continue}o+=n[c],n[c]==="\\"?i=!0:a&&n[c]==="]"?a=!1:!a&&n[c]==="["&&(a=!0)}try{new RegExp(o)}catch{return console.warn(`Could not convert regex pattern at ${e.currentPath.join("/")} to a flag-independent form! Falling back to the flag-ignorant source`),r.source}return o}function Cs(r,e){if(e.target==="openAi"&&console.warn("Warning: OpenAI may not support records in schemas! Try an array of key-value pairs instead."),e.target==="openApi3"&&r.keyType?._def.typeName===Wi.ZodEnum)return{type:"object",required:r.keyType._def.values,properties:r.keyType._def.values.reduce((n,o)=>({...n,[o]:K(r.valueType._def,{...e,currentPath:[...e.currentPath,"properties",o]})??Ne(e)}),{}),additionalProperties:e.rejectedAdditionalProperties};let t={type:"object",additionalProperties:K(r.valueType._def,{...e,currentPath:[...e.currentPath,"additionalProperties"]})??e.allowedAdditionalProperties};if(e.target==="openApi3")return t;if(r.keyType?._def.typeName===Wi.ZodString&&r.keyType._def.checks?.length){let{type:n,...o}=Rs(r.keyType._def,e);return{...t,propertyNames:o}}else{if(r.keyType?._def.typeName===Wi.ZodEnum)return{...t,propertyNames:{enum:r.keyType._def.values}};if(r.keyType?._def.typeName===Wi.ZodBranded&&r.keyType._def.type._def.typeName===Wi.ZodString&&r.keyType._def.type._def.checks?.length){let{type:n,...o}=ws(r.keyType._def,e);return{...t,propertyNames:o}}}return t}function Fh(r,e){if(e.mapStrategy==="record")return Cs(r,e);let t=K(r.keyType._def,{...e,currentPath:[...e.currentPath,"items","items","0"]})||Ne(e),n=K(r.valueType._def,{...e,currentPath:[...e.currentPath,"items","items","1"]})||Ne(e);return{type:"array",maxItems:125,items:{type:"array",items:[t,n],minItems:2,maxItems:2}}}function Bh(r){let e=r.values,n=Object.keys(r.values).filter(i=>typeof e[e[i]]!="number").map(i=>e[i]),o=Array.from(new Set(n.map(i=>typeof i)));return{type:o.length===1?o[0]==="string"?"string":"number":["string","number"],enum:n}}function zh(r){return r.target==="openAi"?void 0:{not:Ne({...r,currentPath:[...r.currentPath,"not"]})}}function Hh(r){return r.target==="openApi3"?{enum:["null"],nullable:!0}:{type:"null"}}var $i={ZodString:"string",ZodNumber:"number",ZodBigInt:"integer",ZodBoolean:"boolean",ZodNull:"null"};function Vh(r,e){if(e.target==="openApi3")return Gh(r,e);let t=r.options instanceof Map?Array.from(r.options.values()):r.options;if(t.every(n=>n._def.typeName in $i&&(!n._def.checks||!n._def.checks.length))){let n=t.reduce((o,i)=>{let a=$i[i._def.typeName];return a&&!o.includes(a)?[...o,a]:o},[]);return{type:n.length>1?n:n[0]}}else if(t.every(n=>n._def.typeName==="ZodLiteral"&&!n.description)){let n=t.reduce((o,i)=>{let a=typeof i._def.value;switch(a){case"string":case"number":case"boolean":return[...o,a];case"bigint":return[...o,"integer"];case"object":if(i._def.value===null)return[...o,"null"];case"symbol":case"undefined":case"function":default:return o}},[]);if(n.length===t.length){let o=n.filter((i,a,l)=>l.indexOf(i)===a);return{type:o.length>1?o:o[0],enum:t.reduce((i,a)=>i.includes(a._def.value)?i:[...i,a._def.value],[])}}}else if(t.every(n=>n._def.typeName==="ZodEnum"))return{type:"string",enum:t.reduce((n,o)=>[...n,...o._def.values.filter(i=>!n.includes(i))],[])};return Gh(r,e)}var Gh=(r,e)=>{let t=(r.options instanceof Map?Array.from(r.options.values()):r.options).map((n,o)=>K(n._def,{...e,currentPath:[...e.currentPath,"anyOf",`${o}`]})).filter(n=>!!n&&(!e.strictUnions||typeof n=="object"&&Object.keys(n).length>0));return t.length?{anyOf:t}:void 0};function jh(r,e){if(["ZodString","ZodNumber","ZodBigInt","ZodBoolean","ZodNull"].includes(r.innerType._def.typeName)&&(!r.innerType._def.checks||!r.innerType._def.checks.length))return e.target==="openApi3"?{type:$i[r.innerType._def.typeName],nullable:!0}:{type:[$i[r.innerType._def.typeName],"null"]};if(e.target==="openApi3"){let n=K(r.innerType._def,{...e,currentPath:[...e.currentPath]});return n&&"$ref"in n?{allOf:[n],nullable:!0}:n&&{...n,nullable:!0}}let t=K(r.innerType._def,{...e,currentPath:[...e.currentPath,"anyOf","0"]});return t&&{anyOf:[t,{type:"null"}]}}function Wh(r,e){let t={type:"number"};if(!r.checks)return t;for(let n of r.checks)switch(n.kind){case"int":t.type="integer",ku(t,"type",n.message,e);break;case"min":e.target==="jsonSchema7"?n.inclusive?ce(t,"minimum",n.value,n.message,e):ce(t,"exclusiveMinimum",n.value,n.message,e):(n.inclusive||(t.exclusiveMinimum=!0),ce(t,"minimum",n.value,n.message,e));break;case"max":e.target==="jsonSchema7"?n.inclusive?ce(t,"maximum",n.value,n.message,e):ce(t,"exclusiveMaximum",n.value,n.message,e):(n.inclusive||(t.exclusiveMaximum=!0),ce(t,"maximum",n.value,n.message,e));break;case"multipleOf":ce(t,"multipleOf",n.value,n.message,e);break}return t}function $h(r,e){let t=e.target==="openAi",n={type:"object",properties:{}},o=[],i=r.shape();for(let l in i){let c=i[l];if(c===void 0||c._def===void 0)continue;let s=eM(c);s&&t&&(c._def.typeName==="ZodOptional"&&(c=c._def.innerType),c.isNullable()||(c=c.nullable()),s=!1);let u=K(c._def,{...e,currentPath:[...e.currentPath,"properties",l],propertyPath:[...e.currentPath,"properties",l]});u!==void 0&&(n.properties[l]=u,s||o.push(l))}o.length&&(n.required=o);let a=Qx(r,e);return a!==void 0&&(n.additionalProperties=a),n}function Qx(r,e){if(r.catchall._def.typeName!=="ZodNever")return K(r.catchall._def,{...e,currentPath:[...e.currentPath,"additionalProperties"]});switch(r.unknownKeys){case"passthrough":return e.allowedAdditionalProperties;case"strict":return e.rejectedAdditionalProperties;case"strip":return e.removeAdditionalStrategy==="strict"?e.allowedAdditionalProperties:e.rejectedAdditionalProperties}}function eM(r){try{return r.isOptional()}catch{return!0}}var qh=(r,e)=>{if(e.currentPath.toString()===e.propertyPath?.toString())return K(r.innerType._def,e);let t=K(r.innerType._def,{...e,currentPath:[...e.currentPath,"anyOf","1"]});return t?{anyOf:[{not:Ne(e)},t]}:Ne(e)};var Kh=(r,e)=>{if(e.pipeStrategy==="input")return K(r.in._def,e);if(e.pipeStrategy==="output")return K(r.out._def,e);let t=K(r.in._def,{...e,currentPath:[...e.currentPath,"allOf","0"]}),n=K(r.out._def,{...e,currentPath:[...e.currentPath,"allOf",t?"1":"0"]});return{allOf:[t,n].filter(o=>o!==void 0)}};function Yh(r,e){return K(r.type._def,e)}function Xh(r,e){let n={type:"array",uniqueItems:!0,items:K(r.valueType._def,{...e,currentPath:[...e.currentPath,"items"]})};return r.minSize&&ce(n,"minItems",r.minSize.value,r.minSize.message,e),r.maxSize&&ce(n,"maxItems",r.maxSize.value,r.maxSize.message,e),n}function Jh(r,e){return r.rest?{type:"array",minItems:r.items.length,items:r.items.map((t,n)=>K(t._def,{...e,currentPath:[...e.currentPath,"items",`${n}`]})).reduce((t,n)=>n===void 0?t:[...t,n],[]),additionalItems:K(r.rest._def,{...e,currentPath:[...e.currentPath,"additionalItems"]})}:{type:"array",minItems:r.items.length,maxItems:r.items.length,items:r.items.map((t,n)=>K(t._def,{...e,currentPath:[...e.currentPath,"items",`${n}`]})).reduce((t,n)=>n===void 0?t:[...t,n],[])}}function Zh(r){return{not:Ne(r)}}function Qh(r){return Ne(r)}var ef=(r,e)=>K(r.innerType._def,e);var tf=(r,e,t)=>{switch(e){case se.ZodString:return Rs(r,t);case se.ZodNumber:return Wh(r,t);case se.ZodObject:return $h(r,t);case se.ZodBigInt:return _h(r,t);case se.ZodBoolean:return Ph();case se.ZodDate:return Uu(r,t);case se.ZodUndefined:return Zh(t);case se.ZodNull:return Hh(t);case se.ZodArray:return Mh(r,t);case se.ZodUnion:case se.ZodDiscriminatedUnion:return Vh(r,t);case se.ZodIntersection:return Dh(r,t);case se.ZodTuple:return Jh(r,t);case se.ZodRecord:return Cs(r,t);case se.ZodLiteral:return kh(r,t);case se.ZodEnum:return Nh(r);case se.ZodNativeEnum:return Bh(r);case se.ZodNullable:return jh(r,t);case se.ZodOptional:return qh(r,t);case se.ZodMap:return Fh(r,t);case se.ZodSet:return Xh(r,t);case se.ZodLazy:return()=>r.getter()._def;case se.ZodPromise:return Yh(r,t);case se.ZodNaN:case se.ZodNever:return zh(t);case se.ZodEffects:return Lh(r,t);case se.ZodAny:return Ne(t);case se.ZodUnknown:return Qh(t);case se.ZodDefault:return Oh(r,t);case se.ZodBranded:return ws(r,t);case se.ZodReadonly:return ef(r,t);case se.ZodCatch:return Ih(r,t);case se.ZodPipeline:return Kh(r,t);case se.ZodFunction:case se.ZodVoid:case se.ZodSymbol:return;default:return(n=>{})(e)}};function K(r,e,t=!1){let n=e.seen.get(r);if(e.override){let l=e.override?.(r,e,n,t);if(l!==Rh)return l}if(n&&!t){let l=tM(n,e);if(l!==void 0)return l}let o={def:r,path:e.currentPath,jsonSchema:void 0};e.seen.set(r,o);let i=tf(r,r.typeName,e),a=typeof i=="function"?K(i(),e):i;if(a&&rM(r,e,a),e.postProcess){let l=e.postProcess(a,r,e);return o.jsonSchema=a,l}return o.jsonSchema=a,a}var tM=(r,e)=>{switch(e.$refStrategy){case"root":return{$ref:r.path.join("/")};case"relative":return{$ref:As(e.currentPath,r.path)};case"none":case"seen":return r.path.length<e.currentPath.length&&r.path.every((t,n)=>e.currentPath[n]===t)?(console.warn(`Recursive reference detected at ${e.currentPath.join("/")}! Defaulting to any`),Ne(e)):e.$refStrategy==="seen"?Ne(e):void 0}},rM=(r,e,t)=>(r.description&&(t.description=r.description,e.markdownDescription&&(t.markdownDescription=r.description)),t);var In=(r,e)=>{let t=xh(e),n=typeof e=="object"&&e.definitions?Object.entries(e.definitions).reduce((c,[s,u])=>({...c,[s]:K(u._def,{...t,currentPath:[...t.basePath,t.definitionPath,s]},!0)??Ne(t)}),{}):void 0,o=typeof e=="string"?e:e?.nameStrategy==="title"?void 0:e?.name,i=K(r._def,o===void 0?t:{...t,currentPath:[...t.basePath,t.definitionPath,o]},!1)??Ne(t),a=typeof e=="object"&&e.name!==void 0&&e.nameStrategy==="title"?e.name:void 0;a!==void 0&&(i.title=a),t.flags.hasReferencedOpenAiAnyType&&(n||(n={}),n[t.openAiAnyTypeName]||(n[t.openAiAnyTypeName]={type:["string","number","integer","boolean","array","null"],items:{$ref:t.$refStrategy==="relative"?"1":[...t.basePath,t.definitionPath,t.openAiAnyTypeName].join("/")}}));let l=o===void 0?n?{...i,[t.definitionPath]:n}:i:{$ref:[...t.$refStrategy==="relative"?[]:t.basePath,t.definitionPath,o].join("/"),[t.definitionPath]:{...n,[o]:i}};return t.target==="jsonSchema7"?l.$schema="http://json-schema.org/draft-07/schema#":(t.target==="jsonSchema2019-09"||t.target==="openAi")&&(l.$schema="https://json-schema.org/draft/2019-09/schema#"),t.target==="openAi"&&("anyOf"in l||"oneOf"in l||"allOf"in l||"type"in l&&Array.isArray(l.type))&&console.warn("Warning: OpenAI may not support schemas with unions as roots! Try wrapping it in an object property."),l};import{z as Ar}from"zod";import{extendZodWithOpenApi as nM}from"zod-openapi";nM(Ar);var Te=(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))(Te||{});var zu=Ar.object({reason:Ar.nativeEnum(Te),previousStepsDescription:Ar.array(Ar.string()).optional(),summary:Ar.string(),rootCause:Ar.string().optional()}).openapi({ref:"TestResultClassification"}),xs=Ar.object({errorMessage:Ar.string(),errorStack:Ar.string().optional(),classification:zu.optional()}).openapi({ref:"TestFailureDetails"});var C=class extends Error{reason;constructor(e,t,n){let o=!1;for(let i of Object.values(Te))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}}},_o=class extends Error{updatedLocatorMemory;constructor(e,t,n={}){super(e,n),this.updatedLocatorMemory=t,this.name="NoElementsFoundUsingAIError"}},nn=class extends Error{decisions;constructor(e,t,n={}){super(e,n),this.decisions=t,this.name="NoElementsFoundUsingCacheError"}toString(){return`${this.message}
7
7
  Decisions:
8
8
  ${this.decisions.map(e=>e.toString()).join(`
9
- `)}`}};function rf(r){return r instanceof Error?r.message.includes("Timeout")&&r.message.includes("exceeded")&&r.message.includes("waiting for locator"):!1}function Uu(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 vr=class extends Error{retryableWithAI;constructor(e,t,n={}){super(e,n),this.name="CacheAttributesDisqualifyElementError",this.retryableWithAI=t}},Cs=class extends vr{constructor(e,t={}){super(e,!0,t),this.name="BoundingBoxMovedError"}},xs=class extends vr{constructor(e,t={}){super(e,!1,t),this.name="ZeroOpacityError"}};function Fu(r){return r instanceof Error?r.message.includes("Could not find attribute data-momentic-id for object"):!1}function Bu(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 zu(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 $i=class extends Error{constructor(e,t={}){super(e,t),this.name="InsufficientCacheDataError"}};var eM={CLICK:"Click on an element on the page.",TYPE:"Focus the element then type the specified text into an input on the page.",PRESS:"Press one or more keyboard keys.",KEY_DOWN:"Hold down one or more keyboard keys.",KEY_UP:"Release one or more keyboard keys.",SELECT_OPTION:"Choose an option from a native <select> component. Never use this command for non <select> elements. Instead, use a series of CLICK commands for those.",NAVIGATE:"Go to the specified fully qualified URL.",SCROLL_UP:"Scroll up.",SCROLL_DOWN:"Scroll down.",GO_BACK:"Go back to the previous page.",HOVER:"Hover over an element.",AI_ASSERTION:"Verify a statement about the current page, retrying until it is true. Only generate an assertion if the goal includes language like 'check that', 'verify that', etc..",WAIT:"Wait a fixed amount of seconds."},tM={...eM,JAVASCRIPT:"Execute JavaScript code in NODE or BROWSER environment.",ELEMENT_CHECK:"Perform a manual assertion on a specific element.",PAGE_CHECK:"Perform a manual case sensitive assertion on the page's html.",NEW_TAB:"Open a new browser tab with the specified URL.",WAIT_FOR_URL:"Wait for the URL to match a pattern.",AI_EXTRACT:"Extract data from the page and optionally store it in an environment variable.",DRAG:"Drag an element from one location and drop it onto another element.",COPY:"Copy the specified text value to the browser clipboard.",GO_FORWARD:"Navigate forward to the next page in the browser history (if available). Only use this after having navigated back with GO_BACK. Do not use this to navigate to a different page - use NAVIGATE instead.",LOCAL_STORAGE:"Set or get a value in the browser's localStorage. Use this to store data that persists across page reloads or to read stored values.",MOUSE_DRAG:"Drag the mouse from a starting point (or element) in a specific direction by pixel amounts. Prefer using DRAG (drag and drop between elements) instead unless the user explicitly requests dragging in a direction or by pixels. Use this when dragging needs to move a specific distance rather than to a target element.",PASTE:"Paste the contents of the browser clipboard into the currently focused element. Use this after copying text with COPY or when pasting content that was previously copied.",REFRESH:"Reload the current page. Use this to refresh the page content or retry a failed operation.",REQUEST:"Make an HTTP API request to a specified URL. Use this to interact with REST APIs, send data to a server, or retrieve data from an endpoint. Supports GET, POST, PUT, DELETE, and PATCH methods with custom headers, query parameters, and request body."};Pu.options.forEach(r=>{let e=r.shape.type.value;if(e!=="SUCCESS"&&!tM[e])throw new Error(`Command type ${e} is missing a description`)});var rM=T.object({type:T.literal("CLICK"),description:T.string().describe("Description of the element to click in the Current Page. Never click on <select> elements, see SELECT_OPTION."),doubleClick:T.boolean().or(T.null()),rightClick:T.boolean().or(T.null())}),nM=T.object({type:T.literal("TYPE"),description:T.string().describe("Description of the element to type into, which must be an <input>, <textarea>, or contenteditable element."),text:T.string().describe("The text to enter, truncated to 500 characters. If the PM provided text in the goals, use it exactly without modification."),pressEnter:T.boolean().or(T.null()).describe("Press enter after typing (useful for form submissions)."),clearContent:T.boolean().describe("Clear existing content before typing. Disable to append to the existing text.")}),oM=T.object({type:T.literal("GO_BACK")}),iM=T.object({type:T.literal("GO_FORWARD")}),aM=T.object({type:T.literal("LOCAL_STORAGE"),key:T.string().describe("The localStorage key to set or get."),value:T.string().describe("The value to store in localStorage. If reading, this can be empty.")}),sM=T.object({type:T.literal("PRESS"),keys:T.array(T.string()).describe('The keys to press. Only use key names supported by the Playwright press method, such as "a", "ArrowLeft", "Meta", "Control", and "Enter". Multiple keys will be pressed together. Do not suggest platform-specific key combinations, such as CTRL+C.')}),lM=T.object({type:T.literal("SELECT_OPTION"),description:T.string().describe("Description of the <select> element to choose from. Only use this command to interact with native HTML <select> elements. You must use CLICK to select from any other HTML element, such as <input>, <div>, or custom elements."),option:T.discriminatedUnion("type",[T.object({type:T.literal("VALUE"),value:T.string()}),T.object({type:T.literal("LABEL"),label:T.string()}),T.object({type:T.literal("INDEX"),index:T.string().describe("Zero-based index of the option within the select.")})]).describe("Which option to select. Choose 1 of 3 strategies for selecting. By value is exactly matching the 'value' attribute. By label is exactly matching the 'label' attribute. By index is using the zero-based index of the option within the select.")}),cM=T.object({type:T.literal("NAVIGATE"),url:T.string().describe("The URL to navigate to. Only navigate to URLs relevant to the user goal.")}),uM=T.object({type:T.literal("SCROLL"),y:T.number().describe("Scroll up or down by the specified pixels. Positive values scroll down.")}),dM=T.object({type:T.literal("WAIT"),timeout:T.number().describe("The number of seconds to wait.")}),pM=T.object({type:T.literal("AI_ASSERTION"),assertion:T.string().describe("The assertion to verify. This should be a statement verifiable based on the current page HTML or screenshot. Be specific enough that the assertion is not ambiguous or open to interpretation. Make sure the assertion aligns with what the user intends to verify."),timeout:T.number().describe("The max amount of seconds to wait for the assertion to be true. Respect user wishes but allow no more than 60. If unspecified, choose 5 for quick checks like form status, 10 for page loads, and 30 for actions that explicitly trigger a long time, like image generation.")}),mM=T.object({type:T.literal("HOVER"),description:T.string().describe("Description of the element to hover over. Prefer elements that have visible bounding boxes according to the screenshot, element class attribute, or child contents.")}),gM=T.object({type:T.literal("COPY"),value:T.string().describe("The text value to copy to the browser clipboard. This should be the exact text that needs to be copied.")}),hM=T.object({type:T.literal("PASTE")}),fM=T.object({type:T.literal("REFRESH")}),SM=T.object({type:T.literal("REQUEST"),url:T.string().describe("The URL to send the HTTP request to. Can be a full URL or relative path."),method:T.enum(["GET","POST","PUT","DELETE","PATCH"]).describe("The HTTP method to use. GET for retrieving data, POST for creating resources, PUT for updating resources, DELETE for removing resources, PATCH for partial updates."),headers:T.record(T.string(),T.string()).or(T.null()).describe("Optional HTTP headers as key-value pairs. Common headers include 'Content-Type', 'Authorization', 'Accept', etc."),params:T.record(T.string(),T.string()).or(T.null()).describe("Optional URL query parameters as key-value pairs. These will be appended to the URL as ?key1=value1&key2=value2."),body:T.string().or(T.null()).describe("Optional request body as a string. For JSON data, stringify the object. Typically used with POST, PUT, or PATCH requests."),timeout:T.number().int().or(T.null()).describe("Optional maximum number of seconds to wait for the request to complete. Defaults to 30 seconds if not specified.")}),yM=T.object({type:T.literal("DRAG"),fromDescription:T.string().describe("Description of the element to drag. Prefer precise identifiers or text that clearly distinguishes the element."),toDescription:T.string().describe("Description of the element to drop onto. Ensure the drop target is interactable and visible."),steps:T.number().int().positive().or(T.null()).describe("Optional number of intermediate mouse move steps during the drag. Do not use this unless the user tells you to."),hoverSeconds:T.number().positive().or(T.null()).describe("Optional seconds to hover over the destination before releasing the drag.")}),bM=T.object({type:T.literal("MOUSE_DRAG"),description:T.string().or(T.null()).describe("Optional description of the element to start the drag from. If not provided, starts from current mouse position."),deltaX:T.number().describe("Number of pixels to move horizontally (positive = right, negative = left)."),deltaY:T.number().describe("Number of pixels to move vertically (positive = down, negative = up)."),steps:T.number().int().positive().or(T.null()).describe("Optional number of intermediate mouse move steps during the drag.")}),EM=T.object({type:T.literal("JAVASCRIPT"),code:T.string().describe("JavaScript code to execute. Defaults to NODE environment unless BROWSER is specified."),environment:T.union([T.literal("NODE"),T.literal("BROWSER")]).or(T.null()).describe("Execution environment. Default is NODE."),timeout:T.number().or(T.null()).describe("Max seconds for the code to complete. Max 60 seconds.")}),TM=T.object({type:T.literal("AI_EXTRACT"),goal:T.string().describe("Description of what data to extract from the page. Be specific about what you want to extract and where to find it."),schema:T.string().or(T.null()).describe("JSON schema defining the expected structure of the extracted data."),envKey:T.string().or(T.null()).describe("Environment variable name to store the extracted result in. If provided, the result will be stored and can be referenced later."),iframeUrl:T.string().or(T.null()).describe("URL or URL regex for the iframe to extract data from.")}),vM=T.object({type:T.literal("ELEMENT_CHECK"),description:T.string().describe("Description of the element to check."),assertionType:T.enum(["EXISTS","VISIBLE","CONTENT_CONTAINS","CONTENT_EQUALS"]).describe("The type of assertion. EXISTS checks if element exists, VISIBLE checks if visible, CONTENT_CONTAINS checks if text contains value, CONTENT_EQUALS checks if text equals value."),value:T.string().or(T.null()).describe("The value to check against (required for CONTENT assertions)."),negated:T.boolean().or(T.null()).describe("If true, asserts the opposite (e.g., does NOT exist)."),timeout:T.number().or(T.null()).describe("Max seconds to wait for the assertion to be true.")}),AM=T.object({type:T.literal("PAGE_CHECK"),value:T.string().describe("The text content to check for on the page."),negated:T.boolean().or(T.null()).describe("If true, checks that the content is NOT present."),timeout:T.number().or(T.null()).describe("Max seconds to wait for the assertion to be true.")}),wM=T.object({type:T.literal("NEW_TAB"),url:T.string().describe("The URL to open in the new tab.")}),RM=T.object({type:T.literal("WAIT_FOR_URL"),matcher:T.discriminatedUnion("type",[T.object({type:T.literal("SUBSTRING"),url:T.string()}),T.object({type:T.literal("GLOB"),glob:T.string()}),T.object({type:T.literal("REGEX"),regex:T.string()}),T.object({type:T.literal("DOMAIN"),domain:T.string()})]).describe("How to match the URL."),caseInsensitive:T.boolean().or(T.null()),negated:T.boolean().or(T.null()).describe("Wait for the URL to NOT match instead."),timeout:T.number().or(T.null()).describe("Max seconds to wait for the URL.")}),nf=T.object({type:T.literal("SUCCESS")}),Hu=T.object({type:T.literal("FAILURE")}),qi=T.discriminatedUnion("type",[rM,nM,sM,lM,cM,uM,dM,pM,mM,oM]),cW=Pn(qi),Ms=T.discriminatedUnion("type",[...qi.options,yM,EM,vM,AM,wM,RM,TM,gM,iM,aM,bM,hM,fM,SM]),uW=Pn(Ms),CM=T.discriminatedUnion("type",[...qi.options,Hu]).describe("The command that will be executed next. This should naturally follow from your reasoning and be consistent with the goal."),dW=Pn(CM),xM=T.discriminatedUnion("type",[...qi.options,nf,Hu]),pW=Pn(xM),mW=T.discriminatedUnion("type",[...Ms.options,nf,Hu]),MM=T.object({command:qi,thoughts:T.string()}),gW=Pn(MM),hW=T.object({command:T.unknown(),thoughts:T.string()});import{z as Gu}from"zod";import{extendZodWithOpenApi as IM}from"zod-openapi";import{z as of}from"zod";import{extendZodWithOpenApi as _M}from"zod-openapi";import{z as In}from"zod";var $t=In.object({index:In.number().optional().describe("global index within a test (in-order traversal)"),id:In.string(),skipped:In.boolean().optional(),envKey:In.string().optional().describe("key in the environment to save the result of this step to"),aiSuggested:In.boolean().optional(),retries:In.number().optional()});_M(of);var PM=$t.extend({type:of.literal("PRESET_ACTION")}),qt=PM.extend({command:Co}).openapi({ref:"PresetAction"});IM(Gu);var On=$t.extend({type:Gu.literal("AI_ACTION"),text:Gu.string(),steps:qt.array().optional()}).openapi({ref:"AIAction"});import{z as _t}from"zod";import{z as _s}from"zod";import{extendZodWithOpenApi as OM}from"zod-openapi";OM(_s);var _o=$t.extend({type:_s.literal("AI_ACTION_DYNAMIC"),text:_s.string(),retries:_s.number().optional()}).openapi({ref:"AIActionDynamic"});import{z as af}from"zod";var Vu=$t.extend({type:af.literal("CONDITIONAL"),skipped:af.boolean().optional()});import{z as ue}from"zod";var LM=ue.object({cacheKey:ue.string(),cacheExpiryMs:ue.number()}),ju=$t.extend({id:ue.string().uuid().describe("ID of the module step itself. Used to 'namespace' step cache entries."),inputs:ue.record(ue.string()).optional(),cacheConfig:LM.optional()}),Gr=ju.extend({type:ue.literal("MODULE"),moduleId:ue.string().uuid()}),NM=ue.union([Gr.pick({type:!0,moduleId:!0}),ue.record(ue.unknown())]),DM=ue.object({type:ue.literal("URL_REGEX"),regex:ue.string()}),kM=ue.object({type:ue.literal("PAGE_CHECK"),substring:ue.string()}),Wu=ue.object({cacheInvalidation:ue.discriminatedUnion("type",[kM,DM]).optional()}),Kt=ue.object({moduleId:ue.string().uuid(),name:ue.string(),description:ue.string().nullish(),enabled:ue.boolean().nullish(),parameters:ue.string().array().nullish(),defaultParameters:ue.record(ue.string(),ue.string()).nullish(),parameterEnums:ue.record(ue.string(),ue.string().array()).nullish(),defaultCacheKey:ue.string().nullish(),defaultCacheTtl:ue.number().nullish(),defaultCacheAllInvocations:ue.boolean().nullish(),autoAuth:ue.boolean().nullish(),advanced:Wu.nullish()});import{z as Yt}from"zod";var sf=(n=>(n.ALWAYS="ALWAYS",n.ON_FAILURE="ON_FAILURE",n.ON_ACTION_FAILURE="ON_ACTION_FAILURE",n))(sf||{});var UM=Yt.discriminatedUnion("type",[Yt.object({type:Yt.literal("NAVIGATE_URL"),url:Yt.string().url()}),Yt.object({type:Yt.literal("GO_TO_SECTION_START")})]),FM=Yt.object({trigger:Yt.nativeEnum(sf).optional(),attempts:Yt.number().int().optional(),restartBehavior:UM}),Ki=$t.extend({type:Yt.literal("SECTION"),description:Yt.string().describe("user provided goal of what the section should accomplish"),plan:Yt.string().array().optional(),autohealingConfig:FM.optional()});var lf=Kt.merge(ju).extend({type:_t.literal("RESOLVED_MODULE"),steps:_t.lazy(()=>ot.array())}),Yi=Kt.extend({steps:_t.lazy(()=>ot.array())}),$u=Ki.extend({steps:_t.lazy(()=>Pt.array())}),BM=Ki.extend({steps:_t.lazy(()=>ot.array())}),Po=Vu.extend({blocks:_t.object({assertion:_t.lazy(()=>qt),steps:_t.lazy(()=>Pt.array())}).array(),elseSteps:_t.lazy(()=>Pt.array().optional())}),zM=Vu.extend({blocks:_t.object({assertion:_t.lazy(()=>qt),steps:_t.lazy(()=>ot.array())}).array(),elseSteps:_t.lazy(()=>ot.array().optional())}),Pt=_t.discriminatedUnion("type",[qt,On,_o,Gr,Po,$u]),ot=_t.discriminatedUnion("type",[qt,On,_o,lf,zM,BM]);import{z as Xt}from"zod";var HM=Xt.object({steps:Pt.array(),beforeSteps:Pt.array().nullish(),afterSteps:Pt.array().nullish()}),Ln=Xt.object({steps:ot.array(),beforeSteps:ot.array().nullish(),afterSteps:ot.array().nullish()}),Nn=Xt.object({steps:Xt.record(Xt.string(),Xt.unknown()).array(),beforeSteps:Xt.record(Xt.string(),Xt.unknown()).array().nullish(),afterSteps:Xt.record(Xt.string(),Xt.unknown()).array().nullish()});var Dn="1.0.21",qu="0.0.1";import{z as ft}from"zod";import{z as kn}from"zod";var GM=/^[a-f0-9]{8}-[a-f0-9]{4}-[1-5][a-f0-9]{3}-[89ab][a-f0-9]{3}-[a-f0-9]{12}$/,nn=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 Io=kn.string().min(1).max(255).superRefine((r,e)=>{try{Ku(r)}catch(t){return e.addIssue({code:kn.ZodIssueCode.custom,message:t.message,fatal:!0}),kn.NEVER}});function Ku(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(GM))throw new Error("Name cannot be a UUID. Please choose a different name.")}var Ps=kn.preprocess(r=>r===null?"":r,kn.union([kn.string().url(),kn.literal("")])).optional();var VM=["AI_EXTRACT","JAVASCRIPT"],jM=ft.object({id:ft.string().optional().describe("Recommended way of selecting an entity. The id of the entity to resolve."),name:Io.optional().describe("1-255 chars; Only letters/numbers/dashes. Cannot start/end with '-'. Not '.yaml', 'none', or UUID."),path:ft.string().optional().describe("The path of the entity to resolve.")}).describe("A selector for a single entity. Exactly one of id, name, or path must be provided. Id is recommended.").refine(r=>[r.id,r.name,r.path].filter(Boolean).length===1,"Exactly one of id, name, or path must be provided."),WM=ft.object({selector:jM,inputs:ft.record(ft.string()).or(ft.null())}),P$=ft.object({type:ft.literal("PRESET_ACTION"),action:Ms,envKey:ft.string().or(ft.null()).describe(`key in the environment to save the result of this step to. Only use this for ${VM.join(" or ")} steps.`)}),I$=ft.object({type:ft.literal("MODULE"),module:WM}),O$=ft.object({type:ft.literal("AI_ACTION_DYNAMIC"),text:ft.string().describe("The goal description for the AI action. Supports handlebars templates like {{env.VARIABLE_NAME}}.")});var cf=I.object({phrase:I.string()}),Yu=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()])}),mq=I.object({text:I.string()}),$M=I.boolean().or(I.nativeEnum(Xr)).transform(r=>!(!r||r==="irrelevant")),uf=I.object({attributes:I.array(I.string()).nullish(),text:$M.nullish(),position:I.nativeEnum(Xr).nullish(),shape:I.nativeEnum(Xr).nullish()}),qM=I.object({id:I.number().int(),requirements:uf}),KM=qM.array(),df=I.object({thoughts:I.string(),review:I.string().optional(),id:I.number().int(),updatedMemory:bu.optional(),requirements:uf.nullish().transform(r=>{if(r!==null)return r}),additionalElements:KM.nullish().transform(r=>{if(r!==null)return r})});var Xu=(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))(Xu||{}),pf=(o=>(o.NONE="NONE",o.AMBIGUOUS_DESCRIPTION="AMBIGUOUS_DESCRIPTION",o.COPILOT_MISUSE="COPILOT_MISUSE",o.IRRELEVANT_MESSAGE="IRRELEVANT_MESSAGE",o))(pf||{});var mf=I.object({thoughts:I.string(),category:I.nativeEnum(Xu)}),gf=I.object({thoughts:I.string(),category:I.nativeEnum(pf)}),YM=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()})]),gq=I.object({thoughts:I.string(),patches:YM.array()}),XM=[I.literal("add"),I.literal("replace"),I.literal("remove")],JM=I.object({op:I.union(XM),path:I.string(),value:ot.optional()}),hf=I.object({patches:JM.array(),thoughts:I.string()}),ff=(n=>(n.LEGITIMATE="LEGITIMATE",n.RECOVERABLE="RECOVERABLE",n.INELIGIBLE="INELIGIBLE",n))(ff||{}),Sf=I.object({thoughts:I.string(),scenario:I.nativeEnum(ff),instructions:I.string().nullish()}),yf=I.object({reasoning:I.string(),scenario:I.string(),patch:I.null().optional()}),hq=I.object({thoughts:I.string(),evaluation:I.number().min(0).max(10)}),fq=I.object({observations:I.string(),reasoning:I.string(),command:bs});var Ju=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")})])}),ZM=I.object({startId:I.number().int(),endId:I.number().int()}),Zu=(n=>(n.SIMPLE_CONTENT_BASED_LOCATOR="SIMPLE_CONTENT_BASED_LOCATOR",n.SIMPLE_CONTENT_BASED_ASSERTION="SIMPLE_CONTENT_BASED_ASSERTION",n.OTHER="OTHER",n))(Zu||{}),bf=I.object({categoryThoughts:I.string(),category:I.nativeEnum(Zu),relevantSections:ZM.array()});import{z as P}from"zod";import*as te from"zod";var vq=te.object({thoughts:te.string().optional().describe("only provided if a description was provided"),target:Zr.optional().describe("only provided if a description was provided"),pageState:te.string().optional().describe("serialized a11y tree, only provided if a description was provided"),options:te.object({label:te.string(),value:te.string()}).array().optional().describe("list of options, provided for <select> elements only"),screenshot:te.object({data:te.string(),height:te.number().int(),width:te.number().int()}).optional().describe("only provided if returnScreenshot is true")}),Ef=te.union([te.literal("ELEMENT_CHECK"),te.literal("NEGATED_CHECK"),te.literal("NEGATED_ELEMENT_VISIBLE_CHECK"),te.literal("SELECT_OPTION"),te.literal("TYPE")]);function Xi(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 Ji=(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))(Ji||{}),Oo=te.object({matched:te.boolean(),reason:te.string().optional().describe("Human understandable description"),logs:te.string().array().optional().describe("Logs for debugging")}),QM=Oo.extend({type:te.literal("USER_SELECTOR")}),e_=Oo.extend({type:te.literal("CSS_SELECTOR"),selectors:te.string().array()}),t_=Oo.extend({type:te.literal("HYBRID_SELECTOR")}),r_=Oo.extend({type:te.literal("HTML_DISTANCE"),distance:te.number().optional(),closestElement:te.string().optional(),savedElement:te.string().optional()}),n_=Oo.extend({type:te.literal("TEMPLATE_MATCHING"),elementImageUrl:te.string().url()}),o_=Oo.extend({type:te.literal("AUTO_FRAME"),logs:te.string().array().optional()}),Tf=te.discriminatedUnion("type",[QM,e_,t_,r_,n_,o_]);import{z as ta}from"zod";import{z as h_}from"zod";import*as G from"zod";import{extendZodWithOpenApi as s_}from"zod-openapi";import{cloneDeep as Lq}from"lodash-es";import Dq from"truncate-json";import*as Bn from"zod";import{extendZodWithOpenApi as a_}from"zod-openapi";import{z as St}from"zod";import{z as ie}from"zod";var Qu=ie.object({autoFollowNewTabs:ie.boolean().optional().describe("Deprecated: Auto-follow new tabs that are opened."),showZeroOpacityElements:ie.union([ie.boolean(),ie.literal("inputs-only")]).optional(),ignoreHrefForCaching:ie.boolean().optional(),disableSecondaryCacheResolution:ie.boolean().optional(),hybridSelectorMode:ie.enum(["off","test","prefer"]).optional(),globalLocatorRedirect:ie.union([ie.boolean(),ie.literal("always")]).optional(),visualActions:ie.boolean().optional(),autoExpandIframes:ie.boolean().optional(),disableHtmlSnapshots:ie.boolean().optional(),importantAttributes:ie.string().array().optional(),importantClasses:ie.string().array().optional(),importantStyles:ie.string().array().optional()});var vf=1e4,Af=6e4,i_=ie.object({server:ie.string(),username:ie.string().optional(),password:ie.string().optional()}),Un=Qu.extend({pageLoadTimeoutMs:ie.number().optional().refine(r=>r===void 0||r<=Af&&r>=-1,{message:`Page load timeout must be between 0 and ${Af/1e3} seconds`}).describe("global page load timeout default for all tests in ms, can still be overridden by individual tests"),smartWaitingTimeoutMs:ie.number().optional().refine(r=>r===void 0||r<=vf&&r>=-1,{message:`Smart waiting timeout must be between 0 and ${vf/1e3} seconds`}),localChromeExtensionPaths:ie.string().array().optional(),extraHeaders:ie.record(ie.string(),ie.string()).optional().describe("HTTP headers to be sent on every request"),initialLocalStorage:ie.record(ie.string(),ie.record(ie.string(),ie.string())).optional().describe("Initial local storage key-value pairs to set per domain on browser startup"),userAgent:ie.string().optional(),disableGpu:ie.boolean().optional(),disableBrowserMonitoring:ie.boolean().optional().describe("Disable console logs and network request recording, which power the console and network tab in the run viewer"),bustCacheOnBoundingBoxChange:ie.boolean().optional().describe("This setting is deprecated. 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:ie.boolean().optional().describe("Allow fetching the partial accessibility tree if fetching the full tree takes too long."),ignoreHttpsErrors:ie.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."),proxy:i_.optional().describe("HTTP proxy server to use for the entire browser. This can dramatically increase network latency.")});var ed="BASE_URL";var Fn="ENV_NAME",Lo="TEST_NAME",Mq={[ed]:"https://www.google.com"},wf=St.string().describe("Name of the fixture (must be available locally in the fixtures directory)."),Rf=St.object({name:St.string(),variables:St.record(St.string().describe("variable name"),St.string().describe("variable value"))}),Cf=St.object({name:St.string(),variables:St.record(St.string().describe("variable name"),St.unknown().describe("variable value")),browser:Un.optional()});var _q=St.object({name:St.string(),variables:St.record(St.string().describe("variable name"),St.unknown().describe("variable value"))});a_(Bn);var td=Bn.object({env:Bn.record(Bn.unknown())}).openapi({ref:"TestContextSnapshot"});var He=(i=>(i.SUCCESS="SUCCESS",i.FAILED="FAILED",i.RUNNING="RUNNING",i.IDLE="IDLE",i.CANCELLED="CANCELLED",i))(He||{}),rd=(n=>(n.SUCCESS="SUCCESS",n.FAILED="FAILED",n.CANCELLED="CANCELLED",n))(rd||{});s_(G);var nd=G.object({beforeUrl:G.string().optional(),afterUrl:G.string().optional(),message:G.string().optional(),beforeSnapshot:G.string().optional(),afterSnapshot:G.string().optional(),startedAt:G.coerce.date(),finishedAt:G.coerce.date()}),l_=nd.extend({viewport:G.object({height:G.number(),width:G.number()}).nullish(),status:G.nativeEnum(rd),message:G.string().optional(),elementInteracted:G.string().optional()}),zn=nd.extend({status:G.nativeEnum(He),message:G.string().optional(),data:G.unknown().optional(),beforeTestContext:td.optional(),afterTestContext:td.optional(),failureReason:G.nativeEnum(Ae).optional(),details:G.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"}),xf=(t=>(t.NOT_ELIGIBLE="NOT_ELIGIBLE",t.ATTEMPTED="ATTEMPTED",t))(xf||{}),Is=zn.merge(qt).extend({results:l_.array().describe("Command that was executed. Array is just for consistency with other result types. There should only ever be one item."),previousAttempts:G.lazy(()=>lt.array()).optional(),failureRecoveryStatus:G.object({type:G.nativeEnum(xf),message:G.string()}).optional()}),c_=zn.merge(On).extend({results:G.lazy(()=>Is.array()),previousAttempts:G.lazy(()=>lt.array()).optional()}),u_=zn.merge(_o).extend({results:G.lazy(()=>Is.array()),previousAttempts:G.lazy(()=>lt.array()).optional()}),d_=zn.merge(Gr).extend({moduleName:G.string().optional(),results:G.lazy(()=>lt.array()),previousAttempts:G.lazy(()=>lt.array()).optional()}),p_=zn.merge(Po).extend({assertion:Is.optional(),results:G.lazy(()=>lt.array()).describe("results for the block actually executed"),previousAttempts:G.lazy(()=>lt.array()).optional()}),m_=zn.merge(Ki).extend({results:G.lazy(()=>lt.array()),healingAttempts:G.lazy(()=>lt.array().array()).optional(),previousAttempts:G.lazy(()=>lt.array()).optional()}),lt=G.discriminatedUnion("type",[c_,u_,Is,d_,p_,m_]),Jq=zn.pick({startedAt:!0,finishedAt:!0,status:!0,message:!0,data:!0}),g_=nd.extend({index:G.number().optional(),description:G.string(),pageState:G.string().optional(),elementInteracted:G.string().optional(),startedAt:G.coerce.date().or(G.string()).optional().catch(void 0),finishedAt:G.coerce.date().or(G.string()).optional().catch(void 0)}),Os=g_.extend({beforeScreenshot:G.string().optional(),afterScreenshot:G.string().optional()});var od=h_.object({results:lt.array().describe("main results"),beforeResults:lt.array().optional(),afterResults:lt.array().optional()}),Zi=od.partial();import{z as B}from"zod";import{extendZodWithOpenApi as v_}from"zod-openapi";var No=(t=>(t.WEB="WEB",t.ANDROID="ANDROID",t))(No||{});import{isValidCron as f_}from"cron-validator";import{z as ne}from"zod";import{z as id}from"zod";var on=(n=>(n.CHROMIUM="Chromium",n.GOOGLE_CHROME="Google Chrome",n.CHROME_FOR_TESTING="Chrome for Testing",n))(on||{});var Ls=id.object({width:id.number().min(200).max(1e4),height:id.number().min(200).max(1e4)}),Mf={"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}},o2=Object.keys(Mf);var an=Mf["Desktop Large"],_f="en-us",Pf="America/Los_Angeles";var If={latitude:37.7749,longitude:-122.4194};var Of=["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 Lf=1e4,S_=Un.extend({browserType:ne.nativeEnum(on).optional(),slowMoMs:ne.number().optional().refine(r=>r===void 0||r<=Lf&&r>=-1,{message:`Slow motion must be between 0 and ${Lf} milliseconds`}),basicAuthorization:ne.object({username:ne.string().optional(),password:ne.string().optional()}).optional(),geolocation:ne.object({latitude:ne.coerce.number().refine(r=>r>=-90&&r<=90,{message:"Latitude must be between -90 and 90 degrees"}),longitude:ne.coerce.number().refine(r=>r>=-180&&r<=180,{message:"Longitude must be between -180 and 180 degrees"})}).optional(),disableJavaScript:ne.boolean().optional(),locale:ne.string().optional(),timezone:ne.enum(Of).optional(),colorScheme:ne.enum(["light","dark"]).optional()});var ad=ne.object({useMemory:ne.boolean().optional(),failureRecovery:ne.boolean().optional().describe("undefined means inherit org settings")}),y_=ad.extend({disableAICaching:ne.boolean().optional(),failureRecoveryInstructions:ne.string().optional()}),b_=ne.object({viewport:Ls.optional()}),Qi=b_.merge(y_).merge(S_),Do=ne.object({cron:ne.string().refine(r=>f_(r),{message:"Invalid cron expression."}).default("0 0 */1 * *"),enabled:ne.boolean().default(!1),env:ne.string().optional(),timeZone:ne.string().default("America/Los_Angeles"),jobKey:ne.string().optional()}),ko=ne.object({onSuccess:ne.boolean().default(!1),failureMessage:ne.string().optional(),onFailure:ne.boolean().default(!0),successMessage:ne.string().optional()}),E_=ne.object({name:ne.string(),required:ne.boolean().optional(),defaultValue:ne.string().describe("this is not optional because we need a value when the editor is first loaded")}),Ns=E_.array(),T_=ne.object({name:ne.string(),value:ne.string()}),Nf=T_.array(),Ds=ne.object({name:ne.string(),default:ne.boolean().optional(),fixtures:wf.array().optional()});v_(B);var Jt={WEBHOOK:"WEBHOOK",CRON:"CRON",MANUAL:"MANUAL",CLI:"CLI"},Te=(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))(Te||{}),ks=(t=>(t.BEFORE_ALL="BEFORE_ALL",t.AFTER_ALL="AFTER_ALL",t))(ks||{});var Je=B.string().pipe(B.coerce.date()).or(B.date()),ea=B.object({id:B.string(),runKey:B.string(),organizationId:B.string(),executionType:B.nativeEnum(No).optional().default("WEB"),createdAt:Je,createdBy:B.string(),flake:B.boolean().nullish(),scheduledAt:Je.or(B.null()),startedAt:Je.or(B.null()),updatedAt:Je.nullish(),finishedAt:Je.or(B.null()),resolvedBaseUrl:B.string().nullish(),environmentName:B.string().nullish(),gitBranchName:B.string().nullish(),githubRepository:B.string().nullish(),gitlabProjectPath:B.string().nullish(),labels:B.array(B.string()).optional(),gitOriginUrl:B.string().nullish(),gitCommitSha:B.string().nullish(),gitCommitShaShort:B.string().nullish(),gitCommitAuthorName:B.string().nullish(),cliVersion:B.string().nullish(),section:B.nativeEnum(ks).nullish(),status:B.nativeEnum(Te),trigger:B.nativeEnum(Jt),attempts:B.number(),runAttempts:B.array(B.object({id:B.string(),status:B.nativeEnum(Te),startedAt:Je.or(B.null()),finishedAt:Je.or(B.null())})).optional(),videos:B.array(B.string()).optional(),failureReason:B.nativeEnum(Ae).nullish(),failureDetails:Rs.nullish(),failureRecoveryDetails:B.record(B.string(),B.unknown()).nullish(),pipelineId:B.string().nullish(),resolvedInputs:B.record(B.string(),B.string()).nullish(),quarantined:B.boolean().nullish().default(!1),quarantinedReason:B.string().nullish(),localTestId:B.string().nullish(),testId:B.string().nullish(),testName:B.string().nullish(),description:B.string().nullish(),test:B.object({name:B.string(),id:B.string()}).nullish().default(null),suiteId:B.string().nullish()}).openapi({ref:"RunMetadata"}),A_={id:!0,status:!0,testName:!0,localTestId:!0,testId:!0,test:{select:{name:!0,id:!0}},finishedAt:!0,failureReason:!0,failureDetails:!0},Us=ea.pick({...A_,test:!0}),Df=ea.omit({failureReason:!0,failureDetails:!0,test:!0}),sd=ea.extend({stepsSnapshot:B.array(B.record(B.unknown())).nullish(),resolvedInputs:B.record(B.string(),B.string()).nullish(),test:B.object({name:B.string(),id:B.string(),description:B.string().nullish(),baseUrl:B.string().nullish(),advanced:Qi.nullish()}).nullish()}).merge(od);var w_=ta.object({id:ta.string().uuid(),startedAt:Je.or(ta.null()),finishedAt:Je.or(ta.null()),status:ta.nativeEnum(Te)}).merge(Zi),C2=w_.array();import{z as Ze}from"zod";var R_=Ze.object({id:Ze.string(),status:Ze.nativeEnum(Te),trigger:Ze.nativeEnum(Jt),createdAt:Je,startedAt:Je.nullish(),finishedAt:Je.nullish(),gitCommitSha:Ze.string().nullish(),gitCommitShaShort:Ze.string().nullish(),gitCommitTimestamp:Je.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(Te)}).array()}).openapi({ref:"RunGroup"}),kf=R_.pick({id:!0,createdAt:!0,startedAt:!0,finishedAt:!0,status:!0,trigger:!0,suite:!0}).extend({runs:Us.array()});import{z as ct}from"zod";var C_=ct.object({type:ct.literal("TARGETING"),name:ct.string().optional().describe("Target name to disambiguate for steps with multiple targets"),elementLocationDecisions:Tf.array(),pageState:ct.string().optional(),targetSource:ct.nativeEnum(Jr).optional(),targetUpdateTime:ct.string().optional()}),x_=ct.object({type:ct.literal("AI_LOCATION"),matched:ct.boolean(),pageState:ct.string().optional(),ragUsed:ct.boolean().optional(),thoughts:ct.string().optional()}),M_=ct.object({type:ct.literal("ASSERTION"),relevantElementsSerialized:ct.string().array().optional(),pageState:ct.string().optional(),ragUsed:ct.boolean().optional()}),__=ct.discriminatedUnion("type",[C_,x_,M_]);import{z as qe}from"zod";var P_=qe.object({id:qe.string(),name:qe.string()}),z2=P_.merge(qe.object({createdAt:Je,createdBy:qe.string(),schedule:Do,notification:ko,environment:qe.object({name:qe.string()}).nullish(),beforeTests:qe.object({id:qe.string()}).array().nullish(),afterTests:qe.object({id:qe.string()}).array().nullish()})),Uf=qe.object({id:qe.string().uuid(),orgId:qe.string(),createdAt:Je,startedAt:Je.or(qe.null()),finishedAt:Je.or(qe.null()),status:qe.nativeEnum(Te),trigger:qe.nativeEnum(Jt),suite:qe.object({id:qe.string(),name:qe.string()}).nullish(),runs:ea.array()}),H2=Uf.pick({id:!0,createdAt:!0,startedAt:!0,finishedAt:!0,status:!0,trigger:!0,suite:!0}),Ff=Uf.extend({runs:Us.array()});import{z as Zt}from"zod";import{cloneDeep as j2}from"lodash-es";import{z as Se}from"zod";var X2=Se.object({thoughts:Se.string(),subGoals:Se.object({instruction:Se.string()}).array()}),J2=Se.object({thoughts:Se.string(),newPlanMarkdown:Se.string()}),Z2=Se.object({thoughts:Se.string(),correct:Se.boolean(),failedActionIndex:Se.number().optional()}),I_=Se.object({type:Se.literal("PLANNING"),beforePlan:Se.string(),goalDecision:Se.string(),thoughts:Se.string()}),O_=Se.object({type:Se.literal("RUNNING"),stepDisplayName:Se.string(),status:Se.nativeEnum(He),results:lt.array()}),L_=Se.object({type:Se.literal("REVISING"),beforePlan:Se.string(),afterPlan:Se.string(),errString:Se.string(),diffs:Se.string(),thoughts:Se.string()}),N_=Se.object({type:Se.literal("SYSTEM"),message:Se.string()}),D_=Se.discriminatedUnion("type",[I_,O_,L_,N_]),Bf=D_.array();var nK=Zt.object({id:Zt.string(),scheduledAt:Zt.coerce.date().nullable(),startedAt:Zt.coerce.date().nullable(),finishedAt:Zt.coerce.date().nullable(),status:Zt.nativeEnum(Te),history:Bf.nullable(),testPlan:Zt.object({id:Zt.string(),name:Zt.string()}).nullable(),test:Zt.object({id:Zt.string(),name:Zt.string()}).nullable()});import{z as It}from"zod";var ld=It.object({content:It.string(),ids:It.string().array(),tokenLength:It.number()}),k_=It.object({chunks:ld.array()}),EK=It.object({ids:It.string().array(),score:It.number(),tokenLength:It.number()}),TK=k_.extend({description:It.string().describe("Input to pass to RAG engine"),tokenLimit:It.number()}),zf=It.object({ids:It.number().array()}),Hf=It.object({indices:It.number().array()});var yt=P.object({disableCache:P.boolean().optional(),useMemory:P.boolean().optional(),clientMode:P.enum(["interactive","runner"]).optional(),loggerTags:P.record(P.string(),P.string()).optional(),langfuseSessionId:P.string().optional(),agentConfigVersion:P.string().optional()}),_K=yt.extend({chunks:ld.array(),description:P.string().describe("Input to pass to AI"),type:P.union([P.literal("locator"),P.literal("assertion"),P.literal("ai-action")]),softTokenLimit:P.number(),hardTokenLimit:P.number(),callId:P.string().optional()}),U_=P.object({screenshotBase64AfterCommand:P.string(),urlAfterCommand:P.string(),serializedCommand:P.string(),elementInteracted:P.string().optional(),thoughts:P.string().optional()}),Gf=P.object({goal:P.string(),browserState:P.string(),screenshot:P.string(),source:Ef.optional().catch(void 0),memory:P.discriminatedUnion("type",[ms,P.object({type:P.literal("RESOLVED_TRACES"),traces:P.unknown().array()})]).optional()}),Vf=P.object({target:P.string().or(P.number()),browserState:P.string().optional(),screenshot:P.string().optional(),boundingBox:P.object({x:P.number(),y:P.number(),height:P.number(),width:P.number()}).optional()}),jf=P.object({goal:P.string(),browserState:P.string(),screenshot:P.string().optional(),returnSchema:P.string().optional()}),F_=P.literal("NEGATED_CHECK"),Wf=P.object({goal:P.string(),browserState:P.string(),screenshot:P.string(),url:P.string(),contextChoice:xu.optional(),memory:P.discriminatedUnion("type",[vu,P.object({type:P.literal("RESOLVED_TRACES"),traces:P.unknown().array()})]).optional(),source:F_.optional()}),$f=P.object({command:Co}),qf=P.object({message:P.string()}),cd=P.object({goal:P.string(),browserState:P.string(),startingScreenshot:P.string().optional(),screenshot:P.string(),url:P.string(),history:U_.array(),actionHint:P.string().optional(),lastError:P.string().optional()}),Kf=P.object({results:Os.array(),errorMessage:P.string(),errorStack:P.string().optional()}),Yf=P.object({results:Os.array(),goal:P.string(),errorMessage:P.string()}),Xf=P.object({failedResults:Os.array(),nextStepsSerialized:P.string().array(),currentUrl:P.string(),currentPageState:P.string(),currentScreenshot:P.string(),customInstructions:P.string().optional(),testDescription:P.string().optional()}),PK=P.object({description:P.string(),type:P.union([P.literal("locator"),P.literal("assertion"),P.literal("ai-action")]),excerpt:P.string()}),Jf=P.object({type:P.string(),browserContext:P.string(),currentStep:P.string(),screenshot:P.string()});import{z as ra}from"zod";var LK=ra.object({goal:ra.string()}),Zf=ra.object({keywords:ra.array(ra.string())});import{z as ud}from"zod";var Fs=(o=>(o.LOCATOR="locator",o.ASSERTION="assertion",o.VISUAL_ASSERTION="visual-assertion",o.TEXT_EXTRACTION="text-extraction",o))(Fs||{}),kK=ud.nativeEnum(Fs),B_=ud.enum(["v1","v2"]),UK=B_.or(ud.string().describe("for people with special configurations"));var Qf={locator:"v3",assertion:"v3","visual-assertion":"v3","text-extraction":"v2"};import{z as De}from"zod";var eS=De.object({attributesRequired:De.array(De.string()).optional(),textRequired:De.boolean().optional(),boundsRequired:De.boolean().optional()}),tS=De.object({id:De.number(),thoughts:De.string(),inWebview:De.boolean().optional(),requirements:eS.optional(),additionalElements:De.object({id:De.number(),requirements:eS}).array().optional()}),rS=De.object({description:De.string(),screenXml:De.string(),screenshot:De.string()}),nS=De.object({assertion:De.string(),screenXml:De.string(),screenshot:De.string()}),oS=De.object({thoughts:De.string(),result:De.boolean(),relevantElements:De.array(De.number()).optional()});import{z as Hn}from"zod";var iS=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")}),dd=iS.merge(yo).extend({type:Hn.literal("REQUEST")}),pd=iS.merge(hs).extend({type:Hn.literal("JAVASCRIPT")}),md=Hn.discriminatedUnion("type",[pd,dd]);import{z as Qt}from"zod";var aS=Qt.object({id:Qt.string(),name:Io,description:Qt.string().optional().nullish(),baseUrl:Ps.nullish(),schemaVersion:Qt.string(),advanced:Qt.unknown().optional(),retries:Qt.number(),envs:Qt.array(Ds).nullish(),parameters:Ns.nullish()}),z_=Qt.object({createdAt:Qt.coerce.date(),updatedAt:Qt.coerce.date(),schedule:Do.nullish(),notification:ko.nullish(),createdBy:Qt.string(),organizationId:Qt.string()}),H_=aS.merge(z_),sY=H_.extend({steps:md.array()}),lY=aS.extend({steps:md.array()});import{z as kt}from"zod";var sS=kt.object({startedAt:kt.coerce.date(),finishedAt:kt.coerce.date(),status:kt.nativeEnum(He),message:kt.string().optional(),data:kt.unknown().optional()}),G_=sS.merge(pd).extend({type:kt.literal("JAVASCRIPT")}),V_=sS.merge(dd).extend({type:kt.literal("REQUEST")}),j_=kt.discriminatedUnion("type",[G_,V_]),lS=kt.object({startedAt:kt.coerce.date(),finishedAt:kt.coerce.date().nullish(),status:kt.nativeEnum(Te),results:j_.array(),failureReason:kt.string().nullish(),failureDetails:Rs.nullish()});import{z as Ut}from"zod";var W_=Ut.object({id:Ut.string(),organizationId:Ut.string(),createdAt:Ut.coerce.date(),updatedAt:Ut.coerce.date(),createdBy:Ut.string(),scheduledAt:Ut.coerce.date().nullish(),startedAt:Ut.coerce.date().nullish(),finishedAt:Ut.coerce.date().nullish(),status:Ut.nativeEnum(Te),trigger:Ut.nativeEnum(Jt),results:lS.array().nullish(),apiTestName:Ut.string().nullish(),apiTestPath:Ut.string().nullish(),apiTestId:Ut.string().nullish()}),yY=W_.pick({status:!0,startedAt:!0,finishedAt:!0});var na=(o=>(o.TestRun="test-run",o.MobileTestRun="mobile-test-run",o.CreditsUsed="credits-used",o.CreditsUsedV2="credits-used-v2",o))(na||{}),cS=3;function $_(r){return r==="MODULE"||r==="CONDITIONAL"||r==="SECTION"||r==="RESOLVED_MODULE"}function gd(r){if(!$_(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 hd(r){switch(r.type){case"AI_EXTRACT":case"AI_ASSERTION":return cS;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 Bs=class{trackStepExecution(){}async flush(){}};import{parseString as q_,splitCookiesString as K_}from"set-cookie-parser";import{z as Ee}from"zod";var fd=Ee.object({name:Ee.string(),value:Ee.string(),url:Ee.string().optional(),domain:Ee.string().optional(),path:Ee.string().optional(),expires:Ee.number().default(Date.now()/1e3+60*60*24*365),httpOnly:Ee.boolean().optional(),secure:Ee.boolean().default(!0),sameSite:Ee.union([Ee.literal("Strict"),Ee.literal("Lax"),Ee.literal("None")]).default("None")});function zs(r,e){let t=[],n=K_(r);for(let o of n){let i=q_(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=fd.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 Y_=Ee.object({origin:Ee.string(),localStorage:Ee.array(Ee.object({name:Ee.string(),value:Ee.string()}))}),X_=Ee.object({entries:Ee.record(Ee.string(),Ee.array(Ee.tuple([Ee.unknown(),Ee.unknown()]))),version:Ee.number().optional()}),uS=Ee.object({cookies:fd.array().optional(),origins:Y_.array().optional(),idb:Ee.record(Ee.string(),X_).optional().describe("key is db name")});function Hs(r,e){let t=[];return r.cloneSync()?.serializeSync()?.cookies.forEach(n=>{let o=fd.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{v4 as Vs}from"uuid";import ke from"zod";import{v4 as HY}from"uuid";import{z as U}from"zod";import*as Me from"zod";var dS=Me.object({requiredText:Me.string().optional(),requiredAttributes:Me.record(Me.string(),Me.string()).optional(),requiredBounds:Me.boolean().optional()}),J_=Me.object({xPath:Me.string(),requirements:dS.optional()}),Z_=Me.object({type:Me.literal("NATIVE"),bounds:Me.number().array(),resolvedDescription:Me.string(),xPath:Me.string(),elementOnlySerializedXml:Me.string(),requirements:dS.optional(),requiredRelatedElements:J_.array().optional()}),Q_=Me.object({type:Me.literal("WEBVIEW"),resolvedDescription:Me.string(),xPath:Me.string(),browserCache:Zr.optional()}),Gs=Me.discriminatedUnion("type",[Z_,Q_]);var sn=(f=>(f.AI_CHECK="AI_CHECK",f.TAP="TAP",f.TYPE="TYPE",f.PRESS="PRESS",f.PRESS_KEYBOARD="PRESS_KEYBOARD",f.OPEN_APP="OPEN_APP",f.KILL_APP="KILL_APP",f.OPEN_NOTIFICATION_DRAWER="OPEN_NOTIFICATION_DRAWER",f.SWIPE="SWIPE",f.JAVASCRIPT="JAVASCRIPT",f.REQUEST="REQUEST",f.WAIT="WAIT",f.ADD_FILE="ADD_FILE",f.INSTALL_APP="INSTALL_APP",f.ADB="ADB",f.STATE="STATE",f))(sn||{}),oa=(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))(oa||{}),Sd=(n=>(n.CLOSE_KEYBOARD="CLOSE_KEYBOARD",n.ENTER="ENTER",n.BACKSPACE="BACKSPACE",n))(Sd||{}),pS=U.object({type:U.literal("description"),description:U.string()}),eP=U.object({type:U.literal("coordinates"),xPercent:U.number(),yPercent:U.number()}),mS=U.discriminatedUnion("type",[pS,eP]),tP=U.object({updatedAt:U.coerce.date().optional()}),bt=U.object({id:U.string().uuid(),disableCache:U.boolean().optional()}),rP=bt.extend({type:U.literal("STATE")}),nP=bt.extend({type:U.literal("KILL_APP")}),yd=tP.extend({target:Gs}),oP=bt.extend({type:U.literal("AI_CHECK"),assertion:U.string(),timeoutSecs:U.number().optional()}),bd=bt.extend({type:U.literal("TAP"),target:mS,cache:yd.optional(),longPress:U.boolean().optional(),longPressDurationMs:U.number().optional(),doubleTap:U.boolean().optional(),doubleTapDelayMs:U.number().optional(),relativePosition:U.object({x:U.number(),y:U.number()}).optional()}),Ed=bt.extend({type:U.literal("TYPE"),target:mS.optional(),cache:yd.optional(),keyPressDelayMs:U.number().optional(),text:U.string(),clearContent:U.boolean().optional()}),iP=bt.extend({type:U.literal("PRESS"),key:U.nativeEnum(oa),longPress:U.boolean().optional()}),aP=bt.extend({type:U.literal("PRESS_KEYBOARD"),key:U.nativeEnum(Sd)}),sP=bt.extend({type:U.literal("OPEN_APP"),packageName:U.string(),activityName:U.string().optional(),intentExtras:U.string().optional()}),lP=bt.extend({type:U.literal("OPEN_NOTIFICATION_DRAWER")});var cP=U.discriminatedUnion("type",[U.object({type:U.literal("SCREEN")}),U.object({type:U.literal("OPEN_APP")}),U.object({type:U.literal("OPEN_WEBVIEW")}),U.object({type:U.literal("CUSTOM"),target:pS})]);var Td=bt.extend({type:U.literal("SWIPE"),direction:U.enum(["up","down","left","right"]),scrollableElement:cP,cache:yd.optional(),viewportPercent:U.number().optional(),durationMs:U.number().optional()}),uP=bt.extend({type:U.literal("JAVASCRIPT"),code:U.string(),timeout:U.number().int().max(60).optional().describe("Max seconds for the code to complete")}),dP=bt.extend({type:U.literal("REQUEST")}).merge(yo),pP=bt.extend({type:U.literal("WAIT"),timeoutSecs:U.number()}),mP=bt.extend({type:U.literal("ADB"),command:U.string(),jsonArgs:U.string().optional()}),gP=bt.extend({type:U.literal("ADD_FILE"),file:U.string(),storageLocation:U.string()}),hP=U.string().trim(),fP=bt.extend({type:U.literal("INSTALL_APP"),uri:hP}),gS=U.discriminatedUnion("type",[oP,bd,Ed,iP,sP,lP,aP,Td,uP,dP,pP,gP,fP,nP,mP,rP]);var vd=r=>{switch(r.type){case"description":return r.description;case"coordinates":return`${r.xPercent}%, ${r.yPercent}%`}};var SP=ke.object({type:ke.literal("TAP"),description:ke.string().describe("Description of the element to tap."),longPress:ke.boolean().describe("Whether to hold the tap down before releasing. Useful for triggering context menus."),doubleTap:ke.boolean().describe("Whether to tap twice in quick succession."),relativePosition:ke.null().or(ke.object({x:ke.number(),y:ke.number()})).describe("Specific position to tap within the bounding box of the element, specified in pixels. E.g. 0,0 is the top left corner.")}).describe(`
9
+ `)}`}};function rf(r){return r instanceof Error?r.message.includes("Timeout")&&r.message.includes("exceeded")&&r.message.includes("waiting for locator"):!1}function Hu(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 wr=class extends Error{retryableWithAI;constructor(e,t,n={}){super(e,n),this.name="CacheAttributesDisqualifyElementError",this.retryableWithAI=t}},Ms=class extends wr{constructor(e,t={}){super(e,!0,t),this.name="BoundingBoxMovedError"}},_s=class extends wr{constructor(e,t={}){super(e,!1,t),this.name="ZeroOpacityError"}};function Gu(r){return r instanceof Error?r.message.includes("Could not find attribute data-momentic-id for object"):!1}function Vu(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 ju(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 qi=class extends Error{constructor(e,t={}){super(e,t),this.name="InsufficientCacheDataError"}};var oM={CLICK:"Click on an element on the page.",TYPE:"Focus the element then type the specified text into an input on the page.",PRESS:"Press one or more keyboard keys.",KEY_DOWN:"Hold down one or more keyboard keys.",KEY_UP:"Release one or more keyboard keys.",SELECT_OPTION:"Choose an option from a native <select> component. Never use this command for non <select> elements. Instead, use a series of CLICK commands for those.",NAVIGATE:"Go to the specified fully qualified URL.",SCROLL_UP:"Scroll up.",SCROLL_DOWN:"Scroll down.",GO_BACK:"Go back to the previous page.",HOVER:"Hover over an element.",AI_ASSERTION:"Verify a statement about the current page, retrying until it is true. Only generate an assertion if the goal includes language like 'check that', 'verify that', etc..",WAIT:"Wait a fixed amount of seconds."},iM={...oM,JAVASCRIPT:"Execute JavaScript code in NODE or BROWSER environment.",ELEMENT_CHECK:"Perform a manual assertion on a specific element.",PAGE_CHECK:"Perform a manual case sensitive assertion on the page's html.",NEW_TAB:"Open a new browser tab with the specified URL.",WAIT_FOR_URL:"Wait for the URL to match a pattern.",AI_EXTRACT:"Extract data from the page and optionally store it in an environment variable.",DRAG:"Drag an element from one location and drop it onto another element.",COPY:"Copy the specified text value to the browser clipboard.",GO_FORWARD:"Navigate forward to the next page in the browser history (if available). Only use this after having navigated back with GO_BACK. Do not use this to navigate to a different page - use NAVIGATE instead.",LOCAL_STORAGE:"Set or get a value in the browser's localStorage. Use this to store data that persists across page reloads or to read stored values.",MOUSE_DRAG:"Drag the mouse from a starting point (or element) in a specific direction by pixel amounts. Prefer using DRAG (drag and drop between elements) instead unless the user explicitly requests dragging in a direction or by pixels. Use this when dragging needs to move a specific distance rather than to a target element.",PASTE:"Paste the contents of the browser clipboard into the currently focused element. Use this after copying text with COPY or when pasting content that was previously copied.",REFRESH:"Reload the current page. Use this to refresh the page content or retry a failed operation.",REQUEST:"Make an HTTP API request to a specified URL. Use this to interact with REST APIs, send data to a server, or retrieve data from an endpoint. Supports GET, POST, PUT, DELETE, and PATCH methods with custom headers, query parameters, and request body."};Lu.options.forEach(r=>{let e=r.shape.type.value;if(e!=="SUCCESS"&&!iM[e])throw new Error(`Command type ${e} is missing a description`)});var aM=T.object({type:T.literal("CLICK"),description:T.string().describe("Description of the element to click in the Current Page. Never click on <select> elements, see SELECT_OPTION."),doubleClick:T.boolean().or(T.null()),rightClick:T.boolean().or(T.null())}),sM=T.object({type:T.literal("TYPE"),description:T.string().describe("Description of the element to type into, which must be an <input>, <textarea>, or contenteditable element."),text:T.string().describe("The text to enter, truncated to 500 characters. If the PM provided text in the goals, use it exactly without modification."),pressEnter:T.boolean().or(T.null()).describe("Press enter after typing (useful for form submissions)."),clearContent:T.boolean().describe("Clear existing content before typing. Disable to append to the existing text.")}),lM=T.object({type:T.literal("GO_BACK")}),cM=T.object({type:T.literal("GO_FORWARD")}),uM=T.object({type:T.literal("LOCAL_STORAGE"),key:T.string().describe("The localStorage key to set or get."),value:T.string().describe("The value to store in localStorage. If reading, this can be empty.")}),dM=T.object({type:T.literal("PRESS"),keys:T.array(T.string()).describe('The keys to press. Only use key names supported by the Playwright press method, such as "a", "ArrowLeft", "Meta", "Control", and "Enter". Multiple keys will be pressed together. Do not suggest platform-specific key combinations, such as CTRL+C.')}),pM=T.object({type:T.literal("SELECT_OPTION"),description:T.string().describe("Description of the <select> element to choose from. Only use this command to interact with native HTML <select> elements. You must use CLICK to select from any other HTML element, such as <input>, <div>, or custom elements."),option:T.discriminatedUnion("type",[T.object({type:T.literal("VALUE"),value:T.string()}),T.object({type:T.literal("LABEL"),label:T.string()}),T.object({type:T.literal("INDEX"),index:T.string().describe("Zero-based index of the option within the select.")})]).describe("Which option to select. Choose 1 of 3 strategies for selecting. By value is exactly matching the 'value' attribute. By label is exactly matching the 'label' attribute. By index is using the zero-based index of the option within the select.")}),mM=T.object({type:T.literal("NAVIGATE"),url:T.string().describe("The URL to navigate to. Only navigate to URLs relevant to the user goal.")}),gM=T.object({type:T.literal("SCROLL"),y:T.number().describe("Scroll up or down by the specified pixels. Positive values scroll down.")}),hM=T.object({type:T.literal("WAIT"),timeout:T.number().describe("The number of seconds to wait.")}),fM=T.object({type:T.literal("AI_ASSERTION"),assertion:T.string().describe("The assertion to verify. This should be a statement verifiable based on the current page HTML or screenshot. Be specific enough that the assertion is not ambiguous or open to interpretation. Make sure the assertion aligns with what the user intends to verify."),timeout:T.number().describe("The max amount of seconds to wait for the assertion to be true. Respect user wishes but allow no more than 60. If unspecified, choose 5 for quick checks like form status, 10 for page loads, and 30 for actions that explicitly trigger a long time, like image generation.")}),SM=T.object({type:T.literal("HOVER"),description:T.string().describe("Description of the element to hover over. Prefer elements that have visible bounding boxes according to the screenshot, element class attribute, or child contents.")}),yM=T.object({type:T.literal("COPY"),value:T.string().describe("The text value to copy to the browser clipboard. This should be the exact text that needs to be copied.")}),bM=T.object({type:T.literal("PASTE")}),EM=T.object({type:T.literal("REFRESH")}),TM=T.object({type:T.literal("REQUEST"),url:T.string().describe("The URL to send the HTTP request to. Can be a full URL or relative path."),method:T.enum(["GET","POST","PUT","DELETE","PATCH"]).describe("The HTTP method to use. GET for retrieving data, POST for creating resources, PUT for updating resources, DELETE for removing resources, PATCH for partial updates."),headers:T.record(T.string(),T.string()).or(T.null()).describe("Optional HTTP headers as key-value pairs. Common headers include 'Content-Type', 'Authorization', 'Accept', etc."),params:T.record(T.string(),T.string()).or(T.null()).describe("Optional URL query parameters as key-value pairs. These will be appended to the URL as ?key1=value1&key2=value2."),body:T.string().or(T.null()).describe("Optional request body as a string. For JSON data, stringify the object. Typically used with POST, PUT, or PATCH requests."),timeout:T.number().int().or(T.null()).describe("Optional maximum number of seconds to wait for the request to complete. Defaults to 30 seconds if not specified.")}),vM=T.object({type:T.literal("DRAG"),fromDescription:T.string().describe("Description of the element to drag. Prefer precise identifiers or text that clearly distinguishes the element."),toDescription:T.string().describe("Description of the element to drop onto. Ensure the drop target is interactable and visible."),steps:T.number().int().positive().or(T.null()).describe("Optional number of intermediate mouse move steps during the drag. Do not use this unless the user tells you to."),hoverSeconds:T.number().positive().or(T.null()).describe("Optional seconds to hover over the destination before releasing the drag.")}),AM=T.object({type:T.literal("MOUSE_DRAG"),description:T.string().or(T.null()).describe("Optional description of the element to start the drag from. If not provided, starts from current mouse position."),deltaX:T.number().describe("Number of pixels to move horizontally (positive = right, negative = left)."),deltaY:T.number().describe("Number of pixels to move vertically (positive = down, negative = up)."),steps:T.number().int().positive().or(T.null()).describe("Optional number of intermediate mouse move steps during the drag.")}),wM=T.object({type:T.literal("JAVASCRIPT"),code:T.string().describe("JavaScript code to execute. Defaults to NODE environment unless BROWSER is specified."),environment:T.union([T.literal("NODE"),T.literal("BROWSER")]).or(T.null()).describe("Execution environment. Default is NODE."),timeout:T.number().or(T.null()).describe("Max seconds for the code to complete. Max 60 seconds.")}),RM=T.object({type:T.literal("AI_EXTRACT"),goal:T.string().describe("Description of what data to extract from the page. Be specific about what you want to extract and where to find it."),schema:T.string().or(T.null()).describe("JSON schema defining the expected structure of the extracted data."),envKey:T.string().or(T.null()).describe("Environment variable name to store the extracted result in. If provided, the result will be stored and can be referenced later."),iframeUrl:T.string().or(T.null()).describe("URL or URL regex for the iframe to extract data from.")}),CM=T.object({type:T.literal("ELEMENT_CHECK"),description:T.string().describe("Description of the element to check."),assertionType:T.enum(["EXISTS","VISIBLE","CONTENT_CONTAINS","CONTENT_EQUALS"]).describe("The type of assertion. EXISTS checks if element exists, VISIBLE checks if visible, CONTENT_CONTAINS checks if text contains value, CONTENT_EQUALS checks if text equals value."),value:T.string().or(T.null()).describe("The value to check against (required for CONTENT assertions)."),negated:T.boolean().or(T.null()).describe("If true, asserts the opposite (e.g., does NOT exist)."),timeout:T.number().or(T.null()).describe("Max seconds to wait for the assertion to be true.")}),xM=T.object({type:T.literal("PAGE_CHECK"),value:T.string().describe("The text content to check for on the page."),negated:T.boolean().or(T.null()).describe("If true, checks that the content is NOT present."),timeout:T.number().or(T.null()).describe("Max seconds to wait for the assertion to be true.")}),MM=T.object({type:T.literal("NEW_TAB"),url:T.string().describe("The URL to open in the new tab.")}),_M=T.object({type:T.literal("WAIT_FOR_URL"),matcher:T.discriminatedUnion("type",[T.object({type:T.literal("SUBSTRING"),url:T.string()}),T.object({type:T.literal("GLOB"),glob:T.string()}),T.object({type:T.literal("REGEX"),regex:T.string()}),T.object({type:T.literal("DOMAIN"),domain:T.string()})]).describe("How to match the URL."),caseInsensitive:T.boolean().or(T.null()),negated:T.boolean().or(T.null()).describe("Wait for the URL to NOT match instead."),timeout:T.number().or(T.null()).describe("Max seconds to wait for the URL.")}),nf=T.object({type:T.literal("SUCCESS")}),Wu=T.object({type:T.literal("FAILURE")}),Ki=T.discriminatedUnion("type",[aM,sM,dM,pM,mM,gM,hM,fM,SM,lM]),yW=In(Ki),Ps=T.discriminatedUnion("type",[...Ki.options,vM,wM,CM,xM,MM,_M,RM,yM,cM,uM,AM,bM,EM,TM]),bW=In(Ps),PM=T.discriminatedUnion("type",[...Ki.options,Wu]).describe("The command that will be executed next. This should naturally follow from your reasoning and be consistent with the goal."),EW=In(PM),IM=T.discriminatedUnion("type",[...Ki.options,nf,Wu]),TW=In(IM),vW=T.discriminatedUnion("type",[...Ps.options,nf,Wu]),OM=T.object({command:Ki,thoughts:T.string()}),AW=In(OM),wW=T.object({command:T.unknown(),thoughts:T.string()});import{z as $u}from"zod";import{extendZodWithOpenApi as DM}from"zod-openapi";import{z as of}from"zod";import{extendZodWithOpenApi as LM}from"zod-openapi";import{z as On}from"zod";var $t=On.object({index:On.number().optional().describe("global index within a test (in-order traversal)"),id:On.string(),skipped:On.boolean().optional(),envKey:On.string().optional().describe("key in the environment to save the result of this step to"),aiSuggested:On.boolean().optional(),retries:On.number().optional()});LM(of);var NM=$t.extend({type:of.literal("PRESET_ACTION")}),qt=NM.extend({command:xo}).openapi({ref:"PresetAction"});DM($u);var Ln=$t.extend({type:$u.literal("AI_ACTION"),text:$u.string(),steps:qt.array().optional()}).openapi({ref:"AIAction"});import{z as _t}from"zod";import{z as Is}from"zod";import{extendZodWithOpenApi as kM}from"zod-openapi";kM(Is);var Po=$t.extend({type:Is.literal("AI_ACTION_DYNAMIC"),text:Is.string(),retries:Is.number().optional()}).openapi({ref:"AIActionDynamic"});import{z as af}from"zod";var qu=$t.extend({type:af.literal("CONDITIONAL"),skipped:af.boolean().optional()});import{z as ue}from"zod";var UM=ue.object({cacheKey:ue.string(),cacheExpiryMs:ue.number()}),Ku=$t.extend({id:ue.string().uuid().describe("ID of the module step itself. Used to 'namespace' step cache entries."),inputs:ue.record(ue.string()).optional(),cacheConfig:UM.optional()}),jr=Ku.extend({type:ue.literal("MODULE"),moduleId:ue.string().uuid()}),FM=ue.union([jr.pick({type:!0,moduleId:!0}),ue.record(ue.unknown())]),BM=ue.object({type:ue.literal("URL_REGEX"),regex:ue.string()}),zM=ue.object({type:ue.literal("PAGE_CHECK"),substring:ue.string()}),Yu=ue.object({cacheInvalidation:ue.discriminatedUnion("type",[zM,BM]).optional()}),Kt=ue.object({moduleId:ue.string().uuid(),name:ue.string(),description:ue.string().nullish(),enabled:ue.boolean().nullish(),parameters:ue.string().array().nullish(),defaultParameters:ue.record(ue.string(),ue.string()).nullish(),parameterEnums:ue.record(ue.string(),ue.string().array()).nullish(),defaultCacheKey:ue.string().nullish(),defaultCacheTtl:ue.number().nullish(),defaultCacheAllInvocations:ue.boolean().nullish(),autoAuth:ue.boolean().nullish(),advanced:Yu.nullish()});import{z as Yt}from"zod";var sf=(n=>(n.ALWAYS="ALWAYS",n.ON_FAILURE="ON_FAILURE",n.ON_ACTION_FAILURE="ON_ACTION_FAILURE",n))(sf||{});var HM=Yt.discriminatedUnion("type",[Yt.object({type:Yt.literal("NAVIGATE_URL"),url:Yt.string().url()}),Yt.object({type:Yt.literal("GO_TO_SECTION_START")})]),GM=Yt.object({trigger:Yt.nativeEnum(sf).optional(),attempts:Yt.number().int().optional(),restartBehavior:HM}),Yi=$t.extend({type:Yt.literal("SECTION"),description:Yt.string().describe("user provided goal of what the section should accomplish"),plan:Yt.string().array().optional(),autohealingConfig:GM.optional()});var lf=Kt.merge(Ku).extend({type:_t.literal("RESOLVED_MODULE"),steps:_t.lazy(()=>ot.array())}),Xi=Kt.extend({steps:_t.lazy(()=>ot.array())}),Xu=Yi.extend({steps:_t.lazy(()=>Pt.array())}),VM=Yi.extend({steps:_t.lazy(()=>ot.array())}),Io=qu.extend({blocks:_t.object({assertion:_t.lazy(()=>qt),steps:_t.lazy(()=>Pt.array())}).array(),elseSteps:_t.lazy(()=>Pt.array().optional())}),jM=qu.extend({blocks:_t.object({assertion:_t.lazy(()=>qt),steps:_t.lazy(()=>ot.array())}).array(),elseSteps:_t.lazy(()=>ot.array().optional())}),Pt=_t.discriminatedUnion("type",[qt,Ln,Po,jr,Io,Xu]),ot=_t.discriminatedUnion("type",[qt,Ln,Po,lf,jM,VM]);import{z as Xt}from"zod";var WM=Xt.object({steps:Pt.array(),beforeSteps:Pt.array().nullish(),afterSteps:Pt.array().nullish()}),Nn=Xt.object({steps:ot.array(),beforeSteps:ot.array().nullish(),afterSteps:ot.array().nullish()}),Dn=Xt.object({steps:Xt.record(Xt.string(),Xt.unknown()).array(),beforeSteps:Xt.record(Xt.string(),Xt.unknown()).array().nullish(),afterSteps:Xt.record(Xt.string(),Xt.unknown()).array().nullish()});var kn="1.0.21",Ju="0.0.1";import{z as St}from"zod";import{z as Un}from"zod";var $M=/^[a-f0-9]{8}-[a-f0-9]{4}-[1-5][a-f0-9]{3}-[89ab][a-f0-9]{3}-[a-f0-9]{12}$/,on=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 Oo=Un.string().min(1).max(255).superRefine((r,e)=>{try{Zu(r)}catch(t){return e.addIssue({code:Un.ZodIssueCode.custom,message:t.message,fatal:!0}),Un.NEVER}});function Zu(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($M))throw new Error("Name cannot be a UUID. Please choose a different name.")}var Os=Un.preprocess(r=>r===null?"":r,Un.union([Un.string().url(),Un.literal("")])).optional();var qM=["AI_EXTRACT","JAVASCRIPT"],KM=St.object({id:St.string().optional().describe("Recommended way of selecting an entity. The id of the entity to resolve."),name:Oo.optional().describe("1-255 chars; Only letters/numbers/dashes. Cannot start/end with '-'. Not '.yaml', 'none', or UUID."),path:St.string().optional().describe("The path of the entity to resolve.")}).describe("A selector for a single entity. Exactly one of id, name, or path must be provided. Id is recommended.").refine(r=>[r.id,r.name,r.path].filter(Boolean).length===1,"Exactly one of id, name, or path must be provided."),YM=St.object({selector:KM,inputs:St.record(St.string()).or(St.null())}),B$=St.object({type:St.literal("PRESET_ACTION"),action:Ps,envKey:St.string().or(St.null()).describe(`key in the environment to save the result of this step to. Only use this for ${qM.join(" or ")} steps.`)}),z$=St.object({type:St.literal("MODULE"),module:YM}),H$=St.object({type:St.literal("AI_ACTION_DYNAMIC"),text:St.string().describe("The goal description for the AI action. Supports handlebars templates like {{env.VARIABLE_NAME}}.")});var cf=I.object({phrase:I.string()}),Qu=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()])}),vq=I.object({text:I.string()}),XM=I.boolean().or(I.nativeEnum(Jr)).transform(r=>!(!r||r==="irrelevant")),uf=I.object({attributes:I.array(I.string()).nullish(),text:XM.nullish(),position:I.nativeEnum(Jr).nullish(),shape:I.nativeEnum(Jr).nullish()}),JM=I.object({id:I.number().int(),requirements:uf}),ZM=JM.array(),df=I.object({thoughts:I.string(),review:I.string().optional(),id:I.number().int(),updatedMemory:vu.optional(),requirements:uf.nullish().transform(r=>{if(r!==null)return r}),additionalElements:ZM.nullish().transform(r=>{if(r!==null)return r})});var ed=(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))(ed||{}),pf=(o=>(o.NONE="NONE",o.AMBIGUOUS_DESCRIPTION="AMBIGUOUS_DESCRIPTION",o.COPILOT_MISUSE="COPILOT_MISUSE",o.IRRELEVANT_MESSAGE="IRRELEVANT_MESSAGE",o))(pf||{});var mf=I.object({thoughts:I.string(),category:I.nativeEnum(ed)}),gf=I.object({thoughts:I.string(),category:I.nativeEnum(pf)}),QM=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()})]),Aq=I.object({thoughts:I.string(),patches:QM.array()}),e_=[I.literal("add"),I.literal("replace"),I.literal("remove")],t_=I.object({op:I.union(e_),path:I.string(),value:ot.optional()}),hf=I.object({patches:t_.array(),thoughts:I.string()}),ff=(n=>(n.LEGITIMATE="LEGITIMATE",n.RECOVERABLE="RECOVERABLE",n.INELIGIBLE="INELIGIBLE",n))(ff||{}),Sf=I.object({thoughts:I.string(),scenario:I.nativeEnum(ff),instructions:I.string().nullish()}),yf=I.object({reasoning:I.string(),scenario:I.string(),patch:I.null().optional()}),wq=I.object({thoughts:I.string(),evaluation:I.number().min(0).max(10)}),Rq=I.object({observations:I.string(),reasoning:I.string(),command:Ts});var td=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")})])}),r_=I.object({startId:I.number().int(),endId:I.number().int()}),bf=(n=>(n.SIMPLE_CONTENT_BASED_LOCATOR="SIMPLE_CONTENT_BASED_LOCATOR",n.SIMPLE_CONTENT_BASED_ASSERTION="SIMPLE_CONTENT_BASED_ASSERTION",n.OTHER="OTHER",n))(bf||{}),Ef=I.object({categoryThoughts:I.string(),category:I.nativeEnum(bf),relevantSections:r_.array()}),an=I.boolean().nullish().transform(r=>r??!1),Tf=I.object({thoughts:I.string().optional(),isPageReady:an,descriptionLabels:I.object({usesTextContent:an,usesAppearance:an,usesPosition:an,usesRelativeElements:an,usesSingleQuotes:an,isAmbiguous:an,targetDoesNotExist:an}).optional()});import{z as P}from"zod";import*as te from"zod";var Iq=te.object({thoughts:te.string().optional().describe("only provided if a description was provided"),target:Qr.optional().describe("only provided if a description was provided"),pageState:te.string().optional().describe("serialized a11y tree, only provided if a description was provided"),options:te.object({label:te.string(),value:te.string()}).array().optional().describe("list of options, provided for <select> elements only"),screenshot:te.object({data:te.string(),height:te.number().int(),width:te.number().int()}).optional().describe("only provided if returnScreenshot is true")}),vf=te.union([te.literal("ELEMENT_CHECK"),te.literal("NEGATED_CHECK"),te.literal("NEGATED_ELEMENT_VISIBLE_CHECK"),te.literal("SELECT_OPTION"),te.literal("TYPE")]);function Ji(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 Zi=(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))(Zi||{}),Lo=te.object({matched:te.boolean(),reason:te.string().optional().describe("Human understandable description"),logs:te.string().array().optional().describe("Logs for debugging")}),n_=Lo.extend({type:te.literal("USER_SELECTOR")}),o_=Lo.extend({type:te.literal("CSS_SELECTOR"),selectors:te.string().array()}),i_=Lo.extend({type:te.literal("HYBRID_SELECTOR")}),a_=Lo.extend({type:te.literal("HTML_DISTANCE"),distance:te.number().optional(),closestElement:te.string().optional(),savedElement:te.string().optional()}),s_=Lo.extend({type:te.literal("TEMPLATE_MATCHING"),elementImageUrl:te.string().url()}),l_=Lo.extend({type:te.literal("AUTO_FRAME"),logs:te.string().array().optional()}),Af=te.discriminatedUnion("type",[n_,o_,i_,a_,s_,l_]);import{z as ra}from"zod";import{z as b_}from"zod";import*as G from"zod";import{extendZodWithOpenApi as d_}from"zod-openapi";import{cloneDeep as Gq}from"lodash-es";import jq from"truncate-json";import*as zn from"zod";import{extendZodWithOpenApi as u_}from"zod-openapi";import{z as yt}from"zod";import{z as ie}from"zod";var rd=ie.object({autoFollowNewTabs:ie.boolean().optional().describe("Deprecated: Auto-follow new tabs that are opened."),showZeroOpacityElements:ie.union([ie.boolean(),ie.literal("inputs-only")]).optional(),ignoreHrefForCaching:ie.boolean().optional(),disableSecondaryCacheResolution:ie.boolean().optional(),hybridSelectorMode:ie.enum(["off","test","prefer"]).optional(),globalLocatorRedirect:ie.union([ie.boolean(),ie.literal("always")]).optional(),visualActions:ie.boolean().optional(),autoExpandIframes:ie.boolean().optional(),disableHtmlSnapshots:ie.boolean().optional(),importantAttributes:ie.string().array().optional(),importantClasses:ie.string().array().optional(),importantStyles:ie.string().array().optional()});var wf=1e4,Rf=6e4,c_=ie.object({server:ie.string(),username:ie.string().optional(),password:ie.string().optional()}),Fn=rd.extend({pageLoadTimeoutMs:ie.number().optional().refine(r=>r===void 0||r<=Rf&&r>=-1,{message:`Page load timeout must be between 0 and ${Rf/1e3} seconds`}).describe("global page load timeout default for all tests in ms, can still be overridden by individual tests"),smartWaitingTimeoutMs:ie.number().optional().refine(r=>r===void 0||r<=wf&&r>=-1,{message:`Smart waiting timeout must be between 0 and ${wf/1e3} seconds`}),localChromeExtensionPaths:ie.string().array().optional(),extraHeaders:ie.record(ie.string(),ie.string()).optional().describe("HTTP headers to be sent on every request"),initialLocalStorage:ie.record(ie.string(),ie.record(ie.string(),ie.string())).optional().describe("Initial local storage key-value pairs to set per domain on browser startup"),userAgent:ie.string().optional(),disableGpu:ie.boolean().optional(),disableBrowserMonitoring:ie.boolean().optional().describe("Disable console logs and network request recording, which power the console and network tab in the run viewer"),bustCacheOnBoundingBoxChange:ie.boolean().optional().describe("This setting is deprecated. 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:ie.boolean().optional().describe("Allow fetching the partial accessibility tree if fetching the full tree takes too long."),ignoreHttpsErrors:ie.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."),proxy:c_.optional().describe("HTTP proxy server to use for the entire browser. This can dramatically increase network latency.")});var nd="BASE_URL";var Bn="ENV_NAME",No="TEST_NAME",Uq={[nd]:"https://www.google.com"},Cf=yt.string().describe("Name of the fixture (must be available locally in the fixtures directory)."),xf=yt.object({name:yt.string(),variables:yt.record(yt.string().describe("variable name"),yt.string().describe("variable value"))}),Mf=yt.object({name:yt.string(),variables:yt.record(yt.string().describe("variable name"),yt.unknown().describe("variable value")),browser:Fn.optional()});var Fq=yt.object({name:yt.string(),variables:yt.record(yt.string().describe("variable name"),yt.unknown().describe("variable value"))});u_(zn);var od=zn.object({env:zn.record(zn.unknown())}).openapi({ref:"TestContextSnapshot"});var He=(i=>(i.SUCCESS="SUCCESS",i.FAILED="FAILED",i.RUNNING="RUNNING",i.IDLE="IDLE",i.CANCELLED="CANCELLED",i))(He||{}),id=(n=>(n.SUCCESS="SUCCESS",n.FAILED="FAILED",n.CANCELLED="CANCELLED",n))(id||{});d_(G);var ad=G.object({beforeUrl:G.string().optional(),afterUrl:G.string().optional(),message:G.string().optional(),beforeSnapshot:G.string().optional(),afterSnapshot:G.string().optional(),startedAt:G.coerce.date(),finishedAt:G.coerce.date()}),p_=ad.extend({viewport:G.object({height:G.number(),width:G.number()}).nullish(),status:G.nativeEnum(id),message:G.string().optional(),elementInteracted:G.string().optional()}),Hn=ad.extend({status:G.nativeEnum(He),message:G.string().optional(),data:G.unknown().optional(),beforeTestContext:od.optional(),afterTestContext:od.optional(),failureReason:G.nativeEnum(Te).optional(),details:G.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"}),_f=(t=>(t.NOT_ELIGIBLE="NOT_ELIGIBLE",t.ATTEMPTED="ATTEMPTED",t))(_f||{}),Ls=Hn.merge(qt).extend({results:p_.array().describe("Command that was executed. Array is just for consistency with other result types. There should only ever be one item."),previousAttempts:G.lazy(()=>lt.array()).optional(),failureRecoveryStatus:G.object({type:G.nativeEnum(_f),message:G.string()}).optional()}),m_=Hn.merge(Ln).extend({results:G.lazy(()=>Ls.array()),previousAttempts:G.lazy(()=>lt.array()).optional()}),g_=Hn.merge(Po).extend({results:G.lazy(()=>Ls.array()),previousAttempts:G.lazy(()=>lt.array()).optional()}),h_=Hn.merge(jr).extend({moduleName:G.string().optional(),results:G.lazy(()=>lt.array()),previousAttempts:G.lazy(()=>lt.array()).optional()}),f_=Hn.merge(Io).extend({assertion:Ls.optional(),results:G.lazy(()=>lt.array()).describe("results for the block actually executed"),previousAttempts:G.lazy(()=>lt.array()).optional()}),S_=Hn.merge(Yi).extend({results:G.lazy(()=>lt.array()),healingAttempts:G.lazy(()=>lt.array().array()).optional(),previousAttempts:G.lazy(()=>lt.array()).optional()}),lt=G.discriminatedUnion("type",[m_,g_,Ls,h_,f_,S_]),aK=Hn.pick({startedAt:!0,finishedAt:!0,status:!0,message:!0,data:!0}),y_=ad.extend({index:G.number().optional(),description:G.string(),pageState:G.string().optional(),elementInteracted:G.string().optional(),startedAt:G.coerce.date().or(G.string()).optional().catch(void 0),finishedAt:G.coerce.date().or(G.string()).optional().catch(void 0)}),Ns=y_.extend({beforeScreenshot:G.string().optional(),afterScreenshot:G.string().optional()});var sd=b_.object({results:lt.array().describe("main results"),beforeResults:lt.array().optional(),afterResults:lt.array().optional()}),Qi=sd.partial();import{z as B}from"zod";import{extendZodWithOpenApi as C_}from"zod-openapi";var Do=(t=>(t.WEB="WEB",t.ANDROID="ANDROID",t))(Do||{});import{isValidCron as E_}from"cron-validator";import{z as ne}from"zod";import{z as ld}from"zod";var sn=(n=>(n.CHROMIUM="Chromium",n.GOOGLE_CHROME="Google Chrome",n.CHROME_FOR_TESTING="Chrome for Testing",n))(sn||{});var Ds=ld.object({width:ld.number().min(200).max(1e4),height:ld.number().min(200).max(1e4)}),Pf={"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}},mK=Object.keys(Pf);var ln=Pf["Desktop Large"],If="en-us",Of="America/Los_Angeles";var Lf={latitude:37.7749,longitude:-122.4194};var Nf=["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 Df=1e4,T_=Fn.extend({browserType:ne.nativeEnum(sn).optional(),slowMoMs:ne.number().optional().refine(r=>r===void 0||r<=Df&&r>=-1,{message:`Slow motion must be between 0 and ${Df} milliseconds`}),basicAuthorization:ne.object({username:ne.string().optional(),password:ne.string().optional()}).optional(),geolocation:ne.object({latitude:ne.coerce.number().refine(r=>r>=-90&&r<=90,{message:"Latitude must be between -90 and 90 degrees"}),longitude:ne.coerce.number().refine(r=>r>=-180&&r<=180,{message:"Longitude must be between -180 and 180 degrees"})}).optional(),disableJavaScript:ne.boolean().optional(),locale:ne.string().optional(),timezone:ne.enum(Nf).optional(),colorScheme:ne.enum(["light","dark"]).optional()});var cd=ne.object({useMemory:ne.boolean().optional(),failureRecovery:ne.boolean().optional().describe("undefined means inherit org settings")}),v_=cd.extend({disableAICaching:ne.boolean().optional(),failureRecoveryInstructions:ne.string().optional()}),A_=ne.object({viewport:Ds.optional()}),ea=A_.merge(v_).merge(T_),ko=ne.object({cron:ne.string().refine(r=>E_(r),{message:"Invalid cron expression."}).default("0 0 */1 * *"),enabled:ne.boolean().default(!1),env:ne.string().optional(),timeZone:ne.string().default("America/Los_Angeles"),jobKey:ne.string().optional()}),Uo=ne.object({onSuccess:ne.boolean().default(!1),failureMessage:ne.string().optional(),onFailure:ne.boolean().default(!0),successMessage:ne.string().optional()}),w_=ne.object({name:ne.string(),required:ne.boolean().optional(),defaultValue:ne.string().describe("this is not optional because we need a value when the editor is first loaded")}),ks=w_.array(),R_=ne.object({name:ne.string(),value:ne.string()}),kf=R_.array(),Us=ne.object({name:ne.string(),default:ne.boolean().optional(),fixtures:Cf.array().optional()});C_(B);var Jt={WEBHOOK:"WEBHOOK",CRON:"CRON",MANUAL:"MANUAL",CLI:"CLI"},ve=(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))(ve||{}),Fs=(t=>(t.BEFORE_ALL="BEFORE_ALL",t.AFTER_ALL="AFTER_ALL",t))(Fs||{});var Je=B.string().pipe(B.coerce.date()).or(B.date()),ta=B.object({id:B.string(),runKey:B.string(),organizationId:B.string(),executionType:B.nativeEnum(Do).optional().default("WEB"),createdAt:Je,createdBy:B.string(),flake:B.boolean().nullish(),scheduledAt:Je.or(B.null()),startedAt:Je.or(B.null()),updatedAt:Je.nullish(),finishedAt:Je.or(B.null()),resolvedBaseUrl:B.string().nullish(),environmentName:B.string().nullish(),gitBranchName:B.string().nullish(),githubRepository:B.string().nullish(),gitlabProjectPath:B.string().nullish(),labels:B.array(B.string()).optional(),gitOriginUrl:B.string().nullish(),gitCommitSha:B.string().nullish(),gitCommitShaShort:B.string().nullish(),gitCommitAuthorName:B.string().nullish(),cliVersion:B.string().nullish(),section:B.nativeEnum(Fs).nullish(),status:B.nativeEnum(ve),trigger:B.nativeEnum(Jt),attempts:B.number(),runAttempts:B.array(B.object({id:B.string(),status:B.nativeEnum(ve),startedAt:Je.or(B.null()),finishedAt:Je.or(B.null())})).optional(),videos:B.array(B.string()).optional(),failureReason:B.nativeEnum(Te).nullish(),failureDetails:xs.nullish(),failureRecoveryDetails:B.record(B.string(),B.unknown()).nullish(),pipelineId:B.string().nullish(),resolvedInputs:B.record(B.string(),B.string()).nullish(),quarantined:B.boolean().nullish().default(!1),quarantinedReason:B.string().nullish(),localTestId:B.string().nullish(),testId:B.string().nullish(),testName:B.string().nullish(),description:B.string().nullish(),test:B.object({name:B.string(),id:B.string()}).nullish().default(null),suiteId:B.string().nullish()}).openapi({ref:"RunMetadata"}),x_={id:!0,status:!0,testName:!0,localTestId:!0,testId:!0,test:{select:{name:!0,id:!0}},finishedAt:!0,failureReason:!0,failureDetails:!0},Bs=ta.pick({...x_,test:!0}),Uf=ta.omit({failureReason:!0,failureDetails:!0,test:!0}),ud=ta.extend({stepsSnapshot:B.array(B.record(B.unknown())).nullish(),resolvedInputs:B.record(B.string(),B.string()).nullish(),test:B.object({name:B.string(),id:B.string(),description:B.string().nullish(),baseUrl:B.string().nullish(),advanced:ea.nullish()}).nullish()}).merge(sd);var M_=ra.object({id:ra.string().uuid(),startedAt:Je.or(ra.null()),finishedAt:Je.or(ra.null()),status:ra.nativeEnum(ve)}).merge(Qi),DK=M_.array();import{z as Ze}from"zod";var __=Ze.object({id:Ze.string(),status:Ze.nativeEnum(ve),trigger:Ze.nativeEnum(Jt),createdAt:Je,startedAt:Je.nullish(),finishedAt:Je.nullish(),gitCommitSha:Ze.string().nullish(),gitCommitShaShort:Ze.string().nullish(),gitCommitTimestamp:Je.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(ve)}).array()}).openapi({ref:"RunGroup"}),Ff=__.pick({id:!0,createdAt:!0,startedAt:!0,finishedAt:!0,status:!0,trigger:!0,suite:!0}).extend({runs:Bs.array()});import{z as ct}from"zod";var P_=ct.object({type:ct.literal("TARGETING"),name:ct.string().optional().describe("Target name to disambiguate for steps with multiple targets"),elementLocationDecisions:Af.array(),pageState:ct.string().optional(),targetSource:ct.nativeEnum(Zr).optional(),targetUpdateTime:ct.string().optional()}),I_=ct.object({type:ct.literal("AI_LOCATION"),matched:ct.boolean(),pageState:ct.string().optional(),ragUsed:ct.boolean().optional(),thoughts:ct.string().optional()}),O_=ct.object({type:ct.literal("ASSERTION"),relevantElementsSerialized:ct.string().array().optional(),pageState:ct.string().optional(),ragUsed:ct.boolean().optional()}),L_=ct.discriminatedUnion("type",[P_,I_,O_]);import{z as qe}from"zod";var N_=qe.object({id:qe.string(),name:qe.string()}),YK=N_.merge(qe.object({createdAt:Je,createdBy:qe.string(),schedule:ko,notification:Uo,environment:qe.object({name:qe.string()}).nullish(),beforeTests:qe.object({id:qe.string()}).array().nullish(),afterTests:qe.object({id:qe.string()}).array().nullish()})),Bf=qe.object({id:qe.string().uuid(),orgId:qe.string(),createdAt:Je,startedAt:Je.or(qe.null()),finishedAt:Je.or(qe.null()),status:qe.nativeEnum(ve),trigger:qe.nativeEnum(Jt),suite:qe.object({id:qe.string(),name:qe.string()}).nullish(),runs:ta.array()}),XK=Bf.pick({id:!0,createdAt:!0,startedAt:!0,finishedAt:!0,status:!0,trigger:!0,suite:!0}),zf=Bf.extend({runs:Bs.array()});import{z as Zt}from"zod";import{cloneDeep as QK}from"lodash-es";import{z as Se}from"zod";var i2=Se.object({thoughts:Se.string(),subGoals:Se.object({instruction:Se.string()}).array()}),a2=Se.object({thoughts:Se.string(),newPlanMarkdown:Se.string()}),s2=Se.object({thoughts:Se.string(),correct:Se.boolean(),failedActionIndex:Se.number().optional()}),D_=Se.object({type:Se.literal("PLANNING"),beforePlan:Se.string(),goalDecision:Se.string(),thoughts:Se.string()}),k_=Se.object({type:Se.literal("RUNNING"),stepDisplayName:Se.string(),status:Se.nativeEnum(He),results:lt.array()}),U_=Se.object({type:Se.literal("REVISING"),beforePlan:Se.string(),afterPlan:Se.string(),errString:Se.string(),diffs:Se.string(),thoughts:Se.string()}),F_=Se.object({type:Se.literal("SYSTEM"),message:Se.string()}),B_=Se.discriminatedUnion("type",[D_,k_,U_,F_]),Hf=B_.array();var p2=Zt.object({id:Zt.string(),scheduledAt:Zt.coerce.date().nullable(),startedAt:Zt.coerce.date().nullable(),finishedAt:Zt.coerce.date().nullable(),status:Zt.nativeEnum(ve),history:Hf.nullable(),testPlan:Zt.object({id:Zt.string(),name:Zt.string()}).nullable(),test:Zt.object({id:Zt.string(),name:Zt.string()}).nullable()});import{z as It}from"zod";var dd=It.object({content:It.string(),ids:It.string().array(),tokenLength:It.number()}),z_=It.object({chunks:dd.array()}),_2=It.object({ids:It.string().array(),score:It.number(),tokenLength:It.number()}),P2=z_.extend({description:It.string().describe("Input to pass to RAG engine"),tokenLimit:It.number()}),Gf=It.object({ids:It.number().array()}),Vf=It.object({indices:It.number().array()});var pt=P.object({disableCache:P.boolean().optional(),useMemory:P.boolean().optional(),clientMode:P.enum(["interactive","runner"]).optional(),loggerTags:P.record(P.string(),P.string()).optional(),langfuseSessionId:P.string().optional(),agentConfigVersion:P.string().optional()}),F2=pt.extend({chunks:dd.array(),description:P.string().describe("Input to pass to AI"),type:P.union([P.literal("locator"),P.literal("assertion"),P.literal("ai-action")]),softTokenLimit:P.number(),hardTokenLimit:P.number(),callId:P.string().optional()}),H_=P.object({screenshotBase64AfterCommand:P.string(),urlAfterCommand:P.string(),serializedCommand:P.string(),elementInteracted:P.string().optional(),thoughts:P.string().optional()}),jf=P.object({goal:P.string(),browserState:P.string(),screenshot:P.string(),source:vf.optional().catch(void 0),memory:P.discriminatedUnion("type",[hs,P.object({type:P.literal("RESOLVED_TRACES"),traces:P.unknown().array()})]).optional()}),Wf=P.object({target:P.string().or(P.number()),browserState:P.string().optional(),screenshot:P.string().optional(),boundingBox:P.object({x:P.number(),y:P.number(),height:P.number(),width:P.number()}).optional()}),$f=P.object({goal:P.string(),browserState:P.string(),screenshot:P.string().optional(),returnSchema:P.string().optional()}),G_=P.literal("NEGATED_CHECK"),qf=P.object({goal:P.string(),browserState:P.string(),screenshot:P.string(),url:P.string(),contextChoice:Pu.optional(),memory:P.discriminatedUnion("type",[Ru,P.object({type:P.literal("RESOLVED_TRACES"),traces:P.unknown().array()})]).optional(),source:G_.optional()}),Kf=P.object({command:xo}),Yf=P.object({message:P.string()}),pd=P.object({goal:P.string(),browserState:P.string(),startingScreenshot:P.string().optional(),screenshot:P.string(),url:P.string(),history:H_.array(),actionHint:P.string().optional(),lastError:P.string().optional()}),Xf=P.object({results:Ns.array(),errorMessage:P.string(),errorStack:P.string().optional()}),Jf=P.object({results:Ns.array(),goal:P.string(),errorMessage:P.string()}),Zf=P.object({failedResults:Ns.array(),nextStepsSerialized:P.string().array(),currentUrl:P.string(),currentPageState:P.string(),currentScreenshot:P.string(),customInstructions:P.string().optional(),testDescription:P.string().optional()}),B2=P.object({description:P.string(),type:P.union([P.literal("locator"),P.literal("assertion"),P.literal("ai-action")]),excerpt:P.string()}),Qf=P.object({type:P.string(),browserContext:P.string(),currentStep:P.string(),screenshot:P.string()}),eS=P.object({description:P.string(),browserState:P.string(),screenshot:P.string()});import{z as na}from"zod";var G2=na.object({goal:na.string()}),tS=na.object({keywords:na.array(na.string())});import{z as md}from"zod";var zs=(o=>(o.LOCATOR="locator",o.ASSERTION="assertion",o.VISUAL_ASSERTION="visual-assertion",o.TEXT_EXTRACTION="text-extraction",o))(zs||{}),W2=md.nativeEnum(zs),V_=md.enum(["v1","v2"]),$2=V_.or(md.string().describe("for people with special configurations"));var rS={locator:"v3",assertion:"v3","visual-assertion":"v3","text-extraction":"v2"};import{z as De}from"zod";var nS=De.object({attributesRequired:De.array(De.string()).optional(),textRequired:De.boolean().optional(),boundsRequired:De.boolean().optional()}),oS=De.object({id:De.number(),thoughts:De.string(),inWebview:De.boolean().optional(),requirements:nS.optional(),additionalElements:De.object({id:De.number(),requirements:nS}).array().optional()}),iS=De.object({description:De.string(),screenXml:De.string(),screenshot:De.string()}),aS=De.object({assertion:De.string(),screenXml:De.string(),screenshot:De.string()}),sS=De.object({thoughts:De.string(),result:De.boolean(),relevantElements:De.array(De.number()).optional()});import{z as Gn}from"zod";var lS=Gn.object({id:Gn.string().uuid(),skipped:Gn.boolean().optional(),envKey:Gn.string().optional().describe("key in the environment to save the result of this step to")}),gd=lS.merge(bo).extend({type:Gn.literal("REQUEST")}),hd=lS.merge(Ss).extend({type:Gn.literal("JAVASCRIPT")}),fd=Gn.discriminatedUnion("type",[hd,gd]);import{z as Qt}from"zod";var cS=Qt.object({id:Qt.string(),name:Oo,description:Qt.string().optional().nullish(),baseUrl:Os.nullish(),schemaVersion:Qt.string(),advanced:Qt.unknown().optional(),retries:Qt.number(),envs:Qt.array(Us).nullish(),parameters:ks.nullish()}),j_=Qt.object({createdAt:Qt.coerce.date(),updatedAt:Qt.coerce.date(),schedule:ko.nullish(),notification:Uo.nullish(),createdBy:Qt.string(),organizationId:Qt.string()}),W_=cS.merge(j_),fY=W_.extend({steps:fd.array()}),SY=cS.extend({steps:fd.array()});import{z as kt}from"zod";var uS=kt.object({startedAt:kt.coerce.date(),finishedAt:kt.coerce.date(),status:kt.nativeEnum(He),message:kt.string().optional(),data:kt.unknown().optional()}),$_=uS.merge(hd).extend({type:kt.literal("JAVASCRIPT")}),q_=uS.merge(gd).extend({type:kt.literal("REQUEST")}),K_=kt.discriminatedUnion("type",[$_,q_]),dS=kt.object({startedAt:kt.coerce.date(),finishedAt:kt.coerce.date().nullish(),status:kt.nativeEnum(ve),results:K_.array(),failureReason:kt.string().nullish(),failureDetails:xs.nullish()});import{z as Ut}from"zod";var Y_=Ut.object({id:Ut.string(),organizationId:Ut.string(),createdAt:Ut.coerce.date(),updatedAt:Ut.coerce.date(),createdBy:Ut.string(),scheduledAt:Ut.coerce.date().nullish(),startedAt:Ut.coerce.date().nullish(),finishedAt:Ut.coerce.date().nullish(),status:Ut.nativeEnum(ve),trigger:Ut.nativeEnum(Jt),results:dS.array().nullish(),apiTestName:Ut.string().nullish(),apiTestPath:Ut.string().nullish(),apiTestId:Ut.string().nullish()}),xY=Y_.pick({status:!0,startedAt:!0,finishedAt:!0});var oa=(o=>(o.TestRun="test-run",o.MobileTestRun="mobile-test-run",o.CreditsUsed="credits-used",o.CreditsUsedV2="credits-used-v2",o))(oa||{}),pS=3;function X_(r){return r==="MODULE"||r==="CONDITIONAL"||r==="SECTION"||r==="RESOLVED_MODULE"}function Sd(r){if(!X_(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 yd(r){switch(r.type){case"AI_EXTRACT":case"AI_ASSERTION":return pS;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 Hs=class{trackStepExecution(){}async flush(){}};import{parseString as J_,splitCookiesString as Z_}from"set-cookie-parser";import{z as Ee}from"zod";var bd=Ee.object({name:Ee.string(),value:Ee.string(),url:Ee.string().optional(),domain:Ee.string().optional(),path:Ee.string().optional(),expires:Ee.number().default(Date.now()/1e3+60*60*24*365),httpOnly:Ee.boolean().optional(),secure:Ee.boolean().default(!0),sameSite:Ee.union([Ee.literal("Strict"),Ee.literal("Lax"),Ee.literal("None")]).default("None")});function Gs(r,e){let t=[],n=Z_(r);for(let o of n){let i=J_(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=bd.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 Q_=Ee.object({origin:Ee.string(),localStorage:Ee.array(Ee.object({name:Ee.string(),value:Ee.string()}))}),eP=Ee.object({entries:Ee.record(Ee.string(),Ee.array(Ee.tuple([Ee.unknown(),Ee.unknown()]))),version:Ee.number().optional()}),mS=Ee.object({cookies:bd.array().optional(),origins:Q_.array().optional(),idb:Ee.record(Ee.string(),eP).optional().describe("key is db name")});function Vs(r,e){let t=[];return r.cloneSync()?.serializeSync()?.cookies.forEach(n=>{let o=bd.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{v4 as Ws}from"uuid";import ke from"zod";import{v4 as XY}from"uuid";import{z as F}from"zod";import*as _e from"zod";var gS=_e.object({requiredText:_e.string().optional(),requiredAttributes:_e.record(_e.string(),_e.string()).optional(),requiredBounds:_e.boolean().optional()}),tP=_e.object({xPath:_e.string(),requirements:gS.optional()}),rP=_e.object({type:_e.literal("NATIVE"),bounds:_e.number().array(),resolvedDescription:_e.string(),xPath:_e.string(),elementOnlySerializedXml:_e.string(),requirements:gS.optional(),requiredRelatedElements:tP.array().optional()}),nP=_e.object({type:_e.literal("WEBVIEW"),resolvedDescription:_e.string(),xPath:_e.string(),browserCache:Qr.optional()}),js=_e.discriminatedUnion("type",[rP,nP]);var cn=(f=>(f.AI_CHECK="AI_CHECK",f.TAP="TAP",f.TYPE="TYPE",f.PRESS="PRESS",f.PRESS_KEYBOARD="PRESS_KEYBOARD",f.OPEN_APP="OPEN_APP",f.KILL_APP="KILL_APP",f.OPEN_NOTIFICATION_DRAWER="OPEN_NOTIFICATION_DRAWER",f.SWIPE="SWIPE",f.JAVASCRIPT="JAVASCRIPT",f.REQUEST="REQUEST",f.WAIT="WAIT",f.ADD_FILE="ADD_FILE",f.INSTALL_APP="INSTALL_APP",f.ADB="ADB",f.STATE="STATE",f))(cn||{}),ia=(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))(ia||{}),Ed=(n=>(n.CLOSE_KEYBOARD="CLOSE_KEYBOARD",n.ENTER="ENTER",n.BACKSPACE="BACKSPACE",n))(Ed||{}),hS=F.object({type:F.literal("description"),description:F.string()}),oP=F.object({type:F.literal("coordinates"),xPercent:F.number(),yPercent:F.number()}),fS=F.discriminatedUnion("type",[hS,oP]),iP=F.object({updatedAt:F.coerce.date().optional()}),bt=F.object({id:F.string().uuid(),disableCache:F.boolean().optional()}),aP=bt.extend({type:F.literal("STATE")}),sP=bt.extend({type:F.literal("KILL_APP")}),Td=iP.extend({target:js}),lP=bt.extend({type:F.literal("AI_CHECK"),assertion:F.string(),timeoutSecs:F.number().optional()}),vd=bt.extend({type:F.literal("TAP"),target:fS,cache:Td.optional(),longPress:F.boolean().optional(),longPressDurationMs:F.number().optional(),doubleTap:F.boolean().optional(),doubleTapDelayMs:F.number().optional(),relativePosition:F.object({x:F.number(),y:F.number()}).optional()}),Ad=bt.extend({type:F.literal("TYPE"),target:fS.optional(),cache:Td.optional(),keyPressDelayMs:F.number().optional(),text:F.string(),clearContent:F.boolean().optional()}),cP=bt.extend({type:F.literal("PRESS"),key:F.nativeEnum(ia),longPress:F.boolean().optional()}),uP=bt.extend({type:F.literal("PRESS_KEYBOARD"),key:F.nativeEnum(Ed)}),dP=bt.extend({type:F.literal("OPEN_APP"),packageName:F.string(),activityName:F.string().optional(),intentExtras:F.string().optional()}),pP=bt.extend({type:F.literal("OPEN_NOTIFICATION_DRAWER")});var mP=F.discriminatedUnion("type",[F.object({type:F.literal("SCREEN")}),F.object({type:F.literal("OPEN_APP")}),F.object({type:F.literal("OPEN_WEBVIEW")}),F.object({type:F.literal("CUSTOM"),target:hS})]);var wd=bt.extend({type:F.literal("SWIPE"),direction:F.enum(["up","down","left","right"]),scrollableElement:mP,cache:Td.optional(),viewportPercent:F.number().optional(),durationMs:F.number().optional()}),gP=bt.extend({type:F.literal("JAVASCRIPT"),code:F.string(),timeout:F.number().int().max(60).optional().describe("Max seconds for the code to complete")}),hP=bt.extend({type:F.literal("REQUEST")}).merge(bo),fP=bt.extend({type:F.literal("WAIT"),timeoutSecs:F.number()}),SP=bt.extend({type:F.literal("ADB"),command:F.string(),jsonArgs:F.string().optional()}),yP=bt.extend({type:F.literal("ADD_FILE"),file:F.string(),storageLocation:F.string()}),bP=F.string().trim(),EP=bt.extend({type:F.literal("INSTALL_APP"),uri:bP}),SS=F.discriminatedUnion("type",[lP,vd,Ad,cP,dP,pP,uP,wd,gP,hP,fP,yP,EP,sP,SP,aP]);var Rd=r=>{switch(r.type){case"description":return r.description;case"coordinates":return`${r.xPercent}%, ${r.yPercent}%`}};var TP=ke.object({type:ke.literal("TAP"),description:ke.string().describe("Description of the element to tap."),longPress:ke.boolean().describe("Whether to hold the tap down before releasing. Useful for triggering context menus."),doubleTap:ke.boolean().describe("Whether to tap twice in quick succession."),relativePosition:ke.null().or(ke.object({x:ke.number(),y:ke.number()})).describe("Specific position to tap within the bounding box of the element, specified in pixels. E.g. 0,0 is the top left corner.")}).describe(`
10
10
  Tap on an element on the screen.
11
- `),yP=ke.object({type:ke.literal("PRESS"),key:ke.nativeEnum(oa)}).describe(`
11
+ `),vP=ke.object({type:ke.literal("PRESS"),key:ke.nativeEnum(ia)}).describe(`
12
12
  Press a button on the device. Some buttons are physical (volume) while others are virtual (Back/Home/App Switcher).
13
- `),bP=ke.object({type:ke.literal("AI_CHECK"),assertion:ke.string().describe("A natural language assertion to validate. On each attempt, Momentic's AI agents will evaluate the assertion by analyzing the current emulator XML and screenshot. Thus, the assertion must be verifiable based on a single point in time. The assertion will be automatically retried until it is true or the timeout is reached."),timeoutSecs:ke.number().describe("Maximum number of seconds to wait for the assertion to be true.")}).describe(`
13
+ `),AP=ke.object({type:ke.literal("AI_CHECK"),assertion:ke.string().describe("A natural language assertion to validate. On each attempt, Momentic's AI agents will evaluate the assertion by analyzing the current emulator XML and screenshot. Thus, the assertion must be verifiable based on a single point in time. The assertion will be automatically retried until it is true or the timeout is reached."),timeoutSecs:ke.number().describe("Maximum number of seconds to wait for the assertion to be true.")}).describe(`
14
14
  Use AI to verify a statement about the current state of the emulator or wait until a statement is true.
15
- `),EP=ke.object({type:ke.literal("TYPE"),text:ke.string().describe("Exact type to text, which will be passed to appium's driver.keys() method."),keyPressDelayMs:ke.number().or(ke.null()).describe("Milliseconds to wait between each key press. Useful for triggering auto-complete and other event listeners."),clearContent:ke.boolean().or(ke.null()).describe("Clear the content of the input before typing. Do not set to true if the input is already empty.")}),Ad=ke.discriminatedUnion("type",[SP,yP,bP,EP]),hS=r=>{let e=Ad.parse(r);switch(e.type){case"TAP":return{id:Vs(),type:"TAP",target:{type:"description",description:e.description},longPress:e.longPress??void 0,doubleTap:e.doubleTap??void 0,relativePosition:e.relativePosition??void 0};case"PRESS":return{id:Vs(),...e};case"AI_CHECK":return{id:Vs(),...e};case"TYPE":return{id:Vs(),type:"TYPE",text:e.text,keyPressDelayMs:e.keyPressDelayMs??void 0,clearContent:e.clearContent??void 0};default:{let t=e;throw new Error("Unreachable")}}};import TP from"zod";var wd={type:!0,cache:!0},ln=TP.discriminatedUnion("type",[bd.pick(wd),Ed.pick(wd),Td.pick(wd)]),vP=Object.values(sn).filter(r=>ln.options.some(e=>e.shape.type.safeParse(r).success));function js(r){return vP.includes(r.type)}var fS=Gi(ln),SS=Vi(ln),t5=Es(ln);import{cloneDeep as ia}from"lodash-es";import yS from"truncate-json";var AP="\u2022\u2022\u2022\u2022\u2022\u2022\u2022\u2022\u2022\u2022\u2022\u2022\u2022\u2022\u2022",wP=[Fn,Lo],bS=[Fn,Lo],Uo=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[Fn],o=e.env[Lo],i={};for(let[l,c]of Object.entries(e.env))bS.includes(l)||(t??{})[l]===void 0&&(i[l]=c);return new r({dynamicVariables:i,envName:n,testName:o,variablesFromEnvironment:t??{}})}setEnvVariables(e){let t=ia(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){wP.includes(e)||(this.env[e]=t)}getEnvName(){return this.env[Fn]}toObjectCopy(){let e={env:Object.assign({},this.env,this.varsFromMomenticEnvironment)};return ia(e)}toEditorDisplayCopy(){return this.toObjectCopy()}toRedactedDisplayCopy(){let e=this.toObjectCopy();e.env=Object.fromEntries(Object.entries(e.env).map(([n,o])=>bS.includes(n)||this.varsFromMomenticEnvironment[n]===void 0?[n,o]:[n,AP]));for(let[n,o]of Object.entries(e.env)){if(!o){e.env[n]=o;continue}let{jsonString:i}=yS(JSON.stringify(o),1e3);try{e.env[n]=JSON.parse(i)}catch{e.env[n]=void 0}}let{jsonString:t}=yS(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=ia(e.variablesFromEnvironment),e.envName&&this.setMomenticSystemVariable(Fn,e.envName),e.testName&&this.setMomenticSystemVariable(Lo,e.testName)}getDynamicVariablesCopy(){return ia(this.env)}getVariablesFromEnvironmentCopy(){return ia(this.varsFromMomenticEnvironment)}};import ES from"zod";var Ws=(t=>(t.US_WEST_1="us-west1",t.EU_NORTH_1="eu-north1",t))(Ws||{}),$s=(e=>(e.LOCAL="local",e))($s||{}),TS=ES.nativeEnum(Ws).or(ES.nativeEnum($s));import Qe from"zod";import{z as mr}from"zod";import{z as Ue}from"zod";var pr=Ue.object({id:Ue.string(),name:Io,baseUrl:Ps,description:Ue.string().optional().nullish(),schemaVersion:Ue.string(),advanced:Qi,retries:Ue.number(),envs:Ue.array(Ds).nullish(),parameters:Ns.nullish(),disabled:Ue.boolean().optional(),labels:Ue.array(Ue.string()).optional().catch([])}),m5=Ue.enum(["INHERIT","ENABLED","DISABLED"]);var RP=Qi.extend({failureRecovery:Ue.boolean().or(Ue.string()).optional().transform(r=>typeof r=="string"?r:r===void 0?"INHERIT":r?"ENABLED":"DISABLED"),useMemory:Ue.boolean().or(Ue.string()).optional().transform(r=>typeof r=="string"?r:r===void 0?"INHERIT":r?"ENABLED":"DISABLED")});var g5=pr.pick({name:!0,description:!0,baseUrl:!0,retries:!0,disabled:!0,parameters:!0}).extend({advanced:RP}),h5=pr.pick({name:!0,description:!0,baseUrl:!0,retries:!0,disabled:!0,advanced:!0,parameters:!0}),CP=Ue.object({labels:Ue.array(Ue.string()).optional(),outputs:Nf.nullish()}),Fo=pr.merge(CP),xP=Ue.object({createdAt:Ue.coerce.date(),updatedAt:Ue.coerce.date(),updatedBy:Ue.string().nullable(),schedule:Do,notification:ko,createdBy:Ue.string(),organizationId:Ue.string(),folderId:Ue.string().nullable().optional()}),MP=pr.merge(xP),f5=MP.merge(Ln),qs=pr.merge(Ln),S5=pr.merge(Nn);var _P="test",PP="module",IP="mobile-test",OP="mobile-module";var _e=(o=>(o.TEST=`momentic/${_P}`,o.MODULE=`momentic/${PP}`,o.MOBILE_TEST=`momentic/${IP}`,o.MOBILE_MODULE=`momentic/${OP}`,o))(_e||{}),w5=pr.merge(Nn),vS=Kt.extend({steps:mr.array(mr.record(mr.string(),mr.unknown())),schemaVersion:mr.string()}),R5=vS.extend({fileType:mr.literal(_e.MODULE)}),C5=mr.object({test:mr.string().describe("YAML for the test, including metadata and steps"),modules:mr.record(mr.string(),mr.string()).describe("Map of module name to YAML for the module")});var Rd=Qe.object({parameterNames:Qe.string().array(),defaultParameters:Qe.record(Qe.string(),Qe.string()).optional(),parameterEnums:Qe.record(Qe.string(),Qe.string().array()).optional()}),LP=Qe.object({moduleId:Qe.string().uuid(),name:Qe.string(),description:Qe.string().nullish(),parameters:Rd.optional(),enabled:Qe.boolean().nullish(),schemaVersion:Qe.string()}),aa=LP.omit({name:!0}),Ks=aa.extend({steps:Qe.array(Qe.record(Qe.string(),Qe.unknown()))}),NP=Qe.object({fileType:Qe.literal(_e.MOBILE_MODULE)}).merge(Ks);import Et from"zod";var Ft=(n=>(n.PRESET="MOBILE_PRESET_STEP",n.MODULE="MOBILE_MODULE_STEP",n.AI_ACTION="MOBILE_AI_ACTION_STEP",n))(Ft||{}),sa=Et.object({id:Et.string().uuid(),envKey:Et.string().optional(),skipped:Et.boolean().optional()}),la=sa.extend({type:Et.literal("MOBILE_PRESET_STEP"),command:gS,keyPressDelayMs:Et.number().optional()}),Bo=Et.object({moduleId:Et.string(),inputs:Et.record(Et.string(),Et.string()).optional(),parameters:Rd.optional()}),ca=sa.merge(Bo.extend({type:Et.literal("MOBILE_MODULE_STEP")})),D5=Bo.extend({steps:Et.lazy(()=>gr.array())}),ua=sa.extend({type:Et.literal("MOBILE_AI_ACTION_STEP"),text:Et.string()}),gr=Et.discriminatedUnion("type",[la,ca,ua]);import Ge from"zod";import Ys from"zod";var Vr=(e=>(e.MODULE="RESOLVED_MOBILE_MODULE",e))(Vr||{}),DP=Bo.extend({steps:Ys.lazy(()=>da.array()),name:Ys.string().describe("name of the module")}),kP=sa.merge(DP).extend({type:Ys.literal("RESOLVED_MOBILE_MODULE")}),da=Ys.discriminatedUnion("type",[kP,la,ua]);function AS(r){return Object.values(Vr).includes(r)||Object.values(Ft).includes(r)}var UP=Ge.object({disableMomenticAccessibilityTree:Ge.boolean().optional(),autoGrantPermissions:Ge.boolean().optional()}),Cd=UP.extend({region:TS.optional(),localEmulatorSettings:Ge.object({avdId:Ge.string()}).optional()}),pa=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(),defaultApkFilePath:Ge.string().trim().min(1,"APK file path must not be empty.").optional().describe("APK to install when using the emulator in the local region."),emulator:Cd.optional()}),Ar=Ge.object({id:Ge.string().uuid(),description:Ge.string(),schemaVersion:Ge.string(),settings:pa.optional()}),FP=Ar.merge(Ge.object({steps:Ge.array(gr)})),Xs=Ge.object({fileType:Ge.literal(_e.MOBILE_TEST)}).merge(FP),X5=Ge.object({name:Ge.string(),steps:Ge.array(gr).optional(),settings:pa.optional()}),BP=Ar.extend({steps:da.array()});import ye from"zod";var Gn=ye.object({startTime:ye.number(),endTime:ye.number().optional(),durationMs:ye.number().optional(),error:ye.string().optional(),result:ye.unknown().optional(),attributes:ye.record(ye.string(),ye.unknown())});var zP=Gn.extend({type:ye.literal("SECTION"),name:ye.string(),subSpans:ye.lazy(()=>xd.array())}),HP=Gn.extend({type:ye.literal("AI_LOCATOR_CALL"),result:ye.object({id:ye.number(),thoughts:ye.string()}).optional()}),GP=Gn.extend({type:ye.literal("AI_ASSERTION_CALL"),result:ye.object({thoughts:ye.string(),result:ye.boolean()}).optional()}),VP=Gn.extend({type:ye.literal("TARGET_RESOLUTION"),result:ye.object({serializedElement:ye.string()}).optional()}),jP=Gn.extend({type:ye.literal("EMULATOR_INTERACTION"),name:ye.string(),withinWebview:ye.boolean().optional()}),WP=Gn.extend({type:ye.literal("EMULATOR_READ_STATE"),name:ye.string()}),$P=Gn.extend({type:ye.literal("GENERIC"),name:ye.string()}),xd=ye.discriminatedUnion("type",[zP,HP,GP,VP,jP,WP,$P]);import er from"zod";var Md=er.object({message:er.string().optional(),startTime:er.number(),endTime:er.number(),status:er.nativeEnum(He),trace:er.unknown(),beforeSnapshot:er.string().optional(),afterSnapshot:er.string().optional(),data:er.unknown().optional().describe("output data from the step")}),qP=Md.merge(la),KP=Md.merge(ca).extend({steps:er.lazy(()=>tr.array())}),YP=Md.merge(ua).extend({steps:er.lazy(()=>tr.array())}),tr=er.discriminatedUnion("type",[qP,KP,YP]);import{parse as sX}from"date-fns";var PX=new Set(Object.values(nt));var XP={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"},IX={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:[]},OX={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."},LX={AI_CHECK:"AI check",RESOLVED_MOBILE_MODULE:"Module",MOBILE_AI_ACTION_STEP:"AI action",TAP:"Tap",TYPE:"Type",PRESS:"Press button",PRESS_KEYBOARD:"Press keyboard",SWIPE:"Swipe",OPEN_APP:"Open app",KILL_APP:"Kill app",OPEN_NOTIFICATION_DRAWER:"Open notification drawer",JAVASCRIPT:"JavaScript",REQUEST:"API request",WAIT:"Wait",ADD_FILE:"Add file",INSTALL_APP:"Install app",ADB:"ADB command",STATE:"Debug state"},NX={MOBILE_AI_ACTION_STEP:"Ask AI to accomplish a high-level goal by generating other steps.",AI_CHECK:"Ask AI to verify whether something is true on the screen.",RESOLVED_MOBILE_MODULE:"A list of steps that can be reused in multiple tests.",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.",SWIPE:"Swipe on the screen.",OPEN_APP:"Open an app on the device.",KILL_APP:"Terminate the currently active app and remove it from recents.",OPEN_NOTIFICATION_DRAWER:"Open the notification drawer.",JAVASCRIPT:"Execute JavaScript code in a NodeJS context.",REQUEST:"Make an HTTP request to a URL.",WAIT:"Wait for a specified amount of time.",ADD_FILE:"Add a file to the device's disk.",INSTALL_APP:"Install one or more APKs onto the connected emulator.",ADB:"Execute an ADB command on the device.",STATE:"Capture and return emulator state details."};import JP from"semver";import{z as ZP}from"zod";var FX=ZP.string().refine(r=>JP.valid(r),{message:"must be a valid semver string"});import{Faker as HX,en as GX}from"@faker-js/faker";import{z as N}from"zod";var jX=N.object({body:N.string(),to:N.string(),from:N.string()}),WX=N.object({from:N.string().optional(),to:N.string(),timeout:N.number().optional(),beforeDate:N.string().pipe(N.coerce.date()).or(N.date()).optional(),afterDate:N.string().pipe(N.coerce.date()).or(N.date()).optional()}),$X=N.object({to:N.string().email(),from:N.string(),subject:N.string(),body:N.string(),html:N.string().optional()}),qX=N.object({inbox:N.string().transform(r=>r.toLowerCase()),afterDate:N.string().pipe(N.coerce.date()).or(N.date()).optional(),timeout:N.number().optional(),trimWhitespace:N.boolean().optional()}),KX=N.object({inbox:N.string(),limit:N.number().optional(),afterDate:N.string().pipe(N.coerce.date()).or(N.date()).optional(),trimWhitespace:N.boolean().optional()});var Js=(t=>(t.RAW="RAW",t.RESPONSE="RESPONSE",t))(Js||{}),wS=N.object({body:N.string().nullish(),status:N.number().optional(),headers:N.array(N.tuple([N.string(),N.string()])).optional()}),QP=N.object({url:N.string(),options:N.object({method:N.string(),body:N.string().nullish(),headers:N.array(N.tuple([N.string(),N.string()])).optional()}).optional()}).optional(),eI=N.object({body:N.string().nullish(),options:N.object({status:N.number(),statusText:N.string().optional(),headers:N.array(N.tuple([N.string(),N.string()])).optional()}).optional()}).optional(),RS=N.object({result:N.unknown(),variableUpdates:N.record(N.string(),N.unknown()).optional(),persistentVariableUpdates:N.record(N.string(),N.unknown()).optional(),error:N.string().optional(),success:N.boolean()}),YX=N.object({id:N.string().optional(),orgId:N.string(),momenticLambdaAuthHash:N.string(),code:N.string(),fragment:N.boolean(),state:N.object({env:N.record(N.string(),N.unknown()),request:QP,response:eI,additionalBindings:N.record(N.string(),N.unknown()).optional()}),timeoutMs:N.number().optional(),disallowVariableUpdates:N.boolean().optional(),responseSerialization:N.nativeEnum(Js).optional()}),cn=15e3;import*as Tt from"zod";import{extendZodWithOpenApi as tI}from"zod-openapi";tI(Tt);var rI=Tt.object({url:Tt.string(),lineNumber:Tt.number(),columnNumber:Tt.number()}).openapi({ref:"CodeLocation"}),Zs=Tt.object({timestamp:Tt.number(),text:Tt.string(),type:Tt.string(),tabIndex:Tt.number(),args:Tt.unknown().array().optional(),url:Tt.string().optional(),location:rI.optional()}).openapi({ref:"ConsoleLog"}),CS=Zs.array(),nI=CS.array();import*as _d from"zod";import{extendZodWithOpenApi as AI}from"zod-openapi";import{z as _}from"zod";var oI=_.object({name:_.string(),version:_.string(),comment:_.string().optional()}),iI=_.object({name:_.string(),version:_.string(),comment:_.string().optional()}),aI=_.object({onContentLoad:_.number().optional(),onLoad:_.number().optional(),comment:_.string().optional()}),MS=_.object({startedDateTime:_.string(),id:_.string(),title:_.string().optional(),pageTimings:aI,comment:_.string().optional()}),sI=_.array(MS),lI=_.object({name:_.string(),value:_.string(),path:_.string().optional(),domain:_.string().optional(),expires:_.string().optional(),httpOnly:_.boolean().optional(),secure:_.boolean().optional(),comment:_.string().optional()}),_S=_.array(lI),cI=_.object({name:_.string(),value:_.string(),comment:_.string().optional()}),PS=_.array(cI),uI=_.object({name:_.string(),value:_.string(),comment:_.string().optional()}),dI=_.array(uI),pI=_.object({name:_.string(),value:_.string().optional(),fileName:_.string().optional(),contentType:_.string().optional(),comment:_.string().optional()}),mI=_.array(pI),gI=_.object({mimeType:_.string(),params:mI,text:_.string(),comment:_.string().optional(),_redactedReason:_.string().optional()}),hI=_.object({method:_.string(),url:_.string(),httpVersion:_.string().optional(),cookies:_S,headers:PS,queryString:dI,postData:gI.optional(),headersSize:_.number().optional(),bodySize:_.number().optional(),comment:_.string().optional()}),fI=_.object({size:_.number().optional(),compression:_.number().optional(),mimeType:_.string().optional(),text:_.string().optional(),encoding:_.string().optional(),comment:_.string().optional(),_redactedReason:_.string().optional()}),SI=_.object({status:_.number(),statusText:_.string(),httpVersion:_.string().optional(),cookies:_S,headers:PS,content:fI,redirectURL:_.string().optional(),headersSize:_.number().optional(),bodySize:_.number().optional(),comment:_.string().optional(),_mocked:_.boolean().optional()}),xS=_.object({expires:_.string().optional(),lastAccess:_.string(),eTag:_.string(),hitCount:_.number(),comment:_.string().optional()}),yI=_.object({beforeRequest:xS.optional(),afterRequest:xS.optional(),comment:_.string().optional()}),bI=_.object({blocked:_.number().optional(),dns:_.number().optional(),connect:_.number().optional(),send:_.number(),wait:_.number(),receive:_.number(),ssl:_.number().optional(),comment:_.string().optional()}),IS=_.object({pageref:_.string().optional(),startedDateTime:_.string(),time:_.number().optional(),request:hI,response:SI.optional(),cache:yI.optional(),timings:bI,serverIPAddress:_.string().optional(),connection:_.string().optional(),comment:_.string().optional(),_resourceType:_.string().optional()}),EI=_.array(IS),TI=_.object({version:_.string().default("1.1"),creator:oI.optional(),browser:iI.optional(),pages:sI.optional(),entries:EI,comment:_.string().optional()}),vI=_.object({log:TI}),OS=_.record(_.string(),MS),LS=_.record(_.string(),IS);AI(_d);var wI=_d.object({logsPerPage:Zs.array().array(),harPages:OS.optional(),harEntries:LS.optional()}).openapi({ref:"DebugData"});import{cloneDeep as RI}from"lodash-es";import{z as wr}from"zod";var DS=(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))(DS||{});var NS=wr.union([wr.string(),wr.number(),wr.boolean(),wr.null(),wr.record(wr.string(),wr.lazy(()=>NS)),wr.array(wr.lazy(()=>NS))]),Qs=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=RI(this.flags);return Object.entries(e).forEach(([t,n])=>{typeof n=="boolean"&&Object.values(DS).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")}},F3=new Qs({},{});var Pd={".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"},kS=[".sh",".exe",".app",".bat",".cmd",".msi",".apk",".jar",".py",".js",".cron",".php",".asp"],z3=Object.keys(Pd);import*as US from"zod";var G3=US.custom().refine(r=>r&&r.length>0).refine(r=>r&&r[0]instanceof File,{message:"Please upload a valid file."});import{z as un}from"zod";var W3=un.object({id:un.string(),name:un.string(),createdAt:un.coerce.date(),createdBy:un.string(),updatedAt:un.coerce.date(),updatedBy:un.string().nullable(),organizationId:un.string()});import{z as O}from"zod";import dn from"zod";var zo=dn.object({platformSep:dn.string(),fullPathSegments:dn.string().array(),relativePathSegments:dn.string().array(),relativePath:dn.string().describe("path relative to the root test directory, i.e. my-folder/my-test.yaml"),fileName:dn.string().describe("base name of the file including the extension, e.g. my-module.module.yaml"),lastModified:dn.coerce.date(),createdAt:dn.coerce.date()});var CI=O.array(zo.extend({id:O.string(),name:O.string(),description:O.string().optional(),labels:O.string().array().optional()})),xI=O.array(zo.extend({id:O.string(),name:O.string(),description:O.string().optional(),content:Yi})),o4=O.object({tests:CI,modules:xI,labels:O.string().array()}),i4=qs.merge(Fo),a4=O.object({schemaVersion:O.string(),stepLists:Ln}),s4=Fo.partial().merge(pr.pick({id:!0})),MI={name:O.string().min(1).max(255).describe("1-255 chars; Only letters/numbers/dashes. Cannot start/end with '-'. Not '.yaml', 'none', or UUID."),description:O.string().optional(),baseUrl:O.string().url().optional().describe("For LLM: Ask the user for the base URL if they don't provide it."),environment:O.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:O.nativeEnum(on).optional().describe("For LLM: Never assign this variable unless the user explicitly asks for it."),viewport:Ls.optional().describe("For LLM: Never assign this variable unless the user explicitly asks for it."),pathSegments:O.string().array().optional().describe("For LLM: Only use if explicitly called for by the user. Used to create the test in the correct folder.")},l4=O.object(MI),c4=qs.merge(O.object({relativeFilePath:O.string().describe("relative to project root")})),u4=O.object({name:O.string()}),d4=O.object({relativeFilePath:O.string()}),p4=O.object({name:O.string()}),m4=O.object({relativeFilePath:O.string()}),g4=O.object({name:O.string(),description:O.string(),enabled:O.boolean(),steps:O.lazy(()=>ot.array()),testFilePath:O.string().describe("relative to the project root"),folderPath:O.string().optional().describe("user selected folder path")}),h4=O.object({name:O.string(),description:O.string(),enabled:O.boolean()}).partial();var f4=O.array(Cf),S4=O.object({defaultEnv:O.string().optional().describe("name of the default env, or undefined to unset")}),y4=O.object({configFilePath:O.string().describe("full path on disk")}),b4=O.string().array(),E4=O.object({message:O.string(),newRelativeTestPath:O.string().optional()}),Id=O.object({name:O.string(),absolutePath:O.string(),relativePath:O.string(),pathSegments:O.array(O.string()),isDirectory:O.boolean(),size:O.number(),createdAt:O.coerce.date(),modifiedAt:O.coerce.date(),accessedAt:O.coerce.date()}),FS=O.object({pathSegments:O.array(O.string())}),T4=O.object({absolutePath:O.string(),pathSegments:O.array(O.string()),contents:O.array(Id)}),BS=O.object({pathSegments:O.array(O.string())}),zS=O.object({pathSegments:O.array(O.string()),newPathSegments:O.array(O.string())}),HS=O.object({pathSegments:O.array(O.string()),recursive:O.boolean().optional()}),v4=O.object({success:O.boolean(),message:O.string(),pathSegments:O.array(O.string()).optional()}),A4=O.object({gitBranch:O.string(),fileMtime:O.coerce.date(),gitCommitSha:O.string()});var el=["node_modules","dist","bin",".git",".npm",".next","out",".yarn","__pycache__","build",".env",".venv","venv","env","wheels"],tl=el.map(r=>`**/${r}/**`),GS=!0,Rr=!1;import Cr from"chalk";import _I from"safe-stable-stringify";import PI from"truncate-json";import II from"zod";var Vn=_I.configure({deterministic:!1});function VS(r){let e=Vn(r),{jsonString:t}=PI(e,5e4);return t}var OI=["app","version","env","namespace","host"];function me(r){let e=r.bindings()??{},t={};for(let n of Object.keys(e)){let o=e[n];!OI.includes(n)&&typeof o=="string"&&(t[n]=o)}return t}var nl=II.enum(["debug","info","warn","error"]);var ma={debug:20,info:30,warn:40,error:50},jS={20:"debug",30:"info",40:"warn",50:"error"},Od=class r{minLogLevel;logBindings;constructor(e,t){typeof e=="string"?this.minLogLevel=ma[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}`)}}indentMultiline(e,t=" "){return e.split(`
15
+ `),wP=ke.object({type:ke.literal("TYPE"),text:ke.string().describe("Exact type to text, which will be passed to appium's driver.keys() method."),keyPressDelayMs:ke.number().or(ke.null()).describe("Milliseconds to wait between each key press. Useful for triggering auto-complete and other event listeners."),clearContent:ke.boolean().or(ke.null()).describe("Clear the content of the input before typing. Do not set to true if the input is already empty.")}),Cd=ke.discriminatedUnion("type",[TP,vP,AP,wP]),yS=r=>{let e=Cd.parse(r);switch(e.type){case"TAP":return{id:Ws(),type:"TAP",target:{type:"description",description:e.description},longPress:e.longPress??void 0,doubleTap:e.doubleTap??void 0,relativePosition:e.relativePosition??void 0};case"PRESS":return{id:Ws(),...e};case"AI_CHECK":return{id:Ws(),...e};case"TYPE":return{id:Ws(),type:"TYPE",text:e.text,keyPressDelayMs:e.keyPressDelayMs??void 0,clearContent:e.clearContent??void 0};default:{let t=e;throw new Error("Unreachable")}}};import RP from"zod";var xd={type:!0,cache:!0},un=RP.discriminatedUnion("type",[vd.pick(xd),Ad.pick(xd),wd.pick(xd)]),CP=Object.values(cn).filter(r=>un.options.some(e=>e.shape.type.safeParse(r).success));function $s(r){return CP.includes(r.type)}var bS=Vi(un),ES=ji(un),u5=vs(un);import{cloneDeep as aa}from"lodash-es";import TS from"truncate-json";var xP="\u2022\u2022\u2022\u2022\u2022\u2022\u2022\u2022\u2022\u2022\u2022\u2022\u2022\u2022\u2022",MP=[Bn,No],vS=[Bn,No],Fo=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[Bn],o=e.env[No],i={};for(let[l,c]of Object.entries(e.env))vS.includes(l)||(t??{})[l]===void 0&&(i[l]=c);return new r({dynamicVariables:i,envName:n,testName:o,variablesFromEnvironment:t??{}})}setEnvVariables(e){let t=aa(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){MP.includes(e)||(this.env[e]=t)}getEnvName(){return this.env[Bn]}toObjectCopy(){let e={env:Object.assign({},this.env,this.varsFromMomenticEnvironment)};return aa(e)}toEditorDisplayCopy(){return this.toObjectCopy()}toRedactedDisplayCopy(){let e=this.toObjectCopy();e.env=Object.fromEntries(Object.entries(e.env).map(([n,o])=>vS.includes(n)||this.varsFromMomenticEnvironment[n]===void 0?[n,o]:[n,xP]));for(let[n,o]of Object.entries(e.env)){if(!o){e.env[n]=o;continue}let{jsonString:i}=TS(JSON.stringify(o),1e3);try{e.env[n]=JSON.parse(i)}catch{e.env[n]=void 0}}let{jsonString:t}=TS(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=aa(e.variablesFromEnvironment),e.envName&&this.setMomenticSystemVariable(Bn,e.envName),e.testName&&this.setMomenticSystemVariable(No,e.testName)}getDynamicVariablesCopy(){return aa(this.env)}getVariablesFromEnvironmentCopy(){return aa(this.varsFromMomenticEnvironment)}};import AS from"zod";var qs=(t=>(t.US_WEST_1="us-west1",t.EU_NORTH_1="eu-north1",t))(qs||{}),Ks=(e=>(e.LOCAL="local",e))(Ks||{}),wS=AS.nativeEnum(qs).or(AS.nativeEnum(Ks));import Qe from"zod";import{z as gr}from"zod";import{z as Ue}from"zod";var mr=Ue.object({id:Ue.string(),name:Oo,baseUrl:Os,description:Ue.string().optional().nullish(),schemaVersion:Ue.string(),advanced:ea,retries:Ue.number(),envs:Ue.array(Us).nullish(),parameters:ks.nullish(),disabled:Ue.boolean().optional(),labels:Ue.array(Ue.string()).optional().catch([])}),v5=Ue.enum(["INHERIT","ENABLED","DISABLED"]);var _P=ea.extend({failureRecovery:Ue.boolean().or(Ue.string()).optional().transform(r=>typeof r=="string"?r:r===void 0?"INHERIT":r?"ENABLED":"DISABLED"),useMemory:Ue.boolean().or(Ue.string()).optional().transform(r=>typeof r=="string"?r:r===void 0?"INHERIT":r?"ENABLED":"DISABLED")});var A5=mr.pick({name:!0,description:!0,baseUrl:!0,retries:!0,disabled:!0,parameters:!0}).extend({advanced:_P}),w5=mr.pick({name:!0,description:!0,baseUrl:!0,retries:!0,disabled:!0,advanced:!0,parameters:!0}),PP=Ue.object({labels:Ue.array(Ue.string()).optional(),outputs:kf.nullish()}),Bo=mr.merge(PP),IP=Ue.object({createdAt:Ue.coerce.date(),updatedAt:Ue.coerce.date(),updatedBy:Ue.string().nullable(),schedule:ko,notification:Uo,createdBy:Ue.string(),organizationId:Ue.string(),folderId:Ue.string().nullable().optional()}),OP=mr.merge(IP),R5=OP.merge(Nn),Ys=mr.merge(Nn),C5=mr.merge(Dn);var LP="test",NP="module",DP="mobile-test",kP="mobile-module";var Pe=(o=>(o.TEST=`momentic/${LP}`,o.MODULE=`momentic/${NP}`,o.MOBILE_TEST=`momentic/${DP}`,o.MOBILE_MODULE=`momentic/${kP}`,o))(Pe||{}),L5=mr.merge(Dn),RS=Kt.extend({steps:gr.array(gr.record(gr.string(),gr.unknown())),schemaVersion:gr.string()}),N5=RS.extend({fileType:gr.literal(Pe.MODULE)}),D5=gr.object({test:gr.string().describe("YAML for the test, including metadata and steps"),modules:gr.record(gr.string(),gr.string()).describe("Map of module name to YAML for the module")});var Md=Qe.object({parameterNames:Qe.string().array(),defaultParameters:Qe.record(Qe.string(),Qe.string()).optional(),parameterEnums:Qe.record(Qe.string(),Qe.string().array()).optional()}),UP=Qe.object({moduleId:Qe.string().uuid(),name:Qe.string(),description:Qe.string().nullish(),parameters:Md.optional(),enabled:Qe.boolean().nullish(),schemaVersion:Qe.string()}),sa=UP.omit({name:!0}),Xs=sa.extend({steps:Qe.array(Qe.record(Qe.string(),Qe.unknown()))}),FP=Qe.object({fileType:Qe.literal(Pe.MOBILE_MODULE)}).merge(Xs);import Et from"zod";var Ft=(n=>(n.PRESET="MOBILE_PRESET_STEP",n.MODULE="MOBILE_MODULE_STEP",n.AI_ACTION="MOBILE_AI_ACTION_STEP",n))(Ft||{}),la=Et.object({id:Et.string().uuid(),envKey:Et.string().optional(),skipped:Et.boolean().optional()}),ca=la.extend({type:Et.literal("MOBILE_PRESET_STEP"),command:SS,keyPressDelayMs:Et.number().optional()}),zo=Et.object({moduleId:Et.string(),inputs:Et.record(Et.string(),Et.string()).optional(),parameters:Md.optional()}),ua=la.merge(zo.extend({type:Et.literal("MOBILE_MODULE_STEP")})),j5=zo.extend({steps:Et.lazy(()=>hr.array())}),da=la.extend({type:Et.literal("MOBILE_AI_ACTION_STEP"),text:Et.string()}),hr=Et.discriminatedUnion("type",[ca,ua,da]);import Ge from"zod";import Js from"zod";var Wr=(e=>(e.MODULE="RESOLVED_MOBILE_MODULE",e))(Wr||{}),BP=zo.extend({steps:Js.lazy(()=>pa.array()),name:Js.string().describe("name of the module")}),zP=la.merge(BP).extend({type:Js.literal("RESOLVED_MOBILE_MODULE")}),pa=Js.discriminatedUnion("type",[zP,ca,da]);function CS(r){return Object.values(Wr).includes(r)||Object.values(Ft).includes(r)}var HP=Ge.object({disableMomenticAccessibilityTree:Ge.boolean().optional(),autoGrantPermissions:Ge.boolean().optional()}),_d=HP.extend({region:wS.optional(),localEmulatorSettings:Ge.object({avdId:Ge.string()}).optional()}),ma=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(),defaultApkFilePath:Ge.string().trim().min(1,"APK file path must not be empty.").optional().describe("APK to install when using the emulator in the local region."),emulator:_d.optional()}),Rr=Ge.object({id:Ge.string().uuid(),description:Ge.string(),schemaVersion:Ge.string(),settings:ma.optional()}),GP=Rr.merge(Ge.object({steps:Ge.array(hr)})),Zs=Ge.object({fileType:Ge.literal(Pe.MOBILE_TEST)}).merge(GP),iX=Ge.object({name:Ge.string(),steps:Ge.array(hr).optional(),settings:ma.optional()}),VP=Rr.extend({steps:pa.array()});import ye from"zod";var Vn=ye.object({startTime:ye.number(),endTime:ye.number().optional(),durationMs:ye.number().optional(),error:ye.string().optional(),result:ye.unknown().optional(),attributes:ye.record(ye.string(),ye.unknown())});var jP=Vn.extend({type:ye.literal("SECTION"),name:ye.string(),subSpans:ye.lazy(()=>Pd.array())}),WP=Vn.extend({type:ye.literal("AI_LOCATOR_CALL"),result:ye.object({id:ye.number(),thoughts:ye.string()}).optional()}),$P=Vn.extend({type:ye.literal("AI_ASSERTION_CALL"),result:ye.object({thoughts:ye.string(),result:ye.boolean()}).optional()}),qP=Vn.extend({type:ye.literal("TARGET_RESOLUTION"),result:ye.object({serializedElement:ye.string()}).optional()}),KP=Vn.extend({type:ye.literal("EMULATOR_INTERACTION"),name:ye.string(),withinWebview:ye.boolean().optional()}),YP=Vn.extend({type:ye.literal("EMULATOR_READ_STATE"),name:ye.string()}),XP=Vn.extend({type:ye.literal("GENERIC"),name:ye.string()}),Pd=ye.discriminatedUnion("type",[jP,WP,$P,qP,KP,YP,XP]);import er from"zod";var Id=er.object({message:er.string().optional(),startTime:er.number(),endTime:er.number(),status:er.nativeEnum(He),trace:er.unknown(),beforeSnapshot:er.string().optional(),afterSnapshot:er.string().optional(),data:er.unknown().optional().describe("output data from the step")}),JP=Id.merge(ca),ZP=Id.merge(ua).extend({steps:er.lazy(()=>tr.array())}),QP=Id.merge(da).extend({steps:er.lazy(()=>tr.array())}),tr=er.discriminatedUnion("type",[JP,ZP,QP]);import{parse as fX}from"date-fns";var BX=new Set(Object.values(nt));var eI={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"},zX={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:[]},HX={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."},GX={AI_CHECK:"AI check",RESOLVED_MOBILE_MODULE:"Module",MOBILE_AI_ACTION_STEP:"AI action",TAP:"Tap",TYPE:"Type",PRESS:"Press button",PRESS_KEYBOARD:"Press keyboard",SWIPE:"Swipe",OPEN_APP:"Open app",KILL_APP:"Kill app",OPEN_NOTIFICATION_DRAWER:"Open notification drawer",JAVASCRIPT:"JavaScript",REQUEST:"API request",WAIT:"Wait",ADD_FILE:"Add file",INSTALL_APP:"Install app",ADB:"ADB command",STATE:"Debug state"},VX={MOBILE_AI_ACTION_STEP:"Ask AI to accomplish a high-level goal by generating other steps.",AI_CHECK:"Ask AI to verify whether something is true on the screen.",RESOLVED_MOBILE_MODULE:"A list of steps that can be reused in multiple tests.",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.",SWIPE:"Swipe on the screen.",OPEN_APP:"Open an app on the device.",KILL_APP:"Terminate the currently active app and remove it from recents.",OPEN_NOTIFICATION_DRAWER:"Open the notification drawer.",JAVASCRIPT:"Execute JavaScript code in a NodeJS context.",REQUEST:"Make an HTTP request to a URL.",WAIT:"Wait for a specified amount of time.",ADD_FILE:"Add a file to the device's disk.",INSTALL_APP:"Install one or more APKs onto the connected emulator.",ADB:"Execute an ADB command on the device.",STATE:"Capture and return emulator state details."};import tI from"semver";import{z as rI}from"zod";var qX=rI.string().refine(r=>tI.valid(r),{message:"must be a valid semver string"});import{Faker as XX,en as JX}from"@faker-js/faker";import{z as N}from"zod";var QX=N.object({body:N.string(),to:N.string(),from:N.string()}),e3=N.object({from:N.string().optional(),to:N.string(),timeout:N.number().optional(),beforeDate:N.string().pipe(N.coerce.date()).or(N.date()).optional(),afterDate:N.string().pipe(N.coerce.date()).or(N.date()).optional()}),t3=N.object({to:N.string().email(),from:N.string(),subject:N.string(),body:N.string(),html:N.string().optional()}),r3=N.object({inbox:N.string().transform(r=>r.toLowerCase()),afterDate:N.string().pipe(N.coerce.date()).or(N.date()).optional(),timeout:N.number().optional(),trimWhitespace:N.boolean().optional()}),n3=N.object({inbox:N.string(),limit:N.number().optional(),afterDate:N.string().pipe(N.coerce.date()).or(N.date()).optional(),trimWhitespace:N.boolean().optional()});var Qs=(t=>(t.RAW="RAW",t.RESPONSE="RESPONSE",t))(Qs||{}),xS=N.object({body:N.string().nullish(),status:N.number().optional(),headers:N.array(N.tuple([N.string(),N.string()])).optional()}),nI=N.object({url:N.string(),options:N.object({method:N.string(),body:N.string().nullish(),headers:N.array(N.tuple([N.string(),N.string()])).optional()}).optional()}).optional(),oI=N.object({body:N.string().nullish(),options:N.object({status:N.number(),statusText:N.string().optional(),headers:N.array(N.tuple([N.string(),N.string()])).optional()}).optional()}).optional(),MS=N.object({result:N.unknown(),variableUpdates:N.record(N.string(),N.unknown()).optional(),persistentVariableUpdates:N.record(N.string(),N.unknown()).optional(),error:N.string().optional(),success:N.boolean()}),o3=N.object({id:N.string().optional(),orgId:N.string(),momenticLambdaAuthHash:N.string(),code:N.string(),fragment:N.boolean(),state:N.object({env:N.record(N.string(),N.unknown()),request:nI,response:oI,additionalBindings:N.record(N.string(),N.unknown()).optional()}),timeoutMs:N.number().optional(),disallowVariableUpdates:N.boolean().optional(),responseSerialization:N.nativeEnum(Qs).optional()}),dn=15e3;import*as Tt from"zod";import{extendZodWithOpenApi as iI}from"zod-openapi";iI(Tt);var aI=Tt.object({url:Tt.string(),lineNumber:Tt.number(),columnNumber:Tt.number()}).openapi({ref:"CodeLocation"}),el=Tt.object({timestamp:Tt.number(),text:Tt.string(),type:Tt.string(),tabIndex:Tt.number(),args:Tt.unknown().array().optional(),url:Tt.string().optional(),location:aI.optional()}).openapi({ref:"ConsoleLog"}),_S=el.array(),sI=_S.array();import*as Od from"zod";import{extendZodWithOpenApi as xI}from"zod-openapi";import{z as M}from"zod";var lI=M.object({name:M.string(),version:M.string(),comment:M.string().optional()}),cI=M.object({name:M.string(),version:M.string(),comment:M.string().optional()}),uI=M.object({onContentLoad:M.number().optional(),onLoad:M.number().optional(),comment:M.string().optional()}),IS=M.object({startedDateTime:M.string(),id:M.string(),title:M.string().optional(),pageTimings:uI,comment:M.string().optional()}),dI=M.array(IS),pI=M.object({name:M.string(),value:M.string(),path:M.string().optional(),domain:M.string().optional(),expires:M.string().optional(),httpOnly:M.boolean().optional(),secure:M.boolean().optional(),comment:M.string().optional()}),OS=M.array(pI),mI=M.object({name:M.string(),value:M.string(),comment:M.string().optional()}),LS=M.array(mI),gI=M.object({name:M.string(),value:M.string(),comment:M.string().optional()}),hI=M.array(gI),fI=M.object({name:M.string(),value:M.string().optional(),fileName:M.string().optional(),contentType:M.string().optional(),comment:M.string().optional()}),SI=M.array(fI),yI=M.object({mimeType:M.string(),params:SI,text:M.string(),comment:M.string().optional(),_redactedReason:M.string().optional()}),bI=M.object({method:M.string(),url:M.string(),httpVersion:M.string().optional(),cookies:OS,headers:LS,queryString:hI,postData:yI.optional(),headersSize:M.number().optional(),bodySize:M.number().optional(),comment:M.string().optional()}),EI=M.object({size:M.number().optional(),compression:M.number().optional(),mimeType:M.string().optional(),text:M.string().optional(),encoding:M.string().optional(),comment:M.string().optional(),_redactedReason:M.string().optional()}),TI=M.object({status:M.number(),statusText:M.string(),httpVersion:M.string().optional(),cookies:OS,headers:LS,content:EI,redirectURL:M.string().optional(),headersSize:M.number().optional(),bodySize:M.number().optional(),comment:M.string().optional(),_mocked:M.boolean().optional()}),PS=M.object({expires:M.string().optional(),lastAccess:M.string(),eTag:M.string(),hitCount:M.number(),comment:M.string().optional()}),vI=M.object({beforeRequest:PS.optional(),afterRequest:PS.optional(),comment:M.string().optional()}),AI=M.object({blocked:M.number().optional(),dns:M.number().optional(),connect:M.number().optional(),send:M.number(),wait:M.number(),receive:M.number(),ssl:M.number().optional(),comment:M.string().optional()}),NS=M.object({pageref:M.string().optional(),startedDateTime:M.string(),time:M.number().optional(),request:bI,response:TI.optional(),cache:vI.optional(),timings:AI,serverIPAddress:M.string().optional(),connection:M.string().optional(),comment:M.string().optional(),_resourceType:M.string().optional()}),wI=M.array(NS),RI=M.object({version:M.string().default("1.1"),creator:lI.optional(),browser:cI.optional(),pages:dI.optional(),entries:wI,comment:M.string().optional()}),CI=M.object({log:RI}),DS=M.record(M.string(),IS),kS=M.record(M.string(),NS);xI(Od);var MI=Od.object({logsPerPage:el.array().array(),harPages:DS.optional(),harEntries:kS.optional()}).openapi({ref:"DebugData"});import{cloneDeep as _I}from"lodash-es";import{z as Cr}from"zod";var FS=(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))(FS||{});var US=Cr.union([Cr.string(),Cr.number(),Cr.boolean(),Cr.null(),Cr.record(Cr.string(),Cr.lazy(()=>US)),Cr.array(Cr.lazy(()=>US))]),tl=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=_I(this.flags);return Object.entries(e).forEach(([t,n])=>{typeof n=="boolean"&&Object.values(FS).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")}},q3=new tl({},{});var Ld={".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"},BS=[".sh",".exe",".app",".bat",".cmd",".msi",".apk",".jar",".py",".js",".cron",".php",".asp"],Y3=Object.keys(Ld);import*as zS from"zod";var J3=zS.custom().refine(r=>r&&r.length>0).refine(r=>r&&r[0]instanceof File,{message:"Please upload a valid file."});import{z as pn}from"zod";var e4=pn.object({id:pn.string(),name:pn.string(),createdAt:pn.coerce.date(),createdBy:pn.string(),updatedAt:pn.coerce.date(),updatedBy:pn.string().nullable(),organizationId:pn.string()});import{z as O}from"zod";import mn from"zod";var Ho=mn.object({platformSep:mn.string(),fullPathSegments:mn.string().array(),relativePathSegments:mn.string().array(),relativePath:mn.string().describe("path relative to the root test directory, i.e. my-folder/my-test.yaml"),fileName:mn.string().describe("base name of the file including the extension, e.g. my-module.module.yaml"),lastModified:mn.coerce.date(),createdAt:mn.coerce.date()});var PI=O.array(Ho.extend({id:O.string(),name:O.string(),description:O.string().optional(),labels:O.string().array().optional()})),II=O.array(Ho.extend({id:O.string(),name:O.string(),description:O.string().optional(),content:Xi})),m4=O.object({tests:PI,modules:II,labels:O.string().array()}),g4=Ys.merge(Bo),h4=O.object({schemaVersion:O.string(),stepLists:Nn}),f4=Bo.partial().merge(mr.pick({id:!0})),OI={name:O.string().min(1).max(255).describe("1-255 chars; Only letters/numbers/dashes. Cannot start/end with '-'. Not '.yaml', 'none', or UUID."),description:O.string().optional(),baseUrl:O.string().url().optional().describe("For LLM: Ask the user for the base URL if they don't provide it."),environment:O.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:O.nativeEnum(sn).optional().describe("For LLM: Never assign this variable unless the user explicitly asks for it."),viewport:Ds.optional().describe("For LLM: Never assign this variable unless the user explicitly asks for it."),pathSegments:O.string().array().optional().describe("For LLM: Only use if explicitly called for by the user. Used to create the test in the correct folder.")},S4=O.object(OI),y4=Ys.merge(O.object({relativeFilePath:O.string().describe("relative to project root")})),b4=O.object({name:O.string()}),E4=O.object({relativeFilePath:O.string()}),T4=O.object({name:O.string()}),v4=O.object({relativeFilePath:O.string()}),A4=O.object({name:O.string(),description:O.string(),enabled:O.boolean(),steps:O.lazy(()=>ot.array()),testFilePath:O.string().describe("relative to the project root"),folderPath:O.string().optional().describe("user selected folder path")}),w4=O.object({name:O.string(),description:O.string(),enabled:O.boolean()}).partial();var R4=O.array(Mf),C4=O.object({defaultEnv:O.string().optional().describe("name of the default env, or undefined to unset")}),x4=O.object({configFilePath:O.string().describe("full path on disk")}),M4=O.string().array(),_4=O.object({message:O.string(),newRelativeTestPath:O.string().optional()}),Nd=O.object({name:O.string(),absolutePath:O.string(),relativePath:O.string(),pathSegments:O.array(O.string()),isDirectory:O.boolean(),size:O.number(),createdAt:O.coerce.date(),modifiedAt:O.coerce.date(),accessedAt:O.coerce.date()}),HS=O.object({pathSegments:O.array(O.string())}),P4=O.object({absolutePath:O.string(),pathSegments:O.array(O.string()),contents:O.array(Nd)}),GS=O.object({pathSegments:O.array(O.string())}),VS=O.object({pathSegments:O.array(O.string()),newPathSegments:O.array(O.string())}),jS=O.object({pathSegments:O.array(O.string()),recursive:O.boolean().optional()}),I4=O.object({success:O.boolean(),message:O.string(),pathSegments:O.array(O.string()).optional()}),O4=O.object({gitBranch:O.string(),fileMtime:O.coerce.date(),gitCommitSha:O.string()});var rl=["node_modules","dist","bin",".git",".npm",".next","out",".yarn","__pycache__","build",".env",".venv","venv","env","wheels"],nl=rl.map(r=>`**/${r}/**`),WS=!0,xr=!1;import Mr from"chalk";import LI from"safe-stable-stringify";import NI from"truncate-json";import DI from"zod";var jn=LI.configure({deterministic:!1});function $S(r){let e=jn(r),{jsonString:t}=NI(e,5e4);return t}var kI=["app","version","env","namespace","host"];function pe(r){let e=r.bindings()??{},t={};for(let n of Object.keys(e)){let o=e[n];!kI.includes(n)&&typeof o=="string"&&(t[n]=o)}return t}var il=DI.enum(["debug","info","warn","error"]);var ga={debug:20,info:30,warn:40,error:50},qS={20:"debug",30:"info",40:"warn",50:"error"},Dd=class r{minLogLevel;logBindings;constructor(e,t){typeof e=="string"?this.minLogLevel=ga[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}`)}}indentMultiline(e,t=" "){return e.split(`
16
16
  `).map((n,o)=>o>0?`${t}${n}`:n).join(`
17
- `)}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;if(c instanceof Error){s=c.message,console.log(t(` ${l}:`,s)),console.log(t(" stack:",c.stack));let d=Object.entries(c).filter(([p])=>p!=="message"&&p!=="stack");for(let[p,m]of d){if(m instanceof Error){console.log(t(` ${l}.${p}:`,m.message)),m.stack&&console.log(t(` ${l}.${p}.stack:`,m.stack));continue}if(typeof m=="object"&&m!==null){let g=this.indentMultiline(Vn(m,void 0,2)," ");console.log(t(` ${l}.${p}:`,g));continue}console.log(t(` ${l}.${p}:`,m))}}else typeof c=="object"?(s=Vn(c,void 0,2),s=this.indentMultiline(s),console.log(t(` ${l}:`,s))):console.log(t(` ${l}:`,s))}}else if(o)for(let a of o){let l=a;typeof a=="object"&&(l=Vn(a,void 0,2),l=l.split(`
17
+ `)}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;if(c instanceof Error){s=c.message,console.log(t(` ${l}:`,s)),console.log(t(" stack:",c.stack));let d=Object.entries(c).filter(([p])=>p!=="message"&&p!=="stack");for(let[p,m]of d){if(m instanceof Error){console.log(t(` ${l}.${p}:`,m.message)),m.stack&&console.log(t(` ${l}.${p}.stack:`,m.stack));continue}if(typeof m=="object"&&m!==null){let g=this.indentMultiline(jn(m,void 0,2)," ");console.log(t(` ${l}.${p}:`,g));continue}console.log(t(` ${l}.${p}:`,m))}}else typeof c=="object"?(s=jn(c,void 0,2),s=this.indentMultiline(s),console.log(t(` ${l}:`,s))):console.log(t(` ${l}:`,s))}}else if(o)for(let a of o){let l=a;typeof a=="object"&&(l=jn(a,void 0,2),l=l.split(`
18
18
  `).map((c,s)=>s>0?` ${c}`:c).join(`
19
- `)),console.log(" ",t(l))}}setMinLevel(e){typeof e=="string"?this.minLogLevel=ma[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})}async flush(){}bindings(){return this.logBindings}},Ld=class{debug(){}info(){}warn(){}error(){}success(){}dimmed(){}underline(){}bold(){}grey(){}child(){return this}async flush(){}bindings(){return{}}},I4=new Ld,LI=typeof window>"u"&&typeof process<"u"&&nl.safeParse(process?.env?.MOMENTIC_DEV_LOG_LEVEL).success?nl.parse(process.env.MOMENTIC_DEV_LOG_LEVEL):30,R=new Od(LI,{}),pn={info:()=>{},error:()=>{},debug:()=>{},warn:()=>{},child:()=>pn,flush:async()=>{},bindings:()=>({})},rl={},ol=({logger:r,logKey:e,maxCount:t,intervalMs:n},o,i,...a)=>{let l=rl[e];l?clearTimeout(l.timer):(l={count:0,totalCount:0},rl[e]=l),l.totalCount++,l.count<t&&(l.count++,r.debug(o,i,...a)),l.timer=setTimeout(()=>{let c=rl[e];c?.totalCount!==c?.count&&r.debug({logKey:e,totalCount:c?.totalCount,count:c?.count},`Debug logs were rate-limited for ${e}`),delete rl[e]},n)};import{z as be}from"zod";var NI=be.array(zo.extend({id:be.string(),name:be.string(),description:be.string().optional(),labels:be.string().array().optional()})),DI=be.array(zo.extend({id:be.string(),name:be.string(),description:be.string().optional(),content:Yi})),WS=be.object({name:be.string(),description:be.string().optional(),settings:pa.optional(),pathSegments:be.string().array()}),U4=be.object({id:be.string(),fileName:be.string(),fullPath:be.string(),relativeFilePath:be.string().describe("relative to project root")});var $S=be.object({steps:da.array().optional(),settings:pa.optional()}),F4=be.object({message:be.literal("ok")}),qS=be.object({tag:be.string(),channel:be.string(),filePath:be.string()}),B4=be.object({tests:NI,modules:DI,labels:be.string().array()}),KS=be.object({name:be.string(),description:be.string(),enabled:be.boolean()}).partial();import{z as Ke}from"zod";var YS=Ke.object({id:Ke.string(),createdAt:Ke.coerce.date(),createdBy:Ke.string(),organizationId:Ke.string(),name:Ke.string(),description:Ke.string().nullish(),enabled:Ke.boolean(),schemaVersion:Ke.string().describe("Schema version for steps"),parameters:Ke.string().array().nullish().describe("Parameter list"),parameterEnums:Ke.record(Ke.string(),Ke.string().array()).nullish(),defaultParameters:Ke.record(Ke.string(),Ke.string()).nullish(),defaultCacheKey:Ke.string().nullish(),defaultCacheTtl:Ke.number().nullish(),defaultCacheAllInvocations:Ke.boolean().nullish(),autoAuth:Ke.boolean().nullish(),advanced:Wu.nullish()}),K4=YS.extend({steps:Ke.lazy(()=>Pt.array())}),Y4=5*60*1e3,kI=Kt.merge(YS.omit({id:!0,createdAt:!0,createdBy:!0,organizationId:!0,enabled:!0}));import{formatInTimeZone as Z4}from"date-fns-tz";import{z as Pe}from"zod";var Nd=ad.extend({aiAction:Pe.boolean().optional(),stepLintSuggestions:Pe.boolean().optional(),agentConfig:Pe.record(Pe.string(),Pe.string()).optional(),aiFailureAnalysis:Pe.boolean().optional(),aiPageFiltering:Pe.boolean().optional().describe("rag v2 feature flag")}),Dd=Pe.object({fakerConstantSeed:Pe.boolean().optional()}),oJ=Pe.object({ai:Nd.optional(),githubAppInstallationId:Pe.number().nullish(),githubAppSummaryMessageEnabled:Pe.boolean().nullish(),githubReleaseAppInstallationId:Pe.number().nullish(),gitlabAppAccessToken:Pe.string().nullish(),gitlabAppBaseUrl:Pe.string().nullish(),qaseAccessToken:Pe.string().nullish(),testSuggestionsEnabled:Pe.boolean().nullish(),browser:Qu.optional(),advanced:Dd.optional()}),iJ=Pe.object({globalOverrides:Pe.record(Pe.string()).optional(),agentConfig:Pe.record(Pe.string(),Pe.string()).optional()}),aJ=Pe.record(Pe.string(),Pe.string()).nullish();import*as S from"zod";import{z as Ve}from"zod";var kd=(e=>(e.TEST_REVIEW="TEST_REVIEW",e))(kd||{});var UI=Ve.object({type:Ve.literal("DESCRIPTION_UPDATE"),thoughts:Ve.string()}),il=Ve.discriminatedUnion("type",[UI]),FI=Ve.object({testId:Ve.string(),name:Ve.string(),orgId:Ve.string(),runId:Ve.string(),steps:ot.array(),purpose:Ve.nativeEnum(kd),details:il.or(il.array()).optional()});var uJ=FI.pick({name:!0,orgId:!0}),BI=Ve.object({id:Ve.string(),name:Ve.string().nullish(),createdAt:Ve.string().pipe(Ve.coerce.date()).or(Ve.date()),organizationId:Ve.string(),schemaVersion:Ve.string(),runId:Ve.string().nullish(),purpose:Ve.nativeEnum(kd),details:il.or(il.array()).optional(),applied:Ve.boolean().nullish(),appliedAt:Ve.coerce.date().nullish()}),XS=BI.extend({steps:ot.array()});var al="x-momentic-cli-version",JS="x-momentic-client-mode",ZS="x-momentic-cli-type",QS="x-momentic-logger-tags",zI="x-momentic-main-branch-name",HI="x-momentic-branch-name",GI="x-momentic-commit-timestamp",VI="x-momentic-last-commit-on-main",jI="x-momentic-last-commit-on-main-timestamp",WI="x-momentic-merged-branch-name",ey="x-momentic-session-id",xJ=S.object({error:S.boolean(),reason:S.string(),message:S.string()}),MJ=yt.merge(cd),ty=bs,_J=yt.merge(cd);var PJ=yt.merge(Wf).extend({useConsensus:S.boolean().optional(),attemptNumber:S.number().optional()}),Ud=eh,IJ=yt.merge(qf),ry=gf,OJ=yt.merge($f),ny=mf,LJ=yt.merge(Gf),oy=df,NJ=yt.merge(Vf),iy=cf,DJ=yt.merge(jf);var kJ=yt.merge(Jf),UJ=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()}),ay=S.object({queuedTests:S.unknown().array(),runIds:S.string().uuid().array(),runGroupId:S.string().optional()});var FJ=S.string().array(),BJ=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")})]),sy=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"))}),$I=S.object({test:S.string().describe("test YAML"),modules:S.record(S.string().describe("moduleId"),S.string().describe("module YAML"))}),zJ=$I.array(),HJ=S.object({testId:S.string(),schemaVersion:S.string()}).merge(Nn);function Fd(r){let{gitMainBranch:e,gitBranchName:t,gitCommitTimestamp:n,lastCommitOnMainSha:o,lastCommitOnMainTimestamp:i}=r,a={};return e&&(a[zI]=encodeURIComponent(e)),t&&(a[HI]=encodeURIComponent(t)),n&&(a[GI]=n.toISOString()),o&&(a[VI]=encodeURIComponent(o)),i&&(a[jI]=i.toISOString()),r.mergedGitBranchName&&(a[WI]=encodeURIComponent(r.mergedGitBranchName)),a}var GJ=S.object({entries:S.array(vh),testId:S.string()}),VJ=S.object({entries:S.array(fS),testId:S.string()}),jJ=S.object({testId:S.string()});function ly(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 cy=ly(Ah),uy=ly(SS),dy=S.object({trigger:S.nativeEnum(Jt),status:S.nativeEnum(Te),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()}),WJ=S.object({id:S.string()}),py=S.object({status:S.nativeEnum(Te),updatedAt:S.coerce.date().optional(),finishedAt:S.coerce.date().optional()}),my=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(Jt),schemaVersion:S.string().optional(),section:S.nativeEnum(ks).optional(),resolvedInputs:S.record(S.string(),S.string()).optional(),quarantined:S.boolean().optional().default(!1),quarantinedReason:S.string().optional()}),$J=S.object({id:S.string()}),qI=sd.pick({id:!0,status:!0,testName:!0,testId:!0,test:!0,failureReason:!0,failureDetails:!0}),gy=qI.array(),hy=sd.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(),qJ=S.object({id:S.string()}),fy=S.object({status:S.nativeEnum(Te),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()}),KJ=S.object({screenshot:S.string()}),Sy=S.object({key:S.string()}),yy=S.object({orgId:S.string(),userId:S.string()}),by=S.array(Rf),YJ=S.record(S.string(),S.union([S.string(),S.boolean()])),XJ=S.object({paths:S.string().array(),env:S.string().optional(),urlOverride:S.string().optional(),customHeaders:S.record(S.string(),S.string()).optional()}),Ey=S.object({suiteRunIds:S.string().array(),runGroupIds:S.string().array()}),JJ=S.object({suiteRunIds:S.string().array()}),ZJ=Ff.array(),QJ=S.object({runGroupIds:S.string().array()}),KI=S.object({uploadUrl:S.string()}),e6=yt.merge(Kf),t6=yt.merge(Xf),r6=yt.merge(Yf),YI=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()}),XI=S.object({transactionId:S.string(),timestamp:S.string(),event:S.nativeEnum(na),properties:YI}),n6=XI.array(),Ty=XS.omit({steps:!0}).extend({steps:S.array(S.record(S.string(),S.unknown())).describe("unparsed ResolvedStep[]")}),o6=S.object({limit:S.number().max(10).optional(),afterTime:S.number().optional()}),vy=Df.array(),i6=S.object({applied:S.boolean().optional(),appliedAt:S.coerce.date().optional()}),Ay=KI.extend({id:S.string()}),a6=S.object({runGroupId:S.string().uuid().optional()}),wy=S.object({runGroupId:S.string().uuid()}),Ry=S.object({quarantined:S.object({testId:S.string().uuid(),quarantinedAt:S.coerce.date(),quarantinedBy:S.string().optional(),quarantinedReason:S.string()}).array()}),s6=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()}),l6=S.object({testName:S.string().optional(),reason:S.string().optional(),gitLocalUsername:S.string().optional(),gitLocalEmail:S.string().optional(),gitLocalName:S.string().optional()}),c6=yt.merge(rS),u6=yt.merge(nS),d6=S.object({apkToInstall:S.object({channel:S.string(),tag:S.string().optional()}).optional(),hostname:S.string().optional(),region:S.nativeEnum(Ws).optional()}),Cy=S.object({name:S.string(),webRtcUrl:S.string(),adbUrl:S.string(),token:S.string(),apkDownloadUrl:S.string().optional(),region:S.string().optional()}),p6=S.object({channel:S.string(),tag:S.string(),md5:S.string()}),xy=S.object({id:S.string(),uploadUrl:S.string().optional(),downloadUrl:S.string(),md5:S.string().optional()}),My=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 Y}from"zod";var _y=7,JI=3,h6=Y.object({localTestId:Y.string(),quarantinedAt:Y.date(),quarantinedBy:Y.string().optional(),quarantinedReason:Y.string(),quarantinedByGitEmail:Y.string().optional(),quarantinedByGitName:Y.string().optional(),quarantinedByGitUsername:Y.string().optional()}).or(Y.object({cloudTestId:Y.string(),quarantinedAt:Y.date(),quarantinedBy:Y.string().optional(),quarantinedReason:Y.string(),quarantinedByGitEmail:Y.string().optional(),quarantinedByGitName:Y.string().optional(),quarantinedByGitUsername:Y.string().optional()})),Py=(t=>(t.QUARANTINE="QUARANTINE",t.UNQUARANTINE="UNQUARANTINE",t))(Py||{});var Bd=Y.object({name:Y.string(),description:Y.string().nullish(),effect:Y.nativeEnum(Py),labels:Y.array(Y.string()).nullish(),githubRepository:Y.string().nullish(),gitlabProjectPath:Y.string().nullish(),gitBranchName:Y.string().nullish()}),ZI=Y.object({type:Y.literal("LAST_N_RUNS"),lastN:Y.number().min(JI)}),QI=Y.object({type:Y.literal("LAST_N_HOURS"),lastN:Y.number().min(1).max(_y*24)}),eO=Y.object({type:Y.literal("LAST_N_DAYS"),lastN:Y.number().min(1).max(_y)}),zd=Y.discriminatedUnion("type",[ZI,QI,eO]),tO=Y.object({flakeRateThreshold:Y.number().min(1).max(100),evaluationWindow:zd}),rO=Bd.extend({type:Y.literal("FLAKE_RATE"),config:tO}),nO=Y.object({passRateThreshold:Y.number().min(1).max(100),evaluationWindow:zd}),oO=Bd.extend({type:Y.literal("PASS_RATE"),config:nO}),iO=Y.object({failureCountThreshold:Y.number().min(0),evaluationWindow:zd}),aO=Bd.extend({type:Y.literal("FAILURE_COUNT"),config:iO}),f6=Y.discriminatedUnion("type",[rO,oO,aO]);import{z as Ye}from"zod";var b6=Ye.object({repositoriesIndexed:Ye.boolean(),indexingInProgress:Ye.boolean(),indexesOutdated:Ye.boolean()}),Iy=(a=>(a.Queued="queued",a.InProgress="in_progress",a.Completed="completed",a.Waiting="waiting",a.Requested="requested",a.Pending="pending",a))(Iy||{}),Oy=(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))(Oy||{}),E6=Ye.object({name:Ye.string(),status:Ye.nativeEnum(Iy),conclusion:Ye.nativeEnum(Oy).nullable()}),ga=Ye.object({sha:Ye.string(),message:Ye.string(),author:Ye.object({name:Ye.string().optional(),email:Ye.string().optional(),date:Ye.coerce.date().optional()}),committer:Ye.object({name:Ye.string().optional(),email:Ye.string().optional(),date:Ye.coerce.date().optional()})}),Hd=Ye.object({mergedBranch:Ye.string().optional()});import{z as Fe}from"zod";var Ly=Fe.object({orgId:Fe.string(),cacheKeys:Fe.string().array()}),A6=Fe.object({keyParams:Ly,clientMetadata:Fe.string(),lockAcquisitionTimeoutMs:Fe.number().optional()}),Ny=Fe.object({acquired:Fe.boolean(),acquiredByMetadata:Fe.string(),keyPrefix:Fe.string()}),w6=Fe.object({keyPrefix:Fe.string(),result:Fe.string(),ttlMs:Fe.number()}),R6=Fe.union([Fe.object({keyPrefix:Fe.string()}),Ly]),sO=Fe.object({remainingTtlMs:Fe.number(),value:Fe.string().nullish()}),C6=Fe.object({results:Fe.record(Fe.string(),sO),activeLocks:Fe.string().array()});var x6=5*60*1e3;var I6=90*24*60*60*1e3,O6=7*24*60*60*1e3;import{z as Dy}from"zod";var D6=Dy.object({quarantineNotifications:Dy.string().nullish()});import{z as pt}from"zod";var lO=pt.object({version:pt.string(),json:pt.record(pt.unknown()),hash:pt.string()}),ky=pt.record(pt.unknown()),B6=pt.object({newSvgs:pt.array(lO),metadata:ky.optional()}),cO=pt.object({version:pt.string(),json:pt.record(pt.unknown()).nullish(),hash:pt.string(),description:pt.string().nullish(),metadata:ky.nullish()}),Uy=pt.record(pt.string().describe("icon hash"),cO);import{z as ze}from"zod";var Gd=ze.object({assertion:ze.string().describe("A human readable assertion that evaluates to either true or false depending on the state of the system.")}),uO=ze.object({instruction:ze.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:Gd.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.")}),Fy=uO.extend({subSteps:ze.lazy(()=>Fy.array().optional()).describe("More granular steps to be take to achieve the current step's higher level objective.")}),By=ze.object({name:ze.string().describe("Short name describing the test plan"),description:ze.string().nullish().transform(r=>r??void 0).describe("Longer form description of the high level goal of the test plan")}),zy=By.extend({id:ze.string(),createdAt:ze.coerce.date(),updatedAt:ze.coerce.date(),updatedBy:ze.string(),createdBy:ze.string(),test:ze.object({id:ze.string(),name:ze.string()}).nullish().transform(r=>r??void 0)}),V6=zy.extend({testGenRuns:ze.tuple([]).or(ze.tuple([ze.object({id:ze.string(),startedAt:ze.coerce.date(),status:ze.nativeEnum(Te)})]))}),Hy=ze.object({preConditions:Gd.array().nullish().transform(r=>r??[]),postConditions:Gd.array().nullish().transform(r=>r??[]),steps:Fy.array().nullish().transform(r=>r??[])}),j6=zy.extend({plan:Hy.nullish().transform(r=>r??{preConditions:[],postConditions:[],steps:[]})}),dO=By.extend({plan:Hy.nullish().transform(r=>r??{preConditions:[],postConditions:[],steps:[]})}),W6=dO.array().nullish().transform(r=>r??[]);import{validator as pO}from"@exodus/schemasafe";function Gy(r){let e;try{e=JSON.parse(r)}catch(t){return`The schema is not valid JSON. ${t}`}try{pO(e)}catch(t){return`The schema is not a valid JSON schema. ${t}`}}var Vy=r=>{r.extraHeaders&&(r.extraHeaders=Object.fromEntries(Object.entries(r.extraHeaders).filter(([e,t])=>e.trim()&&t.trim())))};var sl=class{async prepareGoldenScreenshotForComparison(e,t,n){return n}};import{z as l8}from"zod";var ll=class{async resolveEntries(){}async saveEntries(){}};import{z as Vd}from"zod";var jy=Vd.object({parentStepIdChain:Vd.array(Vd.string()),result:tr});import{z as $}from"zod";var mO=$.object({step:ot,status:$.nativeEnum(He),startedAt:$.coerce.date(),finishedAt:$.coerce.date().optional(),healMetadata:$.object({healType:$.nativeEnum(Ji).or($.literal("AI")),healedAt:$.coerce.date()}).optional(),beforeSnapshotId:$.string().uuid().optional(),afterSnapshotId:$.string().uuid().optional(),message:$.string().optional()}),gO=mO.extend({finishedAt:$.coerce.date().optional().transform(r=>r??new Date)}),C8=gO.extend({step:$.unknown()}),Wy="1.0.0",jd=fy.extend({id:$.string().uuid().optional(),startedAt:$.coerce.date(),runAttemptSchemaVersion:$.string().optional(),schemaVersion:$.string().optional().default("1.0.19"),results:$.record($.string(),$.unknown()).array().optional(),beforeResults:$.record($.string(),$.unknown()).array().optional(),afterResults:$.record($.string(),$.unknown()).array().optional(),activeVideos:$.array($.object({videoName:$.string(),timestamp:$.coerce.date()})).optional()}),$y=jd.extend({finishedAt:$.coerce.date().optional().transform(r=>r??new Date)}),x8=jd.merge(Zi),M8=$y.merge(Zi),qy=$.object({results:$.array(tr),beforeResults:$.array(tr).optional(),afterResults:$.array(tr).optional()}),_8=jd.merge(qy),P8=$y.merge(qy),hO=hy.merge(my).extend({executionType:$.nativeEnum(No).optional().default("WEB"),testId:$.string().uuid(),testDescription:$.string().optional(),runGroupId:$.string().uuid(),status:$.nativeEnum(Te),startedAt:$.coerce.date(),attempts:$.number(),failureRecoveryDetails:$.record($.unknown()).optional()}),I8=hO.extend({finishedAt:$.coerce.date().optional().transform(r=>r??new Date)}),fO=dy.merge(py).extend({id:$.string().uuid().optional(),startedAt:$.coerce.date(),cliVersion:$.string(),labels:$.string().array().optional().default([])}),cl=fO.extend({updatedAt:$.coerce.date().optional().transform(r=>r??new Date),finishedAt:$.coerce.date().optional().transform(r=>r??new Date)});import{confirm as SO,input as yO}from"@inquirer/prompts";import{existsSync as iZ,mkdirSync as aZ,statSync as bO}from"fs";var jn=!!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;var EO=!1,Ky=(()=>{try{return bO("/.dockerenv"),!0}catch{return!1}})();async function ul(r){return jn||EO||Ky?!0:(await R.flush(),await new Promise(t=>setTimeout(t,100)),await SO({message:r}))}async function Yy(r,e){return jn||Ky?e:(await yO({message:r,default:e})).trim()||e}import Vo,{supportsColor as IO}from"chalk";import{Console as Xy}from"console";import{format as ha}from"util";var Wd=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}},dl=class r extends Xy{_buffer=[];_groupDepth=0;Console=Xy;constructor(){super({write:e=>(r.write(this._buffer,"log",e),!0)})}static write(e,t,n,o=2){let i=new Wd(void 0,r.write).stack;if(!i)return e;let a=i.split(`
19
+ `)),console.log(" ",t(l))}}setMinLevel(e){typeof e=="string"?this.minLogLevel=ga[e]:this.minLogLevel=e}log(...e){this.logWithLevel(30,Mr.reset,...e)}info(...e){this.logWithLevel(30,Mr.white,...e)}debug(...e){this.logWithLevel(20,Mr.dim,...e)}warn(...e){this.logWithLevel(40,Mr.yellow,...e)}error(...e){this.logWithLevel(50,Mr.red,...e)}success(...e){this.logWithLevel(1/0,Mr.green,...e)}dimmed(...e){this.logWithLevel(30,Mr.dim,...e)}underline(...e){this.logWithLevel(40,Mr.underline,...e)}bold(...e){this.logWithLevel(40,Mr.bold,...e)}grey(...e){this.logWithLevel(20,Mr.grey,...e)}child(e){return new r(this.minLogLevel,{...this.logBindings,...e})}async flush(){}bindings(){return this.logBindings}},kd=class{debug(){}info(){}warn(){}error(){}success(){}dimmed(){}underline(){}bold(){}grey(){}child(){return this}async flush(){}bindings(){return{}}},z4=new kd,UI=typeof window>"u"&&typeof process<"u"&&il.safeParse(process?.env?.MOMENTIC_DEV_LOG_LEVEL).success?il.parse(process.env.MOMENTIC_DEV_LOG_LEVEL):30,w=new Dd(UI,{}),gn={info:()=>{},error:()=>{},debug:()=>{},warn:()=>{},child:()=>gn,flush:async()=>{},bindings:()=>({})},ol={},al=({logger:r,logKey:e,maxCount:t,intervalMs:n},o,i,...a)=>{let l=ol[e];l?clearTimeout(l.timer):(l={count:0,totalCount:0},ol[e]=l),l.totalCount++,l.count<t&&(l.count++,r.debug(o,i,...a)),l.timer=setTimeout(()=>{let c=ol[e];c?.totalCount!==c?.count&&r.debug({logKey:e,totalCount:c?.totalCount,count:c?.count},`Debug logs were rate-limited for ${e}`),delete ol[e]},n)};import{z as be}from"zod";var FI=be.array(Ho.extend({id:be.string(),name:be.string(),description:be.string().optional(),labels:be.string().array().optional()})),BI=be.array(Ho.extend({id:be.string(),name:be.string(),description:be.string().optional(),content:Xi})),KS=be.object({name:be.string(),description:be.string().optional(),settings:ma.optional(),pathSegments:be.string().array()}),$4=be.object({id:be.string(),fileName:be.string(),fullPath:be.string(),relativeFilePath:be.string().describe("relative to project root")});var YS=be.object({steps:pa.array().optional(),settings:ma.optional()}),q4=be.object({message:be.literal("ok")}),XS=be.object({tag:be.string(),channel:be.string(),filePath:be.string()}),K4=be.object({tests:FI,modules:BI,labels:be.string().array()}),JS=be.object({name:be.string(),description:be.string(),enabled:be.boolean()}).partial();import{z as Ke}from"zod";var ZS=Ke.object({id:Ke.string(),createdAt:Ke.coerce.date(),createdBy:Ke.string(),organizationId:Ke.string(),name:Ke.string(),description:Ke.string().nullish(),enabled:Ke.boolean(),schemaVersion:Ke.string().describe("Schema version for steps"),parameters:Ke.string().array().nullish().describe("Parameter list"),parameterEnums:Ke.record(Ke.string(),Ke.string().array()).nullish(),defaultParameters:Ke.record(Ke.string(),Ke.string()).nullish(),defaultCacheKey:Ke.string().nullish(),defaultCacheTtl:Ke.number().nullish(),defaultCacheAllInvocations:Ke.boolean().nullish(),autoAuth:Ke.boolean().nullish(),advanced:Yu.nullish()}),nJ=ZS.extend({steps:Ke.lazy(()=>Pt.array())}),oJ=5*60*1e3,zI=Kt.merge(ZS.omit({id:!0,createdAt:!0,createdBy:!0,organizationId:!0,enabled:!0}));import{formatInTimeZone as sJ}from"date-fns-tz";import{z as we}from"zod";var Ud=cd.extend({aiAction:we.boolean().optional(),stepLintSuggestions:we.boolean().optional(),agentConfig:we.record(we.string(),we.string()).optional(),aiFailureAnalysis:we.boolean().optional(),aiPageFiltering:we.boolean().optional().describe("rag v2 feature flag")}),HI=we.object({cliOnly:we.boolean().optional()}),Fd=we.object({fakerConstantSeed:we.boolean().optional()}),mJ=we.object({ai:Ud.optional(),githubAppInstallationId:we.number().nullish(),githubAppSummaryMessageEnabled:we.boolean().nullish(),githubReleaseAppInstallationId:we.number().nullish(),gitlabAppAccessToken:we.string().nullish(),gitlabAppBaseUrl:we.string().nullish(),qaseAccessToken:we.string().nullish(),testSuggestionsEnabled:we.boolean().nullish(),browser:rd.optional(),internal:HI.optional(),advanced:Fd.optional()}),gJ=we.object({globalOverrides:we.record(we.string()).optional(),agentConfig:we.record(we.string(),we.string()).optional()}),hJ=we.record(we.string(),we.string()).nullish();import*as S from"zod";import{z as Ve}from"zod";var Bd=(e=>(e.TEST_REVIEW="TEST_REVIEW",e))(Bd||{});var GI=Ve.object({type:Ve.literal("DESCRIPTION_UPDATE"),thoughts:Ve.string()}),sl=Ve.discriminatedUnion("type",[GI]),VI=Ve.object({testId:Ve.string(),name:Ve.string(),orgId:Ve.string(),runId:Ve.string(),steps:ot.array(),purpose:Ve.nativeEnum(Bd),details:sl.or(sl.array()).optional()});var bJ=VI.pick({name:!0,orgId:!0}),jI=Ve.object({id:Ve.string(),name:Ve.string().nullish(),createdAt:Ve.string().pipe(Ve.coerce.date()).or(Ve.date()),organizationId:Ve.string(),schemaVersion:Ve.string(),runId:Ve.string().nullish(),purpose:Ve.nativeEnum(Bd),details:sl.or(sl.array()).optional(),applied:Ve.boolean().nullish(),appliedAt:Ve.coerce.date().nullish()}),QS=jI.extend({steps:ot.array()});var ll="x-momentic-cli-version",ey="x-momentic-client-mode",ty="x-momentic-cli-type",ry="x-momentic-logger-tags",WI="x-momentic-main-branch-name",$I="x-momentic-branch-name",qI="x-momentic-commit-timestamp",KI="x-momentic-last-commit-on-main",YI="x-momentic-last-commit-on-main-timestamp",XI="x-momentic-merged-branch-name",ny="x-momentic-session-id",kJ=S.object({error:S.boolean(),reason:S.string(),message:S.string()}),UJ=pt.merge(pd),oy=Ts,FJ=pt.merge(pd);var BJ=pt.merge(qf).extend({useConsensus:S.boolean().optional(),attemptNumber:S.number().optional()}),zd=th,zJ=pt.merge(Yf),iy=gf,HJ=pt.merge(Kf),ay=mf,GJ=pt.merge(jf),sy=df,VJ=pt.merge(Wf),ly=cf,jJ=pt.merge($f);var WJ=pt.merge(Qf),$J=pt.merge(eS),qJ=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()}),cy=S.object({queuedTests:S.unknown().array(),runIds:S.string().uuid().array(),runGroupId:S.string().optional()});var KJ=S.string().array(),YJ=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")})]),uy=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"))}),JI=S.object({test:S.string().describe("test YAML"),modules:S.record(S.string().describe("moduleId"),S.string().describe("module YAML"))}),XJ=JI.array(),JJ=S.object({testId:S.string(),schemaVersion:S.string()}).merge(Dn);function Hd(r){let{gitMainBranch:e,gitBranchName:t,gitCommitTimestamp:n,lastCommitOnMainSha:o,lastCommitOnMainTimestamp:i}=r,a={};return e&&(a[WI]=encodeURIComponent(e)),t&&(a[$I]=encodeURIComponent(t)),n&&(a[qI]=n.toISOString()),o&&(a[KI]=encodeURIComponent(o)),i&&(a[YI]=i.toISOString()),r.mergedGitBranchName&&(a[XI]=encodeURIComponent(r.mergedGitBranchName)),a}var ZJ=S.object({entries:S.array(vh),testId:S.string()}),QJ=S.object({entries:S.array(bS),testId:S.string()}),e6=S.object({testId:S.string()});function dy(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 py=dy(Ah),my=dy(ES),gy=S.object({trigger:S.nativeEnum(Jt),status:S.nativeEnum(ve),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()}),t6=S.object({id:S.string()}),hy=S.object({status:S.nativeEnum(ve),updatedAt:S.coerce.date().optional(),finishedAt:S.coerce.date().optional()}),fy=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(Jt),schemaVersion:S.string().optional(),section:S.nativeEnum(Fs).optional(),resolvedInputs:S.record(S.string(),S.string()).optional(),quarantined:S.boolean().optional().default(!1),quarantinedReason:S.string().optional()}),r6=S.object({id:S.string()}),ZI=ud.pick({id:!0,status:!0,testName:!0,testId:!0,test:!0,failureReason:!0,failureDetails:!0}),Sy=ZI.array(),yy=ud.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(),n6=S.object({id:S.string()}),by=S.object({status:S.nativeEnum(ve),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()}),o6=S.object({screenshot:S.string()}),Ey=S.object({key:S.string()}),Ty=S.object({orgId:S.string(),userId:S.string()}),vy=S.array(xf),i6=S.record(S.string(),S.union([S.string(),S.boolean()])),a6=S.object({paths:S.string().array(),env:S.string().optional(),urlOverride:S.string().optional(),customHeaders:S.record(S.string(),S.string()).optional()}),Ay=S.object({suiteRunIds:S.string().array(),runGroupIds:S.string().array()}),s6=S.object({suiteRunIds:S.string().array()}),l6=zf.array(),c6=S.object({runGroupIds:S.string().array()}),QI=S.object({uploadUrl:S.string()}),u6=pt.merge(Xf),d6=pt.merge(Zf),p6=pt.merge(Jf),eO=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()}),tO=S.object({transactionId:S.string(),timestamp:S.string(),event:S.nativeEnum(oa),properties:eO}),m6=tO.array(),wy=QS.omit({steps:!0}).extend({steps:S.array(S.record(S.string(),S.unknown())).describe("unparsed ResolvedStep[]")}),g6=S.object({limit:S.number().max(10).optional(),afterTime:S.number().optional()}),Ry=Uf.array(),h6=S.object({applied:S.boolean().optional(),appliedAt:S.coerce.date().optional()}),Cy=QI.extend({id:S.string()}),f6=S.object({runGroupId:S.string().uuid().optional()}),xy=S.object({runGroupId:S.string().uuid()}),My=S.object({quarantined:S.object({testId:S.string().uuid(),quarantinedAt:S.coerce.date(),quarantinedBy:S.string().optional(),quarantinedReason:S.string()}).array()}),S6=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()}),y6=S.object({testName:S.string().optional(),reason:S.string().optional(),gitLocalUsername:S.string().optional(),gitLocalEmail:S.string().optional(),gitLocalName:S.string().optional()}),b6=pt.merge(iS),E6=pt.merge(aS),T6=S.object({apkToInstall:S.object({channel:S.string(),tag:S.string().optional()}).optional(),hostname:S.string().optional(),region:S.nativeEnum(qs).optional()}),_y=S.object({name:S.string(),webRtcUrl:S.string(),adbUrl:S.string(),token:S.string(),apkDownloadUrl:S.string().optional(),region:S.string().optional()}),v6=S.object({channel:S.string(),tag:S.string(),md5:S.string()}),Py=S.object({id:S.string(),uploadUrl:S.string().optional(),downloadUrl:S.string(),md5:S.string().optional()}),Iy=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 X}from"zod";var Oy=7,rO=3,R6=X.object({localTestId:X.string(),quarantinedAt:X.date(),quarantinedBy:X.string().optional(),quarantinedReason:X.string(),quarantinedByGitEmail:X.string().optional(),quarantinedByGitName:X.string().optional(),quarantinedByGitUsername:X.string().optional()}).or(X.object({cloudTestId:X.string(),quarantinedAt:X.date(),quarantinedBy:X.string().optional(),quarantinedReason:X.string(),quarantinedByGitEmail:X.string().optional(),quarantinedByGitName:X.string().optional(),quarantinedByGitUsername:X.string().optional()})),Ly=(t=>(t.QUARANTINE="QUARANTINE",t.UNQUARANTINE="UNQUARANTINE",t))(Ly||{});var Gd=X.object({name:X.string(),description:X.string().nullish(),effect:X.nativeEnum(Ly),labels:X.array(X.string()).nullish(),githubRepository:X.string().nullish(),gitlabProjectPath:X.string().nullish(),gitBranchName:X.string().nullish()}),nO=X.object({type:X.literal("LAST_N_RUNS"),lastN:X.number().min(rO)}),oO=X.object({type:X.literal("LAST_N_HOURS"),lastN:X.number().min(1).max(Oy*24)}),iO=X.object({type:X.literal("LAST_N_DAYS"),lastN:X.number().min(1).max(Oy)}),Vd=X.discriminatedUnion("type",[nO,oO,iO]),aO=X.object({flakeRateThreshold:X.number().min(1).max(100),evaluationWindow:Vd}),sO=Gd.extend({type:X.literal("FLAKE_RATE"),config:aO}),lO=X.object({passRateThreshold:X.number().min(1).max(100),evaluationWindow:Vd}),cO=Gd.extend({type:X.literal("PASS_RATE"),config:lO}),uO=X.object({failureCountThreshold:X.number().min(0),evaluationWindow:Vd}),dO=Gd.extend({type:X.literal("FAILURE_COUNT"),config:uO}),C6=X.discriminatedUnion("type",[sO,cO,dO]);import{z as Ye}from"zod";var _6=Ye.object({repositoriesIndexed:Ye.boolean(),indexingInProgress:Ye.boolean(),indexesOutdated:Ye.boolean()}),Ny=(a=>(a.Queued="queued",a.InProgress="in_progress",a.Completed="completed",a.Waiting="waiting",a.Requested="requested",a.Pending="pending",a))(Ny||{}),Dy=(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))(Dy||{}),P6=Ye.object({name:Ye.string(),status:Ye.nativeEnum(Ny),conclusion:Ye.nativeEnum(Dy).nullable()}),ha=Ye.object({sha:Ye.string(),message:Ye.string(),author:Ye.object({name:Ye.string().optional(),email:Ye.string().optional(),date:Ye.coerce.date().optional()}),committer:Ye.object({name:Ye.string().optional(),email:Ye.string().optional(),date:Ye.coerce.date().optional()})}),jd=Ye.object({mergedBranch:Ye.string().optional()});import{z as Fe}from"zod";var ky=Fe.object({orgId:Fe.string(),cacheKeys:Fe.string().array()}),L6=Fe.object({keyParams:ky,clientMetadata:Fe.string(),lockAcquisitionTimeoutMs:Fe.number().optional()}),Uy=Fe.object({acquired:Fe.boolean(),acquiredByMetadata:Fe.string(),keyPrefix:Fe.string()}),N6=Fe.object({keyPrefix:Fe.string(),result:Fe.string(),ttlMs:Fe.number()}),D6=Fe.union([Fe.object({keyPrefix:Fe.string()}),ky]),pO=Fe.object({remainingTtlMs:Fe.number(),value:Fe.string().nullish()}),k6=Fe.object({results:Fe.record(Fe.string(),pO),activeLocks:Fe.string().array()});var U6=5*60*1e3;var H6=90*24*60*60*1e3,G6=7*24*60*60*1e3;import{z as Fy}from"zod";var W6=Fy.object({quarantineNotifications:Fy.string().nullish()});import{z as mt}from"zod";var mO=mt.object({version:mt.string(),json:mt.record(mt.unknown()),hash:mt.string()}),By=mt.record(mt.unknown()),Y6=mt.object({newSvgs:mt.array(mO),metadata:By.optional()}),gO=mt.object({version:mt.string(),json:mt.record(mt.unknown()).nullish(),hash:mt.string(),description:mt.string().nullish(),metadata:By.nullish()}),zy=mt.record(mt.string().describe("icon hash"),gO);import{z as ze}from"zod";var Wd=ze.object({assertion:ze.string().describe("A human readable assertion that evaluates to either true or false depending on the state of the system.")}),hO=ze.object({instruction:ze.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:Wd.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.")}),Hy=hO.extend({subSteps:ze.lazy(()=>Hy.array().optional()).describe("More granular steps to be take to achieve the current step's higher level objective.")}),Gy=ze.object({name:ze.string().describe("Short name describing the test plan"),description:ze.string().nullish().transform(r=>r??void 0).describe("Longer form description of the high level goal of the test plan")}),Vy=Gy.extend({id:ze.string(),createdAt:ze.coerce.date(),updatedAt:ze.coerce.date(),updatedBy:ze.string(),createdBy:ze.string(),test:ze.object({id:ze.string(),name:ze.string()}).nullish().transform(r=>r??void 0)}),Q6=Vy.extend({testGenRuns:ze.tuple([]).or(ze.tuple([ze.object({id:ze.string(),startedAt:ze.coerce.date(),status:ze.nativeEnum(ve)})]))}),jy=ze.object({preConditions:Wd.array().nullish().transform(r=>r??[]),postConditions:Wd.array().nullish().transform(r=>r??[]),steps:Hy.array().nullish().transform(r=>r??[])}),e8=Vy.extend({plan:jy.nullish().transform(r=>r??{preConditions:[],postConditions:[],steps:[]})}),fO=Gy.extend({plan:jy.nullish().transform(r=>r??{preConditions:[],postConditions:[],steps:[]})}),t8=fO.array().nullish().transform(r=>r??[]);import{validator as SO}from"@exodus/schemasafe";function Wy(r){let e;try{e=JSON.parse(r)}catch(t){return`The schema is not valid JSON. ${t}`}try{SO(e)}catch(t){return`The schema is not a valid JSON schema. ${t}`}}var $y=r=>{r.extraHeaders&&(r.extraHeaders=Object.fromEntries(Object.entries(r.extraHeaders).filter(([e,t])=>e.trim()&&t.trim())))};var cl=class{async prepareGoldenScreenshotForComparison(e,t,n){return n}};import{z as y8}from"zod";var ul=class{async resolveEntries(){}async saveEntries(){}};import{z as $d}from"zod";var qy=$d.object({parentStepIdChain:$d.array($d.string()),result:tr});import{z as $}from"zod";var yO=$.object({step:ot,status:$.nativeEnum(He),startedAt:$.coerce.date(),finishedAt:$.coerce.date().optional(),healMetadata:$.object({healType:$.nativeEnum(Zi).or($.literal("AI")),healedAt:$.coerce.date()}).optional(),beforeSnapshotId:$.string().uuid().optional(),afterSnapshotId:$.string().uuid().optional(),message:$.string().optional()}),bO=yO.extend({finishedAt:$.coerce.date().optional().transform(r=>r??new Date)}),k8=bO.extend({step:$.unknown()}),Ky="1.0.0",qd=by.extend({id:$.string().uuid().optional(),startedAt:$.coerce.date(),runAttemptSchemaVersion:$.string().optional(),schemaVersion:$.string().optional().default("1.0.19"),results:$.record($.string(),$.unknown()).array().optional(),beforeResults:$.record($.string(),$.unknown()).array().optional(),afterResults:$.record($.string(),$.unknown()).array().optional(),activeVideos:$.array($.object({videoName:$.string(),timestamp:$.coerce.date()})).optional()}),Yy=qd.extend({finishedAt:$.coerce.date().optional().transform(r=>r??new Date)}),U8=qd.merge(Qi),F8=Yy.merge(Qi),Xy=$.object({results:$.array(tr),beforeResults:$.array(tr).optional(),afterResults:$.array(tr).optional()}),B8=qd.merge(Xy),z8=Yy.merge(Xy),EO=yy.merge(fy).extend({executionType:$.nativeEnum(Do).optional().default("WEB"),testId:$.string().uuid(),testDescription:$.string().optional(),runGroupId:$.string().uuid(),status:$.nativeEnum(ve),startedAt:$.coerce.date(),attempts:$.number(),failureRecoveryDetails:$.record($.unknown()).optional()}),H8=EO.extend({finishedAt:$.coerce.date().optional().transform(r=>r??new Date)}),TO=gy.merge(hy).extend({id:$.string().uuid().optional(),startedAt:$.coerce.date(),cliVersion:$.string(),labels:$.string().array().optional().default([])}),dl=TO.extend({updatedAt:$.coerce.date().optional().transform(r=>r??new Date),finishedAt:$.coerce.date().optional().transform(r=>r??new Date)});import{confirm as vO,input as AO}from"@inquirer/prompts";import{existsSync as hZ,mkdirSync as fZ,statSync as wO}from"fs";var Wn=!!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;var RO=!1,Jy=(()=>{try{return wO("/.dockerenv"),!0}catch{return!1}})();async function pl(r){return Wn||RO||Jy?!0:(await w.flush(),await new Promise(t=>setTimeout(t,100)),await vO({message:r}))}async function Zy(r,e){return Wn||Jy?e:(await AO({message:r,default:e})).trim()||e}import jo,{supportsColor as kO}from"chalk";import{Console as Qy}from"console";import{format as fa}from"util";var Kd=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}},ml=class r extends Qy{_buffer=[];_groupDepth=0;Console=Qy;constructor(){super({write:e=>(r.write(this._buffer,"log",e),!0)})}static write(e,t,n,o=2){let i=new Kd(void 0,r.write).stack;if(!i)return e;let a=i.split(`
20
20
  `).slice(o).filter(Boolean).join(`
21
- `);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",ha(e,...t))}error(e,...t){this._log("error",ha(e,...t))}info(e,...t){this._log("info",ha(e,...t))}log(e,...t){this._log("log",ha(e,...t))}warn(e,...t){this._log("warn",ha(e,...t))}getBuffer(){return this._buffer.length>0?this._buffer:void 0}};function Jy(r){let e=globalThis.console,t=new dl;globalThis.console=t;try{r()}finally{let o=t.getBuffer()?.map(i=>i.message).join(`
21
+ `);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",fa(e,...t))}error(e,...t){this._log("error",fa(e,...t))}info(e,...t){this._log("info",fa(e,...t))}log(e,...t){this._log("log",fa(e,...t))}warn(e,...t){this._log("warn",fa(e,...t))}getBuffer(){return this._buffer.length>0?this._buffer:void 0}};function eb(r){let e=globalThis.console,t=new ml;globalThis.console=t;try{r()}finally{let o=t.getBuffer()?.map(i=>i.message).join(`
22
22
  `);process.stderr.write(`${o}
23
- `),globalThis.console=e}}var $d=" ".repeat(6);import TO from"fetch-retry";import vO from"os";import Zy,{multistream as AO}from"pino";import wO from"pino-pretty";import RO from"pino-std-serializers";var Ho=new Map,CO=!0,Qy="Log throttle exceeded",xO=100,MO=5e3,_O=TO(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}}),qd=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??vO.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=CO?Zy(a):Zy(a,AO([{stream:wO({colorize:!0})}]))}child(e){return new r({bindings:{...this.bindingAttributes,...e},hostname:this.hostname,disableConsoleLogs:this.disableConsoleLogs,flushIntervalMs:this.flushIntervalMs,maxBatchSize:this.maxBatchSize})}async flush(){await this.flushBuffer(),this.disableConsoleLogs||this.consoleLogger.flush()}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 _O(this.site,{method:"POST",headers:{"Content-Type":"application/json","signoz-access-token":"CumAaTMUcwjt05OddAmefKgshbhfRmWxzxih"},body:Vn(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 Momentic's observability provider, continuing...")}}shouldAllowLog(e){if(e===Qy)return!0;let t=Date.now();return t-this.lastWindowStart>MO&&(this.logsInCurrentWindow=0,this.droppedLogsInWindow&&this.log("error",void 0,Qy),this.droppedLogsInWindow=!1,this.lastWindowStart=t),this.logsInCurrentWindow<xO?(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(ma[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=RO.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:VS({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,Ho.set("app",this),Ho.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=jS[e]):(this.minLevelValue=ma[e],this.consoleLogger.level=e)}enableConsoleLogs(){this.disableConsoleLogs=!1}},Go=({app:r,hostname:e,disableConsoleLogs:t})=>(Ho.has(r)||Ho.set(r,new qd({bindings:{app:r},hostname:e,disableConsoleLogs:t})),Ho.get(r));async function eb(){await Promise.all([...Ho.values()].map(r=>r.flush()))}import{hostname as PO}from"os";var rr=Go({app:"cli",hostname:PO(),disableConsoleLogs:!0}).child({cliVersion:"0.4.0"});function Kd(r){if(!r)return;r=r.toLowerCase();let e=nl.safeParse(r);if(e.success)return R.setMinLevel(e.data),e.data}function tb({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 Jy(()=>{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 fa=({status:r,testLogRef:e,getRunningTestsCount:t,getTotalTestsCount:n,additionalText:o})=>{r=r.toUpperCase();let i=r,a;r.includes("FAIL")?(i=Vo.bgRed.white("FAIL"),a=3):r.includes("PASS")?(i=Vo.bgGreen.white("PASS"),a=3):r.includes("START")?(i=Vo.bgBlue.white("START"),a=2):r.includes("CANCEL")?(i=Vo.bgRgb(191,68,11).white("CANCEL"),a=1):r.includes("RETRY")?(i=Vo.bgRgb(191,68,11).white("RETRY"),a=2):r.includes("RUN")||r.includes("PROG")?(i=Vo.bgMagenta.white("RUNNING"),a=0):(R.warn(`Unknown status tried to be logged in run test locally: ${r}`),a=0),IO||(i=`${i}`),R.log(`${i}${" ".repeat(a)} ${e} ${o?`${o} `:""}(${t()}/${n()})`)};import OO from"fs";import{tmpdir as LO}from"os";import NO from"path";import{registry as Sa}from"playwright-core/lib/server";import rb from"proper-lockfile";var nb=NO.join(LO(),"momenticBrowserInstallation");var Yd=["chrome","chromium","chrome-for-testing","ffmpeg"],DO={Chromium:"chromium","Google Chrome":"chrome","Chrome for Testing":"chrome-for-testing"},ob={chrome:"chrome",chromium:"chromium","chrome-for-testing":"chromium-headless-shell",ffmpeg:"ffmpeg"};function ib(r){let e=ob[DO[r]??""]??"",t=Sa.findExecutable(e);return!t||t.installType==="none"?!1:Xd(t)}function Xd(r){let e=r.executablePath();return OO.existsSync(e)}function kO(r,e){let t=ob[r];if(!t)throw new Error(`Requested install of unknown browser type ${r}`);let n=Sa.findExecutable(t);if(!n||n.installType==="none")throw new Error(`Requested install of unknown browser type ${r}`);if(!(!e&&Xd(n)))return n}async function UO({browser:r,force:e}){let t=kO(r,e);if(!t){R.info(`Browser '${r}' is already installed, skipping...`);return}R.info(`Installing browser '${r}'...`);try{await Sa.installDeps([t],!1),await Sa.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=Sa.findExecutable(r),i=5*60*1e3,a=Date.now();for(;Date.now()-a<i&&!Xd(o);)R.info("Waiting for browser to finish installing..."),await new Promise(l=>setTimeout(l,5e3))}else throw n}}async function pl({rawBrowsers:r,force:e=!1,all:t=!1}){let n=t?Yd:Array.from(new Set(r));try{await rb.lock(nb,{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 UO({browser:i,force:e})}catch(a){o=a,R.error(`Failed to install the ${i} browser: ${a}`)}}finally{await rb.unlock(nb,{realpath:!1})}if(o)throw o}import{createServer as FO}from"http";async function ml(r,e,t=30){for(let n=0;n<t;n+=1){let o=r+n;if(await gl(o))return o}R.error(`Could not find an available port for ${e} starting from ${r} after ${t} attempts`),process.exit(1)}async function gl(r){return new Promise((e,t)=>{let n=FO();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 dQ from"blocked-at";import mQ from"why-is-node-running";import m0 from"fs";import{tmpdir as g0}from"os";import h0 from"path";import{remote as f0}from"webdriverio";import{createInstanceClient as s0}from"@limrun/api";import{execSync as l0}from"child_process";import wQ,{multistream as CQ}from"pino";import MQ from"pino-pretty";import{PostHog as HQ}from"posthog-node";var mn=class extends Error{constructor(e){super(e),this.name="TimeoutError"}};var ab=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 F(r,e){let{milliseconds:t,fallback:n,message:o,customTimers:i={setTimeout,clearTimeout}}=e,a;if(typeof t!="number"||Math.sign(t)!==1)throw new TypeError(`Expected \`milliseconds\` to be a positive number, got \`${t}\``);return new Promise((l,c)=>{let s;if(e.signal){let{signal:p}=e;if(p.aborted)return c(ab(p));s=()=>c(ab(p)),p.addEventListener("abort",s,{once:!0})}let u=()=>{if(e.signal&&e.signal.removeEventListener("abort",s),n)try{l(n())}catch(p){c(p)}else{typeof r.cancel=="function"&&Promise.resolve().then(()=>r.cancel()).catch(()=>{});let p=o instanceof Error?o:new mn(o??`Promise timed out after ${t}ms`);c(p)}};t<1/0&&(a=i.setTimeout(u,t));let d=()=>{i.clearTimeout(a),e.signal&&e.signal.removeEventListener("abort",s)};Promise.resolve(r).then(p=>{d(),l(p)}).catch(p=>{d(),c(p)})})}import{PostHog as XQ}from"posthog-node";import{execSync as BO}from"child_process";import jo from"os";import zO from"v8";var sb,xr,cb=jo.platform(),HO=jo.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),{}),lb=r=>{try{let e=!1,t=GO(),n=VO(),o=`${Math.round(t.freePercentage*100)}%`;t.freePercentage<.05&&(e=!0);let i=`${n?Math.round(n.idle):"unknown"}%`;n&&n?.total>80&&(e=!0);let a=zO.getHeapStatistics(),l=a.used_heap_size,c=a.heap_size_limit;l/c>.9&&(e=!0),e?(r.warn({memory:t,cpu:n,heapStats:a},"Critical resource usage metrics detected"),jn&&R.warn(`Low machine resources detected (memory: ${o} free, cpu: ${i} free)`)):r.debug({memory:t,cpu:n},"Got machine resource usage metrics")}catch{}};function ub(r){if(!Rr)return lb(r),{interval:setInterval(()=>lb(r),2e4),cpuMetadata:HO,platform:cb}}function GO(){let r=jo.totalmem(),e=cb==="darwin"?jO():(()=>{let n=jo.freemem();return{availableMemory:n,rawFreeMemory:n,cachedMemory:0}})(),t=e.availableMemory/r;return{totalMemory:r,freeMemory:e.availableMemory,freePercentage:t}}function VO(){let r=jo.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,!xr)return xr=t,null;let n={user:t.user-xr.user,nice:t.nice-xr.nice,sys:t.sys-xr.sys,idle:t.idle-xr.idle,irq:t.irq-xr.irq,total:t.total-xr.total};return sb={measurementTime:e,intervalMs:e-xr.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},xr=t,sb}function jO(){try{let r=BO("/usr/bin/vm_stat",{encoding:"utf8",stdio:["pipe","pipe","ignore"]}),t=r.match(/page size of (\d+) bytes/)?.[1],n=t?Number.parseInt(t,10):4096,o=u=>{let p=r.match(new RegExp(`${u}:\\s+(\\d+)\\.`,"i"))?.[1];return p?Number.parseInt(p,10):0},i=o("Pages free"),a=o("Pages inactive"),l=o("Pages speculative"),c=i*n,s=(a+l)*n;return{availableMemory:c+s,rawFreeMemory:c,cachedMemory:s}}catch{let e=jo.freemem();return{availableMemory:e,rawFreeMemory:e,cachedMemory:0}}}var hl=class{increment(e,t,n){}gauge(e,t){}distribution(e,t,n){}async flush(){}async recordDuration({fn:e}){return await e()}};function WO(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 fl(r,e){let t=WO(r);return!e||Object.keys(e).length===0?t:{...e,...t}}var Ub="=",El=";",lp=",";var Fb=8192;var Ko={};KC(Ko,{getKeyPairs:()=>wL,parseKeyPairsIntoRecord:()=>RL,parsePairKeyValue:()=>Bb,serializeKeyPairs:()=>AL});Ce();var vL=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 AL(r){return r.reduce(function(e,t){var n=""+e+(e!==""?lp:"")+t;return n.length>Fb?e:n},"")}function wL(r){return r.getAllEntries().map(function(e){var t=vL(e,2),n=t[0],o=t[1],i=encodeURIComponent(n)+"="+encodeURIComponent(o.value);return o.metadata!==void 0&&(i+=El+o.metadata.toString()),i})}function Bb(r){var e=r.split(El);if(!(e.length<=0)){var t=e.shift();if(t){var n=t.indexOf(Ub);if(!(n<=0)){var o=decodeURIComponent(t.substring(0,n).trim()),i=decodeURIComponent(t.substring(n+1).trim()),a;return e.length>0&&(a=Zd(e.join(El))),{key:o,value:i,metadata:a}}}}}function RL(r){return typeof r!="string"||r.length===0?{}:r.split(lp).map(function(e){return Bb(e)}).filter(function(e){return e!==void 0&&e.value.length>0}).reduce(function(e,t){return e[t.key]=t.value,e},{})}Ce();var Tl;(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"})(Tl||(Tl={}));var CL=",",xL=["OTEL_SDK_DISABLED"];function ML(r){return xL.indexOf(r)>-1}var _L=["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 PL(r){return _L.indexOf(r)>-1}var IL=["OTEL_NO_PATCH_MODULES","OTEL_PROPAGATORS"];function OL(r){return IL.indexOf(r)>-1}var cp=1/0,up=128,LL=128,NL=128,dp={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:Le.INFO,OTEL_NO_PATCH_MODULES:[],OTEL_PROPAGATORS:["tracecontext","baggage"],OTEL_RESOURCE_ATTRIBUTES:"",OTEL_SERVICE_NAME:"",OTEL_ATTRIBUTE_VALUE_LENGTH_LIMIT:cp,OTEL_ATTRIBUTE_COUNT_LIMIT:up,OTEL_SPAN_ATTRIBUTE_VALUE_LENGTH_LIMIT:cp,OTEL_SPAN_ATTRIBUTE_COUNT_LIMIT:up,OTEL_LOGRECORD_ATTRIBUTE_VALUE_LENGTH_LIMIT:cp,OTEL_LOGRECORD_ATTRIBUTE_COUNT_LIMIT:up,OTEL_SPAN_EVENT_COUNT_LIMIT:128,OTEL_SPAN_LINK_COUNT_LIMIT:128,OTEL_SPAN_ATTRIBUTE_PER_EVENT_COUNT_LIMIT:LL,OTEL_SPAN_ATTRIBUTE_PER_LINK_COUNT_LIMIT:NL,OTEL_TRACES_EXPORTER:"",OTEL_TRACES_SAMPLER:Tl.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 DL(r,e,t){if(!(typeof t[r]>"u")){var n=String(t[r]);e[r]=n.toLowerCase()==="true"}}function kL(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 UL(r,e,t,n){n===void 0&&(n=CL);var o=t[r];typeof o=="string"&&(e[r]=o.split(n).map(function(i){return i.trim()}))}var FL={ALL:Le.ALL,VERBOSE:Le.VERBOSE,DEBUG:Le.DEBUG,INFO:Le.INFO,WARN:Le.WARN,ERROR:Le.ERROR,NONE:Le.NONE};function BL(r,e,t){var n=t[r];if(typeof n=="string"){var o=FL[n.toUpperCase()];o!=null&&(e[r]=o)}}function zb(r){var e={};for(var t in dp){var n=t;switch(n){case"OTEL_LOG_LEVEL":BL(n,e,r);break;default:if(ML(n))DL(n,e,r);else if(PL(n))kL(n,e,r);else if(OL(n))UL(n,e,r);else{var o=r[n];typeof o<"u"&&o!==null&&(e[n]=String(o))}}}return e}function mt(){var r=zb(process.env);return Object.assign({},dp,r)}function Hb(r){return r>=48&&r<=57?r-48:r>=97&&r<=102?r-87:r-55}function vl(r){for(var e=new Uint8Array(r.length/2),t=0,n=0;n<r.length;n+=2){var o=Hb(r.charCodeAt(n)),i=Hb(r.charCodeAt(n+1));e[t++]=o<<4|i}return e}var Gb="1.25.1";var zL="deployment.environment";var HL="process.runtime.name";var GL="service.name";var VL="service.instance.id";var jL="telemetry.sdk.name",WL="telemetry.sdk.language",$L="telemetry.sdk.version";var Vb=zL;var jb=HL;var Al=GL;var Wb=VL;var wa=jL,Ra=WL,Ca=$L;var qL="nodejs";var $b=qL;var Yo,wl=(Yo={},Yo[wa]="opentelemetry",Yo[jb]="node",Yo[Ra]=$b,Yo[Ca]=Gb,Yo);var KL=9,YL=6,XL=Math.pow(10,YL),JL=Math.pow(10,KL);function qb(r){var e=r/1e3,t=Math.trunc(e),n=Math.round(r%1e3*XL);return[t,n]}function Kb(r){return r[0]*JL+r[1]}function xa(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 Yb=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 ZL=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},QL=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))},Xb=function(){function r(e,t){this._callback=e,this._that=t,this._isCalled=!1,this._deferred=new Yb}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,QL([this._that],ZL(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 nr;(function(r){r[r.DELTA=0]="DELTA",r[r.CUMULATIVE=1]="CUMULATIVE"})(nr||(nr={}));var vt;(function(r){r[r.HISTOGRAM=0]="HISTOGRAM",r[r.EXPONENTIAL_HISTOGRAM=1]="EXPONENTIAL_HISTOGRAM",r[r.GAUGE=2]="GAUGE",r[r.SUM=3]="SUM"})(vt||(vt={}));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)}}();var Ete=function(r){eN(e,r);function e(t){var n=r.call(this,t)||this;return Object.setPrototypeOf(n,e.prototype),n}return e}(Error);function Jb(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}Ce();var or;(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"})(or||(or={}));var Zb=function(){function r(){this.kind=or.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 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={}));var tN=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 rN(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 pp=function(){function r(e,t,n,o){n===void 0&&(n=!0),o===void 0&&(o=rN(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=Jb(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 mp=function(){function r(e,t){this._boundaries=e,this._recordMinMax=t,this.kind=or.HISTOGRAM}return r.prototype.createAccumulation=function(e){return new pp(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 pp(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 pp(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:vt.HISTOGRAM,dataPoints:n.map(function(i){var a=tN(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}();Ce();var gp=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},hp=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))},fp=function(){function r(e,t,n,o){e===void 0&&(e=new nN),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 nN=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,hp([n,this._counts.length-t],gp(this._counts.slice(t)),!1)),o.splice.apply(o,hp([0,t],gp(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(hp([],gp(this._counts),!1))},r}();var Qb=52,oN=2146435072,iN=1048575,Sp=1023,Rl=-Sp+1,Cl=Sp,Ma=Math.pow(2,-1022);function xl(r){var e=new DataView(new ArrayBuffer(8));e.setFloat64(0,r);var t=e.getUint32(0),n=(t&oN)>>20;return n-Sp}function Ml(r){var e=new DataView(new ArrayBuffer(8));e.setFloat64(0,r);var t=e.getUint32(0),n=e.getUint32(4),o=(t&iN)*Math.pow(2,32);return o+n}function _a(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 aN=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)}}(),gn=function(r){aN(e,r);function e(){return r!==null&&r.apply(this,arguments)||this}return e}(Error);var nE=function(){function r(e){this._shift=-e}return r.prototype.mapToIndex=function(e){if(e<Ma)return this._minNormalLowerBoundaryIndex();var t=xl(e),n=this._rightShift(Ml(e)-1,Qb);return t+n>>this._shift},r.prototype.lowerBoundary=function(e){var t=this._minNormalLowerBoundaryIndex();if(e<t)throw new gn("underflow: "+e+" is < minimum lower boundary: "+t);var n=this._maxNormalLowerBoundaryIndex();if(e>n)throw new gn("overflow: "+e+" is > maximum lower boundary: "+n);return _a(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=Rl>>this._shift;return this._shift<2&&e--,e},r.prototype._maxNormalLowerBoundaryIndex=function(){return Cl>>this._shift},r.prototype._rightShift=function(e,t){return Math.floor(e*Math.pow(2,-t))},r}();var oE=function(){function r(e){this._scale=e,this._scaleFactor=_a(Math.LOG2E,e),this._inverseFactor=_a(Math.LN2,-e)}return r.prototype.mapToIndex=function(e){if(e<=Ma)return this._minNormalLowerBoundaryIndex()-1;if(Ml(e)===0){var t=xl(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 gn("overflow: "+e+" is > maximum lower boundary: "+t)}var n=this._minNormalLowerBoundaryIndex();if(e<=n){if(e===n)return Ma;if(e===n-1)return Math.exp((e+(1<<this._scale))/this._scaleFactor)/2;throw new gn("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 Rl<<this._scale},r.prototype._maxNormalLowerBoundaryIndex=function(){return(Cl+1<<this._scale)-1},r}();var iE=-10,aE=20,sN=Array.from({length:31},function(r,e){return e>10?new oE(e-10):new nE(e-10)});function yp(r){if(r>aE||r<iE)throw new gn("expected scale >= "+iE+" && <= "+aE+", got: "+r);return sN[r+10]}var lN=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(){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}(),cN=20,uN=160,bp=2,dN=function(){function r(e,t,n,o,i,a,l,c,s,u,d){e===void 0&&(e=e),t===void 0&&(t=uN),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 fp),u===void 0&&(u=new fp),d===void 0&&(d=yp(cN)),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<bp&&(H.warn("Exponential Histogram Max Size set to "+this._maxSize+", changing to the minimum size of: "+bp),this._maxSize=bp)}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=yp(t)}},r.prototype._minScale=function(e){var t=Math.min(this.scale,e.scale),n=_l.combine(this._highLowAtScale(this.positive,this.scale,t),this._highLowAtScale(e.positive,e.scale,t)),o=_l.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 _l(0,-1);var o=t-n;return new _l(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 sE=function(){function r(e,t){this._maxSize=e,this._recordMinMax=t,this.kind=or.EXPONENTIAL_HISTOGRAM}return r.prototype.createAccumulation=function(e){return new dN(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:vt.EXPONENTIAL_HISTOGRAM,dataPoints:n.map(function(i){var a=lN(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}();var pN=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},Ep=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=qb(Date.now())},r.prototype.setStartTime=function(e){this.startTime=e},r.prototype.toPointValue=function(){return this._current},r}();var lE=function(){function r(){this.kind=or.LAST_VALUE}return r.prototype.createAccumulation=function(e){return new Ep(e)},r.prototype.merge=function(e,t){var n=xa(t.sampleTime)>=xa(e.sampleTime)?t:e;return new Ep(e.startTime,n.toPointValue(),n.sampleTime)},r.prototype.diff=function(e,t){var n=xa(t.sampleTime)>=xa(e.sampleTime)?t:e;return new Ep(t.startTime,n.toPointValue(),n.sampleTime)},r.prototype.toMetricData=function(e,t,n,o){return{descriptor:e,aggregationTemporality:t,dataPointType:vt.GAUGE,dataPoints:n.map(function(i){var a=pN(i,2),l=a[0],c=a[1];return{attributes:l,startTime:c.startTime,endTime:o,value:c.toPointValue()}})}},r}();var mN=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},Pa=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 Tp=function(){function r(e){this.monotonic=e,this.kind=or.SUM}return r.prototype.createAccumulation=function(e){return new Pa(e,this.monotonic)},r.prototype.merge=function(e,t){var n=e.toPointValue(),o=t.toPointValue();return t.reset?new Pa(t.startTime,this.monotonic,o,t.reset):new Pa(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 Pa(t.startTime,this.monotonic,o,!0):new Pa(t.startTime,this.monotonic,o-n)},r.prototype.toMetricData=function(e,t,n,o){return{descriptor:e,aggregationTemporality:t,dataPointType:vt.SUM,dataPoints:n.map(function(i){var a=mN(i,2),l=a[0],c=a[1];return{attributes:l,startTime:c.startTime,endTime:o,value:c.toPointValue()}}),isMonotonic:this.monotonic}},r}();var qn=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)}}(),_r=function(){function r(){}return r.Drop=function(){return fE},r.Sum=function(){return SE},r.LastValue=function(){return yE},r.Histogram=function(){return bE},r.ExponentialHistogram=function(){return gN},r.Default=function(){return hN},r}();var cE=function(r){qn(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 Zb,e}(_r);var uE=function(r){qn(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 Tp(!0),e.NON_MONOTONIC_INSTANCE=new Tp(!1),e}(_r);var dE=function(r){qn(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 lE,e}(_r);var pE=function(r){qn(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 mp([0,5,10,25,50,75,100,250,500,750,1e3,2500,5e3,7500,1e4],!0),e}(_r);var mE=function(r){qn(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 mp(this._boundaries,this._recordMinMax)},e}(_r);var gE=function(r){qn(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 sE(this._maxSize,this._recordMinMax)},e}(_r);var hE=function(r){qn(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 SE;case oe.GAUGE:case oe.OBSERVABLE_GAUGE:return yE;case oe.HISTOGRAM:return t.advice.explicitBucketBoundaries?new mE(t.advice.explicitBucketBoundaries):bE}return H.warn("Unable to recognize instrument type: "+t.type),fE},e.prototype.createAggregator=function(t){return this._resolve(t).createAggregator(t)},e}(_r);var fE=new cE,SE=new uE,yE=new dE,bE=new pE,gN=new gE,hN=new hE;Ce();function Pl(){return"unknown_service:"+process.argv0}var hn=function(){return hn=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},hn.apply(this,arguments)},fN=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())})},SN=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}}},yN=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},vp=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 H.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[Al]=Pl(),e[Ra]=wl[Ra],e[wa]=wl[wa],e[Ca]=wl[Ca],e))},Object.defineProperty(r.prototype,"attributes",{get:function(){var e;return this.asyncAttributesPending&&H.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 fN(this,void 0,void 0,function(){return SN(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=hn(hn({},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=yN(a,2),s=c[0],u=c[1];return hn(hn(hn(hn({},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 Kn;(function(r){r[r.DELTA=0]="DELTA",r[r.CUMULATIVE=1]="CUMULATIVE",r[r.LOWMEMORY=2]="LOWMEMORY"})(Kn||(Kn={}));Ce();var bN=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())})},EN=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}}},Ap=function(){return nr.CUMULATIVE},EE=function(r){switch(r){case oe.COUNTER:case oe.OBSERVABLE_COUNTER:case oe.GAUGE:case oe.HISTOGRAM:case oe.OBSERVABLE_GAUGE:return nr.DELTA;case oe.UP_DOWN_COUNTER:case oe.OBSERVABLE_UP_DOWN_COUNTER:return nr.CUMULATIVE}},TE=function(r){switch(r){case oe.COUNTER:case oe.HISTOGRAM:return nr.DELTA;case oe.GAUGE:case oe.UP_DOWN_COUNTER:case oe.OBSERVABLE_UP_DOWN_COUNTER:case oe.OBSERVABLE_COUNTER:case oe.OBSERVABLE_GAUGE:return nr.CUMULATIVE}};function TN(){var r=mt(),e=r.OTEL_EXPORTER_OTLP_METRICS_TEMPORALITY_PREFERENCE.trim().toLowerCase();return e==="cumulative"?Ap:e==="delta"?EE:e==="lowmemory"?TE:(H.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."),Ap)}function vN(r){return r!=null?r===Kn.DELTA?EE:r===Kn.LOWMEMORY?TE:Ap:TN()}function AN(r){return r?.aggregationPreference?r.aggregationPreference:function(e){return _r.Default()}}var vE=function(){function r(e,t){this._otlpExporter=e,this._aggregationSelector=AN(t),this._aggregationTemporalitySelector=vN(t?.temporalityPreference)}return r.prototype.export=function(e,t){this._otlpExporter.export([e],t)},r.prototype.shutdown=function(){return bN(this,void 0,void 0,function(){return EN(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}();Ce();Ce();var wN=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},AE=1e4,wE=5,RE=1e3,CE=5e3,xE=1.5;function Ia(r){r===void 0&&(r={});var e={};return Object.entries(r).forEach(function(t){var n=wN(t,2),o=n[0],i=n[1];typeof i<"u"?e[o]=String(i):H.warn('Header "'+o+'" has invalid value ('+i+") and will be ignored")}),e}function wp(r,e){return r.endsWith("/")||(r=r+"/"),r+e}function Rp(r){try{var e=new URL(r);return e.pathname===""&&(e.pathname=e.pathname+"/"),e.toString()}catch{return H.warn("Could not parse export URL: '"+r+"'"),r}}function Cp(r){return typeof r=="number"?r<=0?xp(r,AE):r:RN()}function RN(){var r,e=Number((r=mt().OTEL_EXPORTER_OTLP_TRACES_TIMEOUT)!==null&&r!==void 0?r:mt().OTEL_EXPORTER_OTLP_TIMEOUT);return e<=0?xp(e,AE):e}function xp(r,e){return H.warn("Timeout must be greater than 0",r),e}function ME(r){var e=[429,502,503,504];return e.includes(r)}function _E(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 PE=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 Xb(this._shutdown,this),this._concurrencyLimit=typeof e.concurrencyLimit=="number"?e.concurrencyLimit:30,this.timeoutMillis=Cp(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{H.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 H.debug("shutdown started"),this.onShutdown(),this.forceFlush()},r}();Ce();import*as Mp from"url";import*as Ol from"http";import*as Ll from"https";import*as IE from"zlib";import{Readable as xN}from"stream";var fn;(function(r){r.NONE="none",r.GZIP="gzip"})(fn||(fn={}));var CN=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)}}(),Xo=function(r){CN(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 Il=function(){return Il=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},Il.apply(this,arguments)};function _p(r,e,t,n,o){var i=r.timeoutMillis,a=new Mp.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 Xo("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:Il({"Content-Type":t},r.headers),agent:r.agent},m=a.protocol==="http:"?Ol.request:Ll.request,g=function(h,f){switch(h===void 0&&(h=wE),f===void 0&&(f=RE),s=m(p,function(b){var C="";b.on("data",function(A){return C+=A}),b.on("aborted",function(){if(u){var A=new Xo("Request Timeout");o(A)}}),b.on("end",function(){if(u===!1)if(b.statusCode&&b.statusCode<299)H.debug("statusCode: "+b.statusCode,C),n(),clearTimeout(d),clearTimeout(c);else if(b.statusCode&&ME(b.statusCode)&&h>0){var A=void 0;f=xE*f,b.headers["retry-after"]?A=_E(b.headers["retry-after"]):A=Math.round(Math.random()*(CE-f)+f),c=setTimeout(function(){g(h-1,f)},A)}else{var v=new Xo(b.statusMessage,b.statusCode,C);o(v),clearTimeout(d),clearTimeout(c)}})}),s.on("error",function(b){if(u){var C=new Xo("Request Timeout",b.code);o(C)}else o(b);clearTimeout(d),clearTimeout(c)}),s.on("abort",function(){if(u){var b=new Xo("Request Timeout");o(b)}clearTimeout(d),clearTimeout(c)}),r.compression){case fn.GZIP:{s.setHeader("Content-Encoding","gzip");var E=MN(e);E.on("error",o).pipe(IE.createGzip()).on("error",o).pipe(s);break}default:s.end(Buffer.from(e));break}};g()}function MN(r){var e=new xN;return e.push(r),e.push(null),e}function Pp(r){if(r.httpAgentOptions&&r.keepAlive===!1){H.warn("httpAgentOptions is used only when keepAlive is true");return}if(!(r.keepAlive===!1||!r.url))try{var e=new Mp.URL(r.url),t=e.protocol==="http:"?Ol.Agent:Ll.Agent;return new t(Il({keepAlive:!0},r.httpAgentOptions))}catch(n){H.error("collector exporter failed to create http agent. err: "+n.message);return}}function Ip(r){if(r)return r;var e=mt().OTEL_EXPORTER_OTLP_TRACES_COMPRESSION||mt().OTEL_EXPORTER_OTLP_COMPRESSION;return e===fn.GZIP?fn.GZIP:fn.NONE}Ce();var _N=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)}}(),Nl=function(r){_N(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&&H.warn("Metadata cannot be set when using http"),i.headers=Object.assign(i.DEFAULT_HEADERS,Ia(t.headers),Ko.parseKeyPairsIntoRecord(mt().OTEL_EXPORTER_OTLP_HEADERS)),i.agent=Pp(t),i.compression=Ip(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){H.debug("Shutdown already started. Cannot send objects");return}var a=new Promise(function(c,s){var u;_p(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}(PE);function LE(r){var e=BigInt(1e9);return BigInt(r[0])*e+BigInt(r[1])}function PN(r){var e=Number(BigInt.asUintN(32,r)),t=Number(BigInt.asUintN(32,r>>BigInt(32)));return{low:e,high:t}}function NE(r){var e=LE(r);return PN(e)}function IN(r){var e=LE(r);return e.toString()}var ON=typeof BigInt<"u"?IN:Kb;function OE(r){return r}function DE(r){if(r!==void 0)return vl(r)}var LN={encodeHrTime:NE,encodeSpanContext:vl,encodeOptionalSpanContext:DE};function kE(r){var e,t;if(r===void 0)return LN;var n=(e=r.useLongBits)!==null&&e!==void 0?e:!0,o=(t=r.useHex)!==null&&t!==void 0?t:!1;return{encodeHrTime:n?NE:ON,encodeSpanContext:o?OE:vl,encodeOptionalSpanContext:o?OE:DE}}var NN=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 UE(r){return{name:r.name,version:r.version}}function Jo(r){return Object.keys(r).map(function(e){return FE(e,r[e])})}function FE(r,e){return{key:r,value:BE(e)}}function BE(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(BE)}}:e==="object"&&r!=null?{kvlistValue:{values:Object.entries(r).map(function(t){var n=NN(t,2),o=n[0],i=n[1];return FE(o,i)})}}:{}}function zE(r){return{attributes:Jo(r.attributes),droppedAttributesCount:0}}Ce();function GE(r,e){var t=kE(e);return{resource:zE(r.resource),schemaUrl:void 0,scopeMetrics:DN(r.scopeMetrics,t)}}function DN(r,e){return Array.from(r.map(function(t){return{scope:UE(t.scope),metrics:t.metrics.map(function(n){return kN(n,e)}),schemaUrl:t.scope.schemaUrl}}))}function kN(r,e){var t={name:r.descriptor.name,description:r.descriptor.description,unit:r.descriptor.unit},n=zN(r.aggregationTemporality);switch(r.dataPointType){case vt.SUM:t.sum={aggregationTemporality:n,isMonotonic:r.isMonotonic,dataPoints:HE(r,e)};break;case vt.GAUGE:t.gauge={dataPoints:HE(r,e)};break;case vt.HISTOGRAM:t.histogram={aggregationTemporality:n,dataPoints:FN(r,e)};break;case vt.EXPONENTIAL_HISTOGRAM:t.exponentialHistogram={aggregationTemporality:n,dataPoints:BN(r,e)};break}return t}function UN(r,e,t){var n={attributes:Jo(r.attributes),startTimeUnixNano:t.encodeHrTime(r.startTime),timeUnixNano:t.encodeHrTime(r.endTime)};switch(e){case Ht.INT:n.asInt=r.value;break;case Ht.DOUBLE:n.asDouble=r.value;break}return n}function HE(r,e){return r.dataPoints.map(function(t){return UN(t,r.descriptor.valueType,e)})}function FN(r,e){return r.dataPoints.map(function(t){var n=t.value;return{attributes:Jo(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 BN(r,e){return r.dataPoints.map(function(t){var n=t.value;return{attributes:Jo(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 zN(r){switch(r){case nr.DELTA:return 1;case nr.CUMULATIVE:return 2}}function VE(r,e){return{resourceMetrics:r.map(function(t){return GE(t,e)})}}var Op={serializeRequest:function(r){var e=VE(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 jE="0.52.1";var WE=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)}}(),Zo=function(){return Zo=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},Zo.apply(this,arguments)},$E="v1/metrics",HN="http://localhost:4318/"+$E,GN={"User-Agent":"OTel-OTLP-Exporter-JavaScript/"+jE},VN=function(r){WE(e,r);function e(t){var n=r.call(this,t,Op,"application/json")||this;return n.headers=Zo(Zo(Zo(Zo({},n.headers),GN),Ko.parseKeyPairsIntoRecord(mt().OTEL_EXPORTER_OTLP_METRICS_HEADERS)),Ia(t?.headers)),n}return e.prototype.getDefaultUrl=function(t){return typeof t.url=="string"?t.url:mt().OTEL_EXPORTER_OTLP_METRICS_ENDPOINT.length>0?Rp(mt().OTEL_EXPORTER_OTLP_METRICS_ENDPOINT):mt().OTEL_EXPORTER_OTLP_ENDPOINT.length>0?wp(mt().OTEL_EXPORTER_OTLP_ENDPOINT,$E):HN},e}(Nl),qE=function(r){WE(e,r);function e(t){return r.call(this,new VN(t),t)||this}return e}(vE);var Qo;(function(r){r[r.DELTA=0]="DELTA",r[r.CUMULATIVE=1]="CUMULATIVE"})(Qo||(Qo={}));var Pr;(function(r){r[r.HISTOGRAM=0]="HISTOGRAM",r[r.EXPONENTIAL_HISTOGRAM=1]="EXPONENTIAL_HISTOGRAM",r[r.GAUGE=2]="GAUGE",r[r.SUM=3]="SUM"})(Pr||(Pr={}));Ce();var jN=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)}}(),KE=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())})},YE=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}}},WN=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},$N=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))},qN=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 XE(r){return r!=null}function Dl(r){var e=Object.keys(r);return e.length===0?"":(e=e.sort(),JSON.stringify(e.map(function(t){return[t,r[t]]})))}function JE(r){var e,t;return r.name+":"+((e=r.version)!==null&&e!==void 0?e:"")+":"+((t=r.schemaUrl)!==null&&t!==void 0?t:"")}var Lp=function(r){jN(e,r);function e(t){var n=r.call(this,t)||this;return Object.setPrototypeOf(n,e.prototype),n}return e}(Error);function Sn(r,e){var t,n=new Promise(function(i,a){t=setTimeout(function(){a(new Lp("Operation timed out."))},e)});return Promise.race([r,n]).then(function(o){return clearTimeout(t),o},function(o){throw clearTimeout(t),o})}function ZE(r){return KE(this,void 0,void 0,function(){var e=this;return YE(this,function(t){return[2,Promise.all(r.map(function(n){return KE(e,void 0,void 0,function(){var o,i;return YE(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 QE(r){return r.status==="rejected"}function Np(r,e){var t=[];return r.forEach(function(n){t.push.apply(t,$N([],WN(e(n)),!1))}),t}function eT(r,e){var t,n;if(r.size!==e.size)return!1;try{for(var o=qN(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 tT(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 rT(r,e){return r.toLowerCase()===e.toLowerCase()}Ce();var ir;(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"})(ir||(ir={}));var Dp=function(){function r(){this.kind=ir.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}();Ce();var de;(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"})(de||(de={}));function Ir(r,e,t){var n,o,i,a;return YN(r)||H.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:Ht.DOUBLE,advice:(a=t?.advice)!==null&&a!==void 0?a:{}}}function nT(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 oT(r,e){return rT(r.name,e.name)&&r.unit===e.unit&&r.type===e.type&&r.valueType===e.valueType}var KN=/^[a-z][a-z0-9_.\-/]{0,254}$/i;function YN(r){return r.match(KN)!=null}var XN=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 JN(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 kl=function(){function r(e,t,n,o){n===void 0&&(n=!0),o===void 0&&(o=JN(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=tT(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 Ul=function(){function r(e,t){this._boundaries=e,this._recordMinMax=t,this.kind=ir.HISTOGRAM}return r.prototype.createAccumulation=function(e){return new kl(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 kl(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 kl(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:Pr.HISTOGRAM,dataPoints:n.map(function(i){var a=XN(i,2),l=a[0],c=a[1],s=c.toPointValue(),u=e.type===de.GAUGE||e.type===de.UP_DOWN_COUNTER||e.type===de.OBSERVABLE_GAUGE||e.type===de.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}();Ce();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},Up=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))},Fp=function(){function r(e,t,n,o){e===void 0&&(e=new ZN),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 ZN=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,Up([n,this._counts.length-t],kp(this._counts.slice(t)),!1)),o.splice.apply(o,Up([0,t],kp(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(Up([],kp(this._counts),!1))},r}();var iT=52,QN=2146435072,eD=1048575,Bp=1023,Fl=-Bp+1,Bl=Bp,Oa=Math.pow(2,-1022);function zl(r){var e=new DataView(new ArrayBuffer(8));e.setFloat64(0,r);var t=e.getUint32(0),n=(t&QN)>>20;return n-Bp}function Hl(r){var e=new DataView(new ArrayBuffer(8));e.setFloat64(0,r);var t=e.getUint32(0),n=e.getUint32(4),o=(t&eD)*Math.pow(2,32);return o+n}function La(r,e){return r===0||r===Number.POSITIVE_INFINITY||r===Number.NEGATIVE_INFINITY||Number.isNaN(r)?r:r*Math.pow(2,e)}function sT(r){return r--,r|=r>>1,r|=r>>2,r|=r>>4,r|=r>>8,r|=r>>16,r++,r}var tD=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)}}(),yn=function(r){tD(e,r);function e(){return r!==null&&r.apply(this,arguments)||this}return e}(Error);var cT=function(){function r(e){this._shift=-e}return r.prototype.mapToIndex=function(e){if(e<Oa)return this._minNormalLowerBoundaryIndex();var t=zl(e),n=this._rightShift(Hl(e)-1,iT);return t+n>>this._shift},r.prototype.lowerBoundary=function(e){var t=this._minNormalLowerBoundaryIndex();if(e<t)throw new yn("underflow: "+e+" is < minimum lower boundary: "+t);var n=this._maxNormalLowerBoundaryIndex();if(e>n)throw new yn("overflow: "+e+" is > maximum lower boundary: "+n);return La(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=Fl>>this._shift;return this._shift<2&&e--,e},r.prototype._maxNormalLowerBoundaryIndex=function(){return Bl>>this._shift},r.prototype._rightShift=function(e,t){return Math.floor(e*Math.pow(2,-t))},r}();var uT=function(){function r(e){this._scale=e,this._scaleFactor=La(Math.LOG2E,e),this._inverseFactor=La(Math.LN2,-e)}return r.prototype.mapToIndex=function(e){if(e<=Oa)return this._minNormalLowerBoundaryIndex()-1;if(Hl(e)===0){var t=zl(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 yn("overflow: "+e+" is > maximum lower boundary: "+t)}var n=this._minNormalLowerBoundaryIndex();if(e<=n){if(e===n)return Oa;if(e===n-1)return Math.exp((e+(1<<this._scale))/this._scaleFactor)/2;throw new yn("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 Fl<<this._scale},r.prototype._maxNormalLowerBoundaryIndex=function(){return(Bl+1<<this._scale)-1},r}();var dT=-10,pT=20,rD=Array.from({length:31},function(r,e){return e>10?new uT(e-10):new cT(e-10)});function zp(r){if(r>pT||r<dT)throw new yn("expected scale >= "+dT+" && <= "+pT+", got: "+r);return rD[r+10]}var nD=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){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}(),oD=20,iD=160,Hp=2,mT=function(){function r(e,t,n,o,i,a,l,c,s,u,d){e===void 0&&(e=e),t===void 0&&(t=iD),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 Fp),u===void 0&&(u=new Fp),d===void 0&&(d=zp(oD)),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<Hp&&(H.warn("Exponential Histogram Max Size set to "+this._maxSize+", changing to the minimum size of: "+Hp),this._maxSize=Hp)}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=sT(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=zp(t)}},r.prototype._minScale=function(e){var t=Math.min(this.scale,e.scale),n=Gl.combine(this._highLowAtScale(this.positive,this.scale,t),this._highLowAtScale(e.positive,e.scale,t)),o=Gl.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 Gl(0,-1);var o=t-n;return new Gl(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 Gp=function(){function r(e,t){this._maxSize=e,this._recordMinMax=t,this.kind=ir.EXPONENTIAL_HISTOGRAM}return r.prototype.createAccumulation=function(e){return new mT(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:Pr.EXPONENTIAL_HISTOGRAM,dataPoints:n.map(function(i){var a=nD(i,2),l=a[0],c=a[1],s=c.toPointValue(),u=e.type===de.GAUGE||e.type===de.UP_DOWN_COUNTER||e.type===de.OBSERVABLE_GAUGE||e.type===de.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}();Ce();var aD=Qd("OpenTelemetry SDK Context Key SUPPRESS_TRACING");function gT(r){return r.setValue(aD,!0)}Ce();function hT(){return function(r){H.error(sD(r))}}function sD(r){return typeof r=="string"?r:JSON.stringify(lD(r))}function lD(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 cD=hT();function Vl(r){try{cD(r)}catch{}}var fT="1.30.1";var uD="process.runtime.name";var dD="service.name";var pD="telemetry.sdk.name",mD="telemetry.sdk.language",gD="telemetry.sdk.version";var ST=uD;var yT=dD;var Na=pD,Da=mD,ka=gD;var hD="nodejs";var bT=hD;var ei,Yn=(ei={},ei[Na]="opentelemetry",ei[ST]="node",ei[Da]=bT,ei[ka]=fT,ei);function Ua(r){r.unref()}var vD=9,AD=6,wD=Math.pow(10,AD),woe=Math.pow(10,vD);function Xn(r){var e=r/1e3,t=Math.trunc(e),n=Math.round(r%1e3*wD);return[t,n]}function ti(r){return r[0]*1e6+r[1]/1e3}var Fa;(function(r){r[r.SUCCESS=0]="SUCCESS",r[r.FAILED=1]="FAILED"})(Fa||(Fa={}));Ce();function ET(r,e){return new Promise(function(t){qo.with(gT(qo.active()),function(){r.export(e,function(n){t(n)})})})}var TT={_export:ET};var RD=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},jl=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=Xn(Date.now())},r.prototype.setStartTime=function(e){this.startTime=e},r.prototype.toPointValue=function(){return this._current},r}();var Vp=function(){function r(){this.kind=ir.LAST_VALUE}return r.prototype.createAccumulation=function(e){return new jl(e)},r.prototype.merge=function(e,t){var n=ti(t.sampleTime)>=ti(e.sampleTime)?t:e;return new jl(e.startTime,n.toPointValue(),n.sampleTime)},r.prototype.diff=function(e,t){var n=ti(t.sampleTime)>=ti(e.sampleTime)?t:e;return new jl(t.startTime,n.toPointValue(),n.sampleTime)},r.prototype.toMetricData=function(e,t,n,o){return{descriptor:e,aggregationTemporality:t,dataPointType:Pr.GAUGE,dataPoints:n.map(function(i){var a=RD(i,2),l=a[0],c=a[1];return{attributes:l,startTime:c.startTime,endTime:o,value:c.toPointValue()}})}},r}();var CD=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},ri=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 Wl=function(){function r(e){this.monotonic=e,this.kind=ir.SUM}return r.prototype.createAccumulation=function(e){return new ri(e,this.monotonic)},r.prototype.merge=function(e,t){var n=e.toPointValue(),o=t.toPointValue();return t.reset?new ri(t.startTime,this.monotonic,o,t.reset):new ri(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 ri(t.startTime,this.monotonic,o,!0):new ri(t.startTime,this.monotonic,o-n)},r.prototype.toMetricData=function(e,t,n,o){return{descriptor:e,aggregationTemporality:t,dataPointType:Pr.SUM,dataPoints:n.map(function(i){var a=CD(i,2),l=a[0],c=a[1];return{attributes:l,startTime:c.startTime,endTime:o,value:c.toPointValue()}}),isMonotonic:this.monotonic}},r}();var Jn=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)}}(),ar=function(){function r(){}return r.Drop=function(){return MT},r.Sum=function(){return _T},r.LastValue=function(){return PT},r.Histogram=function(){return IT},r.ExponentialHistogram=function(){return xD},r.Default=function(){return MD},r}();var vT=function(r){Jn(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 Dp,e}(ar);var AT=function(r){Jn(e,r);function e(){return r!==null&&r.apply(this,arguments)||this}return e.prototype.createAggregator=function(t){switch(t.type){case de.COUNTER:case de.OBSERVABLE_COUNTER:case de.HISTOGRAM:return e.MONOTONIC_INSTANCE;default:return e.NON_MONOTONIC_INSTANCE}},e.MONOTONIC_INSTANCE=new Wl(!0),e.NON_MONOTONIC_INSTANCE=new Wl(!1),e}(ar);var wT=function(r){Jn(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 Vp,e}(ar);var RT=function(r){Jn(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 Ul([0,5,10,25,50,75,100,250,500,750,1e3,2500,5e3,7500,1e4],!0),e}(ar);var Ba=function(r){Jn(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 Ul(this._boundaries,this._recordMinMax)},e}(ar);var CT=function(r){Jn(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 Gp(this._maxSize,this._recordMinMax)},e}(ar);var xT=function(r){Jn(e,r);function e(){return r!==null&&r.apply(this,arguments)||this}return e.prototype._resolve=function(t){switch(t.type){case de.COUNTER:case de.UP_DOWN_COUNTER:case de.OBSERVABLE_COUNTER:case de.OBSERVABLE_UP_DOWN_COUNTER:return _T;case de.GAUGE:case de.OBSERVABLE_GAUGE:return PT;case de.HISTOGRAM:return t.advice.explicitBucketBoundaries?new Ba(t.advice.explicitBucketBoundaries):IT}return H.warn("Unable to recognize instrument type: "+t.type),MT},e.prototype.createAggregator=function(t){return this._resolve(t).createAggregator(t)},e}(ar);var MT=new vT,_T=new AT,PT=new wT,IT=new RT,xD=new CT,MD=new xT;var OT=function(r){return ar.Default()},LT=function(r){return Qo.CUMULATIVE};var jp=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())})},Wp=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}}},NT=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))},DT=function(){function r(e){var t,n,o;this._shutdown=!1,this._aggregationSelector=(t=e?.aggregationSelector)!==null&&t!==void 0?t:OT,this._aggregationTemporalitySelector=(n=e?.aggregationTemporalitySelector)!==null&&n!==void 0?n:LT,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 jp(this,void 0,void 0,function(){var t,n,o,i,a,l;return Wp(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(_D([this._sdkMetricProducer.collect({timeoutMillis:e?.timeoutMillis})],NT(this._metricProducers.map(function(s){return s.collect({timeoutMillis:e?.timeoutMillis})})),!1))];case 1:return t=NT.apply(void 0,[c.sent()]),n=t[0],o=t.slice(1),i=n.errors.concat(Np(o,function(s){return s.errors})),a=n.resourceMetrics.resource,l=n.resourceMetrics.scopeMetrics.concat(Np(o,function(s){return s.resourceMetrics.scopeMetrics})),[2,{resourceMetrics:{resource:a,scopeMetrics:l},errors:i}]}})})},r.prototype.shutdown=function(e){return jp(this,void 0,void 0,function(){return Wp(this,function(t){switch(t.label){case 0:return this._shutdown?(H.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,Sn(this.onShutdown(),e.timeoutMillis)];case 3:t.sent(),t.label=4;case 4:return this._shutdown=!0,[2]}})})},r.prototype.forceFlush=function(e){return jp(this,void 0,void 0,function(){return Wp(this,function(t){switch(t.label){case 0:return this._shutdown?(H.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,Sn(this.onForceFlush(),e.timeoutMillis)];case 3:return t.sent(),[2]}})})},r}();Ce();var PD=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)}}(),$l=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())})},ql=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}}},ID=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},OD=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))},$p=function(r){PD(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 $l(this,void 0,void 0,function(){var t;return ql(this,function(n){switch(n.label){case 0:return n.trys.push([0,2,,3]),[4,Sn(this._doRun(),this._exportTimeout)];case 1:return n.sent(),[3,3];case 2:return t=n.sent(),t instanceof Lp?(H.error("Export took longer than %s milliseconds and timed out.",this._exportTimeout),[2]):(Vl(t),[3,3]);case 3:return[2]}})})},e.prototype._doRun=function(){var t,n;return $l(this,void 0,void 0,function(){var o,i,a,l,c,s;return ql(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=H).error.apply(s,OD(["PeriodicExportingMetricReader: metrics collection errors"],ID(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(),H.debug("Error while resolving async portion of resource: ",l),Vl(l),[3,5];case 5:return i.scopeMetrics.length===0?[2]:[4,TT._export(this._exporter,i)];case 6:if(c=u.sent(),c.code!==Fa.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),Ua(this._interval)},e.prototype.onForceFlush=function(){return $l(this,void 0,void 0,function(){return ql(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 $l(this,void 0,void 0,function(){return ql(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}(DT);Ce();Ce();function Kl(){return"unknown_service:"+process.argv0}var bn=function(){return bn=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},bn.apply(this,arguments)},LD=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())})},ND=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}}},DD=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},Yl=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 H.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[yT]=Kl(),e[Da]=Yn[Da],e[Na]=Yn[Na],e[ka]=Yn[ka],e))},Object.defineProperty(r.prototype,"attributes",{get:function(){var e;return this.asyncAttributesPending&&H.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 LD(this,void 0,void 0,function(){return ND(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=bn(bn({},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=DD(a,2),s=c[0],u=c[1];return bn(bn(bn(bn({},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 kT=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}();Ce();var Zn=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)}}(),Xl=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=qo.active()),typeof e!="number"){H.warn("non-number value provided to metric "+this._descriptor.name+": "+e);return}this._descriptor.valueType===Ht.INT&&!Number.isInteger(e)&&(H.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,Xn(Date.now()))},r}();var UT=function(r){Zn(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}(Xl);var FT=function(r){Zn(e,r);function e(){return r!==null&&r.apply(this,arguments)||this}return e.prototype.add=function(t,n,o){if(t<0){H.warn("negative value provided to counter "+this._descriptor.name+": "+t);return}this._record(t,n,o)},e}(Xl);var BT=function(r){Zn(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}(Xl);var zT=function(r){Zn(e,r);function e(){return r!==null&&r.apply(this,arguments)||this}return e.prototype.record=function(t,n,o){if(t<0){H.warn("negative value provided to histogram "+this._descriptor.name+": "+t);return}this._record(t,n,o)},e}(Xl);var Jl=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 HT=function(r){Zn(e,r);function e(){return r!==null&&r.apply(this,arguments)||this}return e}(Jl);var GT=function(r){Zn(e,r);function e(){return r!==null&&r.apply(this,arguments)||this}return e}(Jl);var VT=function(r){Zn(e,r);function e(){return r!==null&&r.apply(this,arguments)||this}return e}(Jl);function za(r){return r instanceof Jl}var jT=function(){function r(e){this._meterSharedState=e}return r.prototype.createGauge=function(e,t){var n=Ir(e,de.GAUGE,t),o=this._meterSharedState.registerMetricStorage(n);return new BT(o,n)},r.prototype.createHistogram=function(e,t){var n=Ir(e,de.HISTOGRAM,t),o=this._meterSharedState.registerMetricStorage(n);return new zT(o,n)},r.prototype.createCounter=function(e,t){var n=Ir(e,de.COUNTER,t),o=this._meterSharedState.registerMetricStorage(n);return new FT(o,n)},r.prototype.createUpDownCounter=function(e,t){var n=Ir(e,de.UP_DOWN_COUNTER,t),o=this._meterSharedState.registerMetricStorage(n);return new UT(o,n)},r.prototype.createObservableGauge=function(e,t){var n=Ir(e,de.OBSERVABLE_GAUGE,t),o=this._meterSharedState.registerAsyncMetricStorage(n);return new GT(n,o,this._meterSharedState.observableRegistry)},r.prototype.createObservableCounter=function(e,t){var n=Ir(e,de.OBSERVABLE_COUNTER,t),o=this._meterSharedState.registerAsyncMetricStorage(n);return new HT(n,o,this._meterSharedState.observableRegistry)},r.prototype.createObservableUpDownCounter=function(e,t){var n=Ir(e,de.OBSERVABLE_UP_DOWN_COUNTER,t),o=this._meterSharedState.registerAsyncMetricStorage(n);return new VT(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 Zl=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 kD=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)}}(),WT=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}}},UD=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 WT(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 WT(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 hr=function(r){kD(e,r);function e(){return r.call(this,Dl)||this}return e}(UD);var FD=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},Ql=function(){function r(e,t){this._aggregator=e,this._activeCollectionStorage=new hr,this._cumulativeMemoStorage=new hr,this._overflowAttributes={"otel.metric.overflow":!0},this._cardinalityLimit=(t??2e3)-1,this._overflowHashCode=Dl(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=FD(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 hr,e},r}();var qp=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.")},$T=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},ec=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===Qo.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=BD(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=qp(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 hr,i=this._unreportedAccumulations.get(e);if(this._unreportedAccumulations.set(e,[]),i===void 0)return o;try{for(var a=qp(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=$T(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=qp(e.keys()),l=a.next();!l.done;l=a.next()){var c=$T(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 BD(r){return Array.from(r.entries())}var zD=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)}}(),HD=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},qT=function(r){zD(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 Ql(n,l._aggregationCardinalityLimit),l._temporalMetricStorage=new ec(n,i),l}return e.prototype.record=function(t,n){var o=this,i=new hr;Array.from(t.entries()).forEach(function(a){var l=HD(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}(Zl);Ce();function Kp(r,e){var t="";return r.unit!==e.unit&&(t+=" - Unit '"+r.unit+"' does not match '"+e.unit+`'
23
+ `),globalThis.console=e}}var Yd=" ".repeat(6);import CO from"fetch-retry";import xO from"os";import tb,{multistream as MO}from"pino";import _O from"pino-pretty";import PO from"pino-std-serializers";var Go=new Map,IO=!0,rb="Log throttle exceeded",OO=100,LO=5e3,NO=CO(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}}),Xd=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??xO.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=IO?tb(a):tb(a,MO([{stream:_O({colorize:!0})}]))}child(e){return new r({bindings:{...this.bindingAttributes,...e},hostname:this.hostname,disableConsoleLogs:this.disableConsoleLogs,flushIntervalMs:this.flushIntervalMs,maxBatchSize:this.maxBatchSize})}async flush(){await this.flushBuffer(),this.disableConsoleLogs||this.consoleLogger.flush()}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 NO(this.site,{method:"POST",headers:{"Content-Type":"application/json","signoz-access-token":"CumAaTMUcwjt05OddAmefKgshbhfRmWxzxih"},body:jn(e),signal:AbortSignal.timeout(5e3)});if(!t.ok)throw new Error(`Got error status (${t.statusText}) from SigNoz`)}catch{}}shouldAllowLog(e){if(e===rb)return!0;let t=Date.now();return t-this.lastWindowStart>LO&&(this.logsInCurrentWindow=0,this.droppedLogsInWindow&&this.log("error",void 0,rb),this.droppedLogsInWindow=!1,this.lastWindowStart=t),this.logsInCurrentWindow<OO?(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(ga[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=PO.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:$S({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,Go.set("app",this),Go.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=qS[e]):(this.minLevelValue=ga[e],this.consoleLogger.level=e)}enableConsoleLogs(){this.disableConsoleLogs=!1}},Vo=({app:r,hostname:e,disableConsoleLogs:t})=>(Go.has(r)||Go.set(r,new Xd({bindings:{app:r},hostname:e,disableConsoleLogs:t})),Go.get(r));async function nb(){await Promise.all([...Go.values()].map(r=>r.flush()))}import{hostname as DO}from"os";var rr=Vo({app:"cli",hostname:DO(),disableConsoleLogs:!0}).child({cliVersion:"0.4.1"});function Jd(r){if(!r)return;r=r.toLowerCase();let e=il.safeParse(r);if(e.success)return w.setMinLevel(e.data),e.data}function ob({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 eb(()=>{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 Sa=({status:r,testLogRef:e,getRunningTestsCount:t,getTotalTestsCount:n,additionalText:o})=>{r=r.toUpperCase();let i=r,a;r.includes("FAIL")?(i=jo.bgRed.white("FAIL"),a=3):r.includes("PASS")?(i=jo.bgGreen.white("PASS"),a=3):r.includes("START")?(i=jo.bgBlue.white("START"),a=2):r.includes("CANCEL")?(i=jo.bgRgb(191,68,11).white("CANCEL"),a=1):r.includes("RETRY")?(i=jo.bgRgb(191,68,11).white("RETRY"),a=2):r.includes("RUN")||r.includes("PROG")?(i=jo.bgMagenta.white("RUNNING"),a=0):(w.warn(`Unknown status tried to be logged in run test locally: ${r}`),a=0),kO||(i=`${i}`),w.log(`${i}${" ".repeat(a)} ${e} ${o?`${o} `:""}(${t()}/${n()})`)};import UO from"fs";import{tmpdir as FO}from"os";import BO from"path";import{registry as ya}from"playwright-core/lib/server";import ib from"proper-lockfile";var ab=BO.join(FO(),"momenticBrowserInstallation");var Zd=["chrome","chromium","chrome-for-testing","ffmpeg"],zO={Chromium:"chromium","Google Chrome":"chrome","Chrome for Testing":"chrome-for-testing"},sb={chrome:"chrome",chromium:"chromium","chrome-for-testing":"chromium-headless-shell",ffmpeg:"ffmpeg"};function lb(r){let e=sb[zO[r]??""]??"",t=ya.findExecutable(e);return!t||t.installType==="none"?!1:Qd(t)}function Qd(r){let e=r.executablePath();return UO.existsSync(e)}function HO(r,e){let t=sb[r];if(!t)throw new Error(`Requested install of unknown browser type ${r}`);let n=ya.findExecutable(t);if(!n||n.installType==="none")throw new Error(`Requested install of unknown browser type ${r}`);if(!(!e&&Qd(n)))return n}async function GO({browser:r,force:e}){let t=HO(r,e);if(!t){w.info(`Browser '${r}' is already installed, skipping...`);return}w.info(`Installing browser '${r}'...`);try{await ya.installDeps([t],!1),await ya.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=ya.findExecutable(r),i=5*60*1e3,a=Date.now();for(;Date.now()-a<i&&!Qd(o);)w.info("Waiting for browser to finish installing..."),await new Promise(l=>setTimeout(l,5e3))}else throw n}}async function gl({rawBrowsers:r,force:e=!1,all:t=!1}){let n=t?Zd:Array.from(new Set(r));try{await ib.lock(ab,{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 GO({browser:i,force:e})}catch(a){o=a,w.error(`Failed to install the ${i} browser: ${a}`)}}finally{await ib.unlock(ab,{realpath:!1})}if(o)throw o}import{createServer as VO}from"http";async function hl(r,e,t=30){for(let n=0;n<t;n+=1){let o=r+n;if(await fl(o))return o}w.error(`Could not find an available port for ${e} starting from ${r} after ${t} attempts`),process.exit(1)}async function fl(r){return new Promise((e,t)=>{let n=VO();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 TQ from"blocked-at";import AQ from"why-is-node-running";import b0 from"fs";import{tmpdir as E0}from"os";import T0 from"path";import{remote as v0}from"webdriverio";import{createInstanceClient as m0}from"@limrun/api";import{execSync as g0}from"child_process";import NQ,{multistream as kQ}from"pino";import FQ from"pino-pretty";var HQ=5*1024,jO="...[truncated]",GQ=Buffer.byteLength(jO,"utf8");import{PostHog as ZQ}from"posthog-node";var hn=class extends Error{constructor(e){super(e),this.name="TimeoutError"}};var cb=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 k(r,e){let{milliseconds:t,fallback:n,message:o,customTimers:i={setTimeout,clearTimeout}}=e,a;if(typeof t!="number"||Math.sign(t)!==1)throw new TypeError(`Expected \`milliseconds\` to be a positive number, got \`${t}\``);return new Promise((l,c)=>{let s;if(e.signal){let{signal:p}=e;if(p.aborted)return c(cb(p));s=()=>c(cb(p)),p.addEventListener("abort",s,{once:!0})}let u=()=>{if(e.signal&&e.signal.removeEventListener("abort",s),n)try{l(n())}catch(p){c(p)}else{typeof r.cancel=="function"&&Promise.resolve().then(()=>r.cancel()).catch(()=>{});let p=o instanceof Error?o:new hn(o??`Promise timed out after ${t}ms`);c(p)}};t<1/0&&(a=i.setTimeout(u,t));let d=()=>{i.clearTimeout(a),e.signal&&e.signal.removeEventListener("abort",s)};Promise.resolve(r).then(p=>{d(),l(p)}).catch(p=>{d(),c(p)})})}import{PostHog as s7}from"posthog-node";import{execSync as WO}from"child_process";import Wo from"os";import $O from"v8";var ub,_r,pb=Wo.platform(),qO=Wo.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),{}),db=r=>{try{let e=!1,t=KO(),n=YO(),o=`${Math.round(t.freePercentage*100)}%`;t.freePercentage<.05&&(e=!0);let i=`${n?Math.round(n.idle):"unknown"}%`;n&&n?.total>80&&(e=!0);let a=$O.getHeapStatistics(),l=a.used_heap_size,c=a.heap_size_limit;l/c>.9&&(e=!0),e?(r.warn({memory:t,cpu:n,heapStats:a},"Critical resource usage metrics detected"),Wn&&w.warn(`Low machine resources detected (memory: ${o} free, cpu: ${i} free)`)):r.debug({memory:t,cpu:n},"Got machine resource usage metrics")}catch{}};function mb(r){if(!xr)return db(r),{interval:setInterval(()=>db(r),2e4),cpuMetadata:qO,platform:pb}}function KO(){let r=Wo.totalmem(),e=pb==="darwin"?XO():(()=>{let n=Wo.freemem();return{availableMemory:n,rawFreeMemory:n,cachedMemory:0}})(),t=e.availableMemory/r;return{totalMemory:r,freeMemory:e.availableMemory,freePercentage:t}}function YO(){let r=Wo.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,!_r)return _r=t,null;let n={user:t.user-_r.user,nice:t.nice-_r.nice,sys:t.sys-_r.sys,idle:t.idle-_r.idle,irq:t.irq-_r.irq,total:t.total-_r.total};return ub={measurementTime:e,intervalMs:e-_r.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},_r=t,ub}function XO(){try{let r=WO("/usr/bin/vm_stat",{encoding:"utf8",stdio:["pipe","pipe","ignore"]}),t=r.match(/page size of (\d+) bytes/)?.[1],n=t?Number.parseInt(t,10):4096,o=u=>{let p=r.match(new RegExp(`${u}:\\s+(\\d+)\\.`,"i"))?.[1];return p?Number.parseInt(p,10):0},i=o("Pages free"),a=o("Pages inactive"),l=o("Pages speculative"),c=i*n,s=(a+l)*n;return{availableMemory:c+s,rawFreeMemory:c,cachedMemory:s}}catch{let e=Wo.freemem();return{availableMemory:e,rawFreeMemory:e,cachedMemory:0}}}var Sl=class{increment(e,t,n){}gauge(e,t){}distribution(e,t,n){}async flush(){}async recordDuration({fn:e}){return await e()}};function JO(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 yl(r,e){let t=JO(r);return!e||Object.keys(e).length===0?t:{...e,...t}}var zb="=",vl=";",dp=",";var Hb=8192;var Yo={};ZC(Yo,{getKeyPairs:()=>PL,parseKeyPairsIntoRecord:()=>IL,parsePairKeyValue:()=>Gb,serializeKeyPairs:()=>_L});xe();var ML=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 _L(r){return r.reduce(function(e,t){var n=""+e+(e!==""?dp:"")+t;return n.length>Hb?e:n},"")}function PL(r){return r.getAllEntries().map(function(e){var t=ML(e,2),n=t[0],o=t[1],i=encodeURIComponent(n)+"="+encodeURIComponent(o.value);return o.metadata!==void 0&&(i+=vl+o.metadata.toString()),i})}function Gb(r){var e=r.split(vl);if(!(e.length<=0)){var t=e.shift();if(t){var n=t.indexOf(zb);if(!(n<=0)){var o=decodeURIComponent(t.substring(0,n).trim()),i=decodeURIComponent(t.substring(n+1).trim()),a;return e.length>0&&(a=tp(e.join(vl))),{key:o,value:i,metadata:a}}}}}function IL(r){return typeof r!="string"||r.length===0?{}:r.split(dp).map(function(e){return Gb(e)}).filter(function(e){return e!==void 0&&e.value.length>0}).reduce(function(e,t){return e[t.key]=t.value,e},{})}xe();var Al;(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"})(Al||(Al={}));var OL=",",LL=["OTEL_SDK_DISABLED"];function NL(r){return LL.indexOf(r)>-1}var DL=["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 kL(r){return DL.indexOf(r)>-1}var UL=["OTEL_NO_PATCH_MODULES","OTEL_PROPAGATORS"];function FL(r){return UL.indexOf(r)>-1}var pp=1/0,mp=128,BL=128,zL=128,gp={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:Le.INFO,OTEL_NO_PATCH_MODULES:[],OTEL_PROPAGATORS:["tracecontext","baggage"],OTEL_RESOURCE_ATTRIBUTES:"",OTEL_SERVICE_NAME:"",OTEL_ATTRIBUTE_VALUE_LENGTH_LIMIT:pp,OTEL_ATTRIBUTE_COUNT_LIMIT:mp,OTEL_SPAN_ATTRIBUTE_VALUE_LENGTH_LIMIT:pp,OTEL_SPAN_ATTRIBUTE_COUNT_LIMIT:mp,OTEL_LOGRECORD_ATTRIBUTE_VALUE_LENGTH_LIMIT:pp,OTEL_LOGRECORD_ATTRIBUTE_COUNT_LIMIT:mp,OTEL_SPAN_EVENT_COUNT_LIMIT:128,OTEL_SPAN_LINK_COUNT_LIMIT:128,OTEL_SPAN_ATTRIBUTE_PER_EVENT_COUNT_LIMIT:BL,OTEL_SPAN_ATTRIBUTE_PER_LINK_COUNT_LIMIT:zL,OTEL_TRACES_EXPORTER:"",OTEL_TRACES_SAMPLER:Al.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 HL(r,e,t){if(!(typeof t[r]>"u")){var n=String(t[r]);e[r]=n.toLowerCase()==="true"}}function GL(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 VL(r,e,t,n){n===void 0&&(n=OL);var o=t[r];typeof o=="string"&&(e[r]=o.split(n).map(function(i){return i.trim()}))}var jL={ALL:Le.ALL,VERBOSE:Le.VERBOSE,DEBUG:Le.DEBUG,INFO:Le.INFO,WARN:Le.WARN,ERROR:Le.ERROR,NONE:Le.NONE};function WL(r,e,t){var n=t[r];if(typeof n=="string"){var o=jL[n.toUpperCase()];o!=null&&(e[r]=o)}}function Vb(r){var e={};for(var t in gp){var n=t;switch(n){case"OTEL_LOG_LEVEL":WL(n,e,r);break;default:if(NL(n))HL(n,e,r);else if(kL(n))GL(n,e,r);else if(FL(n))VL(n,e,r);else{var o=r[n];typeof o<"u"&&o!==null&&(e[n]=String(o))}}}return e}function gt(){var r=Vb(process.env);return Object.assign({},gp,r)}function jb(r){return r>=48&&r<=57?r-48:r>=97&&r<=102?r-87:r-55}function wl(r){for(var e=new Uint8Array(r.length/2),t=0,n=0;n<r.length;n+=2){var o=jb(r.charCodeAt(n)),i=jb(r.charCodeAt(n+1));e[t++]=o<<4|i}return e}var Wb="1.25.1";var $L="deployment.environment";var qL="process.runtime.name";var KL="service.name";var YL="service.instance.id";var XL="telemetry.sdk.name",JL="telemetry.sdk.language",ZL="telemetry.sdk.version";var $b=$L;var qb=qL;var Rl=KL;var Kb=YL;var Ra=XL,Ca=JL,xa=ZL;var QL="nodejs";var Yb=QL;var Xo,Cl=(Xo={},Xo[Ra]="opentelemetry",Xo[qb]="node",Xo[Ca]=Yb,Xo[xa]=Wb,Xo);var eN=9,tN=6,rN=Math.pow(10,tN),nN=Math.pow(10,eN);function Xb(r){var e=r/1e3,t=Math.trunc(e),n=Math.round(r%1e3*rN);return[t,n]}function Jb(r){return r[0]*nN+r[1]}function Ma(r){return r[0]*1e6+r[1]/1e3}var qn;(function(r){r[r.SUCCESS=0]="SUCCESS",r[r.FAILED=1]="FAILED"})(qn||(qn={}));var Zb=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 oN=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},iN=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))},Qb=function(){function r(e,t){this._callback=e,this._that=t,this._isCalled=!1,this._deferred=new Zb}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,iN([this._that],oN(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 nr;(function(r){r[r.DELTA=0]="DELTA",r[r.CUMULATIVE=1]="CUMULATIVE"})(nr||(nr={}));var vt;(function(r){r[r.HISTOGRAM=0]="HISTOGRAM",r[r.EXPONENTIAL_HISTOGRAM=1]="EXPONENTIAL_HISTOGRAM",r[r.GAUGE=2]="GAUGE",r[r.SUM=3]="SUM"})(vt||(vt={}));var aN=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 Ite=function(r){aN(e,r);function e(t){var n=r.call(this,t)||this;return Object.setPrototypeOf(n,e.prototype),n}return e}(Error);function eE(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}xe();var or;(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"})(or||(or={}));var tE=function(){function r(){this.kind=or.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 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={}));var sN=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 lN(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 hp=function(){function r(e,t,n,o){n===void 0&&(n=!0),o===void 0&&(o=lN(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=eE(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 fp=function(){function r(e,t){this._boundaries=e,this._recordMinMax=t,this.kind=or.HISTOGRAM}return r.prototype.createAccumulation=function(e){return new hp(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 hp(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 hp(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:vt.HISTOGRAM,dataPoints:n.map(function(i){var a=sN(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}();xe();var Sp=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},yp=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))},bp=function(){function r(e,t,n,o){e===void 0&&(e=new cN),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 cN=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,yp([n,this._counts.length-t],Sp(this._counts.slice(t)),!1)),o.splice.apply(o,yp([0,t],Sp(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(yp([],Sp(this._counts),!1))},r}();var rE=52,uN=2146435072,dN=1048575,Ep=1023,xl=-Ep+1,Ml=Ep,_a=Math.pow(2,-1022);function _l(r){var e=new DataView(new ArrayBuffer(8));e.setFloat64(0,r);var t=e.getUint32(0),n=(t&uN)>>20;return n-Ep}function Pl(r){var e=new DataView(new ArrayBuffer(8));e.setFloat64(0,r);var t=e.getUint32(0),n=e.getUint32(4),o=(t&dN)*Math.pow(2,32);return o+n}function Pa(r,e){return r===0||r===Number.POSITIVE_INFINITY||r===Number.NEGATIVE_INFINITY||Number.isNaN(r)?r:r*Math.pow(2,e)}function oE(r){return r--,r|=r>>1,r|=r>>2,r|=r>>4,r|=r>>8,r|=r>>16,r++,r}var pN=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)}}(),fn=function(r){pN(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<_a)return this._minNormalLowerBoundaryIndex();var t=_l(e),n=this._rightShift(Pl(e)-1,rE);return t+n>>this._shift},r.prototype.lowerBoundary=function(e){var t=this._minNormalLowerBoundaryIndex();if(e<t)throw new fn("underflow: "+e+" is < minimum lower boundary: "+t);var n=this._maxNormalLowerBoundaryIndex();if(e>n)throw new fn("overflow: "+e+" is > maximum lower boundary: "+n);return Pa(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=xl>>this._shift;return this._shift<2&&e--,e},r.prototype._maxNormalLowerBoundaryIndex=function(){return Ml>>this._shift},r.prototype._rightShift=function(e,t){return Math.floor(e*Math.pow(2,-t))},r}();var sE=function(){function r(e){this._scale=e,this._scaleFactor=Pa(Math.LOG2E,e),this._inverseFactor=Pa(Math.LN2,-e)}return r.prototype.mapToIndex=function(e){if(e<=_a)return this._minNormalLowerBoundaryIndex()-1;if(Pl(e)===0){var t=_l(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 fn("overflow: "+e+" is > maximum lower boundary: "+t)}var n=this._minNormalLowerBoundaryIndex();if(e<=n){if(e===n)return _a;if(e===n-1)return Math.exp((e+(1<<this._scale))/this._scaleFactor)/2;throw new fn("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 xl<<this._scale},r.prototype._maxNormalLowerBoundaryIndex=function(){return(Ml+1<<this._scale)-1},r}();var lE=-10,cE=20,mN=Array.from({length:31},function(r,e){return e>10?new sE(e-10):new aE(e-10)});function Tp(r){if(r>cE||r<lE)throw new fn("expected scale >= "+lE+" && <= "+cE+", got: "+r);return mN[r+10]}var gN=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},Il=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}(),hN=20,fN=160,vp=2,SN=function(){function r(e,t,n,o,i,a,l,c,s,u,d){e===void 0&&(e=e),t===void 0&&(t=fN),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 bp),u===void 0&&(u=new bp),d===void 0&&(d=Tp(hN)),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<vp&&(H.warn("Exponential Histogram Max Size set to "+this._maxSize+", changing to the minimum size of: "+vp),this._maxSize=vp)}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=oE(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=Tp(t)}},r.prototype._minScale=function(e){var t=Math.min(this.scale,e.scale),n=Il.combine(this._highLowAtScale(this.positive,this.scale,t),this._highLowAtScale(e.positive,e.scale,t)),o=Il.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 Il(0,-1);var o=t-n;return new Il(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 uE=function(){function r(e,t){this._maxSize=e,this._recordMinMax=t,this.kind=or.EXPONENTIAL_HISTOGRAM}return r.prototype.createAccumulation=function(e){return new SN(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:vt.EXPONENTIAL_HISTOGRAM,dataPoints:n.map(function(i){var a=gN(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}();var yN=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},Ap=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=Xb(Date.now())},r.prototype.setStartTime=function(e){this.startTime=e},r.prototype.toPointValue=function(){return this._current},r}();var dE=function(){function r(){this.kind=or.LAST_VALUE}return r.prototype.createAccumulation=function(e){return new Ap(e)},r.prototype.merge=function(e,t){var n=Ma(t.sampleTime)>=Ma(e.sampleTime)?t:e;return new Ap(e.startTime,n.toPointValue(),n.sampleTime)},r.prototype.diff=function(e,t){var n=Ma(t.sampleTime)>=Ma(e.sampleTime)?t:e;return new Ap(t.startTime,n.toPointValue(),n.sampleTime)},r.prototype.toMetricData=function(e,t,n,o){return{descriptor:e,aggregationTemporality:t,dataPointType:vt.GAUGE,dataPoints:n.map(function(i){var a=yN(i,2),l=a[0],c=a[1];return{attributes:l,startTime:c.startTime,endTime:o,value:c.toPointValue()}})}},r}();var bN=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},Ia=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 wp=function(){function r(e){this.monotonic=e,this.kind=or.SUM}return r.prototype.createAccumulation=function(e){return new Ia(e,this.monotonic)},r.prototype.merge=function(e,t){var n=e.toPointValue(),o=t.toPointValue();return t.reset?new Ia(t.startTime,this.monotonic,o,t.reset):new Ia(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 Ia(t.startTime,this.monotonic,o,!0):new Ia(t.startTime,this.monotonic,o-n)},r.prototype.toMetricData=function(e,t,n,o){return{descriptor:e,aggregationTemporality:t,dataPointType:vt.SUM,dataPoints:n.map(function(i){var a=bN(i,2),l=a[0],c=a[1];return{attributes:l,startTime:c.startTime,endTime:o,value:c.toPointValue()}}),isMonotonic:this.monotonic}},r}();var Kn=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)}}(),Ir=function(){function r(){}return r.Drop=function(){return bE},r.Sum=function(){return EE},r.LastValue=function(){return TE},r.Histogram=function(){return vE},r.ExponentialHistogram=function(){return EN},r.Default=function(){return TN},r}();var pE=function(r){Kn(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 tE,e}(Ir);var mE=function(r){Kn(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 wp(!0),e.NON_MONOTONIC_INSTANCE=new wp(!1),e}(Ir);var gE=function(r){Kn(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 dE,e}(Ir);var hE=function(r){Kn(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 fp([0,5,10,25,50,75,100,250,500,750,1e3,2500,5e3,7500,1e4],!0),e}(Ir);var fE=function(r){Kn(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 fp(this._boundaries,this._recordMinMax)},e}(Ir);var SE=function(r){Kn(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 uE(this._maxSize,this._recordMinMax)},e}(Ir);var yE=function(r){Kn(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 EE;case oe.GAUGE:case oe.OBSERVABLE_GAUGE:return TE;case oe.HISTOGRAM:return t.advice.explicitBucketBoundaries?new fE(t.advice.explicitBucketBoundaries):vE}return H.warn("Unable to recognize instrument type: "+t.type),bE},e.prototype.createAggregator=function(t){return this._resolve(t).createAggregator(t)},e}(Ir);var bE=new pE,EE=new mE,TE=new gE,vE=new hE,EN=new SE,TN=new yE;xe();function Ol(){return"unknown_service:"+process.argv0}var Sn=function(){return Sn=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},Sn.apply(this,arguments)},vN=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())})},AN=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}}},wN=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},Rp=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 H.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[Rl]=Ol(),e[Ca]=Cl[Ca],e[Ra]=Cl[Ra],e[xa]=Cl[xa],e))},Object.defineProperty(r.prototype,"attributes",{get:function(){var e;return this.asyncAttributesPending&&H.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 vN(this,void 0,void 0,function(){return AN(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=Sn(Sn({},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=wN(a,2),s=c[0],u=c[1];return Sn(Sn(Sn(Sn({},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 Yn;(function(r){r[r.DELTA=0]="DELTA",r[r.CUMULATIVE=1]="CUMULATIVE",r[r.LOWMEMORY=2]="LOWMEMORY"})(Yn||(Yn={}));xe();var RN=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())})},CN=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}}},Cp=function(){return nr.CUMULATIVE},AE=function(r){switch(r){case oe.COUNTER:case oe.OBSERVABLE_COUNTER:case oe.GAUGE:case oe.HISTOGRAM:case oe.OBSERVABLE_GAUGE:return nr.DELTA;case oe.UP_DOWN_COUNTER:case oe.OBSERVABLE_UP_DOWN_COUNTER:return nr.CUMULATIVE}},wE=function(r){switch(r){case oe.COUNTER:case oe.HISTOGRAM:return nr.DELTA;case oe.GAUGE:case oe.UP_DOWN_COUNTER:case oe.OBSERVABLE_UP_DOWN_COUNTER:case oe.OBSERVABLE_COUNTER:case oe.OBSERVABLE_GAUGE:return nr.CUMULATIVE}};function xN(){var r=gt(),e=r.OTEL_EXPORTER_OTLP_METRICS_TEMPORALITY_PREFERENCE.trim().toLowerCase();return e==="cumulative"?Cp:e==="delta"?AE:e==="lowmemory"?wE:(H.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."),Cp)}function MN(r){return r!=null?r===Yn.DELTA?AE:r===Yn.LOWMEMORY?wE:Cp:xN()}function _N(r){return r?.aggregationPreference?r.aggregationPreference:function(e){return Ir.Default()}}var RE=function(){function r(e,t){this._otlpExporter=e,this._aggregationSelector=_N(t),this._aggregationTemporalitySelector=MN(t?.temporalityPreference)}return r.prototype.export=function(e,t){this._otlpExporter.export([e],t)},r.prototype.shutdown=function(){return RN(this,void 0,void 0,function(){return CN(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}();xe();xe();var PN=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},CE=1e4,xE=5,ME=1e3,_E=5e3,PE=1.5;function Oa(r){r===void 0&&(r={});var e={};return Object.entries(r).forEach(function(t){var n=PN(t,2),o=n[0],i=n[1];typeof i<"u"?e[o]=String(i):H.warn('Header "'+o+'" has invalid value ('+i+") and will be ignored")}),e}function xp(r,e){return r.endsWith("/")||(r=r+"/"),r+e}function Mp(r){try{var e=new URL(r);return e.pathname===""&&(e.pathname=e.pathname+"/"),e.toString()}catch{return H.warn("Could not parse export URL: '"+r+"'"),r}}function _p(r){return typeof r=="number"?r<=0?Pp(r,CE):r:IN()}function IN(){var r,e=Number((r=gt().OTEL_EXPORTER_OTLP_TRACES_TIMEOUT)!==null&&r!==void 0?r:gt().OTEL_EXPORTER_OTLP_TIMEOUT);return e<=0?Pp(e,CE):e}function Pp(r,e){return H.warn("Timeout must be greater than 0",r),e}function IE(r){var e=[429,502,503,504];return e.includes(r)}function OE(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 LE=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 Qb(this._shutdown,this),this._concurrencyLimit=typeof e.concurrencyLimit=="number"?e.concurrencyLimit:30,this.timeoutMillis=_p(e.timeoutMillis),this.onInit(e)}return r.prototype.export=function(e,t){if(this._shutdownOnce.isCalled){t({code:qn.FAILED,error:new Error("Exporter has been shutdown")});return}if(this._sendingPromises.length>=this._concurrencyLimit){t({code:qn.FAILED,error:new Error("Concurrent export limit reached")});return}this._export(e).then(function(){t({code:qn.SUCCESS})}).catch(function(n){t({code:qn.FAILED,error:n})})},r.prototype._export=function(e){var t=this;return new Promise(function(n,o){try{H.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 H.debug("shutdown started"),this.onShutdown(),this.forceFlush()},r}();xe();import*as Ip from"url";import*as Nl from"http";import*as Dl from"https";import*as NE from"zlib";import{Readable as LN}from"stream";var yn;(function(r){r.NONE="none",r.GZIP="gzip"})(yn||(yn={}));var ON=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)}}(),Jo=function(r){ON(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 Ll=function(){return Ll=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},Ll.apply(this,arguments)};function Op(r,e,t,n,o){var i=r.timeoutMillis,a=new Ip.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 Jo("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:Ll({"Content-Type":t},r.headers),agent:r.agent},m=a.protocol==="http:"?Nl.request:Dl.request,g=function(h,f){switch(h===void 0&&(h=xE),f===void 0&&(f=ME),s=m(p,function(b){var x="";b.on("data",function(A){return x+=A}),b.on("aborted",function(){if(u){var A=new Jo("Request Timeout");o(A)}}),b.on("end",function(){if(u===!1)if(b.statusCode&&b.statusCode<299)H.debug("statusCode: "+b.statusCode,x),n(),clearTimeout(d),clearTimeout(c);else if(b.statusCode&&IE(b.statusCode)&&h>0){var A=void 0;f=PE*f,b.headers["retry-after"]?A=OE(b.headers["retry-after"]):A=Math.round(Math.random()*(_E-f)+f),c=setTimeout(function(){g(h-1,f)},A)}else{var v=new Jo(b.statusMessage,b.statusCode,x);o(v),clearTimeout(d),clearTimeout(c)}})}),s.on("error",function(b){if(u){var x=new Jo("Request Timeout",b.code);o(x)}else o(b);clearTimeout(d),clearTimeout(c)}),s.on("abort",function(){if(u){var b=new Jo("Request Timeout");o(b)}clearTimeout(d),clearTimeout(c)}),r.compression){case yn.GZIP:{s.setHeader("Content-Encoding","gzip");var E=NN(e);E.on("error",o).pipe(NE.createGzip()).on("error",o).pipe(s);break}default:s.end(Buffer.from(e));break}};g()}function NN(r){var e=new LN;return e.push(r),e.push(null),e}function Lp(r){if(r.httpAgentOptions&&r.keepAlive===!1){H.warn("httpAgentOptions is used only when keepAlive is true");return}if(!(r.keepAlive===!1||!r.url))try{var e=new Ip.URL(r.url),t=e.protocol==="http:"?Nl.Agent:Dl.Agent;return new t(Ll({keepAlive:!0},r.httpAgentOptions))}catch(n){H.error("collector exporter failed to create http agent. err: "+n.message);return}}function Np(r){if(r)return r;var e=gt().OTEL_EXPORTER_OTLP_TRACES_COMPRESSION||gt().OTEL_EXPORTER_OTLP_COMPRESSION;return e===yn.GZIP?yn.GZIP:yn.NONE}xe();var DN=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)}}(),kl=function(r){DN(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&&H.warn("Metadata cannot be set when using http"),i.headers=Object.assign(i.DEFAULT_HEADERS,Oa(t.headers),Yo.parseKeyPairsIntoRecord(gt().OTEL_EXPORTER_OTLP_HEADERS)),i.agent=Lp(t),i.compression=Np(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){H.debug("Shutdown already started. Cannot send objects");return}var a=new Promise(function(c,s){var u;Op(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}(LE);function kE(r){var e=BigInt(1e9);return BigInt(r[0])*e+BigInt(r[1])}function kN(r){var e=Number(BigInt.asUintN(32,r)),t=Number(BigInt.asUintN(32,r>>BigInt(32)));return{low:e,high:t}}function UE(r){var e=kE(r);return kN(e)}function UN(r){var e=kE(r);return e.toString()}var FN=typeof BigInt<"u"?UN:Jb;function DE(r){return r}function FE(r){if(r!==void 0)return wl(r)}var BN={encodeHrTime:UE,encodeSpanContext:wl,encodeOptionalSpanContext:FE};function BE(r){var e,t;if(r===void 0)return BN;var n=(e=r.useLongBits)!==null&&e!==void 0?e:!0,o=(t=r.useHex)!==null&&t!==void 0?t:!1;return{encodeHrTime:n?UE:FN,encodeSpanContext:o?DE:wl,encodeOptionalSpanContext:o?DE:FE}}var zN=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 zE(r){return{name:r.name,version:r.version}}function Zo(r){return Object.keys(r).map(function(e){return HE(e,r[e])})}function HE(r,e){return{key:r,value:GE(e)}}function GE(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(GE)}}:e==="object"&&r!=null?{kvlistValue:{values:Object.entries(r).map(function(t){var n=zN(t,2),o=n[0],i=n[1];return HE(o,i)})}}:{}}function VE(r){return{attributes:Zo(r.attributes),droppedAttributesCount:0}}xe();function WE(r,e){var t=BE(e);return{resource:VE(r.resource),schemaUrl:void 0,scopeMetrics:HN(r.scopeMetrics,t)}}function HN(r,e){return Array.from(r.map(function(t){return{scope:zE(t.scope),metrics:t.metrics.map(function(n){return GN(n,e)}),schemaUrl:t.scope.schemaUrl}}))}function GN(r,e){var t={name:r.descriptor.name,description:r.descriptor.description,unit:r.descriptor.unit},n=$N(r.aggregationTemporality);switch(r.dataPointType){case vt.SUM:t.sum={aggregationTemporality:n,isMonotonic:r.isMonotonic,dataPoints:jE(r,e)};break;case vt.GAUGE:t.gauge={dataPoints:jE(r,e)};break;case vt.HISTOGRAM:t.histogram={aggregationTemporality:n,dataPoints:jN(r,e)};break;case vt.EXPONENTIAL_HISTOGRAM:t.exponentialHistogram={aggregationTemporality:n,dataPoints:WN(r,e)};break}return t}function VN(r,e,t){var n={attributes:Zo(r.attributes),startTimeUnixNano:t.encodeHrTime(r.startTime),timeUnixNano:t.encodeHrTime(r.endTime)};switch(e){case Ht.INT:n.asInt=r.value;break;case Ht.DOUBLE:n.asDouble=r.value;break}return n}function jE(r,e){return r.dataPoints.map(function(t){return VN(t,r.descriptor.valueType,e)})}function jN(r,e){return r.dataPoints.map(function(t){var n=t.value;return{attributes:Zo(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 WN(r,e){return r.dataPoints.map(function(t){var n=t.value;return{attributes:Zo(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 $N(r){switch(r){case nr.DELTA:return 1;case nr.CUMULATIVE:return 2}}function $E(r,e){return{resourceMetrics:r.map(function(t){return WE(t,e)})}}var Dp={serializeRequest:function(r){var e=$E(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 qE="0.52.1";var KE=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)}}(),Qo=function(){return Qo=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},Qo.apply(this,arguments)},YE="v1/metrics",qN="http://localhost:4318/"+YE,KN={"User-Agent":"OTel-OTLP-Exporter-JavaScript/"+qE},YN=function(r){KE(e,r);function e(t){var n=r.call(this,t,Dp,"application/json")||this;return n.headers=Qo(Qo(Qo(Qo({},n.headers),KN),Yo.parseKeyPairsIntoRecord(gt().OTEL_EXPORTER_OTLP_METRICS_HEADERS)),Oa(t?.headers)),n}return e.prototype.getDefaultUrl=function(t){return typeof t.url=="string"?t.url:gt().OTEL_EXPORTER_OTLP_METRICS_ENDPOINT.length>0?Mp(gt().OTEL_EXPORTER_OTLP_METRICS_ENDPOINT):gt().OTEL_EXPORTER_OTLP_ENDPOINT.length>0?xp(gt().OTEL_EXPORTER_OTLP_ENDPOINT,YE):qN},e}(kl),XE=function(r){KE(e,r);function e(t){return r.call(this,new YN(t),t)||this}return e}(RE);var ei;(function(r){r[r.DELTA=0]="DELTA",r[r.CUMULATIVE=1]="CUMULATIVE"})(ei||(ei={}));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={}));xe();var 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)}}(),JE=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())})},ZE=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}}},JN=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},ZN=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))},QN=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 QE(r){return r!=null}function Ul(r){var e=Object.keys(r);return e.length===0?"":(e=e.sort(),JSON.stringify(e.map(function(t){return[t,r[t]]})))}function eT(r){var e,t;return r.name+":"+((e=r.version)!==null&&e!==void 0?e:"")+":"+((t=r.schemaUrl)!==null&&t!==void 0?t:"")}var kp=function(r){XN(e,r);function e(t){var n=r.call(this,t)||this;return Object.setPrototypeOf(n,e.prototype),n}return e}(Error);function bn(r,e){var t,n=new Promise(function(i,a){t=setTimeout(function(){a(new kp("Operation timed out."))},e)});return Promise.race([r,n]).then(function(o){return clearTimeout(t),o},function(o){throw clearTimeout(t),o})}function tT(r){return JE(this,void 0,void 0,function(){var e=this;return ZE(this,function(t){return[2,Promise.all(r.map(function(n){return JE(e,void 0,void 0,function(){var o,i;return ZE(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 rT(r){return r.status==="rejected"}function Up(r,e){var t=[];return r.forEach(function(n){t.push.apply(t,ZN([],JN(e(n)),!1))}),t}function nT(r,e){var t,n;if(r.size!==e.size)return!1;try{for(var o=QN(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 oT(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 iT(r,e){return r.toLowerCase()===e.toLowerCase()}xe();var ir;(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"})(ir||(ir={}));var Fp=function(){function r(){this.kind=ir.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}();xe();var de;(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"})(de||(de={}));function Lr(r,e,t){var n,o,i,a;return tD(r)||H.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:Ht.DOUBLE,advice:(a=t?.advice)!==null&&a!==void 0?a:{}}}function aT(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 sT(r,e){return iT(r.name,e.name)&&r.unit===e.unit&&r.type===e.type&&r.valueType===e.valueType}var eD=/^[a-z][a-z0-9_.\-/]{0,254}$/i;function tD(r){return r.match(eD)!=null}var rD=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 nD(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 Fl=function(){function r(e,t,n,o){n===void 0&&(n=!0),o===void 0&&(o=nD(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=oT(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 Bl=function(){function r(e,t){this._boundaries=e,this._recordMinMax=t,this.kind=ir.HISTOGRAM}return r.prototype.createAccumulation=function(e){return new Fl(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 Fl(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 Fl(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=rD(i,2),l=a[0],c=a[1],s=c.toPointValue(),u=e.type===de.GAUGE||e.type===de.UP_DOWN_COUNTER||e.type===de.OBSERVABLE_GAUGE||e.type===de.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}();xe();var Bp=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},zp=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))},Hp=function(){function r(e,t,n,o){e===void 0&&(e=new oD),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 oD=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,zp([n,this._counts.length-t],Bp(this._counts.slice(t)),!1)),o.splice.apply(o,zp([0,t],Bp(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(zp([],Bp(this._counts),!1))},r}();var lT=52,iD=2146435072,aD=1048575,Gp=1023,zl=-Gp+1,Hl=Gp,La=Math.pow(2,-1022);function Gl(r){var e=new DataView(new ArrayBuffer(8));e.setFloat64(0,r);var t=e.getUint32(0),n=(t&iD)>>20;return n-Gp}function Vl(r){var e=new DataView(new ArrayBuffer(8));e.setFloat64(0,r);var t=e.getUint32(0),n=e.getUint32(4),o=(t&aD)*Math.pow(2,32);return o+n}function Na(r,e){return r===0||r===Number.POSITIVE_INFINITY||r===Number.NEGATIVE_INFINITY||Number.isNaN(r)?r:r*Math.pow(2,e)}function uT(r){return r--,r|=r>>1,r|=r>>2,r|=r>>4,r|=r>>8,r|=r>>16,r++,r}var sD=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)}}(),En=function(r){sD(e,r);function e(){return r!==null&&r.apply(this,arguments)||this}return e}(Error);var pT=function(){function r(e){this._shift=-e}return r.prototype.mapToIndex=function(e){if(e<La)return this._minNormalLowerBoundaryIndex();var t=Gl(e),n=this._rightShift(Vl(e)-1,lT);return t+n>>this._shift},r.prototype.lowerBoundary=function(e){var t=this._minNormalLowerBoundaryIndex();if(e<t)throw new En("underflow: "+e+" is < minimum lower boundary: "+t);var n=this._maxNormalLowerBoundaryIndex();if(e>n)throw new En("overflow: "+e+" is > maximum lower boundary: "+n);return Na(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=zl>>this._shift;return this._shift<2&&e--,e},r.prototype._maxNormalLowerBoundaryIndex=function(){return Hl>>this._shift},r.prototype._rightShift=function(e,t){return Math.floor(e*Math.pow(2,-t))},r}();var mT=function(){function r(e){this._scale=e,this._scaleFactor=Na(Math.LOG2E,e),this._inverseFactor=Na(Math.LN2,-e)}return r.prototype.mapToIndex=function(e){if(e<=La)return this._minNormalLowerBoundaryIndex()-1;if(Vl(e)===0){var t=Gl(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 En("overflow: "+e+" is > maximum lower boundary: "+t)}var n=this._minNormalLowerBoundaryIndex();if(e<=n){if(e===n)return La;if(e===n-1)return Math.exp((e+(1<<this._scale))/this._scaleFactor)/2;throw new En("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 zl<<this._scale},r.prototype._maxNormalLowerBoundaryIndex=function(){return(Hl+1<<this._scale)-1},r}();var gT=-10,hT=20,lD=Array.from({length:31},function(r,e){return e>10?new mT(e-10):new pT(e-10)});function Vp(r){if(r>hT||r<gT)throw new En("expected scale >= "+gT+" && <= "+hT+", got: "+r);return lD[r+10]}var cD=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},jl=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}(),uD=20,dD=160,jp=2,fT=function(){function r(e,t,n,o,i,a,l,c,s,u,d){e===void 0&&(e=e),t===void 0&&(t=dD),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 Hp),u===void 0&&(u=new Hp),d===void 0&&(d=Vp(uD)),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<jp&&(H.warn("Exponential Histogram Max Size set to "+this._maxSize+", changing to the minimum size of: "+jp),this._maxSize=jp)}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=uT(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=Vp(t)}},r.prototype._minScale=function(e){var t=Math.min(this.scale,e.scale),n=jl.combine(this._highLowAtScale(this.positive,this.scale,t),this._highLowAtScale(e.positive,e.scale,t)),o=jl.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 jl(0,-1);var o=t-n;return new jl(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 Wp=function(){function r(e,t){this._maxSize=e,this._recordMinMax=t,this.kind=ir.EXPONENTIAL_HISTOGRAM}return r.prototype.createAccumulation=function(e){return new fT(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=cD(i,2),l=a[0],c=a[1],s=c.toPointValue(),u=e.type===de.GAUGE||e.type===de.UP_DOWN_COUNTER||e.type===de.OBSERVABLE_GAUGE||e.type===de.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}();xe();var pD=rp("OpenTelemetry SDK Context Key SUPPRESS_TRACING");function ST(r){return r.setValue(pD,!0)}xe();function yT(){return function(r){H.error(mD(r))}}function mD(r){return typeof r=="string"?r:JSON.stringify(gD(r))}function gD(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 hD=yT();function Wl(r){try{hD(r)}catch{}}var bT="1.30.1";var fD="process.runtime.name";var SD="service.name";var yD="telemetry.sdk.name",bD="telemetry.sdk.language",ED="telemetry.sdk.version";var ET=fD;var TT=SD;var Da=yD,ka=bD,Ua=ED;var TD="nodejs";var vT=TD;var ti,Xn=(ti={},ti[Da]="opentelemetry",ti[ET]="node",ti[ka]=vT,ti[Ua]=bT,ti);function Fa(r){r.unref()}var MD=9,_D=6,PD=Math.pow(10,_D),Doe=Math.pow(10,MD);function Jn(r){var e=r/1e3,t=Math.trunc(e),n=Math.round(r%1e3*PD);return[t,n]}function ri(r){return r[0]*1e6+r[1]/1e3}var Ba;(function(r){r[r.SUCCESS=0]="SUCCESS",r[r.FAILED=1]="FAILED"})(Ba||(Ba={}));xe();function AT(r,e){return new Promise(function(t){Ko.with(ST(Ko.active()),function(){r.export(e,function(n){t(n)})})})}var wT={_export:AT};var ID=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(){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=Jn(Date.now())},r.prototype.setStartTime=function(e){this.startTime=e},r.prototype.toPointValue=function(){return this._current},r}();var $p=function(){function r(){this.kind=ir.LAST_VALUE}return r.prototype.createAccumulation=function(e){return new $l(e)},r.prototype.merge=function(e,t){var n=ri(t.sampleTime)>=ri(e.sampleTime)?t:e;return new $l(e.startTime,n.toPointValue(),n.sampleTime)},r.prototype.diff=function(e,t){var n=ri(t.sampleTime)>=ri(e.sampleTime)?t:e;return new $l(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=ID(i,2),l=a[0],c=a[1];return{attributes:l,startTime:c.startTime,endTime:o,value:c.toPointValue()}})}},r}();var OD=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},ni=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 ql=function(){function r(e){this.monotonic=e,this.kind=ir.SUM}return r.prototype.createAccumulation=function(e){return new ni(e,this.monotonic)},r.prototype.merge=function(e,t){var n=e.toPointValue(),o=t.toPointValue();return t.reset?new ni(t.startTime,this.monotonic,o,t.reset):new ni(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 ni(t.startTime,this.monotonic,o,!0):new ni(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=OD(i,2),l=a[0],c=a[1];return{attributes:l,startTime:c.startTime,endTime:o,value:c.toPointValue()}}),isMonotonic:this.monotonic}},r}();var Zn=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)}}(),ar=function(){function r(){}return r.Drop=function(){return IT},r.Sum=function(){return OT},r.LastValue=function(){return LT},r.Histogram=function(){return NT},r.ExponentialHistogram=function(){return LD},r.Default=function(){return ND},r}();var RT=function(r){Zn(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 Fp,e}(ar);var CT=function(r){Zn(e,r);function e(){return r!==null&&r.apply(this,arguments)||this}return e.prototype.createAggregator=function(t){switch(t.type){case de.COUNTER:case de.OBSERVABLE_COUNTER:case de.HISTOGRAM:return e.MONOTONIC_INSTANCE;default:return e.NON_MONOTONIC_INSTANCE}},e.MONOTONIC_INSTANCE=new ql(!0),e.NON_MONOTONIC_INSTANCE=new ql(!1),e}(ar);var xT=function(r){Zn(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 $p,e}(ar);var MT=function(r){Zn(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 Bl([0,5,10,25,50,75,100,250,500,750,1e3,2500,5e3,7500,1e4],!0),e}(ar);var za=function(r){Zn(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 Bl(this._boundaries,this._recordMinMax)},e}(ar);var _T=function(r){Zn(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 Wp(this._maxSize,this._recordMinMax)},e}(ar);var PT=function(r){Zn(e,r);function e(){return r!==null&&r.apply(this,arguments)||this}return e.prototype._resolve=function(t){switch(t.type){case de.COUNTER:case de.UP_DOWN_COUNTER:case de.OBSERVABLE_COUNTER:case de.OBSERVABLE_UP_DOWN_COUNTER:return OT;case de.GAUGE:case de.OBSERVABLE_GAUGE:return LT;case de.HISTOGRAM:return t.advice.explicitBucketBoundaries?new za(t.advice.explicitBucketBoundaries):NT}return H.warn("Unable to recognize instrument type: "+t.type),IT},e.prototype.createAggregator=function(t){return this._resolve(t).createAggregator(t)},e}(ar);var IT=new RT,OT=new CT,LT=new xT,NT=new MT,LD=new _T,ND=new PT;var DT=function(r){return ar.Default()},kT=function(r){return ei.CUMULATIVE};var qp=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())})},Kp=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}}},UT=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},DD=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))},FT=function(){function r(e){var t,n,o;this._shutdown=!1,this._aggregationSelector=(t=e?.aggregationSelector)!==null&&t!==void 0?t:DT,this._aggregationTemporalitySelector=(n=e?.aggregationTemporalitySelector)!==null&&n!==void 0?n:kT,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 qp(this,void 0,void 0,function(){var t,n,o,i,a,l;return Kp(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(DD([this._sdkMetricProducer.collect({timeoutMillis:e?.timeoutMillis})],UT(this._metricProducers.map(function(s){return s.collect({timeoutMillis:e?.timeoutMillis})})),!1))];case 1:return t=UT.apply(void 0,[c.sent()]),n=t[0],o=t.slice(1),i=n.errors.concat(Up(o,function(s){return s.errors})),a=n.resourceMetrics.resource,l=n.resourceMetrics.scopeMetrics.concat(Up(o,function(s){return s.resourceMetrics.scopeMetrics})),[2,{resourceMetrics:{resource:a,scopeMetrics:l},errors:i}]}})})},r.prototype.shutdown=function(e){return qp(this,void 0,void 0,function(){return Kp(this,function(t){switch(t.label){case 0:return this._shutdown?(H.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,bn(this.onShutdown(),e.timeoutMillis)];case 3:t.sent(),t.label=4;case 4:return this._shutdown=!0,[2]}})})},r.prototype.forceFlush=function(e){return qp(this,void 0,void 0,function(){return Kp(this,function(t){switch(t.label){case 0:return this._shutdown?(H.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,bn(this.onForceFlush(),e.timeoutMillis)];case 3:return t.sent(),[2]}})})},r}();xe();var kD=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)}}(),Kl=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())})},Yl=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}}},UD=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},FD=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))},Yp=function(r){kD(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 Kl(this,void 0,void 0,function(){var t;return Yl(this,function(n){switch(n.label){case 0:return n.trys.push([0,2,,3]),[4,bn(this._doRun(),this._exportTimeout)];case 1:return n.sent(),[3,3];case 2:return t=n.sent(),t instanceof kp?(H.error("Export took longer than %s milliseconds and timed out.",this._exportTimeout),[2]):(Wl(t),[3,3]);case 3:return[2]}})})},e.prototype._doRun=function(){var t,n;return Kl(this,void 0,void 0,function(){var o,i,a,l,c,s;return Yl(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=H).error.apply(s,FD(["PeriodicExportingMetricReader: metrics collection errors"],UD(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(),H.debug("Error while resolving async portion of resource: ",l),Wl(l),[3,5];case 5:return i.scopeMetrics.length===0?[2]:[4,wT._export(this._exporter,i)];case 6:if(c=u.sent(),c.code!==Ba.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),Fa(this._interval)},e.prototype.onForceFlush=function(){return Kl(this,void 0,void 0,function(){return Yl(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 Kl(this,void 0,void 0,function(){return Yl(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}(FT);xe();xe();function Xl(){return"unknown_service:"+process.argv0}var Tn=function(){return Tn=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},Tn.apply(this,arguments)},BD=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())})},zD=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}}},HD=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},Jl=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 H.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[TT]=Xl(),e[ka]=Xn[ka],e[Da]=Xn[Da],e[Ua]=Xn[Ua],e))},Object.defineProperty(r.prototype,"attributes",{get:function(){var e;return this.asyncAttributesPending&&H.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 BD(this,void 0,void 0,function(){return zD(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=Tn(Tn({},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=HD(a,2),s=c[0],u=c[1];return Tn(Tn(Tn(Tn({},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 BT=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}();xe();var Qn=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)}}(),Zl=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=Ko.active()),typeof e!="number"){H.warn("non-number value provided to metric "+this._descriptor.name+": "+e);return}this._descriptor.valueType===Ht.INT&&!Number.isInteger(e)&&(H.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,Jn(Date.now()))},r}();var zT=function(r){Qn(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}(Zl);var HT=function(r){Qn(e,r);function e(){return r!==null&&r.apply(this,arguments)||this}return e.prototype.add=function(t,n,o){if(t<0){H.warn("negative value provided to counter "+this._descriptor.name+": "+t);return}this._record(t,n,o)},e}(Zl);var GT=function(r){Qn(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}(Zl);var VT=function(r){Qn(e,r);function e(){return r!==null&&r.apply(this,arguments)||this}return e.prototype.record=function(t,n,o){if(t<0){H.warn("negative value provided to histogram "+this._descriptor.name+": "+t);return}this._record(t,n,o)},e}(Zl);var Ql=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 jT=function(r){Qn(e,r);function e(){return r!==null&&r.apply(this,arguments)||this}return e}(Ql);var WT=function(r){Qn(e,r);function e(){return r!==null&&r.apply(this,arguments)||this}return e}(Ql);var $T=function(r){Qn(e,r);function e(){return r!==null&&r.apply(this,arguments)||this}return e}(Ql);function Ha(r){return r instanceof Ql}var qT=function(){function r(e){this._meterSharedState=e}return r.prototype.createGauge=function(e,t){var n=Lr(e,de.GAUGE,t),o=this._meterSharedState.registerMetricStorage(n);return new GT(o,n)},r.prototype.createHistogram=function(e,t){var n=Lr(e,de.HISTOGRAM,t),o=this._meterSharedState.registerMetricStorage(n);return new VT(o,n)},r.prototype.createCounter=function(e,t){var n=Lr(e,de.COUNTER,t),o=this._meterSharedState.registerMetricStorage(n);return new HT(o,n)},r.prototype.createUpDownCounter=function(e,t){var n=Lr(e,de.UP_DOWN_COUNTER,t),o=this._meterSharedState.registerMetricStorage(n);return new zT(o,n)},r.prototype.createObservableGauge=function(e,t){var n=Lr(e,de.OBSERVABLE_GAUGE,t),o=this._meterSharedState.registerAsyncMetricStorage(n);return new WT(n,o,this._meterSharedState.observableRegistry)},r.prototype.createObservableCounter=function(e,t){var n=Lr(e,de.OBSERVABLE_COUNTER,t),o=this._meterSharedState.registerAsyncMetricStorage(n);return new jT(n,o,this._meterSharedState.observableRegistry)},r.prototype.createObservableUpDownCounter=function(e,t){var n=Lr(e,de.OBSERVABLE_UP_DOWN_COUNTER,t),o=this._meterSharedState.registerAsyncMetricStorage(n);return new $T(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 ec=function(){function r(e){this._instrumentDescriptor=e}return r.prototype.getInstrumentDescriptor=function(){return this._instrumentDescriptor},r.prototype.updateDescription=function(e){this._instrumentDescriptor=Lr(this._instrumentDescriptor.name,this._instrumentDescriptor.type,{description:e,valueType:this._instrumentDescriptor.valueType,unit:this._instrumentDescriptor.unit,advice:this._instrumentDescriptor.advice})},r}();var GD=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)}}(),KT=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}}},VD=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 KT(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 KT(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 fr=function(r){GD(e,r);function e(){return r.call(this,Ul)||this}return e}(VD);var jD=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},tc=function(){function r(e,t){this._aggregator=e,this._activeCollectionStorage=new fr,this._cumulativeMemoStorage=new fr,this._overflowAttributes={"otel.metric.overflow":!0},this._cardinalityLimit=(t??2e3)-1,this._overflowHashCode=Ul(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=jD(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 fr,e},r}();var Xp=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.")},YT=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},rc=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===ei.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=WD(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=Xp(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 fr,i=this._unreportedAccumulations.get(e);if(this._unreportedAccumulations.set(e,[]),i===void 0)return o;try{for(var a=Xp(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=YT(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=Xp(e.keys()),l=a.next();!l.done;l=a.next()){var c=YT(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 WD(r){return Array.from(r.entries())}var $D=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)}}(),qD=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},XT=function(r){$D(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 tc(n,l._aggregationCardinalityLimit),l._temporalMetricStorage=new rc(n,i),l}return e.prototype.record=function(t,n){var o=this,i=new fr;Array.from(t.entries()).forEach(function(a){var l=qD(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}(ec);xe();function Jp(r,e){var t="";return r.unit!==e.unit&&(t+=" - Unit '"+r.unit+"' does not match '"+e.unit+`'
24
24
  `),r.type!==e.type&&(t+=" - Type '"+r.type+"' does not match '"+e.type+`'
25
25
  `),r.valueType!==e.valueType&&(t+=" - Value Type '"+r.valueType+"' does not match '"+e.valueType+`'
26
26
  `),r.description!==e.description&&(t+=" - Description '"+r.description+"' does not match '"+e.description+`'
27
- `),t}function GD(r,e){return" - use valueType '"+r.valueType+"' on instrument creation or use an instrument name other than '"+e.name+"'"}function VD(r,e){return" - use unit '"+r.unit+"' on instrument creation or use an instrument name other than '"+e.name+"'"}function jD(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 WD(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+`'
27
+ `),t}function KD(r,e){return" - use valueType '"+r.valueType+"' on instrument creation or use an instrument name other than '"+e.name+"'"}function YD(r,e){return" - use unit '"+r.unit+"' on instrument creation or use an instrument name other than '"+e.name+"'"}function XD(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 JD(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+`'
28
28
  - OR - create a new view with the name `+r.name+" and description '"+r.description+"' and InstrumentSelector "+n+`
29
- - OR - create a new view with the name `+e.name+" and description '"+r.description+"' and InstrumentSelector "+n}function Yp(r,e){return r.valueType!==e.valueType?GD(r,e):r.unit!==e.unit?VD(r,e):r.type!==e.type?jD(r,e):r.description!==e.description?WD(r,e):""}var Xp=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.")},KT=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=Xp(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=Xp(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=Xp(t),l=a.next();!l.done;l=a.next()){var c=l.value,s=c.getInstrumentDescriptor();oT(s,e)?(s.description!==e.description&&(e.description.length>s.description.length&&c.updateDescription(e.description),H.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.
29
+ - OR - create a new view with the name `+e.name+" and description '"+r.description+"' and InstrumentSelector "+n}function Zp(r,e){return r.valueType!==e.valueType?KD(r,e):r.unit!==e.unit?YD(r,e):r.type!==e.type?XD(r,e):r.description!==e.description?JD(r,e):""}var Qp=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.")},JT=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=Qp(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=Qp(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=Qp(t),l=a.next();!l.done;l=a.next()){var c=l.value,s=c.getInstrumentDescriptor();sT(s,e)?(s.description!==e.description&&(e.description.length>s.description.length&&c.updateDescription(e.description),H.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.
30
30
  `,`Details:
31
- `,Kp(s,e),`The longer description will be used.
32
- To resolve the conflict:`,Yp(s,e))),i=c):H.warn("A view or instrument with the name ",e.name,` has already been registered and is incompatible with another registered view.
31
+ `,Jp(s,e),`The longer description will be used.
32
+ To resolve the conflict:`,Zp(s,e))),i=c):H.warn("A view or instrument with the name ",e.name,` has already been registered and is incompatible with another registered view.
33
33
  `,`Details:
34
- `,Kp(s,e),`To resolve the conflict:
35
- `,Yp(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 YT=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}();Ce();Ce();var XT=function(){function r(e,t){this._instrumentName=e,this._valueType=t,this._buffer=new hr}return r.prototype.observe=function(e,t){if(t===void 0&&(t={}),typeof e!="number"){H.warn("non-number value provided to metric "+this._instrumentName+": "+e);return}this._valueType===Ht.INT&&!Number.isInteger(e)&&(H.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 JT=function(){function r(){this._buffer=new Map}return r.prototype.observe=function(e,t,n){if(n===void 0&&(n={}),!!za(e)){var o=this._buffer.get(e);if(o==null&&(o=new hr,this._buffer.set(e,o)),typeof t!="number"){H.warn("non-number value provided to metric "+e._descriptor.name+": "+t);return}e._descriptor.valueType===Ht.INT&&!Number.isInteger(t)&&(H.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 Jp=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())})},Zp=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}}},ZT=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},QT=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))},ev=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(za));if(n.size===0){H.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(za)),o=this._findBatchCallback(e,n);o<0||this._batchCallbacks.splice(o,1)},r.prototype.observe=function(e,t){return Jp(this,void 0,void 0,function(){var n,o,i,a;return Zp(this,function(l){switch(l.label){case 0:return n=this._observeCallbacks(e,t),o=this._observeBatchCallbacks(e,t),[4,ZE(QT(QT([],ZT(n),!1),ZT(o),!1))];case 1:return i=l.sent(),a=i.filter(QE).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 Jp(n,void 0,void 0,function(){var l,c;return Zp(this,function(s){switch(s.label){case 0:return l=new XT(a._descriptor.name,a._descriptor.valueType),c=Promise.resolve(i(l)),t!=null&&(c=Sn(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 Jp(n,void 0,void 0,function(){var l,c;return Zp(this,function(s){switch(s.label){case 0:return l=new JT,c=Promise.resolve(i(l)),t!=null&&(c=Sn(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&&eT(n.instruments,t)})},r}();var $D=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)}}(),tv=function(r){$D(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 Ql(n,l._aggregationCardinalityLimit),l._temporalMetricStorage=new ec(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}(Zl);var rv=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)}}(),ni=function(){function r(){}return r.Noop=function(){return KD},r}();var qD=function(r){rv(e,r);function e(){return r!==null&&r.apply(this,arguments)||this}return e.prototype.process=function(t,n){return t},e}(ni);var nv=function(r){rv(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}(ni);var KD=new qD;var YD=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())})},XD=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}}},JD=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},ov=function(){function r(e,t){this._meterProviderSharedState=e,this._instrumentationScope=t,this.metricStorageRegistry=new KT,this.observableRegistry=new ev,this.meter=new jT(this)}return r.prototype.registerMetricStorage=function(e){var t=this._registerMetricStorage(e,tv);return t.length===1?t[0]:new YT(t)},r.prototype.registerAsyncMetricStorage=function(e){var t=this._registerMetricStorage(e,qT);return t},r.prototype.collect=function(e,t,n){return YD(this,void 0,void 0,function(){var o,i,a;return XD(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(XE),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=nT(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=JD(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,ni.Noop(),[u],g);return n.metricStorageRegistry.registerForCollector(u,h),h});i=i.concat(l)}return i},r}();var ZD=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.")},iv=function(){function r(e){this.resource=e,this.viewRegistry=new kT,this.metricCollectors=[],this.meterSharedStates=new Map}return r.prototype.getMeterSharedState=function(e){var t=JE(e),n=this.meterSharedStates.get(t);return n==null&&(n=new ov(this,e),this.meterSharedStates.set(t,n)),n},r.prototype.selectAggregations=function(e){var t,n,o=[];try{for(var i=ZD(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 tc=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())})},rc=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}}},QD=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},e0=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))},av=function(){function r(e,t){this._sharedState=e,this._metricReader=t}return r.prototype.collect=function(e){return tc(this,void 0,void 0,function(){var t,n,o,i,a=this;return rc(this,function(l){switch(l.label){case 0:return t=Xn(Date.now()),n=[],o=[],i=Array.from(this._sharedState.meterSharedStates.values()).map(function(c){return tc(a,void 0,void 0,function(){var s;return rc(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,e0([],QD(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 tc(this,void 0,void 0,function(){return rc(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 tc(this,void 0,void 0,function(){return rc(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 sv=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())})},lv=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}}},cv=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 t0(r,e){var t=e??Yl.empty();return r?Yl.default().merge(t):t}var Qp=function(){function r(e){var t,n,o,i,a;if(this._shutdown=!1,this._sharedState=new iv(t0((a=e?.mergeResourceWithDefaults)!==null&&a!==void 0?a:!0,e?.resource)),e?.views!=null&&e.views.length>0)try{for(var l=cv(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=cv(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?(H.warn("A shutdown MeterProvider cannot provide a Meter"),op()):this._sharedState.getMeterSharedState({name:e,version:t,schemaUrl:n.schemaUrl}).meter},r.prototype.addMetricReader=function(e){var t=new av(this._sharedState,e);e.setMetricProducer(t),this._sharedState.metricCollectors.push(t)},r.prototype.shutdown=function(e){return sv(this,void 0,void 0,function(){return lv(this,function(t){switch(t.label){case 0:return this._shutdown?(H.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 sv(this,void 0,void 0,function(){return lv(this,function(t){switch(t.label){case 0:return this._shutdown?(H.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 r0=/[\^$\\.+?()[\]{}|]/g,nc=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(r0,"\\$&").replace("*",".*")+"$"},r.hasWildcard=function(e){return e.includes("*")},r}();var oi=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 uv=function(){function r(e){var t;this._nameFilter=new nc((t=e?.name)!==null&&t!==void 0?t:"*"),this._type=e?.type,this._unitFilter=new oi(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 dv=function(){function r(e){this._nameFilter=new oi(e?.name),this._versionFilter=new oi(e?.version),this._schemaUrlFilter=new oi(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 n0(r){return r.instrumentName==null&&r.instrumentType==null&&r.instrumentUnit==null&&r.meterName==null&&r.meterVersion==null&&r.meterSchemaUrl==null}var oc=function(){function r(e){var t;if(n0(e))throw new Error("Cannot create view with no selector arguments supplied");if(e.name!=null&&(e?.instrumentName==null||nc.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 nv(e.attributeKeys):this.attributesProcessor=ni.Noop(),this.name=e.name,this.description=e.description,this.aggregation=(t=e.aggregation)!==null&&t!==void 0?t:ar.Default(),this.instrumentSelector=new uv({name:e.instrumentName,type:e.instrumentType,unit:e.instrumentUnit}),this.meterSelector=new dv({name:e.meterName,version:e.meterVersion,schemaUrl:e.meterSchemaUrl}),this.aggregationCardinalityLimit=e.aggregationCardinalityLimit}return r}();var ise=process.env.APP||"unknown";Ce();import{v4 as o0}from"uuid";function i0(){return new qE({url:"https://us-west.metrics.momentic.ai/v1/metrics",headers:{"x-momentic-metrics-api-key":"c60c6a0f-60da-41a7-a61b-07969a0aa303"},temporalityPreference:Kn.DELTA})}var a0=[new oc({instrumentName:"test_event_duration",instrumentType:de.HISTOGRAM,aggregation:new Ba([100,500,1e3,5e3,7500,1e4,15e3,2e4])}),new oc({instrumentName:"test_step_duration",instrumentType:de.HISTOGRAM,aggregation:new Ba([100,500,1e3,5e3,7500,1e4,15e3,2e4])})],ac=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 vp({[Al]:e.serviceName,[Vb]:t,[Wb]:typeof process<"u"&&process.env.SERVICE_INSTANCE_ID?process.env.SERVICE_INSTANCE_ID:o0()}),o=i0(),i=new $p({exporter:o,exportIntervalMillis:e.exportIntervalMs??15e3});this.provider=new Qp({resource:n,readers:[i],views:a0}),bl.setGlobalMeterProvider(this.provider),this.meter=bl.getMeter("momentic-serverless")}increment(e,t,n){try{let o=fl(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=fl(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 At=new hl;function pv(r){r.disabled||(At=new ac(r))}import{hostname as c0}from"os";import u0 from"path";async function mv(r){let{apiClient:e,logger:t,creationOpts:n,onStatusUpdate:o,logLevel:i,orgId:a}=r,{token:l,webRtcUrl:c,adbUrl:s,name:u,apkDownloadUrl:d,region:p}=await e.createAndroidEmulator({...n,hostname:c0()}),m;try{l0("adb --version"),m="adb"}catch{if(process.env.ANDROID_HOME)m=u0.join(process.env.ANDROID_HOME,"platform-tools","adb");else throw new Error("The adb binary was not found in PATH and ANDROID_HOME is not set either")}t.info({emulatorName:u,apkToInstall:n.apkToInstall,region:p,apkDownloadUrl:d},"Android instance creation ok");let g=await At.recordDuration({fn:async()=>await s0({adbUrl:s,endpointUrl:c,token:l,logLevel:i,adbPath:m}),name:"test_event_duration",tags:["name:limbar-client-creation",`orgId:${a}`]}),h=["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"];d&&h.push(d);let f=n.apkToInstall?.channel,E=n.apkToInstall?.tag;o(`Installing APK${f?` with channel ${f}`:""}${E?` and tag ${E}`:""}`),await Promise.all(h.map(C=>g.sendAsset(C))),o("Starting tunnel");let b=await At.recordDuration({fn:async()=>await g.startAdbTunnel(),name:"test_event_duration",tags:["name:limbar-tunnel-connect",`orgId:${a}`]});return{port:b.address.port,close:b.close,token:l,webRtcUrl:c,emulatorName:u,client:g}}async function sc({onStatusUpdate:r,creationOpts:e,apiClient:t,logger:n,driverLogLevel:o,appiumPort:i,socket:a,orgId:l}){let c=Date.now(),s=[],u;if("avdId"in e)u=e;else{u=await b0({apiClient:t,logger:n,creationOpts:e,onStatusUpdate:r,orgId:l});let m=u.emulatorName;s.push(()=>t.deleteAndroidEmulator(m),u.close)}let d=async()=>{for(let m=s.length-1;m>=0;m-=1)try{await s[m]()}catch(g){if(g instanceof Error&&g.message.includes("ECONNREFUSED"))return;n.warn({err:g},"Error running cleanup task")}},p=async()=>{if(a&&!a.connected)throw await d(),new Error("Client disconnected before Appium driver could be started")};await p();try{let m=await S0({logger:n,driverLogLevel:o,appiumPort:i,emulatorStart:c,emulatorCreationParams:u,apiClient:t,onStatusUpdate:r,creationOpts:e,orgId:l});return s.push(m.appiumClose),s.push(async()=>m.driver.deleteSession()),await p(),{...u,...m,cleanup:d,appiumPort:i}}catch(m){throw await d(),new Error(`Failed to start Appium driver: ${m}`)}}async function S0({logger:r,driverLogLevel:e="warn",emulatorStart:t,appiumPort:n,emulatorCreationParams:o,onStatusUpdate:i,orgId:a,creationOpts:l}){let c=[],{adbPort:s,emulatorName:u}=o,d;if(!s){let v=0;for(;v<30;){let M=5560+Math.floor(Math.random()*100);if(M%2!==0&&(M=Math.min(M+1,5658)),await gl(M)&&await gl(M+1)){d=M,s=M+1;break}v+=1}if(!s)throw new Error(`Failed to find an available ADB port after ${v} attempts`)}u||(u=`emulator-${d}`,c.push(async()=>{let v=process.env.ANDROID_HOME?`${process.env.ANDROID_HOME}/platform-tools/adb`:"adb";try{p0(`${v} -s ${u} emu kill`,{stdio:"inherit"})}catch(M){r.warn({err:M,emulatorName:u},"Failed to kill emulator")}}));let p=Date.now(),{close:m,logFile:g}=await y0({logger:r,logLevel:e,appiumPort:n}),h={platformName:"Android","appium:automationName":"UiAutomator2","appium:deviceName":"Android","appium:udid":`127.0.0.1:${s}`,"appium:adbExecTimeout":3e4,"appium:newCommandTimeout":600,"appium:skipDeviceInitialization":!0,"appium:skipServerInstallation":!0,"appium:androidInstallTimeout":6e4,"appium:autoWebview":!1,"appium:autoWebviewTimeout":0,"appium:clearDeviceLogsOnStart":!0,"appium:ensureWebviewsHavePages":!0},f={hostname:"localhost",port:n,logLevel:e,capabilities:h,connectionRetryTimeout:15e3,connectionRetryCount:2};"avdId"in o&&(h["appium:avd"]=o.avdId,h["appium:avdLaunchTimeout"]=18e4,h["appium:avdReadyTimeout"]=18e4,h["appium:skipDeviceInitialization"]=!1,h["appium:skipServerInstallation"]=!1,h["appium:udid"]=void 0,h["appium:avdArgs"]=`-port ${d} -no-snapshot-save -no-boot-anim -noaudio`,f.connectionRetryTimeout=12e4,f.connectionRetryCount=3);let E=Date.now(),b;try{b=await f0(f)}catch(v){throw i(`Emulator creation failed: ${v}`),await Promise.all(c.map(M=>M())),v}if(await b.updateSettings({enableMultiWindows:!0}),"avdId"in l){let v=l.apkFilePath?.trim();if(v){let M=h0.resolve(v);if(!m0.existsSync(M))throw new Error(`APK not found at path: ${M}`);i("Installing local APK...");let w=Date.now();try{await b.installApp(M),r.info({apkFilePath:M,installDurationMs:Date.now()-w},"Installed local APK")}catch(D){throw r.error({err:D,apkFilePath:M},"Failed to install local APK"),new Error(`Failed to install APK from ${M}: ${D.message}`)}}}let C=new Map;return b.on("command",v=>{C.set(v.command,Date.now())}),b.on("result",v=>{let M=C.get(v.command);if(!M)return;let w=Date.now()-M;v.result instanceof Error?r.warn({err:v.result,command:v.command,args:v.body,durationMs:w},"Appium cmd failed"):w>1e4&&r.warn({command:v.command,args:v.body,durationMs:w},"Appium cmd took very long"),C.delete(v.command)}),r.info({timings:{emulatorDuration:p-t,appiumDuration:E-p,wdioDuration:Date.now()-E},capabilities:h,emulatorName:u},"Started Appium driver"),{driver:b,appiumClose:async()=>{await m(),await Promise.all(c.map(v=>v()))},appiumPort:n,appiumLogFile:g,emulatorName:u,adbPort:s}}async function y0({logger:r,logLevel:e,appiumPort:t}){let n=`${g0()}/appium-port-${Date.now()}.log`,o=await d0.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 b0({apiClient:r,logger:e,onStatusUpdate:t,creationOpts:n,orgId:o}){let{close:i,port:a,token:l,webRtcUrl:c,emulatorName:s,client:u}=await mv({apiClient:r,logger:e,creationOpts:n,onStatusUpdate:t,orgId:o});return{adbPort:a,close:i,limbarToken:l,limbarUrl:c,emulatorName:s,client:u}}import gv from"crypto";import E0 from"fs";async function lc({tag:r,channel:e,filePath:t,apiClient:n,logger:o}){let i=await E0.promises.readFile(t),a=gv.createHash("md5").update(i).digest("base64"),l=gv.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 hv}from"child_process";import{existsSync as T0}from"fs";import{platform as fv}from"os";import{dirname as v0,join as A0,resolve as w0}from"path";import{fileURLToPath as R0}from"url";var Sv,C0=R0(import.meta.url),x0=v0(C0);Sv=w0(x0,"..");var Ha=Sv;R.info(`Setting APPIUM_HOME to ${Ha}`);process.env.APPIUM_HOME=Ha;var M0="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.",_0="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.",P0="Follow the instructions at https://developer.android.com/tools/variables to set the ANDROID_HOME environment variable.",yv="On Mac OS, the SDK is typically installed at /Users/<username>/Library/Android/sdk.",bv="On Windows, the SDK is typically installed at C:\\Users\\<username>\\AppData\\Local\\Android\\Sdk.";function I0(){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)=>A0(t,"bin",process.platform==="win32"?`${n}.exe`:n))(process.env.JAVA_HOME,"java");T0(e)||R.warn(`JAVA_HOME does not appear to point to a valid Java installation: expected the 'java' binary to exist at ${e}`)}try{hv("java --version",{stdio:"pipe",encoding:"utf-8"})||(R.error(`Could not find a Java installation. ${M0}`),process.exit(1))}catch(r){R.error(`Got error while checking if the Java JDK is installed: ${r}`),process.exit(1)}}function O0(){process.env.ANDROID_HOME||(R.error(`The ANDROID_HOME environment variable is not set. ${P0} ${fv()==="darwin"?yv:bv}`),process.exit(1))}function L0(){let r=process.env.ANDROID_HOME?`${process.env.ANDROID_HOME}/platform-tools/adb`:"adb";try{hv(`${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. ${_0} Finally, ensure that the 'adb' command is available in your shell. ${fv()==="darwin"?yv:bv}`),process.exit(1))}catch(e){R.error(`Got error while checking if ADB is installed: ${e}`),process.exit(1)}}function Ev(){I0(),O0(),L0()}import{create as N0,windowedFiniteBatchScheduler as D0}from"@yornaath/batshit";import k0 from"ws";var U0=100,F0=2500,Tv=4e3,B0="\u2026";async function cc({driver:r,onLogs:e}){await r.execute("mobile: startLogsBroadcast");let t=N0({fetcher:async s=>{e(s)},resolver:()=>{},scheduler:D0({windowMs:F0,maxBatchSize:U0})}),{hostname:n="localhost",port:o=4723,protocol:i="http"}=r.options,l=`${i==="https"?"wss":"ws"}://${n}:${o}/ws/session/${r.sessionId}/appium/device/logcat`,c=new k0(l);return c.on("message",s=>{let u=s.toString().trim();u.length!==0&&(u.length>Tv&&(u=u.slice(0,Tv)+B0),t.fetch(u).catch(()=>{}))}),async()=>{try{c.close()}catch{}try{await r.execute("mobile: stopLogsBroadcast")}catch{}try{t.next()}catch{}}}import{Server as YB}from"socket.io";import{randomUUID as X0}from"crypto";import{faker as z0}from"@faker-js/faker";import H0 from"assert";import G0 from"axios";import*as V0 from"child_process";import j0 from"moment";import*as W0 from"otpauth";import $0 from"pg";async function vv(r){let e;try{e=new URL(r.url).hostname}catch{}let t=[];return r.headers.getSetCookie()?.forEach(n=>{let o=zs(n,e);t.push(...o)}),t}function q0(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 K0(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 Y0=Object.getPrototypeOf(async function(){}).constructor;async function Av(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=(C,A)=>{o[C]=A,s[C]=A},d={},p=(C,A)=>{o[C]=A,d[C]=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 Y0("axios","moment","faker","assert","pg","Octokit","createAppAuth","OTPAuth","child_process","extractCookiesFromResponse","env","setVariable","setPersistentVariable","sendSms","waitForLatestSms","email","sms","ai","mock",...Object.keys(i??{}),n)(G0,j0,c.fakerInstance??z0,H0,$0,m,g,W0,V0,vv,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,q0(a,l),...Object.values(i??{}))),f=!0,E,b;try{let C=await F(h(),{milliseconds:e.options.timeoutMs,message:`Timeout of ${e.options.timeoutMs}ms exceeded for code execution`,signal:e.signal});E=await K0(e.options.responseSerialization??"RAW",C)}catch(C){t.error({err:C,env:o,evalCode:n},`[${r}] Error executing code: ${C}`),f=!1,C instanceof mn?b=`Timeout of ${e.options.timeoutMs}ms exceeded for code execution`:b=C instanceof Error?C.message:`${C}`}return{result:E,variableUpdates:s,persistentVariableUpdates:d,success:f,error:b}}async function wv({code:r,fragment:e,context:t,localTools:n,logger:o,signal:i,timeoutMs:a=cn,disallowVariableUpdates:l,additionalBindings:c,responseSerialization:s,mock:u}){let d=X0(),p=await Av(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 J0,randomUUID as Z0}from"crypto";import Q0 from"fetch-retry";var ek=Q0(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}}),Rv=process.env.GCP_JS_EVAL_FUNCTION_ENDPOINT,Cv=process.env.MOMENTIC_LAMBDA_AUTH_SECRET;async function xv({orgId:r,code:e,fragment:t,context:n,timeoutMs:o=cn,retries:i=2,signal:a,logger:l,additionalBindings:c,disallowVariableUpdates:s,responseSerialization:u,mock:d}){if(!Rv)throw new Error("GCP_JS_EVAL_FUNCTION_ENDPOINT environment variable not set");let p,m,g=0;if(!Cv)throw new Error("Missing lambda auth secret.");let h=J0("sha256",Cv).update(r).digest("hex");for(;g<=i;){g++,a?.throwIfAborted();let E={id:Z0(),orgId:r,momenticLambdaAuthHash:h,code:e,fragment:t,state:{...n.toObjectCopy(),...d,additionalBindings:c},timeoutMs:o,disallowVariableUpdates:s,responseSerialization:u};try{if(p=await F(ek(Rv,{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=RS.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 Or(r){let e;if(process.env.GCP_JS_EVAL_FUNCTION_ENDPOINT)e=await xv(r);else if(r.localTools)e=await wv({...r,localTools:r.localTools});else throw new Error("No code evaluation environment available");if(e.error){let t=`Failed to evaluate code:
34
+ `,Jp(s,e),`To resolve the conflict:
35
+ `,Zp(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 ZT=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}();xe();xe();var QT=function(){function r(e,t){this._instrumentName=e,this._valueType=t,this._buffer=new fr}return r.prototype.observe=function(e,t){if(t===void 0&&(t={}),typeof e!="number"){H.warn("non-number value provided to metric "+this._instrumentName+": "+e);return}this._valueType===Ht.INT&&!Number.isInteger(e)&&(H.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 ev=function(){function r(){this._buffer=new Map}return r.prototype.observe=function(e,t,n){if(n===void 0&&(n={}),!!Ha(e)){var o=this._buffer.get(e);if(o==null&&(o=new fr,this._buffer.set(e,o)),typeof t!="number"){H.warn("non-number value provided to metric "+e._descriptor.name+": "+t);return}e._descriptor.valueType===Ht.INT&&!Number.isInteger(t)&&(H.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 em=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())})},tm=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}}},tv=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},rv=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))},nv=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(Ha));if(n.size===0){H.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(Ha)),o=this._findBatchCallback(e,n);o<0||this._batchCallbacks.splice(o,1)},r.prototype.observe=function(e,t){return em(this,void 0,void 0,function(){var n,o,i,a;return tm(this,function(l){switch(l.label){case 0:return n=this._observeCallbacks(e,t),o=this._observeBatchCallbacks(e,t),[4,tT(rv(rv([],tv(n),!1),tv(o),!1))];case 1:return i=l.sent(),a=i.filter(rT).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 em(n,void 0,void 0,function(){var l,c;return tm(this,function(s){switch(s.label){case 0:return l=new QT(a._descriptor.name,a._descriptor.valueType),c=Promise.resolve(i(l)),t!=null&&(c=bn(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 em(n,void 0,void 0,function(){var l,c;return tm(this,function(s){switch(s.label){case 0:return l=new ev,c=Promise.resolve(i(l)),t!=null&&(c=bn(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&&nT(n.instruments,t)})},r}();var ZD=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)}}(),ov=function(r){ZD(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 tc(n,l._aggregationCardinalityLimit),l._temporalMetricStorage=new rc(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}(ec);var iv=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)}}(),oi=function(){function r(){}return r.Noop=function(){return e0},r}();var QD=function(r){iv(e,r);function e(){return r!==null&&r.apply(this,arguments)||this}return e.prototype.process=function(t,n){return t},e}(oi);var av=function(r){iv(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}(oi);var e0=new QD;var t0=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())})},r0=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}}},n0=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},sv=function(){function r(e,t){this._meterProviderSharedState=e,this._instrumentationScope=t,this.metricStorageRegistry=new JT,this.observableRegistry=new nv,this.meter=new qT(this)}return r.prototype.registerMetricStorage=function(e){var t=this._registerMetricStorage(e,ov);return t.length===1?t[0]:new ZT(t)},r.prototype.registerAsyncMetricStorage=function(e){var t=this._registerMetricStorage(e,XT);return t},r.prototype.collect=function(e,t,n){return t0(this,void 0,void 0,function(){var o,i,a;return r0(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(QE),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=aT(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=n0(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,oi.Noop(),[u],g);return n.metricStorageRegistry.registerForCollector(u,h),h});i=i.concat(l)}return i},r}();var o0=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.")},lv=function(){function r(e){this.resource=e,this.viewRegistry=new BT,this.metricCollectors=[],this.meterSharedStates=new Map}return r.prototype.getMeterSharedState=function(e){var t=eT(e),n=this.meterSharedStates.get(t);return n==null&&(n=new sv(this,e),this.meterSharedStates.set(t,n)),n},r.prototype.selectAggregations=function(e){var t,n,o=[];try{for(var i=o0(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 nc=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())})},oc=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}}},i0=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},a0=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))},cv=function(){function r(e,t){this._sharedState=e,this._metricReader=t}return r.prototype.collect=function(e){return nc(this,void 0,void 0,function(){var t,n,o,i,a=this;return oc(this,function(l){switch(l.label){case 0:return t=Jn(Date.now()),n=[],o=[],i=Array.from(this._sharedState.meterSharedStates.values()).map(function(c){return nc(a,void 0,void 0,function(){var s;return oc(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,a0([],i0(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 nc(this,void 0,void 0,function(){return oc(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 nc(this,void 0,void 0,function(){return oc(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 uv=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())})},dv=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}}},pv=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 s0(r,e){var t=e??Jl.empty();return r?Jl.default().merge(t):t}var rm=function(){function r(e){var t,n,o,i,a;if(this._shutdown=!1,this._sharedState=new lv(s0((a=e?.mergeResourceWithDefaults)!==null&&a!==void 0?a:!0,e?.resource)),e?.views!=null&&e.views.length>0)try{for(var l=pv(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=pv(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?(H.warn("A shutdown MeterProvider cannot provide a Meter"),sp()):this._sharedState.getMeterSharedState({name:e,version:t,schemaUrl:n.schemaUrl}).meter},r.prototype.addMetricReader=function(e){var t=new cv(this._sharedState,e);e.setMetricProducer(t),this._sharedState.metricCollectors.push(t)},r.prototype.shutdown=function(e){return uv(this,void 0,void 0,function(){return dv(this,function(t){switch(t.label){case 0:return this._shutdown?(H.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 uv(this,void 0,void 0,function(){return dv(this,function(t){switch(t.label){case 0:return this._shutdown?(H.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 l0=/[\^$\\.+?()[\]{}|]/g,ic=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(l0,"\\$&").replace("*",".*")+"$"},r.hasWildcard=function(e){return e.includes("*")},r}();var ii=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 mv=function(){function r(e){var t;this._nameFilter=new ic((t=e?.name)!==null&&t!==void 0?t:"*"),this._type=e?.type,this._unitFilter=new ii(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 gv=function(){function r(e){this._nameFilter=new ii(e?.name),this._versionFilter=new ii(e?.version),this._schemaUrlFilter=new ii(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 c0(r){return r.instrumentName==null&&r.instrumentType==null&&r.instrumentUnit==null&&r.meterName==null&&r.meterVersion==null&&r.meterSchemaUrl==null}var ac=function(){function r(e){var t;if(c0(e))throw new Error("Cannot create view with no selector arguments supplied");if(e.name!=null&&(e?.instrumentName==null||ic.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 av(e.attributeKeys):this.attributesProcessor=oi.Noop(),this.name=e.name,this.description=e.description,this.aggregation=(t=e.aggregation)!==null&&t!==void 0?t:ar.Default(),this.instrumentSelector=new mv({name:e.instrumentName,type:e.instrumentType,unit:e.instrumentUnit}),this.meterSelector=new gv({name:e.meterName,version:e.meterVersion,schemaUrl:e.meterSchemaUrl}),this.aggregationCardinalityLimit=e.aggregationCardinalityLimit}return r}();var fse=process.env.APP||"unknown";xe();import{v4 as u0}from"uuid";function d0(){return new XE({url:"https://us-west.metrics.momentic.ai/v1/metrics",headers:{"x-momentic-metrics-api-key":"c60c6a0f-60da-41a7-a61b-07969a0aa303"},temporalityPreference:Yn.DELTA})}var p0=[new ac({instrumentName:"test_event_duration",instrumentType:de.HISTOGRAM,aggregation:new za([100,500,1e3,5e3,7500,1e4,15e3,2e4])}),new ac({instrumentName:"test_step_duration",instrumentType:de.HISTOGRAM,aggregation:new za([100,500,1e3,5e3,7500,1e4,15e3,2e4])})],lc=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 Rp({[Rl]:e.serviceName,[$b]:t,[Kb]:typeof process<"u"&&process.env.SERVICE_INSTANCE_ID?process.env.SERVICE_INSTANCE_ID:u0()}),o=d0(),i=new Yp({exporter:o,exportIntervalMillis:e.exportIntervalMs??15e3});this.provider=new rm({resource:n,readers:[i],views:p0}),Tl.setGlobalMeterProvider(this.provider),this.meter=Tl.getMeter("momentic-serverless")}increment(e,t,n){try{let o=yl(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=yl(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 At=new Sl;function hv(r){r.disabled||(At=new lc(r))}import{hostname as h0}from"os";import f0 from"path";async function fv(r){let{apiClient:e,logger:t,creationOpts:n,onStatusUpdate:o,logLevel:i,orgId:a}=r,{token:l,webRtcUrl:c,adbUrl:s,name:u,apkDownloadUrl:d,region:p}=await e.createAndroidEmulator({...n,hostname:h0()}),m;try{g0("adb --version"),m="adb"}catch{if(process.env.ANDROID_HOME)m=f0.join(process.env.ANDROID_HOME,"platform-tools","adb");else throw new Error("The adb binary was not found in PATH and ANDROID_HOME is not set either")}t.info({emulatorName:u,apkToInstall:n.apkToInstall,region:p,apkDownloadUrl:d},"Android instance creation ok");let g=await At.recordDuration({fn:async()=>await m0({adbUrl:s,endpointUrl:c,token:l,logLevel:i,adbPath:m}),name:"test_event_duration",tags:["name:limbar-client-creation",`orgId:${a}`]}),h=["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"];d&&h.push(d);let f=n.apkToInstall?.channel,E=n.apkToInstall?.tag;o(`Installing APK${f?` with channel ${f}`:""}${E?` and tag ${E}`:""}`),await Promise.all(h.map(x=>g.sendAsset(x))),o("Starting tunnel");let b=await At.recordDuration({fn:async()=>await g.startAdbTunnel(),name:"test_event_duration",tags:["name:limbar-tunnel-connect",`orgId:${a}`]});return{port:b.address.port,close:b.close,token:l,webRtcUrl:c,emulatorName:u,client:g}}async function cc({onStatusUpdate:r,creationOpts:e,apiClient:t,logger:n,driverLogLevel:o,appiumPort:i,socket:a,orgId:l}){let c=Date.now(),s=[],u;if("avdId"in e)u=e;else{u=await R0({apiClient:t,logger:n,creationOpts:e,onStatusUpdate:r,orgId:l});let m=u.emulatorName;s.push(()=>t.deleteAndroidEmulator(m),u.close)}let d=async()=>{for(let m=s.length-1;m>=0;m-=1)try{await s[m]()}catch(g){if(g instanceof Error&&g.message.includes("ECONNREFUSED"))return;n.warn({err:g},"Error running cleanup task")}},p=async()=>{if(a&&!a.connected)throw await d(),new Error("Client disconnected before Appium driver could be started")};await p();try{let m=await A0({logger:n,driverLogLevel:o,appiumPort:i,emulatorStart:c,emulatorCreationParams:u,apiClient:t,onStatusUpdate:r,creationOpts:e,orgId:l});return s.push(m.appiumClose),s.push(async()=>m.driver.deleteSession()),await p(),{...u,...m,cleanup:d,appiumPort:i}}catch(m){throw await d(),new Error(`Failed to start Appium driver: ${m}`)}}async function A0({logger:r,driverLogLevel:e="warn",emulatorStart:t,appiumPort:n,emulatorCreationParams:o,onStatusUpdate:i,orgId:a,creationOpts:l}){let c=[],{adbPort:s,emulatorName:u}=o,d;if(!s){let v=0;for(;v<30;){let _=5560+Math.floor(Math.random()*100);if(_%2!==0&&(_=Math.min(_+1,5658)),await fl(_)&&await fl(_+1)){d=_,s=_+1;break}v+=1}if(!s)throw new Error(`Failed to find an available ADB port after ${v} attempts`)}u||(u=`emulator-${d}`,c.push(async()=>{let v=process.env.ANDROID_HOME?`${process.env.ANDROID_HOME}/platform-tools/adb`:"adb";try{y0(`${v} -s ${u} emu kill`,{stdio:"inherit"})}catch(_){r.warn({err:_,emulatorName:u},"Failed to kill emulator")}}));let p=Date.now(),{close:m,logFile:g}=await w0({logger:r,logLevel:e,appiumPort:n}),h={platformName:"Android","appium:automationName":"UiAutomator2","appium:deviceName":"Android","appium:udid":`127.0.0.1:${s}`,"appium:adbExecTimeout":3e4,"appium:newCommandTimeout":600,"appium:skipDeviceInitialization":!0,"appium:skipServerInstallation":!0,"appium:androidInstallTimeout":6e4,"appium:autoWebview":!1,"appium:autoWebviewTimeout":0,"appium:clearDeviceLogsOnStart":!0,"appium:ensureWebviewsHavePages":!0},f={hostname:"localhost",port:n,logLevel:e,capabilities:h,connectionRetryTimeout:15e3,connectionRetryCount:2};"avdId"in o&&(h["appium:avd"]=o.avdId,h["appium:avdLaunchTimeout"]=18e4,h["appium:avdReadyTimeout"]=18e4,h["appium:skipDeviceInitialization"]=!1,h["appium:skipServerInstallation"]=!1,h["appium:udid"]=void 0,h["appium:avdArgs"]=`-port ${d} -no-snapshot-save -no-boot-anim -noaudio`,f.connectionRetryTimeout=12e4,f.connectionRetryCount=3);let E=Date.now(),b;try{b=await v0(f)}catch(v){throw i(`Emulator creation failed: ${v}`),await Promise.all(c.map(_=>_())),v}if(await b.updateSettings({enableMultiWindows:!0}),"avdId"in l){let v=l.apkFilePath?.trim();if(v){let _=T0.resolve(v);if(!b0.existsSync(_))throw new Error(`APK not found at path: ${_}`);i("Installing local APK...");let R=Date.now();try{await b.installApp(_),r.info({apkFilePath:_,installDurationMs:Date.now()-R},"Installed local APK")}catch(D){throw r.error({err:D,apkFilePath:_},"Failed to install local APK"),new Error(`Failed to install APK from ${_}: ${D.message}`)}}}let x=new Map;return b.on("command",v=>{x.set(v.command,Date.now())}),b.on("result",v=>{let _=x.get(v.command);if(!_)return;let R=Date.now()-_;v.result instanceof Error?r.warn({err:v.result,command:v.command,args:v.body,durationMs:R},"Appium cmd failed"):R>1e4&&r.warn({command:v.command,args:v.body,durationMs:R},"Appium cmd took very long"),x.delete(v.command)}),r.info({timings:{emulatorDuration:p-t,appiumDuration:E-p,wdioDuration:Date.now()-E},capabilities:h,emulatorName:u},"Started Appium driver"),{driver:b,appiumClose:async()=>{await m(),await Promise.all(c.map(v=>v()))},appiumPort:n,appiumLogFile:g,emulatorName:u,adbPort:s}}async function w0({logger:r,logLevel:e,appiumPort:t}){let n=`${E0()}/appium-port-${Date.now()}.log`,o=await S0.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 R0({apiClient:r,logger:e,onStatusUpdate:t,creationOpts:n,orgId:o}){let{close:i,port:a,token:l,webRtcUrl:c,emulatorName:s,client:u}=await fv({apiClient:r,logger:e,creationOpts:n,onStatusUpdate:t,orgId:o});return{adbPort:a,close:i,limbarToken:l,limbarUrl:c,emulatorName:s,client:u}}import Sv from"crypto";import C0 from"fs";async function uc({tag:r,channel:e,filePath:t,apiClient:n,logger:o}){let i=await C0.promises.readFile(t),a=Sv.createHash("md5").update(i).digest("base64"),l=Sv.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 yv}from"child_process";import{existsSync as x0}from"fs";import{platform as bv}from"os";import{dirname as M0,join as _0,resolve as P0}from"path";import{fileURLToPath as I0}from"url";var Ev,O0=I0(import.meta.url),L0=M0(O0);Ev=P0(L0,"..");var Ga=Ev;w.info(`Setting APPIUM_HOME to ${Ga}`);process.env.APPIUM_HOME=Ga;var N0="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.",D0="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.",k0="Follow the instructions at https://developer.android.com/tools/variables to set the ANDROID_HOME environment variable.",Tv="On Mac OS, the SDK is typically installed at /Users/<username>/Library/Android/sdk.",vv="On Windows, the SDK is typically installed at C:\\Users\\<username>\\AppData\\Local\\Android\\Sdk.";function U0(){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)=>_0(t,"bin",process.platform==="win32"?`${n}.exe`:n))(process.env.JAVA_HOME,"java");x0(e)||w.warn(`JAVA_HOME does not appear to point to a valid Java installation: expected the 'java' binary to exist at ${e}`)}try{yv("java --version",{stdio:"pipe",encoding:"utf-8"})||(w.error(`Could not find a Java installation. ${N0}`),process.exit(1))}catch(r){w.error(`Got error while checking if the Java JDK is installed: ${r}`),process.exit(1)}}function F0(){process.env.ANDROID_HOME||(w.error(`The ANDROID_HOME environment variable is not set. ${k0} ${bv()==="darwin"?Tv:vv}`),process.exit(1))}function B0(){let r=process.env.ANDROID_HOME?`${process.env.ANDROID_HOME}/platform-tools/adb`:"adb";try{yv(`${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. ${D0} Finally, ensure that the 'adb' command is available in your shell. ${bv()==="darwin"?Tv:vv}`),process.exit(1))}catch(e){w.error(`Got error while checking if ADB is installed: ${e}`),process.exit(1)}}function Av(){U0(),F0(),B0()}import{create as z0,windowedFiniteBatchScheduler as H0}from"@yornaath/batshit";import G0 from"ws";var V0=100,j0=2500,wv=4e3,W0="\u2026";async function dc({driver:r,onLogs:e}){await r.execute("mobile: startLogsBroadcast");let t=z0({fetcher:async s=>{e(s)},resolver:()=>{},scheduler:H0({windowMs:j0,maxBatchSize:V0})}),{hostname:n="localhost",port:o=4723,protocol:i="http"}=r.options,l=`${i==="https"?"wss":"ws"}://${n}:${o}/ws/session/${r.sessionId}/appium/device/logcat`,c=new G0(l);return c.on("message",s=>{let u=s.toString().trim();u.length!==0&&(u.length>wv&&(u=u.slice(0,wv)+W0),t.fetch(u).catch(()=>{}))}),async()=>{try{c.close()}catch{}try{await r.execute("mobile: stopLogsBroadcast")}catch{}try{t.next()}catch{}}}import{Server as oz}from"socket.io";import{randomUUID as rk}from"crypto";import{faker as $0}from"@faker-js/faker";import q0 from"assert";import K0 from"axios";import*as Y0 from"child_process";import X0 from"moment";import*as J0 from"otpauth";import Z0 from"pg";async function Rv(r){let e;try{e=new URL(r.url).hostname}catch{}let t=[];return r.headers.getSetCookie()?.forEach(n=>{let o=Gs(n,e);t.push(...o)}),t}function Q0(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 ek(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 tk=Object.getPrototypeOf(async function(){}).constructor;async function Cv(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=(x,A)=>{o[x]=A,s[x]=A},d={},p=(x,A)=>{o[x]=A,d[x]=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 tk("axios","moment","faker","assert","pg","Octokit","createAppAuth","OTPAuth","child_process","extractCookiesFromResponse","env","setVariable","setPersistentVariable","sendSms","waitForLatestSms","email","sms","ai","mock",...Object.keys(i??{}),n)(K0,X0,c.fakerInstance??$0,q0,Z0,m,g,J0,Y0,Rv,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,Q0(a,l),...Object.values(i??{}))),f=!0,E,b;try{let x=await k(h(),{milliseconds:e.options.timeoutMs,message:`Timeout of ${e.options.timeoutMs}ms exceeded for code execution`,signal:e.signal});E=await ek(e.options.responseSerialization??"RAW",x)}catch(x){t.error({err:x,env:o,evalCode:n},`[${r}] Error executing code: ${x}`),f=!1,x instanceof hn?b=`Timeout of ${e.options.timeoutMs}ms exceeded for code execution`:b=x instanceof Error?x.message:`${x}`}return{result:E,variableUpdates:s,persistentVariableUpdates:d,success:f,error:b}}async function xv({code:r,fragment:e,context:t,localTools:n,logger:o,signal:i,timeoutMs:a=dn,disallowVariableUpdates:l,additionalBindings:c,responseSerialization:s,mock:u}){let d=rk(),p=await Cv(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(p)}`),p}import{createHmac as nk,randomUUID as ok}from"crypto";import ik from"fetch-retry";var ak=ik(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}}),Mv=process.env.GCP_JS_EVAL_FUNCTION_ENDPOINT,_v=process.env.MOMENTIC_LAMBDA_AUTH_SECRET;async function Pv({orgId:r,code:e,fragment:t,context:n,timeoutMs:o=dn,retries:i=2,signal:a,logger:l,additionalBindings:c,disallowVariableUpdates:s,responseSerialization:u,mock:d}){if(!Mv)throw new Error("GCP_JS_EVAL_FUNCTION_ENDPOINT environment variable not set");let p,m,g=0;if(!_v)throw new Error("Missing lambda auth secret.");let h=nk("sha256",_v).update(r).digest("hex");for(;g<=i;){g++,a?.throwIfAborted();let E={id:ok(),orgId:r,momenticLambdaAuthHash:h,code:e,fragment:t,state:{...n.toObjectCopy(),...d,additionalBindings:c},timeoutMs:o,disallowVariableUpdates:s,responseSerialization:u};try{if(p=await k(ak(Mv,{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=MS.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 Nr(r){let e;if(process.env.GCP_JS_EVAL_FUNCTION_ENDPOINT)e=await Pv(r);else if(r.localTools)e=await xv({...r,localTools:r.localTools});else throw new Error("No code evaluation environment available");if(e.error){let t=`Failed to evaluate code:
36
36
  ${e.error}
37
37
  Code received:
38
- ${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 tk}from"lodash-es";async function em(r){let{orgId:e,s:t,context:n,logger:o,signal:i,retries:a=2,timeoutMs:l=cn,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 Or({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 x("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 uc(r){return Mv(r)}async function Mv({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 em({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 Mv({obj:s,bannedKeys:e,context:n,prefixPath:u,replacements:i,allowList:c?void 0:t,...a})}return i}function dc(r,e){for(let{path:t,original:n}of e)tk(r,t,n)}import rk from"fetch-retry";var Sce=process.env.MAILINATOR_API_KEY,yce=rk(global.fetch,{retryOn:function(r,e,t){return r>3?!1:!!(e!==null||t&&t.status>=400)},retryDelay:function(r){return 500}});import vB from"fetch-cookie";import AB from"path";import{diff as nk}from"deep-object-diff";import{cloneDeep as Vce}from"lodash-es";function Pv(r,e){return!r&&!e?!1:!r||!e?!0:Object.keys(nk(r,e)).length>0}function tm({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=ln.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=ik(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(!js(p.command)||p.command.type==="TYPE"&&!p.command.target||"cache"in p.command&&p.command.cache.cache)continue;s++,d(p.command,i);break}case"RESOLVED_MOBILE_MODULE":{s+=p.steps.length;let{cacheKeysHit:m,cacheKeysMissed:g,uniqueKeysHit:h}=tm({...t,steps:p.steps,keyPrefix:i?`${i}:${p.id}`:p.id,topLevel:!1});a.push(...m),l.push(...g),c.push(...h);break}case"MOBILE_AI_ACTION_STEP":{s++;break}default:{let m=p}}return e&&s&&l.length>0&&o.warn({totalSteps:s,cacheKeysMissed:l,cacheKeysHit:a,uniqueKeysHit:c,cacheEntriesKeys:Object.values(n).map(p=>p.uniqueKey)},"Step cache did not fully resolve"),{cacheKeysHit:a,cacheKeysMissed:l,uniqueKeysHit:c}}function ok(r,e){return e?`${e}:${r}`:r}function ik(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 rm(r){let{moduleStepParents:e=[],moduleIdParents:t=[]}=r;if(e.length!==t.length)throw new Error(`Invalid cache entry parent length: ${JSON.stringify(e)}
39
- ${JSON.stringify(t)}`);let n=[];return n.push({key:ok(r.id,e.join(":")),organizationId:r.orgId,value:r.value,testId:r.testId}),n}function pc({cmd:r,newTarget:e,key:t,logger:n,updatedWithAI:o}){if(r.type==="DRAG")if(t!=="fromTarget"&&t!=="toTarget")n.error({cmd:r,newTarget:e,key:t},"Attempted to apply invalid cache to DRAG command");else{let i=r.cache?.updatedAt;r.cache={...r.cache,[t]:e,updatedAt:i&&!o?i:new Date}}else if(t==="target"&&Th(r)){let i=r.cache?.updatedAt;r.cache={...r.cache,target:e,updatedAt:i&&!o?i:new Date}}else n.error({cmd:r,newTarget:e,key:t},"Invalid target cache application")}function mc(r,e,t){let n=r.cache&&"memory"in r.cache?r.cache.memory?.traces:void 0;Pv(n,e)&&(t.info({updatedTraces:e,oldCmd:r},"Wrote new memory to assertion command"),r.cache={...r.cache,memory:{type:"GCS_TRACES",traces:e},updatedAt:new Date})}function nm(r){return{...r,serializedHtml:void 0,nodeOnlySerializedHtml:void 0,screenshotUrl:void 0,boundingBox:void 0,selector:void 0,hybridSelector:void 0,generatedSelectors:void 0,id:-1}}function Iv(r,e){return r?Pv(r.target.memory,e.target.memory)?{target:{...r.target,memory:e.target.memory},updatedAt:e.updatedAt}:r:{target:nm(e.target),updatedAt:e.updatedAt}}function Ot(r,e,t=!1){return r.length<e?r:r.slice(0,e-3)+(t?"...TRUNCATED...":"[...]")}var eo={EQUALS:"equals",CONTAINS:"contains",STARTS_WITH:"starts with",EXISTS:"exists"},to={EQUALS:"does not equal",CONTAINS:"does not contain",STARTS_WITH:"does not start with",EXISTS:"does not exist"},Ov={EXISTS:"exists",VISIBLE:"is visible",ENABLED:"is enabled",EDITABLE:"is editable",FOCUSED:"is focused"},Lv={EXISTS:"does not exist",VISIBLE:"is not visible",ENABLED:"is disabled",EDITABLE:"is not editable",FOCUSED:"is not focused"};var yue={CONTENT:"The page"};function Nv(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 ak(r){return typeof r=="object"&&r!==null}function Qn(r){if(Array.isArray(r))return r.map(Qn);if(ak(r)){let e={};return Object.entries(r).forEach(([t,n])=>{n!==void 0&&(e[t]=Qn(n))}),e}return r}function sk(r){switch(r.type){case"AI_CHECK":return`AI check: ${r.assertion}`;case"TAP":return`Tap on element: ${vd(r.target)}`;case"TYPE":return`Type ${r.text} ${r.target?`into ${vd(r.target)}`:""}`;case"PRESS":return`Press the ${r.key} button`;case"PRESS_KEYBOARD":return`Press the ${r.key} key`;case"SWIPE":return r.scrollableElement.type==="CUSTOM"?`Swipe ${r.direction} in container: ${r.scrollableElement.target.description}`:`Swipe ${r.direction} in the ${r.scrollableElement.type.toLowerCase()}`;case"OPEN_APP":return`Open app: ${r.packageName}`;case"OPEN_NOTIFICATION_DRAWER":return"Open notification drawer";case"JAVASCRIPT":return`Execute JavaScript: ${r.code}`;case"REQUEST":return`Make API request to ${r.url}`;case"WAIT":return`Wait ${r.timeoutSecs} seconds`;case"ADD_FILE":return`Add file: ${r.file} to ${r.storageLocation}`;case"INSTALL_APP":return`Install app: ${r.uri}`;case"ADB":return`ADB command: ${r.command}`;case"KILL_APP":return"Kill active app";case"STATE":return"Send debug state to Momentic";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 Dv(r){switch(r.type){case"MOBILE_PRESET_STEP":return sk(r.command);case"MOBILE_MODULE_STEP":return`Module ${r.moduleId}`;case"RESOLVED_MOBILE_MODULE":return`Module ${r.name}`;case"MOBILE_AI_ACTION_STEP":return`AI action: ${r.text}`;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 kv}from"lodash-es";async function Uv(r){let e={},{resolvedSteps:t,newSchemaVersion:n}=await gc({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 gc({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 gc({rawSteps:r,onFetchModule:e,logger:t,metadata:n,resolvedModuleCache:o={}}){let i=[];for(let a of r)i.push(await Fv({rawStep:gr.parse(a),onFetchModule:e,logger:t,resolvedModuleCache:o}));return{resolvedSteps:i,newSchemaVersion:n.schemaVersion}}async function Fv({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{...kv(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=gr.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=>Fv({rawStep:u,onFetchModule:e,logger:t,resolvedModuleCache:n}))),s={...a,steps:c};return n[o]=kv(s),{...s,...r,type:"RESOLVED_MOBILE_MODULE"}}case"MOBILE_AI_ACTION_STEP":case"MOBILE_PRESET_STEP":return r}}import{cloneDeep as lk}from"lodash-es";import{v4 as om}from"uuid";async function ro(r){let e=new Map,t=new Set,n=lk(r.steps),o=await Bv({...r,steps:n,moduleStepParents:[],moduleIdParents:[],moduleIdReplacements:e,seenModules:t});return{stepsToSave:o.stepsToSave,cachesToSave:o.cachesToSave,moduleUpdates:o.moduleUpdates}}async function Bv({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?om():u.id,u.type){case"MOBILE_PRESET_STEP":{let d=u.command;d.id=c?om():d.id,"cache"in d&&d.cache&&(n&&(s.cachesToSave=s.cachesToSave.concat(rm({id:d.id,orgId:n.orgId,testId:n.testId,value:ln.parse(d),moduleIdParents:o,moduleStepParents:i}))),delete d.cache),s.stepsToSave.push({...u,command:d});break}case"RESOLVED_MOBILE_MODULE":{let d=c?om():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 Bv({...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({...Bo.parse(u),steps:gr.array().parse(g),moduleId:p}));let f=ca.parse({...u,type:"MOBILE_MODULE_STEP",moduleId:p,inputs:u.inputs,id:d});s.stepsToSave.push(f);break}case"MOBILE_AI_ACTION_STEP":{s.stepsToSave.push(u);break}default:{let d=u}}return s}function ck(r){let e={parentChain:[]};return zv(r,e),e}function zv(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),zv({...r,steps:i.steps},e)&&o))return!0;e.parentChain.pop();continue}if(t(i,e)&&o)return!0}return!1}function uk(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 ck({steps:r,earlyStop:!0,onPreset:i,onModule:i}),{result:n,parentChain:o}}function Hv({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!!uk([r],t,i).result}function Gv(r){let e=r[0],t=r[0],n=!1;for(;!n&&t;)switch(t.type){case"MOBILE_AI_ACTION_STEP":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_AI_ACTION_STEP":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 Vv({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 gde}from"lodash-es";import fde from"truncate-json";import{v4 as Rde}from"uuid";import{cloneDeep as ode,unset as ide}from"lodash-es";import{cloneDeep as Pde}from"lodash-es";import{cloneDeep as Qpe}from"lodash-es";import Epe from"diff-lines";import im,{gte as vpe}from"semver";var jv={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 Wv={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 dk=["target","fromTarget","toTarget"];function $v(r){for(let e of dk){if(r[e]===void 0)continue;let t=r[e];t.elementDescriptor!==void 0?t.type="description":r[e]={type:"description",elementDescriptor:""}}}var qv={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 $v(e.command),e;case"AI_ACTION":{let t=e.commands;for(let n of t??[])$v(n);return e}default:return e}})};import{v4 as pk}from"uuid";var Kv={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=pk()),e;default:return e}})};import{v4 as Yv}from"uuid";var Xv={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??Yv(),e}case"AI_ACTION":return e.commands&&(e.steps=e.commands.map(t=>({type:"PRESET_ACTION",command:{...t,id:t.id??Yv()}})),delete e.commands),e;default:return e}})};var Jv={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 mk}from"uuid";var Zv={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=mk()),e))};import{v4 as Qv}from"uuid";var eA={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=Qv())}return e.id=Qv(),e})};var tA={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 gk}from"uuid";var rA={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=gk()),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 nA={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 oA={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&&iA(t),e})};function iA(r){r&&Object.keys(r).forEach(e=>{if(typeof r[e]=="object"&&r[e]){iA(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 aA={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 sA={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 lA={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 cA={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 uA={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 dA={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 hc=new Set(["CLICK","TYPE","SELECT_OPTION"]),pA={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||hc.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||hc.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||hc.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||hc.has(m))&&(d.target={elementDescriptor:p??""})})}),e}),stopOnFailure:!0};var mA={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 gA={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 fc=[dA,mA,gA,pA,jv,Wv,qv,Kv,Xv,Jv,Zv,eA,tA,rA,nA,oA,aA,sA,lA,cA,uA];if(Dn!==fc[fc.length-1].toVersion)throw new Error("Please bump LATEST_SCHEMA_VERSION in types package after adding a migration");fc.forEach((r,e)=>{if(!im.valid(r.toVersion)||!im.valid(r.fromVersion))throw new Error(`Migration '${r.name}' has invalid version`);if(!im.gt(r.toVersion,r.fromVersion))throw new Error(`Migration '${r.name}' has toVersion <= fromVersion`);if(e===0)return;if(fc[e-1].toVersion!==r.fromVersion)throw new Error(`Migration '${r.name}' at index ${e} is not contiguous with previous migration`)});import{diff as Sme}from"deep-object-diff";import{cloneDeep as bme}from"lodash-es";import{v4 as Nme}from"uuid";import{cloneDeep as Fme}from"lodash-es";import{stringify as Xme}from"yaml";async function X(r,e){if(!(r<=0))return new Promise((t,n)=>{if(e?.aborted){n(e.reason);return}e?.addEventListener("abort",i,{once:!0});let o=setTimeout(()=>{e?.removeEventListener("abort",i),t()},r);function i(){clearTimeout(o),e?.removeEventListener("abort",i),n(e?.reason)}})}async function am({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,{once:!0}),(async()=>{try{l(await r())}catch(u){c(u)}finally{clearInterval(a),e?.removeEventListener("abort",s)}})()})}async function Ga({promiseGenerator:r,timeoutMs:e,codePath:t,logger:n,signal:o}){let i=!1,a=new AbortController,l=()=>{a.abort()},c=setTimeout(()=>{o?.removeEventListener("abort",l),!i&&a.abort()},e);o?.addEventListener("abort",l,{once:!0});try{return await am({promiseGenerator:r,signal:a.signal,codePath:t,logger:n})}finally{i=!0,o?.removeEventListener("abort",l),clearTimeout(c)}}function Sc(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 hk from"picomatch";var yc=(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||hk(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},bc=(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}},ii=r=>{try{return new URL(r),!0}catch{return!1}},fA=r=>!r.toLowerCase().startsWith("http"),ai=(r,e)=>{try{return new URL(r,e),!0}catch{return!1}};function no(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 SA}from"uuid";function sm(r,e){return{...r,testId:e?.testId??"",testName:e?.testName??"",suiteId:e?.suiteId??"",suiteName:e?.suiteName??""}}var Ec=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:sm({},this.metadata)}]).catch(l=>e.error({err:l},"Failed to report billable event"))]}trackStepExecution(e){if(AS(e.type)){this.creditsUsedV2+=1;return}let t=gd(e.type);if(this.creditsUsedV1+=t??0,e.type==="PRESET_ACTION"){this.creditsUsedV2+=1;let n=hd(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:SA(),properties:sm({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:SA(),properties:sm({creditsUsed:this.creditsUsedV2},this.metadata)}]).catch(t=>e.error({err:t},"Failed to report credits used"))),await Promise.allSettled(this.asyncWork)}};import{cloneDeep as Ige}from"lodash-es";import{CookieJar as wB}from"tough-cookie";var lm={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
38
+ ${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 sk}from"lodash-es";async function Va(r){let{orgId:e,s:t,context:n,logger:o,signal:i,retries:a=2,timeoutMs:l=dn,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 Nr({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 C("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 pc(r){return Iv(r)}async function Iv({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 Va({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 Iv({obj:s,bannedKeys:e,context:n,prefixPath:u,replacements:i,allowList:c?void 0:t,...a})}return i}function mc(r,e){for(let{path:t,original:n}of e)sk(r,t,n)}import lk from"fetch-retry";var Mce=process.env.MAILINATOR_API_KEY,_ce=lk(global.fetch,{retryOn:function(r,e,t){return r>3?!1:!!(e!==null||t&&t.status>=400)},retryDelay:function(r){return 500}});import IB from"fetch-cookie";import OB from"path";import{diff as ck}from"deep-object-diff";import{cloneDeep as eue}from"lodash-es";function Lv(r,e){return!r&&!e?!1:!r||!e?!0:Object.keys(ck(r,e)).length>0}function nm({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=un.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=dk(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(!$s(p.command)||p.command.type==="TYPE"&&!p.command.target||"cache"in p.command&&p.command.cache.cache)continue;s++,d(p.command,i);break}case"RESOLVED_MOBILE_MODULE":{s+=p.steps.length;let{cacheKeysHit:m,cacheKeysMissed:g,uniqueKeysHit:h}=nm({...t,steps:p.steps,keyPrefix:i?`${i}:${p.id}`:p.id,topLevel:!1});a.push(...m),l.push(...g),c.push(...h);break}case"MOBILE_AI_ACTION_STEP":{s++;break}default:{let m=p}}return e&&s&&l.length>0&&o.warn({totalSteps:s,cacheKeysMissed:l,cacheKeysHit:a,uniqueKeysHit:c,cacheEntriesKeys:Object.values(n).map(p=>p.uniqueKey)},"Step cache did not fully resolve"),{cacheKeysHit:a,cacheKeysMissed:l,uniqueKeysHit:c}}function uk(r,e){return e?`${e}:${r}`:r}function dk(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 om(r){let{moduleStepParents:e=[],moduleIdParents:t=[]}=r;if(e.length!==t.length)throw new Error(`Invalid cache entry parent length: ${JSON.stringify(e)}
39
+ ${JSON.stringify(t)}`);let n=[];return n.push({key:uk(r.id,e.join(":")),organizationId:r.orgId,value:r.value,testId:r.testId}),n}function gc({cmd:r,newTarget:e,key:t,logger:n,updatedWithAI:o}){if(r.type==="DRAG")if(t!=="fromTarget"&&t!=="toTarget")n.error({cmd:r,newTarget:e,key:t},"Attempted to apply invalid cache to DRAG command");else{let i=r.cache?.updatedAt;r.cache={...r.cache,[t]:e,updatedAt:i&&!o?i:new Date}}else if(t==="target"&&Du(r)){let i=r.cache?.updatedAt;r.cache={...r.cache,target:e,updatedAt:i&&!o?i:new Date}}else n.error({cmd:r,newTarget:e,key:t},"Invalid target cache application")}function hc(r,e,t){let n=r.cache&&"memory"in r.cache?r.cache.memory?.traces:void 0;Lv(n,e)&&(t.info({updatedTraces:e,oldCmd:r},"Wrote new memory to assertion command"),r.cache={...r.cache,memory:{type:"GCS_TRACES",traces:e},updatedAt:new Date})}function im(r){return{...r,serializedHtml:void 0,nodeOnlySerializedHtml:void 0,screenshotUrl:void 0,boundingBox:void 0,selector:void 0,hybridSelector:void 0,generatedSelectors:void 0,id:-1}}function Nv(r,e){return r?Lv(r.target.memory,e.target.memory)?{target:{...r.target,memory:e.target.memory},updatedAt:e.updatedAt}:r:{target:im(e.target),updatedAt:e.updatedAt}}function Ot(r,e,t=!1){return r.length<e?r:r.slice(0,e-3)+(t?"...TRUNCATED...":"[...]")}var to={EQUALS:"equals",CONTAINS:"contains",STARTS_WITH:"starts with",EXISTS:"exists"},ro={EQUALS:"does not equal",CONTAINS:"does not contain",STARTS_WITH:"does not start with",EXISTS:"does not exist"},Dv={EXISTS:"exists",VISIBLE:"is visible",ENABLED:"is enabled",EDITABLE:"is editable",FOCUSED:"is focused"},kv={EXISTS:"does not exist",VISIBLE:"is not visible",ENABLED:"is disabled",EDITABLE:"is not editable",FOCUSED:"is not focused"};var Iue={CONTENT:"The page"};function Uv(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 pk(r){return typeof r=="object"&&r!==null}function eo(r){if(Array.isArray(r))return r.map(eo);if(pk(r)){let e={};return Object.entries(r).forEach(([t,n])=>{n!==void 0&&(e[t]=eo(n))}),e}return r}function mk(r){switch(r.type){case"AI_CHECK":return`AI check: ${r.assertion}`;case"TAP":return`Tap on element: ${Rd(r.target)}`;case"TYPE":return`Type ${r.text} ${r.target?`into ${Rd(r.target)}`:""}`;case"PRESS":return`Press the ${r.key} button`;case"PRESS_KEYBOARD":return`Press the ${r.key} key`;case"SWIPE":return r.scrollableElement.type==="CUSTOM"?`Swipe ${r.direction} in container: ${r.scrollableElement.target.description}`:`Swipe ${r.direction} in the ${r.scrollableElement.type.toLowerCase()}`;case"OPEN_APP":return`Open app: ${r.packageName}`;case"OPEN_NOTIFICATION_DRAWER":return"Open notification drawer";case"JAVASCRIPT":return`Execute JavaScript: ${r.code}`;case"REQUEST":return`Make API request to ${r.url}`;case"WAIT":return`Wait ${r.timeoutSecs} seconds`;case"ADD_FILE":return`Add file: ${r.file} to ${r.storageLocation}`;case"INSTALL_APP":return`Install app: ${r.uri}`;case"ADB":return`ADB command: ${r.command}`;case"KILL_APP":return"Kill active app";case"STATE":return"Send debug state to Momentic";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 Fv(r){switch(r.type){case"MOBILE_PRESET_STEP":return mk(r.command);case"MOBILE_MODULE_STEP":return`Module ${r.moduleId}`;case"RESOLVED_MOBILE_MODULE":return`Module ${r.name}`;case"MOBILE_AI_ACTION_STEP":return`AI action: ${r.text}`;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 Bv}from"lodash-es";async function zv(r){let e={},{resolvedSteps:t,newSchemaVersion:n}=await fc({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 fc({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 fc({rawSteps:r,onFetchModule:e,logger:t,metadata:n,resolvedModuleCache:o={}}){let i=[];for(let a of r)i.push(await Hv({rawStep:hr.parse(a),onFetchModule:e,logger:t,resolvedModuleCache:o}));return{resolvedSteps:i,newSchemaVersion:n.schemaVersion}}async function Hv({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{...Bv(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=hr.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=>Hv({rawStep:u,onFetchModule:e,logger:t,resolvedModuleCache:n}))),s={...a,steps:c};return n[o]=Bv(s),{...s,...r,type:"RESOLVED_MOBILE_MODULE"}}case"MOBILE_AI_ACTION_STEP":case"MOBILE_PRESET_STEP":return r}}import{cloneDeep as gk}from"lodash-es";import{v4 as am}from"uuid";async function no(r){let e=new Map,t=new Set,n=gk(r.steps),o=await Gv({...r,steps:n,moduleStepParents:[],moduleIdParents:[],moduleIdReplacements:e,seenModules:t});return{stepsToSave:o.stepsToSave,cachesToSave:o.cachesToSave,moduleUpdates:o.moduleUpdates}}async function Gv({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?am():u.id,u.type){case"MOBILE_PRESET_STEP":{let d=u.command;d.id=c?am():d.id,"cache"in d&&d.cache&&(n&&(s.cachesToSave=s.cachesToSave.concat(om({id:d.id,orgId:n.orgId,testId:n.testId,value:un.parse(d),moduleIdParents:o,moduleStepParents:i}))),delete d.cache),s.stepsToSave.push({...u,command:d});break}case"RESOLVED_MOBILE_MODULE":{let d=c?am():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 Gv({...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({...zo.parse(u),steps:hr.array().parse(g),moduleId:p}));let f=ua.parse({...u,type:"MOBILE_MODULE_STEP",moduleId:p,inputs:u.inputs,id:d});s.stepsToSave.push(f);break}case"MOBILE_AI_ACTION_STEP":{s.stepsToSave.push(u);break}default:{let d=u}}return s}function hk(r){let e={parentChain:[]};return Vv(r,e),e}function Vv(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),Vv({...r,steps:i.steps},e)&&o))return!0;e.parentChain.pop();continue}if(t(i,e)&&o)return!0}return!1}function fk(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 hk({steps:r,earlyStop:!0,onPreset:i,onModule:i}),{result:n,parentChain:o}}function jv({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!!fk([r],t,i).result}function Wv(r){let e=r[0],t=r[0],n=!1;for(;!n&&t;)switch(t.type){case"MOBILE_AI_ACTION_STEP":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_AI_ACTION_STEP":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 $v({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 xde}from"lodash-es";import _de from"truncate-json";import{v4 as Fde}from"uuid";import{cloneDeep as Sde,unset as yde}from"lodash-es";import{cloneDeep as Vde}from"lodash-es";import{cloneDeep as pme}from"lodash-es";import Lpe from"diff-lines";import sm,{gte as Dpe}from"semver";var qv={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 Kv={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 Sk=["target","fromTarget","toTarget"];function Yv(r){for(let e of Sk){if(r[e]===void 0)continue;let t=r[e];t.elementDescriptor!==void 0?t.type="description":r[e]={type:"description",elementDescriptor:""}}}var Xv={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 Yv(e.command),e;case"AI_ACTION":{let t=e.commands;for(let n of t??[])Yv(n);return e}default:return e}})};import{v4 as yk}from"uuid";var Jv={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=yk()),e;default:return e}})};import{v4 as Zv}from"uuid";var Qv={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??Zv(),e}case"AI_ACTION":return e.commands&&(e.steps=e.commands.map(t=>({type:"PRESET_ACTION",command:{...t,id:t.id??Zv()}})),delete e.commands),e;default:return e}})};var eA={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 bk}from"uuid";var tA={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=bk()),e))};import{v4 as rA}from"uuid";var nA={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=rA())}return e.id=rA(),e})};var oA={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 Ek}from"uuid";var iA={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=Ek()),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 aA={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 sA={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&&lA(t),e})};function lA(r){r&&Object.keys(r).forEach(e=>{if(typeof r[e]=="object"&&r[e]){lA(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 cA={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 uA={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 dA={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 pA={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 mA={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 gA={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 Sc=new Set(["CLICK","TYPE","SELECT_OPTION"]),hA={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||Sc.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||Sc.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||Sc.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||Sc.has(m))&&(d.target={elementDescriptor:p??""})})}),e}),stopOnFailure:!0};var fA={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 SA={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 yc=[gA,fA,SA,hA,qv,Kv,Xv,Jv,Qv,eA,tA,nA,oA,iA,aA,sA,cA,uA,dA,pA,mA];if(kn!==yc[yc.length-1].toVersion)throw new Error("Please bump LATEST_SCHEMA_VERSION in types package after adding a migration");yc.forEach((r,e)=>{if(!sm.valid(r.toVersion)||!sm.valid(r.fromVersion))throw new Error(`Migration '${r.name}' has invalid version`);if(!sm.gt(r.toVersion,r.fromVersion))throw new Error(`Migration '${r.name}' has toVersion <= fromVersion`);if(e===0)return;if(yc[e-1].toVersion!==r.fromVersion)throw new Error(`Migration '${r.name}' at index ${e} is not contiguous with previous migration`)});import{diff as Pme}from"deep-object-diff";import{cloneDeep as Ome}from"lodash-es";import{v4 as qme}from"uuid";import{cloneDeep as Jme}from"lodash-es";import{stringify as cge}from"yaml";async function Y(r,e){if(!(r<=0))return new Promise((t,n)=>{if(e?.aborted){n(e.reason);return}e?.addEventListener("abort",i,{once:!0});let o=setTimeout(()=>{e?.removeEventListener("abort",i),t()},r);function i(){clearTimeout(o),e?.removeEventListener("abort",i),n(e?.reason)}})}async function lm({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,{once:!0}),(async()=>{try{l(await r())}catch(u){c(u)}finally{clearInterval(a),e?.removeEventListener("abort",s)}})()})}async function ja({promiseGenerator:r,timeoutMs:e,codePath:t,logger:n,signal:o}){let i=!1,a=new AbortController,l=()=>{a.abort()},c=setTimeout(()=>{o?.removeEventListener("abort",l),!i&&a.abort()},e);o?.addEventListener("abort",l,{once:!0});try{return await lm({promiseGenerator:r,signal:a.signal,codePath:t,logger:n})}finally{i=!0,o?.removeEventListener("abort",l),clearTimeout(c)}}function bc(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 Tk from"picomatch";var Ec=(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||Tk(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},Tc=(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}},ai=r=>{try{return new URL(r),!0}catch{return!1}},bA=r=>!r.toLowerCase().startsWith("http"),si=(r,e)=>{try{return new URL(r,e),!0}catch{return!1}};function oo(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 EA}from"uuid";function cm(r,e){return{...r,testId:e?.testId??"",testName:e?.testName??"",suiteId:e?.suiteId??"",suiteName:e?.suiteName??""}}var vc=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:cm({},this.metadata)}]).catch(l=>e.error({err:l},"Failed to report billable event"))]}trackStepExecution(e){if(CS(e.type)){this.creditsUsedV2+=1;return}let t=Sd(e.type);if(this.creditsUsedV1+=t??0,e.type==="PRESET_ACTION"){this.creditsUsedV2+=1;let n=yd(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:EA(),properties:cm({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:EA(),properties:cm({creditsUsed:this.creditsUsedV2},this.metadata)}]).catch(t=>e.error({err:t},"Failed to report credits used"))),await Promise.allSettled(this.asyncWork)}};import{cloneDeep as jge}from"lodash-es";import{CookieJar as LB}from"tough-cookie";var um={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
40
40
  var momenticConstants = {
41
41
  bannedClassSubstrings: [
42
42
  "relative",
@@ -1505,25 +1505,6 @@ function addCssGenerationScript() {
1505
1505
  customWindow.generateCssSelectors = generateCssSelectors;
1506
1506
  }
1507
1507
 
1508
- // src/html/cursor.ts
1509
- function addTrackCursorScript() {
1510
- const customWindow = window;
1511
- if (customWindow.trackCursorMove) {
1512
- return;
1513
- }
1514
- customWindow.trackCursorMove = function(e) {
1515
- e = e || window.event;
1516
- customWindow.lastCursorPos = {
1517
- left: e.pageX,
1518
- top: e.pageY
1519
- };
1520
- };
1521
- document.addEventListener("mousemove", customWindow.trackCursorMove, {
1522
- capture: true,
1523
- passive: true
1524
- });
1525
- }
1526
-
1527
1508
  // src/html/data-momentic-id.ts
1528
1509
  function addAddIdsScript() {
1529
1510
  const customWindow = window;
@@ -2564,8 +2545,8 @@ function addEvaluateHybridSelectorScript() {
2564
2545
  secondBestStrength = strength.totalStrength;
2565
2546
  }
2566
2547
  }
2567
- const winnerSerialized = winner ? customWindow.serializeElementOnlyWithText?.(winner).slice(0, 500) : null;
2568
- const secondBestSerialized = secondBest ? customWindow.serializeElementOnlyWithText?.(secondBest).slice(0, 500) : null;
2548
+ const winnerSerialized = winner ? customWindow.serializeElementOnlyWithText?.(winner) : null;
2549
+ const secondBestSerialized = secondBest ? customWindow.serializeElementOnlyWithText?.(secondBest) : null;
2569
2550
  if (!winner) {
2570
2551
  logs.push(\`No winner was found at all\`);
2571
2552
  return {
@@ -4082,7 +4063,6 @@ function registerAllMomenticListeners() {
4082
4063
  addFindElementInBodyOrShadowDomScript();
4083
4064
  addBrowserLdistScript();
4084
4065
  addMomenticSelectorGeneratorLib();
4085
- addTrackCursorScript();
4086
4066
  addTargetRedirectionScript();
4087
4067
  addCssGenerationScript();
4088
4068
  addEvaluateCssSelectorsScript();
@@ -4098,33 +4078,33 @@ function registerAllMomenticListeners() {
4098
4078
 
4099
4079
  // src/html/index.ts
4100
4080
  registerAllMomenticListeners();
4101
- `};var sr={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-index","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:["data-test-id","data-testid","id","name","href","aria-describedby","aria-labelledby","aria-description","data-row","data-col","data-index","data-row-index","data-col-index","for","title","alt","aria-label","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","aria-keyshortcuts","data-ved","aria-controls","d"],ineligibleElementAttribute:"momentic-ineligible"};var yA="BoundingBoxMovedError",bA="ZeroOpacityError",Tc="visual_actions",$r="data-momentic-id";function EA(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(`
4081
+ `};var sr={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-index","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:["data-test-id","data-testid","id","name","href","aria-describedby","aria-labelledby","aria-description","data-row","data-col","data-index","data-row-index","data-col-index","for","title","alt","aria-label","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","aria-keyshortcuts","data-ved","aria-controls","d"],ineligibleElementAttribute:"momentic-ineligible"};var TA="BoundingBoxMovedError",vA="ZeroOpacityError",Ac="visual_actions",Kr="data-momentic-id";function AA(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(`
4102
4082
  `,o);a>0&&a<n&&(o=a);let l=i,c=0;for(;c<1e3&&l>n&&r[l]!==`
4103
4083
  `;)c++,l--;return l>n&&r[l]===`
4104
- `&&(i=l),r.slice(o,i)}function fr(r){let e=typeof r=="string"?r:r.toString();return`[${$r}="${e}"]`}import{execSync as tF}from"child_process";import{randomUUID as Wm}from"crypto";import{diff as $m}from"deep-object-diff";import{existsSync as Oc,readFileSync as rF,readdirSync as nF,statSync as Lw,writeFileSync as oF}from"fs";import{Jimp as Nw}from"jimp";import iF from"js-beautify";import{cloneDeep as pi}from"lodash-es";import aF from"mime";import{platform as sF}from"os";import{basename as Dw,extname as lF,join as cF}from"path";import{v4 as uF}from"uuid";import{rmSync as nw}from"fs";import{basename as cU,join as uU}from"path";import{errors as dU}from"playwright-core";import{devices as Sk}from"playwright-core";var TA=2,si=8e3;var li=250,it=500;var vA=5e3,AA=250,J=3e3,ge=2e3,Z=1e3,cm=3e4,um=8e3,wA=10,dm=.05;var RA=6e4,CA=new Set(["about:blank","chrome-error://chromewebdata/"]);var pm=["button","image","generic","graphics-symbol","tab","link","menuitem","group"],mm=1e4,Va=500,vc=Sk["Desktop Chrome"].userAgent,ci=process.env.TWO_CAPTCHA_KEY;import{mkdirSync as yk,rmSync as xA,statSync as bk}from"fs";import*as Sm from"node:fs";import Ek from"nodejs-file-downloader";import{tmpdir as Tk}from"os";import En,{basename as vk,dirname as Ak}from"path";var ym="file://",fm=En.join(Tk(),"momentic","downloads"),hm=1e4,wk=50*1024*1024;async function MA(r){let{uri:e}=r;if(e.startsWith(ym))return Ck(r);if(e.startsWith("http"))return Mk(r);if(GS)return xk(r);throw new x("UserConfigurationError","The source URI for the file upload step must be a valid URL or a previously downloaded file beginning with 'file://'")}function Rk(r,e){let t=En.join(fm,r,e.slice(ym.length)),n=En.join(fm,r),o=t.startsWith(n);if(!Sm.existsSync(t)||!o)throw new x("UserConfigurationError",`The referenced file (${e}) does not exist. Please make sure that it has been downloaded successfully.`);return t}async function Ck({uri:r,orgId:e}){let t=Rk(e,r);return{filePath:t,cleanup:()=>{xA(Ak(t),{recursive:!0,force:!0})}}}async function xk({uri:r}){let e=En.resolve(r);if(!Sm.existsSync(e))throw new x("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 Mk({uri:r,logger:e,orgId:t}){let n=new URL(r);n.search&&(n.search="");let o=vk(n.href),i=Em(o),a=En.extname(i);if(kS.includes(a))throw new Error(`Downloading files with extension ${a} is not allowed.`);let l=bm(t),c,s;for(let g=1;g<=3;g++){let h=new Ek({url:r,fileName:i,directory:l,maxAttempts:1,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:hm});try{let{downloadStatus:f,filePath:E}=await F(h.download(),{milliseconds:hm,message:`Download timed out after ${hm}ms`});if(f!=="COMPLETE"||!E)throw new Error(`Download ended in non-success status: ${f}`);c=E;break}catch(f){s=f}}if(!c)throw new Error(`Download failed after 3 attempts. Last error: ${s instanceof Error?s.message:s}`);let u=c,p=bk(u).size;if(p>wk)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(()=>xA(l,{recursive:!0,force:!0}),10*60*1e3)}}}function _A(r,e){return`${ym}${r}/${e}`}function bm(r){let e=Math.random().toString(36).substring(4),t=En.join(fm,r,e);return yk(t,{recursive:!0}),t}function Em(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 qr(r,e){try{return await r.evaluate(n=>window.serializeElementOnlyWithText?.(n,{truncateToLength:500}),void 0,{timeout:Z})}catch(t){e.debug({err:t},"Failed to get HTML from locator for Playwright error translation");return}}var Tn=3.1783027;function _k(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 Lr(r){return Math.ceil(Tm(r)/Tn)}function Tm(r){let e=0;if(typeof r=="string"){let t=r;t=t.replaceAll(`
4105
- `,""),t=t.replaceAll(" ","");let n=_k(t);return t.length-n+Tn*n}if(typeof r>"u"||r===null)return 0;if(typeof r=="number")return String(r).length;if(Array.isArray(r))return r.forEach(t=>{e+=Tm(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*Tn:e+=85*Tn:n==="source"&&typeof t[n]=="object"&&t[n]?.type==="base64"?e+=1600*Tn:e+=Tm(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 Ac=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 PA(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 F(t,{milliseconds:J});return o&&e.warn({err:o},"Failed to fetch indexedDB data"),n}async function IA(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 F(n,{milliseconds:J})}catch(n){t.warn({err:n},"Failed to import indexedDB data")}}}async function OA(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 F(t,{milliseconds:J})}catch(t){e.debug({err:t},"Failed clearing index db data, continuing...")}}async function LA(r,e,t,n,o){try{await Pk(r,e,t,n)}catch(i){o.error({err:i,tabIndex:e},"Error handling new console log")}}async function Pk(r,e,t,n){let o=n.text();o.length>Va&&(o=o.slice(0,Va)+"...(TRUNCATED)");let i=[];for(let a of n.args())try{let l=await a.jsonValue(),c=JSON.stringify(l);c.length>Va?i.push(c.slice(0,Va)+"...(TRUNCATED)"):(typeof l!="object"||Object.keys(l).length>0)&&i.push(l)}catch{}vm(r,t,e,{url:r.url(),location:n.location(),type:n.type(),text:n.text(),args:i})}function vm(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>mm&&(i[t]=i[t].slice(Math.floor(mm/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 lr({fn:r,codePath:e,logObject:t,signal:n,logger:o}){n?.throwIfAborted();let i=Date.now(),a=await am({promiseGenerator:r,signal:n,codePath:e,logger:o}),l=Date.now();return t[e]=l-i,a}import Ik from"truncate-json";var Ok="[redacted due to size]",NA=5e3,Lk=5e3,kA=1e4;async function UA(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 Am(r,e){let t=e.timing(),n=new URL(e.url()),o=[...n.searchParams.entries()].map(([l,c])=>({name:l,value:c})),i={...await BA(e),url:n.toString(),method:e.method(),queryString:o};return{pageref:r,_resourceType:e.resourceType(),startedDateTime:new Date().toISOString(),request:i,timings:HA(t).timings}}async function FA(r,e,t,n){let o={},a=((await t.headerValue("content-type"))?.toLowerCase()??void 0)?.split(";")[0]??void 0;if(n)try{o=await Bk({response:t,mimeType:a,sizes:n})}catch{}let l={...await BA(t),status:t.status(),statusText:t.statusText(),content:o,redirectURL:t.headers().location,_mocked:!1};r.response=l,r.response&&n&&(r.response.bodySize=n.responseBodySize,r.response.headersSize=n.responseHeadersSize,r.response.content.size=n.responseBodySize);let c=e.timing();r.startedDateTime=new Date(c.startTime).toISOString();let{timings:s,total:u}=HA(c);r.time=u,r.timings=s}function ja(r,e,t){r.harEntries||(r.harEntries={}),r.harEntries[t]=e}function DA(r){try{return new Date(r).toISOString()}catch{return}}function Nk(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=Nr(i),e.value=Nr(a);continue}i==="Domain"&&(e.domain=Nr(a)),i==="Expires"&&(e.expires=DA(a)),i==="HttpOnly"&&(e.httpOnly=!0),i==="Max-Age"&&(e.expires=DA(Date.now()+ +a*1e3)),i==="Path"&&(e.path=Nr(a)),i==="Secure"&&(e.secure=!0)}return e}async function BA(r){let e=await r.allHeaders(),t=e.cookie?.split(";").map(Nk)??[];return{headers:Object.entries(e).map(([n,o])=>({name:Nr(n),value:Nr(o)})),cookies:t}}async function zA(r,e,t){let n=await r.headerValue("content-type")??"application/octet-stream";if(t&&(e.request.bodySize=t.requestBodySize,e.request.headersSize=t.requestHeadersSize),t&&t.requestBodySize>kA){e.request.postData={mimeType:n,text:"",params:[],_redactedReason:"Request body redacted due to size"};return}let o=r.postData();if(!o)return;let i={mimeType:n,text:Nr(o),params:[]};if(n==="application/x-www-form-urlencoded"){let a=new URLSearchParams(o.toString());for(let[l,c]of a.entries())i.params.push({name:Nr(l),value:c?Nr(c):void 0})}e.request.postData=i}var Dk=["image","font","video","audio"],kk=["text"],Uk=["json","xml","html","javascript"];function Fk(r){let[e,t]=r.split("/");return!e||Dk.includes(e)?!1:kk.includes(e)?!0:t?!!Uk.some(n=>t?.includes(n)):!1}async function Bk({response:r,mimeType:e,sizes:t}){let n={mimeType:e,encoding:await r.headerValue("content-encoding")??void 0};return t.responseBodySize>=kA&&(n._redactedReason="Response body redacted due to size"),!e||!Fk(e)?n._redactedReason="Body redacted because it's not a viewable MIME type":n.text=Nr(await r.text()),n}function Nr(r){try{let e=JSON.parse(r),{jsonString:t}=Ik(r,Lk);return t}catch{return r.length>NA?r.slice(0,NA)+Ok:r}}function oo(r){return r<0?0:r}function HA(r){return{timings:{blocked:oo(r.domainLookupStart),dns:oo(r.domainLookupEnd-r.domainLookupStart),connect:oo(r.connectEnd-r.connectStart),send:oo(r.responseStart-r.requestStart),wait:0,receive:oo(r.responseEnd-r.responseStart),ssl:oo(r.connectEnd-r.secureConnectionStart)},total:oo(r.responseEnd)}}function GA(){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 et({root:r,fn:e,arg:t,timeout:n,waitForPageLoad:o,codePath:i}){return await o(),await F(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 wm(){return window.lastCursorPos}import{errors as zk}from"playwright-core";async function io({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 zk.TimeoutError)t.warn({err:c,rootUrl:(await n.state.getRoot()).url()},`Encountered Playwright error while performing ${e}`),l=await Hk(c,i.locator,n,t);else throw c}throw l instanceof x?l:new x("ActionFailureError",`Failed to interact with targeted element. Error: ${l.message}`,{errOptions:{cause:l}})}async function Hk(r,e,t,n){return r.message.includes("attempt #")?Gk(r,e,t,n):Vk(r)}async function Gk(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(`
4106
- `,";").replace(/\s+/g," ");let a="",l=await qr(e,n);if(l&&(a=`Target element HTML: ${Ot(l,100,!0)}`),i.includes("element is not enabled"))return new x("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(fr(s)),d=await qr(u,n);d&&(c=`Covering element HTML: ${Ot(d,100,!0)}`)}return new x("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}
4107
- ${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:J});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 x("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 x("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 Vk(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 x("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}import{execSync as Xk}from"child_process";import{existsSync as $a,mkdirSync as Pm,readdirSync as Jk,rmSync as qA}from"fs";import{homedir as KA}from"os";import{basename as Zk,join as An,resolve as Qk}from"path";import{chromium as YA}from"playwright-core";import{addExtra as eU}from"playwright-extra";import tU from"puppeteer-extra-plugin-recaptcha";function VA(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 Wk}from"crypto";function jA(r,e){for(let t of Object.values(e))if(t.matcher.matches({url:r.url(),method:r.method()}))return t}async function WA(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 jk(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},ja(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 jk(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 Rm(r){try{await $k(r)}catch(e){r.logger.warn({err:e},"Error handling intercepted request, continuing...")}}async function $k(r){let{pageId:e,route:t,request:n,debugData:o,logger:i,requestRecorders:a,mocks:l}=r,c=Wk(),s=await Am(e,n);try{ja(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=jA(n,l);u?await WA({logger:i,route:t,mock:u,entry:s,debugData:o,requestId:c,requestRecorders:a}):await qk({route:t,request:n,debugData:o,logger:i,requestRecorders:a,entry:s,requestId:c})}async function qk({route:r,request:e,debugData:t,logger:n,requestRecorders:o,entry:i,requestId:a}){await r.continue();try{let l=await e.response(),c;try{await l?.finished()}catch{}try{c=await e.sizes()}catch{}if(i&&await zA(e,i,c),!l||!i)return;await FA(i,e,l,c),ja(t,i,a);for(let s of Object.values(o))s.onRequestComplete(a,i)}catch(l){l.message.includes("has been closed")||n.warn({err:l},"Failed to add response to HAR")}}async function Kk(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 Yk(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 wc(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 Cm(r){let e=r.request(),t=r.status(),n=r.headers(),o=await Yk(r);return{request:{url:e.url(),method:e.method(),headers:e.headers(),...await Kk(e)},response:{status:t,headers:n,...o},status:t,headers:n,...o}}var vn=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:yc(t,this.requestMatcher.urlMatcher)}};function Wa(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()}import{homedir as xm,platform as Mm}from"os";import{join as _m}from"path";function Rc(){let r=[];if(Mm()==="linux"){let e=xm();["chromium","google-chrome","chrome-canary"].forEach(t=>{r.push(_m(e,".config",t,"Crash Reports"))})}else if(Mm()==="darwin"){let e=xm();["Chromium","Google","Chrome for Testing"].forEach(t=>{r.push(_m(e,"Library","Application Support",t,"Crashpad"))})}else if(Mm()==="win32"){let e=xm();["Chromium","Google","Google Chrome Canary"].forEach(t=>{r.push(_m(e,"AppData","Local",t,"User Data","Crashpad","reports"))})}return r}function $A(){return{name:"fs_optout",value:"1",domain:".fullstory.com",path:"/",expires:Date.now()/1e3+365*24*60*60,httpOnly:!1,secure:!0,sameSite:"None"}}var Im=An(KA(),"momentic","chromium"),XA=eU(YA);XA.use(tU({provider:{id:"2captcha",token:ci},visualFeedback:!0}));var rU=["--enable-crashpad","--crash-on-hang-threads=UI:18,IO:18"],nU=["--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"],oU=["--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-webgl2","--disable-audio-input","--disable-audio-output"];async function JA({baseUrl:r,logger:e,storage:t,enricher:n,userBrowserSettings:o,contextArgs:i,iconKnowledgeBase:a,callbacks:l,videoOptions:c}){process.env.PW_TEST_SCREENSHOT_NO_FONTS_READY="1";let s;switch(o.browserType){case"Google Chrome":s="chrome";break;case"Chrome for Testing":s=void 0;break;case"Chromium":s="chromium";break;default:s="chromium";break}let u=[...nU];!Rr&&aU()&&u.push("--disable-dev-shm-usage");let d={headless:process.env.MOMENTIC_HEADFUL_BROWSER!=="true",handleSIGTERM:!1,chromiumSandbox:!1,channel:s},p={...i??{},geolocation:i?.geolocation||If,locale:i?.locale||_f,timezoneId:i?.timezoneId||Pf,colorScheme:i?.colorScheme,httpCredentials:o.basicAuthorization?{username:o.basicAuthorization.username??"",password:o.basicAuthorization.password??""}:void 0,javaScriptEnabled:o.disableJavaScript?!1:void 0,ignoreHTTPSErrors:o.ignoreHttpsErrors??!1,userAgent:o.userAgent??vc,viewport:i?.viewport??an,serviceWorkers:"block",storageState:{cookies:[$A()],origins:[]},proxy:o.proxy};o.initialLocalStorage&&(p.storageState.origins=Object.entries(o.initialLocalStorage).map(([b,C])=>({origin:b,localStorage:Object.entries(C).map(([A,v])=>({name:A,value:v}))}))),process.env.MOMENTIC_CHROME_EXTRA_ARGS&&u.push(...process.env.MOMENTIC_CHROME_EXTRA_ARGS.split(","));let m=null,g,h,f={systemDevicePixelRatio:i?.deviceScaleFactor,isNewHeadless:!1};(s==="chrome"||s==="chromium")&&(f.isNewHeadless=!0,d.headless&&u.push("--headless=new")),process.env.BROWSER_MEMORY_MB&&u.push(`--js-flags=--max_old_space_size=${process.env.BROWSER_MEMORY_MB}`);try{let b=Rc();b.forEach(C=>{if(!$a(C))return;["new","pending","completed"].forEach(v=>{let M=An(C,v);if(!$a(M))return;let w=Jk(M);for(let D=0;D<w.length;D++){let j=An(M,w[D]);qA(j,{force:!0})}})}),b.forEach(C=>{$a(C)||Pm(C,{recursive:!0});let A=An(C,`write-test-${Date.now()}`);Pm(A,{recursive:!0}),qA(A,{recursive:!0,force:!0})}),u.push(...rU)}catch(b){e.warn({err:b},"Could not create Chrome crash report directory, not enabling crashpad")}o.disableGpu&&u.push(...oU);let E=o.localChromeExtensionPaths?.map(b=>b.startsWith("~")?An(KA(),b.slice(1)):b);if(E?.length){if(s===void 0)throw new x("UserConfigurationError","Chrome extensions are only supported on Chromium and Google Chrome.");for(let v of E){let M=An(v,"manifest.json");if(!$a(M))throw new x("UserConfigurationError",`Chrome extension path ${M} does not exist.`)}if(Rr)throw new x("UserConfigurationError","Cannot use persistent browser context on Momentic Cloud");let b=An(Im,`momentic-session-${Date.now()}`);if(!$a(b))try{Pm(b,{recursive:!0})}catch(v){throw new x("UserConfigurationError",`Failed to create browser cache directory. Please make sure you have sufficient permissions to create the ${Im} folder: ${v}`)}let C=[...u],A=E.map(v=>Qk(v)).join(",");C.push(`--disable-extensions-except=${A}`),p?.deviceScaleFactor&&C.push(`--force-device-scale-factor=${p.deviceScaleFactor}`,`--device-scale-factor=${p.deviceScaleFactor}`),p.viewport&&C.push(`--window-size=${p.viewport.width},${p.viewport.height}`),g=await YA.launchPersistentContext(An(Im,`momentic-session-${Date.now()}`),{...d,...p,ignoreDefaultArgs:["--disable-extensions","--disable-component-extensions-with-background-pages"],args:C,baseURL:r}),e.info({sharedContextOptions:p,sharedBrowserOptions:d,userBrowserSettings:o,chromeArgs:C,properties:f,baseUrl:r},"Browser initialization context args (persistent)"),h=g.pages()[0]}else{m=await XA.launch({...d,args:u});let b={...p,baseURL:r,recordVideo:c?{dir:c.videoOutputPath}:void 0};g=await m.newContext(b),e.info({contextArgs:b,sharedBrowserOptions:d,chromeArgs:u,userBrowserSettings:o,properties:f,baseUrl:r},"Browser initialization context args (standard)"),h=await g.newPage()}if(c){let b=await h.video()?.path();if(b){let C=Zk(b);c.onVideoPageChange({videoName:C})}}Rr&&await g.route("**",Wa);try{let b=m?.version();e.info({browserVersion:b},"Got browser version")}catch(b){e.warn({err:b},"Could not get browser version string")}return{browser:m,context:g,page:h,baseUrl:r,logger:e,storage:t,enricher:n,userBrowserSettings:o,viewport:p.viewport||an,properties:f,clientCallbacks:l,iconKnowledgeBase:a,onVideoPageChange:c?.onVideoPageChange}}function iU(){if(process.platform!=="linux")return null;try{let e=Xk("df -k /dev/shm",{encoding:"utf8"}).trim().split(/\r?\n/),n=e[e.length-1]?.trim().split(/\s+/)??[];if(!n||n.length<2)return null;let o=parseInt(n[1],10);return Number.isNaN(o)||o<=0?null:o/1024}catch{return null}}function aU(){let e=process.env.BROWSER_ENABLE_DEV_SHM;if(e==="1")return!1;if(e==="0")return!0;let t=iU();return t==null?!1:t<128}async function ZA(r){try{return await sU(r)}catch(e){r.logger.warn({err:e},"Failed to transform locator for Chakra click, continuing...");return}}async function sU({locator:r,logger:e}){let[t,n]=await r.evaluate(c=>[c.id,c.tagName.toLowerCase()],{timeout:Z}),o=await qr(r,e),i=await r.boundingBox({timeout:Z});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:Z}),{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?.[Tc],h=c.getAttribute($r),f=!g&&h?fr(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:Z});if(a.type==="error")throw new Error(a.error);let l=r.page().locator(a.selector);return await l.waitFor({state:"visible",timeout:Z}),e.info({parentElementResult:a,originalElementDisplayString:o},`Redirected click to parent element with selector: ${a.selector}`),{locator:l,relativePoint:a.relativePoint}}var ew=["date","datetime-local","month","time","week"],QA={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 tw(r){try{await F(lU(r),{milliseconds:J})}catch(e){r.logger.warn({err:e},"Failed to transform native datetime input, continuing...")}}async function lU({root:r,text:e,options:t,logger:n,callbacks:o}){let i=(await et({root:r,fn:()=>document.activeElement?.getAttribute("type")??"",timeout:Z,arg:void 0,waitForPageLoad:o.waitForPageLoad,codePath:"transforming native datetime input"})).toLowerCase();if(!QA[i])return;QA[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 Bt}from"zod";var rw=Bt.object({doubleClick:Bt.boolean().optional(),rightClick:Bt.boolean().optional(),force:Bt.boolean().optional(),waitForDownload:Bt.boolean().optional(),delayMs:Bt.number().optional(),downloadTimeoutMs:Bt.number().optional(),relativePosition:Bt.object({x:Bt.number(),y:Bt.number()}).optional()}),hSe=Bt.object({repeat:Bt.number().optional(),convertMeta:Bt.boolean().optional().describe("misleading name due to backcompat. converts keyshortcuts + meta/control to platform-specific combos. defaults to true"),delayMs:Bt.number().optional()});async function Cc({locator:r,callbacks:e,logger:t,timeoutMs:n=Z}){try{await Om(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 F(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 Om(r,e=Z){let t=await r.state.getRoot();await et({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 Lm(r){let e=!!r.browserCallbacks.state.userBrowserSettings.visualActions;return io({action:"clicking element",targetingResult:r.targetingResult,logger:r.logger,retryTimeoutMs:r.retryTimeoutMs,callbacks:r.browserCallbacks,func:async t=>ow({...r,targetingResult:t,useVisualClick:e})})}async function pU(r,e){let{redirectionAttempts:t=0}=e;if(t>=2)throw r;try{return await mU(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 mU(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:Z});if(!i)throw r;let a=o.page().locator(`[for=${JSON.stringify(i)}]`);return await a.waitFor({state:"visible",timeout:Z}),t.warn({err:r},"Attempting locator redirection due to input being covered by label"),ow({...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 gU(r){let{logger:e,targetingResult:t,position:n,options:o}=r,i=rw.safeParse(o),a=Date.now(),{clickX:l,clickY:c,reason:s}=await SU({targetingResult:t,position:n,options:o});return e.info({position:n,options:i.success?i.data:void 0,clickLocation:{clickX:l,clickY:c,reason:s},duration:Date.now()-a},"Visual click"),{x:l,y:c}}async function hU(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 s=await ZA({locator:i,logger:o});s&&(i=s.locator,a=s.relativePoint??a)}let l=n?.force||t.hints?.force||!1;l&&!a&&t.hints?.relativeXYToLocator&&(a=t.hints.relativeXYToLocator);let c=i.toString();try{o.info({locator:c},"Locator click"),n?.doubleClick?await i.dblclick({button:n.rightClick?"right":"left",timeout:J,position:a,delay:n?.delayMs??25,force:l}):await i.click({button:n?.rightClick?"right":"left",timeout:J,position:a,delay:n?.delayMs??25,force:l})}catch(s){let u=s;if(bU(u))o.warn({err:u},"Click action timed out while waiting for navigation after completion, continuing...");else return o.error({err:u},"Error clicking on locator, attempting to recover..."),pU(u,{...r,targetingResult:{...i,locator:i}})}return{locatorSource:c}}async function ow(r){let{options:e,logger:t,browserCallbacks:n,controllerCallbacks:o,useVisualClick:i,targetingResult:a}=r,l;e?.waitForDownload&&(l=(async()=>{let u=e.downloadTimeoutMs??cm;try{return await a.locator.page().waitForEvent("download",{timeout:u})}catch(d){return d instanceof dU.TimeoutError?new x("ActionFailureError",`Download did not complete in ${u}ms`):new x("ActionFailureError",`Download failed: ${d.message}`)}})());try{await Cc({locator:a.locator,callbacks:n,logger:t,timeoutMs:Z})}catch(u){t.warn({err:u},"Error highlighting locator in click, continuing...")}let c,s;if(i?c=await gU(r):s=(await hU(r)).locatorSource,e?.waitForDownload)if(l){if(!o?.createIsolatedFolder)throw new x("InternalWebAgentError","Cannot wait for download without a callback to create an isolated folder");t.info("Waiting for download to start and complete");let u=await F(l,{milliseconds:e.downloadTimeoutMs??cm});if(u instanceof Error)throw u;return{downloadedFile:await yU(u,o.createIsolatedFolder,t),coordinates:c,locatorSource:s}}else throw new Error("No download promise or error but the step requested to wait for a download");return{coordinates:c,locatorSource:s}}async function fU(r){let e=await r.locator.boundingBox({timeout:J});if(!e)throw new x("ActionFailureError","Element does not have a bounding box");if(r.hints?.relativeXYToLocator){let o=e.x+r.hints.relativeXYToLocator.x,i=e.y+r.hints.relativeXYToLocator.y;return[{x:o,y:i},"targeting hint"]}let t=e.x+e.width/2,n=e.y+e.height/2;return[{x:t,y:n},"halfway point"]}async function SU({options:r,targetingResult:e,position:t}){let n,o,i;if(r?.relativePosition){let s=await e.locator.boundingBox({timeout:J}),u=r.relativePosition.x,d=r.relativePosition.y;s?.width&&(u=Math.max(0,Math.min(r.relativePosition.x,s.width))),s?.height&&(d=Math.max(0,Math.min(r.relativePosition.y,s.height))),n=(s?.x??0)+u,o=(s?.y??0)+d,i="relative position from user"}else if(t){let s=await e.locator.boundingBox({timeout:J});n=(s?.x??0)+t.x,o=(s?.y??0)+t.y,i="predefined position"}else{let[s,u]=await fU(e);n=s.x,o=s.y,i=u}let a=e.locator.page(),l=r?.rightClick?"right":"left",c=r?.delayMs??25;return r?.doubleClick?await a.mouse.dblclick(n,o,{button:l,delay:c}):await a.mouse.click(n,o,{button:l,delay:c}),{clickX:n,clickY:o,reason:i}}async function yU(r,e,t){t.info("Download detected, saving file to disk");let n=await r.path(),o=Em(r.suggestedFilename()),i=e();await r.saveAs(uU(i,o)),nw(n,{force:!0}),setTimeout(()=>{nw(i,{recursive:!0,force:!0})},5*60*1e3);let a=_A(cU(i),o);return t.info({uri:a,downloadFolder:i},"Saved download to isolated folder"),a}function bU(r){return r.message.includes("locator.click: Timeout")&&r.message.includes("click action done")}import{platform as EU}from"os";var TU={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 vU(){let r=EU();return r==="win32"?"win32":r==="darwin"?"darwin":"linux"}function iw(r){return JSON.stringify(r.split("+").sort())}function xc(r,e){let t=vU(),n=iw(r);for(let o of Object.values(TU))if(Object.values(o).some(i=>iw(i)===n))return o[t];return process.platform==="darwin"&&!e?r=r.replaceAll("Control","Meta"):r=r.replaceAll("Meta","Control"),r}async function Nm({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 et({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:ge,codePath:"scrolling page"});else{let d=e.viewportSize()||an,p=await et({root:e,fn:()=>document.body.scrollHeight,arg:void 0,waitForPageLoad:l.waitForPageLoad,timeout:ge,codePath:"computing page height"}),[m,g,h]=await et({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:ge,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<ge;){a?.throwIfAborted();let E=await F(e.evaluate(()=>document.body.scrollHeight),{milliseconds:Z}),[b,C,A]=await F(e.evaluate(()=>{let v=document.activeElement;if(!v)return[void 0,void 0,void 0];let M=v.getBoundingClientRect();return[v.scrollTop,M.x,M.y]}),{milliseconds:Z});if(E===p&&b===m&&C===g&&A===h)break;p=E,m=b,g=C,h=A,await X(it)}}catch(f){c.warn({err:f},"Failed to wait for scroll to complete, continuing...")}}}async function Dm(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 X(it)}throw new Error(`Failed to get tab titles after all retries: ${n?.message}`)}import{randomUUID as PU}from"crypto";import{cloneDeep as Fm}from"lodash-es";function wn(r,e){let t=r.findIndex(n=>n===e);if(!(t===-1||!r[t+1]))return r[t+1]}import{createHash as AU}from"crypto";var wU="v1";function km(r,e){if(r.tagName.toLowerCase()==="svg"&&!CU(r))try{let t=aw(r,e),n=RU(JSON.stringify(t));return{version:wU,json:t,hash:n}}catch{return}}function RU(r){return AU("md5").update(r).digest("hex")}function aw(r,e){let t=r.tagName.toLowerCase(),n=xU(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=aw(a,e);l&&o.children.push(l)}}return o}function CU(r){let e=r.computedStyles.display,t=r.computedStyles.visibility,n=r.computedStyles.opacity;return e==="none"||t==="hidden"||n==="0"}function xU(r){let e={},t=r.attributes;for(let n of Object.keys(t))sr.visualAttributesForSvgSerialization.includes(n)&&(e[n]=t[n]);return t.id&&r.tagName.toLowerCase()!=="svg"&&(e.id=t.id),e}var ao={r:147,g:196,b:125,a:.55},lw={showRulers:!1,showStyles:!1,showExtensionLines:!1,contrastAlgorithm:"aa",contentColor:ao,paddingColor:ao,borderColor:ao,marginColor:ao,eventTargetColor:ao,shapeColor:ao,shapeMarginColor:ao,showInfo:!0,showAccessibilityInfo:!0};function cw({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=MU({allDocuments:i,stringConstants:o,computedStylesToFetch:t,devicePixelRatio:e,frameIndex:u,backendIdToNode:a,frameIndexToIframeNode:l,logger:n});c.roots.push(d)}),c}function MU({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((w,D)=>{u[w]=D});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??[],C=m.nodeType??[],A=m.pseudoType??{index:[],value:[]},v=m.inputChecked??{index:[]},M=e[c.frameId];for(let w=0;w<h.length;w++){let D=h[w],j=C[w],ae=f[w]??[],Q=E[w]!==void 0&&E[w]>=0?E[w]:void 0,pe=Q!==void 0?h[Q]:void 0,st=pe!==void 0?a[pe]:void 0,W=A.index.indexOf(w),z=W!==-1?e[A.value[W]]:void 0,re=u[w],le;re?le=p[re]??[]:le=[];let Xe=b[w]!==void 0?e[b[w]]?.toLowerCase():void 0;if(!Xe){l.warn({backendNodeId:D,frameId:M,frameIndex:o,nodeBounds:le},"DOM node has no tag name");continue}let we={backendNodeId:D,psuedoType:z,nodeType:j,frameIndex:o,parentFrameId:M,ownedFrameId:void 0,bounds:{x:le[0]??null,y:le[1]??null,width:le[2]??null,height:le[3]??null},computedStyles:{},attributes:{},parentBackendNodeId:pe??null,tagName:Xe,parent:st??void 0,childrenBackendIds:[],momenticIgnored:void 0,mPathSelector:void 0};st&&st.childrenBackendIds.push(D);let Dt=g.index.indexOf(w);if(Dt!==-1){let Re=g.value[Dt];i[Re]=we;let We=r[Re]?.frameId;we.ownedFrameId=We!==void 0?e[We]:void 0}for(let Re of Object.keys(we.bounds)){let We=Re;we.bounds[We]!==null&&(we.bounds[We]/=n)}let wt=re!==void 0?d[re]??[]:[];for(let Re=0;Re<wt.length&&!(Re>=t.length);Re++){let We=wt[Re];if(We===void 0||isNaN(We))continue;let Rt=e[We];if(Rt===void 0)continue;let cr=t[Re];we.computedStyles[cr]=Rt}for(let Re=0;Re<ae.length;Re+=2){let We=ae[Re],Rt=ae[Re+1];if(!We||!Rt)continue;let cr=e[We],Br=e[Rt];!cr||!Br||(we.attributes[cr]=Br)}v.index.includes(w)&&(we.attributes.checked="true"),a[we.backendNodeId]=we}return a[h[0]]}function Um(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=`${Um(t,e)}${a}`}return r.mPathSelector=n,n}function sw(r,e){return r.parentBackendNodeId!==null?e.backendIdToNode[r.parentBackendNodeId]:r.frameIndex===0?void 0:e.frameIndexToIframeNode[r.frameIndex]}var _U=["html","#document","#document-fragment"];function uw({node:r,domGraph:e}){let t=[],n=r,o=sw(r,e);if(!o)return[r.tagName];let i=()=>{if(n=o,o=sw(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++,_U.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 dw(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 pw(r,e){await r.send({method:"DOM.getDocument",params:{depth:0},timeout:ge});let t=await r.send({method:"DOM.requestNode",params:{objectId:e},timeout:ge}),o=(await r.send({method:"DOM.getAttributes",params:{nodeId:t.nodeId},timeout:ge})).attributes,i=wn(o,$r);if(!i)throw new Error(`Could not find attribute ${$r} for object ${e}`);return i}var IU=["focusable","keyshortcuts","controls","live","relevant","orientation"],OU=["selected","readonly","modal","required","invalid"],LU=["id","name","role","content"],mw=["absolute","fixed","sticky"],NU=["i"],DU=["path"],kU=["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"],fw=["ariaHiddenElement","ariaHiddenSubtree","hiddenByChildTree","inertElement","inertSubtree","notRendered","notVisible"],Sw=["activeAriaModalDialog","activeFullscreenElement","activeModalDialog"],UU=["menulistpopup","statictext","inlinetextbox"],FU=80,gw=100,yw=50,Hm=["StaticText","ListMarker","RootWebArea","LineBreak","emphasis","::before","::after"],BU=["cite"],zU={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"]},HU={name:!0,value:!0,title:!0,alt:!0,placeholder:!0,checked:!0,selected:!0,contenteditable:!0},hw={indentLevel:0},Bm=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<yw?t:""),this.role=this.role||(e.domNode.attributes.role??""),WU(this.properties,e.domNode,e.importantProperties)}qU(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&&DU.includes(this.domNode.tagName)||this.domNode?.computedStyles.display==="contents"||this.ignoredReasons.some(n=>Sw.includes(n)))return!1;if(e){if(Object.keys(this.domNode?.attributes??{}).some(o=>Aw(o,e)))return!0;let n=this.domNode?.attributes.class?.split(" ");if(n&&n.length>0&&n.some(o=>ww(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&&NU.includes(this.domNode.tagName)||kU.includes(this.role.toLowerCase())||this.role.toLowerCase()==="inlinetextbox"&&this.tagName||!this.properties.hidden&&(this.properties.focusable||this.properties.settable)||sr.alwaysInterestingTruthyPropertyNames.some(n=>!!this.properties[n]))return!0;let t=this.properties.class;return typeof t=="string"&&t.split(" ").some(n=>vw(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=hw){let t=Object.assign({},hw,e),{indentLevel:n,noChildren:o,noProperties:i,noId:a,noContent:l,condensedMode:c}=t,s=Fm(this.properties),u=" ".repeat(n),d=this.role||"",p=this.tagName??"unknown",m=this.name;d==="heading"&&m==="heading"&&(m=""),this.nameSources?.find(v=>!v.superseded&&v.type==="contents")&&this.children.length>0&&(m="");let h=this.nameSources?.find(v=>!v.superseded);if(h&&!h.nativeSource&&h.type==="relatedElement"){let v=h.attributeValue?.relatedNodes??[];v.length===1&&v[0].text&&v[0].text===m&&(m="")}let f=Hm.includes(this.role)||BU.includes(this.tagName||"");if(this.role==="StaticText"||this.role==="ListMarker")return`${u}${m}
4108
- `;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&&!(zU[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+=` ${sr.ineligibleElementAttribute}`),this.shouldSerializeBounds()&&this.domNode?.bounds){let v=this.domNode.bounds,M=Math.round(v.x??0),w=Math.round(v.y??0),D=Math.round((v.x??0)+(v.width??0)),j=Math.round((v.y??0)+(v.height??0));E+=` bounds=[${M} ${w} ${D} ${j}]`}let C=Date.now();if(Object.keys(s).length>0&&!i){if(Date.now()-C>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(([v,M])=>{if(!IU.includes(v)){{if(OU.includes(v)&&(!M||M==="false"))return;if(v==="value"&&b&&(s.type==="text"||this.role==="textbox"))return;if(v==="level"&&`${M}`=="1")return;if(v==="url"&&s.src&&p==="img")return;if(v==="url"&&s.href&&p==="a")return;if(v==="editable"&&M==="plaintext")return;if(v==="type"&&M===p)return;if(c&&!HU[v])return}typeof M=="string"?E+=` ${v}="${Ot(M,gw,!0)}"`:typeof M=="boolean"?M?E+=` ${v}`:E+=` ${v}={false}`:typeof M<"u"&&(E+=` ${v}={${Ot(JSON.stringify(M),gw,!0)}}`)}})}if(p==="::before"||p==="::after"){let v="";for(let M of this.children)v+=M.serialize({...e,indentLevel:n,neighbors:0});return v}let A=e.maxLevel!==void 0&&n/2>=e.maxLevel;if(this.children.length===0||o||A)E+=` />
4109
- `;else{let v="";for(let w of this.children)v+=w.serialize({...e,indentLevel:n+2,neighbors:0});let M=v.trim();M.length<=FU&&!M.includes(`
4110
- `)?E+=`>${M}</${p}>
4084
+ `&&(i=l),r.slice(o,i)}function Sr(r){let e=typeof r=="string"?r:r.toString();return`[${Kr}="${e}"]`}import{execSync as sF}from"child_process";import{randomUUID as $m}from"crypto";import{diff as qm}from"deep-object-diff";import{existsSync as Nc,readFileSync as lF,readdirSync as cF,statSync as kw,writeFileSync as uF}from"fs";import{Jimp as Uw}from"jimp";import dF from"js-beautify";import{cloneDeep as mi}from"lodash-es";import pF from"mime";import{platform as mF}from"os";import{basename as Fw,extname as gF,join as hF}from"path";import{v4 as fF}from"uuid";import{rmSync as aw}from"fs";import{basename as hU,join as fU}from"path";import{errors as SU}from"playwright-core";import{devices as Ak}from"playwright-core";var wA=2,li=8e3;var ci=250,it=500;var RA=5e3,CA=250,J=3e3,ge=2e3,Z=1e3,dm=3e4,pm=8e3,xA=10,mm=.05;var MA=6e4,_A=new Set(["about:blank","chrome-error://chromewebdata/"]);var gm=["button","image","generic","graphics-symbol","tab","link","menuitem","group"],hm=1e4,Wa=500,wc=Ak["Desktop Chrome"].userAgent,ui=process.env.TWO_CAPTCHA_KEY;import{mkdirSync as wk,rmSync as PA,statSync as Rk}from"fs";import*as bm from"node:fs";import Ck from"nodejs-file-downloader";import{tmpdir as xk}from"os";import vn,{basename as Mk,dirname as _k}from"path";var Em="file://",ym=vn.join(xk(),"momentic","downloads"),Sm=1e4,Pk=50*1024*1024;async function IA(r){let{uri:e}=r;if(e.startsWith(Em))return Ok(r);if(e.startsWith("http"))return Nk(r);if(WS)return Lk(r);throw new C("UserConfigurationError","The source URI for the file upload step must be a valid URL or a previously downloaded file beginning with 'file://'")}function Ik(r,e){let t=vn.join(ym,r,e.slice(Em.length)),n=vn.join(ym,r),o=t.startsWith(n);if(!bm.existsSync(t)||!o)throw new C("UserConfigurationError",`The referenced file (${e}) does not exist. Please make sure that it has been downloaded successfully.`);return t}async function Ok({uri:r,orgId:e}){let t=Ik(e,r);return{filePath:t,cleanup:()=>{PA(_k(t),{recursive:!0,force:!0})}}}async function Lk({uri:r}){let e=vn.resolve(r);if(!bm.existsSync(e))throw new C("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 Nk({uri:r,logger:e,orgId:t}){let n=new URL(r);n.search&&(n.search="");let o=Mk(n.href),i=vm(o),a=vn.extname(i);if(BS.includes(a))throw new Error(`Downloading files with extension ${a} is not allowed.`);let l=Tm(t),c,s;for(let g=1;g<=3;g++){let h=new Ck({url:r,fileName:i,directory:l,maxAttempts:1,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:Sm});try{let{downloadStatus:f,filePath:E}=await k(h.download(),{milliseconds:Sm,message:`Download timed out after ${Sm}ms`});if(f!=="COMPLETE"||!E)throw new Error(`Download ended in non-success status: ${f}`);c=E;break}catch(f){s=f}}if(!c)throw new Error(`Download failed after 3 attempts. Last error: ${s instanceof Error?s.message:s}`);let u=c,p=Rk(u).size;if(p>Pk)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(()=>PA(l,{recursive:!0,force:!0}),10*60*1e3)}}}function OA(r,e){return`${Em}${r}/${e}`}function Tm(r){let e=Math.random().toString(36).substring(4),t=vn.join(ym,r,e);return wk(t,{recursive:!0}),t}function vm(r){let e=vn.extname(r),t=vn.basename(r,e);return r=(t.length>100?t.slice(t.length-100):t)+e,r=r.trim().replaceAll(" ","_"),r}async function Dr(r,e,t){try{return await r.evaluate(o=>window.serializeElementOnlyWithText?.(o,{truncateToLength:t}),void 0,{timeout:Z})}catch(n){e.debug({err:n},"Failed to get HTML from locator for Playwright error translation");return}}var An=3.1783027;function Dk(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 yr(r){return Math.ceil(Am(r)/An)}function Am(r){let e=0;if(typeof r=="string"){let t=r;t=t.replaceAll(`
4085
+ `,""),t=t.replaceAll(" ","");let n=Dk(t);return t.length-n+An*n}if(typeof r>"u"||r===null)return 0;if(typeof r=="number")return String(r).length;if(Array.isArray(r))return r.forEach(t=>{e+=Am(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*An:e+=85*An:n==="source"&&typeof t[n]=="object"&&t[n]?.type==="base64"?e+=1600*An:e+=Am(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 Rc=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 LA(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 k(t,{milliseconds:J});return o&&e.warn({err:o},"Failed to fetch indexedDB data"),n}async function NA(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 k(n,{milliseconds:J})}catch(n){t.warn({err:n},"Failed to import indexedDB data")}}}async function DA(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 k(t,{milliseconds:J})}catch(t){e.debug({err:t},"Failed clearing index db data, continuing...")}}async function kA(r,e,t,n,o){try{await kk(r,e,t,n)}catch(i){o.error({err:i,tabIndex:e},"Error handling new console log")}}async function kk(r,e,t,n){let o=n.text();o.length>Wa&&(o=o.slice(0,Wa)+"...(TRUNCATED)");let i=[];for(let a of n.args())try{let l=await a.jsonValue(),c=JSON.stringify(l);c.length>Wa?i.push(c.slice(0,Wa)+"...(TRUNCATED)"):(typeof l!="object"||Object.keys(l).length>0)&&i.push(l)}catch{}wm(r,t,e,{url:r.url(),location:n.location(),type:n.type(),text:n.text(),args:i})}function wm(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>hm&&(i[t]=i[t].slice(Math.floor(hm/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 lr({fn:r,codePath:e,logObject:t,signal:n,logger:o}){n?.throwIfAborted();let i=Date.now(),a=await lm({promiseGenerator:r,signal:n,codePath:e,logger:o}),l=Date.now();return t[e]=l-i,a}import Uk from"truncate-json";var Fk="[redacted due to size]",UA=5e3,Bk=5e3,BA=1e4;async function zA(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 Rm(r,e){let t=e.timing(),n=new URL(e.url()),o=[...n.searchParams.entries()].map(([l,c])=>({name:l,value:c})),i={...await GA(e),url:n.toString(),method:e.method(),queryString:o};return{pageref:r,_resourceType:e.resourceType(),startedDateTime:new Date().toISOString(),request:i,timings:jA(t).timings}}async function HA(r,e,t,n){let o={},a=((await t.headerValue("content-type"))?.toLowerCase()??void 0)?.split(";")[0]??void 0;if(n)try{o=await Wk({response:t,mimeType:a,sizes:n})}catch{}let l={...await GA(t),status:t.status(),statusText:t.statusText(),content:o,redirectURL:t.headers().location,_mocked:!1};r.response=l,r.response&&n&&(r.response.bodySize=n.responseBodySize,r.response.headersSize=n.responseHeadersSize,r.response.content.size=n.responseBodySize);let c=e.timing();r.startedDateTime=new Date(c.startTime).toISOString();let{timings:s,total:u}=jA(c);r.time=u,r.timings=s}function $a(r,e,t){r.harEntries||(r.harEntries={}),r.harEntries[t]=e}function FA(r){try{return new Date(r).toISOString()}catch{return}}function zk(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=kr(i),e.value=kr(a);continue}i==="Domain"&&(e.domain=kr(a)),i==="Expires"&&(e.expires=FA(a)),i==="HttpOnly"&&(e.httpOnly=!0),i==="Max-Age"&&(e.expires=FA(Date.now()+ +a*1e3)),i==="Path"&&(e.path=kr(a)),i==="Secure"&&(e.secure=!0)}return e}async function GA(r){let e=await r.allHeaders(),t=e.cookie?.split(";").map(zk)??[];return{headers:Object.entries(e).map(([n,o])=>({name:kr(n),value:kr(o)})),cookies:t}}async function VA(r,e,t){let n=await r.headerValue("content-type")??"application/octet-stream";if(t&&(e.request.bodySize=t.requestBodySize,e.request.headersSize=t.requestHeadersSize),t&&t.requestBodySize>BA){e.request.postData={mimeType:n,text:"",params:[],_redactedReason:"Request body redacted due to size"};return}let o=r.postData();if(!o)return;let i={mimeType:n,text:kr(o),params:[]};if(n==="application/x-www-form-urlencoded"){let a=new URLSearchParams(o.toString());for(let[l,c]of a.entries())i.params.push({name:kr(l),value:c?kr(c):void 0})}e.request.postData=i}var Hk=["image","font","video","audio"],Gk=["text"],Vk=["json","xml","html","javascript"];function jk(r){let[e,t]=r.split("/");return!e||Hk.includes(e)?!1:Gk.includes(e)?!0:t?!!Vk.some(n=>t?.includes(n)):!1}async function Wk({response:r,mimeType:e,sizes:t}){let n={mimeType:e,encoding:await r.headerValue("content-encoding")??void 0};return t.responseBodySize>=BA&&(n._redactedReason="Response body redacted due to size"),!e||!jk(e)?n._redactedReason="Body redacted because it's not a viewable MIME type":n.text=kr(await r.text()),n}function kr(r){try{let e=JSON.parse(r),{jsonString:t}=Uk(r,Bk);return t}catch{return r.length>UA?r.slice(0,UA)+Fk:r}}function io(r){return r<0?0:r}function jA(r){return{timings:{blocked:io(r.domainLookupStart),dns:io(r.domainLookupEnd-r.domainLookupStart),connect:io(r.connectEnd-r.connectStart),send:io(r.responseStart-r.requestStart),wait:0,receive:io(r.responseEnd-r.responseStart),ssl:io(r.connectEnd-r.secureConnectionStart)},total:io(r.responseEnd)}}function WA(){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 et({root:r,fn:e,arg:t,timeout:n,waitForPageLoad:o,codePath:i}){return await o(),await k(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.`})}import{errors as $k}from"playwright-core";async function ao({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 $k.TimeoutError)t.warn({err:c,rootUrl:(await n.state.getRoot()).url()},`Encountered Playwright error while performing ${e}`),l=await qk(c,i.locator,n,t);else throw c}throw l instanceof C?l:new C("ActionFailureError",`Failed to interact with targeted element. Error: ${l.message}`,{errOptions:{cause:l}})}async function qk(r,e,t,n){return r.message.includes("attempt #")?Kk(r,e,t,n):Yk(r)}async function Kk(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(`
4086
+ `,";").replace(/\s+/g," ");let a="",l=await Dr(e,n,150);if(l&&(a=`Target element HTML: ${Ot(l,100,!0)}`),i.includes("element is not enabled"))return new C("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(Sr(s)),d=await Dr(u,n,150);d&&(c=`Covering element HTML: ${Ot(d,100,!0)}`)}return new C("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}
4087
+ ${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:J});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 C("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 C("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 Yk(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 C("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}import{execSync as rU}from"child_process";import{existsSync as Ka,mkdirSync as Im,readdirSync as nU,rmSync as XA}from"fs";import{homedir as JA}from"os";import{basename as oU,join as Rn,resolve as iU}from"path";import{chromium as ZA}from"playwright-core";import{addExtra as aU}from"playwright-extra";import sU from"puppeteer-extra-plugin-recaptcha";function $A(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 Jk}from"crypto";function qA(r,e){for(let t of Object.values(e))if(t.matcher.matches({url:r.url(),method:r.method()}))return t}async function KA(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 Xk(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},$a(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 Xk(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 Cm(r){try{await Zk(r)}catch(e){r.logger.warn({err:e},"Error handling intercepted request, continuing...")}}async function Zk(r){let{pageId:e,route:t,request:n,debugData:o,logger:i,requestRecorders:a,mocks:l}=r,c=Jk(),s=await Rm(e,n);try{$a(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=qA(n,l);u?await KA({logger:i,route:t,mock:u,entry:s,debugData:o,requestId:c,requestRecorders:a}):await Qk({route:t,request:n,debugData:o,logger:i,requestRecorders:a,entry:s,requestId:c})}async function Qk({route:r,request:e,debugData:t,logger:n,requestRecorders:o,entry:i,requestId:a}){await r.continue();try{let l=await e.response(),c;try{await l?.finished()}catch{}try{c=await e.sizes()}catch{}if(i&&await VA(e,i,c),!l||!i)return;await HA(i,e,l,c),$a(t,i,a);for(let s of Object.values(o))s.onRequestComplete(a,i)}catch(l){l.message.includes("has been closed")||n.warn({err:l},"Failed to add response to HAR")}}async function eU(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 tU(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 Cc(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 xm(r){let e=r.request(),t=r.status(),n=r.headers(),o=await tU(r);return{request:{url:e.url(),method:e.method(),headers:e.headers(),...await eU(e)},response:{status:t,headers:n,...o},status:t,headers:n,...o}}var wn=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:Ec(t,this.requestMatcher.urlMatcher)}};function qa(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()}import{homedir as Mm,platform as _m}from"os";import{join as Pm}from"path";function xc(){let r=[];if(_m()==="linux"){let e=Mm();["chromium","google-chrome","chrome-canary"].forEach(t=>{r.push(Pm(e,".config",t,"Crash Reports"))})}else if(_m()==="darwin"){let e=Mm();["Chromium","Google","Chrome for Testing"].forEach(t=>{r.push(Pm(e,"Library","Application Support",t,"Crashpad"))})}else if(_m()==="win32"){let e=Mm();["Chromium","Google","Google Chrome Canary"].forEach(t=>{r.push(Pm(e,"AppData","Local",t,"User Data","Crashpad","reports"))})}return r}function YA(){return{name:"fs_optout",value:"1",domain:".fullstory.com",path:"/",expires:Date.now()/1e3+365*24*60*60,httpOnly:!1,secure:!0,sameSite:"None"}}var Om=Rn(JA(),"momentic","chromium"),QA=aU(ZA);QA.use(sU({provider:{id:"2captcha",token:ui},visualFeedback:!0}));var lU=["--enable-crashpad","--crash-on-hang-threads=UI:18,IO:18"],cU=["--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"],uU=["--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-webgl2","--disable-audio-input","--disable-audio-output"];async function ew({baseUrl:r,logger:e,storage:t,enricher:n,userBrowserSettings:o,contextArgs:i,iconKnowledgeBase:a,callbacks:l,videoOptions:c}){process.env.PW_TEST_SCREENSHOT_NO_FONTS_READY="1";let s;switch(o.browserType){case"Google Chrome":s="chrome";break;case"Chrome for Testing":s=void 0;break;case"Chromium":s="chromium";break;default:s="chromium";break}let u=[...cU];!xr&&pU()&&u.push("--disable-dev-shm-usage");let d={headless:process.env.MOMENTIC_HEADFUL_BROWSER!=="true",handleSIGTERM:!1,chromiumSandbox:!1,channel:s},p={...i??{},geolocation:i?.geolocation||Lf,locale:i?.locale||If,timezoneId:i?.timezoneId||Of,colorScheme:i?.colorScheme,httpCredentials:o.basicAuthorization?{username:o.basicAuthorization.username??"",password:o.basicAuthorization.password??""}:void 0,javaScriptEnabled:o.disableJavaScript?!1:void 0,ignoreHTTPSErrors:o.ignoreHttpsErrors??!1,userAgent:o.userAgent??wc,viewport:i?.viewport??ln,serviceWorkers:"block",storageState:{cookies:[YA()],origins:[]},proxy:o.proxy};o.initialLocalStorage&&(p.storageState.origins=Object.entries(o.initialLocalStorage).map(([b,x])=>({origin:b,localStorage:Object.entries(x).map(([A,v])=>({name:A,value:v}))}))),process.env.MOMENTIC_CHROME_EXTRA_ARGS&&u.push(...process.env.MOMENTIC_CHROME_EXTRA_ARGS.split(","));let m=null,g,h,f={systemDevicePixelRatio:i?.deviceScaleFactor,isNewHeadless:!1};(s==="chrome"||s==="chromium")&&(f.isNewHeadless=!0,d.headless&&u.push("--headless=new")),process.env.BROWSER_MEMORY_MB&&u.push(`--js-flags=--max_old_space_size=${process.env.BROWSER_MEMORY_MB}`);try{let b=xc();b.forEach(x=>{if(!Ka(x))return;["new","pending","completed"].forEach(v=>{let _=Rn(x,v);if(!Ka(_))return;let R=nU(_);for(let D=0;D<R.length;D++){let j=Rn(_,R[D]);XA(j,{force:!0})}})}),b.forEach(x=>{Ka(x)||Im(x,{recursive:!0});let A=Rn(x,`write-test-${Date.now()}`);Im(A,{recursive:!0}),XA(A,{recursive:!0,force:!0})}),u.push(...lU)}catch(b){e.warn({err:b},"Could not create Chrome crash report directory, not enabling crashpad")}o.disableGpu&&u.push(...uU);let E=o.localChromeExtensionPaths?.map(b=>b.startsWith("~")?Rn(JA(),b.slice(1)):b);if(E?.length){if(s===void 0)throw new C("UserConfigurationError","Chrome extensions are only supported on Chromium and Google Chrome.");for(let v of E){let _=Rn(v,"manifest.json");if(!Ka(_))throw new C("UserConfigurationError",`Chrome extension path ${_} does not exist.`)}if(xr)throw new C("UserConfigurationError","Cannot use persistent browser context on Momentic Cloud");let b=Rn(Om,`momentic-session-${Date.now()}`);if(!Ka(b))try{Im(b,{recursive:!0})}catch(v){throw new C("UserConfigurationError",`Failed to create browser cache directory. Please make sure you have sufficient permissions to create the ${Om} folder: ${v}`)}let x=[...u],A=E.map(v=>iU(v)).join(",");x.push(`--disable-extensions-except=${A}`),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}`),g=await ZA.launchPersistentContext(Rn(Om,`momentic-session-${Date.now()}`),{...d,...p,ignoreDefaultArgs:["--disable-extensions","--disable-component-extensions-with-background-pages"],args:x,baseURL:r}),e.info({sharedContextOptions:p,sharedBrowserOptions:d,userBrowserSettings:o,chromeArgs:x,properties:f,baseUrl:r},"Browser initialization context args (persistent)"),h=g.pages()[0]}else{m=await QA.launch({...d,args:u});let b={...p,baseURL:r,recordVideo:c?{dir:c.videoOutputPath}:void 0};g=await m.newContext(b),e.info({contextArgs:b,sharedBrowserOptions:d,chromeArgs:u,userBrowserSettings:o,properties:f,baseUrl:r},"Browser initialization context args (standard)"),h=await g.newPage()}if(c){let b=await h.video()?.path();if(b){let x=oU(b);c.onVideoPageChange({videoName:x})}}xr&&await g.route("**",qa);try{let b=m?.version();e.info({browserVersion:b},"Got browser version")}catch(b){e.warn({err:b},"Could not get browser version string")}return{browser:m,context:g,page:h,baseUrl:r,logger:e,storage:t,enricher:n,userBrowserSettings:o,viewport:p.viewport||ln,properties:f,clientCallbacks:l,iconKnowledgeBase:a,onVideoPageChange:c?.onVideoPageChange}}function dU(){if(process.platform!=="linux")return null;try{let e=rU("df -k /dev/shm",{encoding:"utf8"}).trim().split(/\r?\n/),n=e[e.length-1]?.trim().split(/\s+/)??[];if(!n||n.length<2)return null;let o=parseInt(n[1],10);return Number.isNaN(o)||o<=0?null:o/1024}catch{return null}}function pU(){let e=process.env.BROWSER_ENABLE_DEV_SHM;if(e==="1")return!1;if(e==="0")return!0;let t=dU();return t==null?!1:t<128}async function tw(r){try{return await mU(r)}catch(e){r.logger.warn({err:e},"Failed to transform locator for Chakra click, continuing...");return}}async function mU({locator:r,logger:e}){let[t,n]=await r.evaluate(c=>[c.id,c.tagName.toLowerCase()],{timeout:Z}),o=await Dr(r,e,500),i=await r.boundingBox({timeout:Z});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:Z}),{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?.[Ac],h=c.getAttribute(Kr),f=!g&&h?Sr(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:Z});if(a.type==="error")throw new Error(a.error);let l=r.page().locator(a.selector);return await l.waitFor({state:"visible",timeout:Z}),e.info({parentElementResult:a,originalElementDisplayString:o},`Redirected click to parent element with selector: ${a.selector}`),{locator:l,relativePoint:a.relativePoint}}var nw=["date","datetime-local","month","time","week"],rw={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 ow(r){try{await k(gU(r),{milliseconds:J})}catch(e){r.logger.warn({err:e},"Failed to transform native datetime input, continuing...")}}async function gU({root:r,text:e,options:t,logger:n,callbacks:o}){let i=(await et({root:r,fn:()=>document.activeElement?.getAttribute("type")??"",timeout:Z,arg:void 0,waitForPageLoad:o.waitForPageLoad,codePath:"transforming native datetime input"})).toLowerCase();if(!rw[i])return;rw[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 Bt}from"zod";var iw=Bt.object({doubleClick:Bt.boolean().optional(),rightClick:Bt.boolean().optional(),force:Bt.boolean().optional(),waitForDownload:Bt.boolean().optional(),delayMs:Bt.number().optional(),downloadTimeoutMs:Bt.number().optional(),relativePosition:Bt.object({x:Bt.number(),y:Bt.number()}).optional()}),PSe=Bt.object({repeat:Bt.number().optional(),convertMeta:Bt.boolean().optional().describe("misleading name due to backcompat. converts keyshortcuts + meta/control to platform-specific combos. defaults to true"),delayMs:Bt.number().optional()});async function Mc({locator:r,callbacks:e,logger:t,timeoutMs:n=Z}){try{await Lm(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 k(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 Lm(r,e=Z){let t=await r.state.getRoot();await et({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 Nm(r){let e=!!r.browserCallbacks.state.userBrowserSettings.visualActions;return ao({action:"clicking element",targetingResult:r.targetingResult,logger:r.logger,retryTimeoutMs:r.retryTimeoutMs,callbacks:r.browserCallbacks,func:async t=>sw({...r,targetingResult:t,useVisualClick:e})})}async function yU(r,e){let{redirectionAttempts:t=0}=e;if(t>=2)throw r;try{return await bU(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 bU(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:Z});if(!i)throw r;let a=o.page().locator(`[for=${JSON.stringify(i)}]`);return await a.waitFor({state:"visible",timeout:Z}),t.warn({err:r},"Attempting locator redirection due to input being covered by label"),sw({...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 EU(r){let{logger:e,targetingResult:t,position:n,options:o}=r,i=iw.safeParse(o),a=Date.now(),{clickX:l,clickY:c,reason:s}=await AU({targetingResult:t,position:n,options:o});return e.info({position:n,options:i.success?i.data:void 0,clickLocation:{clickX:l,clickY:c,reason:s},duration:Date.now()-a},"Visual click"),{x:l,y:c}}async function TU(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 s=await tw({locator:i,logger:o});s&&(i=s.locator,a=s.relativePoint??a)}let l=n?.force||t.hints?.force||!1;l&&!a&&t.hints?.relativeXYToLocator&&(a=t.hints.relativeXYToLocator);let c=i.toString();try{o.info({locator:c},"Locator click"),n?.doubleClick?await i.dblclick({button:n.rightClick?"right":"left",timeout:J,position:a,delay:n?.delayMs??25,force:l}):await i.click({button:n?.rightClick?"right":"left",timeout:J,position:a,delay:n?.delayMs??25,force:l})}catch(s){let u=s;if(RU(u))o.warn({err:u},"Click action timed out while waiting for navigation after completion, continuing...");else return o.error({err:u},"Error clicking on locator, attempting to recover..."),yU(u,{...r,targetingResult:{...i,locator:i}})}return{locatorSource:c}}async function sw(r){let{options:e,logger:t,browserCallbacks:n,controllerCallbacks:o,useVisualClick:i,targetingResult:a}=r,l;e?.waitForDownload&&(l=(async()=>{let u=e.downloadTimeoutMs??dm;try{return await a.locator.page().waitForEvent("download",{timeout:u})}catch(d){return d instanceof SU.TimeoutError?new C("ActionFailureError",`Download did not complete in ${u}ms`):new C("ActionFailureError",`Download failed: ${d.message}`)}})());try{await Mc({locator:a.locator,callbacks:n,logger:t,timeoutMs:Z})}catch(u){t.warn({err:u},"Error highlighting locator in click, continuing...")}let c,s;if(i?c=await EU(r):s=(await TU(r)).locatorSource,e?.waitForDownload)if(l){if(!o?.createIsolatedFolder)throw new C("InternalWebAgentError","Cannot wait for download without a callback to create an isolated folder");t.info("Waiting for download to start and complete");let u=await k(l,{milliseconds:e.downloadTimeoutMs??dm});if(u instanceof Error)throw u;return{downloadedFile:await wU(u,o.createIsolatedFolder,t),coordinates:c,locatorSource:s}}else throw new Error("No download promise or error but the step requested to wait for a download");return{coordinates:c,locatorSource:s}}async function vU(r){let e=await r.locator.boundingBox({timeout:J});if(!e)throw new C("ActionFailureError","Element does not have a bounding box");if(r.hints?.relativeXYToLocator){let o=e.x+r.hints.relativeXYToLocator.x,i=e.y+r.hints.relativeXYToLocator.y;return[{x:o,y:i},"targeting hint"]}let t=e.x+e.width/2,n=e.y+e.height/2;return[{x:t,y:n},"halfway point"]}async function AU({options:r,targetingResult:e,position:t}){let n,o,i;if(r?.relativePosition){let s=await e.locator.boundingBox({timeout:J}),u=r.relativePosition.x,d=r.relativePosition.y;s?.width&&(u=Math.max(0,Math.min(r.relativePosition.x,s.width))),s?.height&&(d=Math.max(0,Math.min(r.relativePosition.y,s.height))),n=(s?.x??0)+u,o=(s?.y??0)+d,i="relative position from user"}else if(t){let s=await e.locator.boundingBox({timeout:J});n=(s?.x??0)+t.x,o=(s?.y??0)+t.y,i="predefined position"}else{let[s,u]=await vU(e);n=s.x,o=s.y,i=u}let a=e.locator.page(),l=r?.rightClick?"right":"left",c=r?.delayMs??25;return r?.doubleClick?await a.mouse.dblclick(n,o,{button:l,delay:c}):await a.mouse.click(n,o,{button:l,delay:c}),{clickX:n,clickY:o,reason:i}}async function wU(r,e,t){t.info("Download detected, saving file to disk");let n=await r.path(),o=vm(r.suggestedFilename()),i=e();await r.saveAs(fU(i,o)),aw(n,{force:!0}),setTimeout(()=>{aw(i,{recursive:!0,force:!0})},5*60*1e3);let a=OA(hU(i),o);return t.info({uri:a,downloadFolder:i},"Saved download to isolated folder"),a}function RU(r){return r.message.includes("locator.click: Timeout")&&r.message.includes("click action done")}import{platform as CU}from"os";var xU={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 MU(){let r=CU();return r==="win32"?"win32":r==="darwin"?"darwin":"linux"}function lw(r){return JSON.stringify(r.split("+").sort())}function _c(r,e){let t=MU(),n=lw(r);for(let o of Object.values(xU))if(Object.values(o).some(i=>lw(i)===n))return o[t];return process.platform==="darwin"&&!e?r=r.replaceAll("Control","Meta"):r=r.replaceAll("Meta","Control"),r}async function Dm({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 et({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:ge,codePath:"scrolling page"});else{let d=e.viewportSize()||ln,p=await et({root:e,fn:()=>document.body.scrollHeight,arg:void 0,waitForPageLoad:l.waitForPageLoad,timeout:ge,codePath:"computing page height"}),[m,g,h]=await et({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:ge,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<ge;){a?.throwIfAborted();let E=await k(e.evaluate(()=>document.body.scrollHeight),{milliseconds:Z}),[b,x,A]=await k(e.evaluate(()=>{let v=document.activeElement;if(!v)return[void 0,void 0,void 0];let _=v.getBoundingClientRect();return[v.scrollTop,_.x,_.y]}),{milliseconds:Z});if(E===p&&b===m&&x===g&&A===h)break;p=E,m=b,g=x,h=A,await Y(it)}}catch(f){c.warn({err:f},"Failed to wait for scroll to complete, continuing...")}}}async function km(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 Y(it)}throw new Error(`Failed to get tab titles after all retries: ${n?.message}`)}import{randomUUID as kU}from"crypto";import{cloneDeep as Bm}from"lodash-es";function Cn(r,e){let t=r.findIndex(n=>n===e);if(!(t===-1||!r[t+1]))return r[t+1]}import{createHash as _U}from"crypto";var PU="v1";function Um(r,e){if(r.tagName.toLowerCase()==="svg"&&!OU(r))try{let t=cw(r,e),n=IU(JSON.stringify(t));return{version:PU,json:t,hash:n}}catch{return}}function IU(r){return _U("md5").update(r).digest("hex")}function cw(r,e){let t=r.tagName.toLowerCase(),n=LU(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=cw(a,e);l&&o.children.push(l)}}return o}function OU(r){let e=r.computedStyles.display,t=r.computedStyles.visibility,n=r.computedStyles.opacity;return e==="none"||t==="hidden"||n==="0"}function LU(r){let e={},t=r.attributes;for(let n of Object.keys(t))sr.visualAttributesForSvgSerialization.includes(n)&&(e[n]=t[n]);return t.id&&r.tagName.toLowerCase()!=="svg"&&(e.id=t.id),e}var so={r:147,g:196,b:125,a:.55},dw={showRulers:!1,showStyles:!1,showExtensionLines:!1,contrastAlgorithm:"aa",contentColor:so,paddingColor:so,borderColor:so,marginColor:so,eventTargetColor:so,shapeColor:so,shapeMarginColor:so,showInfo:!0,showAccessibilityInfo:!0};function pw({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=NU({allDocuments:i,stringConstants:o,computedStylesToFetch:t,devicePixelRatio:e,frameIndex:u,backendIdToNode:a,frameIndexToIframeNode:l,logger:n});c.roots.push(d)}),c}function NU({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((R,D)=>{u[R]=D});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??[],x=m.nodeType??[],A=m.pseudoType??{index:[],value:[]},v=m.inputChecked??{index:[]},_=e[c.frameId];for(let R=0;R<h.length;R++){let D=h[R],j=x[R],ae=f[R]??[],Q=E[R]!==void 0&&E[R]>=0?E[R]:void 0,me=Q!==void 0?h[Q]:void 0,st=me!==void 0?a[me]:void 0,W=A.index.indexOf(R),z=W!==-1?e[A.value[W]]:void 0,re=u[R],le;re?le=p[re]??[]:le=[];let Xe=b[R]!==void 0?e[b[R]]?.toLowerCase():void 0;if(!Xe){l.warn({backendNodeId:D,frameId:_,frameIndex:o,nodeBounds:le},"DOM node has no tag name");continue}let Re={backendNodeId:D,psuedoType:z,nodeType:j,frameIndex:o,parentFrameId:_,ownedFrameId:void 0,bounds:{x:le[0]??null,y:le[1]??null,width:le[2]??null,height:le[3]??null},computedStyles:{},attributes:{},parentBackendNodeId:me??null,tagName:Xe,parent:st??void 0,childrenBackendIds:[],momenticIgnored:void 0,mPathSelector:void 0};st&&st.childrenBackendIds.push(D);let Dt=g.index.indexOf(R);if(Dt!==-1){let Ce=g.value[Dt];i[Ce]=Re;let We=r[Ce]?.frameId;Re.ownedFrameId=We!==void 0?e[We]:void 0}for(let Ce of Object.keys(Re.bounds)){let We=Ce;Re.bounds[We]!==null&&(Re.bounds[We]/=n)}let wt=re!==void 0?d[re]??[]:[];for(let Ce=0;Ce<wt.length&&!(Ce>=t.length);Ce++){let We=wt[Ce];if(We===void 0||isNaN(We))continue;let Rt=e[We];if(Rt===void 0)continue;let ur=t[Ce];Re.computedStyles[ur]=Rt}for(let Ce=0;Ce<ae.length;Ce+=2){let We=ae[Ce],Rt=ae[Ce+1];if(!We||!Rt)continue;let ur=e[We],Hr=e[Rt];!ur||!Hr||(Re.attributes[ur]=Hr)}v.index.includes(R)&&(Re.attributes.checked="true"),a[Re.backendNodeId]=Re}return a[h[0]]}function Fm(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=`${Fm(t,e)}${a}`}return r.mPathSelector=n,n}function uw(r,e){return r.parentBackendNodeId!==null?e.backendIdToNode[r.parentBackendNodeId]:r.frameIndex===0?void 0:e.frameIndexToIframeNode[r.frameIndex]}var DU=["html","#document","#document-fragment"];function mw({node:r,domGraph:e}){let t=[],n=r,o=uw(r,e);if(!o)return[r.tagName];let i=()=>{if(n=o,o=uw(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++,DU.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 gw(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 hw(r,e){await r.send({method:"DOM.getDocument",params:{depth:0},timeout:ge});let t=await r.send({method:"DOM.requestNode",params:{objectId:e},timeout:ge}),o=(await r.send({method:"DOM.getAttributes",params:{nodeId:t.nodeId},timeout:ge})).attributes,i=Cn(o,Kr);if(!i)throw new Error(`Could not find attribute ${Kr} for object ${e}`);return i}var UU=["focusable","keyshortcuts","controls","live","relevant","orientation"],FU=["selected","readonly","modal","required","invalid"],BU=["id","name","role","content"],fw=["absolute","fixed","sticky"],zU=["i"],HU=["path"],GU=["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"],bw=["ariaHiddenElement","ariaHiddenSubtree","hiddenByChildTree","inertElement","inertSubtree","notRendered","notVisible"],Ew=["activeAriaModalDialog","activeFullscreenElement","activeModalDialog"],VU=["menulistpopup","statictext","inlinetextbox"],jU=80,Sw=100,Tw=50,Gm=["StaticText","ListMarker","RootWebArea","LineBreak","emphasis","::before","::after"],WU=["cite"],$U={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"]},qU={name:!0,value:!0,title:!0,alt:!0,placeholder:!0,checked:!0,selected:!0,contenteditable:!0},yw={indentLevel:0},zm=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<Tw?t:""),this.role=this.role||(e.domNode.attributes.role??""),JU(this.properties,e.domNode,e.importantProperties)}QU(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&&HU.includes(this.domNode.tagName)||this.domNode?.computedStyles.display==="contents"||this.ignoredReasons.some(n=>Ew.includes(n)))return!1;if(e){if(Object.keys(this.domNode?.attributes??{}).some(o=>Cw(o,e)))return!0;let n=this.domNode?.attributes.class?.split(" ");if(n&&n.length>0&&n.some(o=>xw(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&&zU.includes(this.domNode.tagName)||GU.includes(this.role.toLowerCase())||this.role.toLowerCase()==="inlinetextbox"&&this.tagName||!this.properties.hidden&&(this.properties.focusable||this.properties.settable)||sr.alwaysInterestingTruthyPropertyNames.some(n=>!!this.properties[n]))return!0;let t=this.properties.class;return typeof t=="string"&&t.split(" ").some(n=>Rw(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=yw){let t=Object.assign({},yw,e),{indentLevel:n,noChildren:o,noProperties:i,noId:a,noContent:l,condensedMode:c}=t,s=Bm(this.properties),u=" ".repeat(n),d=this.role||"",p=this.tagName??"unknown",m=this.name;d==="heading"&&m==="heading"&&(m=""),this.nameSources?.find(v=>!v.superseded&&v.type==="contents")&&this.children.length>0&&(m="");let h=this.nameSources?.find(v=>!v.superseded);if(h&&!h.nativeSource&&h.type==="relatedElement"){let v=h.attributeValue?.relatedNodes??[];v.length===1&&v[0].text&&v[0].text===m&&(m="")}let f=Gm.includes(this.role)||WU.includes(this.tagName||"");if(this.role==="StaticText"||this.role==="ListMarker")return`${u}${m}
4088
+ `;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&&!($U[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+=` ${sr.ineligibleElementAttribute}`),this.shouldSerializeBounds()&&this.domNode?.bounds){let v=this.domNode.bounds,_=Math.round(v.x??0),R=Math.round(v.y??0),D=Math.round((v.x??0)+(v.width??0)),j=Math.round((v.y??0)+(v.height??0));E+=` bounds=[${_} ${R} ${D} ${j}]`}let x=Date.now();if(Object.keys(s).length>0&&!i){if(Date.now()-x>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(([v,_])=>{if(!UU.includes(v)){{if(FU.includes(v)&&(!_||_==="false"))return;if(v==="value"&&b&&(s.type==="text"||this.role==="textbox"))return;if(v==="level"&&`${_}`=="1")return;if(v==="url"&&s.src&&p==="img")return;if(v==="url"&&s.href&&p==="a")return;if(v==="editable"&&_==="plaintext")return;if(v==="type"&&_===p)return;if(c&&!qU[v])return}typeof _=="string"?E+=` ${v}="${Ot(_,Sw,!0)}"`:typeof _=="boolean"?_?E+=` ${v}`:E+=` ${v}={false}`:typeof _<"u"&&(E+=` ${v}={${Ot(JSON.stringify(_),Sw,!0)}}`)}})}if(p==="::before"||p==="::after"){let v="";for(let _ of this.children)v+=_.serialize({...e,indentLevel:n,neighbors:0});return v}let A=e.maxLevel!==void 0&&n/2>=e.maxLevel;if(this.children.length===0||o||A)E+=` />
4089
+ `;else{let v="";for(let R of this.children)v+=R.serialize({...e,indentLevel:n+2,neighbors:0});let _=v.trim();_.length<=jU&&!_.includes(`
4090
+ `)?E+=`>${_}</${p}>
4111
4091
  `:E+=`>
4112
4092
  ${v}${u}</${p}>
4113
- `}if(e.neighbors!==void 0&&e.neighbors>0&&this.parent){let v=this.parent.children.findIndex(D=>D.id===this.id),M=v>0?this.parent.children[v-1]?.serialize({...e,neighbors:0}):"",w=v<this.parent.children.length-1?this.parent.children[v+1]?.serialize({...e,neighbors:0}):"";return`${M||""}
4093
+ `}if(e.neighbors!==void 0&&e.neighbors>0&&this.parent){let v=this.parent.children.findIndex(D=>D.id===this.id),_=v>0?this.parent.children[v-1]?.serialize({...e,neighbors:0}):"",R=v<this.parent.children.length-1?this.parent.children[v+1]?.serialize({...e,neighbors:0}):"";return`${_||""}
4114
4094
  ${E}
4115
- ${w||""}`}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:Fm(this.internalProperties),importantProperties:this.importantProperties,parentFrame:this.parentFrame,flagNotActionableNodes:this.flagNotActionableNodes});return e.tagName=this.tagName,e.dataMomenticId=this.dataMomenticId,e.properties=Fm(this.properties),e}},zm=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(Hm.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=c=>c.role==="StaticText"||c.role==="ListMarker",o=new WeakMap,i=(c,s)=>{if(o.has(c))return o.get(c);let u=c.serialize({indentLevel:s,noChildren:!0});return o.set(c,u),u},a=(c,s,u)=>{let d=c.shallowClone();d.children=[];let p=i(c,s).length;if(u<=p)return{clone:d,used:p};if(n(c)||c.children.length===0)return{clone:d,used:p};let m=p,g=u-m;for(let h of c.children){let f=s+2,E=i(h,f).length;if(g<E)break;let{clone:b,used:C}=a(h,f,g);if(C>g)break;d.children.push(b),b.parent=d,m+=C,g-=C}return{clone:d,used:m}},{clone:l}=a(t,0,Math.max(1e4,e));return new r(l,this.a11yIdNodeMap,this.dataMomenticIdMap,this.selectorToNodeMap)}};function GU(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 VU(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?(ol({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?(ol({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 bw({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,allowedA11yIgnoreReasonsOverride:m,cdpClient:g,logger:h,callId:f}){if(!e&&r.parentId)throw new Error(`Got no parent for accessibility node ${r.nodeId}: ${JSON.stringify(r)}`);let E=(z,re={})=>{},b=r.backendDOMNodeId,C=UU.includes(r.role?.value?.toLowerCase()??"");if(!C&&b===void 0)return E("Filtering out node since it doesn't exist in the DOM"),[];let A=b?i.backendIdToNode[b]:void 0;if(!C&&!A)try{let z=await F(g.send({method:"DOM.describeNode",params:{backendNodeId:b}}),{milliseconds:750,fallback:()=>{h.debug("Timeout getting node from CDP while processing a11y tree")}});if(z&&z.node.nodeName.toLowerCase()==="slot"&&z.node.distributedNodes?.length)h.debug({redirectedDomNode:A,parentAXNode:e?.getNodeOnlySerializedForm(),originalAXNode:r,cdpResult:z},"Redirecting node to assigned slot");else return E("Filtering out node since it doesn't exist in the DOM",{cdpResult:z}),[]}catch(z){return E("Filtering out node since it doesn't exist in the DOM",{err:z}),[]}if(A&&e&&s&&u&&r.backendDOMNodeId&&!VU(A,u,h,f))return A.momenticIgnored=!0,[];if(A&&A.computedStyles.display==="none")return A.momenticIgnored=!0,[];if(A&&A.computedStyles.opacity==="0"&&c!==!0){if(c==="inputs-only"&&A.tagName.toLowerCase()!=="input")return A.momenticIgnored=!0,[];if(c===!1)return A.momenticIgnored=!0,[]}let v=r.name?.value?typeof r.name.value=="string"?r.name.value:`${r.name.value}`:"",M=r.value?.value?typeof r.value.value=="string"?r.value.value:`${r.value.value}`:"",w=new Bm({domNode:A,id:parseInt(r.nodeId),role:r.role?.value||"",name:v,nameSources:r.name?.sources,content:M,properties:r.properties,children:[],ignoredReasons:r.ignoredReasons?.filter(z=>(m??fw).includes(z.name)||Sw.includes(z.name))??[],pathFromRoot:(e?`${e.pathFromRoot} `:"")+GU(r),backendNodeID:r.backendDOMNodeId,ignoredByCDP:r.ignored,internalProperties:{inCodeMirrorEditor:e?.internalProperties?.inCodeMirrorEditor},importantProperties:p,parentFrame:n.type==="root"?void 0:n,flagNotActionableNodes:l}),D=n,j=a[t],ae=t;if(A?.tagName.toLowerCase()==="iframe"&&A.ownedFrameId){let z=n.childFrames.find(Xe=>Xe.frameId===A.ownedFrameId),re=o[z?.frameId??""]?.root,le=a[z?.frameId??""];if(z&&re&&le){r.childIds&&r.childIds.length>0&&h.debug("Replacing existing node's children with children from the iframe");let Xe=re;r.childIds=Xe.childIds,D=z,j=le,ae=z.frameId}}let Q=A?.childrenBackendIds?.length??0,pe=(r.childIds??[]).filter(z=>!!j.get(parseInt(z))).length;if(Q>pe){let z=r.childIds?.map(le=>j.get(parseInt(le))).filter(Boolean).map(le=>le?.backendDOMNodeId).filter(le=>le!==void 0)??[],re=0;for(let le of A?.childrenBackendIds??[]){if(z.includes(le)){re=(r.childIds?.findIndex(Re=>j.get(parseInt(Re))?.backendDOMNodeId===le)??0)+1;continue}let Xe=i.backendIdToNode[le];if(!Xe||Xe?.tagName.toLowerCase()!=="svg")continue;let we=Math.floor(-1*Math.random()*1e7),Dt={nodeId:we.toString(),parentId:r.nodeId,ignored:!1,backendDOMNodeId:le,frameId:ae,role:{type:"string",value:"graphics-symbol"}};j.set(we,Dt),r.childIds||(r.childIds=[]),r.childIds.splice(re,0,we.toString()),re++}}if(r.childIds?.length===1&&A){let z=j.get(parseInt(r.childIds[0])),re=z?.role?.value,le=A.childrenBackendIds;if(z&&re==="StaticText"&&le.length===1){let Xe=i.backendIdToNode[le[0]];if(Xe?.tagName?.toLowerCase()==="span"){let we=Math.floor(-1*Math.random()*1e7).toString(),Dt={nodeId:we,parentId:r.nodeId,ignored:!1,backendDOMNodeId:Xe.backendNodeId,frameId:ae,childIds:[z.nodeId]};z.parentId=we,j.set(parseInt(we),Dt),r.childIds=[we]}}}for(let z of r.childIds??[]){if(!z)continue;let re=j.get(parseInt(z));if(!re)continue;let le=await bw({node:re,parent:w,domGraph:i,axGraph:o,frameId:ae,frameContext:D,inputNodeMap:a,cdpClient:g,logger:h,callId:f,filterByViewport:s,showZeroOpacityElements:c,importantProperties:p,viewportDetails:u,useMPaths:d,flagNotActionableNodes:l});le.length&&(w.children=w.children.concat(le))}if(w.role==="StaticText"&&(w.children=[]),w.children.length===1&&w.children[0].role==="StaticText"){let z=w.name,re=w.children[0]?.name;(z===re||!re)&&(w.children=[])}let st=[];for(let z=w.children.length-1;z>=0;z--){let re=w.children[z];if(re.role!=="StaticText"){st.push(re);continue}if(z===0||w.children[z-1].role!=="StaticText"){st.push(re);continue}w.children[z-1].name+=re.name}if(w.children=st.reverse(),!w.isInteresting(p)&&r.parentId)return A&&(A.momenticIgnored=!0),w.children;for(let z of w.children)z.parent=w;return $U(w),A&&d&&Um(A,i),[w]}function Ew({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:Hm.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=km(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=Ew({node:p,a11yIdNodeMap:e,dataMomenticIdMap:t,logger:n,callId:o,startId:s,useMPaths:a,domGraph:i,selectorToNodeMap:l,iconKnowledgeBase:c});return s}async function Tw({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,allowedA11yIgnoreReasonsOverride:m}){let g=t??"root",h=r[g]?.root;if(!h)throw new Error("A11y tree has no root");let f=PU(),E=w=>{let D=w.allNodes.filter(ae=>!ae.ignoredReasons?.find(pe=>(m??fw).includes(pe.name))),j=new Map;return D.forEach(ae=>{j.set(parseInt(ae.nodeId),ae)}),j},b={};Object.entries(r).forEach(([w,D])=>{b[w]=E(D)});let C=await bw({node:h,domGraph:e,parent:null,inputNodeMap:b,axGraph:r,frameId:g,frameContext:d,cdpClient:o,logger:n,callId:f,showZeroOpacityElements:a,importantProperties:c,filterByViewport:i,viewportDetails:s,useMPaths:u,flagNotActionableNodes:l,allowedA11yIgnoreReasonsOverride:m});if(C.length>1)throw new Error(`Something went horribly wrong processing the a11y tree, we got: ${JSON.stringify(C)}`);if(C.length===0)throw new Error("There are no accessible elements on this page or frame. Are you sure this website loads properly?");let A={},v={},M={};return Ew({node:C[0],a11yIdNodeMap:A,dataMomenticIdMap:v,selectorToNodeMap:M,domGraph:e,logger:n,callId:f,useMPaths:u,iconKnowledgeBase:p}),new zm(C[0],A,v,M)}function jU(r,e,t,n){if(r==="class"){if(t.tagName?.toLowerCase()==="svg")return e.split(" ").filter(a=>a.length<yw&&!sr.bannedClassSubstrings.some(l=>a.includes(l))).slice(0,3).join(" ");let o=e.split(" "),i=[];for(let a of o)if(vw(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 WU(r,e,t){if(!e)return;Object.entries(e.attributes).forEach(([a,l])=>{let c=r[a]||a.startsWith("aria")||LU.includes(a);if((sr.relevantElementAttributes.includes(a)||Aw(a,t))&&!c){let u=jU(a,l,e,t);u!==null&&(r[a]=u)}});let n,o=[];if(e.computedStyles.position&&mw.includes(e.computedStyles.position))n=e.computedStyles.position;else if(e.attributes.style){for(let a of mw)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 $U(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(Ot(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=>Ot(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 qU(r){let e=r.properties.class,t=typeof e=="string"&&e.includes("cm-content");r.internalProperties.inCodeMirrorEditor=r.internalProperties?.inCodeMirrorEditor||t}function vw(r,e){if(e&&ww(r,e))return!0;if(sr.bannedClassSubstrings.some(t=>r.includes(t)))return!1;if(sr.alwaysInterestingClassNames.includes(r))return!0;for(let t of sr.alwaysInterestingClassPrefixes)if(r.startsWith(t))return!0;return!1}function Aw(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 ww(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 Mc=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 F(i.newCDPSession(a),{milliseconds:o*u,fallback:()=>{throw new x("UserInfrastructureError",`Failed to initialize Chrome session within the page load timeout (${a.url()})`)}});break}catch(d){await X(it),c=d}if(!l)throw c;let s=new r(l,e,t,n,o);try{await F(s.registerHandlers(l),{milliseconds:o,message:`CDP handler registration timed out after ${o}ms`})}catch(u){throw s.cdpFullyDead=!0,new x("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 Promise.all([e.send("Accessibility.enable"),e.send("Page.enable"),e.send("DOM.enable"),e.send("Overlay.enable"),e.send("DOMSnapshot.enable"),e.send("CSS.enable")])}async send({method:e,params:t,timeout:n=this.defaultTimeoutMs,timeoutMsg:o}){for(;this.cdpInitializingPromise;)await F(this.cdpInitializingPromise,{milliseconds:n});if(this.cdpCrashDetails){if(this.cdpFullyDead)throw new x("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 F(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 F(this.contextGetter().newCDPSession(n),{milliseconds:t,fallback:()=>{throw this.logger.error(`Failed to initialize CDP session within the page load timeout (${n.url()})`),new x("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 F(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 F(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 ui="<empty>";function KU(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 Cw(r){let e=r.adFrameStatus?.adFrameType;return e==="child"||e==="root"||KU(r.url)}async function YU(r,e){let t=await r.send({timeout:J,method:"DOM.getFrameOwner",params:{frameId:e}}),o=(await r.send({timeout:J,method:"DOM.pushNodesByBackendIdsToFrontend",params:{backendNodeIds:[t.backendNodeId]}})).nodeIds[0],a=(await r.send({timeout:J,method:"DOM.describeNode",params:{backendNodeId:t.backendNodeId}})).node;return a.nodeId=o,a}async function di({cdpClient:r,page:e,logger:t}){let n={type:"root",childFrames:[],page:e},o=[],[i,a]=await Promise.all([r.send({timeout:si,method:"Page.getFrameTree",params:{}}),r.send({timeout:si,method:"DOM.getDocument",params:{depth:0}})]),s=(i.frameTree.childFrames??[]).map(async(d,p)=>{if(Cw(d.frame))return null;try{return await xw({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 xw({cdpClient:r,rawFrameTree:e,indices:t,parent:n,warnings:o,logger:i}){let a=e.frame.id,l=await YU(r,a),c=l.attributes??[],s=null,u=[];for(let g of["src","name","id","title","srcdoc","sandbox"]){let h=wn(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(Cw(g.frame))return null;try{return await xw({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 XU(r){try{return await r.owner().count()===1}catch{return!1}}async function JU(r){try{return await r.count()===1}catch{return!1}}async function Dr(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,ui]){let p=o.frameLocator(d===ui?"iframe":`iframe[${d}]`);if(await XU(p)){u=!0,o=p,i.push(d);break}}if(!u)throw new x("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,ui]){let u=o.locator(s===ui?"iframe":`iframe[${s}]`);if(await JU(u)){a=u,i.push(s);break}}if(!a)throw new x("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:Z}),c=await l.asElement().contentFrame();if(!c)throw new x("InternalWebAgentError",`Failed to load Playwright Frame for iframe with url '${r.url}'`);return await l.dispose(),{frame:c,mPathSelectorTokens:i}}function Rw(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 Mw({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===ui?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===ui?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 Dr(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=Rw(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 Dr(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=Rw(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 Dr(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 Dr(n,r)).frame,handle:n,mPathSelectorTokens:t.mPathSelectorTokens,frameTree:e},logs:i};throw i.push(`Found ${a.length} frames with indices ${t.indices}`),new rn("Failed to find the iframe that previously contained this element",[{type:"AUTO_FRAME",matched:!1,logs:i}])}function _c(r){return r.type==="auto"?JSON.stringify({type:"auto",frameId:r.handle.frameId}):JSON.stringify(r)}function Gm(r){for(;r.parent.type==="frame";)r=r.parent;return r.parent}function _w(r){let e=Gm(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 Pw(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 Iw({frame:r,logger:e,signal:t}){let n;try{n=await r.frameElement(),await ZU({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 ZU({frameElementHandle:r,logger:e,signal:t}){let n=await r.boundingBox();await Ga({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:ge,codePath:"scrollIframeIntoView",signal:t}),e.info({oldBb:n,newBb:await r.boundingBox()},"Successfully scrolled iframe into view")}async function Ow({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 F(g?.boundingBox(),{milliseconds:J})??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 kr}from"crypto";import QU from"js-beautify";var eF=["Dead"],Pc=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:kr(),type:"PRESET_ACTION",command:Hr(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=Hr(i);a={id:kr(),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=Hr(i);a={id:kr(),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=Hr(i);a={id:kr(),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:me(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=QU.html(d,{indent_size:1,indent_with_tabs:!1,preserve_newlines:!1}),d=EA(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,...me(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(eF.includes(t)||this.signal.aborted)return;let o="normal";t.length>1&&(o="special");let i;if(o==="normal"){let d=Hr("TYPE");i={id:kr(),type:"PRESET_ACTION",command:{...d,target:void 0,value:t,clearContent:!1}}}else{let d=Hr("PRESS");i={id:kr(),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:kr(),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:kr(),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=Hr(s);u.deltaY=Math.abs(i);let d={id:kr(),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=Hr(s);u.deltaX=Math.abs(i);let d={id:kr(),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 Vm}from"zod";var Sbe=Vm.object({type:Vm.literal("url"),url:Vm.string()});var Ic=class{smartWaitingTimeoutMs;pageLoadTimeoutMs;allowPartialAccessibilityTree;logger;cdpClient;pageGetter;abortSignalGetter;userControlledBrowserSettings;enricher;iconKnowledgeBase;computedStylesToFetch=["display","opacity","visibility","height","position"];activeFrameCache;activeFrameConfig;lastA11yIdToNodeMap={};lastDataMomenticIdToNodeMap={};lastSelectorToNodeMap={};lastA11yTreeRoot;lastDomGraph;allowedA11yIgnoreReasonsOverride;constructor({smartWaitingTimeoutMs:e,pageLoadTimeoutMs:t,allowPartialAccessibilityTree:n,logger:o,cdpClient:i,pageGetter:a,abortSignalGetter:l,enricher:c,iconKnowledgeBase:s,userBrowserSettings:u,allowedA11yIgnoreReasonsOverride:d}){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.userControlledBrowserSettings=u,this.allowedA11yIgnoreReasonsOverride=d,this.userControlledBrowserSettings.importantStyles)for(let p of this.userControlledBrowserSettings.importantStyles){let m=p.split(":");if(m.length!==2){this.logger.warn({style:p},"Invalid style property passed to importantStyles");continue}let g=m[0]?.trim(),h=m[1]?.trim();if(g===void 0||h===void 0){this.logger.warn({style:p},"Invalid style property passed to importantStyles");continue}this.computedStylesToFetch.includes(g)||this.computedStylesToFetch.push(g)}}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.userControlledBrowserSettings.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=Gm(e),{frame:o,mPathSelectorTokens:i}=await Dr(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 di({cdpClient:this.cdpClient,page:t,logger:this.logger}),{resolution:o,logs:i}=await Mw({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(_c(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:_c(this.frameConfig),cacheTime:Date.now(),frameTree:this.frameConfig.frameTree,mPathSelectorTokens:this.frameConfig.mPathSelectorTokens},await Iw({frame:n.frame,logger:e,signal:t}),this.activeFrameCache=n,n}async executeFunctionInAllFrames(e,t){let n=this.pageGetter(),o=await di({cdpClient:this.cdpClient,page:n,logger:this.logger}),i=[F(n.evaluate(e,t),{milliseconds:ge})],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(Dr(c,n).then(({frame:u})=>F(u.evaluate(e,t),{milliseconds:ge})).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 di({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 lr({fn:()=>this.resolveActiveFrameConfig({logger:n,signal:o}),codePath:"getActiveFrameDetails",logObject:t,signal:o,logger:n})??void 0,!a)throw new x("ActionFailureError","Got null frame details despite active frame config");l=a.handle,c=l.frameId}else this.userControlledBrowserSettings.autoExpandIframes?(l=await lr({fn:()=>di({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 lr({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 lr({fn:()=>this.getDOMTree({devicePixelRatio:e.devicePixelRatio??1,signal:o,logger:n}),codePath:"domFetch",logObject:t,signal:o,logger:n}),u=await lr({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 lr({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:pn,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.userControlledBrowserSettings.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=uw({node:o,domGraph:this.domGraph});return dw(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:ge});if(!n||!n.object.objectId)throw new Error(`Could not resolve backend node ${t}`);let o;try{o=await pw(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(fr(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 di({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 x&&s.reason==="UserInfrastructureError")throw s;c%3===0&&this.logger.warn({attempt:c,err:s},"Failed to resolve active frame, retrying..."),await X(it,t)}finally{c++}if(a)return{source:"url",frame:a.frame,handle:a.handle,frameIdentifierStringified:_c(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=wn(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 Dr(l,o)});break}}else if(n.trim()===d.trim()){a.push({handle:l,matchType:"url",...await Dr(l,o)});break}}}if(a.length===1){let l=a[0];return this.userControlledBrowserSettings.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 x("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 Tw({rawA11yGraph:t,startingFrameId:o,frameContext:i,domGraph:n,logger:a,cdpClient:this.cdpClient,showZeroOpacityElements:c,flagNotActionableNodes:s,filterByViewport:e.filterByViewport,importantProperties:{attributes:this.userControlledBrowserSettings.importantAttributes,classes:this.userControlledBrowserSettings.importantClasses,styles:this.userControlledBrowserSettings.importantStyles},viewportDetails:void 0,iconKnowledgeBase:l,useMPaths:this.userControlledBrowserSettings.visualActions,allowedA11yIgnoreReasonsOverride:this.allowedA11yIgnoreReasonsOverride});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.userControlledBrowserSettings.visualActions)return;let i=await this.addMomenticIdsHelper(n??e,1);if(!this.userControlledBrowserSettings.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 Dr(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.userControlledBrowserSettings.visualActions)return t;let n=this.logger;return await et({root:e,fn:i=>window.addIdsToElement?.(document.body,i),arg:t,timeout:ge,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(wn(t,"aria-hidden")==="true")return{shouldUnroll:!1,reason:"aria-hidden"};let n=wn(t,"style");if(n?.includes("display: none")||n?.includes("visibility: hidden"))return{shouldUnroll:!1,reason:"hidden CSS style"};await this.cdpClient.send({timeout:J,method:"DOM.pushNodesByBackendIdsToFrontend",params:{backendNodeIds:[e.backendNodeId]}});let[o,i]=await Promise.all([this.cdpClient.send({timeout:J,method:"DOM.getBoxModel",params:{backendNodeId:e.backendNodeId}}),this.cdpClient.send({timeout:J,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 lr({fn:()=>this.getRawA11yTreeForFrame({frameId:t,timeoutMs:this.pageLoadTimeoutMs,logTimings:o}),codePath:"a11y-tree-fetch-root",logObject:o,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.userControlledBrowserSettings.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 lr({fn:()=>this.getRawA11yTreeForFrame({frameId:m.frameId,timeoutMs:this.smartWaitingTimeoutMs,logTimings:o}),codePath:`a11y-tree-fetch-child-${m.frameId}`,logObject:o,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 lr({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,logger:this.logger})).nodes;else{let a=(await lr({fn:()=>this.cdpClient.send({method:"Accessibility.getRootAXNode",params:{frameId:e??void 0},timeout:ge}),codePath:"cdp-get-root-ax-node",logObject:n,logger:this.logger})).node.backendDOMNodeId;o=(await lr({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,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:J}),!o||!o.documents.length)throw new Error("Got empty DOM tree")}catch(l){await X(it,t),i++,a=l}if(!o||!o.documents.length)throw n.error({err:a},"Fatal error fetching DOM tree"),new x("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 cw({snapshot:o,devicePixelRatio:e,computedStylesToFetch:this.computedStylesToFetch,logger:n})}constructIframeRegexAsync(e,t){if(t.frameSrcRegex||t.frameUrlRegex)return;let n=_w(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 jm(r){let e=[],t="";for(let n of r)n==="+"&&t?(e.push(t),t=""):t+=n;return e.push(t),e}var qa=class r{static USER_AGENT=vc;abortSignal=void 0;contextInitialized=!1;browser;context;properties;page;userControlledBrowserSettings;pageLoadPromises={};lastTabChangeEventTimeout=void 0;clientCallbacks;iconKnowledgeBase;cdpClient;debugData={logsPerPage:[],harPages:{},harEntries:{}};recentFrameNavigations={};requestRecorders={};mocks={};customHeaders=[];enricher;storage;logger;stateManager;transformer;lastScreenshotForRecording=void 0;originsVisited=new Set;viewport;onVideoPageChange;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,onVideoPageChange:m}){Vy(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,this.iconKnowledgeBase=p,this.onVideoPageChange=m}registerAbortSignal(e){this.abortSignal=e}async initialize({grantPermissions:e,runInitScripts:t,timingRecorder:n}){if(this.contextInitialized)return;let o={[Tc]:this.userBrowserSettings.visualActions},i=[];if(this.userControlledBrowserSettings.extraHeaders&&i.push(this.context.setExtraHTTPHeaders(this.userControlledBrowserSettings.extraHeaders)),e){let u=["clipboard-read","clipboard-write","microphone","camera","geolocation"];Rr||u.push("local-network-access"),i.push(this.context.grantPermissions(u))}i.push(this.context.addInitScript({content:lm.htmlUtilsLibJs}),this.context.addInitScript({content:`window._MOMENTIC_BROWSER = true; window._MOMENTIC_FEATURE_FLAGS = ${JSON.stringify(o)}; window.addEventListener('load', (event) => { console.log('[MOMENTIC] Page loaded'); });`}),this.exposeRecordingBindings());let a=u=>this.handleNewPageEvent(u);this.context.on("page",a),this.handleNewPageEventHelper(this.page),this.context.on("close",()=>{this.context.off("page",a)});let l=!1;if(t){let u=async()=>{let d=Date.now();try{await Promise.all([this.page.addScriptTag({content:lm.htmlUtilsLibJs}),this.page.addScriptTag({content:`window._MOMENTIC_BROWSER = true; window._MOMENTIC_FEATURE_FLAGS = ${JSON.stringify(o)}; window.addEventListener('load', (event) => { console.log('[MOMENTIC] Page loaded'); });`})])}catch(p){if(p instanceof Error&&p.message.includes("Content Security Policy"))this.logger.warn({err:p},"Content Security Policy error from adding Momentic scripts, reloading page instead"),l=!0;else throw p}(n??{})["add-init-scripts"]=Date.now()-d};i.push(u())}if(!this.properties.systemDevicePixelRatio)if(process.env.MOMENTIC_LOCAL_DEV==="1"&&sF()==="darwin"&&tF("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;else{let u=async()=>{let d=Date.now();this.properties.systemDevicePixelRatio=await this.page.evaluate(()=>window.devicePixelRatio),(n??{})["fetch-dpr"]=Date.now()-d};i.push(u())}let c=Date.now();await F(Promise.all(i),{milliseconds:this.pageLoadTimeout,message:"Timed out attaching Chrome permissions and initialization scripts",signal:this.abortSignal});let s=Date.now();(n??{})["ops-attach"]=s-c,l&&await this.page.reload(),this.cdpClient=await Mc.init({logger:this.logger,contextGetter:()=>this.context,pageGetter:()=>this.page,defaultTimeoutMs:this.pageLoadTimeout}),(n??{})["cdp-init"]=Date.now()-s,await this.initializeScreencast(),this.stateManager=new Ic({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,allowedA11yIgnoreReasonsOverride:this.properties.allowedA11yIgnoreReasonsOverride}),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(e){let t=await JA(e),n=new r(t);return await n.initialize({grantPermissions:!0,runInitScripts:!1}),n}static async fromExistingContext({context:e,storage:t,enricher:n,userBrowserSettings:o,properties:i,logger:a,timingRecorder:l}){let c=e.pages()[0];if(!c)throw new Error("No page found in existing context");let s=c.viewportSize();if(!s){let p=Date.now();s=await c.evaluate(()=>({width:window.innerWidth,height:window.innerHeight})),l["eval-viewport"]=Date.now()-p}let u=c?.url(),d=new r({browser:e.browser(),context:e,page:c,baseUrl:u,logger:a,storage:t,enricher:n,userBrowserSettings:o,viewport:s,properties:i,clientCallbacks:void 0,iconKnowledgeBase:null});return await d.initialize({grantPermissions:!1,runInitScripts:!0,timingRecorder:l}),d}async handleAvailableTabsChangeHelper(){try{let e=await Dm(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=Wm(),o=`${e}-${n}`,i=Date.now(),a=!1,l=async()=>{try{await F(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()||!no(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();this.logger.info({url:t},"Detected new page event, registering handlers and waiting for load to complete");try{this.handleNewPageEventHelper(e)}catch(n){this.logger.warn({err:n},"Error handling new page open, continuing....")}}handleNewPageEventHelper(e){let t=Wm(),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);this.userBrowserSettings.disableBrowserMonitoring||e.on("console",a=>{LA(e,o,this.debugData,a,this.logger)});let i=async()=>{this.userBrowserSettings.disableBrowserMonitoring||(await UA(t,this.debugData,e),await e.route("**/*",async(a,l)=>{await Rm({pageId:t,route:a,request:l,debugData:this.debugData,logger:this.logger,requestRecorders:this.requestRecorders,mocks:this.mocks})}),await e.route("**/*",VA(this.customHeaders,this.logger))),Rr&&await e.route("**/*",Wa),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"||!no(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}),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){this.abortSignal=void 0,this.debugData.logsPerPage=[],this.debugData.harPages={},this.debugData.harEntries={},this.pageLoadPromises={},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 F(Om(this.getBrowserCallbacks()),{milliseconds:Z})}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<si;){a++,n?.throwIfAborted();try{if(await et({fn:()=>{let c=window;return!!(c.generateCssSelectors&&c.evaluateCssSelectors&&c.evaluatePrimaryCaches&&c.generateHtmlCacheAttributes&&c.ldist)},timeout:Z,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 X(it),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),et({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:J,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 X(li),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??ge}),c=Buffer.from(l.data,"base64"),s=await Nw.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&&oF(n,c),this.lastScreenshotForRecording=c,!e)return c;let p=await e.boundingBox({timeout:J});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 Nw.fromBuffer(c),b=E.bitmap.width,C=E.bitmap.height;m=Math.max(0,Math.min(m,b-1)),g=Math.max(0,Math.min(g,C-1)),h=Math.max(1,Math.min(h,b-m)),f=Math.max(1,Math.min(f,C-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(){if(this.viewport)return this.viewport;let e=this.page.viewportSize();return e||null}async navigate({url:e,initialNavigation:t=!1,loadTimeoutMs:n=this.pageLoadTimeout}){fA(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 X(it),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:Z})}if(!i)throw new x("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(CA.has(l))throw new x("UserInfrastructureError",`${e} took too long to load \u{1F61E}. Please ensure the site is accessible and returns content within the page load timeout.`);await this.fixViewportForNewHeadless()}async type(e,t={},n=!1){await this.directTypeHelper(e,t,n)}async getActiveElement(e){try{return await et({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:Z,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 tw({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 X(li),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"?(this.properties.isAndroid?await this.page.keyboard.press("Control+A"):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??hh}),t.pressEnter&&await this.press("Enter",{})}async scrollIntoViewIfNeeded(e){try{await e.scrollIntoViewIfNeeded({timeout:ge})}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:ge})}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 Cc({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:Z}),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 OA(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:Z});let n=0;for(let i of e.origins??[])for(let a of i.localStorage)try{await this.cdpClient.send({timeout:Z,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 IA(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 PA(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 x("ActionFailureError",`Failed to save auth state: ${n?.message}`)}async getOpenPages(e){return Dm(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,startingBoundingBox:o,allowNotActionableNodesOverride:i,logger:a=this.logger}){if(e&&this.saveA11yDetailsToCache(e,t),t.frameCache=this.stateManager.saveAutoFrameCacheDetails(t.frameCache),n)try{let l=await this.fetchHtmlAttributes({locator:n,logger:a,startingBoundingBox:o,allowNotActionableNodesOverride:i});l?(t.generatedSelectors=l.generatedSelectors,t.serializedHtml=l.serializedHtml,t.nodeOnlySerializedHtml=l.nodeOnlySerializedHtml,t.hybridSelector=l.hybridSelector):a.warn("Got undefined HTML attributes when trying to update cache")}catch(l){if(l instanceof vr)throw a.warn({err:l},"Cache attributes disqualify found element"),l;a.warn({err:l},"Failed to fetch HTML attributes for target, continuing...")}try{await this.saveElementVisualAttributes({target:t,locator:n,logger:a,boundingBox:o})}catch(l){a.debug({err:l},"Failed to save element visual details, continuing...")}}async saveElementVisualAttributes({target:e,locator:t,logger:n,boundingBox:o}){if(!t)return{scrollPerformed:!1};if(!pm.includes(e?.role??""))return{scrollPerformed:!1};if(await this.scrollIntoViewIfNeeded(t),o||(o=await t.boundingBox({timeout:J})),!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({logger:e,locator:t,requirements:n}){let o={},i=!!n?.position&&n.position!=="irrelevant",a=!!n?.shape&&n.shape!=="irrelevant";if(i||a){let l=await t.boundingBox({timeout:J});if(!l||!l.width||!l.height)throw new x("ActionFailureError","Element does not have a bounding box as required");a&&(o.shape={width:l.width,height:l.height,tolerance:n.shape}),i&&(o.position={x1:l.x,y1:l.y,x2:l.x+l.width,y2:l.y+l.height,tolerance:n.position})}if(n?.text){let l=await t.textContent({timeout:J});o.text=l?.trim()}if(n?.attributes&&n.attributes.length>0){let l={};for(let c of n.attributes){let s=c.trim().toLowerCase();if(!(!s||sr.bannedAiRequiredCacheAttributes.includes(s)))try{let u=await t.getAttribute(s,{timeout:J});u!==null&&(l[c]=u)}catch(u){e.warn({err:u,attr:c},"Failed to fetch required attribute, continuing...")}}o.attributes=l}return o}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({logger:o,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}){if(t)try{o.requirements=await this.getElementRequiredValues({logger:l,locator:i,requirements:t})}catch(c){l.warn({err:c},"Failed to generate required values for target")}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 x("InternalWebAgentError","Only positive IDs should be passed to resolveAllyIdToTarget");let c=this.stateManager.a11yIdToNodeMap[e];if(!c)throw new x("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:C,config:A}=await this.stateManager.getAutoFrameDetailsFromHandle(b);d=C,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:me(i),frameCache:d},f,E=!1;o||(p&&(i.info({frameConfigSource:m,frameConfig:Pw(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,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 X(it,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,shouldLogOnFailure:m,logger:i,allowNotActionableNodesOverride:l,signal:a});break}catch(g){if(g instanceof $i)break;if(g instanceof vr){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 X(it,a)}a?.throwIfAborted(),m&&i.warn({err:g},`Could not resolve target using primary cache only (x${u})`),await X(it,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=me(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,shouldLogOnFailure:l}){let c=pi(t),s=[],u=(await this.getBrowserState({logger:o,abortSignal:i,skipWait:!0,allowNotActionableNodesOverride:a})).serialize(),d;if(t.generatedSelectors||t.hybridSelector){let p;try{p=await this.resolveTargetWithPrimaryMethods({root:e,target:t,logger:o,allowNotActionableNodesOverride:a,shouldLogOnFailure:l})}catch(m){d=m,m instanceof rn&&s.push(...m.decisions)}if(p)return{...p,pageState:void 0,decisions:[...s,...p.decisions]};n||(s.push({type:"CSS_SELECTOR",matched:!1,reason:d?.message,selectors:pi(t.generatedSelectors??[])}),t.generatedSelectors=void 0,t.hybridSelector=void 0)}if(n)throw d;if(!this.userBrowserSettings.disableSecondaryCacheResolution){let p=await this.resolveTargetWithSecondaryMethods({root:e,tree:u,target:t,decisions:s,logger:o,signal:i,allowNotActionableNodesOverride:a});if(p)return p}throw new rn(`Could not find any relevant node given target: ${JSON.stringify(c)}`,s)}async resolveTargetWithPrimaryMethods({root:e,target:t,logger:n,allowNotActionableNodesOverride:o,shouldLogOnFailure:i}){if(!t.nodeOnlySerializedHtml)throw new $i("Insufficient data to resolve target using primary methods (missing node HTML)");let a=i?n:pn,l=this.userControlledBrowserSettings.hybridSelectorMode,c={ldistThreshold:dm,requireBoundingBox:!o,ignoreHrefForCaching:this.userControlledBrowserSettings.ignoreHrefForCaching,requireMatchingBoundingBox:this.userControlledBrowserSettings.bustCacheOnBoundingBoxChange?t.boundingBox:void 0,requirements:t.requirements,additionalElements:t.additionalElements,importantProperties:{attributes:this.userControlledBrowserSettings.importantAttributes,classes:this.userControlledBrowserSettings.importantClasses,styles:this.userControlledBrowserSettings.importantStyles}},{css:s,hybrid:u}=await et({fn:C=>window.evaluatePrimaryCaches(C),arg:{cssParams:{selectors:t.generatedSelectors??[],cachedElementSerialized:t.nodeOnlySerializedHtml,opts:c},hybridParams:l&&t.hybridSelector?{nodes:t.hybridSelector,cachedElementSerialized:t.nodeOnlySerializedHtml,opts:c}:void 0},root:e,timeout:J,waitForPageLoad:()=>this.waitForPageLoad(),codePath:"evaluating target caches"}),d,p,m=[];if(l==="prefer"&&u?.result){d=u.result;let C={type:"HYBRID_SELECTOR",matched:!0,logs:u.logs,reason:"Discovered a match using Momentic's hybrid text and CSS selector approach"};m.push(C),p="HYBRID_SELECTOR"}else if(s?.result){d=s.result;let C=`${d.workingSelectors.length} CSS selectors matched the following element: ${d.serializedElement}`,A=d.workingSelectors.slice(0,5);m.push({type:"CSS_SELECTOR",matched:!0,logs:s.logs,reason:C,selectors:A}),n.debug({reason:C,workingSelectors:A},"Resolved with CSS selectors"),p="CSS_SELECTOR"}else throw m.push({type:"CSS_SELECTOR",matched:!1,reason:s.logs.length===1?"CSS evaluation failed":"No CSS selectors matched",selectors:[],logs:s.logs}),u&&m.push({type:"HYBRID_SELECTOR",matched:!1,reason:u.logs.length===1?"Hybrid evaluation failed":"No hybrid selectors matched",logs:u.logs}),s?.error&&n.error({err:new Error(s.error)},"Cache evaluation errored unexpectedly (CSS)"),u?.error&&n.error({err:new Error(u.error)},"Cache evaluation errored unexpectedly (Hybrid)"),new rn("Cache evaluation failed",m);let g,h,f;if(this.userBrowserSettings.visualActions){let C=d.mPath;if(!C)throw new Error("Found element did not have an mPath despite using visual actions");let A=C.join(" > ");g=e.locator(A),h=this.stateManager.getNodeUsingMPathSelector(A)}else if(d.dataMomenticId!==void 0)f=parseInt(d.dataMomenticId),h=this.stateManager.dataMomenticIdToNodeMap[f],"workingSelectors"in d?g=e.locator(d.workingSelectors[0]):g=e.locator(fr(f));else throw new x("InternalWebAgentError","Received an element resolution result with no identifying attributes");l&&t.hybridSelector&&(u?.logs.length===1?a.warn({hybridResult:u,cssResult:s,hybridMode:l},"Hybrid selector resolution rejected, continuing..."):u?.result?s?.result&&u?.result&&u.result.serializedElement!==s.result.serializedElement&&(this.userBrowserSettings.visualActions&&JSON.stringify(s.result.mPath)!==JSON.stringify(u.result.mPath)?n.warn({originalCache:t,hybridResult:u,cssResult:s,hybridMode:l,mode:"visualActions"},"Hybrid selector resolution returned a different element than CSS selector resolution, continuing..."):s.result.dataMomenticId!==u.result.dataMomenticId&&n.warn({originalCache:t,hybridResult:u,cssResult:s,hybridMode:l,mode:"dataMomenticId"},"Hybrid selector resolution returned a different element than CSS selector resolution, continuing...")):a.warn({originalCache:t,hybridResult:u,cssResult:s,hybridMode:l},"Hybrid selector resolution returned no eligible elements while CSS resolution did, continuing..."));let E=pi(t);await this.updateCacheWithNewNodeDetails({node:h,target:t,locator:g,logger:n,startingBoundingBox:d.boundingBox,allowNotActionableNodesOverride:o});let b=$m(E,t);return b&&Object.keys(b).length>0&&(t.cacheResolutionUpdateTime=new Date().toISOString(),t.cacheResolutionUpdateLoggerTags=me(n),t.cacheResolutionUpdateSource=p),{a11yNode:h,displayString:d.serializedElement,locator:g,decisions:m}}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:Z}),m=await qr(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 x("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 X(it,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:J});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<wA){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 et({fn:d=>window.findClosestElementByLDist?.(d),arg:{nodeOnlySerializedHtml:t.nodeOnlySerializedHtml},timeout:ge,root:e,waitForPageLoad:()=>this.waitForPageLoad(),codePath:"finding the closest element on the page"}),u=Math.floor(dm*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(fr(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 qr(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=pi(t);await this.updateCacheWithNewNodeDetails({node:p,target:t,locator:m,logger:o,startingBoundingBox:s.boundingBox,allowNotActionableNodesOverride:a});let f=$m(h,t);return f&&Object.keys(f).length>0&&(t.cacheResolutionUpdateTime=new Date().toISOString(),t.cacheResolutionUpdateLoggerTags=me(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&&pm.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({screenshotUrl:e,oldTarget:t,signal:n,allowNotActionableNodesOverride:o}){let i;if(!this.enricher)throw new Error("Enricher not available for screenshot resolution");let a=await this.screenshot({retries:0}),c=await(await fetch(e)).arrayBuffer(),s=uF(),u=await this.enricher.runTemplateMatching({id:s,searchImageBase64String:Buffer.from(c).toString("base64"),pageImageBase64String:a.toString("base64")},{signal:n}),{target:d,locator:p}=await this.getTargetFromPositionPercentages({percentX:u.x,percentY:u.y,allowNotActionableNodesOverride:o}),m=d.boundingBox?.width,g=d.boundingBox?.height;if(!m||!g)throw i="Rejecting target from screenshot due to no bounding box",new Error(i);let h=d.id,f=this.stateManager.a11yIdToNodeMap[h],E=pi(t);await this.updateCacheWithNewNodeDetails({target:t,node:f,locator:p,allowNotActionableNodesOverride:o});let b=$m(E,t);return b&&Object.keys(b).length>0&&(t.cacheResolutionUpdateTime=new Date().toISOString(),t.cacheResolutionUpdateLoggerTags=me(this.logger),t.cacheResolutionUpdateSource="TEMPLATE_MATCHING",this.logger.info({id:s,diffs:b,templateMatch:u},"Updated cache after template matching resolution")),{locator:p,a11yNode:f,displayString:d.nodeOnlySerializedHtml??"",decisions:[{type:"TEMPLATE_MATCHING",matched:!0,reason:"Found element using screenshot",elementImageUrl:e}]}}async typeIntoTarget(e,t,n={}){await this.highlight(t.locator);let o=await t.locator.getAttribute("type",{timeout:Z})??"",i=ew.some(a=>a===o.toLowerCase());return await Lm({targetingResult:t,options:{force:n.force,relativePosition:n.relativePosition},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 Lm({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(),yc(l,t,n)){a=!0;break}await X(it,this.abortSignal)}if(!a)throw new x("ActionFailureError",`The active page URL ${n?.negated?"still does":"does not"} ${Nv(t)} in ${o}ms.
4116
- 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:J});if(!o)throw new x("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 X(n.hoverSeconds?Math.min(n.hoverSeconds*1e3,ge):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(wm);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 X(li),await this.page.mouse.up()}async hover(e){await this.highlight(e.locator),await io({func:async t=>{await this.scrollIntoViewIfNeeded(t.locator);let n=await t.locator.boundingBox({timeout:J});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 io({func:t=>t.locator.focus({timeout:ge}),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 et({fn:()=>{let n=document.activeElement;n&&n.nodeType===1&&n.blur()},root:t,arg:void 0,waitForPageLoad:()=>this.waitForPageLoad(),timeout:Z,codePath:"blurring the active element"});return}await this.highlight(e.locator),await io({func:t=>t.locator.blur({timeout:ge}),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 io({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 x("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:J})},targetingResult:e})}async press(e,t){let n=t.repeat??1;if(t.convertMeta){let o=xc(e,this.properties.isAndroid);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=xc(e,this.properties.isAndroid);n!==e&&(this.logger.info({keyString:e,convertedKey:n},"Converted platform dependent keys"),e=n)}for(let n of jm(e))await this.page.keyboard.down(n)}async keyUp(e,t){if(t.convertMeta){let n=xc(e,this.properties.isAndroid);n!==e&&(this.logger.info({keyString:e,convertedKey:n},"Converted platform dependent keys"),e=n)}for(let n of jm(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,shouldLogOnFailure:a}=e,l=e.abortSignal??this.abortSignal,c=!i,s=i?!0:this.userControlledBrowserSettings.showZeroOpacityElements,u=a?n:pn;o||await this.waitForPageLoad(),e.skipWait||await this.waitForDOMStability({logger:n,signal:l});let d=0,p;for(;d<t;){d++;try{return await F(this.stateManager.getA11yTree({devicePixelRatio:this.devicePixelRatio,abortSignal:l,logger:n,filterByViewport:e.filterByViewport,showZeroOpacityElements:s,flagNotActionableNodes:c}),{milliseconds:this.pageLoadTimeout*d,signal:l,message:"Getting browser state took too long"})}catch(m){if(l?.throwIfAborted(),p=m instanceof Error?m.message:`${m}`,d>=t)throw m;u.warn({err:m,url:this.url()},"Error getting a11y tree, retrying...")}}throw new x("ActionFailureError",`Getting page content failed after ${t} attempts. Error: ${p}`)}async getViewportOffsetDetails(e){let[t,n,o,i,a]=await et({root:e,fn:()=>[window.scrollY,window.scrollX,window.screen.width,window.screen.height,window.devicePixelRatio],arg:void 0,timeout:J,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 X(li,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<AA)){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 X(n.hoverSeconds?Math.min(n.hoverSeconds*1e3,um):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(wm);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 X(li),await this.page.mouse.up()}async getElementLocation(e){let t=await this.cdpClient.send({method:"DOMSnapshot.captureSnapshot",params:{computedStyles:[],includeDOMRects:!0,includePaintOrder:!0},timeout:J}),n=await F(this.page.evaluate(()=>window.devicePixelRatio),{milliseconds:ge});process.platform==="darwin"&&n===1&&(n=TA);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 Nm({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 Nm({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){if(await this.stopScreencast(),this.recordUrlVisited(e.url()),this.onVideoPageChange){let n=await e.video()?.path();if(n){let o=Dw(n);this.onVideoPageChange({videoName:o})}}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 X(it)}}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 x("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)}.
4117
- Available pages:${JSON.stringify(n.map(i=>i.url))}`);if(!no(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=zs(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:J}),n=await fetch("https://api.2captcha.com/createTask",{method:"POST",body:JSON.stringify({clientKey:ci,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<RA;){await X(2500);let l=await fetch("https://api.2captcha.com/getTaskResult",{method:"POST",body:JSON.stringify({clientKey:ci,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(){try{await F(this.exposeRecordingBindingsHelper(),{milliseconds:this.pageLoadTimeout})}catch(e){e instanceof Error&&e.message.includes("already registered")||this.logger.error({err:e},"Failed to install Momentic libraries for action recording")}}async exposeRecordingBindingsHelper(){await this.context.exposeBinding("isRecordingActive",()=>this.transformer!==void 0,{handle:!1}),await this.context.exposeBinding("captureTargetedEvent",({frame:e},t)=>{this.transformer&&Ow({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(c=>c.url),o=0,i=!1,a=async()=>{if(e.aborted||o>8){clearTimeout(t);return}i=!0;let c;try{c=(await this.getOpenPages()).map(u=>u.url),o=0}catch(u){this.logger.debug({err:u},"Failed getting new open pages during recording tab switch cron, skipping..."),o++;return}let s=this.url();for(let u=c.length-1;u>=n.length;u--){let d=c[u];no(d,this.logger)&&d!==s&&this.logger.info({lastActivePages:n,currentUrl:s,newOpenPages:c},"Auto-following new tab during recording"),await this.switchToPage({type:"INDEX",index:String(u)});break}n=c};t=setInterval(async()=>{if(!i){i=!0;try{await a()}catch(c){this.logger.error({err:c},"Error while checking pages during recording")}finally{i=!1}}},it);let l=async()=>{clearInterval(t)};e.addEventListener("abort",l,{once:!0})}async startRecording(e,t,n){this.logger.debug({isClickToRecord:n},"Starting recording mode in Chrome browser"),await this.startRecordingCrons(e),await this.page.evaluate(i=>{let a=window;a._MOMENTIC_RECORDING_ACTIVE=!0,a._MOMENTIC_CLICK_RECORD_ACTIVE=i},n),this.transformer=t,await this.injectKnowledgeBaseIntoBrowser(this.page);let o=async()=>{this.transformer=void 0,this.lastScreenshotForRecording=void 0;try{await this.page.evaluate(()=>{let i=window;i._MOMENTIC_RECORDING_ACTIVE=!1,i._MOMENTIC_CLICK_RECORD_ACTIVE=!1})}catch{}};e.addEventListener("abort",o,{once:!0})}async getSelectOptions(e){return await e.evaluate(n=>Array.from(n.querySelectorAll("option")).map(i=>({value:i.value,label:i.label})),void 0,{timeout:Z})}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 Ga({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 x("UserInfrastructureError",`The page with URL ${Ot(i,50)} did not load within the configured timeout (${o}ms): ${l}`);if(!l.message.includes("detached"))throw l}try{await Ga({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 iF.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 et({fn:()=>window.getCondensedHtmlTree(),root:e,arg:void 0,timeout:ge,waitForPageLoad:()=>this.waitForPageLoad(),codePath:"getting condensed HTML tree"});if(n)throw new Error(`Failed to process page HTML: ${n}`);if(!t)throw new x("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=ge){let i=await this.getActivePageOrFrame();return et({root:i,fn:e,arg:t,timeout:o,waitForPageLoad:()=>this.waitForPageLoad(),codePath:n})}async evaluateCodeInPage({code:e,fragment:t,context:n,timeoutMs:o=cn}){let i=GA(),a={code:e,fragment:t,context:n},{result:l}=await F(this.page.evaluate(i,a),{milliseconds:o,fallback:()=>{throw this.abortSignal?.throwIfAborted(),new x("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:ge});let n;try{n=await this.cdpClient.send({method:"DOM.getNodeForLocation",params:{x:e,y:t},timeout:Z})}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 x("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:Z,params:{highlightConfig:lw,backendNodeId:n.backendNodeId}}),async()=>{try{await this.cdpClient.send({timeout:Z,method:"Overlay.hideHighlight",params:{backendNodeId:n?.backendNodeId}})}catch{}}):async()=>{}}async clearAllCdpHighlights(){try{await this.cdpClient.send({method:"Overlay.hideHighlight",params:void 0,timeout:Z})}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(fr(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 F(this.performTargetRedirectionHelper(e,t,n),{milliseconds:J})??{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 qr(e,t);if(n===void 0&&(n=await e.boundingBox({timeout:J})??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,foundElementRelativePoint:f,force:E,logs:b}=await e.evaluate(A=>{let v=window;if(!v.performTargetRedirection)throw new Error("performTargetRedirection script is not defined");return v.performTargetRedirection(A)},void 0,{timeout:Z}),C=Date.now()-o;if(g){t.warn({error:g,serializedElement:h,duration:C,force:E,logs:b},"Got error from target redirection with bounding box");return}else{if(p)return t.info({newDataMomenticId:p,serializedElement:h,duration:C,force:E,logs:b},"Redirected target to new element with bounding box with data-momentic-id"),{locator:d.locator(fr(p)),hints:{relativeXYToLocator:f,force:E}};if(m)return t.info({newMPathSelector:m,serializedElement:h,duration:C,force:E,logs:b},"Redirected target to new element with bounding box with mPath"),{locator:d.locator(m),hints:{relativeXYToLocator:f,force:E}};if(f)return t.info({foundElementRelativePoint:f,serializedElement:h,duration:C,force:E,logs:b},"Chose specific visible point on original element"),{locator:e,hints:{relativeXYToLocator:f,force:E}};if(E)return t.info({serializedElement:h,duration:C,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:ge});if("error"in l&&l.error)throw l.error.startsWith(yA)?new Cs(l.error):l.error.startsWith(bA)?new xs(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:Z})}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!!ci}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,vm(e,this.debugData,i,{type:t,text:`[MOMENTIC] ${n}`,args:o})}async setFileChooserHandlerHelper({filePath:e,filename:t}){if(!Oc(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()||Dw(e),o=rF(e),i=lF(e),a=Pd[i];this.page.once("filechooser",async c=>{this.logger.info({filePath:e,fileName:n},"File chooser triggered");try{if(!Oc(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:aF.getType(e)||"application/octet-stream"},{timeout:um})}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??Wm();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??vA}get userBrowserSettings(){return pi(this.userControlledBrowserSettings)}get pageLoadTimeout(){return this.userControlledBrowserSettings.pageLoadTimeoutMs??si}get isInPageLoad(){return Object.values(this.pageLoadPromises).length>0}get devicePixelRatio(){return this.properties.systemDevicePixelRatio??1}get browserCrashDumpDir(){let e=Rc();for(let t of e)if(!(!Oc(t)||!Lw(t).isDirectory()||!["new","pending","completed"].some(o=>{let i=cF(t,o);return Oc(i)&&Lw(i).isDirectory()&&nF(i).length>0})))return t}};import DF from"fetch-cookie";import{cloneDeep as iR}from"lodash-es";import{CookieJar as kF}from"tough-cookie";async function Ur({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 dF=["NAVIGATE","NEW_TAB","TAB","REFRESH","WAIT_FOR_URL"];async function Uw({beforeUrl:r,beforePages:e,browser:t,command:n,logger:o}){if(dF.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 X(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(no(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}}}}async function Rn(r,e={}){let t=await r.getBrowserState(e);return{serializedTree:t.serialize(e.serializationOpts),tree:t}}import{randomUUID as SF}from"crypto";var Bw={minChunkTokenCount:500,acceptableChunkTokenCount:3e3,maxChunkTokenCount:8e3,maxLineLength:4e3},zw={minChunkTokenCount:5e3,acceptableChunkTokenCount:1e4,maxChunkTokenCount:3e4,maxLineLength:500},Fw=/<(\S+) id="(\d+)".*?>/g,pF=/(<\/(\S+)>)|(<(\S+).*?\/>)/g,Hw=["h1","h2","section","footer","nav","aside","form","label","dialog"],mF=[...Hw,"span","div","h3"],gF=["table","select","form","ul","ol","menu","pre","code","dialog"],hF=["table","form","dialog","nav","section","ul","select"];function Lc(r){return fF(r)}function fF({logger:r,serializedTree:e,options:t}){let{minChunkTokenCount:n,acceptableChunkTokenCount:o,maxChunkTokenCount:i,maxLineLength:a}=t,l=[],c=e.split(`
4095
+ ${R||""}`}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:Bm(this.internalProperties),importantProperties:this.importantProperties,parentFrame:this.parentFrame,flagNotActionableNodes:this.flagNotActionableNodes});return e.tagName=this.tagName,e.dataMomenticId=this.dataMomenticId,e.properties=Bm(this.properties),e}},Hm=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(Gm.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=c=>c.role==="StaticText"||c.role==="ListMarker",o=new WeakMap,i=(c,s)=>{if(o.has(c))return o.get(c);let u=c.serialize({indentLevel:s,noChildren:!0});return o.set(c,u),u},a=(c,s,u)=>{let d=c.shallowClone();d.children=[];let p=i(c,s).length;if(u<=p)return{clone:d,used:p};if(n(c)||c.children.length===0)return{clone:d,used:p};let m=p,g=u-m;for(let h of c.children){let f=s+2,E=i(h,f).length;if(g<E)break;let{clone:b,used:x}=a(h,f,g);if(x>g)break;d.children.push(b),b.parent=d,m+=x,g-=x}return{clone:d,used:m}},{clone:l}=a(t,0,Math.max(1e4,e));return new r(l,this.a11yIdNodeMap,this.dataMomenticIdMap,this.selectorToNodeMap)}};function KU(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 YU(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?(al({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?(al({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 vw({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,allowedA11yIgnoreReasonsOverride:m,cdpClient:g,logger:h,callId:f}){if(!e&&r.parentId)throw new Error(`Got no parent for accessibility node ${r.nodeId}: ${JSON.stringify(r)}`);let E=(z,re={})=>{},b=r.backendDOMNodeId,x=VU.includes(r.role?.value?.toLowerCase()??"");if(!x&&b===void 0)return E("Filtering out node since it doesn't exist in the DOM"),[];let A=b?i.backendIdToNode[b]:void 0;if(!x&&!A)try{let z=await k(g.send({method:"DOM.describeNode",params:{backendNodeId:b}}),{milliseconds:750,fallback:()=>{h.debug("Timeout getting node from CDP while processing a11y tree")}});if(z&&z.node.nodeName.toLowerCase()==="slot"&&z.node.distributedNodes?.length)h.debug({redirectedDomNode:A,parentAXNode:e?.getNodeOnlySerializedForm(),originalAXNode:r,cdpResult:z},"Redirecting node to assigned slot");else return E("Filtering out node since it doesn't exist in the DOM",{cdpResult:z}),[]}catch(z){return E("Filtering out node since it doesn't exist in the DOM",{err:z}),[]}if(A&&e&&s&&u&&r.backendDOMNodeId&&!YU(A,u,h,f))return A.momenticIgnored=!0,[];if(A&&A.computedStyles.display==="none")return A.momenticIgnored=!0,[];if(A&&A.computedStyles.opacity==="0"&&c!==!0){if(c==="inputs-only"&&A.tagName.toLowerCase()!=="input")return A.momenticIgnored=!0,[];if(c===!1)return A.momenticIgnored=!0,[]}let v=r.name?.value?typeof r.name.value=="string"?r.name.value:`${r.name.value}`:"",_=r.value?.value?typeof r.value.value=="string"?r.value.value:`${r.value.value}`:"",R=new zm({domNode:A,id:parseInt(r.nodeId),role:r.role?.value||"",name:v,nameSources:r.name?.sources,content:_,properties:r.properties,children:[],ignoredReasons:r.ignoredReasons?.filter(z=>(m??bw).includes(z.name)||Ew.includes(z.name))??[],pathFromRoot:(e?`${e.pathFromRoot} `:"")+KU(r),backendNodeID:r.backendDOMNodeId,ignoredByCDP:r.ignored,internalProperties:{inCodeMirrorEditor:e?.internalProperties?.inCodeMirrorEditor},importantProperties:p,parentFrame:n.type==="root"?void 0:n,flagNotActionableNodes:l}),D=n,j=a[t],ae=t;if(A?.tagName.toLowerCase()==="iframe"&&A.ownedFrameId){let z=n.childFrames.find(Xe=>Xe.frameId===A.ownedFrameId),re=o[z?.frameId??""]?.root,le=a[z?.frameId??""];if(z&&re&&le){r.childIds&&r.childIds.length>0&&h.debug("Replacing existing node's children with children from the iframe");let Xe=re;r.childIds=Xe.childIds,D=z,j=le,ae=z.frameId}}let Q=A?.childrenBackendIds?.length??0,me=(r.childIds??[]).filter(z=>!!j.get(parseInt(z))).length;if(Q>me){let z=r.childIds?.map(le=>j.get(parseInt(le))).filter(Boolean).map(le=>le?.backendDOMNodeId).filter(le=>le!==void 0)??[],re=0;for(let le of A?.childrenBackendIds??[]){if(z.includes(le)){re=(r.childIds?.findIndex(Ce=>j.get(parseInt(Ce))?.backendDOMNodeId===le)??0)+1;continue}let Xe=i.backendIdToNode[le];if(!Xe||Xe?.tagName.toLowerCase()!=="svg")continue;let Re=Math.floor(-1*Math.random()*1e7),Dt={nodeId:Re.toString(),parentId:r.nodeId,ignored:!1,backendDOMNodeId:le,frameId:ae,role:{type:"string",value:"graphics-symbol"}};j.set(Re,Dt),r.childIds||(r.childIds=[]),r.childIds.splice(re,0,Re.toString()),re++}}if(r.childIds?.length===1&&A){let z=j.get(parseInt(r.childIds[0])),re=z?.role?.value,le=A.childrenBackendIds;if(z&&re==="StaticText"&&le.length===1){let Xe=i.backendIdToNode[le[0]];if(Xe?.tagName?.toLowerCase()==="span"){let Re=Math.floor(-1*Math.random()*1e7).toString(),Dt={nodeId:Re,parentId:r.nodeId,ignored:!1,backendDOMNodeId:Xe.backendNodeId,frameId:ae,childIds:[z.nodeId]};z.parentId=Re,j.set(parseInt(Re),Dt),r.childIds=[Re]}}}for(let z of r.childIds??[]){if(!z)continue;let re=j.get(parseInt(z));if(!re)continue;let le=await vw({node:re,parent:R,domGraph:i,axGraph:o,frameId:ae,frameContext:D,inputNodeMap:a,cdpClient:g,logger:h,callId:f,filterByViewport:s,showZeroOpacityElements:c,importantProperties:p,viewportDetails:u,useMPaths:d,flagNotActionableNodes:l});le.length&&(R.children=R.children.concat(le))}if(R.role==="StaticText"&&(R.children=[]),R.children.length===1&&R.children[0].role==="StaticText"){let z=R.name,re=R.children[0]?.name;(z===re||!re)&&(R.children=[])}let st=[];for(let z=R.children.length-1;z>=0;z--){let re=R.children[z];if(re.role!=="StaticText"){st.push(re);continue}if(z===0||R.children[z-1].role!=="StaticText"){st.push(re);continue}R.children[z-1].name+=re.name}if(R.children=st.reverse(),!R.isInteresting(p)&&r.parentId)return A&&(A.momenticIgnored=!0),R.children;for(let z of R.children)z.parent=R;return ZU(R),A&&d&&Fm(A,i),[R]}function Aw({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:Gm.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=Um(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=Aw({node:p,a11yIdNodeMap:e,dataMomenticIdMap:t,logger:n,callId:o,startId:s,useMPaths:a,domGraph:i,selectorToNodeMap:l,iconKnowledgeBase:c});return s}async function ww({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,allowedA11yIgnoreReasonsOverride:m}){let g=t??"root",h=r[g]?.root;if(!h)throw new Error("A11y tree has no root");let f=kU(),E=R=>{let D=R.allNodes.filter(ae=>!ae.ignoredReasons?.find(me=>(m??bw).includes(me.name))),j=new Map;return D.forEach(ae=>{j.set(parseInt(ae.nodeId),ae)}),j},b={};Object.entries(r).forEach(([R,D])=>{b[R]=E(D)});let x=await vw({node:h,domGraph:e,parent:null,inputNodeMap:b,axGraph:r,frameId:g,frameContext:d,cdpClient:o,logger:n,callId:f,showZeroOpacityElements:a,importantProperties:c,filterByViewport:i,viewportDetails:s,useMPaths:u,flagNotActionableNodes:l,allowedA11yIgnoreReasonsOverride:m});if(x.length>1)throw new Error(`Something went horribly wrong processing the a11y tree, we got: ${JSON.stringify(x)}`);if(x.length===0)throw new Error("There are no accessible elements on this page or frame. Are you sure this website loads properly?");let A={},v={},_={};return Aw({node:x[0],a11yIdNodeMap:A,dataMomenticIdMap:v,selectorToNodeMap:_,domGraph:e,logger:n,callId:f,useMPaths:u,iconKnowledgeBase:p}),new Hm(x[0],A,v,_)}function XU(r,e,t,n){if(r==="class"){if(t.tagName?.toLowerCase()==="svg")return e.split(" ").filter(a=>a.length<Tw&&!sr.bannedClassSubstrings.some(l=>a.includes(l))).slice(0,3).join(" ");let o=e.split(" "),i=[];for(let a of o)if(Rw(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 JU(r,e,t){if(!e)return;Object.entries(e.attributes).forEach(([a,l])=>{let c=r[a]||a.startsWith("aria")||BU.includes(a);if((sr.relevantElementAttributes.includes(a)||Cw(a,t))&&!c){let u=XU(a,l,e,t);u!==null&&(r[a]=u)}});let n,o=[];if(e.computedStyles.position&&fw.includes(e.computedStyles.position))n=e.computedStyles.position;else if(e.attributes.style){for(let a of fw)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 ZU(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(Ot(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=>Ot(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 QU(r){let e=r.properties.class,t=typeof e=="string"&&e.includes("cm-content");r.internalProperties.inCodeMirrorEditor=r.internalProperties?.inCodeMirrorEditor||t}function Rw(r,e){if(e&&xw(r,e))return!0;if(sr.bannedClassSubstrings.some(t=>r.includes(t)))return!1;if(sr.alwaysInterestingClassNames.includes(r))return!0;for(let t of sr.alwaysInterestingClassPrefixes)if(r.startsWith(t))return!0;return!1}function Cw(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 xw(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 Pc=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 k(i.newCDPSession(a),{milliseconds:o*u,fallback:()=>{throw new C("UserInfrastructureError",`Failed to initialize Chrome session within the page load timeout (${a.url()})`)}});break}catch(d){await Y(it),c=d}if(!l)throw c;let s=new r(l,e,t,n,o);try{await k(s.registerHandlers(l),{milliseconds:o,message:`CDP handler registration timed out after ${o}ms`})}catch(u){throw s.cdpFullyDead=!0,new C("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 Promise.all([e.send("Accessibility.enable"),e.send("Page.enable"),e.send("DOM.enable"),e.send("Overlay.enable"),e.send("DOMSnapshot.enable"),e.send("CSS.enable")])}async send({method:e,params:t,timeout:n=this.defaultTimeoutMs,timeoutMsg:o}){for(;this.cdpInitializingPromise;)await k(this.cdpInitializingPromise,{milliseconds:n});if(this.cdpCrashDetails){if(this.cdpFullyDead)throw new C("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 k(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 k(this.contextGetter().newCDPSession(n),{milliseconds:t,fallback:()=>{throw this.logger.error(`Failed to initialize CDP session within the page load timeout (${n.url()})`),new C("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 k(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 k(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 di="<empty>";function eF(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 _w(r){let e=r.adFrameStatus?.adFrameType;return e==="child"||e==="root"||eF(r.url)}async function tF(r,e){let t=await r.send({timeout:J,method:"DOM.getFrameOwner",params:{frameId:e}}),o=(await r.send({timeout:J,method:"DOM.pushNodesByBackendIdsToFrontend",params:{backendNodeIds:[t.backendNodeId]}})).nodeIds[0],a=(await r.send({timeout:J,method:"DOM.describeNode",params:{backendNodeId:t.backendNodeId}})).node;return a.nodeId=o,a}async function pi({cdpClient:r,page:e,logger:t}){let n={type:"root",childFrames:[],page:e},o=[],[i,a]=await Promise.all([r.send({timeout:li,method:"Page.getFrameTree",params:{}}),r.send({timeout:li,method:"DOM.getDocument",params:{depth:0}})]),s=(i.frameTree.childFrames??[]).map(async(d,p)=>{if(_w(d.frame))return null;try{return await Pw({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 Pw({cdpClient:r,rawFrameTree:e,indices:t,parent:n,warnings:o,logger:i}){let a=e.frame.id,l=await tF(r,a),c=l.attributes??[],s=null,u=[];for(let g of["src","name","id","title","srcdoc","sandbox"]){let h=Cn(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(_w(g.frame))return null;try{return await Pw({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 rF(r){try{return await r.owner().count()===1}catch{return!1}}async function nF(r){try{return await r.count()===1}catch{return!1}}async function Ur(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,di]){let p=o.frameLocator(d===di?"iframe":`iframe[${d}]`);if(await rF(p)){u=!0,o=p,i.push(d);break}}if(!u)throw new C("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,di]){let u=o.locator(s===di?"iframe":`iframe[${s}]`);if(await nF(u)){a=u,i.push(s);break}}if(!a)throw new C("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:Z}),c=await l.asElement().contentFrame();if(!c)throw new C("InternalWebAgentError",`Failed to load Playwright Frame for iframe with url '${r.url}'`);return await l.dispose(),{frame:c,mPathSelectorTokens:i}}function Mw(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 Iw({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===di?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===di?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 Ur(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=Mw(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 Ur(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=Mw(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 Ur(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 Ur(n,r)).frame,handle:n,mPathSelectorTokens:t.mPathSelectorTokens,frameTree:e},logs:i};throw i.push(`Found ${a.length} frames with indices ${t.indices}`),new nn("Failed to find the iframe that previously contained this element",[{type:"AUTO_FRAME",matched:!1,logs:i}])}function Ic(r){return r.type==="auto"?JSON.stringify({type:"auto",frameId:r.handle.frameId}):JSON.stringify(r)}function Vm(r){for(;r.parent.type==="frame";)r=r.parent;return r.parent}function Ow(r){let e=Vm(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 Lw(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 Nw({frame:r,logger:e,signal:t}){let n;try{n=await r.frameElement(),await oF({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 oF({frameElementHandle:r,logger:e,signal:t}){let n=await r.boundingBox();await ja({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:ge,codePath:"scrollIframeIntoView",signal:t}),e.info({oldBb:n,newBb:await r.boundingBox()},"Successfully scrolled iframe into view")}async function Dw({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 k(g?.boundingBox(),{milliseconds:J})??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 Fr}from"crypto";import iF from"js-beautify";var aF=["Dead"],Oc=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:Fr(),type:"PRESET_ACTION",command:Vr(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=Vr(i);a={id:Fr(),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=Vr(i);a={id:Fr(),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=Vr(i);a={id:Fr(),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=iF.html(d,{indent_size:1,indent_with_tabs:!1,preserve_newlines:!1}),d=AA(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(aF.includes(t)||this.signal.aborted)return;let o="normal";t.length>1&&(o="special");let i;if(o==="normal"){let d=Vr("TYPE");i={id:Fr(),type:"PRESET_ACTION",command:{...d,target:void 0,value:t,clearContent:!1}}}else{let d=Vr("PRESS");i={id:Fr(),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:Fr(),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:Fr(),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=Vr(s);u.deltaY=Math.abs(i);let d={id:Fr(),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=Vr(s);u.deltaX=Math.abs(i);let d={id:Fr(),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 jm}from"zod";var Obe=jm.object({type:jm.literal("url"),url:jm.string()});var Lc=class{smartWaitingTimeoutMs;pageLoadTimeoutMs;allowPartialAccessibilityTree;logger;cdpClient;pageGetter;abortSignalGetter;userControlledBrowserSettings;enricher;iconKnowledgeBase;computedStylesToFetch=["display","opacity","visibility","height","position"];activeFrameCache;activeFrameConfig;lastA11yIdToNodeMap={};lastDataMomenticIdToNodeMap={};lastSelectorToNodeMap={};lastA11yTreeRoot;lastDomGraph;allowedA11yIgnoreReasonsOverride;constructor({smartWaitingTimeoutMs:e,pageLoadTimeoutMs:t,allowPartialAccessibilityTree:n,logger:o,cdpClient:i,pageGetter:a,abortSignalGetter:l,enricher:c,iconKnowledgeBase:s,userBrowserSettings:u,allowedA11yIgnoreReasonsOverride:d}){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.userControlledBrowserSettings=u,this.allowedA11yIgnoreReasonsOverride=d,this.userControlledBrowserSettings.importantStyles)for(let p of this.userControlledBrowserSettings.importantStyles){let m=p.split(":");if(m.length!==2){this.logger.warn({style:p},"Invalid style property passed to importantStyles");continue}let g=m[0]?.trim(),h=m[1]?.trim();if(g===void 0||h===void 0){this.logger.warn({style:p},"Invalid style property passed to importantStyles");continue}this.computedStylesToFetch.includes(g)||this.computedStylesToFetch.push(g)}}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.userControlledBrowserSettings.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=Vm(e),{frame:o,mPathSelectorTokens:i}=await Ur(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 pi({cdpClient:this.cdpClient,page:t,logger:this.logger}),{resolution:o,logs:i}=await Iw({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(Ic(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:Ic(this.frameConfig),cacheTime:Date.now(),frameTree:this.frameConfig.frameTree,mPathSelectorTokens:this.frameConfig.mPathSelectorTokens},await Nw({frame:n.frame,logger:e,signal:t}),this.activeFrameCache=n,n}async executeFunctionInAllFrames(e,t){let n=this.pageGetter(),o=await pi({cdpClient:this.cdpClient,page:n,logger:this.logger}),i=[k(n.evaluate(e,t),{milliseconds:ge})],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(Ur(c,n).then(({frame:u})=>k(u.evaluate(e,t),{milliseconds:ge})).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 pi({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 lr({fn:()=>this.resolveActiveFrameConfig({logger:n,signal:o}),codePath:"getActiveFrameDetails",logObject:t,signal:o,logger:n})??void 0,!a)throw new C("ActionFailureError","Got null frame details despite active frame config");l=a.handle,c=l.frameId}else this.userControlledBrowserSettings.autoExpandIframes?(l=await lr({fn:()=>pi({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 lr({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 lr({fn:()=>this.getDOMTree({devicePixelRatio:e.devicePixelRatio??1,signal:o,logger:n}),codePath:"domFetch",logObject:t,signal:o,logger:n}),u=await lr({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 lr({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:gn,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.userControlledBrowserSettings.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=mw({node:o,domGraph:this.domGraph});return gw(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:ge});if(!n||!n.object.objectId)throw new Error(`Could not resolve backend node ${t}`);let o;try{o=await hw(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(Sr(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 pi({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 C&&s.reason==="UserInfrastructureError")throw s;c%3===0&&this.logger.warn({attempt:c,err:s},"Failed to resolve active frame, retrying..."),await Y(it,t)}finally{c++}if(a)return{source:"url",frame:a.frame,handle:a.handle,frameIdentifierStringified:Ic(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=Cn(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 Ur(l,o)});break}}else if(n.trim()===d.trim()){a.push({handle:l,matchType:"url",...await Ur(l,o)});break}}}if(a.length===1){let l=a[0];return this.userControlledBrowserSettings.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 C("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 ww({rawA11yGraph:t,startingFrameId:o,frameContext:i,domGraph:n,logger:a,cdpClient:this.cdpClient,showZeroOpacityElements:c,flagNotActionableNodes:s,filterByViewport:e.filterByViewport,importantProperties:{attributes:this.userControlledBrowserSettings.importantAttributes,classes:this.userControlledBrowserSettings.importantClasses,styles:this.userControlledBrowserSettings.importantStyles},viewportDetails:void 0,iconKnowledgeBase:l,useMPaths:this.userControlledBrowserSettings.visualActions,allowedA11yIgnoreReasonsOverride:this.allowedA11yIgnoreReasonsOverride});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.userControlledBrowserSettings.visualActions)return;let i=await this.addMomenticIdsHelper(n??e,1);if(!this.userControlledBrowserSettings.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 Ur(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.userControlledBrowserSettings.visualActions)return t;let n=this.logger;return await et({root:e,fn:i=>window.addIdsToElement?.(document.body,i),arg:t,timeout:ge,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(Cn(t,"aria-hidden")==="true")return{shouldUnroll:!1,reason:"aria-hidden"};let n=Cn(t,"style");if(n?.includes("display: none")||n?.includes("visibility: hidden"))return{shouldUnroll:!1,reason:"hidden CSS style"};await this.cdpClient.send({timeout:J,method:"DOM.pushNodesByBackendIdsToFrontend",params:{backendNodeIds:[e.backendNodeId]}});let[o,i]=await Promise.all([this.cdpClient.send({timeout:J,method:"DOM.getBoxModel",params:{backendNodeId:e.backendNodeId}}),this.cdpClient.send({timeout:J,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 lr({fn:()=>this.getRawA11yTreeForFrame({frameId:t,timeoutMs:this.pageLoadTimeoutMs,logTimings:o}),codePath:"a11y-tree-fetch-root",logObject:o,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.userControlledBrowserSettings.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 lr({fn:()=>this.getRawA11yTreeForFrame({frameId:m.frameId,timeoutMs:this.smartWaitingTimeoutMs,logTimings:o}),codePath:`a11y-tree-fetch-child-${m.frameId}`,logObject:o,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 lr({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,logger:this.logger})).nodes;else{let a=(await lr({fn:()=>this.cdpClient.send({method:"Accessibility.getRootAXNode",params:{frameId:e??void 0},timeout:ge}),codePath:"cdp-get-root-ax-node",logObject:n,logger:this.logger})).node.backendDOMNodeId;o=(await lr({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,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:J}),!o||!o.documents.length)throw new Error("Got empty DOM tree")}catch(l){await Y(it,t),i++,a=l}if(!o||!o.documents.length)throw n.error({err:a},"Fatal error fetching DOM tree"),new C("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 pw({snapshot:o,devicePixelRatio:e,computedStylesToFetch:this.computedStylesToFetch,logger:n})}constructIframeRegexAsync(e,t){if(t.frameSrcRegex||t.frameUrlRegex)return;let n=Ow(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 Wm(r){let e=[],t="";for(let n of r)n==="+"&&t?(e.push(t),t=""):t+=n;return e.push(t),e}var Ya=class r{static USER_AGENT=wc;abortSignal=void 0;contextInitialized=!1;browser;context;properties;page;userControlledBrowserSettings;pageLoadPromises={};lastTabChangeEventTimeout=void 0;clientCallbacks;iconKnowledgeBase;cdpClient;debugData={logsPerPage:[],harPages:{},harEntries:{}};recentFrameNavigations={};requestRecorders={};mocks={};customHeaders=[];enricher;storage;logger;stateManager;transformer;lastScreenshotForRecording=void 0;originsVisited=new Set;viewport;onVideoPageChange;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,onVideoPageChange:m}){$y(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,this.iconKnowledgeBase=p,this.onVideoPageChange=m}registerAbortSignal(e){this.abortSignal=e}async initialize({grantPermissions:e,runInitScripts:t,timingRecorder:n}){if(this.contextInitialized)return;let o={[Ac]:this.userBrowserSettings.visualActions},i=[];if(this.userControlledBrowserSettings.extraHeaders&&i.push(this.context.setExtraHTTPHeaders(this.userControlledBrowserSettings.extraHeaders)),e){let u=["clipboard-read","clipboard-write","microphone","camera","geolocation"];xr||u.push("local-network-access"),i.push(this.context.grantPermissions(u))}i.push(this.context.addInitScript({content:um.htmlUtilsLibJs}),this.context.addInitScript({content:`window._MOMENTIC_BROWSER = true; window._MOMENTIC_FEATURE_FLAGS = ${JSON.stringify(o)}; window.addEventListener('load', (event) => { console.log('[MOMENTIC] Page loaded'); });`}),this.exposeRecordingBindings());let a=u=>this.handleNewPageEvent(u);this.context.on("page",a),this.handleNewPageEventHelper(this.page),this.context.on("close",()=>{this.context.off("page",a)});let l=!1;if(t){let u=async()=>{let d=Date.now();try{await Promise.all([this.page.addScriptTag({content:um.htmlUtilsLibJs}),this.page.addScriptTag({content:`window._MOMENTIC_BROWSER = true; window._MOMENTIC_FEATURE_FLAGS = ${JSON.stringify(o)}; window.addEventListener('load', (event) => { console.log('[MOMENTIC] Page loaded'); });`})])}catch(p){if(p instanceof Error&&p.message.includes("Content Security Policy"))this.logger.warn({err:p},"Content Security Policy error from adding Momentic scripts, reloading page instead"),l=!0;else throw p}(n??{})["add-init-scripts"]=Date.now()-d};i.push(u())}if(!this.properties.systemDevicePixelRatio)if(process.env.MOMENTIC_LOCAL_DEV==="1"&&mF()==="darwin"&&sF("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;else{let u=async()=>{let d=Date.now();this.properties.systemDevicePixelRatio=await this.page.evaluate(()=>window.devicePixelRatio),(n??{})["fetch-dpr"]=Date.now()-d};i.push(u())}let c=Date.now();await k(Promise.all(i),{milliseconds:this.pageLoadTimeout,message:"Timed out attaching Chrome permissions and initialization scripts",signal:this.abortSignal});let s=Date.now();(n??{})["ops-attach"]=s-c,l&&await this.page.reload(),this.cdpClient=await Pc.init({logger:this.logger,contextGetter:()=>this.context,pageGetter:()=>this.page,defaultTimeoutMs:this.pageLoadTimeout}),(n??{})["cdp-init"]=Date.now()-s,await this.initializeScreencast(),this.stateManager=new Lc({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,allowedA11yIgnoreReasonsOverride:this.properties.allowedA11yIgnoreReasonsOverride}),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(e){let t=await ew(e),n=new r(t);return await n.initialize({grantPermissions:!0,runInitScripts:!1}),n}static async fromExistingContext({context:e,storage:t,enricher:n,userBrowserSettings:o,properties:i,logger:a,timingRecorder:l}){let c=e.pages()[0];if(!c)throw new Error("No page found in existing context");let s=c.viewportSize();if(!s){let p=Date.now();s=await c.evaluate(()=>({width:window.innerWidth,height:window.innerHeight})),l["eval-viewport"]=Date.now()-p}let u=c?.url(),d=new r({browser:e.browser(),context:e,page:c,baseUrl:u,logger:a,storage:t,enricher:n,userBrowserSettings:o,viewport:s,properties:i,clientCallbacks:void 0,iconKnowledgeBase:null});return await d.initialize({grantPermissions:!1,runInitScripts:!0,timingRecorder:l}),d}async handleAvailableTabsChangeHelper(){try{let e=await km(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=$m(),o=`${e}-${n}`,i=Date.now(),a=!1,l=async()=>{try{await k(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()||!oo(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();this.logger.info({url:t},"Detected new page event, registering handlers and waiting for load to complete");try{this.handleNewPageEventHelper(e)}catch(n){this.logger.warn({err:n},"Error handling new page open, continuing....")}}handleNewPageEventHelper(e){let t=$m(),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);this.userBrowserSettings.disableBrowserMonitoring||e.on("console",a=>{kA(e,o,this.debugData,a,this.logger)});let i=async()=>{this.userBrowserSettings.disableBrowserMonitoring||(await zA(t,this.debugData,e),await e.route("**/*",async(a,l)=>{await Cm({pageId:t,route:a,request:l,debugData:this.debugData,logger:this.logger,requestRecorders:this.requestRecorders,mocks:this.mocks})}),await e.route("**/*",$A(this.customHeaders,this.logger))),xr&&await e.route("**/*",qa),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"||!oo(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}),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){this.abortSignal=void 0,this.debugData.logsPerPage=[],this.debugData.harPages={},this.debugData.harEntries={},this.pageLoadPromises={},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 k(Lm(this.getBrowserCallbacks()),{milliseconds:Z})}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<li;){a++,n?.throwIfAborted();try{if(await et({fn:()=>{let c=window;return!!(c.generateCssSelectors&&c.evaluateCssSelectors&&c.evaluatePrimaryCaches&&c.generateHtmlCacheAttributes&&c.ldist)},timeout:Z,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 Y(it),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),et({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:J,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 Y(ci),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??ge}),c=Buffer.from(l.data,"base64"),s=await Uw.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&&uF(n,c),this.lastScreenshotForRecording=c,!e)return c;let p=await e.boundingBox({timeout:J});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 Uw.fromBuffer(c),b=E.bitmap.width,x=E.bitmap.height;m=Math.max(0,Math.min(m,b-1)),g=Math.max(0,Math.min(g,x-1)),h=Math.max(1,Math.min(h,b-m)),f=Math.max(1,Math.min(f,x-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(){if(this.viewport)return this.viewport;let e=this.page.viewportSize();return e||null}async navigate({url:e,initialNavigation:t=!1,loadTimeoutMs:n=this.pageLoadTimeout}){bA(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 Y(it),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:Z})}if(!i)throw new C("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(_A.has(l))throw new C("UserInfrastructureError",`${e} took too long to load \u{1F61E}. Please ensure the site is accessible and returns content within the page load timeout.`);await this.fixViewportForNewHeadless()}async type(e,t={},n=!1){await this.directTypeHelper(e,t,n)}async getActiveElement(e){try{return await et({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:Z,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 ow({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 Y(ci),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"?(this.properties.isAndroid?await this.page.keyboard.press("Control+A"):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??fh}),t.pressEnter&&await this.press("Enter",{})}async scrollIntoViewIfNeeded(e){try{await e.scrollIntoViewIfNeeded({timeout:ge})}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:ge})}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 Mc({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:Z}),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 DA(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:Z});let n=0;for(let i of e.origins??[])for(let a of i.localStorage)try{await this.cdpClient.send({timeout:Z,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 NA(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 LA(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 C("ActionFailureError",`Failed to save auth state: ${n?.message}`)}async getOpenPages(e){return km(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,startingBoundingBox:o,allowNotActionableNodesOverride:i,logger:a=this.logger}){if(e&&this.saveA11yDetailsToCache(e,t),t.frameCache=this.stateManager.saveAutoFrameCacheDetails(t.frameCache),n)try{let l=await this.fetchHtmlAttributes({locator:n,logger:a,startingBoundingBox:o,allowNotActionableNodesOverride:i});l?(t.generatedSelectors=l.generatedSelectors,t.serializedHtml=l.serializedHtml,t.nodeOnlySerializedHtml=l.nodeOnlySerializedHtml,t.hybridSelector=l.hybridSelector):a.warn("Got undefined HTML attributes when trying to update cache")}catch(l){if(l instanceof wr)throw a.warn({err:l},"Cache attributes disqualify found element"),l;a.warn({err:l},"Failed to fetch HTML attributes for target, continuing...")}try{await this.saveElementVisualAttributes({target:t,locator:n,logger:a,boundingBox:o})}catch(l){a.debug({err:l},"Failed to save element visual details, continuing...")}}async saveElementVisualAttributes({target:e,locator:t,logger:n,boundingBox:o}){if(!t)return{scrollPerformed:!1};if(!gm.includes(e?.role??""))return{scrollPerformed:!1};if(await this.scrollIntoViewIfNeeded(t),o||(o=await t.boundingBox({timeout:J})),!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({logger:e,locator:t,requirements:n}){let o={},i=!!n?.position&&n.position!=="irrelevant",a=!!n?.shape&&n.shape!=="irrelevant";if(i||a){let l=await t.boundingBox({timeout:J});if(!l||!l.width||!l.height)throw new C("ActionFailureError","Element does not have a bounding box as required");a&&(o.shape={width:l.width,height:l.height,tolerance:n.shape}),i&&(o.position={x1:l.x,y1:l.y,x2:l.x+l.width,y2:l.y+l.height,tolerance:n.position})}if(n?.text){let l=await t.textContent({timeout:J});o.text=l?.trim()}if(n?.attributes&&n.attributes.length>0){let l={};for(let c of n.attributes){let s=c.trim().toLowerCase();if(!(!s||sr.bannedAiRequiredCacheAttributes.includes(s)))try{let u=await t.getAttribute(s,{timeout:J});u!==null&&(l[c]=u)}catch(u){e.warn({err:u,attr:c},"Failed to fetch required attribute, continuing...")}}o.attributes=l}return o}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({logger:o,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}){if(t)try{o.requirements=await this.getElementRequiredValues({logger:l,locator:i,requirements:t})}catch(c){l.warn({err:c},"Failed to generate required values for target")}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 C("InternalWebAgentError","Only positive IDs should be passed to resolveAllyIdToTarget");let c=this.stateManager.a11yIdToNodeMap[e];if(!c)throw new C("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:x,config:A}=await this.stateManager.getAutoFrameDetailsFromHandle(b);d=x,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:Lw(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,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 Y(it,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,shouldLogOnFailure:m,logger:i,allowNotActionableNodesOverride:l,signal:a});break}catch(g){if(g instanceof qi)break;if(g instanceof wr){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 Y(it,a)}a?.throwIfAborted(),m&&i.warn({err:g},`Could not resolve target using primary cache only (x${u})`),await Y(it,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,shouldLogOnFailure:l}){let c=mi(t),s=[],u=(await this.getBrowserState({logger:o,abortSignal:i,skipWait:!0,allowNotActionableNodesOverride:a})).serialize(),d;if(t.generatedSelectors||t.hybridSelector){let p;try{p=await this.resolveTargetWithPrimaryMethods({root:e,target:t,logger:o,allowNotActionableNodesOverride:a,shouldLogOnFailure:l})}catch(m){d=m,m instanceof nn&&s.push(...m.decisions)}if(p)return{...p,pageState:void 0,decisions:[...s,...p.decisions]};n||(s.push({type:"CSS_SELECTOR",matched:!1,reason:d?.message,selectors:mi(t.generatedSelectors??[])}),t.generatedSelectors=void 0,t.hybridSelector=void 0)}if(n)throw d;if(!this.userBrowserSettings.disableSecondaryCacheResolution){let p=await this.resolveTargetWithSecondaryMethods({root:e,tree:u,target:t,decisions:s,logger:o,signal:i,allowNotActionableNodesOverride:a});if(p)return p}throw new nn(`Could not find any relevant node given target: ${JSON.stringify(c)}`,s)}async resolveTargetWithPrimaryMethods({root:e,target:t,logger:n,allowNotActionableNodesOverride:o,shouldLogOnFailure:i}){if(!t.nodeOnlySerializedHtml)throw new qi("Insufficient data to resolve target using primary methods (missing node HTML)");let a=i?n:gn,l=this.userControlledBrowserSettings.hybridSelectorMode,c={ldistThreshold:mm,requireBoundingBox:!o,ignoreHrefForCaching:this.userControlledBrowserSettings.ignoreHrefForCaching,requireMatchingBoundingBox:this.userControlledBrowserSettings.bustCacheOnBoundingBoxChange?t.boundingBox:void 0,requirements:t.requirements,additionalElements:t.additionalElements,importantProperties:{attributes:this.userControlledBrowserSettings.importantAttributes,classes:this.userControlledBrowserSettings.importantClasses,styles:this.userControlledBrowserSettings.importantStyles}},{css:s,hybrid:u}=await et({fn:A=>window.evaluatePrimaryCaches(A),arg:{cssParams:{selectors:t.generatedSelectors??[],cachedElementSerialized:t.nodeOnlySerializedHtml,opts:c},hybridParams:l&&t.hybridSelector?{nodes:t.hybridSelector,cachedElementSerialized:t.nodeOnlySerializedHtml,opts:c}:void 0},root:e,timeout:J,waitForPageLoad:()=>this.waitForPageLoad(),codePath:"evaluating target caches"}),d,p,m=[];if(l==="prefer"&&u?.result){d=u.result;let A={type:"HYBRID_SELECTOR",matched:!0,logs:u.logs,reason:"Discovered a match using Momentic's hybrid text and CSS selector approach"};m.push(A),p="HYBRID_SELECTOR"}else if(s?.result){d=s.result;let A=`${d.workingSelectors.length} CSS selectors matched the following element: ${d.serializedElement}`,v=d.workingSelectors.slice(0,5);m.push({type:"CSS_SELECTOR",matched:!0,logs:s.logs,reason:A,selectors:v}),n.debug({reason:A,workingSelectors:v},"Resolved with CSS selectors"),p="CSS_SELECTOR"}else throw m.push({type:"CSS_SELECTOR",matched:!1,reason:s.logs.length===1?"CSS evaluation failed":"No CSS selectors matched",selectors:[],logs:s.logs}),u&&m.push({type:"HYBRID_SELECTOR",matched:!1,reason:u.logs.length===1?"Hybrid evaluation failed":"No hybrid selectors matched",logs:u.logs}),s?.error&&n.error({err:new Error(s.error)},"Cache evaluation errored unexpectedly (CSS)"),u?.error&&n.error({err:new Error(u.error)},"Cache evaluation errored unexpectedly (Hybrid)"),new nn("Cache evaluation failed",m);let g,h,f;if(this.userBrowserSettings.visualActions){let A=d.mPath;if(!A)throw new Error("Found element did not have an mPath despite using visual actions");let v=A.join(" > ");g=e.locator(v),h=this.stateManager.getNodeUsingMPathSelector(v)}else if(d.dataMomenticId!==void 0)f=parseInt(d.dataMomenticId),h=this.stateManager.dataMomenticIdToNodeMap[f],"workingSelectors"in d?g=e.locator(d.workingSelectors[0]):g=e.locator(Sr(f));else throw new C("InternalWebAgentError","Received an element resolution result with no identifying attributes");l&&t.hybridSelector&&(u?.logs.length===1?a.warn({hybridResult:u,cssResult:s,hybridMode:l},"Hybrid selector resolution rejected, continuing..."):u?.result?s?.result&&u?.result&&u.result.serializedElement!==s.result.serializedElement&&(this.userBrowserSettings.visualActions&&JSON.stringify(s.result.mPath)!==JSON.stringify(u.result.mPath)?n.warn({originalCache:t,hybridResult:u,cssResult:s,hybridMode:l,mode:"visualActions"},"Hybrid selector resolution returned a different element than CSS selector resolution, continuing..."):s.result.dataMomenticId!==u.result.dataMomenticId&&n.warn({originalCache:t,hybridResult:u,cssResult:s,hybridMode:l,mode:"dataMomenticId"},"Hybrid selector resolution returned a different element than CSS selector resolution, continuing...")):a.warn({originalCache:t,hybridResult:u,cssResult:s,hybridMode:l},"Hybrid selector resolution returned no eligible elements while CSS resolution did, continuing..."));let E=await Dr(g,n);if(E&&E!==d.serializedElement)throw n.warn({currentNodeOnlySerializedHtml:E,cachedSerializedHtml:d.serializedElement},"Retrying cache resolution because element's HTML has changed since resolution"),new Error("Element's HTML has changed since cache was generated");let b=mi(t);await this.updateCacheWithNewNodeDetails({node:h,target:t,locator:g,logger:n,startingBoundingBox:d.boundingBox,allowNotActionableNodesOverride:o});let x=qm(b,t);return x&&Object.keys(x).length>0&&(t.cacheResolutionUpdateTime=new Date().toISOString(),t.cacheResolutionUpdateLoggerTags=pe(n),t.cacheResolutionUpdateSource=p),{a11yNode:h,displayString:d.serializedElement,locator:g,decisions:m}}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:Z}),m=await Dr(p,o,500)??"",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 C("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 Y(it,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:J});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<xA){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 et({fn:d=>window.findClosestElementByLDist?.(d),arg:{nodeOnlySerializedHtml:t.nodeOnlySerializedHtml},timeout:ge,root:e,waitForPageLoad:()=>this.waitForPageLoad(),codePath:"finding the closest element on the page"}),u=Math.floor(mm*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(Sr(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 Dr(m,o,500)??"unknown element";o.warn({result:s,originalTarget:t,displayString:g},"Resolved cached target to new node with pure html levenshtein distance");let h=mi(t);await this.updateCacheWithNewNodeDetails({node:p,target:t,locator:m,logger:o,startingBoundingBox:s.boundingBox,allowNotActionableNodesOverride:a});let f=qm(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&&gm.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({screenshotUrl:e,oldTarget:t,signal:n,allowNotActionableNodesOverride:o}){let i;if(!this.enricher)throw new Error("Enricher not available for screenshot resolution");let a=await this.screenshot({retries:0}),c=await(await fetch(e)).arrayBuffer(),s=fF(),u=await this.enricher.runTemplateMatching({id:s,searchImageBase64String:Buffer.from(c).toString("base64"),pageImageBase64String:a.toString("base64")},{signal:n}),{target:d,locator:p}=await this.getTargetFromPositionPercentages({percentX:u.x,percentY:u.y,allowNotActionableNodesOverride:o}),m=d.boundingBox?.width,g=d.boundingBox?.height;if(!m||!g)throw i="Rejecting target from screenshot due to no bounding box",new Error(i);let h=d.id,f=this.stateManager.a11yIdToNodeMap[h],E=mi(t);await this.updateCacheWithNewNodeDetails({target:t,node:f,locator:p,allowNotActionableNodesOverride:o});let b=qm(E,t);return b&&Object.keys(b).length>0&&(t.cacheResolutionUpdateTime=new Date().toISOString(),t.cacheResolutionUpdateLoggerTags=pe(this.logger),t.cacheResolutionUpdateSource="TEMPLATE_MATCHING",this.logger.info({id:s,diffs:b,templateMatch:u},"Updated cache after template matching resolution")),{locator:p,a11yNode:f,displayString:d.nodeOnlySerializedHtml??"",decisions:[{type:"TEMPLATE_MATCHING",matched:!0,reason:"Found element using screenshot",elementImageUrl:e}]}}async typeIntoTarget(e,t,n={}){await this.highlight(t.locator);let o=await t.locator.getAttribute("type",{timeout:Z})??"",i=nw.some(a=>a===o.toLowerCase());return await Nm({targetingResult:t,options:{force:n.force,relativePosition:n.relativePosition},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 Nm({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(),Ec(l,t,n)){a=!0;break}await Y(it,this.abortSignal)}if(!a)throw new C("ActionFailureError",`The active page URL ${n?.negated?"still does":"does not"} ${Uv(t)} in ${o}ms.
4096
+ 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:J});if(!o)throw new C("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 Y(n.hoverSeconds?Math.min(n.hoverSeconds*1e3,ge):500),await this.page.mouse.up()}async mouseDrag(e,t,n,o){o&&await this.hover({locator:o}),await this.page.mouse.down();let i;if(o){let a=await o.boundingBox({timeout:J});a&&(i={x:a.x+a.width/2,y:a.y+a.height/2})}i||(this.logger.warn("Could not get starting position from fromTarget, falling back to (0,0)"),i={x:0,y:0}),await this.page.mouse.move(i.x+e,i.y+t,{steps:n}),await Y(ci),await this.page.mouse.up()}async hover(e){await this.highlight(e.locator),await ao({func:async t=>{await this.scrollIntoViewIfNeeded(t.locator);let n=await t.locator.boundingBox({timeout:J});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 ao({func:t=>t.locator.focus({timeout:ge}),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 et({fn:()=>{let n=document.activeElement;n&&n.nodeType===1&&n.blur()},root:t,arg:void 0,waitForPageLoad:()=>this.waitForPageLoad(),timeout:Z,codePath:"blurring the active element"});return}await this.highlight(e.locator),await ao({func:t=>t.locator.blur({timeout:ge}),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 ao({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 C("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:J})},targetingResult:e})}async press(e,t){let n=t.repeat??1;if(t.convertMeta){let o=_c(e,this.properties.isAndroid);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=_c(e,this.properties.isAndroid);n!==e&&(this.logger.info({keyString:e,convertedKey:n},"Converted platform dependent keys"),e=n)}for(let n of Wm(e))await this.page.keyboard.down(n)}async keyUp(e,t){if(t.convertMeta){let n=_c(e,this.properties.isAndroid);n!==e&&(this.logger.info({keyString:e,convertedKey:n},"Converted platform dependent keys"),e=n)}for(let n of Wm(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,shouldLogOnFailure:a}=e,l=e.abortSignal??this.abortSignal,c=!i,s=i?!0:this.userControlledBrowserSettings.showZeroOpacityElements,u=a?n:gn;o||await this.waitForPageLoad(),e.skipWait||await this.waitForDOMStability({logger:n,signal:l});let d=0,p;for(;d<t;){d++;try{return await k(this.stateManager.getA11yTree({devicePixelRatio:this.devicePixelRatio,abortSignal:l,logger:n,filterByViewport:e.filterByViewport,showZeroOpacityElements:s,flagNotActionableNodes:c}),{milliseconds:this.pageLoadTimeout*d,signal:l,message:"Getting browser state took too long"})}catch(m){if(l?.throwIfAborted(),p=m instanceof Error?m.message:`${m}`,d>=t)throw m;u.warn({err:m,url:this.url()},"Error getting a11y tree, retrying...")}}throw new C("ActionFailureError",`Getting page content failed after ${t} attempts. Error: ${p}`)}async getViewportOffsetDetails(e){let[t,n,o,i,a]=await et({root:e,fn:()=>[window.scrollY,window.scrollX,window.screen.width,window.screen.height,window.devicePixelRatio],arg:void 0,timeout:J,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 Y(ci,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<CA)){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 Y(n.hoverSeconds?Math.min(n.hoverSeconds*1e3,pm):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),await this.page.mouse.down(),await this.page.mouse.move(e+o.x,t+o.y,{steps:n}),await Y(ci),await this.page.mouse.up()}async getElementLocation(e){let t=await this.cdpClient.send({method:"DOMSnapshot.captureSnapshot",params:{computedStyles:[],includeDOMRects:!0,includePaintOrder:!0},timeout:J}),n=await k(this.page.evaluate(()=>window.devicePixelRatio),{milliseconds:ge});process.platform==="darwin"&&n===1&&(n=wA);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 Dm({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 Dm({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){if(await this.stopScreencast(),this.recordUrlVisited(e.url()),this.onVideoPageChange){let n=await e.video()?.path();if(n){let o=Fw(n);this.onVideoPageChange({videoName:o})}}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 Y(it)}}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 C("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)}.
4097
+ Available pages:${JSON.stringify(n.map(i=>i.url))}`);if(!oo(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=Gs(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:J}),n=await fetch("https://api.2captcha.com/createTask",{method:"POST",body:JSON.stringify({clientKey:ui,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<MA;){await Y(2500);let l=await fetch("https://api.2captcha.com/getTaskResult",{method:"POST",body:JSON.stringify({clientKey:ui,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(){try{await k(this.exposeRecordingBindingsHelper(),{milliseconds:this.pageLoadTimeout})}catch(e){e instanceof Error&&e.message.includes("already registered")||this.logger.error({err:e},"Failed to install Momentic libraries for action recording")}}async exposeRecordingBindingsHelper(){await this.context.exposeBinding("isRecordingActive",()=>this.transformer!==void 0,{handle:!1}),await this.context.exposeBinding("captureTargetedEvent",({frame:e},t)=>{this.transformer&&Dw({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(c=>c.url),o=0,i=!1,a=async()=>{if(e.aborted||o>8){clearTimeout(t);return}i=!0;let c;try{c=(await this.getOpenPages()).map(u=>u.url),o=0}catch(u){this.logger.debug({err:u},"Failed getting new open pages during recording tab switch cron, skipping..."),o++;return}let s=this.url();for(let u=c.length-1;u>=n.length;u--){let d=c[u];oo(d,this.logger)&&d!==s&&this.logger.info({lastActivePages:n,currentUrl:s,newOpenPages:c},"Auto-following new tab during recording"),await this.switchToPage({type:"INDEX",index:String(u)});break}n=c};t=setInterval(async()=>{if(!i){i=!0;try{await a()}catch(c){this.logger.error({err:c},"Error while checking pages during recording")}finally{i=!1}}},it);let l=async()=>{clearInterval(t)};e.addEventListener("abort",l,{once:!0})}async startRecording(e,t,n){this.logger.debug({isClickToRecord:n},"Starting recording mode in Chrome browser"),await this.startRecordingCrons(e),await this.page.evaluate(i=>{let a=window;a._MOMENTIC_RECORDING_ACTIVE=!0,a._MOMENTIC_CLICK_RECORD_ACTIVE=i},n),this.transformer=t,await this.injectKnowledgeBaseIntoBrowser(this.page);let o=async()=>{this.transformer=void 0,this.lastScreenshotForRecording=void 0;try{await this.page.evaluate(()=>{let i=window;i._MOMENTIC_RECORDING_ACTIVE=!1,i._MOMENTIC_CLICK_RECORD_ACTIVE=!1})}catch{}};e.addEventListener("abort",o,{once:!0})}async getSelectOptions(e){return await e.evaluate(n=>Array.from(n.querySelectorAll("option")).map(i=>({value:i.value,label:i.label})),void 0,{timeout:Z})}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 ja({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 C("UserInfrastructureError",`The page with URL ${Ot(i,50)} did not load within the configured timeout (${o}ms): ${l}`);if(!l.message.includes("detached"))throw l}try{await ja({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 dF.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 et({fn:()=>window.getCondensedHtmlTree(),root:e,arg:void 0,timeout:ge,waitForPageLoad:()=>this.waitForPageLoad(),codePath:"getting condensed HTML tree"});if(n)throw new Error(`Failed to process page HTML: ${n}`);if(!t)throw new C("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=ge){let i=await this.getActivePageOrFrame();return et({root:i,fn:e,arg:t,timeout:o,waitForPageLoad:()=>this.waitForPageLoad(),codePath:n})}async evaluateCodeInPage({code:e,fragment:t,context:n,timeoutMs:o=dn}){let i=WA(),a={code:e,fragment:t,context:n},{result:l}=await k(this.page.evaluate(i,a),{milliseconds:o,fallback:()=>{throw this.abortSignal?.throwIfAborted(),new C("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:ge});let n;try{n=await this.cdpClient.send({method:"DOM.getNodeForLocation",params:{x:e,y:t},timeout:Z})}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 C("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:Z,params:{highlightConfig:dw,backendNodeId:n.backendNodeId}}),async()=>{try{await this.cdpClient.send({timeout:Z,method:"Overlay.hideHighlight",params:{backendNodeId:n?.backendNodeId}})}catch{}}):async()=>{}}async clearAllCdpHighlights(){try{await this.cdpClient.send({method:"Overlay.hideHighlight",params:void 0,timeout:Z})}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[Kr],a=parseInt(i??"");if(!i||isNaN(a))throw new Error("No data-momentic-id was found on the DOM node");let l=e.locator(Sr(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 k(this.performTargetRedirectionHelper(e,t,n),{milliseconds:J})??{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();if(n===void 0&&(n=await e.boundingBox({timeout:J})??void 0),!n){let x=await Dr(e,t,500);t.error(`Attempted to click on element with no bounding box: ${x}`);return}let{x:i,y:a,width:l,height:c}=n,s=this.getViewport();if(i<0||a<0||!s||i+l>s.width||a+c>s.height){t.info("Skipping locator redirection because the element is outside the viewport");return}let u=await this.getActivePageOrFrame(),{dataMomenticId:d,mPathSelector:p,error:m,serializedElement:g,foundElementRelativePoint:h,force:f,logs:E}=await e.evaluate(x=>{let A=window;if(!A.performTargetRedirection)throw new Error("performTargetRedirection script is not defined");return A.performTargetRedirection(x)},void 0,{timeout:Z}),b=Date.now()-o;if(m){t.warn({error:m,serializedElement:g,duration:b,force:f,logs:E},"Got error from target redirection with bounding box");return}else{if(d)return t.info({newDataMomenticId:d,serializedElement:g,duration:b,force:f,logs:E},"Redirected target to new element with bounding box with data-momentic-id"),{locator:u.locator(Sr(d)),hints:{relativeXYToLocator:h,force:f}};if(p)return t.info({newMPathSelector:p,serializedElement:g,duration:b,force:f,logs:E},"Redirected target to new element with bounding box with mPath"),{locator:u.locator(p),hints:{relativeXYToLocator:h,force:f}};if(h)return t.info({foundElementRelativePoint:h,serializedElement:g,duration:b,force:f,logs:E},"Chose specific visible point on original element"),{locator:e,hints:{relativeXYToLocator:h,force:f}};if(f)return t.info({serializedElement:g,duration:b,force:f,logs:E},"Forcing click on original element"),{locator:e,hints:{force:f}}}}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:ge});if("error"in l&&l.error)throw l.error.startsWith(TA)?new Ms(l.error):l.error.startsWith(vA)?new _s(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:Z})}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!!ui}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,wm(e,this.debugData,i,{type:t,text:`[MOMENTIC] ${n}`,args:o})}async setFileChooserHandlerHelper({filePath:e,filename:t}){if(!Nc(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()||Fw(e),o=lF(e),i=gF(e),a=Ld[i];this.page.once("filechooser",async c=>{this.logger.info({filePath:e,fileName:n},"File chooser triggered");try{if(!Nc(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:pF.getType(e)||"application/octet-stream"},{timeout:pm})}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??$m();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??RA}get userBrowserSettings(){return mi(this.userControlledBrowserSettings)}get pageLoadTimeout(){return this.userControlledBrowserSettings.pageLoadTimeoutMs??li}get isInPageLoad(){return Object.values(this.pageLoadPromises).length>0}get devicePixelRatio(){return this.properties.systemDevicePixelRatio??1}get browserCrashDumpDir(){let e=xc();for(let t of e)if(!(!Nc(t)||!kw(t).isDirectory()||!["new","pending","completed"].some(o=>{let i=hF(t,o);return Nc(i)&&kw(i).isDirectory()&&cF(i).length>0})))return t}};import jF from"fetch-cookie";import{cloneDeep as cR}from"lodash-es";import{CookieJar as WF}from"tough-cookie";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 SF=["NAVIGATE","NEW_TAB","TAB","REFRESH","WAIT_FOR_URL"];async function zw({beforeUrl:r,beforePages:e,browser:t,command:n,logger:o}){if(SF.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 Y(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(oo(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}}}}async function Br(r,e={}){let t=await r.getBrowserState(e);return{serializedTree:t.serialize(e.serializationOpts),tree:t}}import{randomUUID as AF}from"crypto";var Gw={minChunkTokenCount:500,acceptableChunkTokenCount:3e3,maxChunkTokenCount:8e3,maxLineLength:4e3},Vw={minChunkTokenCount:5e3,acceptableChunkTokenCount:1e4,maxChunkTokenCount:3e4,maxLineLength:500},Hw=/<(\S+) id="(\d+)".*?>/g,yF=/(<\/(\S+)>)|(<(\S+).*?\/>)/g,jw=["h1","h2","section","footer","nav","aside","form","label","dialog"],bF=[...jw,"span","div","h3"],EF=["table","select","form","ul","ol","menu","pre","code","dialog"],TF=["table","form","dialog","nav","section","ul","select"];function Dc(r){return vF(r)}function vF({logger:r,serializedTree:e,options:t}){let{minChunkTokenCount:n,acceptableChunkTokenCount:o,maxChunkTokenCount:i,maxLineLength:a}=t,l=[],c=e.split(`
4118
4098
  `),s=0,u=[],d=0,p=[],m=[],g=!1;for(;s<c.length;){g&&(l.push({ids:p,content:u.join(`
4119
- `),tokenLength:d}),u=[],d=0,p=m.length?[m[m.length-1].id]:[],g=!1);let h=c[s],f=Lr(h);d+=f,h.length>a&&(h=h.slice(0,a));let C=Array.from(h.matchAll(Fw)).map(W=>W&&W.length>=3?{tagName:W[1],id:W[2]}:void 0).filter(W=>!!W),v=Array.from(h.matchAll(pF)).map(W=>W&&(W[2]||W[4])).filter(W=>!!W);v.reverse();let M=h.replace(/ id="[0-9]+"/g,"");u.push(M);for(let W of C)p.push(W.id),m.push(W);for(let W of v){let z=m[m.length-1];z&&z.tagName===W&&m.pop()}let w=m.some(W=>gF.includes(W.tagName)),D=c[s+1]??"",j=Lr(D),Q=Array.from(D.matchAll(Fw)).map(W=>W&&W.length>2?W[1]:void 0).filter(W=>!!W),pe=Q.some(W=>Hw.includes(W)),st=Q.some(W=>mF.includes(W));d+j>=i&&(g=!0),d>=n&&(pe&&!w||v.some(W=>hF.includes(W)))&&(g=!0),d>=o&&st&&!w&&(g=!0),s++}return u.length&&l.push({ids:p,content:u.join(`
4120
- `),tokenLength:d}),l.forEach((h,f)=>{let E=h.ids[0],b=h.ids[h.ids.length-1];r.debug({tokenLength:h.tokenLength,minId:E,maxId:b},`Chunk for page filtering (index ${f+1}/${l.length})`)}),{chunks:l}}var yF=75e4,Nc=3e5,bF=5e3;async function so(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=Lr(u);if(d>yF)try{let p=Lc({serializedTree:u,options:{minChunkTokenCount:1e4,maxChunkTokenCount:1e5,acceptableChunkTokenCount:5e4,maxLineLength:4e3},logger:i});s=await TF({...r,tokenLimit:Nc-1e4,chunks:p.chunks}),u=s.serialize();let m=Lr(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(Nc*Tn),u=s.serialize();let m=Lr(u);i.info({oldTokens:d,newTokens:m},"Filtered page using naive truncation"),d=m}if(d>Nc)try{if(o){let p=Lc({serializedTree:u,options:zw,logger:i}),m=SF();s=await F(EF({...r,chunks:p.chunks,callId:m}),{milliseconds:12e3,signal:c}),u=s.serialize();let g=Lr(u);i.info({oldTokens:d,newTokens:g,langfuseCallId:m},"Filtered page using AI chunk ranking"),d=g}else{let p=Lc({serializedTree:u,options:Bw,logger:i});s=await F(vF({...r,chunkResult:p,tokenLimit:4e4}),{milliseconds:12e3,signal:c}),u=s.serialize();let m=Lr(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(Nc*Tn),u=s.serialize(),i.info("Filtered page using naive truncation")}if(o&&d>bF&&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:me(i),abortSignal:c});if(i.info(p,"Got AI summaries"),p.category!=="OTHER"){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=Lr(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 EF({type:r,callId:e,chunks:t,description:n,fixtures:o,tree:i}){let{generator:a,signal:l,logger:c}=o,s=await a.rankChunksWithAi({chunks:t,description:n,type:r,softTokenLimit:4e4,hardTokenLimit:8e4,callId:e},{abortSignal:l,logger:c,loggerTags:me(c)}),u=[];return t.forEach((p,m)=>{s.indices.includes(m)&&(u=u.concat(p.ids))}),i.pruneUsingRelevantIds(new Set(u))}async function TF(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:me(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 vF(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:me(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 Km(r,e){if(!r.description)throw new x("UserConfigurationError","Cannot locate element with empty description");return Ur({action:async()=>AF(r,e),frameConfig:r.iframeUrl?{type:"url",url:r.iframeUrl}:void 0,browser:e.browser,logger:r.logger})}async function AF(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 em({orgId:p,s:E,context:n,localTools:g,signal:f,logger:s})),a&&(E=RF(E,a));let{serializedTree:C,tree:A}=await Rn(m,{allowNotActionableNodesOverride:u,filterByViewport:o,abortSignal:f,skipWait:i,logger:s}),v,M=Date.now(),w;for(;!v&&Date.now()-M<3e3;){f.throwIfAborted();try{v=await m.screenshot({clearHighlights:!0,respectActiveFrame:!0,retries:2})}catch(le){w=le}}if(!v)throw new x("ActionFailureError",`Failed to take screenshot of page to locate element. The page may be unresponsive, or your machine might be severely resource constrained. Error: ${w?.message}`);let D=C,j=!1,Q=`data:image/jpeg;base64,${v.toString("base64")}`;D=await so({type:"locator",description:E,screenshot:Q,serializedTree:C,options:{aiPageFiltering:c},tree:A,fixtures:{generator:h,signal:f,logger:s,orgId:p}}),D!==C&&(j=!0);let pe=await h.getElementLocation({browserState:D,goal:E,screenshot:Q,source:a,memory:b?l:void 0},{disableCache:t,abortSignal:f,loggerTags:me(s),useMemory:b});s.debug({usedRag:j,result:pe},"Got locator result");let st=pe.id>0;if(d?.details?.push({type:"AI_LOCATION",matched:st,pageState:D,ragUsed:j,thoughts:pe.thoughts}),!st)throw new Mo(`Could not find any relevant element: ${pe.thoughts}`,pe.updatedMemory?{type:"GCS_TRACES",traces:pe.updatedMemory}:void 0);let{resolution:W,target:z,frameConfig:re}=await m.createTargetFromA11yId({id:pe.id,requirements:pe.requirements,additionalElements:pe.additionalElements,description:E,targetSource:"AI",logger:s});if(W.a11yNode?.properties?.hidden&&W.a11yNode?.properties?.hidden!=="false")throw new x("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: ${W.displayString}`);return b&&(pe.updatedMemory?z.memory={type:"GCS_TRACES",traces:pe.updatedMemory}:l&&(z.memory=l)),{thoughts:pe.thoughts,target:z,resolution:W,frameConfig:re,screenshot:Q}}var wF=["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:"],Gw="<select> element:",Vw="text input or contenteditable element:",jw="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:",Ww="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:",qm=[Gw,Vw,jw,Ww,...wF];function $w(r,e){if(r===e)return!0;for(let t of qm){if(!r.startsWith(t))continue;let n=r.slice(t.length).trim();if(qm.some(o=>e.startsWith(o)&&e.slice(o.length).trim()===n)||n===e.trim())return!0}return!!qm.some(t=>e.startsWith(t)&&e.slice(t.length).trim()===r.trim())}function RF(r,e){if(!r||!e)return r;switch(e){case"SELECT_OPTION":return`${Gw} ${r}`;case"TYPE":return`${Vw} ${r}`;case"NEGATED_ELEMENT_VISIBLE_CHECK":return`${jw}
4121
- ${r}`;case"ELEMENT_CHECK":return`${Ww}
4122
- ${r}`;default:return r}}var CF=15;async function Dc({command:r,aiPageFiltering:e,logger:t,fixtures:n,source:o,useMemory:i,maxRetries:a=CF}){if(!r.assertion.trim())throw new x("ActionFailureError","Assertion command is missing the assertion content");let{browser:l}=n,c=r.timeout?r.timeout*1e3:l.smartWaitingTimeout,s=Sc(c),u=0,d=Date.now(),p,m,g;try{await Ur({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 X(s,n.abortSignal),h=Date.now();try{if(p=await Ur({action:async()=>{let E=await qw(l,t,n.abortSignal);return m&&m.serializedTree===E.serializedTree&&m.screenshotBuff.equals(E.screenshotBuff)?p:(m=E,Kw({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&&mc(r,p.updatedMemory,t),p?.success)break;throw p?.thoughts?new x("AssertionFailureError",p.thoughts):new x("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 Ur({action:async()=>Kw({command:r,state:await qw(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 x("AssertionFailureError",f)}return{...p,succeedImmediately:!1,urlAfterCommand:l.url()}}async function qw(r,e,t){let[n,o]=await Promise.all([Rn(r,{abortSignal:t,skipWait:!0,skipWaitForPageLoad:!0,logger:e}),r.screenshot({retries:1,respectActiveFrame:!0})]);return{...n,screenshotBuff:o}}async function Kw({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(),C=r.contextChoice??"MULTIMODAL",A=g;C!=="VISION_ONLY"&&(A=await so({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 v={goal:r.assertion,url:b,memory:o?r.cache?.memory:void 0,browserState:A,screenshot:E,contextChoice:C,source:c},w=await(C==="VISION_ONLY"?(D,j)=>d.getVisualAssertionResult(D,j):(D,j)=>d.getAssertionResult(D,j))(v,{useConsensus:n,attemptNumber:l,useMemory:o,disableCache:!!r.disableCache,abortSignal:p,logger:s,loggerTags:me(s)});return(w.result||i)&&w.relevantElements&&(m.relevantElementsSerialized=w.relevantElements.map(D=>u.getSerializedFormFromA11yId(D)).filter(D=>!!D),await xF(w.relevantElements,u,s)),{success:w.result,thoughts:w.thoughts,afterScreenshotOverride:f,updatedMemory:o?w.updatedMemory:void 0}}async function xF(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 F(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 Xw}from"lodash-es";async function Jw(r){let{command:e,timeoutMs:t,fixtures:n}=r,{abortSignal:o}=n,i=()=>oh(e.cache)?e.cache:void 0,a=i(),l=Xw(a),c=()=>{if(a=i(),!a)return;let h=Iv(l,a);a.target=h.target,a.updatedAt=h.updatedAt},s=Date.now(),u=0,d,p=500,m=!1;for(;u<2||Date.now()-s<t;){u++,u>1&&await X(p,o),o?.throwIfAborted(),a=i();let{result:h,elementWasFound:f}=await Yw({cacheToUse:a,params:r});if(d=h,m=f,h.success)break;c(),p=Math.min(p*2,1e4)}if(!d)throw new x("InternalPlatformError",`Failed to evaluate manual element assertion in ${t}ms.`);if(o?.throwIfAborted(),!d.success&&a?.target&&gs(a.target)){let h=a?.target?.memory?{target:{id:-1,memory:a.target.memory}}:void 0,{result:f}=await Yw({cacheToUse:h,params:r});d=f,d.success||c()}let g=i();return d.success&&g?.target&&!m&&(g.target=nm(g.target),g.updatedAt=new Date),d}async function Yw({cacheToUse:r,params:e}){let{command:t,disableCache:n,fixtures:o,tracer:i,targetingWrapper:a}=e,{logger:l}=o;if(t.target&&!Qr(t.target))throw new Error("Element assertion with x/y is not supported yet");let c=_F(t.assertion),s,u=!1,d=Xw(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=>MF(h.locator,e),options:{...t,allowNotActionableNodesOverride:!0,disableCache:n,memory:d?.target?.memory,disableGlobalLocatorRedirect:!0,source:Xi(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 x)||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 MF(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:Ot(c,500,!0)},!kc(c,n.value,n.operation,!!n.negated)){let s=n.negated?eo[n.operation]:to[n.operation];o=!1,i=new x("AssertionFailureError",`The content ${s} '${n.value}': ${c}`)}break}case"ELEMENT_ATTRIBUTE":{a={elementOuterHtml:Ot(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 x("AssertionFailureError",`The element does not have an attribute named ${n.attr}: ${s}`),o=!1;break}if(!kc(c,n.value,n.operation,!!n.negated)){let s=n.negated?eo[n.operation]:to[n.operation];o=!1,n.operation==="EXISTS"?i=new x("AssertionFailureError",`The attribute ${n.attr} ${s}`):i=new x("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},en*1e3);break}case"EDITABLE":{o=await r.isEditable({timeout:en*1e3});break}case"EXISTS":{o=!0;break}case"ENABLED":{o=await r.isEnabled({timeout:en*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?Ov[n.condition]:Lv[n.condition];i=new x("AssertionFailureError",`The element ${c}`)}break}case"ELEMENT_NAME":{let c=await r.evaluate(s=>s.tagName);if(!kc(c,n.value,n.operation,!!n.negated)){let s=n.negated?eo[n.operation]:to[n.operation];o=!1,i=new x("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(!kc(c,n.value,n.operation,!!n.negated)){let s=n.negated?eo[n.operation]:to[n.operation];o=!1,n.operation==="EXISTS"?i=new x("AssertionFailureError",`The style property ${n.property} ${s}`):i=new x("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 kc(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 _F(r){return r.type==="ELEMENT_EXISTENCE"&&r.negated&&(r.condition==="EXISTS"||r.condition==="VISIBLE")}function Zw(r){return r.type==="ELEMENT_EXISTENCE"&&r.negated&&r.condition==="EXISTS"}import{Jimp as PF}from"jimp";async function Ka(r,e){let t=await r.screenshot(e),n=await PF.fromBuffer(t);return{buffer:t,width:Math.ceil(n.bitmap.width??0),height:Math.ceil(n.bitmap.height??0)}}import{Jimp as Qw}from"jimp";import Ym from"jpeg-js";import IF from"pixelmatch";async function eR({ctx:r,tracer:e,command:t,disableCache:n,browser:o,targetingWrapper:i,logger:a,screenshotStorage:l}){if(t.target&&!Qr(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 Q=>Ka(o,{locator:Q.locator,...c}),options:{...t,disableCache:n,disableGlobalLocatorRedirect:!0,memory:t.cache?.target?.memory,targetName:"target"}})).result:s=await Ka(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 ae=`${s.width}x${s.height}`,Q=`${u.width}x${u.height}`;return{fail:!0,thoughts:`Current screenshot (${ae}) does not match saved screenshot dimensions (${Q}) - 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 Qw.fromBuffer(s.buffer),p={width:s.width,height:s.height},m=await Qw.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),C=Math.abs(p.width-g.width);if(f>E){let ae=d.cover({w:g.width,h:g.height});s.buffer=await ae.getBuffer("image/jpeg"),h="current",s.width=g.width,s.height=g.height}else if(E>f){let ae=m.cover({w:p.width,h:p.height});u.buffer=await ae.getBuffer("image/jpeg"),h="saved"}let A={data:Buffer.alloc(s.width*s.height*4),width:s.width,height:s.height},v=t.threshold??.1,w=IF(Ym.decode(u.buffer).data,Ym.decode(s.buffer).data,A.data,s.width,s.height,{threshold:v,diffColorAlt:[0,255,0]})/(s.width*s.height)*100,D=w>v*100,j=`Visual diff of ${w.toFixed(2)}% detected, which is ${D?"over":"under"} the threshold of ${v*100}%.`;if(h&&(j+=` The ${h} screenshot was cropped since it was taller by ${b} pixels and wider by ${C} pixels.`),D)throw new x("ActionFailureError",j);return{fail:D,thoughts:j,beforeScreenshotOverride:s.buffer,afterScreenshotOverride:Ym.encode(A,75).data,succeedImmediately:!1,urlAfterCommand:o.url()}}var OF=3e4;async function Uc({command:r,logger:e,baseUrl:t,fetchImplementation:n=fetch}){let o=r.timeout??OF/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(ii(r.url)&&(c=r.url),t&&ai(r.url,t)&&(c=new URL(r.url,t).toString()),!c)throw new x("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 F((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 x("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 x("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 LF=5e3;async function nR({timeout:r=en,...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 tR(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 X(l,e.signal),l=Math.min(Math.floor(l*1.5),LF);else return i}return i=await tR(e),i}async function tR({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(rR,{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(rR,{value:r.value,negated:!!r.negated,returnHtml:!0},"checking page content"));if(!i){let c=r.negated?eo.CONTAINS:to.CONTAINS;a=new x("AssertionFailureError",`The page ${c} '${r.value}'.`),o=l}}catch(l){a=new x("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 rR({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 NF=3e4;async function oR({command:r,logger:e,baseUrl:t,fetchImplementation:n=fetch}){let o=r.timeout??NF/1e3,i=new AbortController,a=Object.fromEntries(Object.entries(r.headers||{}).filter(([d,p])=>d&&p));a["Content-Type"]="application/json";let l;if(ii(r.url)&&(l=r.url),t&&ai(r.url,t)&&(l=new URL(r.url,t).toString()),!l)throw new x("ActionFailureError",`Invalid URL: ${r.url}`);let s=await F((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 x("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 x("ActionFailureError",`GraphQL request failed with status ${s.status}: ${p}`)}throw d?.errors?.length&&d?.errors[0]?.message?new x("ActionFailureError",`GraphQL request failed with status ${s.status}: ${d.errors[0].message}`):new x("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 Fc=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([Rn(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 so({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:{...me(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([Rn(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 so({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:{...me(a)},langfuseSessionId:l})}catch(g){throw new x("InternalWebAgentError",`Error generating command: ${g instanceof Error?g.message:g}`,{errOptions:{cause:g}})}}async getBrowserState(e){return Rn(this.browser,e)}async locateElement(e){return await Km({...e,aiPageFiltering:!!this.options?.aiPageFiltering},this.getControllerFixtures())}async locateElementWithSelector(e,t){return Ur({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 x("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 Ur({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&&Uu(i)){t.warn({err:i},"Invalid mpath error, retrying element targeting command");continue}if(!this.browser.userBrowserSettings.visualActions&&(Bu(i)||Fu(i))){t.warn({err:i},"Invalid momentic id error, retrying element targeting command");continue}if(zu(i)){t.warn({err:i},"Invalid backend node id error, retrying element targeting command");continue}if(i instanceof vr&&i.retryableWithAI){t.warn({err:i},"Element cache disqualification error, retrying element targeting command");continue}throw i}throw n instanceof x?n:new x("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 x("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 X(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=iR(e.cache);if((!b||s)&&!Eu(o))throw new x("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&&!$w(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 C=v=>!!v&&gs(v),A=!0;if(!C(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 X(this.browser.smartWaitingTimeout,this.executeAbortController.signal),f--;let v;try{v=await Km({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(D){if(D instanceof Mo&&D.updatedLocatorMemory){let j={id:-1,...i,memory:D.updatedLocatorMemory};pc({cmd:c,key:d,newTarget:j,logger:g,updatedWithAI:!0})}throw new x("ActionFailureError",D.message)}v.frameConfig&&this.browser.setActiveFrameConfig(v.frameConfig);let M=l.disableGlobalLocatorRedirect?{locator:v.resolution.locator}:await this.attemptLocatorRedirect(v.resolution.locator,g),w=await a(M);return pc({cmd:c,key:d,newTarget:v.target,logger:g,updatedWithAI:!0}),p&&(n.recordTargetAutoHeal({healType:"AI"}),v.target.targetSource="AI_HEALED",v.target.targetUpdateTime=new Date().toUTCString(),v.target.targetUpdateLoggerTags=me(g)),{result:w,elementInteractedDisplayString:v.resolution.displayString,thoughts:v.thoughts}}try{let v=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(v.locator);let M=l.disableGlobalLocatorRedirect?{locator:v.locator}:await this.attemptLocatorRedirect(v.locator,g),w=await a(M);if(At.increment("cache_target_resolution_v2",1,["outcome:hit","platform:web",`hasRequirements:${!!b.requirements}`,`hasAdditionalElements:${!!b.additionalElements}`,`orgId:${this.orgId}`,"cliVersion:0.4.0"]),pc({cmd:c,key:d,newTarget:b,logger:g,updatedWithAI:!1}),A){let D=v.decisions.filter(j=>j.matched);if(D.length!==1)g.warn({decisions:v.decisions},"Expected exactly 1 matching method for element location, got more or less");else{let j=D[0].type;n.recordTargetAutoHeal({healType:j})}}return{result:w,elementInteractedDisplayString:v.displayString}}catch(v){this.throwIfClosed(),At.increment("cache_target_resolution_v2",1,["outcome:miss","platform:web",`hasRequirements:${!!b.requirements}`,`hasAdditionalElements:${!!b.additionalElements}`,`orgId:${this.orgId}`,"cliVersion:0.4.0"]);let M=!1;if((v instanceof vr||Uu(v)||Bu(v)||zu(v)||rf(v)||Fu(v))&&(M=!0),v instanceof x&&!M)throw g.error({err:v},"Failed to execute action with cached target (fatal)"),v;if(f>0&&o){g.info({err:v},"Failed to execute action with cached target, retrying with AI");let w;return b.memory&&Zg(b.memory)&&(w=b.memory),this.wrapElementTargetingCommand({ctx:t,tracer:n,command:c,target:o,cache:void 0,originalCache:i,action:a,options:{...l,memory:w,retriesWithAI:f,targetHealingInProgress:!0}})}throw new x("ActionFailureError",v.message,{errOptions:{cause:v}})}}async attemptLocatorRedirect(e,t){return this.browser.userBrowserSettings.globalLocatorRedirect!==!1?this.browser.performTargetRedirection(e,t):{locator:e}}async screenshotWithDimensions(e){return Ka(this.browser,e)}async executePresetCommand(e,t,n,o,i){this.options?.slowMoMs&&await X(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 x("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&&Eh(n)?await this.browser.waitForDOMStability({timeout:ge}):!this.browser.userBrowserSettings.visualActions&&["PRESS","TYPE"].includes(n.type)&&await this.browser.waitForDOMStability({timeout:Z}),this.options?.autoFollowNewTabs&&await Uw({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{dc(n,c)}}createCallbacksForBrowser(e){return{createIsolatedFolder:()=>bm(e)}}async resolveCommandTemplateStrings(e,t){return uc({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()?Dc({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 x("ActionFailureError","Missing assertion");if(n.timeout&&n.timeout>1800)throw new x("AssertionFailureError",`AI check timeout of ${n.timeout} exceeds the maximum allowed value of 30 minutes.`);return Dc({command:n,fixtures:this.getControllerFixtures(e),useMemory:this.shouldUseMemory(),aiPageFiltering:!!this.options?.aiPageFiltering,logger:a})}case"AI_EXTRACT":{if(!n.goal.trim())throw new x("ActionFailureError","Cannot perform AI extraction without goal");if(n.schema){let f=Gy(n.schema);if(f)throw new x("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:me(a)});if(f.result==="NOT_FOUND")throw new x("ActionFailureError","No relevant data found for extraction goal on this page");if(f.thoughts?.includes("MaxGenerationLengthExceededError"))throw new x("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 x("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 x("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(!ii(n.url)&&!ai(n.url,this.browser.baseUrl))throw new x("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&&Er(n.target))await this.browser.hoverUsingVisualCoordinates(n.target.pixels);else if(n.target&&n.target.elementDescriptor.trim()){let{elementInteractedDisplayString:b,thoughts:C}=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=C}let f=this.browser.getViewport()?.height??an.height,E=this.browser.getViewport()?.width??an.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 x("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 x("UserConfigurationError",`Wait timeout of ${n.delay} seconds exceeds the maximum allowed value of 30 minutes`);let s=n.delay*1e3;await X(s,this.executeAbortController.signal);break;case"REFRESH":await this.browser.refresh({loadTimeoutMs:n.loadTimeout?n.loadTimeout*1e3:void 0});break;case"CLICK":{if(Er(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:C=>this.browser.click(C,this.createCallbacksForBrowser(this.orgId),n),options:{disableCache:i,targetName:"target",...n}}),b={urlAfterCommand:this.browser.url(),succeedImmediately:!1,elementInteracted:h,thoughts:E,data:f.downloadedFile?{downloadedFile:f.downloadedFile}:void 0};return bc(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(Er(n.fromTarget)&&Er(n.toTarget)){await this.browser.dragAndDropUsingVisualCoordinates(n.fromTarget.pixels,n.toTarget.pixels,{hoverSeconds:n.hoverSeconds});break}if(Er(n.fromTarget)||Er(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 x("ActionFailureError",`Invalid pixel values passed to mouse drag command: (${n.deltaX}, ${n.deltaY})`);if(n.target&&Er(n.target)){await this.browser.mouseDragUsingVisualCoordinates(g,h,f,n.target.pixels,{force:n.force});break}let E,b,C;if(n.target?.elementDescriptor){let{elementInteractedDisplayString:A,result:v,thoughts:M}=await this.wrapElementTargetingCommand({ctx:e,tracer:t,command:n,target:n.target,cache:n.cache?.target,action:async w=>w.locator,options:{disableCache:i,targetName:"target",...n}});E=v,b=A,C=M}return await this.browser.mouseDrag(g,h,f,E,{force:n.force}),{succeedImmediately:!1,urlAfterCommand:this.browser.url(),elementInteracted:b,thoughts:C}}case"SELECT_OPTION":{if(!Qr(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:Xi(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 Or({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 x("ActionFailureError",h instanceof Error?h.message:`${h}`,{errOptions:{cause:h}})}try{JSON.stringify(g)}catch(h){throw new x("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&&Er(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=iR(n.target),b=this.browser.userBrowserSettings.globalLocatorRedirect===void 0||this.browser.userBrowserSettings.globalLocatorRedirect==="always";if(E){let{elementInteractedDisplayString:A,thoughts:v}=await this.wrapElementTargetingCommand({ctx:e,tracer:t,command:n,target:E,cache:n.cache?.target,action:M=>this.browser.typeIntoTarget(n.value,M,{force:n.force,clearContent:n.clearContent,forceClearContent:n.forceClearContent,delay:n.delay,pressEnter:n.pressEnter,relativePosition:n.relativePosition}),options:{...n,targetName:"target",disableCache:i,disableGlobalLocatorRedirect:!b,source:Xi(n)}});h=A,f=v}else await this.browser.type(n.value,{force:n.force,clearContent:n.clearContent,forceClearContent:n.forceClearContent,delay:n.delay,pressEnter:n.pressEnter},!0);let C={urlAfterCommand:this.browser.url(),succeedImmediately:!1,elementInteracted:h,thoughts:f};return bc(g,C.urlAfterCommand)&&(C.succeedImmediately=!0,C.succeedImmediatelyReason="URL changed"),C}case"HOVER":{if(Er(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(!Qr(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&&!Qr(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 bc(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 kF,h=DF(fetch,g),f;try{f=new URL(n.url).hostname}catch{}return{data:{...await Uc({command:n,baseUrl:this.browser.baseUrl,logger:a,fetchImplementation:h}),cookies:Hs(g,f)},succeedImmediately:!1,urlAfterCommand:this.browser.url()}}case"GRAPHQL_REQUEST":return{data:await oR({command:n,baseUrl:this.browser.baseUrl,logger:a}),succeedImmediately:!1,urlAfterCommand:this.browser.url()};case"VISUAL_DIFF":return eR({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 MA({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 x("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 Or({orgId:this.orgId,code:n.storageState,fragment:!1,context:o,logger:a,localTools:this.localCodeEvalTools,signal:this.executeAbortController.signal}),typeof g!="object")throw new x("ActionFailureError",`Credentials must evaluate to an object (received ${typeof g} instead)`);let h;try{h=uS.optional().parse(g)}catch(f){throw new x("ActionFailureError",`Credentials provided do not follow the required format: ${f}`)}await this.browser.loadAuthState(h);break}case"ELEMENT_CHECK":{let g=(n.timeout??en)*1e3,h=this.generator.getAgentConfig()?.assertion;if(Zw(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 Dc({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&&mc(n,E.cache?.memory.traces,a)}}let f=await Jw({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 Ur({action:async()=>nR({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 vn(n.requestMatcher),h=this.browser.registerRequestListener(g);return this.registeredListeners[n.key]=h.then(async f=>await Cm(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 x("ActionFailureError",`No listener registered with key: ${n.key}`);let h=n.timeout??10;return{data:await F(g,{milliseconds:h*1e3,message:`Request listener timed out after ${h} seconds`}),succeedImmediately:!1,urlAfterCommand:this.browser.url()}}case"RECORD_REQUESTS":{let g=new vn(n.requestMatcher);return this.recordedRequests[n.key]={},this.browser.registerRequestRecorder(n.key,g,{onRequestStart:(h,f)=>{this.recordedRequests[n.key][h]=wc(f)},onRequestComplete:(h,f)=>{this.recordedRequests[n.key][h]=wc(f)}}),{succeedImmediately:!1,urlAfterCommand:this.browser.url()}}case"GET_RECORDED_REQUESTS":{let g=this.recordedRequests[n.key];if(!g)throw new x("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 vn(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 vn(n.requestMatcher),async(h,f)=>{let E=await Or({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=wS.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:me(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 Pc({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:me(this.logger)})}async getFailureRecoveryPlan(e){return this.generator.getFailureRecoveryPlan(e,{disableCache:!0,abortSignal:this.executeAbortController.signal,loggerTags:me(this.logger)})}};import{cloneDeep as UF}from"lodash-es";import uR from"truncate-json";var aR=1e3,sR=5e6,FF=5*1024*1024;function dR(r,e){for(let t=0;t<r.length;t++){let n=r[t];try{if(n.data){let{jsonString:o}=uR(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":lR(n);break;case"MOBILE_AI_ACTION_STEP":case"MOBILE_MODULE_STEP":lR(n),dR(n.steps,e);break;default:{let o=n;throw new Error("If Typescript complains about the line below, you missed a case or break in the switch above")}}}}function lR(r){if(r.type==="MOBILE_PRESET_STEP"){let e=r.command;"cache"in e&&e.cache&&(e.cache=void 0)}}function cR(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 Bc(r,e){let t=UF(r);if(dR(t,e),t.length>aR)return e.error("Database content violation: results too long, truncating before insertion"),t.slice(0,aR);let n=cR(t,e);if(n.length>sR)for(e.error({serializedLength:n.length,resultsArrayLength:t.length},"Database content violation: results too large, truncating before insertion");n.length>sR;)t.pop(),n=cR(t,e);let{jsonString:o}=uR(n,FF);try{return tr.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}}import{AsyncLocalStorage as BF}from"async_hooks";var Ya=new BF;function zF(r){Ya.enterWith({activeTracers:[r]})}function HF(r,e){let t=Ya.getStore()?.activeTracers;if(!t)return e();t.push(r);try{return e()}finally{t.pop()}}async function GF(r,e){let t=Ya.getStore()?.activeTracers;if(!t)return e();let n=[...t,r];return Ya.run({activeTracers:n},e)}var Kr={globalAls:Ya,initializeRootTracerContext:zF,withChildTracer:HF,withChildTracerAsync:GF};var lo=class r{spans;parentSection;finished=!1;startTime;endTime;constructor(e){this.startTime=e?.startTime??Date.now(),this.spans=e?.subSpans??[],this.parentSection=e}startSection(e,t){let n={type:"SECTION",name:e,startTime:Date.now(),endTime:void 0,subSpans:[],attributes:{}},o=new r(n);try{return Kr.withChildTracer(o,()=>t(o,n))}catch(i){throw n.error=i instanceof Error?i.message:String(i),i}finally{o.finish(),this.addSpan(n)}}async startAsyncSection(e,t,n){let o={type:"SECTION",name:e,startTime:Date.now(),endTime:void 0,subSpans:[],attributes:{}},i=new r(o);this.addSpan(o);try{let a;return n?.signal||n?.timeoutMs?a=await Kr.withChildTracerAsync(i,()=>F(t(i,o),{milliseconds:n?.timeoutMs??1/0,signal:n?.signal,message:n?.timeoutMsg})):a=await Kr.withChildTracerAsync(i,()=>t(i,o)),a}catch(a){throw o.error=a instanceof Error?a.message:String(a),a}finally{i.finish()}}finish(){if(!this.finished){this.endTime=Date.now();for(let e of this.spans)e.endTime||(e.endTime=this.endTime,e.durationMs=e.endTime-e.startTime);this.parentSection&&(this.parentSection.endTime=this.endTime,this.parentSection.durationMs=this.parentSection.endTime-this.parentSection.startTime),this.finished=!0}}addSpan(e){this.spans.push(e)}startSpan(e,t,...n){let o={type:e,startTime:Date.now(),endTime:void 0,attributes:{}},i=n[0]??void 0;Object.assign(o,i??{}),this.addSpan(o);let a;try{a=t(o),o.endTime=Date.now(),o.durationMs=o.endTime-o.startTime}catch(l){throw o.error=l instanceof Error?l.message:String(l),o.endTime=Date.now(),o.durationMs=o.endTime-o.startTime,l}return a}async startAsyncSpan(e,t,...n){let o={type:e,startTime:Date.now(),endTime:void 0,attributes:{}},i=n[0]??void 0;Object.assign(o,i??{}),this.addSpan(o);let a;try{i?.signal||i?.timeoutMs?a=await F(t(o),{milliseconds:i?.timeoutMs??1/0,signal:i?.signal}):a=await t(o),o.endTime=Date.now(),o.durationMs=o.endTime-o.startTime}catch(l){throw o.error=l instanceof Error?l.message:String(l),o.endTime=Date.now(),o.durationMs=o.endTime-o.startTime,l}return a}getRootSpan(){return this.finished||this.finish(),{type:"SECTION",name:"root step span",startTime:this.startTime,endTime:this.endTime,subSpans:this.spans,attributes:{},durationMs:this.endTime?this.endTime-this.startTime:void 0}}};function ve(){let r=Kr.globalAls.getStore()?.activeTracers,e;return!r||r.length===0?e=void 0:e=r[r.length-1],e||new lo}async function pR(r){let{driver:e,abortSignal:t,logger:n,packageName:o}=r,i;try{i=await F(e.execute("mobile: shell",{command:"dumpsys",args:["activity","recents"]}),{signal:t,milliseconds:1e4})}catch(l){t?.throwIfAborted(),n.warn({err:l,packageName:o},"Failed to read recents output while removing package");return}if(typeof i!="string"){n.warn({packageName:o,outputType:typeof i},"Unexpected dumpsys output when removing package from recents");return}let a=VF(i,o);if(a.length!==0)for(let l of a){t?.throwIfAborted();try{await e.execute("mobile: shell",{command:"am",args:["stack","remove",l.toString()]}),n.info({packageName:o,taskId:l},"Removed task from recents")}catch(c){t?.throwIfAborted(),n.warn({err:c,packageName:o,taskId:l},"Failed to remove task from recents")}}}function VF(r,e){let t=r.split("Task{");if(t.length<=1)return[];let n=new Set;for(let o of t.slice(1)){let i=`Task{${o}`;if(!i.includes(e)||i.includes("app.lawnchair/.LawnchairLauncher"))continue;let a=i.match(/taskId=(\d+)/);if(!a)continue;let[,l]=a;if(!l)continue;let c=Number.parseInt(l,10);Number.isNaN(c)||n.add(c)}return Array.from(n)}import{mkdirSync as sB}from"fs";import{tmpdir as lB}from"os";import ER from"path";import{diff as iB}from"deep-object-diff";import{cloneDeep as aB}from"lodash-es";import hR from"fontoxpath";import jF from"@prettier/plugin-xml";import WF from"prettier";import{DOMParser as $F,XMLSerializer as qF}from"slimdom";var KF=new Set(["android.webkit.webview","com.facebook.react.views.webview.reactwebview","com.tencent.smtt.sdk.webview","com.tencent.smtt.sdk.x5webview","org.xwalk.core.xwalkview","com.uc.webview.export.webview"]);function Xa(r){let e=r.toLowerCase();return e.endsWith("webview")||KF.has(e)}function YF(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 XF=new Set(["index","package","a11y-important","screen-reader-focusabl"]),JF=new Set(["selected","checked","checkable","clickable","enabled","focusable","focused","long-clickable","password","scrollable","selected","showing-hint","context-clickable","multiline","text-entry-key","heading","dismissable","screen-reader-focusable","content-invalid","a11y-focused"]),ZF=new Set(["text","hint"]),QF=new Set(["live-region","drawing-order"]),eB=new Set(["displayed","enabled"]);function tB(r,e){let t={};for(let[n,o]of Object.entries(e))XF.has(n)||n==="class"&&r===o||n==="focusable"&&o==="true"&&e.clickable==="true"||JF.has(n)&&o==="false"||ZF.has(n)&&o===""||eB.has(n)&&o==="true"||QF.has(n)&&o==="0"||n!=="id"&&(t[n]=o);return t}function mR(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=tB(e.tagName,s);for(let[p,m]of Object.entries(u))t.setAttribute(p,m);if(o.set(c,e),i.set(c,t),Xa(e.tagName)){let p=l?.injectedWebviewContent??"";if(!l?.disableMomenticAccessibilityTree&&p.trim().length>0){for(;t.firstChild;)t.removeChild(t.firstChild);p.trim().length>0&&t.appendChild(n.createCDATASection(`
4099
+ `),tokenLength:d}),u=[],d=0,p=m.length?[m[m.length-1].id]:[],g=!1);let h=c[s],f=yr(h);d+=f,h.length>a&&(h=h.slice(0,a));let x=Array.from(h.matchAll(Hw)).map(W=>W&&W.length>=3?{tagName:W[1],id:W[2]}:void 0).filter(W=>!!W),v=Array.from(h.matchAll(yF)).map(W=>W&&(W[2]||W[4])).filter(W=>!!W);v.reverse();let _=h.replace(/ id="[0-9]+"/g,"");u.push(_);for(let W of x)p.push(W.id),m.push(W);for(let W of v){let z=m[m.length-1];z&&z.tagName===W&&m.pop()}let R=m.some(W=>EF.includes(W.tagName)),D=c[s+1]??"",j=yr(D),Q=Array.from(D.matchAll(Hw)).map(W=>W&&W.length>2?W[1]:void 0).filter(W=>!!W),me=Q.some(W=>jw.includes(W)),st=Q.some(W=>bF.includes(W));d+j>=i&&(g=!0),d>=n&&(me&&!R||v.some(W=>TF.includes(W)))&&(g=!0),d>=o&&st&&!R&&(g=!0),s++}return u.length&&l.push({ids:p,content:u.join(`
4100
+ `),tokenLength:d}),l.forEach((h,f)=>{let E=h.ids[0],b=h.ids[h.ids.length-1];r.debug({tokenLength:h.tokenLength,minId:E,maxId:b},`Chunk for page filtering (index ${f+1}/${l.length})`)}),{chunks:l}}var wF=75e4,kc=3e5;async function lo(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=yr(u);if(d>wF)try{let p=Dc({serializedTree:u,options:{minChunkTokenCount:1e4,maxChunkTokenCount:1e5,acceptableChunkTokenCount:5e4,maxLineLength:4e3},logger:i});s=await CF({...r,tokenLimit:kc-1e4,chunks:p.chunks}),u=s.serialize();let m=yr(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(kc*An),u=s.serialize();let m=yr(u);i.info({oldTokens:d,newTokens:m},"Filtered page using naive truncation"),d=m}if(d>kc)try{if(o){let p=Dc({serializedTree:u,options:Vw,logger:i}),m=AF();s=await k(RF({...r,chunks:p.chunks,callId:m}),{milliseconds:12e3,signal:c}),u=s.serialize();let g=yr(u);i.info({oldTokens:d,newTokens:g,langfuseCallId:m},"Filtered page using AI chunk ranking"),d=g}else{let p=Dc({serializedTree:u,options:Gw,logger:i});s=await k(xF({...r,chunkResult:p,tokenLimit:4e4}),{milliseconds:12e3,signal:c}),u=s.serialize();let m=yr(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(kc*An),u=s.serialize(),i.info("Filtered page using naive truncation")}return u}async function RF({type:r,callId:e,chunks:t,description:n,fixtures:o,tree:i}){let{generator:a,signal:l,logger:c}=o,s=await a.rankChunksWithAi({chunks:t,description:n,type:r,softTokenLimit:4e4,hardTokenLimit:8e4,callId:e},{abortSignal:l,logger:c,loggerTags:pe(c)}),u=[];return t.forEach((p,m)=>{s.indices.includes(m)&&(u=u.concat(p.ids))}),i.pruneUsingRelevantIds(new Set(u))}async function CF(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 xF(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 Ym(r,e){if(!r.description)throw new C("UserConfigurationError","Cannot locate element with empty description");return cr({action:async()=>MF(r,e),frameConfig:r.iframeUrl?{type:"url",url:r.iframeUrl}:void 0,browser:e.browser,logger:r.logger})}async function MF(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 Va({orgId:p,s:E,context:n,localTools:g,signal:f,logger:s})),a&&(E=PF(E,a));let{serializedTree:x,tree:A}=await Br(m,{allowNotActionableNodesOverride:u,filterByViewport:o,abortSignal:f,skipWait:i,logger:s}),v,_=Date.now(),R;for(;!v&&Date.now()-_<3e3;){f.throwIfAborted();try{v=await m.screenshot({clearHighlights:!0,respectActiveFrame:!0,retries:2})}catch(le){R=le}}if(!v)throw new C("ActionFailureError",`Failed to take screenshot of page to locate element. The page may be unresponsive, or your machine might be severely resource constrained. Error: ${R?.message}`);let D=x,j=!1,Q=`data:image/jpeg;base64,${v.toString("base64")}`;D=await lo({type:"locator",description:E,screenshot:Q,serializedTree:x,options:{aiPageFiltering:c},tree:A,fixtures:{generator:h,signal:f,logger:s,orgId:p}}),D!==x&&(j=!0);let me=await h.getElementLocation({browserState:D,goal:E,screenshot:Q,source:a,memory:b?l:void 0},{disableCache:t,abortSignal:f,loggerTags:pe(s),useMemory:b});s.debug({usedRag:j,result:me},"Got locator result");let st=me.id>0;if(d?.details?.push({type:"AI_LOCATION",matched:st,pageState:D,ragUsed:j,thoughts:me.thoughts}),!st)throw new _o(`Could not find any relevant element: ${me.thoughts}`,me.updatedMemory?{type:"GCS_TRACES",traces:me.updatedMemory}:void 0);let{resolution:W,target:z,frameConfig:re}=await m.createTargetFromA11yId({id:me.id,requirements:me.requirements,additionalElements:me.additionalElements,description:E,targetSource:"AI",logger:s});if(W.a11yNode?.properties?.hidden&&W.a11yNode?.properties?.hidden!=="false")throw new C("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: ${W.displayString}`);return b&&(me.updatedMemory?z.memory={type:"GCS_TRACES",traces:me.updatedMemory}:l&&(z.memory=l)),{thoughts:me.thoughts,target:z,resolution:W,frameConfig:re,screenshot:Q}}var _F=["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:"],Ww="<select> element:",$w="text input or contenteditable element:",qw="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:",Kw="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:",Km=[Ww,$w,qw,Kw,..._F];function Yw(r,e){if(r===e)return!0;for(let t of Km){if(!r.startsWith(t))continue;let n=r.slice(t.length).trim();if(Km.some(o=>e.startsWith(o)&&e.slice(o.length).trim()===n)||n===e.trim())return!0}return!!Km.some(t=>e.startsWith(t)&&e.slice(t.length).trim()===r.trim())}function PF(r,e){if(!r||!e)return r;switch(e){case"SELECT_OPTION":return`${Ww} ${r}`;case"TYPE":return`${$w} ${r}`;case"NEGATED_ELEMENT_VISIBLE_CHECK":return`${qw}
4101
+ ${r}`;case"ELEMENT_CHECK":return`${Kw}
4102
+ ${r}`;default:return r}}var IF=15;async function Uc({command:r,aiPageFiltering:e,logger:t,fixtures:n,source:o,useMemory:i,maxRetries:a=IF}){if(!r.assertion.trim())throw new C("ActionFailureError","Assertion command is missing the assertion content");let{browser:l}=n,c=r.timeout?r.timeout*1e3:l.smartWaitingTimeout,s=bc(c),u=0,d=Date.now(),p,m,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 Y(s,n.abortSignal),h=Date.now();let f=!1;try{if(p=await cr({action:async()=>{let b=await Xw(l,t,n.abortSignal);return m&&m.serializedTree===b.serializedTree&&m.screenshotBuff.equals(b.screenshotBuff)?(f=!0,p):(m=b,Jw({command:r,state:b,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&&hc(r,p.updatedMemory,t),p?.success)break;throw p?.thoughts?new C("AssertionFailureError",p.thoughts):new C("InternalPlatformError","No thoughts were provided for AI assertion failure")}catch(E){n.abortSignal.throwIfAborted(),g=E instanceof Error?E:new Error(`${E}`),f?t.info(`AI check attempt ${u} failed (re-used previous result)`):t.info({err:E},`AI check assert attempt ${u} failed, retrying...`)}finally{u++}}if(!p?.success)try{p=await cr({action:async()=>Jw({command:r,state:await Xw(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 C("AssertionFailureError",f)}return{...p,succeedImmediately:!1,urlAfterCommand:l.url()}}async function Xw(r,e,t){let[n,o]=await Promise.all([Br(r,{abortSignal:t,skipWait:!0,skipWaitForPageLoad:!0,logger:e}),r.screenshot({retries:1,respectActiveFrame:!0})]);return{...n,screenshotBuff:o}}async function Jw({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(),x=r.contextChoice??"MULTIMODAL",A=g;x!=="VISION_ONLY"&&(A=await lo({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 v={goal:r.assertion,url:b,memory:o?r.cache?.memory:void 0,browserState:A,screenshot:E,contextChoice:x,source:c},R=await(x==="VISION_ONLY"?(D,j)=>d.getVisualAssertionResult(D,j):(D,j)=>d.getAssertionResult(D,j))(v,{useConsensus:n,attemptNumber:l,useMemory:o,disableCache:!!r.disableCache,abortSignal:p,logger:s,loggerTags:pe(s)});return(R.result||i)&&R.relevantElements&&(m.relevantElementsSerialized=R.relevantElements.map(D=>u.getSerializedFormFromA11yId(D)).filter(D=>!!D),await OF(R.relevantElements,u,s)),{success:R.result,thoughts:R.thoughts,afterScreenshotOverride:f,updatedMemory:o?R.updatedMemory:void 0}}async function OF(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 k(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}}}var LF=75e4,Fc=class extends Error{constructor(){super("The page content exceeds the maximum token limit for AI smart waiting."),this.name="ExceededMaxAISmartWaitingTokensError"}};async function Zw(r,e){let{logger:t}=r,{abortSignal:n,browser:o}=e,i=Date.now();try{await NF(i,r,e)}catch(a){if(a instanceof Error&&(a.name==="AbortError"||a.name==="TimeoutError")||n.aborted)return;a instanceof Fc?t.warn("Skipping AI smart waiting due to excessive page size - falling back to naive waiting"):t.warn({err:a},"Unexpected error occurred during AI smart waiting");let l=o.smartWaitingTimeout-(Date.now()-i);l>0&&await Y(l,n)}finally{t.debug({durationMs:Date.now()-i},"AI smart waiting complete")}}async function NF(r,e,t){let{abortSignal:n,browser:o}=t;if(o.smartWaitingTimeout<3e3){await Y(o.smartWaitingTimeout,n);return}if(!e.description)throw new C("UserConfigurationError","Cannot locate element with empty description");await k(DF(r,e,t),{milliseconds:o.smartWaitingTimeout})}async function DF(r,e,t){let{logger:n,iframeUrl:o}=e,{browser:i}=t;for(;Date.now()-r<i.smartWaitingTimeout;)if(await cr({action:async()=>kF(e,t),frameConfig:o?{type:"url",url:o}:void 0,browser:i,logger:n}))return}async function kF(r,e){let{testContext:t,logger:n,filterByViewport:o,allowNotActionableNodesOverride:i}=r,{browser:a,abortSignal:l,localCodeEvalTools:c,orgId:s,generator:u}=e,d=r.description;t&&(d=await Va({orgId:s,s:d,context:t,localTools:c,signal:l,logger:n}));let{serializedTree:p}=await Br(a,{allowNotActionableNodesOverride:i,filterByViewport:o,abortSignal:l,logger:n});if(yr(p)>LF)throw new Fc;l.throwIfAborted();let g;try{g=await a.screenshot({clearHighlights:!0,respectActiveFrame:!0,retries:2})}catch(b){throw new C("ActionFailureError",`Failed to take screenshot of page to perform smart waiting. The page may be unresponsive, or your machine might be severely resource constrained. Error: ${b instanceof Error?b.message:b}`)}let f=`data:image/jpeg;base64,${g.toString("base64")}`;l.throwIfAborted();let E=await u.getSmartWaitingDecision({browserState:p,description:d,screenshot:f},{abortSignal:l,loggerTags:pe(n)});return n.debug({result:E},"Got smart waiting result"),E.isPageReady}import{cloneDeep as eR}from"lodash-es";async function tR(r){let{command:e,timeoutMs:t,fixtures:n}=r,{abortSignal:o}=n,i=()=>ih(e.cache)?e.cache:void 0,a=i(),l=eR(a),c=(h=!1)=>{if(a=i(),!!a)if(h){let f=Nv(l,a);a.target=f.target,a.updatedAt=f.updatedAt}else{if(!l){a=void 0;return}a.target=l.target,a.updatedAt=l.updatedAt}},s=Date.now(),u=0,d,p=500,m=!1;for(;u<2||Date.now()-s<t;){u++,u>1&&await Y(p,o),o?.throwIfAborted(),a=i();let{result:h,elementWasFound:f}=await Qw({cacheToUse:a,params:r});if(d=h,m=f,h.success)break;c(),p=Math.min(p*2,1e4)}if(!d)throw new C("InternalPlatformError",`Failed to evaluate manual element assertion in ${t}ms.`);if(o?.throwIfAborted(),!d.success&&a?.target&&fs(a.target)){let h=a?.target?.memory?{target:{id:-1,memory:a.target.memory}}:void 0,{result:f}=await Qw({cacheToUse:h,params:r});d=f,d.success||c(!0)}let g=i();return d.success&&g?.target&&!m&&(g.target=im(g.target),g.updatedAt=new Date),d}async function Qw({cacheToUse:r,params:e}){let{command:t,disableCache:n,fixtures:o,tracer:i,targetingWrapper:a}=e,{logger:l}=o;if(t.target&&!en(t.target))throw new Error("Element assertion with x/y is not supported yet");let c=FF(t.assertion),s,u=!1,d=eR(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=>UF(h.locator,e),options:{...t,allowNotActionableNodesOverride:!0,disableCache:n,memory:d?.target?.memory,disableGlobalLocatorRedirect:!0,source:Ji(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 C)||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 UF(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:Ot(c,500,!0)},!Bc(c,n.value,n.operation,!!n.negated)){let s=n.negated?to[n.operation]:ro[n.operation];o=!1,i=new C("AssertionFailureError",`The content ${s} '${n.value}': ${c}`)}break}case"ELEMENT_ATTRIBUTE":{a={elementOuterHtml:Ot(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 C("AssertionFailureError",`The element does not have an attribute named ${n.attr}: ${s}`),o=!1;break}if(!Bc(c,n.value,n.operation,!!n.negated)){let s=n.negated?to[n.operation]:ro[n.operation];o=!1,n.operation==="EXISTS"?i=new C("AssertionFailureError",`The attribute ${n.attr} ${s}`):i=new C("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},tn*1e3);break}case"EDITABLE":{o=await r.isEditable({timeout:tn*1e3});break}case"EXISTS":{o=!0;break}case"ENABLED":{o=await r.isEnabled({timeout:tn*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?Dv[n.condition]:kv[n.condition];i=new C("AssertionFailureError",`The element ${c}`)}break}case"ELEMENT_NAME":{let c=await r.evaluate(s=>s.tagName);if(!Bc(c,n.value,n.operation,!!n.negated)){let s=n.negated?to[n.operation]:ro[n.operation];o=!1,i=new C("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(!Bc(c,n.value,n.operation,!!n.negated)){let s=n.negated?to[n.operation]:ro[n.operation];o=!1,n.operation==="EXISTS"?i=new C("AssertionFailureError",`The style property ${n.property} ${s}`):i=new C("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 Bc(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 FF(r){return r.type==="ELEMENT_EXISTENCE"&&r.negated&&(r.condition==="EXISTS"||r.condition==="VISIBLE")}function rR(r){return r.type==="ELEMENT_EXISTENCE"&&r.negated&&r.condition==="EXISTS"}import{Jimp as BF}from"jimp";async function Xa(r,e){let t=await r.screenshot(e),n=await BF.fromBuffer(t);return{buffer:t,width:Math.ceil(n.bitmap.width??0),height:Math.ceil(n.bitmap.height??0)}}import{Jimp as nR}from"jimp";import Xm from"jpeg-js";import zF from"pixelmatch";async function oR({ctx:r,tracer:e,command:t,disableCache:n,browser:o,targetingWrapper:i,logger:a,screenshotStorage:l}){if(t.target&&!en(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 Q=>Xa(o,{locator:Q.locator,...c}),options:{...t,disableCache:n,disableGlobalLocatorRedirect:!0,memory:t.cache?.target?.memory,targetName:"target"}})).result:s=await Xa(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 ae=`${s.width}x${s.height}`,Q=`${u.width}x${u.height}`;return{fail:!0,thoughts:`Current screenshot (${ae}) does not match saved screenshot dimensions (${Q}) - 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 nR.fromBuffer(s.buffer),p={width:s.width,height:s.height},m=await nR.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),x=Math.abs(p.width-g.width);if(f>E){let ae=d.cover({w:g.width,h:g.height});s.buffer=await ae.getBuffer("image/jpeg"),h="current",s.width=g.width,s.height=g.height}else if(E>f){let ae=m.cover({w:p.width,h:p.height});u.buffer=await ae.getBuffer("image/jpeg"),h="saved"}let A={data:Buffer.alloc(s.width*s.height*4),width:s.width,height:s.height},v=t.threshold??.1,R=zF(Xm.decode(u.buffer).data,Xm.decode(s.buffer).data,A.data,s.width,s.height,{threshold:v,diffColorAlt:[0,255,0]})/(s.width*s.height)*100,D=R>v*100,j=`Visual diff of ${R.toFixed(2)}% detected, which is ${D?"over":"under"} the threshold of ${v*100}%.`;if(h&&(j+=` The ${h} screenshot was cropped since it was taller by ${b} pixels and wider by ${x} pixels.`),D)throw new C("ActionFailureError",j);return{fail:D,thoughts:j,beforeScreenshotOverride:s.buffer,afterScreenshotOverride:Xm.encode(A,75).data,succeedImmediately:!1,urlAfterCommand:o.url()}}var HF=3e4;async function zc({command:r,logger:e,baseUrl:t,fetchImplementation:n=fetch}){let o=r.timeout??HF/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(ai(r.url)&&(c=r.url),t&&si(r.url,t)&&(c=new URL(r.url,t).toString()),!c)throw new C("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 k((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 C("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 C("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 GF=5e3;async function sR({timeout:r=tn,...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 iR(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 Y(l,e.signal),l=Math.min(Math.floor(l*1.5),GF);else return i}return i=await iR(e),i}async function iR({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(aR,{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(aR,{value:r.value,negated:!!r.negated,returnHtml:!0},"checking page content"));if(!i){let c=r.negated?to.CONTAINS:ro.CONTAINS;a=new C("AssertionFailureError",`The page ${c} '${r.value}'.`),o=l}}catch(l){a=new C("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 aR({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 VF=3e4;async function lR({command:r,logger:e,baseUrl:t,fetchImplementation:n=fetch}){let o=r.timeout??VF/1e3,i=new AbortController,a=Object.fromEntries(Object.entries(r.headers||{}).filter(([d,p])=>d&&p));a["Content-Type"]="application/json";let l;if(ai(r.url)&&(l=r.url),t&&si(r.url,t)&&(l=new URL(r.url,t).toString()),!l)throw new C("ActionFailureError",`Invalid URL: ${r.url}`);let s=await k((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 C("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 C("ActionFailureError",`GraphQL request failed with status ${s.status}: ${p}`)}throw d?.errors?.length&&d?.errors[0]?.message?new C("ActionFailureError",`GraphQL request failed with status ${s.status}: ${d.errors[0].message}`):new C("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 Hc=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([Br(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 lo({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([Br(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 lo({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 C("InternalWebAgentError",`Error generating command: ${g instanceof Error?g.message:g}`,{errOptions:{cause:g}})}}async getBrowserState(e){return Br(this.browser,e)}async locateElement(e){return await Ym({...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,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 C("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&&Hu(i)){t.warn({err:i},"Invalid mpath error, retrying element targeting command");continue}if(!this.browser.userBrowserSettings.visualActions&&(Vu(i)||Gu(i))){t.warn({err:i},"Invalid momentic id error, retrying element targeting command");continue}if(ju(i)){t.warn({err:i},"Invalid backend node id error, retrying element targeting command");continue}if(i instanceof wr&&i.retryableWithAI){t.warn({err:i},"Element cache disqualification error, retrying element targeting command");continue}throw i}throw n instanceof C?n:new C("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 C("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 Y(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=cR(e.cache);if((!b||s)&&!Au(o))throw new C("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&&!Yw(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 x=v=>!!v&&fs(v),A=!0;if(!x(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||!i)&&await Zw({description:o.elementDescriptor,iframeUrl:l.iframeUrl,source:m,logger:g,allowNotActionableNodesOverride:l.allowNotActionableNodesOverride},this.getControllerFixtures(t)),f--;let v;try{v=await Ym({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(D){if(D instanceof _o&&D.updatedLocatorMemory){let j={id:-1,...i,memory:D.updatedLocatorMemory};gc({cmd:c,key:d,newTarget:j,logger:g,updatedWithAI:!0})}throw new C("ActionFailureError",D.message)}v.frameConfig&&this.browser.setActiveFrameConfig(v.frameConfig);let _=l.disableGlobalLocatorRedirect?{locator:v.resolution.locator}:await this.attemptLocatorRedirect(v.resolution.locator,g),R=await a(_);return gc({cmd:c,key:d,newTarget:v.target,logger:g,updatedWithAI:!0}),p&&(n.recordTargetAutoHeal({healType:"AI"}),v.target.targetSource="AI_HEALED",v.target.targetUpdateTime=new Date().toUTCString(),v.target.targetUpdateLoggerTags=pe(g)),{result:R,elementInteractedDisplayString:v.resolution.displayString,thoughts:v.thoughts}}try{let v=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(v.locator);let _=l.disableGlobalLocatorRedirect?{locator:v.locator}:await this.attemptLocatorRedirect(v.locator,g),R=await a(_);if(At.increment("cache_target_resolution_v2",1,["outcome:hit","platform:web",`hasRequirements:${!!b.requirements}`,`hasAdditionalElements:${!!b.additionalElements}`,`orgId:${this.orgId}`,"cliVersion:0.4.1"]),gc({cmd:c,key:d,newTarget:b,logger:g,updatedWithAI:!1}),A){let D=v.decisions.filter(j=>j.matched);if(D.length!==1)g.warn({decisions:v.decisions},"Expected exactly 1 matching method for element location, got more or less");else{let j=D[0].type;n.recordTargetAutoHeal({healType:j})}}return{result:R,elementInteractedDisplayString:v.displayString}}catch(v){this.throwIfClosed(),At.increment("cache_target_resolution_v2",1,["outcome:miss","platform:web",`hasRequirements:${!!b.requirements}`,`hasAdditionalElements:${!!b.additionalElements}`,`orgId:${this.orgId}`,"cliVersion:0.4.1"]);let _=!1;if((v instanceof wr||Hu(v)||Vu(v)||ju(v)||rf(v)||Gu(v))&&(_=!0),v instanceof C&&!_)throw g.error({err:v},"Failed to execute action with cached target (fatal)"),v;if(f>0&&o){g.info({err:v},"Failed to execute action with cached target, retrying with AI");let R;return b.memory&&Qg(b.memory)&&(R=b.memory),this.wrapElementTargetingCommand({ctx:t,tracer:n,command:c,target:o,cache:void 0,originalCache:i,action:a,options:{...l,memory:R,retriesWithAI:f,targetHealingInProgress:!0}})}throw new C("ActionFailureError",v.message,{errOptions:{cause:v}})}}async attemptLocatorRedirect(e,t){return this.browser.userBrowserSettings.globalLocatorRedirect!==!1?this.browser.performTargetRedirection(e,t):{locator:e}}async screenshotWithDimensions(e){return Xa(this.browser,e)}async executePresetCommand(e,t,n,o,i){this.options?.slowMoMs&&await Y(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 C("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&&Th(n)?await this.browser.waitForDOMStability({timeout:ge}):!this.browser.userBrowserSettings.visualActions&&["PRESS","TYPE"].includes(n.type)&&await this.browser.waitForDOMStability({timeout:Z}),this.options?.autoFollowNewTabs&&await zw({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{mc(n,c)}}createCallbacksForBrowser(e){return{createIsolatedFolder:()=>Tm(e)}}async resolveCommandTemplateStrings(e,t){return pc({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()?Uc({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 C("ActionFailureError","Missing assertion");if(n.timeout&&n.timeout>1800)throw new C("AssertionFailureError",`AI check timeout of ${n.timeout} exceeds the maximum allowed value of 30 minutes.`);return Uc({command:n,fixtures:this.getControllerFixtures(e),useMemory:this.shouldUseMemory(),aiPageFiltering:!!this.options?.aiPageFiltering,logger:a})}case"AI_EXTRACT":{if(!n.goal.trim())throw new C("ActionFailureError","Cannot perform AI extraction without goal");if(n.schema){let f=Wy(n.schema);if(f)throw new C("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 C("ActionFailureError","No relevant data found for extraction goal on this page");if(f.thoughts?.includes("MaxGenerationLengthExceededError"))throw new C("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 C("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 C("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(!ai(n.url)&&!si(n.url,this.browser.baseUrl))throw new C("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&&vr(n.target))await this.browser.hoverUsingVisualCoordinates(n.target.pixels);else if(n.target&&n.target.elementDescriptor.trim()){let{elementInteractedDisplayString:b,thoughts:x}=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=x}let f=this.browser.getViewport()?.height??ln.height,E=this.browser.getViewport()?.width??ln.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 C("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 C("UserConfigurationError",`Wait timeout of ${n.delay} seconds exceeds the maximum allowed value of 30 minutes`);let s=n.delay*1e3;await Y(s,this.executeAbortController.signal);break;case"REFRESH":await this.browser.refresh({loadTimeoutMs:n.loadTimeout?n.loadTimeout*1e3:void 0});break;case"CLICK":{if(vr(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:x=>this.browser.click(x,this.createCallbacksForBrowser(this.orgId),n),options:{disableCache:i,targetName:"target",...n}}),b={urlAfterCommand:this.browser.url(),succeedImmediately:!1,elementInteracted:h,thoughts:E,data:f.downloadedFile?{downloadedFile:f.downloadedFile}:void 0};return Tc(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(vr(n.fromTarget)&&vr(n.toTarget)){await this.browser.dragAndDropUsingVisualCoordinates(n.fromTarget.pixels,n.toTarget.pixels,{hoverSeconds:n.hoverSeconds});break}if(vr(n.fromTarget)||vr(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 C("ActionFailureError",`Invalid pixel values passed to mouse drag command: (${n.deltaX}, ${n.deltaY})`);if(n.target&&vr(n.target)){await this.browser.mouseDragUsingVisualCoordinates(g,h,f,n.target.pixels,{force:n.force});break}let E,b;if(n.target?.elementDescriptor){let{elementInteractedDisplayString:x,thoughts:A}=await this.wrapElementTargetingCommand({ctx:e,tracer:t,command:n,target:n.target,cache:n.cache?.target,action:async v=>this.browser.mouseDrag(g,h,f,v.locator,{force:n.force}),options:{disableCache:i,targetName:"target",...n}});E=x,b=A}else await this.browser.mouseDrag(g,h,f,void 0,{force:n.force});return{succeedImmediately:!1,urlAfterCommand:this.browser.url(),elementInteracted:E,thoughts:b}}case"SELECT_OPTION":{if(!en(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:Ji(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 Nr({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 C("ActionFailureError",h instanceof Error?h.message:`${h}`,{errOptions:{cause:h}})}try{JSON.stringify(g)}catch(h){throw new C("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&&vr(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=cR(n.target),b=this.browser.userBrowserSettings.globalLocatorRedirect===void 0||this.browser.userBrowserSettings.globalLocatorRedirect==="always";if(E){let{elementInteractedDisplayString:A,thoughts:v}=await this.wrapElementTargetingCommand({ctx:e,tracer:t,command:n,target:E,cache:n.cache?.target,action:_=>this.browser.typeIntoTarget(n.value,_,{force:n.force,clearContent:n.clearContent,forceClearContent:n.forceClearContent,delay:n.delay,pressEnter:n.pressEnter,relativePosition:n.relativePosition}),options:{...n,targetName:"target",disableCache:i,disableGlobalLocatorRedirect:!b,source:Ji(n)}});h=A,f=v}else await this.browser.type(n.value,{force:n.force,clearContent:n.clearContent,forceClearContent:n.forceClearContent,delay:n.delay,pressEnter:n.pressEnter},!0);let x={urlAfterCommand:this.browser.url(),succeedImmediately:!1,elementInteracted:h,thoughts:f};return Tc(g,x.urlAfterCommand)&&(x.succeedImmediately=!0,x.succeedImmediatelyReason="URL changed"),x}case"HOVER":{if(vr(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(!en(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&&!en(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 Tc(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 WF,h=jF(fetch,g),f;try{f=new URL(n.url).hostname}catch{}return{data:{...await zc({command:n,baseUrl:this.browser.baseUrl,logger:a,fetchImplementation:h}),cookies:Vs(g,f)},succeedImmediately:!1,urlAfterCommand:this.browser.url()}}case"GRAPHQL_REQUEST":return{data:await lR({command:n,baseUrl:this.browser.baseUrl,logger:a}),succeedImmediately:!1,urlAfterCommand:this.browser.url()};case"VISUAL_DIFF":return oR({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 IA({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 C("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 Nr({orgId:this.orgId,code:n.storageState,fragment:!1,context:o,logger:a,localTools:this.localCodeEvalTools,signal:this.executeAbortController.signal}),typeof g!="object")throw new C("ActionFailureError",`Credentials must evaluate to an object (received ${typeof g} instead)`);let h;try{h=mS.optional().parse(g)}catch(f){throw new C("ActionFailureError",`Credentials provided do not follow the required format: ${f}`)}await this.browser.loadAuthState(h);break}case"ELEMENT_CHECK":{let g=(n.timeout??tn)*1e3,h=this.generator.getAgentConfig()?.assertion;if(rR(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 Uc({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&&hc(n,E.cache?.memory.traces,a)}}let f=await tR({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 cr({action:async()=>sR({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 wn(n.requestMatcher),h=this.browser.registerRequestListener(g);return this.registeredListeners[n.key]=h.then(async f=>await xm(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 C("ActionFailureError",`No listener registered with key: ${n.key}`);let h=n.timeout??10;return{data:await k(g,{milliseconds:h*1e3,message:`Request listener timed out after ${h} seconds`}),succeedImmediately:!1,urlAfterCommand:this.browser.url()}}case"RECORD_REQUESTS":{let g=new wn(n.requestMatcher);return this.recordedRequests[n.key]={},this.browser.registerRequestRecorder(n.key,g,{onRequestStart:(h,f)=>{this.recordedRequests[n.key][h]=Cc(f)},onRequestComplete:(h,f)=>{this.recordedRequests[n.key][h]=Cc(f)}}),{succeedImmediately:!1,urlAfterCommand:this.browser.url()}}case"GET_RECORDED_REQUESTS":{let g=this.recordedRequests[n.key];if(!g)throw new C("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 wn(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 wn(n.requestMatcher),async(h,f)=>{let E=await Nr({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=xS.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 Oc({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{cloneDeep as $F}from"lodash-es";import gR from"truncate-json";var uR=1e3,dR=5e6,qF=5*1024*1024;function hR(r,e){for(let t=0;t<r.length;t++){let n=r[t];try{if(n.data){let{jsonString:o}=gR(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":pR(n);break;case"MOBILE_AI_ACTION_STEP":case"MOBILE_MODULE_STEP":pR(n),hR(n.steps,e);break;default:{let o=n;throw new Error("If Typescript complains about the line below, you missed a case or break in the switch above")}}}}function pR(r){if(r.type==="MOBILE_PRESET_STEP"){let e=r.command;"cache"in e&&e.cache&&(e.cache=void 0)}}function mR(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 Gc(r,e){let t=$F(r);if(hR(t,e),t.length>uR)return e.error("Database content violation: results too long, truncating before insertion"),t.slice(0,uR);let n=mR(t,e);if(n.length>dR)for(e.error({serializedLength:n.length,resultsArrayLength:t.length},"Database content violation: results too large, truncating before insertion");n.length>dR;)t.pop(),n=mR(t,e);let{jsonString:o}=gR(n,qF);try{return tr.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}}import{AsyncLocalStorage as KF}from"async_hooks";var Ja=new KF;function YF(r){Ja.enterWith({activeTracers:[r]})}function XF(r,e){let t=Ja.getStore()?.activeTracers;if(!t)return e();t.push(r);try{return e()}finally{t.pop()}}async function JF(r,e){let t=Ja.getStore()?.activeTracers;if(!t)return e();let n=[...t,r];return Ja.run({activeTracers:n},e)}var Yr={globalAls:Ja,initializeRootTracerContext:YF,withChildTracer:XF,withChildTracerAsync:JF};var co=class r{spans;parentSection;finished=!1;startTime;endTime;constructor(e){this.startTime=e?.startTime??Date.now(),this.spans=e?.subSpans??[],this.parentSection=e}startSection(e,t){let n={type:"SECTION",name:e,startTime:Date.now(),endTime:void 0,subSpans:[],attributes:{}},o=new r(n);try{return Yr.withChildTracer(o,()=>t(o,n))}catch(i){throw n.error=i instanceof Error?i.message:String(i),i}finally{o.finish(),this.addSpan(n)}}async startAsyncSection(e,t,n){let o={type:"SECTION",name:e,startTime:Date.now(),endTime:void 0,subSpans:[],attributes:{}},i=new r(o);this.addSpan(o);try{let a;return n?.signal||n?.timeoutMs?a=await Yr.withChildTracerAsync(i,()=>k(t(i,o),{milliseconds:n?.timeoutMs??1/0,signal:n?.signal,message:n?.timeoutMsg})):a=await Yr.withChildTracerAsync(i,()=>t(i,o)),a}catch(a){throw o.error=a instanceof Error?a.message:String(a),a}finally{i.finish()}}finish(){if(!this.finished){this.endTime=Date.now();for(let e of this.spans)e.endTime||(e.endTime=this.endTime,e.durationMs=e.endTime-e.startTime);this.parentSection&&(this.parentSection.endTime=this.endTime,this.parentSection.durationMs=this.parentSection.endTime-this.parentSection.startTime),this.finished=!0}}addSpan(e){this.spans.push(e)}startSpan(e,t,...n){let o={type:e,startTime:Date.now(),endTime:void 0,attributes:{}},i=n[0]??void 0;Object.assign(o,i??{}),this.addSpan(o);let a;try{a=t(o),o.endTime=Date.now(),o.durationMs=o.endTime-o.startTime}catch(l){throw o.error=l instanceof Error?l.message:String(l),o.endTime=Date.now(),o.durationMs=o.endTime-o.startTime,l}return a}async startAsyncSpan(e,t,...n){let o={type:e,startTime:Date.now(),endTime:void 0,attributes:{}},i=n[0]??void 0;Object.assign(o,i??{}),this.addSpan(o);let a;try{i?.signal||i?.timeoutMs?a=await k(t(o),{milliseconds:i?.timeoutMs??1/0,signal:i?.signal}):a=await t(o),o.endTime=Date.now(),o.durationMs=o.endTime-o.startTime}catch(l){throw o.error=l instanceof Error?l.message:String(l),o.endTime=Date.now(),o.durationMs=o.endTime-o.startTime,l}return a}getRootSpan(){return this.finished||this.finish(),{type:"SECTION",name:"root step span",startTime:this.startTime,endTime:this.endTime,subSpans:this.spans,attributes:{},durationMs:this.endTime?this.endTime-this.startTime:void 0}}};function Ae(){let r=Yr.globalAls.getStore()?.activeTracers,e;return!r||r.length===0?e=void 0:e=r[r.length-1],e||new co}async function fR(r){let{driver:e,abortSignal:t,logger:n,packageName:o}=r,i;try{i=await k(e.execute("mobile: shell",{command:"dumpsys",args:["activity","recents"]}),{signal:t,milliseconds:1e4})}catch(l){t?.throwIfAborted(),n.warn({err:l,packageName:o},"Failed to read recents output while removing package");return}if(typeof i!="string"){n.warn({packageName:o,outputType:typeof i},"Unexpected dumpsys output when removing package from recents");return}let a=ZF(i,o);if(a.length!==0)for(let l of a){t?.throwIfAborted();try{await e.execute("mobile: shell",{command:"am",args:["stack","remove",l.toString()]}),n.info({packageName:o,taskId:l},"Removed task from recents")}catch(c){t?.throwIfAborted(),n.warn({err:c,packageName:o,taskId:l},"Failed to remove task from recents")}}}function ZF(r,e){let t=r.split("Task{");if(t.length<=1)return[];let n=new Set;for(let o of t.slice(1)){let i=`Task{${o}`;if(!i.includes(e)||i.includes("app.lawnchair/.LawnchairLauncher"))continue;let a=i.match(/taskId=(\d+)/);if(!a)continue;let[,l]=a;if(!l)continue;let c=Number.parseInt(l,10);Number.isNaN(c)||n.add(c)}return Array.from(n)}import{mkdirSync as fB}from"fs";import{tmpdir as SB}from"os";import wR from"path";import{diff as gB}from"deep-object-diff";import{cloneDeep as hB}from"lodash-es";import bR from"fontoxpath";import QF from"@prettier/plugin-xml";import eB from"prettier";import{DOMParser as tB,XMLSerializer as rB}from"slimdom";var nB=new Set(["android.webkit.webview","com.facebook.react.views.webview.reactwebview","com.tencent.smtt.sdk.webview","com.tencent.smtt.sdk.x5webview","org.xwalk.core.xwalkview","com.uc.webview.export.webview"]);function Za(r){let e=r.toLowerCase();return e.endsWith("webview")||nB.has(e)}function oB(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 iB=new Set(["index","package","a11y-important","screen-reader-focusabl"]),aB=new Set(["selected","checked","checkable","clickable","enabled","focusable","focused","long-clickable","password","scrollable","selected","showing-hint","context-clickable","multiline","text-entry-key","heading","dismissable","screen-reader-focusable","content-invalid","a11y-focused"]),sB=new Set(["text","hint"]),lB=new Set(["live-region","drawing-order"]),cB=new Set(["displayed","enabled"]);function uB(r,e){let t={};for(let[n,o]of Object.entries(e))iB.has(n)||n==="class"&&r===o||n==="focusable"&&o==="true"&&e.clickable==="true"||aB.has(n)&&o==="false"||sB.has(n)&&o===""||cB.has(n)&&o==="true"||lB.has(n)&&o==="0"||n!=="id"&&(t[n]=o);return t}function SR(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=uB(e.tagName,s);for(let[p,m]of Object.entries(u))t.setAttribute(p,m);if(o.set(c,e),i.set(c,t),Za(e.tagName)){let p=l?.injectedWebviewContent??"";if(!l?.disableMomenticAccessibilityTree&&p.trim().length>0){for(;t.firstChild;)t.removeChild(t.firstChild);p.trim().length>0&&t.appendChild(n.createCDATASection(`
4123
4103
  ${p}
4124
- `));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(YF(g.tagName));mR(r,g,h),t.appendChild(h)}}}function rB(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;mR(a,e,l);let c=new qF().serializeToString(o);return{prunedDocument:o,prunedIdToElement:i,xml:c}}async function gR(r,e){let t=new $F,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}=rB(t,i,o,e);return{xml:await WF.format(c,{parser:"xml",plugins:[jF],printWidth:120,tabWidth:1,singleAttributePerLine:!1}),originalXml:r,document:n,idToElement:o,prunedDocument:a,prunedIdToElement:l}}function nB(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 zc(r,e){let t=r.idToElement.get(e);if(t)return nB(t)}function Xm(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 mi(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 Jm(r,e){if(r&&!(!e||e.length===0))return Object.fromEntries(e.map(t=>[t,r.getAttribute(t)]).filter(([,t])=>t!==null))}function SR({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=mi(n);if(!o)throw new Error(`Node ${r.id} has no bounding box: ${n.outerHTML}`);let i=zc(t.graph,r.id)??"",a=Xm(t.graph,r.id)??"",l=t.graph.idToElement.get(r.id),c=Jm(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=zc(t.graph,m);return f?{xPath:f,requirements:{requiredText:g.textRequired?h.getAttribute("text")??void 0:void 0,requiredAttributes:Jm(h,g.attributesRequired),requiredBounds:g.boundsRequired}}:void 0}).filter(m=>!!m));let p;return Xa(n.tagName)&&r.inWebview!==!1?p={type:"WEBVIEW",resolvedDescription:e,xPath:i}:p={type:"NATIVE",bounds:o,resolvedDescription:e,xPath:i,elementOnlySerializedXml:a,requirements:u,requiredRelatedElements:d},p}var fR=(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=mi(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 yR(r){let{target:e,domState:t}=r,{graph:n}=t,{document:o}=n,i=ve();if(e.type==="WEBVIEW")return oB(e,r);let a=hR.evaluateXPathToFirstNode(e.xPath,o,null,null);if(!a)throw new Error(`ActionFailureError: Could not resolve cached target via XPath: ${e.xPath}`);if(e.requiredRelatedElements){let p=e.requiredRelatedElements;i.startSection("Validate related elements are similar enough to past runs",()=>{for(let m of p){let g=hR.evaluateXPathToFirstNode(m.xPath,o);if(!g)throw new Error(`ActionFailureError: Required related element not found for XPath: ${m.xPath}`);fR(g,m.requirements)}})}let l=mi(a);if(!l)throw new Error("ActionFailureError: Resolved native element has no bounding box");fR(a,e.requirements,e.bounds);let c;for(let[p,m]of n.idToElement.entries())if(m===a){c=p;break}let s=e.elementOnlySerializedXml,u=e.xPath;return c!==void 0&&(s=Xm(n,c)??s,u=zc(n,c)??u),{resolvedTarget:{...e,bounds:l,elementOnlySerializedXml:s,xPath:u}}}async function oB(r,e){let{stateManager:t,logger:n,signal:o}=e,i=ve(),a=await t.getActiveWebview();if(!a||!a.browserController)throw new Error("No browser controller is attached to the requested webview");let l=a.browserController.browser;if(!r.browserCache)throw new Error("No browser target available on cache");let c=r.browserCache,s=await i.startAsyncSection("Resolve target in webview",()=>l.resolveTarget(null,c,{logger:n,signal:o}));return{resolvedTarget:{...r,controller:a.browserController,resolution:s}}}function Zm(r){let{command:e,cacheKey:t="cache",targetName:n="target",updatedCache:o}=r;js(e)&&(e[t]={...e[t],[n]:Gs.parse(o)},r.updatedWithAI&&(e[t].updatedAt=new Date))}function bR(r){return r.type==="WEBVIEW"?{type:"WEBVIEW",resolvedDescription:r.resolvedDescription,xPath:r.xPath,browserCache:r.browserCache}:r}var zt=class{driver;generator;stateManager;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,reason:"Waiting for stability before locating an element with AI"});let n=await t.startAsyncSection("Get emulator state",async()=>{let c=await this.stateManager.getDomState(),s=await this.stateManager.getCurrentScreenshotPngString();return{emulatorState:c,screenshot:s}}),o;try{o=await t.startAsyncSpan("AI_LOCATOR_CALL",async c=>{let s=await this.generator.getElementLocation({description:e,screenXml:n.emulatorState.graph.xml,screenshot:n.screenshot},{logger:this.logger,loggerTags:me(this.logger),abortSignal:this.aborter.controller?.signal});return c.result=s,s})}catch(c){throw this.throwIfAborted(),this.logger.error({err:c},"Failed to locate element"),new Error(`ActionFailureError: Failed to locate element: ${c instanceof Error?c.message:c}`)}if(o.id===-1)throw new Error(`ActionFailureError: No matching element found: ${o.thoughts}`);let i=SR({aiResponse:o,description:e,emulatorState:n.emulatorState});if(i.type==="NATIVE")return t.addSpan({type:"TARGET_RESOLUTION",startTime:Date.now(),endTime:Date.now(),result:{serializedElement:i.elementOnlySerializedXml},attributes:{}}),{resolvedTarget:i,thoughts:o.thoughts};let{browserLocateResult:a,browserController:l}=await t.startAsyncSpan("TARGET_RESOLUTION",async c=>{let s=await this.stateManager.getActiveWebview();if(!s||!s.browserController)throw new Error("No browser controller is attached to the requested webview");let u=await s.browserController.locateElement({description:e,disableCache:!1,logger:this.logger});return c.result={serializedElement:u.target.nodeOnlySerializedHtml??"Unknown HTML element in webview"},{browserLocateResult:u,browserController:s.browserController}});return{resolvedTarget:{...i,controller:l,resolution:a.resolution,browserCache:a.target},thoughts:a.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=aB(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({description:n,cacheDescription:p?.resolvedDescription},"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});m=h.thoughts;let f=await t(h.resolvedTarget);return Zm({command:o,cacheKey:i,targetName:a,updatedCache:h.resolvedTarget,updatedWithAI:!0}),{result:f,thoughts:m}}let g;try{await this.stateManager.waitForScreenshotStability({timeoutMs:5e3,signal:this.aborter.controller?.signal,reason:"Waiting for stability before cache resolution"}),g=await this.stateManager.getDomState();let{resolvedTarget:h,updatedCache:f}=await c.startAsyncSection("Resolve target cache",async(b,C)=>{let{resolvedTarget:A}=await yR({target:p,domState:g,stateManager:this.stateManager,logger:this.logger}),v=bR(A),M=iB(p,v);return M&&Object.keys(M).length>0&&this.logger.info({cacheDiffs:M},"Successfully resolved target with cache"),C.attributes.serializedElement=A.type==="WEBVIEW"?A.browserCache?.nodeOnlySerializedHtml??"Unknown HTML element in webview":A.elementOnlySerializedXml,{resolvedTarget:A,updatedCache:v}}),E=await t(h);return Zm({command:o,cacheKey:i,targetName:a,updatedCache:f,updatedWithAI:!1}),p.type!=="WEBVIEW"&&At.increment("cache_target_resolution_v2",1,["outcome:hit","platform:native",`hasRequirements:${!!p.requirements}`,`hasAdditionalElements:${!!p.requiredRelatedElements?.length}`,`orgId:${this.orgId}`,"cliVersion:0.4.0"]),{result:E,thoughts:"Successfully executed preset action with cache."}}catch(h){if(p.type!=="WEBVIEW"&&At.increment("cache_target_resolution_v2",1,["outcome:miss","platform:native",`hasRequirements:${!!p.requirements}`,`hasAdditionalElements:${!!p.requiredRelatedElements?.length}`,`orgId:${this.orgId}`,"cliVersion:0.4.0"]),this.throwIfAborted(),u>0)return this.logger.warn({err:h},"Failed to resolve target cache, retrying with AI"),this.logger.debug({domState:g?.graph.originalXml},"Emulator state"),this.wrapTargetingAction({...e,cacheIsInvalidAfterResolution:!0,retriesWithAI:u-1});throw new Error(`ActionFailureError: ${h instanceof Error?h.message:h}`,{cause:h})}}constructPerformerParams(){return{stateManager:this.stateManager,generator:this.generator,driver:this.driver,logger:this.logger,fixtures:this.fixtures,aborter:this.aborter,orgId:this.orgId}}throwIfAborted(){this.aborter.controller?.signal.throwIfAborted()}get abortSignal(){return this.aborter.controller?.signal}};function cB(r){let e={relativePosition:r.relativePosition};if(r.doubleTap&&r.longPress)throw new Error("UserConfigurationError: Cannot specify both doubleTap and longPress");return r.doubleTap?{...e,doubleTap:!0,doubleTapDelayMs:r.doubleTapDelayMs}:r.longPress?{...e,longPress:!0,longPressDurationMs:r.longPressDurationMs}:e}var hi=class extends zt{async tapOnAbsoluteCoordinates(e){let t=e.x,n=e.y;if(this.logger.info({x:t,y:n},"Tap at coordinates"),e.longPress)return await this.driver.executeScript("mobile: longClickGesture",[{x:t,y:n,duration:e.longPressDurationMs??2e3}]);if(e.doubleTap){await this.driver.tap({x:t,y:n});let o=e.doubleTapDelayMs??100;await new Promise(i=>setTimeout(i,o))}await this.driver.tap({x:t,y:n})}async tapOnNativeTarget(e,t){let[n,o,i,a]=e.bounds,l=i-n,c=a-o,s=t?.relativePosition?.x??l/2,u=t?.relativePosition?.y??c/2;s=Math.max(0,Math.min(s,l)),u=Math.max(0,Math.min(u,c));let d=n+s,p=o+u;return await this.tapOnAbsoluteCoordinates({x:d,y:p,...t}),{x:d,y:p}}async tapOnWebviewTarget(e,t){let{controller:n}=e;return(await n.browser.click(e.resolution,{createIsolatedFolder:()=>{let i=Math.random().toString(36).substring(4),a=ER.join(lB(),"momentic","downloads"),l=ER.join(a,this.orgId,i);return sB(l,{recursive:!0}),l}},{delayMs:t?.longPress?t?.longPressDurationMs??2e3:void 0,relativePosition:t?.relativePosition,doubleClick:t?.doubleTap})).coordinates}async tapOnTarget({target:e,options:t}){return await ve().startAsyncSpan("EMULATOR_INTERACTION",async o=>{o.attributes.options=t,"type"in e&&e.type==="NATIVE"?o.attributes.point=await this.tapOnNativeTarget(e,t):(o.withinWebview=!0,o.attributes.point=await this.tapOnWebviewTarget(e,t))},{name:"Tap on target"})}async executeTap({command:e}){let t=ve(),n=cB(e);if(e.target.type==="coordinates"){let a=await this.driver.getWindowSize(),l=e.target.xPercent*a.width,c=e.target.yPercent*a.height;return await t.startAsyncSpan("EMULATOR_INTERACTION",async()=>{await this.tapOnAbsoluteCoordinates({...n,x:l,y:c})},{name:`Tap at coordinates ${l}, ${c}`}),{success:!0,message:`Tapped at ${l}, ${c}`}}let o=e.target.description,{thoughts:i}=await this.wrapTargetingAction({command:e,tracer:t,action:a=>this.tapOnTarget({target:a,options:n}),description:o});return{success:!0,message:i}}};var Cn=class extends zt{async doPress({keycode:e,longPress:t}){await ve().startAsyncSpan("EMULATOR_INTERACTION",async()=>this.driver.executeScript("mobile: pressKey",[{keycode:e,isLongPress:t}]),{name:"Send key events to emulator"})}};var Hc=class extends zt{async doType(e){if(!e.target){if(e.clearContent)throw new Error("UserConfigurationError: clearing content is only supported when a target is provided to the Type step");return await this.sendKeys(e),{success:!0,message:void 0}}if(e.target.type!=="description")throw new Error("UserConfigurationError: x/y targets are not supported for the Type step");let t=ve(),{thoughts:n}=await this.wrapTargetingAction({command:e,tracer:t,action:async o=>{"type"in o&&o.type==="NATIVE"?await this.doNativeType(e,o):await this.doWebviewType(e,o)},description:e.target.description});return{success:!0,message:n}}async doWebviewType(e,t){await ve().startAsyncSpan("EMULATOR_INTERACTION",async o=>{o.withinWebview=!0,o.attributes.options={clearContent:e.clearContent};let{controller:i,resolution:a}=t;await i.browser.typeIntoTarget(e.text,a,{clearContent:e.clearContent,delay:e.keyPressDelayMs})},{name:"Typing within web view"})}async doNativeType(e,t){let n=new hi(this.constructPerformerParams());e.clearContent?(await n.tapOnNativeTarget(t,{longPress:!0}),await this.clearContent()):await n.tapOnNativeTarget(t),await this.stateManager.waitForScreenshotStability({timeoutMs:2e3,signal:this.aborter.controller?.signal,reason:"Waiting for keyboard to appear before typing"}),await this.sendKeys(e)}async sendKeys(e){let t=ve(),n=e.keyPressDelayMs;n?await t.startAsyncSpan("EMULATOR_INTERACTION",async()=>{await this.driver.updateSettings({keyInjectionDelay:n}),await this.driver.keys(e.text),await this.driver.updateSettings({keyInjectionDelay:0})},{name:"Typing keys with a delay"}):await t.startAsyncSpan("EMULATOR_INTERACTION",async()=>{await this.driver.keys(e.text)},{name:"Typing keys"})}async clearContent(){let e=ve();try{await e.startAsyncSection("Clearing any content from the focused field",()=>this.clearContentHelper())}catch(t){this.logger.warn({err:t},"Failed to clear content because the select all button was not found, continuing...")}}async clearContentHelper(){let e=this.driver.$('//android.widget.LinearLayout[@content-desc="Select all" and @clickable="true"]');await e.waitForExist({timeout:750}),await e.click(),await new Cn(this.constructPerformerParams()).doPress({keycode:67})}};import Gt from"zod";var TR=.9,uB=Gt.object({navigationBar:Gt.object({visible:Gt.boolean(),x:Gt.number(),y:Gt.number(),width:Gt.number(),height:Gt.number()}),statusBar:Gt.object({visible:Gt.boolean(),x:Gt.number(),y:Gt.number(),width:Gt.number(),height:Gt.number()})}),Gc=class extends zt{async executeSwipe(e){let t=ve();if(e.scrollableElement.type!=="CUSTOM"){await this.stateManager.waitForScreenshotStability({timeoutMs:2e3,signal:this.aborter.controller?.signal,reason:"Waiting for screen to stabilize before swiping"});let n=await this.driver.getWindowRect(),o;switch(e.scrollableElement.type){case"SCREEN":o={left:n.x+25,top:n.y+50,width:n.width-50,height:n.height-100};break;case"OPEN_APP":try{let i=uB.parse(await this.driver.executeScript("mobile: getSystemBars",[]));o={left:n.x+25,top:n.y+50,width:n.width-50,height:n.height-100},i.navigationBar.visible&&(o.height-=i.navigationBar.height),i.statusBar.visible&&(o.top+=i.statusBar.height,o.height-=i.statusBar.height)}catch(i){this.logger.warn({err:i},"Failed to get system bars, using hardcoded bounds"),o={left:n.x+50,top:n.y+100,width:n.width-100,height:n.height-200}}break;case"OPEN_WEBVIEW":{let i=await this.stateManager.getActiveWebviewNodes();if(i.length===0)throw new Error("No active webviews found");if(i.length>1)throw new Error("Multiple active webviews found");let a=i[0]?.bounds;if(!a)throw new Error("No bounds found for active webview");o={left:a[0]+50,top:a[1]+100,width:a[2]-a[0]-100,height:a[3]-a[1]-200};break}default:{let i=e.scrollableElement;throw new Error("If Typescript complains about the line above, you missed a switch case")}}return await t.startAsyncSpan("EMULATOR_INTERACTION",async i=>{await this.swipeByAbsoluteCoordinates({span:i,direction:e.direction,percent:e.viewportPercent,durationMs:e.durationMs,containerBounds:o})},{name:`Swipe ${e.direction} in the entire ${e.scrollableElement.type.toLowerCase()}`}),{success:!0}}return await this.wrapTargetingAction({command:e,description:e.scrollableElement.target.description,action:async n=>ve().startAsyncSpan("EMULATOR_INTERACTION",async i=>"type"in n&&n.type==="NATIVE"?this.scrollInNativeContainer({span:i,cmd:e,target:n}):(i.withinWebview=!0,this.scrollInWebview({cmd:e,target:n})),{name:`Swipe ${e.direction} in the specified container`}),tracer:t}),{success:!0}}async scrollInNativeContainer({span:e,cmd:t,target:n}){let o=Math.floor(n.bounds[2]*.05),i=Math.floor(n.bounds[3]*.05);await this.swipeByAbsoluteCoordinates({span:e,direction:t.direction,percent:t.viewportPercent,durationMs:t.durationMs,containerBounds:{left:n.bounds[0]+o,top:n.bounds[1]+i,width:n.bounds[2]-n.bounds[0]-o*2,height:n.bounds[3]-n.bounds[1]-i*2}})}async scrollInWebview({cmd:e,target:t}){let{controller:n}=t,o=n.browser.getViewport();if(!o)throw new Error("Failed to get viewport size from webview");if(e.direction==="down"||e.direction==="up"){let i=o.height*(e.viewportPercent??TR)*(e.direction==="down"?1:-1);await n.browser.scrollVertical(i)}else{let i=o.width*(e.viewportPercent??.9)*(e.direction==="right"?1:-1);await n.browser.scrollHorizontal(i)}}async swipeByAbsoluteCoordinates({span:e,direction:t,percent:n=TR,durationMs:o=500,containerBounds:i}){e.attributes.containerBounds=i;let a,l;t==="up"||t==="down"?(a=i.height*n,l=Math.floor(a/(o/1e3))):(a=i.width*n,l=Math.floor(a/(o/1e3))),e.attributes.pixelDelta=a,e.attributes.pixelsPerSecond=l,await this.driver.executeScript("mobile: swipeGesture",[{...i,direction:t,percent:n,speed:l}])}};import{randomUUID as dB}from"crypto";import Za from"fs";import{tmpdir as pB}from"os";import fi from"path";var Vc=class extends zt{async doInstallApk(e){return await this.installApkFromUri(e.uri),{success:!0,message:"Installed APK."}}async installApkFromUri(e){let t=await this.resolveUriToLocalApk(e);try{await this.stateManager.executeRawADBCommand(`install ${fi.resolve(t.localPath)}`),this.logger.info({uri:e,localPath:t.localPath},"Installed APK on device")}finally{t.cleanup()}}async resolveUriToLocalApk(e){try{let t=new URL(e);if(t.protocol==="file:"){let n=t.href.slice(7),o;if(Za.existsSync(n))o=n;else if(Za.existsSync(fi.join("/",n)))o=fi.join("/",n);else throw new Error(`APK not found at path: ${n}`);return this.assertFileExists(o),{localPath:o,cleanup:()=>{}}}if(t.protocol==="http:"||t.protocol==="https:"){let n=await this.fetchWithTimeout(t);if(!n.ok)throw new Error(`Failed to download APK from ${e} (status ${n.status})`);let o=await n.arrayBuffer(),i=Buffer.from(o),a=await this.writeBufferToTempFile(i,t.pathname);return{localPath:a,cleanup:()=>{try{Za.unlinkSync(a)}catch(l){this.logger.warn({err:l,path:a},"Failed to remove temporary APK file")}}}}throw new Error(`Unsupported URI scheme for APK installation: ${t.protocol}`)}catch(t){if(t instanceof TypeError){let n=fi.resolve(e);return this.assertFileExists(n),{localPath:n,cleanup:()=>{}}}throw t}}assertFileExists(e){try{Za.accessSync(e)}catch{throw new Error(`APK not found at path: ${e}`)}}async fetchWithTimeout(e){let t=AbortSignal.timeout(9e4);return await fetch(e,{signal:t})}async writeBufferToTempFile(e,t){let n=fi.extname(t)||".apk",o=fi.join(pB(),`momentic-apk-${dB()}${n}`);return Za.writeFileSync(o,e),o}};import{existsSync as mB,readFileSync as gB}from"fs";import hB from"zod";var fB=hB.string().url();async function vR(r){if(fB.safeParse(r).success){let e=new AbortController,t=setTimeout(()=>e.abort(),1e4),n;try{n=await fetch(r,{signal:e.signal})}catch(i){throw new Error(`Fetch failed or timed out for URL: ${r}`,{cause:i})}finally{clearTimeout(t)}if(!n.ok)throw new Error(`Failed to fetch file from URL: ${r}, status: ${n.status}`);let o=await n.arrayBuffer();return Buffer.from(o).toString("base64")}if(!mB(r))throw new Error(`File does not exist at path: ${r}`);return gB(r).toString("base64")}import{execSync as RR}from"child_process";import bB from"pixelmatch";import{_android as EB,chromium as TB}from"playwright";import{PNG as CR}from"pngjs";import{z as je}from"zod";var AR=je.array(je.object({proc:je.string(),webview:je.string(),info:je.object({"Android-Package":je.string(),Browser:je.string(),"Protocol-Version":je.string(),"User-Agent":je.string(),"V8-Version":je.string(),"WebKit-Version":je.string(),webSocketDebuggerUrl:je.string()}),pages:je.array(je.object({description:je.string(),devtoolsFrontendUrl:je.string(),id:je.string(),title:je.string(),type:je.string(),url:je.string(),webSocketDebuggerUrl:je.string()})),webviewName:je.string()}));var jc=class r{driver;limbarClient;device;currentContext;logger;webviews=new Map;fixtures;orgId;options;aborter;constructor({driver:e,context:t,limbarClient:n,logger:o,device:i,fixtures:a,orgId:l,options:c,aborter:s}){this.driver=e,this.limbarClient=n,this.device=i,this.currentContext=t,this.logger=o,this.fixtures=a,this.orgId=l,this.options=c,this.aborter=s;for(let u of["SIGINT","SIGTERM"])process.on(u,async()=>{await this.cleanupWebviews()})}static async init({driver:e,logger:t,fixtures:n,limbarClient:o,orgId:i,adbPort:a,options:l,aborter:c}){let s=await e.getContext(),u=typeof s=="string"?s:s.id,d=(await EB.devices()).filter(g=>g._initializer?.serial?.endsWith(a.toString())||g._initializer?.serial?.endsWith((a-1).toString()));if(d.length===0)throw new Error(`Momentic found no devices listening on port ${a} or ${a-1}. This can occur if Android Studio reuses existing emulators. Please run 'adb emu kill' and 'adb disconnect' and retry.`);if(d.length>1)throw new Error(`Momentic found multiple devices on the ports ${a} or ${a-1}. This can occur if Android Studio reuses existing emulators. Please run 'adb emu kill' and 'adb disconnect' and retry.`);let p=d[0];return new r({driver:e,context:u,logger:t,device:p,fixtures:n,orgId:i,options:l,aborter:c,limbarClient:o})}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 getRawScreenshotBase64(e=1){let t=ve(),n;for(let o=0;o<e;o++)try{return await t.startAsyncSpan("EMULATOR_READ_STATE",async()=>await this.driver.takeScreenshot(),{name:"Take screenshot",signal:this.aborter.controller?.signal,timeoutMs:2e3})}catch(i){if(n=i,o===e-1)throw i}throw new Error(`Failed to take screenshot: ${n}`)}async getCurrentScreenshotPngString(){return`data:image/png;base64,${await this.getRawScreenshotBase64(1)}`}async waitForScreenshotStability({timeoutMs:e,signal:t,reason:n,tolerancePercent:o=1}){await ve().startAsyncSection("Waiting for stability",async(i,a)=>{a.attributes.reason=n;let l=Date.now(),c,s=!1,u=(d,p)=>{let m=Buffer.from(d,"base64"),g=Buffer.from(p,"base64"),h=CR.sync.read(m),f=CR.sync.read(g);if(h.width!==f.width||h.height!==f.height)return 100;let E=h.width,b=h.height,C=Buffer.alloc(E*b*4);return bB(h.data,f.data,C,E,b,{threshold:.01})/(E*b)*100};for(;Date.now()-l<e;){if(t?.throwIfAborted(),!c){c=await this.getRawScreenshotBase64();continue}let d=await this.getRawScreenshotBase64();if(u(c,d)<=o){s=!0;break}c=d,await X(250,t)}s||(a.attributes.timedOut=!0,this.logger.warn({purpose:n},"Timed out waiting for screenshot stability"))})}async getCurrentPackage(){let e=await this.driver.execute("mobile: getCurrentPackage");return typeof e=="string"?e:void 0}async getActiveWebviewNodes(){await this.refreshWebviews();let t=(await this.getDomState({skipWebviews:!0})).graph,n=await this.getCurrentPackage(),o=[];for(let[i,a]of t.idToElement.entries()){if(o.some(s=>s.id===i))continue;let l=a.getAttribute("content-desc");(Xa(a.tagName)||n==="com.android.chrome"&&l==="Web View"&&a.tagName.toLowerCase().startsWith("frame"))&&o.push({id:i,originalElement:a,bounds:mi(a)})}return o}async getActiveWebviewContent(){let e=await this.getActiveWebview();if(!e||!e.browserController)return;this.throwIfAborted();let t=e.browserController;return(await ve().startAsyncSpan("EMULATOR_READ_STATE",()=>t.getBrowserState({abortSignal:this.aborter.controller?.signal,serializationOpts:{noId:!0}}),{name:"Get webview content",signal:this.aborter.controller?.signal})).serializedTree}async getDomState(e){return await ve().startAsyncSection("Get emulator state XML",async()=>{let n;if(!e?.skipWebviews)try{n=await this.getActiveWebviewContent()}catch(a){this.logger.error({err:a},"Could not get webview info to get the nested DOM state")}this.throwIfAborted();let o=await this.getPageSource();return{graph:await gR(o,{injectedWebviewContent:n,disableMomenticAccessibilityTree:this.options.disableMomenticAccessibilityTree}),context:this.currentContext}},{timeoutMs:15e3})}async getPageSource(){return await ve().startAsyncSpan("EMULATOR_READ_STATE",()=>this.driver.getPageSource(),{name:"Get Android page source",signal:this.aborter.controller?.signal})}async refreshWebviews(){try{await this.refreshWebviewsHelper()}catch(e){this.logger.warn({err:e},"Error refreshing webviews, continuing...")}}async refreshWebviewsHelper(){await this.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"?(this.logger.info({webviewInfo:a},`Connecting Playwright to Android Chrome: ${o.webview}`),l=await this.connectPlaywrightToChrome(a),this.logger.info(`Connected Playwright to Android Chrome: ${o.webview}`)):(this.logger.info({webviewInfo:a},`Connecting 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 ve().startAsyncSection("Refresh webviews",async()=>{await this.refreshWebviews()});let e=await this.driver.execute("mobile: getCurrentPackage");e!==void 0&&typeof e!="string"&&this.logger.warn({currentPkg:e},"Unexpected getCurrentPackage result");let 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=RR(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(){return await ve().startAsyncSpan("EMULATOR_READ_STATE",async()=>{let t=await this.driver.execute("mobile: getContexts");return this.aborter.controller?.signal.throwIfAborted(),AR.parse(t).filter(o=>{if(!o.webviewName)return!0;let i=o.pages.filter(a=>{if(!a.title)return!1;let l=a.url;return!(!l||l===""||l.startsWith("about:blank")||l.startsWith("chrome-error:"))});return i||this.logger.debug({context:o},"Webview has no qualified pages, skipping"),i})},{name:"Get available contexts",signal:this.aborter.controller?.signal})}async createBrowserController({context:e}){return await ve().startSection("Run remote Chrome initialization",async(n,o)=>{let i={};o.attributes.timings=i;let a=await qa.fromExistingContext({context:e,logger:this.logger,timingRecorder:i,userBrowserSettings:{visualActions:!0,disableBrowserMonitoring:!0},properties:{isNewHeadless:!0,allowedA11yIgnoreReasonsOverride:[],isAndroid:!0},storage:this.fixtures.storage,enricher:this.fixtures.browserEnricher});return new Fc({browser:a,generator:this.fixtures.browserGenerator,logger:this.logger,orgId:this.orgId,storage:this.fixtures.storage,localCodeEvalTools:this.fixtures.localCodeEvalTools,visualDiffScreenshotStorage:new sl})})}async connectPlaywrightToWebview(e,t){return ve().startAsyncSection("Connect headless browser client to webview",async()=>this.connectPlaywrightToWebviewHelper(e,t),{signal:this.aborter.controller?.signal,timeoutMs:8e3,timeoutMsg:"Timed out connecting Playwright to the webview"})}async connectPlaywrightToWebviewHelper(e,t){let o=this.device.webViews().find(s=>!(s.pkg()!==e||"_socketName"in s&&typeof s._socketName=="string"&&s._socketName!==t));if(!o){this.logger.warn(`[WebviewManager] Could not find webview for ${e} with socket name ${t}`);return}let i=await o.page(),a=i.url();if(a===""||a.startsWith("about:blank")||a.startsWith("chrome-error:")){this.logger.warn({pageUrl:a},`Webview ${e} with socket ${t} is not a valid webview`);return}let l=i.context();return await this.createBrowserController({context:l})}async connectPlaywrightToChrome(e){return await ve().startAsyncSpan("EMULATOR_READ_STATE",async()=>this.connectPlaywrightToChromeHelper(e),{name:"Connect headless browser client to Chrome",signal:this.aborter.controller?.signal})}async connectPlaywrightToChromeHelper(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 TB.connectOverCDP({endpointURL:o,timeout:8e3}),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.warn({err:o},`Error connecting Playwright to webview ${e.contextId}, continuing...`);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=RR(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 Si=class r extends zt{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,limbarClient:s}){let u={controller:l},d=await jc.init({driver:e,logger:n,fixtures:o,orgId:i,limbarClient:s,options:a?.emulator??{},aborter:u,adbPort:c}),p=new r({driver:e,generator:t,stateManager:d,logger:n,fixtures:o,options:a,aborter:u,orgId:i,adbPort:c});return await p.initializeSettings(),p}async installApp(e){await this.stateManager.executeRawADBCommand(`install ${AB.resolve(e)}`)}async executeCommand(e){let t=["type","a11yData","thoughts","cache","code"],n;try{n=await uc({obj:e.command,context:this.fixtures.testContext,bannedKeys:t,orgId:this.orgId,logger:this.logger,signal:this.abortSignal,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{dc(e.command,n)}}async executeCommandHelper({command:e}){let t=ve();switch(e.type){case"TAP":return new hi(this.constructPerformerParams()).executeTap({command:e});case"TYPE":return await new Hc(this.constructPerformerParams()).doType(e);case"AI_CHECK":{let o=e.timeoutSecs?e.timeoutSecs*1e3:5e3,i=Sc(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 X(i,this.abortSignal),c=Date.now();try{let d="",p="";await t.startAsyncSpan("EMULATOR_READ_STATE",async()=>{d=(await this.stateManager.getDomState({})).graph.xml,p=await this.stateManager.getCurrentScreenshotPngString()},{name:"Get emulator state"});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:me(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"SWIPE":return new Gc(this.constructPerformerParams()).executeSwipe(e);case"JAVASCRIPT":{let n=await Or({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.abortSignal});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"REQUEST":{let n;try{n=new URL(e.url).hostname}catch(s){throw new Error(`UserConfigurationError: Invalid URL: ${s}`)}let o=new wB,i=vB(fetch,o),a=Date.now(),l=await Uc({command:e,baseUrl:void 0,logger:this.logger,fetchImplementation:i}),c=Hs(o,n);return{output:{...l,cookies:c},success:!0,message:`Successfully executed request in ${Date.now()-a}ms`}}case"OPEN_NOTIFICATION_DRAWER":return await new Cn(this.constructPerformerParams()).doPress({keycode:83}),{success:!0};case"OPEN_APP":{let n=e.activityName;if(!n){let i=["resolve-activity","--brief","-a","android.intent.action.MAIN","-c","android.intent.category.LAUNCHER",e.packageName],a=await F(this.driver.execute("mobile: shell",{command:"pm",args:i}),{signal:this.abortSignal,milliseconds:1e4});if(typeof a!="string")throw new Error(`Could not find main activity name for package ${e.packageName}. Unexpected output: ${a}`);if(a.includes("No activity found"))throw new Error(`No activity found for package ${e.packageName}.`);if(n=a.trim().split(`
4125
- `).pop()?.replace(/^.*\//,""),!n)throw new Error(`Could not parse main activity name for package ${e.packageName}. Raw output: ${a}`)}if(this.options.emulator?.autoGrantPermissions&&!this.appsWithGrantedPermissions.has(e.packageName)){let i={permissions:"all",appPackage:e.packageName,action:"grant"};await this.driver.executeScript("mobile: changePermissions",[i]),this.appsWithGrantedPermissions.add(e.packageName)}let o=["start"];if(e.intentExtras)try{let i=JSON.parse(e.intentExtras);for(let[a,l]of Object.entries(i))o.push("-e",a,typeof l=="string"?l:JSON.stringify(l))}catch(i){throw new Error(`UserConfigurationError: Invalid intent extras does not parse as valid JSON: ${i instanceof Error?i.message:`${i}`}`)}return o.push("-n",`${e.packageName}/${n}`),await this.driver.execute("mobile: shell",{command:"am",args:o}),await this.stateManager.waitForScreenshotStability({timeoutMs:5e3,signal:this.abortSignal,reason:"Waiting for stability after app launch"}),{success:!0}}case"PRESS":{let n=new Cn(this.constructPerformerParams());switch(e.key){case"HOME":await n.doPress({keycode:3});break;case"BACK":await n.doPress({keycode:4});break;case"APP_SWITCHER":await n.doPress({keycode:187});break;case"POWER":await n.doPress({keycode:26});break;case"SEARCH":await n.doPress({keycode:84});break;case"VOLUME_UP":await n.doPress({keycode:24});break;case"VOLUME_DOWN":await n.doPress({keycode:25});break;case"VOLUME_MUTE":await n.doPress({keycode:164});break}return{success:!0}}case"PRESS_KEYBOARD":{let n=new Cn(this.constructPerformerParams()),o=i=>n.doPress({keycode:i});switch(e.key){case"CLOSE_KEYBOARD":await this.driver.isKeyboardShown()&&await this.driver.hideKeyboard();break;case"ENTER":await o(66);break;case"BACKSPACE":await o(67);break;default:{let i=e}}return{success:!0}}case"WAIT":return await X(e.timeoutSecs*1e3,this.aborter.controller?.signal),{success:!0};case"INSTALL_APP":return new Vc(this.constructPerformerParams()).doInstallApk(e);case"ADD_FILE":{let n=await vR(e.file);return await this.driver.pushFile(e.storageLocation,n),await this.driver.execute("mobile: shell",{command:"am",args:["broadcast","-a","android.intent.action.MEDIA_SCANNER_SCAN_FILE","-d",`file://${e.storageLocation}`]}),{success:!0}}case"ADB":{let n=await this.driver.execute(e.command,JSON.parse(e.jsonArgs??"{}"));return this.logger.info({output:n},"ADB command executed successfully"),{success:!0,output:n,message:"ADB command executed successfully"}}case"KILL_APP":{let n=await this.stateManager.getCurrentPackage();if(!n)throw new Error("No package is currently active");await this.driver.execute("mobile: shell",{command:"input",args:["keyevent","KEYCODE_HOME"]}),await this.driver.terminateApp(n);try{await pR({packageName:n,driver:this.driver,abortSignal:this.abortSignal,logger:this.logger})}catch(o){this.throwIfAborted(),this.logger.warn({err:o,packageName:n},"Failed to remove package from recents, continuing...")}return{success:!0}}case"STATE":{await this.stateManager.refreshWebviews();let n=await this.stateManager.getDomState(),o=await this.stateManager.getContexts(),i={xml:n.graph.xml,contexts:o};return this.logger.info({result:i},"State debug command output"),{output:i,success:!0}}default:{let n=e;return{success:!0}}}}async initializeSettings(){}async getScreenshotBase64(){return this.stateManager.getRawScreenshotBase64()}async getScreenshotPngString(){return this.stateManager.getCurrentScreenshotPngString()}async getA11yTree(){return(await this.stateManager.getDomState({})).graph.xml}async waitForScreenshotStability(e){return this.stateManager.waitForScreenshotStability({timeoutMs:e.timeoutMs??5e3,reason:e.reason,signal:this.aborter.controller?.signal})}resetAbortController(e){this.aborter.controller=e??new AbortController}isAborted(){return this.aborter.controller?.signal.aborted}abort(){this.aborter.controller?.abort()}async cleanup(){await this.stateManager.cleanupWebviews()}get abortSignal(){return this.aborter.controller?.signal}get context(){return this.fixtures.testContext}get localCodeEvalTools(){return this.fixtures.localCodeEvalTools}};async function xR({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,C=h.settings?.defaultApkFilePath?.trim(),A=await n({testId:f});e=e.child({sessionId:d,testId:f,orgId:A});let M={...(await u(A,e)).emulator,...h.settings?.emulator},w;if(M.region==="local"){if(!M.localEmulatorSettings?.avdId)throw new Error("AVD name is required when region is local");w={avdId:M.localEmulatorSettings.avdId,apkToInstall:E?{channel:E,tag:b}:void 0,apkFilePath:C||void 0}}else w={region:M.region,apkToInstall:E?{channel:E,tag:b}:void 0};let D=Date.now(),{driver:j,cleanup:ae,emulatorName:Q,adbPort:pe,limbarClient:st,limbarToken:W,limbarUrl:z}=await t({socket:r,logger:e,creationOpts:w}),re=await cc({driver:j,onLogs:So=>{r.emit("logcatLogs",So)}});e.info({adbPort:pe,apkChannel:E,apkTag:b,duration:Date.now()-D,emulatorName:Q},"Android emulator session initiated"),e=e.child({emulator:Q});let le=await o(A,e),Xe=await i(A,e),we=await a(A,e),Dt=await l(A),wt=c?await c(A):void 0,Re={};h.settings?.defaultEnv&&(Re=(await Dt.fetchEnvironment(h.settings?.defaultEnv,e))?.variables??{});let We=new Uo({variablesFromEnvironment:Re,envName:h.settings?.defaultEnv,testName:g}),Rt=await Si.init({driver:j,generator:le,logger:e,limbarClient:st,options:{emulator:M},fixtures:{storage:Dt,browserEnricher:we,browserGenerator:Xe,localCodeEvalTools:wt,testContext:We},orgId:A,adbPort:pe,abortController:new AbortController});if(!r.connected)throw await re(),await ae(),new Error("Socket not connected anymore, not proceeding with Android session setup");let cr=RB({socket:r,testContext:We}),Br=async()=>{clearInterval(cr);try{await re(),await ae(),await Rt.cleanup()}catch(So){e.warn({err:So},"Failed to clean up emulator in socket server")}};return s.registerSession(d,{controller:Rt,cleanup:Br,emulatorName:Q,local:M.region==="local"}),r.emit("session",{testId:f,sessionId:d,limbarUrl:z,limbarToken:W}),{sessionId:d,testId:f,orgId:A,emulatorName:Q,logger:e}}function RB({socket:r,testContext:e}){return setInterval(()=>{let t=e.toEditorDisplayCopy();r.emit("emulatorState",{context:t})},3e3)}async function MR({socket:r,logger:e,globalStateManager:t}){await t.removeSession(r.id,e)}var CB=({socket:r,globalStateManager:e})=>async()=>{let t=e.getSession(r.id);if(!t)throw new Error("No active Android session found");t.controller.abort()},_R={event:"cancel",createHandler:CB};var xB=({logger:r,globalStateManager:e,socket:t})=>async(n,o)=>{let i=e.getSession(t.id);if(!i){o({err:"No active Android session found"});return}try{let l=await i.controller.getA11yTree();o({a11yTree:l})}catch(a){r.error({err:a},"Error fetching a11y tree from the session controller"),o({err:a.message})}},PR={event:"fetchA11yTree",createHandler:xB};import{diff as jB}from"deep-object-diff";import{cloneDeep as WB}from"lodash-es";function IR(r,e,t=1e4,n=5e3){let o=0;async function i(){try{let l=await F(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 OR(r){let e=Date.now(),t=r.fixtures.controller;try{return await MB(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 MB({moduleParams:r,...e}){let t=Date.now(),{step:n,stepTracer:o,executeMobileStepList:i}=r,a=await _B({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(),Vv({result:c,...Gv(d)}),c}async function _B({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 Or({orgId:e.inputs.orgId,code:a,fragment:!0,logger:n,context:o.context,localTools:o.localCodeEvalTools})}return t}import{randomUUID as LR}from"crypto";async function NR({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.getScreenshotBase64()}catch(s){i.warn({err:s},"Failed to take before screenshot")}let c={...e,status:"SUCCESS",startTime:o,endTime:Date.now()};try{let s=await a.executeCommand({command:e.command});c={...e,status:s.success?"SUCCESS":"FAILED",message:s.message,startTime:o,endTime:Date.now(),data:s.output}}catch(s){s instanceof Error&&s.name==="AbortError"||a.isAborted()?c={...e,status:"CANCELLED",message:"Step cancelled.",startTime:o,endTime:Date.now()}:(i.error({err:s},"Failed to execute preset step"),c={...e,status:"FAILED",message:s instanceof Error?s.message:String(s),startTime:o,endTime:Date.now()})}finally{if(!t.interactive){try{let s=LR(),u=await a.getScreenshotBase64();c.afterSnapshot=s,n.attachAfterScreenshot({logger:i,snapshotId:s,screenshot:Buffer.from(u,"base64")})}catch(s){i.warn({err:s},"Failed to take after screenshot")}if(l){let s=LR();c.beforeSnapshot=s,n.attachBeforeScreenshot({logger:i,snapshotId:s,screenshot:Buffer.from(l,"base64")})}}}return c}import{streamText as zB}from"ai";import{randomUUID as HB}from"crypto";var Wc=class{controller;logger;callbacks;rootStep;subStepIndex=0;finalState=void 0;results=[];constructor(e){let{controller:t,logger:n,callbacks:o,rootStep:i}=e;this.controller=t,this.logger=n,this.callbacks=o,this.rootStep=i}async createAndExecuteStep(e){this.callbacks.onAiActionEvent?.({type:"SUBSTEP_CREATED",rootStep:this.rootStep,step:e});let t=this.subStepIndex++,n=await this.callbacks.executeStep(e,t);return this.results.push(n),n}};import{hasToolCall as FB,stepCountIs as BB}from"ai";var DR="get_emulator_state",$c="finish";import kR from"dedent";var IB=kR`
4104
+ `));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(oB(g.tagName));SR(r,g,h),t.appendChild(h)}}}function dB(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;SR(a,e,l);let c=new rB().serializeToString(o);return{prunedDocument:o,prunedIdToElement:i,xml:c}}async function yR(r,e){let t=new tB,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}=dB(t,i,o,e);return{xml:await eB.format(c,{parser:"xml",plugins:[QF],printWidth:120,tabWidth:1,singleAttributePerLine:!1}),originalXml:r,document:n,idToElement:o,prunedDocument:a,prunedIdToElement:l}}function pB(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 Vc(r,e){let t=r.idToElement.get(e);if(t)return pB(t)}function Jm(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 gi(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 Zm(r,e){if(r&&!(!e||e.length===0))return Object.fromEntries(e.map(t=>[t,r.getAttribute(t)]).filter(([,t])=>t!==null))}function TR({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=gi(n);if(!o)throw new Error(`Node ${r.id} has no bounding box: ${n.outerHTML}`);let i=Vc(t.graph,r.id)??"",a=Jm(t.graph,r.id)??"",l=t.graph.idToElement.get(r.id),c=Zm(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=Vc(t.graph,m);return f?{xPath:f,requirements:{requiredText:g.textRequired?h.getAttribute("text")??void 0:void 0,requiredAttributes:Zm(h,g.attributesRequired),requiredBounds:g.boundsRequired}}:void 0}).filter(m=>!!m));let p;return Za(n.tagName)&&r.inWebview!==!1?p={type:"WEBVIEW",resolvedDescription:e,xPath:i}:p={type:"NATIVE",bounds:o,resolvedDescription:e,xPath:i,elementOnlySerializedXml:a,requirements:u,requiredRelatedElements:d},p}var ER=(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=gi(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 vR(r){let{target:e,domState:t}=r,{graph:n}=t,{document:o}=n,i=Ae();if(e.type==="WEBVIEW")return mB(e,r);let a=bR.evaluateXPathToFirstNode(e.xPath,o,null,null);if(!a)throw new Error(`ActionFailureError: Could not resolve cached target via XPath: ${e.xPath}`);if(e.requiredRelatedElements){let p=e.requiredRelatedElements;i.startSection("Validate related elements are similar enough to past runs",()=>{for(let m of p){let g=bR.evaluateXPathToFirstNode(m.xPath,o);if(!g)throw new Error(`ActionFailureError: Required related element not found for XPath: ${m.xPath}`);ER(g,m.requirements)}})}let l=gi(a);if(!l)throw new Error("ActionFailureError: Resolved native element has no bounding box");ER(a,e.requirements,e.bounds);let c;for(let[p,m]of n.idToElement.entries())if(m===a){c=p;break}let s=e.elementOnlySerializedXml,u=e.xPath;return c!==void 0&&(s=Jm(n,c)??s,u=Vc(n,c)??u),{resolvedTarget:{...e,bounds:l,elementOnlySerializedXml:s,xPath:u}}}async function mB(r,e){let{stateManager:t,logger:n,signal:o}=e,i=Ae(),a=await t.getActiveWebview();if(!a||!a.browserController)throw new Error("No browser controller is attached to the requested webview");let l=a.browserController.browser;if(!r.browserCache)throw new Error("No browser target available on cache");let c=r.browserCache,s=await i.startAsyncSection("Resolve target in webview",()=>l.resolveTarget(null,c,{logger:n,signal:o}));return{resolvedTarget:{...r,controller:a.browserController,resolution:s}}}function Qm(r){let{command:e,cacheKey:t="cache",targetName:n="target",updatedCache:o}=r;$s(e)&&(e[t]={...e[t],[n]:js.parse(o)},r.updatedWithAI&&(e[t].updatedAt=new Date))}function AR(r){return r.type==="WEBVIEW"?{type:"WEBVIEW",resolvedDescription:r.resolvedDescription,xPath:r.xPath,browserCache:r.browserCache}:r}var zt=class{driver;generator;stateManager;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,reason:"Waiting for stability before locating an element with AI"});let n=await t.startAsyncSection("Get emulator state",async()=>{let c=await this.stateManager.getDomState(),s=await this.stateManager.getCurrentScreenshotPngString();return{emulatorState:c,screenshot:s}}),o;try{o=await t.startAsyncSpan("AI_LOCATOR_CALL",async c=>{let s=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});return c.result=s,s})}catch(c){throw this.throwIfAborted(),this.logger.error({err:c},"Failed to locate element"),new Error(`ActionFailureError: Failed to locate element: ${c instanceof Error?c.message:c}`)}if(o.id===-1)throw new Error(`ActionFailureError: No matching element found: ${o.thoughts}`);let i=TR({aiResponse:o,description:e,emulatorState:n.emulatorState});if(i.type==="NATIVE")return t.addSpan({type:"TARGET_RESOLUTION",startTime:Date.now(),endTime:Date.now(),result:{serializedElement:i.elementOnlySerializedXml},attributes:{}}),{resolvedTarget:i,thoughts:o.thoughts};let{browserLocateResult:a,browserController:l}=await t.startAsyncSpan("TARGET_RESOLUTION",async c=>{let s=await this.stateManager.getActiveWebview();if(!s||!s.browserController)throw new Error("No browser controller is attached to the requested webview");let u=await s.browserController.locateElement({description:e,disableCache:!1,logger:this.logger});return c.result={serializedElement:u.target.nodeOnlySerializedHtml??"Unknown HTML element in webview"},{browserLocateResult:u,browserController:s.browserController}});return{resolvedTarget:{...i,controller:l,resolution:a.resolution,browserCache:a.target},thoughts:a.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=hB(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({description:n,cacheDescription:p?.resolvedDescription},"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});m=h.thoughts;let f=await t(h.resolvedTarget);return Qm({command:o,cacheKey:i,targetName:a,updatedCache:h.resolvedTarget,updatedWithAI:!0}),{result:f,thoughts:m}}let g;try{await this.stateManager.waitForScreenshotStability({timeoutMs:5e3,signal:this.aborter.controller?.signal,reason:"Waiting for stability before cache resolution"}),g=await this.stateManager.getDomState();let{resolvedTarget:h,updatedCache:f}=await c.startAsyncSection("Resolve target cache",async(b,x)=>{let{resolvedTarget:A}=await vR({target:p,domState:g,stateManager:this.stateManager,logger:this.logger}),v=AR(A),_=gB(p,v);return _&&Object.keys(_).length>0&&this.logger.info({cacheDiffs:_},"Successfully resolved target with cache"),x.attributes.serializedElement=A.type==="WEBVIEW"?A.browserCache?.nodeOnlySerializedHtml??"Unknown HTML element in webview":A.elementOnlySerializedXml,{resolvedTarget:A,updatedCache:v}}),E=await t(h);return Qm({command:o,cacheKey:i,targetName:a,updatedCache:f,updatedWithAI:!1}),p.type!=="WEBVIEW"&&At.increment("cache_target_resolution_v2",1,["outcome:hit","platform:native",`hasRequirements:${!!p.requirements}`,`hasAdditionalElements:${!!p.requiredRelatedElements?.length}`,`orgId:${this.orgId}`,"cliVersion:0.4.1"]),{result:E,thoughts:"Successfully executed preset action with cache."}}catch(h){if(p.type!=="WEBVIEW"&&At.increment("cache_target_resolution_v2",1,["outcome:miss","platform:native",`hasRequirements:${!!p.requirements}`,`hasAdditionalElements:${!!p.requiredRelatedElements?.length}`,`orgId:${this.orgId}`,"cliVersion:0.4.1"]),this.throwIfAborted(),u>0)return this.logger.warn({err:h},"Failed to resolve target cache, retrying with AI"),this.logger.debug({domState:g?.graph.originalXml},"Emulator state"),this.wrapTargetingAction({...e,cacheIsInvalidAfterResolution:!0,retriesWithAI:u-1});throw new Error(`ActionFailureError: ${h instanceof Error?h.message:h}`,{cause:h})}}constructPerformerParams(){return{stateManager:this.stateManager,generator:this.generator,driver:this.driver,logger:this.logger,fixtures:this.fixtures,aborter:this.aborter,orgId:this.orgId}}throwIfAborted(){this.aborter.controller?.signal.throwIfAborted()}get abortSignal(){return this.aborter.controller?.signal}};function yB(r){let e={relativePosition:r.relativePosition};if(r.doubleTap&&r.longPress)throw new Error("UserConfigurationError: Cannot specify both doubleTap and longPress");return r.doubleTap?{...e,doubleTap:!0,doubleTapDelayMs:r.doubleTapDelayMs}:r.longPress?{...e,longPress:!0,longPressDurationMs:r.longPressDurationMs}:e}var fi=class extends zt{async tapOnAbsoluteCoordinates(e){let t=e.x,n=e.y;if(this.logger.info({x:t,y:n},"Tap at coordinates"),e.longPress)return await this.driver.executeScript("mobile: longClickGesture",[{x:t,y:n,duration:e.longPressDurationMs??2e3}]);if(e.doubleTap){await this.driver.tap({x:t,y:n});let o=e.doubleTapDelayMs??100;await new Promise(i=>setTimeout(i,o))}await this.driver.tap({x:t,y:n})}async tapOnNativeTarget(e,t){let[n,o,i,a]=e.bounds,l=i-n,c=a-o,s=t?.relativePosition?.x??l/2,u=t?.relativePosition?.y??c/2;s=Math.max(0,Math.min(s,l)),u=Math.max(0,Math.min(u,c));let d=n+s,p=o+u;return await this.tapOnAbsoluteCoordinates({x:d,y:p,...t}),{x:d,y:p}}async tapOnWebviewTarget(e,t){let{controller:n}=e;return(await n.browser.click(e.resolution,{createIsolatedFolder:()=>{let i=Math.random().toString(36).substring(4),a=wR.join(SB(),"momentic","downloads"),l=wR.join(a,this.orgId,i);return fB(l,{recursive:!0}),l}},{delayMs:t?.longPress?t?.longPressDurationMs??2e3:void 0,relativePosition:t?.relativePosition,doubleClick:t?.doubleTap})).coordinates}async tapOnTarget({target:e,options:t}){return await Ae().startAsyncSpan("EMULATOR_INTERACTION",async o=>{o.attributes.options=t,"type"in e&&e.type==="NATIVE"?o.attributes.point=await this.tapOnNativeTarget(e,t):(o.withinWebview=!0,o.attributes.point=await this.tapOnWebviewTarget(e,t))},{name:"Tap on target"})}async executeTap({command:e}){let t=Ae(),n=yB(e);if(e.target.type==="coordinates"){let a=await this.driver.getWindowSize(),l=e.target.xPercent*a.width,c=e.target.yPercent*a.height;return await t.startAsyncSpan("EMULATOR_INTERACTION",async()=>{await this.tapOnAbsoluteCoordinates({...n,x:l,y:c})},{name:`Tap at coordinates ${l}, ${c}`}),{success:!0,message:`Tapped at ${l}, ${c}`}}let o=e.target.description,{thoughts:i}=await this.wrapTargetingAction({command:e,tracer:t,action:a=>this.tapOnTarget({target:a,options:n}),description:o});return{success:!0,message:i}}};var xn=class extends zt{async doPress({keycode:e,longPress:t}){await Ae().startAsyncSpan("EMULATOR_INTERACTION",async()=>this.driver.executeScript("mobile: pressKey",[{keycode:e,isLongPress:t}]),{name:"Send key events to emulator"})}};var jc=class extends zt{async doType(e){if(!e.target){if(e.clearContent)throw new Error("UserConfigurationError: clearing content is only supported when a target is provided to the Type step");return await this.sendKeys(e),{success:!0,message:void 0}}if(e.target.type!=="description")throw new Error("UserConfigurationError: x/y targets are not supported for the Type step");let t=Ae(),{thoughts:n}=await this.wrapTargetingAction({command:e,tracer:t,action:async o=>{"type"in o&&o.type==="NATIVE"?await this.doNativeType(e,o):await this.doWebviewType(e,o)},description:e.target.description});return{success:!0,message:n}}async doWebviewType(e,t){await Ae().startAsyncSpan("EMULATOR_INTERACTION",async o=>{o.withinWebview=!0,o.attributes.options={clearContent:e.clearContent};let{controller:i,resolution:a}=t;await i.browser.typeIntoTarget(e.text,a,{clearContent:e.clearContent,delay:e.keyPressDelayMs})},{name:"Typing within web view"})}async doNativeType(e,t){let n=new fi(this.constructPerformerParams());e.clearContent?(await n.tapOnNativeTarget(t,{longPress:!0}),await this.clearContent()):await n.tapOnNativeTarget(t),await this.stateManager.waitForScreenshotStability({timeoutMs:2e3,signal:this.aborter.controller?.signal,reason:"Waiting for keyboard to appear before typing"}),await this.sendKeys(e)}async sendKeys(e){let t=Ae(),n=e.keyPressDelayMs;n?await t.startAsyncSpan("EMULATOR_INTERACTION",async()=>{await this.driver.updateSettings({keyInjectionDelay:n}),await this.driver.keys(e.text),await this.driver.updateSettings({keyInjectionDelay:0})},{name:"Typing keys with a delay"}):await t.startAsyncSpan("EMULATOR_INTERACTION",async()=>{await this.driver.keys(e.text)},{name:"Typing keys"})}async clearContent(){let e=Ae();try{await e.startAsyncSection("Clearing any content from the focused field",()=>this.clearContentHelper())}catch(t){this.logger.warn({err:t},"Failed to clear content because the select all button was not found, continuing...")}}async clearContentHelper(){let e=this.driver.$('//android.widget.LinearLayout[@content-desc="Select all" and @clickable="true"]');await e.waitForExist({timeout:750}),await e.click(),await new xn(this.constructPerformerParams()).doPress({keycode:67})}};import Gt from"zod";var RR=.9,bB=Gt.object({navigationBar:Gt.object({visible:Gt.boolean(),x:Gt.number(),y:Gt.number(),width:Gt.number(),height:Gt.number()}),statusBar:Gt.object({visible:Gt.boolean(),x:Gt.number(),y:Gt.number(),width:Gt.number(),height:Gt.number()})}),Wc=class extends zt{async executeSwipe(e){let t=Ae();if(e.scrollableElement.type!=="CUSTOM"){await this.stateManager.waitForScreenshotStability({timeoutMs:2e3,signal:this.aborter.controller?.signal,reason:"Waiting for screen to stabilize before swiping"});let n=await this.driver.getWindowRect(),o;switch(e.scrollableElement.type){case"SCREEN":o={left:n.x+25,top:n.y+50,width:n.width-50,height:n.height-100};break;case"OPEN_APP":try{let i=bB.parse(await this.driver.executeScript("mobile: getSystemBars",[]));o={left:n.x+25,top:n.y+50,width:n.width-50,height:n.height-100},i.navigationBar.visible&&(o.height-=i.navigationBar.height),i.statusBar.visible&&(o.top+=i.statusBar.height,o.height-=i.statusBar.height)}catch(i){this.logger.warn({err:i},"Failed to get system bars, using hardcoded bounds"),o={left:n.x+50,top:n.y+100,width:n.width-100,height:n.height-200}}break;case"OPEN_WEBVIEW":{let i=await this.stateManager.getActiveWebviewNodes();if(i.length===0)throw new Error("No active webviews found");if(i.length>1)throw new Error("Multiple active webviews found");let a=i[0]?.bounds;if(!a)throw new Error("No bounds found for active webview");o={left:a[0]+50,top:a[1]+100,width:a[2]-a[0]-100,height:a[3]-a[1]-200};break}default:{let i=e.scrollableElement;throw new Error("If Typescript complains about the line above, you missed a switch case")}}return await t.startAsyncSpan("EMULATOR_INTERACTION",async i=>{await this.swipeByAbsoluteCoordinates({span:i,direction:e.direction,percent:e.viewportPercent,durationMs:e.durationMs,containerBounds:o})},{name:`Swipe ${e.direction} in the entire ${e.scrollableElement.type.toLowerCase()}`}),{success:!0}}return await this.wrapTargetingAction({command:e,description:e.scrollableElement.target.description,action:async n=>Ae().startAsyncSpan("EMULATOR_INTERACTION",async i=>"type"in n&&n.type==="NATIVE"?this.scrollInNativeContainer({span:i,cmd:e,target:n}):(i.withinWebview=!0,this.scrollInWebview({cmd:e,target:n})),{name:`Swipe ${e.direction} in the specified container`}),tracer:t}),{success:!0}}async scrollInNativeContainer({span:e,cmd:t,target:n}){let o=Math.floor(n.bounds[2]*.05),i=Math.floor(n.bounds[3]*.05);await this.swipeByAbsoluteCoordinates({span:e,direction:t.direction,percent:t.viewportPercent,durationMs:t.durationMs,containerBounds:{left:n.bounds[0]+o,top:n.bounds[1]+i,width:n.bounds[2]-n.bounds[0]-o*2,height:n.bounds[3]-n.bounds[1]-i*2}})}async scrollInWebview({cmd:e,target:t}){let{controller:n}=t,o=n.browser.getViewport();if(!o)throw new Error("Failed to get viewport size from webview");if(e.direction==="down"||e.direction==="up"){let i=o.height*(e.viewportPercent??RR)*(e.direction==="down"?1:-1);await n.browser.scrollVertical(i)}else{let i=o.width*(e.viewportPercent??.9)*(e.direction==="right"?1:-1);await n.browser.scrollHorizontal(i)}}async swipeByAbsoluteCoordinates({span:e,direction:t,percent:n=RR,durationMs:o=500,containerBounds:i}){e.attributes.containerBounds=i;let a,l;t==="up"||t==="down"?(a=i.height*n,l=Math.floor(a/(o/1e3))):(a=i.width*n,l=Math.floor(a/(o/1e3))),e.attributes.pixelDelta=a,e.attributes.pixelsPerSecond=l,await this.driver.executeScript("mobile: swipeGesture",[{...i,direction:t,percent:n,speed:l}])}};import{randomUUID as EB}from"crypto";import es from"fs";import{tmpdir as TB}from"os";import Si from"path";var $c=class extends zt{async doInstallApk(e){return await this.installApkFromUri(e.uri),{success:!0,message:"Installed APK."}}async installApkFromUri(e){let t=await this.resolveUriToLocalApk(e);try{await this.stateManager.executeRawADBCommand(`install ${Si.resolve(t.localPath)}`),this.logger.info({uri:e,localPath:t.localPath},"Installed APK on device")}finally{t.cleanup()}}async resolveUriToLocalApk(e){try{let t=new URL(e);if(t.protocol==="file:"){let n=t.href.slice(7),o;if(es.existsSync(n))o=n;else if(es.existsSync(Si.join("/",n)))o=Si.join("/",n);else throw new Error(`APK not found at path: ${n}`);return this.assertFileExists(o),{localPath:o,cleanup:()=>{}}}if(t.protocol==="http:"||t.protocol==="https:"){let n=await this.fetchWithTimeout(t);if(!n.ok)throw new Error(`Failed to download APK from ${e} (status ${n.status})`);let o=await n.arrayBuffer(),i=Buffer.from(o),a=await this.writeBufferToTempFile(i,t.pathname);return{localPath:a,cleanup:()=>{try{es.unlinkSync(a)}catch(l){this.logger.warn({err:l,path:a},"Failed to remove temporary APK file")}}}}throw new Error(`Unsupported URI scheme for APK installation: ${t.protocol}`)}catch(t){if(t instanceof TypeError){let n=Si.resolve(e);return this.assertFileExists(n),{localPath:n,cleanup:()=>{}}}throw t}}assertFileExists(e){try{es.accessSync(e)}catch{throw new Error(`APK not found at path: ${e}`)}}async fetchWithTimeout(e){let t=AbortSignal.timeout(9e4);return await fetch(e,{signal:t})}async writeBufferToTempFile(e,t){let n=Si.extname(t)||".apk",o=Si.join(TB(),`momentic-apk-${EB()}${n}`);return es.writeFileSync(o,e),o}};import{existsSync as vB,readFileSync as AB}from"fs";import wB from"zod";var RB=wB.string().url();async function CR(r){if(RB.safeParse(r).success){let e=new AbortController,t=setTimeout(()=>e.abort(),1e4),n;try{n=await fetch(r,{signal:e.signal})}catch(i){throw new Error(`Fetch failed or timed out for URL: ${r}`,{cause:i})}finally{clearTimeout(t)}if(!n.ok)throw new Error(`Failed to fetch file from URL: ${r}, status: ${n.status}`);let o=await n.arrayBuffer();return Buffer.from(o).toString("base64")}if(!vB(r))throw new Error(`File does not exist at path: ${r}`);return AB(r).toString("base64")}import{execSync as _R}from"child_process";import MB from"pixelmatch";import{_android as _B,chromium as PB}from"playwright";import{PNG as PR}from"pngjs";import{z as je}from"zod";var xR=je.array(je.object({proc:je.string(),webview:je.string(),info:je.object({"Android-Package":je.string(),Browser:je.string(),"Protocol-Version":je.string(),"User-Agent":je.string(),"V8-Version":je.string(),"WebKit-Version":je.string(),webSocketDebuggerUrl:je.string()}),pages:je.array(je.object({description:je.string(),devtoolsFrontendUrl:je.string(),id:je.string(),title:je.string(),type:je.string(),url:je.string(),webSocketDebuggerUrl:je.string()})),webviewName:je.string()}));var qc=class r{driver;limbarClient;device;currentContext;logger;webviews=new Map;fixtures;orgId;options;aborter;constructor({driver:e,context:t,limbarClient:n,logger:o,device:i,fixtures:a,orgId:l,options:c,aborter:s}){this.driver=e,this.limbarClient=n,this.device=i,this.currentContext=t,this.logger=o,this.fixtures=a,this.orgId=l,this.options=c,this.aborter=s;for(let u of["SIGINT","SIGTERM"])process.on(u,async()=>{await this.cleanupWebviews()})}static async init({driver:e,logger:t,fixtures:n,limbarClient:o,orgId:i,adbPort:a,options:l,aborter:c}){let s=await e.getContext(),u=typeof s=="string"?s:s.id,d=(await _B.devices()).filter(g=>g._initializer?.serial?.endsWith(a.toString())||g._initializer?.serial?.endsWith((a-1).toString()));if(d.length===0)throw new Error(`Momentic found no devices listening on port ${a} or ${a-1}. This can occur if Android Studio reuses existing emulators. Please run 'adb emu kill' and 'adb disconnect' and retry.`);if(d.length>1)throw new Error(`Momentic found multiple devices on the ports ${a} or ${a-1}. This can occur if Android Studio reuses existing emulators. Please run 'adb emu kill' and 'adb disconnect' and retry.`);let p=d[0];return new r({driver:e,context:u,logger:t,device:p,fixtures:n,orgId:i,options:l,aborter:c,limbarClient:o})}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 getRawScreenshotBase64(e=1){let t=Ae(),n;for(let o=0;o<e;o++)try{return await t.startAsyncSpan("EMULATOR_READ_STATE",async()=>await this.driver.takeScreenshot(),{name:"Take screenshot",signal:this.aborter.controller?.signal,timeoutMs:2e3})}catch(i){if(n=i,o===e-1)throw i}throw new Error(`Failed to take screenshot: ${n}`)}async getCurrentScreenshotPngString(){return`data:image/png;base64,${await this.getRawScreenshotBase64(1)}`}async waitForScreenshotStability({timeoutMs:e,signal:t,reason:n,tolerancePercent:o=1}){await Ae().startAsyncSection("Waiting for stability",async(i,a)=>{a.attributes.reason=n;let l=Date.now(),c,s=!1,u=(d,p)=>{let m=Buffer.from(d,"base64"),g=Buffer.from(p,"base64"),h=PR.sync.read(m),f=PR.sync.read(g);if(h.width!==f.width||h.height!==f.height)return 100;let E=h.width,b=h.height,x=Buffer.alloc(E*b*4);return MB(h.data,f.data,x,E,b,{threshold:.01})/(E*b)*100};for(;Date.now()-l<e;){if(t?.throwIfAborted(),!c){c=await this.getRawScreenshotBase64();continue}let d=await this.getRawScreenshotBase64();if(u(c,d)<=o){s=!0;break}c=d,await Y(250,t)}s||(a.attributes.timedOut=!0,this.logger.warn({purpose:n},"Timed out waiting for screenshot stability"))})}async getCurrentPackage(){let e=await this.driver.execute("mobile: getCurrentPackage");return typeof e=="string"?e:void 0}async getActiveWebviewNodes(){await this.refreshWebviews();let t=(await this.getDomState({skipWebviews:!0})).graph,n=await this.getCurrentPackage(),o=[];for(let[i,a]of t.idToElement.entries()){if(o.some(s=>s.id===i))continue;let l=a.getAttribute("content-desc");(Za(a.tagName)||n==="com.android.chrome"&&l==="Web View"&&a.tagName.toLowerCase().startsWith("frame"))&&o.push({id:i,originalElement:a,bounds:gi(a)})}return o}async getActiveWebviewContent(){let e=await this.getActiveWebview();if(!e||!e.browserController)return;this.throwIfAborted();let t=e.browserController;return(await Ae().startAsyncSpan("EMULATOR_READ_STATE",()=>t.getBrowserState({abortSignal:this.aborter.controller?.signal,serializationOpts:{noId:!0}}),{name:"Get webview content",signal:this.aborter.controller?.signal})).serializedTree}async getDomState(e){return await Ae().startAsyncSection("Get emulator state XML",async()=>{let n;if(!e?.skipWebviews)try{n=await this.getActiveWebviewContent()}catch(a){this.logger.error({err:a},"Could not get webview info to get the nested DOM state")}this.throwIfAborted();let o=await this.getPageSource();return{graph:await yR(o,{injectedWebviewContent:n,disableMomenticAccessibilityTree:this.options.disableMomenticAccessibilityTree}),context:this.currentContext}},{timeoutMs:15e3})}async getPageSource(){return await Ae().startAsyncSpan("EMULATOR_READ_STATE",()=>this.driver.getPageSource(),{name:"Get Android page source",signal:this.aborter.controller?.signal})}async refreshWebviews(){try{await this.refreshWebviewsHelper()}catch(e){this.logger.warn({err:e},"Error refreshing webviews, continuing...")}}async refreshWebviewsHelper(){await this.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"?(this.logger.info({webviewInfo:a},`Connecting Playwright to Android Chrome: ${o.webview}`),l=await this.connectPlaywrightToChrome(a),this.logger.info(`Connected Playwright to Android Chrome: ${o.webview}`)):(this.logger.info({webviewInfo:a},`Connecting 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 Ae().startAsyncSection("Refresh webviews",async()=>{await this.refreshWebviews()});let e=await this.driver.execute("mobile: getCurrentPackage");e!==void 0&&typeof e!="string"&&this.logger.warn({currentPkg:e},"Unexpected getCurrentPackage result");let 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=_R(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(){return await Ae().startAsyncSpan("EMULATOR_READ_STATE",async()=>{let t=await this.driver.execute("mobile: getContexts");return this.aborter.controller?.signal.throwIfAborted(),xR.parse(t).filter(o=>{if(!o.webviewName)return!0;let i=o.pages.filter(a=>{if(!a.title)return!1;let l=a.url;return!(!l||l===""||l.startsWith("about:blank")||l.startsWith("chrome-error:"))});return i||this.logger.debug({context:o},"Webview has no qualified pages, skipping"),i})},{name:"Get available contexts",signal:this.aborter.controller?.signal})}async createBrowserController({context:e}){return await Ae().startSection("Run remote Chrome initialization",async(n,o)=>{let i={};o.attributes.timings=i;let a=await Ya.fromExistingContext({context:e,logger:this.logger,timingRecorder:i,userBrowserSettings:{visualActions:!0,disableBrowserMonitoring:!0},properties:{isNewHeadless:!0,allowedA11yIgnoreReasonsOverride:[],isAndroid:!0},storage:this.fixtures.storage,enricher:this.fixtures.browserEnricher});return new Hc({browser:a,generator:this.fixtures.browserGenerator,logger:this.logger,orgId:this.orgId,storage:this.fixtures.storage,localCodeEvalTools:this.fixtures.localCodeEvalTools,visualDiffScreenshotStorage:new cl})})}async connectPlaywrightToWebview(e,t){return Ae().startAsyncSection("Connect headless browser client to webview",async()=>this.connectPlaywrightToWebviewHelper(e,t),{signal:this.aborter.controller?.signal,timeoutMs:8e3,timeoutMsg:"Timed out connecting Playwright to the webview"})}async connectPlaywrightToWebviewHelper(e,t){let o=this.device.webViews().find(s=>!(s.pkg()!==e||"_socketName"in s&&typeof s._socketName=="string"&&s._socketName!==t));if(!o){this.logger.warn(`[WebviewManager] Could not find webview for ${e} with socket name ${t}`);return}let i=await o.page(),a=i.url();if(a===""||a.startsWith("about:blank")||a.startsWith("chrome-error:")){this.logger.warn({pageUrl:a},`Webview ${e} with socket ${t} is not a valid webview`);return}let l=i.context();return await this.createBrowserController({context:l})}async connectPlaywrightToChrome(e){return await Ae().startAsyncSpan("EMULATOR_READ_STATE",async()=>this.connectPlaywrightToChromeHelper(e),{name:"Connect headless browser client to Chrome",signal:this.aborter.controller?.signal})}async connectPlaywrightToChromeHelper(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 PB.connectOverCDP({endpointURL:o,timeout:8e3}),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.warn({err:o},`Error connecting Playwright to webview ${e.contextId}, continuing...`);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=_R(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 yi=class r extends zt{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,limbarClient:s}){let u={controller:l},d=await qc.init({driver:e,logger:n,fixtures:o,orgId:i,limbarClient:s,options:a?.emulator??{},aborter:u,adbPort:c}),p=new r({driver:e,generator:t,stateManager:d,logger:n,fixtures:o,options:a,aborter:u,orgId:i,adbPort:c});return await p.initializeSettings(),p}async installApp(e){await this.stateManager.executeRawADBCommand(`install ${OB.resolve(e)}`)}async executeCommand(e){let t=["type","a11yData","thoughts","cache","code"],n;try{n=await pc({obj:e.command,context:this.fixtures.testContext,bannedKeys:t,orgId:this.orgId,logger:this.logger,signal:this.abortSignal,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{mc(e.command,n)}}async executeCommandHelper({command:e}){let t=Ae();switch(e.type){case"TAP":return new fi(this.constructPerformerParams()).executeTap({command:e});case"TYPE":return await new jc(this.constructPerformerParams()).doType(e);case"AI_CHECK":{let o=e.timeoutSecs?e.timeoutSecs*1e3:5e3,i=bc(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 Y(i,this.abortSignal),c=Date.now();try{let d="",p="";await t.startAsyncSpan("EMULATOR_READ_STATE",async()=>{d=(await this.stateManager.getDomState({})).graph.xml,p=await this.stateManager.getCurrentScreenshotPngString()},{name:"Get emulator state"});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"SWIPE":return new Wc(this.constructPerformerParams()).executeSwipe(e);case"JAVASCRIPT":{let n=await Nr({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.abortSignal});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"REQUEST":{let n;try{n=new URL(e.url).hostname}catch(s){throw new Error(`UserConfigurationError: Invalid URL: ${s}`)}let o=new LB,i=IB(fetch,o),a=Date.now(),l=await zc({command:e,baseUrl:void 0,logger:this.logger,fetchImplementation:i}),c=Vs(o,n);return{output:{...l,cookies:c},success:!0,message:`Successfully executed request in ${Date.now()-a}ms`}}case"OPEN_NOTIFICATION_DRAWER":return await new xn(this.constructPerformerParams()).doPress({keycode:83}),{success:!0};case"OPEN_APP":{let n=e.activityName;if(!n){let i=["resolve-activity","--brief","-a","android.intent.action.MAIN","-c","android.intent.category.LAUNCHER",e.packageName],a=await k(this.driver.execute("mobile: shell",{command:"pm",args:i}),{signal:this.abortSignal,milliseconds:1e4});if(typeof a!="string")throw new Error(`Could not find main activity name for package ${e.packageName}. Unexpected output: ${a}`);if(a.includes("No activity found"))throw new Error(`No activity found for package ${e.packageName}.`);if(n=a.trim().split(`
4105
+ `).pop()?.replace(/^.*\//,""),!n)throw new Error(`Could not parse main activity name for package ${e.packageName}. Raw output: ${a}`)}if(this.options.emulator?.autoGrantPermissions&&!this.appsWithGrantedPermissions.has(e.packageName)){let i={permissions:"all",appPackage:e.packageName,action:"grant"};await this.driver.executeScript("mobile: changePermissions",[i]),this.appsWithGrantedPermissions.add(e.packageName)}let o=["start"];if(e.intentExtras)try{let i=JSON.parse(e.intentExtras);for(let[a,l]of Object.entries(i))o.push("-e",a,typeof l=="string"?l:JSON.stringify(l))}catch(i){throw new Error(`UserConfigurationError: Invalid intent extras does not parse as valid JSON: ${i instanceof Error?i.message:`${i}`}`)}return o.push("-n",`${e.packageName}/${n}`),await this.driver.execute("mobile: shell",{command:"am",args:o}),await this.stateManager.waitForScreenshotStability({timeoutMs:5e3,signal:this.abortSignal,reason:"Waiting for stability after app launch"}),{success:!0}}case"PRESS":{let n=new xn(this.constructPerformerParams());switch(e.key){case"HOME":await n.doPress({keycode:3});break;case"BACK":await n.doPress({keycode:4});break;case"APP_SWITCHER":await n.doPress({keycode:187});break;case"POWER":await n.doPress({keycode:26});break;case"SEARCH":await n.doPress({keycode:84});break;case"VOLUME_UP":await n.doPress({keycode:24});break;case"VOLUME_DOWN":await n.doPress({keycode:25});break;case"VOLUME_MUTE":await n.doPress({keycode:164});break}return{success:!0}}case"PRESS_KEYBOARD":{let n=new xn(this.constructPerformerParams()),o=i=>n.doPress({keycode:i});switch(e.key){case"CLOSE_KEYBOARD":await this.driver.isKeyboardShown()&&await this.driver.hideKeyboard();break;case"ENTER":await o(66);break;case"BACKSPACE":await o(67);break;default:{let i=e}}return{success:!0}}case"WAIT":return await Y(e.timeoutSecs*1e3,this.aborter.controller?.signal),{success:!0};case"INSTALL_APP":return new $c(this.constructPerformerParams()).doInstallApk(e);case"ADD_FILE":{let n=await CR(e.file);return await this.driver.pushFile(e.storageLocation,n),await this.driver.execute("mobile: shell",{command:"am",args:["broadcast","-a","android.intent.action.MEDIA_SCANNER_SCAN_FILE","-d",`file://${e.storageLocation}`]}),{success:!0}}case"ADB":{let n=await this.driver.execute(e.command,JSON.parse(e.jsonArgs??"{}"));return this.logger.info({output:n},"ADB command executed successfully"),{success:!0,output:n,message:"ADB command executed successfully"}}case"KILL_APP":{let n=await this.stateManager.getCurrentPackage();if(!n)throw new Error("No package is currently active");await this.driver.execute("mobile: shell",{command:"input",args:["keyevent","KEYCODE_HOME"]}),await this.driver.terminateApp(n);try{await fR({packageName:n,driver:this.driver,abortSignal:this.abortSignal,logger:this.logger})}catch(o){this.throwIfAborted(),this.logger.warn({err:o,packageName:n},"Failed to remove package from recents, continuing...")}return{success:!0}}case"STATE":{await this.stateManager.refreshWebviews();let n=await this.stateManager.getDomState(),o=await this.stateManager.getContexts(),i={xml:n.graph.xml,contexts:o};return this.logger.info({result:i},"State debug command output"),{output:i,success:!0}}default:{let n=e;return{success:!0}}}}async initializeSettings(){}async getScreenshotBase64(){return this.stateManager.getRawScreenshotBase64()}async getScreenshotPngString(){return this.stateManager.getCurrentScreenshotPngString()}async getA11yTree(){return(await this.stateManager.getDomState({})).graph.xml}async waitForScreenshotStability(e){return this.stateManager.waitForScreenshotStability({timeoutMs:e.timeoutMs??5e3,reason:e.reason,signal:this.aborter.controller?.signal})}resetAbortController(e){this.aborter.controller=e??new AbortController}isAborted(){return this.aborter.controller?.signal.aborted}abort(){this.aborter.controller?.abort()}async cleanup(){await this.stateManager.cleanupWebviews()}get abortSignal(){return this.aborter.controller?.signal}get context(){return this.fixtures.testContext}get localCodeEvalTools(){return this.fixtures.localCodeEvalTools}};async function IR({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=Rr.parse(JSON.parse(p??"")),f=h.id,E=h.settings?.defaultChannel,b=h.settings?.defaultTag,x=h.settings?.defaultApkFilePath?.trim(),A=await n({testId:f});e=e.child({sessionId:d,testId:f,orgId:A});let _={...(await u(A,e)).emulator,...h.settings?.emulator},R;if(_.region==="local"){if(!_.localEmulatorSettings?.avdId)throw new Error("AVD name is required when region is local");R={avdId:_.localEmulatorSettings.avdId,apkToInstall:E?{channel:E,tag:b}:void 0,apkFilePath:x||void 0}}else R={region:_.region,apkToInstall:E?{channel:E,tag:b}:void 0};let D=Date.now(),{driver:j,cleanup:ae,emulatorName:Q,adbPort:me,limbarClient:st,limbarToken:W,limbarUrl:z}=await t({socket:r,logger:e,creationOpts:R}),re=await dc({driver:j,onLogs:yo=>{r.emit("logcatLogs",yo)}});e.info({adbPort:me,apkChannel:E,apkTag:b,duration:Date.now()-D,emulatorName:Q},"Android emulator session initiated"),e=e.child({emulator:Q});let le=await o(A,e),Xe=await i(A,e),Re=await a(A,e),Dt=await l(A),wt=c?await c(A):void 0,Ce={};h.settings?.defaultEnv&&(Ce=(await Dt.fetchEnvironment(h.settings?.defaultEnv,e))?.variables??{});let We=new Fo({variablesFromEnvironment:Ce,envName:h.settings?.defaultEnv,testName:g}),Rt=await yi.init({driver:j,generator:le,logger:e,limbarClient:st,options:{emulator:_},fixtures:{storage:Dt,browserEnricher:Re,browserGenerator:Xe,localCodeEvalTools:wt,testContext:We},orgId:A,adbPort:me,abortController:new AbortController});if(!r.connected)throw await re(),await ae(),new Error("Socket not connected anymore, not proceeding with Android session setup");let ur=NB({socket:r,testContext:We}),Hr=async()=>{clearInterval(ur);try{await re(),await ae(),await Rt.cleanup()}catch(yo){e.warn({err:yo},"Failed to clean up emulator in socket server")}};return s.registerSession(d,{controller:Rt,cleanup:Hr,emulatorName:Q,local:_.region==="local"}),r.emit("session",{testId:f,sessionId:d,limbarUrl:z,limbarToken:W}),{sessionId:d,testId:f,orgId:A,emulatorName:Q,logger:e}}function NB({socket:r,testContext:e}){return setInterval(()=>{let t=e.toEditorDisplayCopy();r.emit("emulatorState",{context:t})},3e3)}async function OR({socket:r,logger:e,globalStateManager:t}){await t.removeSession(r.id,e)}var DB=({socket:r,globalStateManager:e})=>async()=>{let t=e.getSession(r.id);if(!t)throw new Error("No active Android session found");t.controller.abort()},LR={event:"cancel",createHandler:DB};var kB=({logger:r,globalStateManager:e,socket:t})=>async(n,o)=>{let i=e.getSession(t.id);if(!i){o({err:"No active Android session found"});return}try{let l=await i.controller.getA11yTree();o({a11yTree:l})}catch(a){r.error({err:a},"Error fetching a11y tree from the session controller"),o({err:a.message})}},NR={event:"fetchA11yTree",createHandler:kB};import{diff as QB}from"deep-object-diff";import{cloneDeep as ez}from"lodash-es";function DR(r,e,t=1e4,n=5e3){let o=0;async function i(){try{let l=await k(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 kR(r){let e=Date.now(),t=r.fixtures.controller;try{return await UB(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 UB({moduleParams:r,...e}){let t=Date.now(),{step:n,stepTracer:o,executeMobileStepList:i}=r,a=await FB({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(),$v({result:c,...Wv(d)}),c}async function FB({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 Nr({orgId:e.inputs.orgId,code:a,fragment:!0,logger:n,context:o.context,localTools:o.localCodeEvalTools})}return t}import{randomUUID as UR}from"crypto";async function FR({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.getScreenshotBase64()}catch(s){i.warn({err:s},"Failed to take before screenshot")}let c={...e,status:"SUCCESS",startTime:o,endTime:Date.now()};try{let s=await a.executeCommand({command:e.command});c={...e,status:s.success?"SUCCESS":"FAILED",message:s.message,startTime:o,endTime:Date.now(),data:s.output}}catch(s){s instanceof Error&&s.name==="AbortError"||a.isAborted()?c={...e,status:"CANCELLED",message:"Step cancelled.",startTime:o,endTime:Date.now()}:(i.error({err:s},"Failed to execute preset step"),c={...e,status:"FAILED",message:s instanceof Error?s.message:String(s),startTime:o,endTime:Date.now()})}finally{if(!t.interactive){try{let s=UR(),u=await a.getScreenshotBase64();c.afterSnapshot=s,n.attachAfterScreenshot({logger:i,snapshotId:s,screenshot:Buffer.from(u,"base64")})}catch(s){i.warn({err:s},"Failed to take after screenshot")}if(l){let s=UR();c.beforeSnapshot=s,n.attachBeforeScreenshot({logger:i,snapshotId:s,screenshot:Buffer.from(l,"base64")})}}}return c}import{streamText as YB}from"ai";import{randomUUID as XB}from"crypto";var Kc=class{controller;logger;callbacks;rootStep;subStepIndex=0;finalState=void 0;results=[];constructor(e){let{controller:t,logger:n,callbacks:o,rootStep:i}=e;this.controller=t,this.logger=n,this.callbacks=o,this.rootStep=i}async createAndExecuteStep(e){this.callbacks.onAiActionEvent?.({type:"SUBSTEP_CREATED",rootStep:this.rootStep,step:e});let t=this.subStepIndex++,n=await this.callbacks.executeStep(e,t);return this.results.push(n),n}};import{hasToolCall as qB,stepCountIs as KB}from"ai";var BR="get_emulator_state",Yc="finish";import zR from"dedent";var zB=zR`
4126
4106
  You cannot interact with the user directly. If you feel like you need to ask the user for clarification, or you are stuck, call the "finish" tool with success=false. Never output text without calling a tool.
4127
- `,UR=r=>kR`
4107
+ `,HR=r=>zR`
4128
4108
  <background>
4129
4109
  You are an advanced, AI agent part of an end-to-end testing platform called Momentic.
4130
4110
  Momentic uses AI agents to translate high-level natural language descriptions of user flows into browser automation for the purpose of validating application correctness.
@@ -4137,7 +4117,7 @@ The steps you generate will be fed to downstream Momentic agents that are respon
4137
4117
  The user will provide you with a high-level goal to achieve. Your task is to use the tools at your disposal to make as much progress as you can towards accomplishing the goal until one of the following is true:
4138
4118
  - You have successfully accomplished the goal, fulfilling all criteria specified by the user. In this case, end the generation cycle by calling the "finish" tool with success=true.
4139
4119
  - You have determined that the goal is impossible to accomplish or too vague to interpret confidently. In this case, end the generation cycle by calling the "finish" tool with success=false. Some examples of why a goal could be impossible: a) the goal requires a step type or capability that is not available to you; b) the user's app crashes or displays a 500 internal server error page; c) Momentic's AI agents repeatedly fail to perform the correct interaction, which could indicate an accessibility issue with the app.
4140
- ${r?"":IB}
4120
+ ${r?"":zB}
4141
4121
  </task>
4142
4122
 
4143
4123
  <values>
@@ -4155,22 +4135,22 @@ Momentic users value the following:
4155
4135
  b) There is a loading state that blocks you from proceeding with generation, and you need to wait until the state changes. In this case, you can generate an AI_CHECK step for the anticipated "done" state (e.g. "There is no loading spinner visible"). Unless explicitly specified by the user, you can generate and retry an assertion up to 3 times with a timeout up to 30 seconds each.
4156
4136
  If the max. allowed retries is exceeded, fail the generation cycle by calling "finish".
4157
4137
  </rules>
4158
- `;import{tool as NB}from"ai";import{randomUUID as DB}from"crypto";import kB from"zod";import{tool as OB}from"ai";import LB from"zod";var FR=r=>{let e=OB({description:"Get the current state of the emulator (XML + screenshot)",inputSchema:LB.object({}),toModelOutput:t=>t,execute:async()=>{let{controller:t,logger:n}=r;return n.info("AI action tool called (get_emulator_state)"),Qm(t)}});return{name:DR,tool:e}};async function Qm(r){let e=await r.getA11yTree(),t=await r.getScreenshotBase64();return{type:"content",value:[{type:"text",text:e},{type:"text",text:"</emulatorXml>"},{type:"text",text:"<screenshot>"},{type:"media",data:t,mediaType:"image/png"},{type:"text",text:"</screenshot>"}]}}var BR=r=>({name:"create_execute_step",tool:NB({description:"Create and immediately execute a new Momentic step in the Android emulator, returning the result from the step and the state of the emulator after the step finished executing.",inputSchema:kB.object({step:Ad}),toModelOutput:t=>t,execute:async({step:t})=>{let{contextManager:n,logger:o,controller:i}=r;o.info({step:t},"AI action tool called (create_execute_step)");let a=hS(t),l={id:DB(),type:"MOBILE_PRESET_STEP",command:a},c=await n.createAndExecuteStep(l);c.status==="SUCCESS"&&await i.waitForScreenshotStability({reason:"Waiting for stability after executing AI-generated sub-step"});let s={...c,trace:void 0,beforeSnapshot:void 0,afterSnapshot:void 0},u=await Qm(i);return{type:"content",value:[{type:"text",text:"<result>"},{type:"text",text:JSON.stringify(s,null,2)},{type:"text",text:"</result>"},{type:"text",text:"<stateAfter>"},...u.value,{type:"text",text:"</stateAfter>"}]}}})});import{tool as UB}from"ai";import eg from"zod";var zR=r=>{let e=UB({description:"Signal that the AI action has reached a terminal state (either success or failure).",inputSchema:eg.object({message:eg.string(),success:eg.boolean()}),toModelOutput:t=>t,execute:async({message:t,success:n})=>{let{contextManager:o,logger:i}=r;return i.info({message:t,success:n},"AI action tool called (finish)"),o.finalState={message:t,status:n?"SUCCESS":"FAILED"},{type:"content",value:[{type:"text",text:"Done"}]}}});return{name:$c,tool:e}};var HR=[BR,FR,zR];function GR(r){let{logger:e,controller:t,contextManager:n,aiActionSessionId:o}=r,i={};for(let c of HR){let s=c({contextManager:n,logger:e,controller:t});i[s.name]=s.tool}let a=t.generator.getVercelAnthropicModelFactory({loggerTags:me(e),sessionId:o}),l=c=>{let{messages:s}=c,u=!1;for(let d=s.length-1;d>=0;d--){let p=s[d];for(let m of p.content)if(!(typeof m!="object"||!("type"in m))&&!(m.type!=="tool-result"||m.output.type!=="content")&&!(m.output.value.length<3))for(let g=0;g<m.output.value.length;g++){let h=m.output.value[g];if(h.type==="text"&&h.text.includes("<emulatorXml>"))if(u){let f=m.output.value[g+1];f.type==="text"?f.text="TRUNCATED DUE TO CONVERSATION LENGTH":e.warn({msg:f},"Got unexpected part when truncating emulator state message")}else{u=!0;continue}}}return c};return{model:a("claude-haiku-4-5-20251001"),tools:i,prepareStep:l,stopWhen:[BB(15),FB($c)],system:UR(!1)}}async function VR(r){let e=Date.now(),{controller:t,logger:n}=r.fixtures;try{return await GB(r)}catch(o){let i=t.isAborted()||o instanceof DOMException&&o.name==="AbortError";return i||n.error({err:o},"Failed to execute mobile AI action"),{...r.aiActionParams.step,steps:[],type:"MOBILE_AI_ACTION_STEP",startTime:e,endTime:Date.now(),status:i?"CANCELLED":"FAILED",message:i?"Step cancelled.":`${o}`}}}async function GB(r){let{step:e,stepTracer:t,executeMobileStepList:n}=r.aiActionParams,{controller:o,logger:i}=r.fixtures,{step:a}=r.callbacks,l=await t.startSubSteps(),c=HB(),s=i.child({stepId:e.id,aiActionSessionId:c}),u=Date.now(),d=async(f,E)=>{let b=await n({...r,listParams:{steps:[f],tracer:l,containerName:`AI action sub-step ${E}`}});if(b.results.length!==1)throw new Error("InternalWebAgentError: Expected exactly one result from executeMobileStepList");return b.results[0]},p={stepId:e.id,parentStepIdChain:t.getParentStepIdChain()},m=new Wc({controller:o,callbacks:{onAiActionEvent:a?.onAiActionEvent,executeStep:d},logger:s,rootStep:p}),g=GR({controller:o,logger:s,contextManager:m,aiActionSessionId:c}),h=zB({...g,messages:[{role:"user",content:e.text}]});for await(let f of h.fullStream)switch(f.type){case"text-delta":a?.onAiActionEvent?.({type:"LLM_TEXT_OUTPUT",text:f.text,rootStep:p})}if(await h.response,o.throwIfAborted(),!m.finalState)throw new Error("InternalWebAgentError: The AI agent never reached a final state. This could be because the maximum number of steps was reached.");return{...e,status:m.finalState.status,startTime:u,endTime:Date.now(),message:m.finalState.message,steps:m.results}}async function qc(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}/${i.length} in ${o} - ${Dv(b)}`),b.skipped){l.debug("Step skipped");continue}if(f&&g){let M=JSON.stringify(u);if(b.id===g.fromStepId&&M===JSON.stringify(g.parentStepIdChain))f=!1;else if(!Hv({currentStep:b,currentParentChain:u,desiredStepId:g.fromStepId,desiredStepParentChain:g.parentStepIdChain}))continue}let C=await a.startStep({logger:l,step:b,attempt:1,parentStepIdChain:u});s.trackStepExecution(b);let A=await VB({step:b,stepTracer:C,params:r}),{trace:v}=await C.finish({parentStepIdChain:u,result:A});if(A.trace=v,l.info({step:{id:b.id},trace:A.trace,status:A.status},`Finished step ${E+1}/${i.length} (${b.type==="MOBILE_PRESET_STEP"?b.command.type:b.type})`),d.push(A),A.status!=="SUCCESS"){m=A.status,p=A;break}if(b.envKey&&c.context.setVariable(b.envKey,A.data),h){let M=JSON.stringify([]);if(b.id===h.toStepId&&M===JSON.stringify(h.parentStepIdChain))break}}return{results:d,status:m,terminalResult:p}}async function VB({step:r,stepTracer:e,params:t}){let{fixtures:n,inputs:o,callbacks:i}=t,a;switch(r.type){case"MOBILE_PRESET_STEP":{a=await NR({fixtures:n,inputs:o,step:r,stepTracer:e,callbacks:i});break}case"RESOLVED_MOBILE_MODULE":{a=await OR({...t,moduleParams:{step:r,stepTracer:e,executeMobileStepList:qc}});break}case"MOBILE_AI_ACTION_STEP":{a=await VR({...t,aiActionParams:{step:r,stepTracer:e,executeMobileStepList:qc}});break}}return a}async function Kc(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=WB(n);a.info({testMetadata:Ar.parse(o)},"Starting mobile test");let s=await e.startMainStepList(),u=ub(a),d=IR(l,a);a.info({cpu:u?.cpuMetadata,platform:u?.platform},`Starting execution of ${t}`);let{status:p,results:m}=await qc({...r,listParams:{containerName:t,tracer:s,steps:c}});if(clearInterval(u?.interval),clearInterval(d),p==="SUCCESS"){let g=jB(c,n);if(g&&Object.keys(g).length>0){a.info({diffs:g},"Saving mobile step cache entries post-success");let{cachesToSave:h}=await ro({steps:c,cacheCreationParams:{orgId:r.inputs.orgId,testId:o.id}});await i.saveEntries({logger:a,testId:o.id,entries:h})}else a.info("No cache entries to update");return{status:"PASSED",results:m}}return p==="CANCELLED"?{status:"CANCELLED",results:m}:{status:"FAILED",results:m}}var tg=class{parentTracer=null;socket;step;interactionTracer;constructor({step:e,socket:t,parentTracer:n}){this.socket=t,this.parentTracer=n,this.step=e,this.interactionTracer=new lo,Kr.initializeRootTracerContext(this.interactionTracer)}attachBeforeScreenshot(){}attachAfterScreenshot(){}attachBeforeHtmlSnapshot(){}attachAfterHtmlSnapshot(){}async finish(e){this.interactionTracer.finish();let t=this.interactionTracer.getRootSpan(),n={...jy.parse(e),trace:xd.parse(t)};switch(n.result.status){case"SUCCESS":this.socket.emit("success",n);break;case"FAILED":this.socket.emit("failure",n);break;case"CANCELLED":this.socket.emit("cancelled",n);break}return{trace:t}}getParentStepIdChain(){return this.parentTracer?this.parentTracer?.getParentStepIdChain()??[]:[]}async startSubSteps(){return new bi({parentStep:this.step,socket:this.socket,parentTracer:this})}},bi=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 tg({step:e.step,parentTracer:this,socket:this.socket})}},Yc=class{constructor(e){this.socket=e}appendLogs(){}async finish(){this.socket.emit("finished")}async startBeforeStepList(){return new bi({parentStep:null,parentTracer:null,socket:this.socket})}async startMainStepList(){return new bi({parentStep:null,parentTracer:null,socket:this.socket})}async startAfterStepList(){return new bi({parentStep:null,parentTracer:null,socket:this.socket})}};var $B=({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=e.child({testId:i.testMetadata.id}),s=await o(r.orgId),u=l.controller;u.resetAbortController();let d=new Yc(n),p=await Kc({fixtures:{controller:u,logger:c,cacheStorage:s,usageTracker:new Bs},containerName:"entire test",inputs:{steps:i.steps,fromStep:i.fromStep,toStep:i.toStep,orgId:r.orgId,testMetadata:i.testMetadata,interactive:!0},tracer:d,callbacks:{step:{onAiActionEvent:g=>{n.emit("aiActionEvent",g)}}}});await d.finish();let m={results:tr.array().parse(p.results),status:p.status};a?.(m)},jR={event:"execute",createHandler:$B};import{debounce as qB}from"ts-debounce";var KB=({socket:r,globalStateManager:e,keepSessionAlive:t})=>{let n=qB(t,3e4,{maxWait:6e4});return async()=>{let o=e.getSession(r.id);if(!o)throw new Error("No active Android session found");o.emulatorName&&(o.local||n(o.emulatorName))}},WR={event:"keepalive",createHandler:KB};var $R=[jR,_R,WR,PR];function qR(r){let{logger:e,baseServer:t,globalStateManager:n}=r,o=new YB(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=>{let c=l.id,s=e.child({sessionId:c});s.info({event:"connection",transport:l.conn.transport.name},"Android websocket connection initiated"),l.on("disconnect",async()=>{await MR({socket:l,globalStateManager:n,logger:s})});let u;try{u=await xR({...r,socket:l,globalStateManager:n,logger:s})}catch(d){s.error({err:d},"Failed to setup Android connection"),l.emit("error",{message:d instanceof Error?d.message:JSON.stringify(d)}),l.disconnect(!0);return}$R.forEach(d=>a(d,{...r,socket:l,metadata:u,logger:s}))});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{randomUUID as Zz}from"crypto";import{diff as APe}from"deep-object-diff";import NPe from"yaml";import{z as kPe}from"zod";import{execSync as XB}from"child_process";function uo(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{XB(n,{encoding:"utf-8"})}catch(o){R.warn({err:o,postSaveCommand:n},"Failed to execute post-save hook command, continuing...")}}import{diff as ePe}from"deep-object-diff";import{cloneDeep as rPe}from"lodash-es";import{v4 as gPe}from"uuid";import fPe from"yaml";import JB from"@dotenvx/dotenvx";import ZB from"fs";import KR from"path";function QB(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 e1(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=QB(i);l&&(n[o]=l);continue}let a;try{a=ZB.readFileSync(KR.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 t1(r){let{project:e,envFile:t,logger:n}=r,o={};if(!t)return o;let i=JB.config({path:KR.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 Xc(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=e1({envVariables:n.envVariables,project:e});Object.assign(o,i);let a=t1({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 g1,readFileSync as h1,readdirSync as f1,writeFileSync as S1}from"fs";import{glob as y1}from"glob";import po,{dirname as JR}from"path";import{cwd as ag}from"process";import ZR from"yaml";import{z as xe}from"zod";import YR from"fs";import{glob as r1}from"glob";import Qa from"path";import n1 from"yaml";import{z as rg}from"zod";var XR=!1,ng=["**/*.test.yaml","**/*.module.yaml"],og=rg.string().refine(r=>/^[a-zA-Z0-9-]+$/.test(r)),ig=15,o1=rg.object({fileType:rg.nativeEnum(_e)});async function Sr(r,e=!1){let t={project:r,tests:{},modules:{},mobileTests:{},mobileModules:{},duplicateEntities:{}},n=r.config.include??ng,o=Array.from(r.config.exclude??[]).concat(tl),i=AbortSignal.timeout(5e3),a;try{a=await r1(n,{absolute:!1,cwd:r.rootDir,ignore:o,dotRelative:!1,maxDepth:ig,nodir:!0,signal:i})}catch(l){throw R.error({err:l},"Failed to list all Momentic files in the current directory. This usually indicates the 'include' and 'exclude' globs are misconfigured in your momentic.config.yaml, or that your machine is severely resource constrained."),new Error("Listing Momentic files timed out after 5 seconds.",{cause:l})}for(let l of a){let c=i1(r.rootDir,l,t,e?pn:R);c&&(t.duplicateEntities[c.id]=c.paths)}return XR=!0,t}function i1(r,e,t,n){let o=Qa.join(r,e),i=a1(o,n);if(!i)return;let a=s1(i,o,n);if(!a)return;let l=o1.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=l1(o,n);if(!s)return;let u=c1(e,o,s);switch(c){case _e.TEST:try{return u1(a,t,u,o,n)}catch(d){n.warn(`Skipping file '${o}' because it is missing Momentic test metadata: ${d}`);return}case _e.MODULE:try{return d1(a,t,u,o,n)}catch(d){n.warn(`Skipping file '${o}' because it is missing Momentic module metadata: ${d}`);return}case _e.MOBILE_TEST:try{return m1(a,t,u,o,n)}catch(d){n.warn(`Skipping file '${o}' because it is missing Momentic mobile test metadata: ${d}`);return}case _e.MOBILE_MODULE:try{return p1(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 a1(r,e){try{return YR.readFileSync(r,"utf-8")}catch(t){e.warn(`Could not read possible Momentic file at ${r}, skipping: ${t}`);return}}function s1(r,e,t){try{let n=n1.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 l1(r,e){try{return YR.statSync(r)}catch(t){e.warn(`Skipping path '${r}' because it could not be stat, skipping: ${t}`);return}}function c1(r,e,t){return{relativePath:r,fullFilePath:e,platformSep:Qa.sep,fullPathSegments:e.split(Qa.sep),relativePathSegments:r.split(Qa.sep),fileName:Qa.basename(e),lastModified:t.mtime,createdAt:t.birthtime}}function u1(r,e,t,n,o){let i=Fo.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:_e.TEST,name:i.name,id:i.id,description:i.description??void 0,labels:i.labels,...t},a}function d1(r,e,t,n,o){let i=Kt.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:_e.MODULE,name:i.name,id:i.moduleId,description:i.description??void 0,...t};let l=t.fileName.replace(".module.yaml","");return!XR&&nn(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 p1(r,e,t,n,o){let i=aa.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:_e.MOBILE_MODULE,name:l,id:i.moduleId,description:i.description??void 0,...t},a}function m1(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:_e.MOBILE_TEST,name:l,id:i.id,description:i.description??void 0,...t},a}var Ei="momentic.config.yaml",sg="momentic.workspace.yaml",b1=xe.object({projects:xe.string().array().describe("list of glob patterns to find project (momentic.config.yaml) files")}),E1=xe.union([xe.string(),xe.object({fromFile:xe.string(),json:xe.boolean().optional()})]),T1=xe.object({name:og,baseUrl:xe.string().optional().describe("Optional for mobile tests"),envFile:xe.string().optional().describe("path to a file on disk to read environment variables from. can be relative to project root or absolute."),envVariables:xe.record(xe.string(),E1).optional(),inheritFromShell:xe.boolean().optional().describe("inherit all environment variables from the shell - might be noisy"),browser:Un.optional().describe("NB: most things should use project-level configuration only")}),v1=xe.object({postSave:xe.string().optional()}),A1=xe.object({name:og,include:xe.string().array().optional().describe("list of glob patterns that match momentic files (optional)"),exclude:xe.string().array().optional().describe("opposite of include, takes precedence over include"),goldenFileDir:xe.string().optional(),reporterDir:xe.string().optional(),outputDir:xe.string().optional(),recordVideo:xe.boolean().optional(),retries:xe.number().optional().describe("number of retries per test"),parallel:xe.number().optional().describe("degree of parallelism"),environments:xe.array(T1).optional(),gitMainBranch:xe.string().optional(),gitProtectedBranches:xe.string().array().optional(),ai:Nd.optional(),browser:Un.optional(),emulator:Cd.optional(),advanced:Dd.optional(),hooks:v1.optional()});function QR(r,e){let t;try{t=h1(r,"utf-8")}catch(o){R.warn(`Could not read possible Momentic ${e} file at ${r}: ${o}`);return}let n;try{if(n=ZR.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 lg(r){let e=QR(r,"project configuration");if(e!==void 0)try{return A1.parse(e)}catch(t){R.warn(`Possible Momentic project configuration file at ${r} does not adhere to the required schema: ${t}`);return}}function w1(r){let e=QR(r,"workspace configuration");if(e!==void 0)try{return b1.parse(e)}catch(t){R.warn(`Possible Momentic workspace configuration file at ${r} does not adhere to the required schema: ${t}`);return}}function R1(){let r=[],e=ag(),t=po.parse(e).root,n=15,o=0;for(;o<n;){o++;let i=po.basename(e);if(el.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 f1(e))if(a.endsWith(Ei)){let l=po.join(e,a),c=lg(l);c&&r.push({configFilePath:l,config:c,rootDir:JR(l)})}if(r.length)return r;if(e=po.dirname(e),e===t)break}return r}async function es(r={}){let{configFilePath:e,nameFilter:t}=r,n=await x1(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:
4159
- ${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]}async function C1(r){let e=w1(r);if(!e||!e.projects||!e.projects.length)return;let t=e.projects.map(a=>(a.endsWith("/")||(a+="/"),`${a}*${Ei}`)),n=AbortSignal.timeout(2e3),o;try{o=await y1(t,{absolute:!1,cwd:ag(),dotRelative:!1,maxDepth:ig,nodir:!0,signal:n})}catch(a){throw R.error({err:a},`Failed to list the available Momentic projects in the current directory. This usually indicates the 'include' or 'exclude' option in your ${sg} is misconfigured.`),a}let i=[];for(let a of o){let l=po.join(ag(),a),c=lg(l);c&&i.push({configFilePath:l,config:c,rootDir:JR(l)})}return i}async function x1(r){if(r){r=po.resolve(r);let t=lg(r);return t||(console.error(`No valid Momentic project file found at ${r}.`),process.exit(1)),[{config:t,configFilePath:r,rootDir:po.dirname(r)}]}if(g1(sg)){let t=await C1(sg);if(t)return t}return R1()}function eC(r,e){let t=ZR.stringify(r);S1(e,t)}import{z as cg}from"zod";var tC="test-results";var EIe=cg.object({width:cg.number(),height:cg.number()});import{execFile as M1}from"node:child_process";import{promisify as _1}from"node:util";import P1 from"simple-git";var Ie=P1(),rC=_1(M1);async function I1(r){let e=await Oe(r,Ie.raw(["config","--list"])),t={};if(!e)return t;for(let n of e.split(`
4160
- `)){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 O1(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 rC("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 rC("gh",o,{timeout:5e3}),a=i?.toString().trim();if(a)return a}catch{}}}async function L1(r,e,t){let n=e?.includes("github.com"),o=e?.includes("gitlab.com");try{if(n)return O1(r,e,t);if(o)return}catch{}}function Jc(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 Oe(r,e){try{return(await e).trim()}catch(t){r.error({err:t},"Failed to run git command");return}}function N1(){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 D1(r){let[e,t,n]=await Promise.all([Oe(r,Ie.show(["--no-patch","--format=%ci"])),Oe(r,Ie.show(["-s","--pretty=%B"])),Oe(r,Ie.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{ciProvider:"GithubActions",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 k1(r){let[e,t,n]=await Promise.all([Oe(r,Ie.listRemote(["--get-url","origin"])),Oe(r,Ie.show(["-s","--pretty=%B"])),Oe(r,Ie.show(["-s","--pretty=%an"]))]);return{ciProvider:"GitlabCI",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 U1(r){let[e,t,n,o]=await Promise.all([Oe(r,Ie.show(["--no-patch","--format=%ci"])),Oe(r,Ie.listRemote(["--get-url","origin"])),Oe(r,Ie.show(["-s","--pretty=%B"])),Oe(r,Ie.show(["-s","--pretty=%an"]))]),i=t?.includes("github.com"),a=t?.includes("gitlab.com"),l=t?Jc(t):void 0;return{ciProvider:"CircleCI",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 F1(r){let[e,t,n]=await Promise.all([Oe(r,Ie.show(["--no-patch","--format=%ci"])),Oe(r,Ie.show(["-s","--pretty=%B"])),Oe(r,Ie.show(["-s","--pretty=%an"]))]),o=process.env.BUILDKITE_REPO,i=o?.includes("github.com"),a=o?.includes("gitlab.com"),l=o?Jc(o):void 0;return{ciProvider:"Buildkite",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 B1(r){let[e,t,n]=await Promise.all([Oe(r,Ie.show(["--no-patch","--format=%ci"])),Oe(r,Ie.show(["-s","--pretty=%B"])),Oe(r,Ie.show(["-s","--pretty=%an"]))]),o=process.env["Build.Repository.Uri"],i=o?.includes("github.com"),a=o?.includes("gitlab.com"),l=o?Jc(o):void 0;return{ciProvider:"AzureDevOps",gitCommitSha:process.env["Build.SourceVersion"],gitCommitShaShort:process.env["Build.SourceVersion"]?.slice(0,6),gitCommitTimestamp:e?new Date(e):void 0,gitBranchName:process.env["System.PullRequest.SourceBranch"]??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 z1(r,e){let[t,n,o,i,a,l,c,s,u]=await Promise.all([Oe(r,Ie.revparse(["HEAD"])),Oe(r,Ie.revparse(["--short","HEAD"])),Oe(r,Ie.revparse(["--abbrev-ref","HEAD"])),Oe(r,Ie.listRemote(["--get-url","origin"])),Oe(r,Ie.show(["--no-patch","--format=%ci"])),Oe(r,Ie.show(["-s","--pretty=%B"])),Oe(r,Ie.show(["-s","--pretty=%an"])),e?Oe(r,Ie.raw(["merge-base","--fork-point",e])):Promise.resolve(void 0),I1(r)]),d=s?await Oe(r,Ie.show(["--no-patch","--format=%ci",s])):void 0,p=i?.includes("github.com"),m=i?.includes("gitlab.com"),g=i?Jc(i):void 0,h=u["user.email"]||void 0,f=u["user.name"]||void 0,E=u["user.username"]||void 0,b=await L1(r,i,u)??E??void 0;return{ciProvider:"none",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 H1(){let r=process.env._HEAD_REPO_URL;return{ciProvider:"GCPCloudBuild",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 G1(r){let e=r.config.gitProtectedBranches??[];return r.config.gitMainBranch&&e.push(r.config.gitMainBranch),{gitMainBranch:r.config.gitMainBranch,gitProtectedBranches:e}}async function ts(r,e){let t=N1();if(!t)return z1(r,e);switch(t){case"GithubActions":return D1(r);case"GitlabCI":return k1(r);case"CircleCI":return U1(r);case"Buildkite":return F1(r);case"AzureDevOps":return B1(r);case"GCPCloudBuild":return H1()}}async function V1(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 j1(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 W1(r,e,t){try{if(t.githubRepository){let[n,o]=t.githubRepository.split("/");return await j1(r,e,n,o,t)}else if(t.gitlabProjectPath)return await V1(r,e,t.gitlabProjectPath,t)}catch(n){r.warn({err:n},"Failed to get remote git metadata")}return t}async function Ti(r,e,t){let n=await G1(t),o=await ts(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 W1(r,e,i);return{...n,...o,...a}}import{diff as nC}from"deep-object-diff";import mo from"fs";import{cloneDeep as $1}from"lodash-es";import ug from"path";import{v4 as HIe}from"uuid";import Zc from"yaml";function oC({content:r,schemaVersion:e,momenticFiles:t,project:n,forceSaveOnNoDiffs:o}){let i=t.mobileModules[r.moduleId]?.fullFilePath;if(!i||!mo.existsSync(i))throw new Error(`Tried to update mobile module ${r.moduleId} that could not be found on disk`);let a=mo.readFileSync(i,"utf-8"),l=Zc.parse(a),c={...l,...r,schemaVersion:e},s=Qn({fileType:_e.MOBILE_MODULE,...aa.parse(c),steps:gr.array().parse(r.steps)}),u=nC(s,l);if(u&&Object.keys(u).length===0&&!o)return;let d=Zc.stringify(s);mo.writeFileSync(i,d,"utf-8"),uo(i,n.config)}function iC({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=rs(i,o),l={...a,...e},c=Qn({fileType:_e.MOBILE_MODULE,...Ks.parse(l)}),s=nC(c,a);if(s&&Object.keys(s).length===0)return;let u=Zc.stringify(c);mo.writeFileSync(i,u,"utf-8");let d;if(e.name){let p=`${nn(e.name)}.module.yaml`;if(d=ug.join(ug.dirname(i),p),mo.existsSync(d))throw new Error(`A conflicting file already exists at the following path: ${d}`);mo.renameSync(i,d)}uo(d||i,n.config)}function rs(r,e){let t=mo.readFileSync(r,"utf-8"),n=Zc.parse(t);try{return{...Ks.parse(n),name:ug.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 dg(r,e,t,n){let o=rs(r.fullFilePath,t),{resolvedSteps:i}=await gc({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 rs(c,t)},logger:t,metadata:{id:o.moduleId,schemaVersion:o.schemaVersion}}),a={...o,name:r.name,steps:i};return n&&(n[r.id]=$1(a)),a}async function aC(r,e){let t={};return await Promise.all(Object.values(r.mobileModules).map(async n=>{await dg(n,r,e,t)})),Array.from(Object.values(t))}import{randomUUID as q1}from"crypto";import go from"fs";import pg from"path";import Qc from"yaml";function sC({name:r,description:e="",steps:t=[],settings:n={},folder:o}){let a=`${nn(r)}.test.yaml`,l=pg.join(o,a);if(go.existsSync(l))throw new Error(`A test named '${r}' already exists at path '${l}'. Choose a different name.`);let c={fileType:_e.MOBILE_TEST,id:q1(),description:e,schemaVersion:qu,settings:n,steps:t},s=Qc.stringify(c);return go.writeFileSync(l,s,"utf-8"),{fullPath:l,testId:c.id}}function K1(r){if(!go.existsSync(r))throw new Error(`Test file not found: ${r}`);let e=go.readFileSync(r,"utf-8").replace(/\r\n|\r/g,`
4161
- `),t=Qc.parse(e),n=Xs.parse(t);if(n.fileType!==_e.MOBILE_TEST)throw new Error(`File is not a mobile test (fileType=${n.fileType}): ${r}`);return n}async function eu(r,e,t){let n=K1(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 Uv({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 rs(c,e)}});return{...o,steps:i.steps}}async function lC({filePath:r,steps:e,settings:t,folder:n,project:o,momenticFiles:i}){let a=pg.isAbsolute(r)?r:pg.join(n,r);if(!go.existsSync(a))throw new Error(`Test file not found: ${a}`);let l=go.readFileSync(a,"utf-8").replace(/\r\n|\r/g,`
4162
- `),c=Qc.parse(l),s=Xs.parse(c);if(s.fileType!==_e.MOBILE_TEST)throw new Error(`File at '${a}' is not a mobile test (fileType=${s.fileType}).`);let u;e&&(u=await ro({steps:e}));let d={...s,...u?.stepsToSave!==void 0?{steps:u.stepsToSave}:{},...t!==void 0?{settings:t}:{}},p=Qc.stringify(Xs.parse(d));for(let m of u?.moduleUpdates??[])oC({content:m,schemaVersion:qu,momenticFiles:i,project:o});go.writeFileSync(a,p,"utf-8"),uo(a,o.config)}import{randomUUID as Y1}from"crypto";import xn from"fs";import vi from"path";var cC=new Set([".DS_Store","__MACOSX"]),uC={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 X1(r,e,t){if(uC[t]){let i=uC[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 mg=class extends Error{constructor(e,t){let n=`${e} contains invalid Momentic results: ${t}. Please ensure that the path points to a folder containing only valid results. If you passed \`--output-dir test-results/results-1\` to the \`run\` command, your results path for merging should be \`test-results\`.`;super(n),this.name="InvalidMomenticResultsPathError"}};function dC(r,e){try{let t=vi.join(e,"metadata.json");return cl.parse(JSON.parse(xn.readFileSync(t,"utf-8")))}catch{throw new mg(r,e)}}function pC(r,e,t){let n=Y1(),o=r.child({runGroupId:n});xn.rmSync(e,{recursive:!0,force:!0});let i=xn.readdirSync(t).filter(c=>!cC.has(c)).map(c=>vi.join(t,c));if(i.length===0)throw new Error(`No run groups found in results path: ${t}`);xn.mkdirSync(e,{recursive:!0});let a={...dC(t,i[0]),id:n};for(let c of i){let s=vi.join(c,"runs");if(!xn.existsSync(s))continue;let u=dC(t,c);o.info({oldRunGroupId:u.id},"Merging run groups");for(let p in u){if(p==="id")continue;let m=p;a[m]=X1(a,u,m)}let d=xn.readdirSync(s);for(let p of d){if(cC.has(p))continue;let m=vi.join(s,p),g=vi.join(e,"runs",p);xn.cpSync(m,g,{recursive:!0})}}let l=vi.join(e,"metadata.json");xn.writeFileSync(l,JSON.stringify(a,null,2))}import gC from"adm-zip";import bg from"fs";import{z as nz}from"zod";var k="v1",gg="mobile-cli",ho="0.4.0";var J1=9e4,Z1=3,Q1=1500,ez=15e3,yr=class extends Error{status;rawError;constructor(e,t,n,o={}){super(n,o),this.status=e,this.rawError=t}};async function tz(r){return r.text().then(e=>{try{return JSON.parse(e).error}catch{return e}})}var hg=class{baseUrl;logger;constructor(e){this.baseUrl=e.baseUrl,this.logger=e.logger}getHeaders(){let e={"Content-Type":"application/json"};return ho&&(e[al]=ho),gg&&(e[ZS]=gg),e}async sendRequest(e,t){let{retries:n=Z1,requestTimeoutMs:o=J1,initialRetryDelayMs:i=Q1,maxRetryDelayMs:a=ez}=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 yr&&d.status>=400&&d.status<500)throw d;if(d instanceof Error&&d.name==="AbortError"&&(s=new mn),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,{once:!0});let c=Date.now(),s={...this.getHeaders(),...t.extraHeaders};try{let u=await fetch(`${this.baseUrl}${e}`,{method:t.method,body:t.body?JSON.stringify(t.body):void 0,headers:s,signal:i.signal});if(!u.ok){let p=await tz(u);throw new yr(u.status,p,`Request to ${t.method} ${e} failed with status ${u.status}: ${p}`)}let d;if(u.status===204)d={};else{let p=await u.text();try{d=JSON.parse(p)}catch{d=p}}return this.logger&&t.logResponse===!0&&d&&this.logger.debug({result:d,status:u.status,durationMs:Date.now()-c,...o},"Got response from Momentic server"),d}finally{clearTimeout(a),t.signal&&t.signal.removeEventListener("abort",l)}}},Fr=class extends hg{apiKey;mode;constructor(e){super(e),this.apiKey=e.apiKey,this.mode=e.mode}getHeaders(){return{...super.getHeaders(),Authorization:`Bearer ${this.apiKey}`,[JS]:this.mode??""}}};import{createAnthropic as rz}from"@ai-sdk/anthropic";var tu=({baseUrl:r,apiKey:e,sessionId:t,extraHeaders:n,loggerTags:o})=>i=>{let a={Authorization:`Bearer ${e}`,[al]:ho??"",...t&&{[ey]:t},...n||{}};return o&&(a[QS]=JSON.stringify(o)),rz({baseURL:`${r}/v1/llm/anthropic/${i}`,headers:a,apiKey:e})(i)};var fo=class extends Fr{agentConfig;constructor(e,t){let n={...Qf,...e};super(t),this.agentConfig=n}getAgentConfig(){return this.agentConfig}async rankChunksWithAi(e,t){let n={...e,loggerTags:t.loggerTags},o=await this.sendRequest(`/${k}/web-agent/recommend-chunks-ai`,{method:"POST",body:n,signal:t.abortSignal});return Hf.parse(o)}async rankChunksWithRag(e,t){let n=await this.sendRequest(`/${k}/web-agent/recommend-chunks`,{method:"POST",body:{cliVersion:ho,...e},signal:t.abortSignal});return zf.parse(n)}async getScreenshotFromS3(e){let t=await this.sendRequest(`/${k}/s3/visual-diff-screenshot`,{method:"POST",body:{url:e}});return nz.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(`/${k}/web-agent/locate-element`,{method:"POST",body:n,signal:t.abortSignal});return oy.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(`/${k}/web-agent/assertion`,{method:"POST",body:n,signal:t.abortSignal});return Ud.parse(o)}async getLintStepResult(e,t){let n={...e,disableCache:!!t.disableCache,loggerTags:t.loggerTags},o=await this.sendRequest(`/${k}/web-agent/lint/step`,{method:"POST",body:n,signal:t.abortSignal});return ny.parse(o)}async getLintMcpCopilotMessageResult(e,t){let n={message:e.message,disableCache:!!t.disableCache,loggerTags:t.loggerTags},o=await this.sendRequest(`/${k}/web-agent/lint/mcp-copilot`,{method:"POST",body:n,signal:t.abortSignal});return ry.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(`/${k}/web-agent/visual-assertion`,{method:"POST",body:n,signal:t.abortSignal});return Ud.parse(o)}async getAiActionCommand(e,t){let n=await this.sendRequest(`/${k}/web-agent/next-command-dynamic`,{method:"POST",body:{...e,disableCache:t.disableCache,loggerTags:t.loggerTags},signal:t.abortSignal});return ty.parse(n)}async getMultiturnAiActionCommand(e,t){return await this.sendRequest(`/${k}/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(`/${k}/web-agent/ai-action/evaluate`,{method:"POST",body:{...e,disableCache:t.disableCache,loggerTags:t.loggerTags},signal:t.abortSignal});return Ju.parse(n)}async getReverseMappedDescription(e,t){let n=await this.sendRequest(`/${k}/web-agent/reverse-mapped-description`,{method:"POST",body:{...e,disableCache:t.disableCache,loggerTags:t.loggerTags},signal:t.abortSignal});return iy.parse(n)}async getTextExtraction(e,t){let n={...e,disableCache:t.disableCache,loggerTags:t.loggerTags,agentConfigVersion:this.agentConfig?.["text-extraction"]},o=await this.sendRequest(`/${k}/web-agent/text-extraction`,{method:"POST",body:n,signal:t.abortSignal});return Yu.parse(o)}async getPageSummary(e,t){let n={...e,disableCache:t.disableCache,loggerTags:t.loggerTags},o=await this.sendRequest(`/${k}/web-agent/page-summary`,{method:"POST",body:n,signal:t.abortSignal});return bf.parse(o)}async getTestResultClassification(e,t){let n=await this.sendRequest(`/${k}/web-agent/result-classification`,{method:"POST",body:{...e,loggerTags:t.loggerTags},signal:t.abortSignal});return ku.parse(n)}async getExtractedKeywords(e,t){let n=await this.sendRequest(`/${k}/web-agent/extract-keywords`,{method:"POST",body:e,signal:t.abortSignal});return Zf.parse(n)}async getAutohealingProposal(e,t){let n=await this.sendRequest(`/${k}/web-agent/autoheal-section`,{method:"POST",body:{...e,loggerTags:t.loggerTags},signal:t.abortSignal});return hf.parse(n)}async getFailureRecoveryProposal(e,t){let n=await this.sendRequest(`/${k}/web-agent/failure-recovery`,{method:"POST",body:{...e,loggerTags:t.loggerTags},signal:t.abortSignal});return yf.parse(n)}async getFailureRecoveryPlan(e,t){let n=await this.sendRequest(`/${k}/web-agent/failure-recovery-plan`,{method:"POST",body:{...e,loggerTags:t.loggerTags},signal:t.abortSignal});return Sf.parse(n)}async getIframeRegex(e,t){let n=await this.sendRequest(`/${k}/web-agent/iframe-regex`,{method:"POST",body:e,signal:t.abortSignal});return Yg.parse(n)}getVercelAnthropicModelFactory({loggerTags:e}){return tu({baseUrl:this.baseUrl,apiKey:this.apiKey,loggerTags:e})}};import{z as fg}from"zod";var br=class extends Fr{constructor(e){super({...e,mode:void 0})}getAppUrl(){return this.baseUrl==="http://localhost:8000"?"http://localhost:3000":this.baseUrl.replace(/\/\/api/,"//app")}async getAuthInfo(){let e=await this.sendRequest(`/${k}/auth/check`,{method:"GET",retries:10,requestTimeoutMs:5e3});return yy.parse(e)}async bulkGetRunStatus(e){let t=await this.sendRequest(`/${k}/runs/status`,{method:"POST",body:e,retries:3,requestTimeoutMs:1e4});return gy.parse(t)}async getTestYAMLExport(e){let t=await this.sendRequest(`/${k}/tests/export`,{method:"POST",body:e,retries:3,requestTimeoutMs:3e4});return sy.parse(t)}async updateStepCaches(e,t){await this.sendRequest(`/${k}/cache`,{method:"PATCH",body:e,extraHeaders:t,retries:3,requestTimeoutMs:1e4,initialRetryDelayMs:3e3})}async getStepCacheForTest(e,t){let n=await this.sendRequest(`/${k}/cache`,{method:"POST",body:e,extraHeaders:t,retries:10,requestTimeoutMs:3e4,initialRetryDelayMs:3e3});return cy.parse(n)}async updateMobileStepCaches(e,t){await this.sendRequest(`/${k}/mobile-cache`,{method:"PATCH",body:e,extraHeaders:t,retries:3,requestTimeoutMs:1e4,initialRetryDelayMs:3e3})}async getMobileStepCacheForTest(e,t){let n=await this.sendRequest(`/${k}/mobile-cache`,{method:"POST",body:e,extraHeaders:t,retries:10,requestTimeoutMs:3e4,initialRetryDelayMs:3e3});return uy.parse(n)}async queueTests(e){let t=await this.sendRequest(`/${k}/tests/queue`,{method:"POST",body:e,retries:3,requestTimeoutMs:1e4});return ay.parse(t)}async uploadScreenshot(e){let t=await this.sendRequest(`/${k}/screenshots`,{method:"POST",body:e,retries:3,requestTimeoutMs:5e3});return Sy.parse(t)}async getAllEnvironments(){let e=await this.sendRequest(`/${k}/environments`,{method:"GET",retries:3,requestTimeoutMs:5e3});return by.parse(e)}async acquireCacheLock(e,t){let n=await this.sendRequest(`/${k}/result-cache/lock`,{method:"POST",body:e,signal:t,retries:3,requestTimeoutMs:3e4});return Ny.parse(n)}async releaseCacheLock(e){await this.sendRequest(`/${k}/result-cache/lock`,{method:"DELETE",body:{key:e},retries:3,requestTimeoutMs:5e3})}async deleteCacheResult(e){await this.sendRequest(`/${k}/result-cache/entry`,{method:"DELETE",body:e,retries:3,requestTimeoutMs:5e3})}async setCacheResult(e){await this.sendRequest(`/${k}/result-cache/entry`,{method:"PATCH",body:e,retries:3,requestTimeoutMs:5e3})}async getCacheResult(e){try{return await this.sendRequest(`/${k}/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(`/${k}/suites/queue`,{method:"POST",body:e,retries:3,requestTimeoutMs:5e3});return Ey.parse(t)}async bulkGetRunGroupStatus(e){let t={runGroupIds:e},n=await this.sendRequest(`/${k}/run-groups/status`,{method:"POST",body:t,retries:3,requestTimeoutMs:5e3});return kf.array().parse(n)}async uploadProposedSteps(e,t){try{await this.sendRequest(`/${k}/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(`/${k}/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(`/${k}/test-fragments/${e}`,{method:"GET",retries:3,requestTimeoutMs:1e4});return Ty.parse(t)}async patchTestFragment(e,t){await this.sendRequest(`/${k}/test-fragments/${e}`,{method:"PATCH",body:t,retries:3,requestTimeoutMs:1e4})}async getPastTestResults(e,t){let n=await this.sendRequest(`/${k}/results/tests/${e}`,{method:"POST",body:t,retries:3,requestTimeoutMs:1e4});return vy.parse(n)}async generateTestResultsUploadUrl(){let e=await this.sendRequest(`/${k}/results/uploads`,{method:"POST",retries:3,requestTimeoutMs:1e4});return Ay.parse(e)}async startProcessingResultsUpload(e,t){let n=await this.sendRequest(`/${k}/results/uploads/${e}/process`,{method:"POST",body:t,retries:3,requestTimeoutMs:1e4});return wy.parse(n)}async fetchIconKnowledgeBase(e){try{let t=await this.sendRequest(`/${k}/knowledge-base/icons`,{method:"GET",retries:3,requestTimeoutMs:5e3});return Uy.parse(t)}catch(t){return e.error({err:t},"Failed to fetch icon knowledge base"),null}}async saveNewIcons(e,t){try{await this.sendRequest(`/${k}/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(`/${k}/git/github/${e}/${t}/merge-base-commit?${i.toString()}`,{method:"GET",retries:3,requestTimeoutMs:1e4});return ga.parse(a)}async getCommitFromGithub(e,t,n){let o=await this.sendRequest(`/${k}/git/github/${e}/${t}/commits/${n}`,{method:"GET",retries:3,requestTimeoutMs:1e4});return ga.parse(o)}async getMergedBranchFromGithub(e,t,n,o){let i=encodeURIComponent(n),a=await this.sendRequest(`/${k}/git/github/${e}/${t}/${i}/${o}/merged-branch`,{method:"GET",retries:3,requestTimeoutMs:1e4});return Hd.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(`/${k}/git/gitlab/${i}/merge-base-commit?${o.toString()}`,{method:"GET",retries:3,requestTimeoutMs:5e3});return ga.parse(a)}async getCommitFromGitlab(e,t){let n=encodeURIComponent(e),o=await this.sendRequest(`/${k}/git/gitlab/${n}/commits/${t}`,{method:"GET",retries:3,requestTimeoutMs:1e4});return ga.parse(o)}async getMergedBranchFromGitlab(e,t,n){let o=encodeURIComponent(t),i=encodeURIComponent(e),a=await this.sendRequest(`/${k}/git/gitlab/${i}/${o}/${n}/merged-branch`,{method:"GET",retries:3,requestTimeoutMs:1e4});return Hd.parse(a)}async getAgentConfig(){let e=await this.sendRequest(`/${k}/web-agent/agent-config`,{method:"GET",retries:3,requestTimeoutMs:5e3});return fg.record(fg.string(),fg.string()).parse(e)}async getQuarantinedTests(){let e=await this.sendRequest(`/${k}/quarantine`,{method:"GET"});return Ry.parse(e)}async quarantineTest(e,t,n){await this.sendRequest(`/${k}/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(`/${k}/quarantine/${e.id}`,{method:"DELETE",body:{testName:e.name,reason:t,...n??{}},retries:3,requestTimeoutMs:1e4})}async createAndroidEmulator(e){let t=await this.sendRequest(`/${k}/limbar/android`,{method:"POST",retries:3,body:e,requestTimeoutMs:9e4,initialRetryDelayMs:5e3,maxRetryDelayMs:15e3});return Cy.parse(t)}async extendAndroidEmulatorTtl(e){try{await this.sendRequest(`/${k}/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(`/${k}/limbar/android/upload-url`,{method:"POST",retries:3,body:o,requestTimeoutMs:15e3,logResponse:!0});return xy.parse(i)}async deleteAndroidEmulator(e){await this.sendRequest(`/${k}/limbar/android/${e}`,{method:"DELETE",retries:3,requestTimeoutMs:3e4})}async getAndroidAssets(){let e=await this.sendRequest(`/${k}/limbar/assets`,{method:"GET",retries:3,requestTimeoutMs:1e4});return My.parse(e)}async deleteAndroidAsset(e,t){await this.sendRequest(`/${k}/limbar/assets/${e}/${t}`,{method:"DELETE",retries:3,requestTimeoutMs:1e4})}};async function Sg(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 ru=class{apiClient;constructor(e){this.apiClient=e}async reportBillableEvents(e,t){await this.apiClient.reportBillableEvents(e,t)}};var Ai=class extends Fr{generator;constructor(e,t){super(e),this.generator=t}async runTemplateMatching(e,t={}){let n=await this.sendRequest(`/${k}/web-agent/template-matching`,{method:"POST",body:e,signal:t?.signal});return Xg.parse(n)}async constructIframeRegex(e,t={}){return this.generator.getIframeRegex(e,{abortSignal:t.signal})}};var wi=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 oz,en as iz}from"@faker-js/faker";var Ri="v1",Ci=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 oz({locale:iz}),this.fakerInstance.seed(e.fakerSeed))}async sendAiGenerate(e){let t=typeof e=="string"?{input:e}:e;return this.httpClient.sendRequest(`/${Ri}/tools/ai/generate`,{method:"POST",body:t}).catch(n=>{throw n instanceof yr?new Error(n.rawError):new Error(`Failed to send AI generation: ${n.message}`)})}async sendSms(e){return this.httpClient.sendRequest(`/${Ri}/tools/sms/send`,{method:"POST",body:e}).then(()=>{}).catch(t=>{throw t instanceof yr?new Error(t.rawError):new Error(`Failed to send sms: ${t.message}`)})}async fetchLatestSms(e){return this.httpClient.sendRequest(`/${Ri}/tools/sms/fetchLatest`,{method:"POST",body:e}).catch(t=>{throw t instanceof yr?new Error(t.rawError):t})}async sendEmail(e){return this.httpClient.sendRequest(`/${Ri}/tools/email/send`,{method:"POST",body:e}).then(()=>{}).catch(t=>{throw t instanceof yr?new Error(t.rawError):new Error(`Failed to send email: ${t.message}`)})}async fetchAllEmails(e){return this.httpClient.sendRequest(`/${Ri}/tools/email/fetchAll`,{method:"POST",body:e}).catch(t=>{throw t instanceof yr?new Error(t.rawError):new Error(`Failed to fetch all emails: ${t.message}`)})}async fetchLatestEmail(e){return this.httpClient.sendRequest(`/${Ri}/tools/email/fetchLatest`,{method:"POST",body:e}).catch(t=>{throw t instanceof yr?new Error(t.rawError):new Error(`Failed to fetch latest emails: ${t.message}`)})}};function mC(r,e,t){return fetch(r,{method:"PUT",body:t,headers:{"Content-Type":e}})}var nu=class{constructor(e){this.client=e}async uploadResultsArchive(e,t){let{uploadUrl:n,id:o}=await this.client.generateTestResultsUploadUrl(),i=await mC(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 xi=class extends Fr{constructor(e){super(e)}async getElementLocation(e,t){let n={...e,loggerTags:t.loggerTags},o=await this.sendRequest(`/${k}/mobile-agent/locate-element`,{method:"POST",body:n,signal:t.abortSignal});return tS.parse(o)}async evaluateAssertion(e,t){let n={...e,loggerTags:t.loggerTags},o=await this.sendRequest(`/${k}/mobile-agent/assertion`,{method:"POST",body:n,signal:t.abortSignal});return oS.parse(o)}getVercelAnthropicModelFactory({loggerTags:e,sessionId:t}){return tu({baseUrl:this.baseUrl,apiKey:this.apiKey,sessionId:t,loggerTags:e})}};function ou({orgId:r,client:e,gitMetadata:t,regenerateCache:n,alwaysSaveCache:o,noCache:i}){return i?new ll:new yg(r,e,t,o)}var yg=class{constructor(e,t,n,o){this.orgId=e;this.client=t;let{gitBranchName:i,gitProtectedBranches:a}=n;this.cacheHeaders=Fd(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.info("Skipping mobile cache last used at update because branch is protected");return}for(let i of[t])i&&tm({steps:i,stepCacheEntries:n,logger:e.logger});let{cachesToSave:o}=await ro({steps:t,cacheCreationParams:{testId:e.testId,orgId:this.orgId}});this.client.updateMobileStepCaches({entries:o,testId:e.testId},this.cacheHeaders)}};import iu from"path";function az(r){let e=new gC,t=iu.join(r,"metadata.json"),n=cl.parse(JSON.parse(bg.readFileSync(t,"utf-8")));e.addLocalFile(t);for(let o of bg.readdirSync(iu.join(r,"runs"))){if(!o.endsWith(".zip"))continue;let i=o.replace(/\.zip$/,""),a=new gC(iu.join(r,"runs",o));for(let l of a.getEntries())l.isDirectory||e.addFile(iu.join("runs",i,l.entryName),l.getData())}return{runGroupId:n.id,buffer:e.toBuffer()}}async function au(r){let{client:e,consoleLogger:t,resultsPath:n}=r;if(!bg.existsSync(n)){t.warn("Results path does not exist, skipping upload.");return}let o=new nu(e);try{let{runGroupId:i,buffer:a}=az(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 sz from"adm-zip";import gt from"fs";import Vt from"path";var ns=class r{constructor(e){this.filePath=e;gt.rmSync(this.filePath,{recursive:!0,force:!0}),gt.mkdirSync(this.filePath,{recursive:!0})}cd(e){return new r(Vt.join(this.filePath,e))}cwd(){return this.filePath}mkdir(e){gt.mkdirSync(Vt.join(this.filePath,e),{recursive:!0})}readFile(e){let t=Vt.join(this.filePath,e);if(gt.existsSync(t))return gt.readFileSync(t)}storeFile(e){let{name:t,contents:n}=e,o=Vt.join(this.filePath,t);try{gt.writeFileSync(o,n)}catch{}}createFileStream(e){let t=Vt.join(this.filePath,e);return gt.createWriteStream(t)}createRunArchive(e){return new Eg(Vt.join(this.filePath,"runs"),e)}},Eg=class{constructor(e,t){this.filePath=e;this.tempPath=Vt.join(e,`.${t}`),this.finalPath=Vt.join(e,`${t}.zip`),gt.rmSync(this.tempPath,{recursive:!0,force:!0}),gt.rmSync(this.finalPath,{recursive:!0,force:!0}),gt.mkdirSync(this.tempPath,{recursive:!0})}tempPath;finalPath;readFile(e){let t=Vt.join(this.tempPath,e);if(gt.existsSync(t))return gt.readFileSync(t)}mkdir(e){gt.mkdirSync(Vt.join(this.tempPath,e),{recursive:!0})}cd(e){return new ns(Vt.join(this.tempPath,e))}cwd(){return this.tempPath}storeFile(e){let{name:t,contents:n}=e,o=Vt.join(this.tempPath,t);gt.writeFileSync(o,n)}createFileStream(e){let t=Vt.join(this.tempPath,e);return gt.createWriteStream(t)}close(){let e=new sz;e.addLocalFolder(this.tempPath,void 0,n=>n!==".DS_Store");let t=e.toBuffer();gt.writeFileSync(this.finalPath,t),gt.rmSync(this.tempPath,{recursive:!0,force:!0})}};import hu from"fs";import MC from"body-parser";import xz from"cors";import Mz from"dedent";import{Router as dz}from"express";import Lt from"fs";import{globSync as pz}from"glob";import ut from"path";import su from"fs";import lz from"path";var cz=new Ac(30,60*1e3),wg="https://api.momentic.ai",vg,fC=r=>{wg=r},Rg=()=>wg,os=()=>vg;var Mi,Ag,hC,SC=async r=>{if(vg&&Mi&&hC)return Mi;let e=new br({baseUrl:wg,apiKey:r,logger:R});vg=e;try{let t=await e.getAuthInfo();return Mi=t.orgId,Ag=t.userId,hC=r,Mi}catch(t){throw new Error(`Error checking API key against server: ${t}`)}},_i=()=>{if(!Mi)throw new Error("Your organization ID is invalid.");return Mi},lu=()=>{if(!Ag)throw new Error("Your user ID is invalid.");return Ag};var Cg,Tg,yC=(r,e)=>{Cg=r,Tg?.abort(),Tg=new AbortController;let t=Tg.signal,n=[r.configFilePath];r.config.environments?.forEach(o=>{if(!o.envFile)return;let i=lz.resolve(r.rootDir,o.envFile);try{if(su.lstatSync(i).isSymbolicLink())return;su.existsSync(i)&&n.push(i)}catch(a){R.warn({err:a},`Failed to check if env file ${i} exists`)}});try{uz({filesToWatch:n,revalidator:e,signal:t,project:r})}catch(o){R.error({err:o},"Failed to start config file watchers")}},tt=()=>Cg;function uz({filesToWatch:r,revalidator:e,signal:t,project:n}){R.debug("Starting watch on the following files:"),r.forEach(o=>{R.debug(`- ${o}`)}),r.forEach(o=>{let i=async(l,c)=>{l.mtime.getTime()!==c.mtime.getTime()&&(cz.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.`),Cg=await Promise.resolve(e(n.configFilePath)))};su.watchFile(o,{persistent:!1},i);let a=()=>{su.unwatchFile(o,i),t.removeEventListener("abort",a)};t.addEventListener("abort",a),process.once("SIGUSR2",()=>{a(),process.kill(process.pid,"SIGUSR2")})})}function at(r){return function(...e){let t=e[e.length-1],n=r(...e);Promise.resolve(n).catch(t)}}var as=dz();function is(r){let e=tt(),t=ut.dirname(e.configFilePath);return ut.join(t,...r)}function mz(r){let e=tt(),t=ut.dirname(e.configFilePath),n=ut.relative(t,r);return n?n.split(ut.sep):[]}function gz(r,e){let t=Lt.statSync(r),n=mz(r);return Id.parse({name:e,absolutePath:r,relativePath:n.join(ut.sep),pathSegments:n,isDirectory:t.isDirectory(),size:t.size,createdAt:t.birthtime,modifiedAt:t.mtime,accessedAt:t.atime})}as.post("/",at(async(r,e,t)=>{let n;try{n=FS.parse(r.body).pathSegments}catch(d){e.status(400).json({error:`Failed to parse folder read body: ${d}`});return}let o=is(n);if(!Lt.existsSync(o)){e.status(404).json({error:`Path not found: ${n.join(ut.sep)}`});return}if(!Lt.statSync(o).isDirectory()){e.status(400).json({error:`Path is not a directory: ${n.join(ut.sep)}`});return}let a=tt(),l=Array.from(a.config.exclude??[]).concat(tl),s=pz("*",{absolute:!1,cwd:o,ignore:l,dotRelative:!1,maxDepth:1,nodir:!1}).map(d=>{let p=ut.join(o,d);return gz(p,d)}),u={absolutePath:o,pathSegments:n,contents:s};e.status(200).json(u)}));as.put("/",at(async(r,e,t)=>{let n;try{n=BS.parse(r.body).pathSegments}catch(a){e.status(400).json({error:`Failed to parse folder create body: ${a}`});return}let o=is(n);if(Lt.existsSync(o)){e.status(200).json({success:!0,message:`Folder already exists: ${n.join(ut.sep)}`,pathSegments:n});return}Lt.mkdirSync(o,{recursive:!0});let i={success:!0,message:`Folder created: ${n.join(ut.sep)}`,pathSegments:n};e.status(201).json(i)}));as.patch("/",at(async(r,e,t)=>{let n,o;try{let s=zS.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=is(n),a=is(o);if(!Lt.existsSync(i)){e.status(400).json({error:`Folder not found: ${n.join(ut.sep)}`});return}if(Lt.existsSync(a)){e.status(400).json({error:`Destination already exists: ${o.join(ut.sep)}`});return}let l=ut.dirname(a);Lt.existsSync(l)||Lt.mkdirSync(l,{recursive:!0}),Lt.renameSync(i,a);let c={success:!0,message:`Folder moved from ${n.join(ut.sep)} to ${o.join(ut.sep)}`,pathSegments:o};e.status(200).json(c)}));as.delete("/",at(async(r,e,t)=>{let n,o=!0;try{let c=HS.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=is(n);if(!Lt.existsSync(i)){e.status(200).json({success:!0,message:`Folder not found: ${n.join(ut.sep)}`,pathSegments:n});return}if(!Lt.statSync(i).isDirectory()){e.status(400).json({error:`Path is not a directory: ${n.join(ut.sep)}`});return}if(o)Lt.rmSync(i,{recursive:!0,force:!0});else{if(Lt.readdirSync(i).length>0){e.status(409).json({error:`Cannot delete non-empty directory without recursive flag: ${n.join("/")}`});return}Lt.rmdirSync(i)}let l={success:!0,message:`Folder deleted: ${n.join("/")}`,pathSegments:n};e.status(200).json(l)}));var xg=as;import{Router as Sz}from"express";import{hostname as hz}from"os";var fz="0.4.0",ss=Go({app:"desktop-server",hostname:hz(),disableConsoleLogs:!0}).child({cliVersion:fz});(async()=>{try{let r=await ts(ss);r.gitBranchName&&ss.addBinding("branch",r.gitBranchName)}catch{}})();var bC=Sz();bC.get("/",async(r,e)=>{let t=tt(),n=os();if(!n){e.status(500).json({message:"API client not initialized"});return}let o=await Ti(ss,n,t);e.status(200).json(o)});var Mg=bC;import _z from"events";import _C,{Router as Pz}from"express";import Iz from"http";import Oz from"path";var cu=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 EC=new cu;import{Router as bz}from"express";import{existsSync as Ez}from"fs";import Tz from"path";import{hostname as yz}from"os";var _g="0.4.0",Nt=Go({app:"mobile-desktop-server",hostname:yz(),disableConsoleLogs:!0}).child({cliVersion:_g});(async()=>{try{let r=await ts(Nt);r.gitBranchName&&Nt.addBinding("branch",r.gitBranchName)}catch{}})();var Pg=bz();Pg.get("/",at(async(r,e)=>{let t=os();if(!t){e.status(500).json({message:"API client not initialized"});return}let n=await t.getAndroidAssets();e.status(200).json(n)}));Pg.post("/upload-url",at(async(r,e)=>{let t;try{t=qS.parse(r.body)}catch(i){e.status(400).json({error:`Invalid request body: ${i}`});return}let n=os();if(!n){e.status(500).json({error:"API client not initialized"});return}let o=Tz.resolve(t.filePath);if(!Ez(o)){e.status(400).json({error:`File not found: ${o}`});return}await lc({tag:t.tag,channel:t.channel,filePath:o,apiClient:n,logger:Nt}),e.sendStatus(204)}));var TC=Pg;import{Router as vz}from"express";var vC=vz();vC.get("/",at(async(r,e)=>{let t=tt(),n=await Sr(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 AC=vC;import{Router as Az}from"express";var wC=Az();wC.get("/",(r,e)=>{e.status(200).json({userId:lu(),orgId:_i(),cliVersion:_g??"0.0.0"})});var RC=wC;import{Router as wz}from"express";var uu=wz();async function Rz(r){return(await aC(r,Nt)).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)}uu.get("/",at(async(r,e)=>{let t=tt(),n=await Sr(t),o=await Rz(n);e.status(200).json(o)}));uu.get("/:moduleId",at(async(r,e)=>{if(!r.params.moduleId){e.status(400).json({error:"Missing moduleId in url path."});return}let t=await Sr(tt()),n=t.mobileModules[r.params.moduleId];if(!n){e.status(404).json({error:"Mobile module not found."});return}try{let o=await dg(n,t,R);e.json(o)}catch(o){e.status(400).json({err:o})}}));uu.patch("/:moduleId/metadata",at(async(r,e)=>{if(!r.params.moduleId){e.status(400).json({error:"Missing moduleId in url path."});return}let t;try{t=KS.parse(r.body)}catch(i){e.status(400).json({error:`Invalid request body: ${i}`});return}let n=tt(),o=await Sr(n);iC({moduleId:r.params.moduleId,patch:t,momenticFiles:o,logger:R,project:n}),e.status(201).json({message:"ok"})}));var CC=uu;import{Router as Cz}from"express";import Ig from"path";var du=Cz();du.patch("/:testPath",at(async(r,e)=>{let t=r.params.testPath;if(!t){e.status(400).json({error:"Missing testPath in path"});return}let n;try{n=$S.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=tt(),i=t.endsWith(".test.yaml")?t:`${t}.test.yaml`,a=await Sr(o);await lC({filePath:i,steps:n.steps,settings:n.settings,folder:o.rootDir,project:o,momenticFiles:a});let l={message:"ok"};e.status(200).json(l)}));du.post("/",at((r,e)=>{let t;try{t=WS.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{Ku(n)}catch(g){e.status(400).json({error:g.message});return}let l=tt(),c=Ig.join(l.rootDir,...a),{fullPath:s,testId:u}=sC({name:n,description:o,steps:[],settings:i,folder:c}),d=Ig.basename(s),p=Ig.relative(l.rootDir,s),m={id:u,fileName:d,fullPath:s,relativeFilePath:p};e.status(201).json(m)}));du.get("/:fileName",at(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=tt(),i=await Sr(o),l=await eu(n,Nt,i);e.status(200).json(l)}));var xC=du;var pu=class extends wi{constructor(t,n){super(t,n);this.client=t;this.orgId=n}async fetchEnvironment(t,n){let o=tt();return Xc(t,o,R)}};var PC="10mb";async function IC(r){let{serverPort:e,apiKey:t,momenticServerUrl:n,staticDir:o,initialProject:i,driverLogLevel:a,regenerateCache:l,alwaysSaveCache:c,noCache:s}=r;n&&fC(n),await SC(t);let u=_i(),d=lu(),p=r.logger.child({orgId:u,userId:d});yC(i,w=>es({configFilePath:w}));let m=_C();m.use(xz()),m.use(MC.json({limit:PC})),m.use(MC.urlencoded({extended:!1,limit:PC}));let g=Pz();if(g.use("/folders",xg),g.use("/entities",AC),g.use("/identify",RC),g.use("/mobile-tests",xC),g.use("/mobile-modules",CC),g.use("/assets",TC),g.use("/git",Mg),m.use("/api",g),m.use((w,D,j)=>{R.debug({url:w.url,path:w.path,query:w.query,method:w.method,body:w.body,headers:w.rawHeaders,client:w.ip},"Incoming request on mobile-desktop-server"),D.on("close",()=>{D.statusCode>=400&&(R.error({url:w.url,method:w.method,statusCode:D.statusCode},"Request completed in error on mobile-desktop-server"),Nt.error({url:w.url,method:w.method,statusCode:D.statusCode},"Request completed in error on mobile-desktop-server"))}),j()}),m.use((w,D,j,ae)=>{if(w instanceof Error&&w.message.includes("BadRequestError: request aborted")){j.status(400).send("Client disconnected");return}R.error({stack:w.stack,msg:w.message,err:w,url:D.url,method:D.method},"Unhandled exception leading to 500 on mobile-desktop-server"),Nt.error({stack:w.stack,msg:w.message,err:w,url:D.url,method:D.method},"Unhandled exception leading to 500 on mobile-desktop-server"),j.status(500).send(`Internal Server Error: ${w.message}`)}),o){let w=_C.static(o,{setHeaders:D=>{D.setHeader("Cache-Control","no-cache")},redirect:!1});m.use(w),m.use("*",(D,j)=>{j.sendFile(Oz.join(o,"index.html"))})}let h=Iz.createServer(m),f=`http://localhost:${e}`;await new Promise(w=>{try{h.listen(e,()=>{p.info(`Mobile desktop server is running at ${f}`),w()})}catch(D){D.message.includes("EADDRINUSE")?Lz(e):R.error(`An unexpected error occurred while starting the server: ${D.message}`),process.exit(1)}});let b={type:"API_KEY",baseUrl:Rg(),apiKey:t,logger:p},C=new br(b),A=tt(),v={...b,mode:"interactive"},{dispose:M}=qR({baseServer:h,logger:p,authorization:b,globalStateManager:EC,getOrgId:()=>_i(),androidDriverFactory:async({socket:w,logger:D,creationOpts:j})=>{let ae=Math.floor(Math.random()*1e4)+4e4,Q=await ml(ae,"appium");return sc({logger:D,driverLogLevel:a,apiClient:C,creationOpts:j,socket:w,appiumPort:Q,orgId:_i(),onStatusUpdate:pe=>{w.emit("connectionStatusUpdate",{message:pe})}})},mobileGeneratorFactory:async w=>new xi({baseUrl:Rg(),apiKey:t,logger:p,mode:"interactive"}),browserGeneratorFactory:async w=>new fo(A.config.ai?.agentConfig,v),browserEnricherFactory:async w=>new Ai(v,new fo(A.config.ai?.agentConfig,v)),storageFactory:async w=>new pu(C,w),cacheStorageFactory:async w=>{let D=await Ti(p,C,A);return ou({orgId:w,client:C,gitMetadata:D,regenerateCache:l??!1,noCache:s??!1,alwaysSaveCache:c??!1})},localToolsFactory:async()=>new Ci({httpClient:C,fakerSeed:void 0}),keepSessionAlive:w=>C.extendAndroidEmulatorTtl(w),settingsFactory:async()=>({emulator:A.config.emulator})});process.once("SIGUSR2",async()=>{return;try{await M(),await At.flush()}catch(w){R.error({err:w},"Error during session dispose on SIGUSR2")}try{h.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 M(),await At.flush()}finally{h.close(()=>process.exit(0))}}),process.once("SIGINT",async()=>{R.info("SIGINT in Momentic mobile app received");try{await M(),await At.flush()}finally{h.close(()=>process.exit(0))}})}_z.setMaxListeners(25);process.on("warning",r=>{Nt.warn({err:r},`Node warning received on mobile-desktop-server: ${r.message}`)});process.on("uncaughtException",r=>{Nt.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=>{Nt.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 Lz(r){R.error(Mz`Port ${r} is already in use by another process. Please close the other process and try again.
4138
+ `;import{tool as VB}from"ai";import{randomUUID as jB}from"crypto";import WB from"zod";import{tool as HB}from"ai";import GB from"zod";var GR=r=>{let e=HB({description:"Get the current state of the emulator (XML + screenshot)",inputSchema:GB.object({}),toModelOutput:t=>t,execute:async()=>{let{controller:t,logger:n}=r;return n.info("AI action tool called (get_emulator_state)"),eg(t)}});return{name:BR,tool:e}};async function eg(r){let e=await r.getA11yTree(),t=await r.getScreenshotBase64();return{type:"content",value:[{type:"text",text:e},{type:"text",text:"</emulatorXml>"},{type:"text",text:"<screenshot>"},{type:"media",data:t,mediaType:"image/png"},{type:"text",text:"</screenshot>"}]}}var VR=r=>({name:"create_execute_step",tool:VB({description:"Create and immediately execute a new Momentic step in the Android emulator, returning the result from the step and the state of the emulator after the step finished executing.",inputSchema:WB.object({step:Cd}),toModelOutput:t=>t,execute:async({step:t})=>{let{contextManager:n,logger:o,controller:i}=r;o.info({step:t},"AI action tool called (create_execute_step)");let a=yS(t),l={id:jB(),type:"MOBILE_PRESET_STEP",command:a},c=await n.createAndExecuteStep(l);c.status==="SUCCESS"&&await i.waitForScreenshotStability({reason:"Waiting for stability after executing AI-generated sub-step"});let s={...c,trace:void 0,beforeSnapshot:void 0,afterSnapshot:void 0},u=await eg(i);return{type:"content",value:[{type:"text",text:"<result>"},{type:"text",text:JSON.stringify(s,null,2)},{type:"text",text:"</result>"},{type:"text",text:"<stateAfter>"},...u.value,{type:"text",text:"</stateAfter>"}]}}})});import{tool as $B}from"ai";import tg from"zod";var jR=r=>{let e=$B({description:"Signal that the AI action has reached a terminal state (either success or failure).",inputSchema:tg.object({message:tg.string(),success:tg.boolean()}),toModelOutput:t=>t,execute:async({message:t,success:n})=>{let{contextManager:o,logger:i}=r;return i.info({message:t,success:n},"AI action tool called (finish)"),o.finalState={message:t,status:n?"SUCCESS":"FAILED"},{type:"content",value:[{type:"text",text:"Done"}]}}});return{name:Yc,tool:e}};var WR=[VR,GR,jR];function $R(r){let{logger:e,controller:t,contextManager:n,aiActionSessionId:o}=r,i={};for(let c of WR){let s=c({contextManager:n,logger:e,controller:t});i[s.name]=s.tool}let a=t.generator.getVercelAnthropicModelFactory({loggerTags:pe(e),sessionId:o}),l=c=>{let{messages:s}=c,u=!1;for(let d=s.length-1;d>=0;d--){let p=s[d];for(let m of p.content)if(!(typeof m!="object"||!("type"in m))&&!(m.type!=="tool-result"||m.output.type!=="content")&&!(m.output.value.length<3))for(let g=0;g<m.output.value.length;g++){let h=m.output.value[g];if(h.type==="text"&&h.text.includes("<emulatorXml>"))if(u){let f=m.output.value[g+1];f.type==="text"?f.text="TRUNCATED DUE TO CONVERSATION LENGTH":e.warn({msg:f},"Got unexpected part when truncating emulator state message")}else{u=!0;continue}}}return c};return{model:a("claude-haiku-4-5-20251001"),tools:i,prepareStep:l,stopWhen:[KB(15),qB(Yc)],system:HR(!1)}}async function qR(r){let e=Date.now(),{controller:t,logger:n}=r.fixtures;try{return await JB(r)}catch(o){let i=t.isAborted()||o instanceof DOMException&&o.name==="AbortError";return i||n.error({err:o},"Failed to execute mobile AI action"),{...r.aiActionParams.step,steps:[],type:"MOBILE_AI_ACTION_STEP",startTime:e,endTime:Date.now(),status:i?"CANCELLED":"FAILED",message:i?"Step cancelled.":`${o}`}}}async function JB(r){let{step:e,stepTracer:t,executeMobileStepList:n}=r.aiActionParams,{controller:o,logger:i}=r.fixtures,{step:a}=r.callbacks,l=await t.startSubSteps(),c=XB(),s=i.child({stepId:e.id,aiActionSessionId:c}),u=Date.now(),d=async(f,E)=>{let b=await n({...r,listParams:{steps:[f],tracer:l,containerName:`AI action sub-step ${E}`}});if(b.results.length!==1)throw new Error("InternalWebAgentError: Expected exactly one result from executeMobileStepList");return b.results[0]},p={stepId:e.id,parentStepIdChain:t.getParentStepIdChain()},m=new Kc({controller:o,callbacks:{onAiActionEvent:a?.onAiActionEvent,executeStep:d},logger:s,rootStep:p}),g=$R({controller:o,logger:s,contextManager:m,aiActionSessionId:c}),h=YB({...g,messages:[{role:"user",content:e.text}]});for await(let f of h.fullStream)switch(f.type){case"text-delta":a?.onAiActionEvent?.({type:"LLM_TEXT_OUTPUT",text:f.text,rootStep:p})}if(await h.response,o.throwIfAborted(),!m.finalState)throw new Error("InternalWebAgentError: The AI agent never reached a final state. This could be because the maximum number of steps was reached.");return{...e,status:m.finalState.status,startTime:u,endTime:Date.now(),message:m.finalState.message,steps:m.results}}async function Xc(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}/${i.length} in ${o} - ${Fv(b)}`),b.skipped){l.debug("Step skipped");continue}if(f&&g){let _=JSON.stringify(u);if(b.id===g.fromStepId&&_===JSON.stringify(g.parentStepIdChain))f=!1;else if(!jv({currentStep:b,currentParentChain:u,desiredStepId:g.fromStepId,desiredStepParentChain:g.parentStepIdChain}))continue}let x=await a.startStep({logger:l,step:b,attempt:1,parentStepIdChain:u});s.trackStepExecution(b);let A=await ZB({step:b,stepTracer:x,params:r}),{trace:v}=await x.finish({parentStepIdChain:u,result:A});if(A.trace=v,l.info({step:{id:b.id},trace:A.trace,status:A.status},`Finished step ${E+1}/${i.length} (${b.type==="MOBILE_PRESET_STEP"?b.command.type:b.type})`),d.push(A),A.status!=="SUCCESS"){m=A.status,p=A;break}if(b.envKey&&c.context.setVariable(b.envKey,A.data),h){let _=JSON.stringify([]);if(b.id===h.toStepId&&_===JSON.stringify(h.parentStepIdChain))break}}return{results:d,status:m,terminalResult:p}}async function ZB({step:r,stepTracer:e,params:t}){let{fixtures:n,inputs:o,callbacks:i}=t,a;switch(r.type){case"MOBILE_PRESET_STEP":{a=await FR({fixtures:n,inputs:o,step:r,stepTracer:e,callbacks:i});break}case"RESOLVED_MOBILE_MODULE":{a=await kR({...t,moduleParams:{step:r,stepTracer:e,executeMobileStepList:Xc}});break}case"MOBILE_AI_ACTION_STEP":{a=await qR({...t,aiActionParams:{step:r,stepTracer:e,executeMobileStepList:Xc}});break}}return a}async function Jc(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=ez(n);a.info({testMetadata:Rr.parse(o)},"Starting mobile test");let s=await e.startMainStepList(),u=mb(a),d=DR(l,a);a.info({cpu:u?.cpuMetadata,platform:u?.platform},`Starting execution of ${t}`);let{status:p,results:m}=await Xc({...r,listParams:{containerName:t,tracer:s,steps:c}});if(clearInterval(u?.interval),clearInterval(d),p==="SUCCESS"){let g=QB(c,n);if(g&&Object.keys(g).length>0){a.info({diffs:g},"Saving mobile step cache entries post-success");let{cachesToSave:h}=await no({steps:c,cacheCreationParams:{orgId:r.inputs.orgId,testId:o.id}});await i.saveEntries({logger:a,testId:o.id,entries:h})}else a.info("No cache entries to update");return{status:"PASSED",results:m}}return p==="CANCELLED"?{status:"CANCELLED",results:m}:{status:"FAILED",results:m}}var rg=class{parentTracer=null;socket;step;interactionTracer;constructor({step:e,socket:t,parentTracer:n}){this.socket=t,this.parentTracer=n,this.step=e,this.interactionTracer=new co,Yr.initializeRootTracerContext(this.interactionTracer)}attachBeforeScreenshot(){}attachAfterScreenshot(){}attachBeforeHtmlSnapshot(){}attachAfterHtmlSnapshot(){}async finish(e){this.interactionTracer.finish();let t=this.interactionTracer.getRootSpan(),n={...qy.parse(e),trace:Pd.parse(t)};switch(n.result.status){case"SUCCESS":this.socket.emit("success",n);break;case"FAILED":this.socket.emit("failure",n);break;case"CANCELLED":this.socket.emit("cancelled",n);break}return{trace:t}}getParentStepIdChain(){return this.parentTracer?this.parentTracer?.getParentStepIdChain()??[]:[]}async startSubSteps(){return new Ei({parentStep:this.step,socket:this.socket,parentTracer:this})}},Ei=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 rg({step:e.step,parentTracer:this,socket:this.socket})}},Zc=class{constructor(e){this.socket=e}appendLogs(){}async finish(){this.socket.emit("finished")}async startBeforeStepList(){return new Ei({parentStep:null,parentTracer:null,socket:this.socket})}async startMainStepList(){return new Ei({parentStep:null,parentTracer:null,socket:this.socket})}async startAfterStepList(){return new Ei({parentStep:null,parentTracer:null,socket:this.socket})}};var tz=({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=e.child({testId:i.testMetadata.id}),s=await o(r.orgId),u=l.controller;u.resetAbortController();let d=new Zc(n),p=await Jc({fixtures:{controller:u,logger:c,cacheStorage:s,usageTracker:new Hs},containerName:"entire test",inputs:{steps:i.steps,fromStep:i.fromStep,toStep:i.toStep,orgId:r.orgId,testMetadata:i.testMetadata,interactive:!0},tracer:d,callbacks:{step:{onAiActionEvent:g=>{n.emit("aiActionEvent",g)}}}});await d.finish();let m={results:tr.array().parse(p.results),status:p.status};a?.(m)},KR={event:"execute",createHandler:tz};import{debounce as rz}from"ts-debounce";var nz=({socket:r,globalStateManager:e,keepSessionAlive:t})=>{let n=rz(t,3e4,{maxWait:6e4});return async()=>{let o=e.getSession(r.id);if(!o)throw new Error("No active Android session found");o.emulatorName&&(o.local||n(o.emulatorName))}},YR={event:"keepalive",createHandler:nz};var XR=[KR,LR,YR,NR];function JR(r){let{logger:e,baseServer:t,globalStateManager:n}=r,o=new oz(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=>{let c=l.id,s=e.child({sessionId:c});s.info({event:"connection",transport:l.conn.transport.name},"Android websocket connection initiated"),l.on("disconnect",async()=>{await OR({socket:l,globalStateManager:n,logger:s})});let u;try{u=await IR({...r,socket:l,globalStateManager:n,logger:s})}catch(d){s.error({err:d},"Failed to setup Android connection"),l.emit("error",{message:d instanceof Error?d.message:JSON.stringify(d)}),l.disconnect(!0);return}XR.forEach(d=>a(d,{...r,socket:l,metadata:u,logger:s}))});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{randomUUID as sH}from"crypto";import{diff as YPe}from"deep-object-diff";import aIe from"yaml";import{z as lIe}from"zod";import{execSync as iz}from"child_process";function po(r,e){let t=e.hooks?.postSave;if(!t)return;let n;t.includes("$1")?n=t.replaceAll("$1",r):n=`${t} ${r}`,w.debug({postSaveCommand:n},"Executing post-save hook command");try{iz(n,{encoding:"utf-8"})}catch(o){w.warn({err:o,postSaveCommand:n},"Failed to execute post-save hook command, continuing...")}}import{diff as CPe}from"deep-object-diff";import{cloneDeep as MPe}from"lodash-es";import{v4 as zPe}from"uuid";import GPe from"yaml";import az from"@dotenvx/dotenvx";import sz from"fs";import ZR from"path";function lz(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 cz(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=lz(i);l&&(n[o]=l);continue}let a;try{a=sz.readFileSync(ZR.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 uz(r){let{project:e,envFile:t,logger:n}=r,o={};if(!t)return o;let i=az.config({path:ZR.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 Qc(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=cz({envVariables:n.envVariables,project:e});Object.assign(o,i);let a=uz({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 Az,readFileSync as wz,readdirSync as Rz,writeFileSync as Cz}from"fs";import{glob as xz}from"glob";import mo,{dirname as tC}from"path";import{cwd as sg}from"process";import rC from"yaml";import{z as Me}from"zod";import QR from"fs";import{glob as dz}from"glob";import ts from"path";import pz from"yaml";import{z as ng}from"zod";var eC=!1,og=["**/*.test.yaml","**/*.module.yaml"],ig=ng.string().refine(r=>/^[a-zA-Z0-9-]+$/.test(r)),ag=15,mz=ng.object({fileType:ng.nativeEnum(Pe)});async function br(r,e=!1){let t={project:r,tests:{},modules:{},mobileTests:{},mobileModules:{},duplicateEntities:{}},n=r.config.include??og,o=Array.from(r.config.exclude??[]).concat(nl),i=AbortSignal.timeout(5e3),a;try{a=await dz(n,{absolute:!1,cwd:r.rootDir,ignore:o,dotRelative:!1,maxDepth:ag,nodir:!0,signal:i})}catch(l){throw w.error({err:l},"Failed to list all Momentic files in the current directory. This usually indicates the 'include' and 'exclude' globs are misconfigured in your momentic.config.yaml, or that your machine is severely resource constrained."),new Error("Listing Momentic files timed out after 5 seconds.",{cause:l})}for(let l of a){let c=gz(r.rootDir,l,t,e?gn:w);c&&(t.duplicateEntities[c.id]=c.paths)}return eC=!0,t}function gz(r,e,t,n){let o=ts.join(r,e),i=hz(o,n);if(!i)return;let a=fz(i,o,n);if(!a)return;let l=mz.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=Sz(o,n);if(!s)return;let u=yz(e,o,s);switch(c){case Pe.TEST:try{return bz(a,t,u,o,n)}catch(d){n.warn(`Skipping file '${o}' because it is missing Momentic test metadata: ${d}`);return}case Pe.MODULE:try{return Ez(a,t,u,o,n)}catch(d){n.warn(`Skipping file '${o}' because it is missing Momentic module metadata: ${d}`);return}case Pe.MOBILE_TEST:try{return vz(a,t,u,o,n)}catch(d){n.warn(`Skipping file '${o}' because it is missing Momentic mobile test metadata: ${d}`);return}case Pe.MOBILE_MODULE:try{return Tz(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 hz(r,e){try{return QR.readFileSync(r,"utf-8")}catch(t){e.warn(`Could not read possible Momentic file at ${r}, skipping: ${t}`);return}}function fz(r,e,t){try{let n=pz.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 Sz(r,e){try{return QR.statSync(r)}catch(t){e.warn(`Skipping path '${r}' because it could not be stat, skipping: ${t}`);return}}function yz(r,e,t){return{relativePath:r,fullFilePath:e,platformSep:ts.sep,fullPathSegments:e.split(ts.sep),relativePathSegments:r.split(ts.sep),fileName:ts.basename(e),lastModified:t.mtime,createdAt:t.birthtime}}function bz(r,e,t,n,o){let i=Bo.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:Pe.TEST,name:i.name,id:i.id,description:i.description??void 0,labels:i.labels,...t},a}function Ez(r,e,t,n,o){let i=Kt.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:Pe.MODULE,name:i.name,id:i.moduleId,description:i.description??void 0,...t};let l=t.fileName.replace(".module.yaml","");return!eC&&on(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 Tz(r,e,t,n,o){let i=sa.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:Pe.MOBILE_MODULE,name:l,id:i.moduleId,description:i.description??void 0,...t},a}function vz(r,e,t,n,o){let i=Rr.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:Pe.MOBILE_TEST,name:l,id:i.id,description:i.description??void 0,...t},a}var Ti="momentic.config.yaml",lg="momentic.workspace.yaml",Mz=Me.object({projects:Me.string().array().describe("list of glob patterns to find project (momentic.config.yaml) files")}),_z=Me.union([Me.string(),Me.object({fromFile:Me.string(),json:Me.boolean().optional()})]),Pz=Me.object({name:ig,baseUrl:Me.string().optional().describe("Optional for mobile tests"),envFile:Me.string().optional().describe("path to a file on disk to read environment variables from. can be relative to project root or absolute."),envVariables:Me.record(Me.string(),_z).optional(),inheritFromShell:Me.boolean().optional().describe("inherit all environment variables from the shell - might be noisy"),browser:Fn.optional().describe("NB: most things should use project-level configuration only")}),Iz=Me.object({postSave:Me.string().optional()}),Oz=Me.object({name:ig,include:Me.string().array().optional().describe("list of glob patterns that match momentic files (optional)"),exclude:Me.string().array().optional().describe("opposite of include, takes precedence over include"),goldenFileDir:Me.string().optional(),reporterDir:Me.string().optional(),outputDir:Me.string().optional(),recordVideo:Me.boolean().optional(),retries:Me.number().optional().describe("number of retries per test"),parallel:Me.number().optional().describe("degree of parallelism"),environments:Me.array(Pz).optional(),gitMainBranch:Me.string().optional(),gitProtectedBranches:Me.string().array().optional(),ai:Ud.optional(),browser:Fn.optional(),emulator:_d.optional(),advanced:Fd.optional(),hooks:Iz.optional()});function nC(r,e){let t;try{t=wz(r,"utf-8")}catch(o){w.warn(`Could not read possible Momentic ${e} file at ${r}: ${o}`);return}let n;try{if(n=rC.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 cg(r){let e=nC(r,"project configuration");if(e!==void 0)try{return Oz.parse(e)}catch(t){w.warn(`Possible Momentic project configuration file at ${r} does not adhere to the required schema: ${t}`);return}}function Lz(r){let e=nC(r,"workspace configuration");if(e!==void 0)try{return Mz.parse(e)}catch(t){w.warn(`Possible Momentic workspace configuration file at ${r} does not adhere to the required schema: ${t}`);return}}function Nz(){let r=[],e=sg(),t=mo.parse(e).root,n=15,o=0;for(;o<n;){o++;let i=mo.basename(e);if(rl.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 Rz(e))if(a.endsWith(Ti)){let l=mo.join(e,a),c=cg(l);c&&r.push({configFilePath:l,config:c,rootDir:tC(l)})}if(r.length)return r;if(e=mo.dirname(e),e===t)break}return r}async function rs(r={}){let{configFilePath:e,nameFilter:t}=r,n=await kz(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:
4139
+ ${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]}async function Dz(r){let e=Lz(r);if(!e||!e.projects||!e.projects.length)return;let t=e.projects.map(a=>(a.endsWith("/")||(a+="/"),`${a}*${Ti}`)),n=AbortSignal.timeout(2e3),o;try{o=await xz(t,{absolute:!1,cwd:sg(),dotRelative:!1,maxDepth:ag,nodir:!0,signal:n})}catch(a){throw w.error({err:a},`Failed to list the available Momentic projects in the current directory. This usually indicates the 'include' or 'exclude' option in your ${lg} is misconfigured.`),a}let i=[];for(let a of o){let l=mo.join(sg(),a),c=cg(l);c&&i.push({configFilePath:l,config:c,rootDir:tC(l)})}return i}async function kz(r){if(r){r=mo.resolve(r);let t=cg(r);return t||(console.error(`No valid Momentic project file found at ${r}.`),process.exit(1)),[{config:t,configFilePath:r,rootDir:mo.dirname(r)}]}if(Az(lg)){let t=await Dz(lg);if(t)return t}return Nz()}function oC(r,e){let t=rC.stringify(r);Cz(e,t)}import{z as ug}from"zod";var iC="test-results";var $Ie=ug.object({width:ug.number(),height:ug.number()});import{execFile as Uz}from"node:child_process";import{promisify as Fz}from"node:util";import Bz from"simple-git";var Ie=Bz(),aC=Fz(Uz);async function zz(r){let e=await Oe(r,Ie.raw(["config","--list"])),t={};if(!e)return t;for(let n of e.split(`
4140
+ `)){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 Hz(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 aC("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 aC("gh",o,{timeout:5e3}),a=i?.toString().trim();if(a)return a}catch{}}}async function Gz(r,e,t){let n=e?.includes("github.com"),o=e?.includes("gitlab.com");try{if(n)return Hz(r,e,t);if(o)return}catch{}}function eu(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 Oe(r,e){try{return(await e).trim()}catch(t){r.error({err:t},"Failed to run git command");return}}function Vz(){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 jz(r){let[e,t,n]=await Promise.all([Oe(r,Ie.show(["--no-patch","--format=%ci"])),Oe(r,Ie.show(["-s","--pretty=%B"])),Oe(r,Ie.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{ciProvider:"GithubActions",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 Wz(r){let[e,t,n]=await Promise.all([Oe(r,Ie.listRemote(["--get-url","origin"])),Oe(r,Ie.show(["-s","--pretty=%B"])),Oe(r,Ie.show(["-s","--pretty=%an"]))]);return{ciProvider:"GitlabCI",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 $z(r){let[e,t,n,o]=await Promise.all([Oe(r,Ie.show(["--no-patch","--format=%ci"])),Oe(r,Ie.listRemote(["--get-url","origin"])),Oe(r,Ie.show(["-s","--pretty=%B"])),Oe(r,Ie.show(["-s","--pretty=%an"]))]),i=t?.includes("github.com"),a=t?.includes("gitlab.com"),l=t?eu(t):void 0;return{ciProvider:"CircleCI",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 qz(r){let[e,t,n]=await Promise.all([Oe(r,Ie.show(["--no-patch","--format=%ci"])),Oe(r,Ie.show(["-s","--pretty=%B"])),Oe(r,Ie.show(["-s","--pretty=%an"]))]),o=process.env.BUILDKITE_REPO,i=o?.includes("github.com"),a=o?.includes("gitlab.com"),l=o?eu(o):void 0;return{ciProvider:"Buildkite",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 Kz(r){let[e,t,n]=await Promise.all([Oe(r,Ie.show(["--no-patch","--format=%ci"])),Oe(r,Ie.show(["-s","--pretty=%B"])),Oe(r,Ie.show(["-s","--pretty=%an"]))]),o=process.env["Build.Repository.Uri"],i=o?.includes("github.com"),a=o?.includes("gitlab.com"),l=o?eu(o):void 0;return{ciProvider:"AzureDevOps",gitCommitSha:process.env["Build.SourceVersion"],gitCommitShaShort:process.env["Build.SourceVersion"]?.slice(0,6),gitCommitTimestamp:e?new Date(e):void 0,gitBranchName:process.env["System.PullRequest.SourceBranch"]??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 Yz(r,e){let[t,n,o,i,a,l,c,s,u]=await Promise.all([Oe(r,Ie.revparse(["HEAD"])),Oe(r,Ie.revparse(["--short","HEAD"])),Oe(r,Ie.revparse(["--abbrev-ref","HEAD"])),Oe(r,Ie.listRemote(["--get-url","origin"])),Oe(r,Ie.show(["--no-patch","--format=%ci"])),Oe(r,Ie.show(["-s","--pretty=%B"])),Oe(r,Ie.show(["-s","--pretty=%an"])),e?Oe(r,Ie.raw(["merge-base","--fork-point",e])):Promise.resolve(void 0),zz(r)]),d=s?await Oe(r,Ie.show(["--no-patch","--format=%ci",s])):void 0,p=i?.includes("github.com"),m=i?.includes("gitlab.com"),g=i?eu(i):void 0,h=u["user.email"]||void 0,f=u["user.name"]||void 0,E=u["user.username"]||void 0,b=await Gz(r,i,u)??E??void 0;return{ciProvider:"none",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 Xz(){let r=process.env._HEAD_REPO_URL;return{ciProvider:"GCPCloudBuild",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 Jz(r){let e=r.config.gitProtectedBranches??[];return r.config.gitMainBranch&&e.push(r.config.gitMainBranch),{gitMainBranch:r.config.gitMainBranch,gitProtectedBranches:e}}async function ns(r,e){let t=Vz();if(!t)return Yz(r,e);switch(t){case"GithubActions":return jz(r);case"GitlabCI":return Wz(r);case"CircleCI":return $z(r);case"Buildkite":return qz(r);case"AzureDevOps":return Kz(r);case"GCPCloudBuild":return Xz()}}async function Zz(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 Qz(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 e1(r,e,t){try{if(t.githubRepository){let[n,o]=t.githubRepository.split("/");return await Qz(r,e,n,o,t)}else if(t.gitlabProjectPath)return await Zz(r,e,t.gitlabProjectPath,t)}catch(n){r.warn({err:n},"Failed to get remote git metadata")}return t}async function vi(r,e,t){let n=await Jz(t),o=await ns(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 e1(r,e,i);return{...n,...o,...a}}import{diff as sC}from"deep-object-diff";import go from"fs";import{cloneDeep as t1}from"lodash-es";import dg from"path";import{v4 as mOe}from"uuid";import tu from"yaml";function lC({content:r,schemaVersion:e,momenticFiles:t,project:n,forceSaveOnNoDiffs:o}){let i=t.mobileModules[r.moduleId]?.fullFilePath;if(!i||!go.existsSync(i))throw new Error(`Tried to update mobile module ${r.moduleId} that could not be found on disk`);let a=go.readFileSync(i,"utf-8"),l=tu.parse(a),c={...l,...r,schemaVersion:e},s=eo({fileType:Pe.MOBILE_MODULE,...sa.parse(c),steps:hr.array().parse(r.steps)}),u=sC(s,l);if(u&&Object.keys(u).length===0&&!o)return;let d=tu.stringify(s);go.writeFileSync(i,d,"utf-8"),po(i,n.config)}function cC({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=os(i,o),l={...a,...e},c=eo({fileType:Pe.MOBILE_MODULE,...Xs.parse(l)}),s=sC(c,a);if(s&&Object.keys(s).length===0)return;let u=tu.stringify(c);go.writeFileSync(i,u,"utf-8");let d;if(e.name){let p=`${on(e.name)}.module.yaml`;if(d=dg.join(dg.dirname(i),p),go.existsSync(d))throw new Error(`A conflicting file already exists at the following path: ${d}`);go.renameSync(i,d)}po(d||i,n.config)}function os(r,e){let t=go.readFileSync(r,"utf-8"),n=tu.parse(t);try{return{...Xs.parse(n),name:dg.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 pg(r,e,t,n){let o=os(r.fullFilePath,t),{resolvedSteps:i}=await fc({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 os(c,t)},logger:t,metadata:{id:o.moduleId,schemaVersion:o.schemaVersion}}),a={...o,name:r.name,steps:i};return n&&(n[r.id]=t1(a)),a}async function uC(r,e){let t={};return await Promise.all(Object.values(r.mobileModules).map(async n=>{await pg(n,r,e,t)})),Array.from(Object.values(t))}import{randomUUID as r1}from"crypto";import ho from"fs";import mg from"path";import ru from"yaml";function dC({name:r,description:e="",steps:t=[],settings:n={},folder:o}){let a=`${on(r)}.test.yaml`,l=mg.join(o,a);if(ho.existsSync(l))throw new Error(`A test named '${r}' already exists at path '${l}'. Choose a different name.`);let c={fileType:Pe.MOBILE_TEST,id:r1(),description:e,schemaVersion:Ju,settings:n,steps:t},s=ru.stringify(c);return ho.writeFileSync(l,s,"utf-8"),{fullPath:l,testId:c.id}}function n1(r){if(!ho.existsSync(r))throw new Error(`Test file not found: ${r}`);let e=ho.readFileSync(r,"utf-8").replace(/\r\n|\r/g,`
4141
+ `),t=ru.parse(e),n=Zs.parse(t);if(n.fileType!==Pe.MOBILE_TEST)throw new Error(`File is not a mobile test (fileType=${n.fileType}): ${r}`);return n}async function nu(r,e,t){let n=n1(r),o;try{o=Rr.parse(n)}catch(l){throw new Error(`Mobile test ${r} is missing metadata or has invalid metadata: ${l}`)}let{resolvedStepLists:i}=await zv({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 os(c,e)}});return{...o,steps:i.steps}}async function pC({filePath:r,steps:e,settings:t,folder:n,project:o,momenticFiles:i}){let a=mg.isAbsolute(r)?r:mg.join(n,r);if(!ho.existsSync(a))throw new Error(`Test file not found: ${a}`);let l=ho.readFileSync(a,"utf-8").replace(/\r\n|\r/g,`
4142
+ `),c=ru.parse(l),s=Zs.parse(c);if(s.fileType!==Pe.MOBILE_TEST)throw new Error(`File at '${a}' is not a mobile test (fileType=${s.fileType}).`);let u;e&&(u=await no({steps:e}));let d={...s,...u?.stepsToSave!==void 0?{steps:u.stepsToSave}:{},...t!==void 0?{settings:t}:{}},p=ru.stringify(Zs.parse(d));for(let m of u?.moduleUpdates??[])lC({content:m,schemaVersion:Ju,momenticFiles:i,project:o});ho.writeFileSync(a,p,"utf-8"),po(a,o.config)}import{randomUUID as o1}from"crypto";import Mn from"fs";import Ai from"path";var mC=new Set([".DS_Store","__MACOSX"]),gC={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 i1(r,e,t){if(gC[t]){let i=gC[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 gg=class extends Error{constructor(e,t){let n=`${e} contains invalid Momentic results: ${t}. Please ensure that the path points to a folder containing only valid results. If you passed \`--output-dir test-results/results-1\` to the \`run\` command, your results path for merging should be \`test-results\`.`;super(n),this.name="InvalidMomenticResultsPathError"}};function hC(r,e){try{let t=Ai.join(e,"metadata.json");return dl.parse(JSON.parse(Mn.readFileSync(t,"utf-8")))}catch{throw new gg(r,e)}}function fC(r,e,t){let n=o1(),o=r.child({runGroupId:n});Mn.rmSync(e,{recursive:!0,force:!0});let i=Mn.readdirSync(t).filter(c=>!mC.has(c)).map(c=>Ai.join(t,c));if(i.length===0)throw new Error(`No run groups found in results path: ${t}`);Mn.mkdirSync(e,{recursive:!0});let a={...hC(t,i[0]),id:n};for(let c of i){let s=Ai.join(c,"runs");if(!Mn.existsSync(s))continue;let u=hC(t,c);o.info({oldRunGroupId:u.id},"Merging run groups");for(let p in u){if(p==="id")continue;let m=p;a[m]=i1(a,u,m)}let d=Mn.readdirSync(s);for(let p of d){if(mC.has(p))continue;let m=Ai.join(s,p),g=Ai.join(e,"runs",p);Mn.cpSync(m,g,{recursive:!0})}}let l=Ai.join(e,"metadata.json");Mn.writeFileSync(l,JSON.stringify(a,null,2))}import yC from"adm-zip";import Eg from"fs";import{z as p1}from"zod";var U="v1",hg="mobile-cli",fo="0.4.1";var a1=9e4,s1=3,l1=1500,c1=15e3,Er=class extends Error{status;rawError;constructor(e,t,n,o={}){super(n,o),this.status=e,this.rawError=t}};async function u1(r){return r.text().then(e=>{try{return JSON.parse(e).error}catch{return e}})}var fg=class{baseUrl;logger;constructor(e){this.baseUrl=e.baseUrl,this.logger=e.logger}getHeaders(){let e={"Content-Type":"application/json"};return fo&&(e[ll]=fo),hg&&(e[ty]=hg),e}async sendRequest(e,t){let{retries:n=s1,requestTimeoutMs:o=a1,initialRetryDelayMs:i=l1,maxRetryDelayMs:a=c1,onFailedRequest:l}=t,c=n,s=n,u,d={path:e,baseUrl:this.baseUrl,method:t.method};for(;c>0;)try{return c--,await this.sendSingleRequestHelper(e,t,o)}catch(p){u=p;try{l?.(u)}catch{}if(p instanceof Er&&p.status>=400&&p.status<500)throw p;if(p instanceof Error&&p.name==="AbortError"&&(u=new hn),c===0)throw u;let m=s-c,g=Math.min(i*Math.pow(2,m-1),a);await new Promise(h=>setTimeout(h,g))}throw this.logger.warn({...d,err:u},"Got fatal error response from Momentic server"),u}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,{once:!0});let c=Date.now(),s={...this.getHeaders(),...t.extraHeaders};try{let u=await fetch(`${this.baseUrl}${e}`,{method:t.method,body:t.body?JSON.stringify(t.body):void 0,headers:s,signal:i.signal});if(!u.ok){let p=await u1(u);throw new Er(u.status,p,`Request to ${t.method} ${e} failed with status ${u.status}: ${p}`)}let d;if(u.status===204)d={};else{let p=await u.text();try{d=JSON.parse(p)}catch{d=p}}return this.logger&&t.logResponse===!0&&d&&this.logger.debug({result:d,status:u.status,durationMs:Date.now()-c,...o},"Got response from Momentic server"),d}finally{clearTimeout(a),t.signal&&t.signal.removeEventListener("abort",l)}}},zr=class extends fg{apiKey;mode;constructor(e){super(e),this.apiKey=e.apiKey,this.mode=e.mode}getHeaders(){return{...super.getHeaders(),Authorization:`Bearer ${this.apiKey}`,[ey]:this.mode??""}}};import{createAnthropic as d1}from"@ai-sdk/anthropic";var ou=({baseUrl:r,apiKey:e,sessionId:t,extraHeaders:n,loggerTags:o})=>i=>{let a={Authorization:`Bearer ${e}`,[ll]:fo??"",...t&&{[ny]:t},...n||{}};return o&&(a[ry]=JSON.stringify(o)),d1({baseURL:`${r}/v1/llm/anthropic/${i}`,headers:a,apiKey:e})(i)};var So=class extends zr{agentConfig;constructor(e,t){let n={...rS,...e};super(t),this.agentConfig=n}getAgentConfig(){return this.agentConfig}async rankChunksWithAi(e,t){let n={...e,loggerTags:t.loggerTags},o=await this.sendRequest(`/${U}/web-agent/recommend-chunks-ai`,{method:"POST",body:n,signal:t.abortSignal});return Vf.parse(o)}async rankChunksWithRag(e,t){let n=await this.sendRequest(`/${U}/web-agent/recommend-chunks`,{method:"POST",body:{cliVersion:fo,...e},signal:t.abortSignal});return Gf.parse(n)}async getScreenshotFromS3(e){let t=await this.sendRequest(`/${U}/s3/visual-diff-screenshot`,{method:"POST",body:{url:e}});return p1.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(`/${U}/web-agent/locate-element`,{method:"POST",body:n,signal:t.abortSignal});return sy.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(`/${U}/web-agent/assertion`,{method:"POST",body:n,signal:t.abortSignal});return zd.parse(o)}async getLintStepResult(e,t){let n={...e,disableCache:!!t.disableCache,loggerTags:t.loggerTags},o=await this.sendRequest(`/${U}/web-agent/lint/step`,{method:"POST",body:n,signal:t.abortSignal});return ay.parse(o)}async getLintMcpCopilotMessageResult(e,t){let n={message:e.message,disableCache:!!t.disableCache,loggerTags:t.loggerTags},o=await this.sendRequest(`/${U}/web-agent/lint/mcp-copilot`,{method:"POST",body:n,signal:t.abortSignal});return iy.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(`/${U}/web-agent/visual-assertion`,{method:"POST",body:n,signal:t.abortSignal});return zd.parse(o)}async getAiActionCommand(e,t){let n=await this.sendRequest(`/${U}/web-agent/next-command-dynamic`,{method:"POST",body:{...e,disableCache:t.disableCache,loggerTags:t.loggerTags},signal:t.abortSignal});return oy.parse(n)}async getMultiturnAiActionCommand(e,t){return await this.sendRequest(`/${U}/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(`/${U}/web-agent/ai-action/evaluate`,{method:"POST",body:{...e,disableCache:t.disableCache,loggerTags:t.loggerTags},signal:t.abortSignal});return td.parse(n)}async getReverseMappedDescription(e,t){let n=await this.sendRequest(`/${U}/web-agent/reverse-mapped-description`,{method:"POST",body:{...e,disableCache:t.disableCache,loggerTags:t.loggerTags},signal:t.abortSignal});return ly.parse(n)}async getTextExtraction(e,t){let n={...e,disableCache:t.disableCache,loggerTags:t.loggerTags,agentConfigVersion:this.agentConfig?.["text-extraction"]},o=await this.sendRequest(`/${U}/web-agent/text-extraction`,{method:"POST",body:n,signal:t.abortSignal});return Qu.parse(o)}async getPageSummary(e,t){let n={...e,disableCache:t.disableCache,loggerTags:t.loggerTags},o=await this.sendRequest(`/${U}/web-agent/page-summary`,{method:"POST",body:n,signal:t.abortSignal});return Ef.parse(o)}async getSmartWaitingDecision(e,t){let n={...e,disableCache:t.disableCache,loggerTags:t.loggerTags},o=await this.sendRequest(`/${U}/web-agent/smart-waiting`,{method:"POST",body:n,signal:t.abortSignal});return Tf.parse(o)}async getTestResultClassification(e,t){let n=await this.sendRequest(`/${U}/web-agent/result-classification`,{method:"POST",body:{...e,loggerTags:t.loggerTags},signal:t.abortSignal});return zu.parse(n)}async getExtractedKeywords(e,t){let n=await this.sendRequest(`/${U}/web-agent/extract-keywords`,{method:"POST",body:e,signal:t.abortSignal});return tS.parse(n)}async getAutohealingProposal(e,t){let n=await this.sendRequest(`/${U}/web-agent/autoheal-section`,{method:"POST",body:{...e,loggerTags:t.loggerTags},signal:t.abortSignal});return hf.parse(n)}async getFailureRecoveryProposal(e,t){let n=await this.sendRequest(`/${U}/web-agent/failure-recovery`,{method:"POST",body:{...e,loggerTags:t.loggerTags},signal:t.abortSignal});return yf.parse(n)}async getFailureRecoveryPlan(e,t){let n=await this.sendRequest(`/${U}/web-agent/failure-recovery-plan`,{method:"POST",body:{...e,loggerTags:t.loggerTags},signal:t.abortSignal});return Sf.parse(n)}async getIframeRegex(e,t){let n=await this.sendRequest(`/${U}/web-agent/iframe-regex`,{method:"POST",body:e,signal:t.abortSignal});return Xg.parse(n)}getVercelAnthropicModelFactory({loggerTags:e}){return ou({baseUrl:this.baseUrl,apiKey:this.apiKey,loggerTags:e})}};import{z as Sg}from"zod";var Tr=class extends zr{constructor(e){super({...e,mode:void 0})}getAppUrl(){return this.baseUrl==="http://localhost:8000"?"http://localhost:3000":this.baseUrl.replace(/\/\/api/,"//app")}async getAuthInfo(){let e=await this.sendRequest(`/${U}/auth/check`,{method:"GET",retries:10,requestTimeoutMs:5e3,onFailedRequest:t=>{w.warn(`API key check failed: ${t.message}`)}});return Ty.parse(e)}async bulkGetRunStatus(e){let t=await this.sendRequest(`/${U}/runs/status`,{method:"POST",body:e,retries:3,requestTimeoutMs:1e4});return Sy.parse(t)}async getTestYAMLExport(e){let t=await this.sendRequest(`/${U}/tests/export`,{method:"POST",body:e,retries:3,requestTimeoutMs:3e4});return uy.parse(t)}async updateStepCaches(e,t){await this.sendRequest(`/${U}/cache`,{method:"PATCH",body:e,extraHeaders:t,retries:3,requestTimeoutMs:1e4,initialRetryDelayMs:3e3})}async getStepCacheForTest(e,t){let n=await this.sendRequest(`/${U}/cache`,{method:"POST",body:e,extraHeaders:t,retries:10,requestTimeoutMs:3e4,initialRetryDelayMs:3e3});return py.parse(n)}async updateMobileStepCaches(e,t){await this.sendRequest(`/${U}/mobile-cache`,{method:"PATCH",body:e,extraHeaders:t,retries:3,requestTimeoutMs:1e4,initialRetryDelayMs:3e3})}async getMobileStepCacheForTest(e,t){let n=await this.sendRequest(`/${U}/mobile-cache`,{method:"POST",body:e,extraHeaders:t,retries:10,requestTimeoutMs:3e4,initialRetryDelayMs:3e3});return my.parse(n)}async queueTests(e){let t=await this.sendRequest(`/${U}/tests/queue`,{method:"POST",body:e,retries:3,requestTimeoutMs:1e4});return cy.parse(t)}async uploadScreenshot(e){let t=await this.sendRequest(`/${U}/screenshots`,{method:"POST",body:e,retries:3,requestTimeoutMs:5e3});return Ey.parse(t)}async getAllEnvironments(){let e=await this.sendRequest(`/${U}/environments`,{method:"GET",retries:3,requestTimeoutMs:5e3});return vy.parse(e)}async acquireCacheLock(e,t){let n=await this.sendRequest(`/${U}/result-cache/lock`,{method:"POST",body:e,signal:t,retries:3,requestTimeoutMs:3e4});return Uy.parse(n)}async releaseCacheLock(e){await this.sendRequest(`/${U}/result-cache/lock`,{method:"DELETE",body:{key:e},retries:3,requestTimeoutMs:5e3})}async deleteCacheResult(e){await this.sendRequest(`/${U}/result-cache/entry`,{method:"DELETE",body:e,retries:3,requestTimeoutMs:5e3})}async setCacheResult(e){await this.sendRequest(`/${U}/result-cache/entry`,{method:"PATCH",body:e,retries:3,requestTimeoutMs:5e3})}async getCacheResult(e){try{return await this.sendRequest(`/${U}/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(`/${U}/suites/queue`,{method:"POST",body:e,retries:3,requestTimeoutMs:5e3});return Ay.parse(t)}async bulkGetRunGroupStatus(e){let t={runGroupIds:e},n=await this.sendRequest(`/${U}/run-groups/status`,{method:"POST",body:t,retries:3,requestTimeoutMs:5e3});return Ff.array().parse(n)}async uploadProposedSteps(e,t){try{await this.sendRequest(`/${U}/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(`/${U}/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(`/${U}/test-fragments/${e}`,{method:"GET",retries:3,requestTimeoutMs:1e4});return wy.parse(t)}async patchTestFragment(e,t){await this.sendRequest(`/${U}/test-fragments/${e}`,{method:"PATCH",body:t,retries:3,requestTimeoutMs:1e4})}async getPastTestResults(e,t){let n=await this.sendRequest(`/${U}/results/tests/${e}`,{method:"POST",body:t,retries:3,requestTimeoutMs:1e4});return Ry.parse(n)}async generateTestResultsUploadUrl(){let e=await this.sendRequest(`/${U}/results/uploads`,{method:"POST",retries:3,requestTimeoutMs:1e4});return Cy.parse(e)}async startProcessingResultsUpload(e,t){let n=await this.sendRequest(`/${U}/results/uploads/${e}/process`,{method:"POST",body:t,retries:3,requestTimeoutMs:1e4});return xy.parse(n)}async fetchIconKnowledgeBase(e){try{let t=await this.sendRequest(`/${U}/knowledge-base/icons`,{method:"GET",retries:3,requestTimeoutMs:5e3});return zy.parse(t)}catch(t){return e.error({err:t},"Failed to fetch icon knowledge base"),null}}async saveNewIcons(e,t){try{await this.sendRequest(`/${U}/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(`/${U}/git/github/${e}/${t}/merge-base-commit?${i.toString()}`,{method:"GET",retries:3,requestTimeoutMs:1e4});return ha.parse(a)}async getCommitFromGithub(e,t,n){let o=await this.sendRequest(`/${U}/git/github/${e}/${t}/commits/${n}`,{method:"GET",retries:3,requestTimeoutMs:1e4});return ha.parse(o)}async getMergedBranchFromGithub(e,t,n,o){let i=encodeURIComponent(n),a=await this.sendRequest(`/${U}/git/github/${e}/${t}/${i}/${o}/merged-branch`,{method:"GET",retries:3,requestTimeoutMs:1e4});return jd.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(`/${U}/git/gitlab/${i}/merge-base-commit?${o.toString()}`,{method:"GET",retries:3,requestTimeoutMs:5e3});return ha.parse(a)}async getCommitFromGitlab(e,t){let n=encodeURIComponent(e),o=await this.sendRequest(`/${U}/git/gitlab/${n}/commits/${t}`,{method:"GET",retries:3,requestTimeoutMs:1e4});return ha.parse(o)}async getMergedBranchFromGitlab(e,t,n){let o=encodeURIComponent(t),i=encodeURIComponent(e),a=await this.sendRequest(`/${U}/git/gitlab/${i}/${o}/${n}/merged-branch`,{method:"GET",retries:3,requestTimeoutMs:1e4});return jd.parse(a)}async getAgentConfig(){let e=await this.sendRequest(`/${U}/web-agent/agent-config`,{method:"GET",retries:3,requestTimeoutMs:5e3});return Sg.record(Sg.string(),Sg.string()).parse(e)}async getQuarantinedTests(){let e=await this.sendRequest(`/${U}/quarantine`,{method:"GET"});return My.parse(e)}async quarantineTest(e,t,n){await this.sendRequest(`/${U}/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(`/${U}/quarantine/${e.id}`,{method:"DELETE",body:{testName:e.name,reason:t,...n??{}},retries:3,requestTimeoutMs:1e4})}async createAndroidEmulator(e){let t=await this.sendRequest(`/${U}/limbar/android`,{method:"POST",retries:3,body:e,requestTimeoutMs:9e4,initialRetryDelayMs:5e3,maxRetryDelayMs:15e3});return _y.parse(t)}async extendAndroidEmulatorTtl(e){try{await this.sendRequest(`/${U}/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(`/${U}/limbar/android/upload-url`,{method:"POST",retries:3,body:o,requestTimeoutMs:15e3,logResponse:!0});return Py.parse(i)}async deleteAndroidEmulator(e){await this.sendRequest(`/${U}/limbar/android/${e}`,{method:"DELETE",retries:3,requestTimeoutMs:3e4})}async getAndroidAssets(){let e=await this.sendRequest(`/${U}/limbar/assets`,{method:"GET",retries:3,requestTimeoutMs:1e4});return Iy.parse(e)}async deleteAndroidAsset(e,t){await this.sendRequest(`/${U}/limbar/assets/${e}/${t}`,{method:"DELETE",retries:3,requestTimeoutMs:1e4})}};async function yg(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 iu=class{apiClient;constructor(e){this.apiClient=e}async reportBillableEvents(e,t){await this.apiClient.reportBillableEvents(e,t)}};var wi=class extends zr{generator;constructor(e,t){super(e),this.generator=t}async runTemplateMatching(e,t={}){let n=await this.sendRequest(`/${U}/web-agent/template-matching`,{method:"POST",body:e,signal:t?.signal});return Jg.parse(n)}async constructIframeRegex(e,t={}){return this.generator.getIframeRegex(e,{abortSignal:t.signal})}};var Ri=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 m1,en as g1}from"@faker-js/faker";var Ci="v1",xi=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 m1({locale:g1}),this.fakerInstance.seed(e.fakerSeed))}async sendAiGenerate(e){let t=typeof e=="string"?{input:e}:e;return this.httpClient.sendRequest(`/${Ci}/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(`/${Ci}/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(`/${Ci}/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(`/${Ci}/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(`/${Ci}/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(`/${Ci}/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}`)})}};function SC(r,e,t){return fetch(r,{method:"PUT",body:t,headers:{"Content-Type":e}})}var au=class{constructor(e){this.client=e}async uploadResultsArchive(e,t){let{uploadUrl:n,id:o}=await this.client.generateTestResultsUploadUrl(),i=await SC(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 Mi=class extends zr{constructor(e){super(e)}async getElementLocation(e,t){let n={...e,loggerTags:t.loggerTags},o=await this.sendRequest(`/${U}/mobile-agent/locate-element`,{method:"POST",body:n,signal:t.abortSignal});return oS.parse(o)}async evaluateAssertion(e,t){let n={...e,loggerTags:t.loggerTags},o=await this.sendRequest(`/${U}/mobile-agent/assertion`,{method:"POST",body:n,signal:t.abortSignal});return sS.parse(o)}getVercelAnthropicModelFactory({loggerTags:e,sessionId:t}){return ou({baseUrl:this.baseUrl,apiKey:this.apiKey,sessionId:t,loggerTags:e})}};function su({orgId:r,client:e,gitMetadata:t,regenerateCache:n,alwaysSaveCache:o,noCache:i}){return i?new ul:new bg(r,e,t,o)}var bg=class{constructor(e,t,n,o){this.orgId=e;this.client=t;let{gitBranchName:i,gitProtectedBranches:a}=n;this.cacheHeaders=Hd(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.info("Skipping mobile cache last used at update because branch is protected");return}for(let i of[t])i&&nm({steps:i,stepCacheEntries:n,logger:e.logger});let{cachesToSave:o}=await no({steps:t,cacheCreationParams:{testId:e.testId,orgId:this.orgId}});this.client.updateMobileStepCaches({entries:o,testId:e.testId},this.cacheHeaders)}};import lu from"path";function h1(r){let e=new yC,t=lu.join(r,"metadata.json"),n=dl.parse(JSON.parse(Eg.readFileSync(t,"utf-8")));e.addLocalFile(t);for(let o of Eg.readdirSync(lu.join(r,"runs"))){if(!o.endsWith(".zip"))continue;let i=o.replace(/\.zip$/,""),a=new yC(lu.join(r,"runs",o));for(let l of a.getEntries())l.isDirectory||e.addFile(lu.join("runs",i,l.entryName),l.getData())}return{runGroupId:n.id,buffer:e.toBuffer()}}async function cu(r){let{client:e,consoleLogger:t,resultsPath:n}=r;if(!Eg.existsSync(n)){t.warn("Results path does not exist, skipping upload.");return}let o=new au(e);try{let{runGroupId:i,buffer:a}=h1(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 f1 from"adm-zip";import ht from"fs";import Vt from"path";var is=class r{constructor(e){this.filePath=e;ht.rmSync(this.filePath,{recursive:!0,force:!0}),ht.mkdirSync(this.filePath,{recursive:!0})}cd(e){return new r(Vt.join(this.filePath,e))}cwd(){return this.filePath}mkdir(e){ht.mkdirSync(Vt.join(this.filePath,e),{recursive:!0})}readFile(e){let t=Vt.join(this.filePath,e);if(ht.existsSync(t))return ht.readFileSync(t)}storeFile(e){let{name:t,contents:n}=e,o=Vt.join(this.filePath,t);try{ht.writeFileSync(o,n)}catch{}}createFileStream(e){let t=Vt.join(this.filePath,e);return ht.createWriteStream(t)}createRunArchive(e){return new Tg(Vt.join(this.filePath,"runs"),e)}},Tg=class{constructor(e,t){this.filePath=e;this.tempPath=Vt.join(e,`.${t}`),this.finalPath=Vt.join(e,`${t}.zip`),ht.rmSync(this.tempPath,{recursive:!0,force:!0}),ht.rmSync(this.finalPath,{recursive:!0,force:!0}),ht.mkdirSync(this.tempPath,{recursive:!0})}tempPath;finalPath;readFile(e){let t=Vt.join(this.tempPath,e);if(ht.existsSync(t))return ht.readFileSync(t)}mkdir(e){ht.mkdirSync(Vt.join(this.tempPath,e),{recursive:!0})}cd(e){return new is(Vt.join(this.tempPath,e))}cwd(){return this.tempPath}storeFile(e){let{name:t,contents:n}=e,o=Vt.join(this.tempPath,t);ht.writeFileSync(o,n)}createFileStream(e){let t=Vt.join(this.tempPath,e);return ht.createWriteStream(t)}close(){let e=new f1;e.addLocalFolder(this.tempPath,void 0,n=>n!==".DS_Store");let t=e.toBuffer();ht.writeFileSync(this.finalPath,t),ht.rmSync(this.tempPath,{recursive:!0,force:!0})}};import yu from"fs";import OC from"body-parser";import k1 from"cors";import U1 from"dedent";import{Router as E1}from"express";import Lt from"fs";import{globSync as T1}from"glob";import ut from"path";import uu from"fs";import S1 from"path";var y1=new Rc(30,60*1e3),Rg="https://api.momentic.ai",Ag,EC=r=>{Rg=r},Cg=()=>Rg,as=()=>Ag;var _i,wg,bC,TC=async r=>{if(Ag&&_i&&bC)return _i;let e=new Tr({baseUrl:Rg,apiKey:r,logger:w});Ag=e;try{let t=await e.getAuthInfo();return _i=t.orgId,wg=t.userId,bC=r,_i}catch(t){throw new Error(`Error checking API key against server: ${t}`)}},Pi=()=>{if(!_i)throw new Error("Your organization ID is invalid.");return _i},du=()=>{if(!wg)throw new Error("Your user ID is invalid.");return wg};var xg,vg,vC=(r,e)=>{xg=r,vg?.abort(),vg=new AbortController;let t=vg.signal,n=[r.configFilePath];r.config.environments?.forEach(o=>{if(!o.envFile)return;let i=S1.resolve(r.rootDir,o.envFile);try{if(uu.lstatSync(i).isSymbolicLink())return;uu.existsSync(i)&&n.push(i)}catch(a){w.warn({err:a},`Failed to check if env file ${i} exists`)}});try{b1({filesToWatch:n,revalidator:e,signal:t,project:r})}catch(o){w.error({err:o},"Failed to start config file watchers")}},tt=()=>xg;function b1({filesToWatch:r,revalidator:e,signal:t,project:n}){w.debug("Starting watch on the following files:"),r.forEach(o=>{w.debug(`- ${o}`)}),r.forEach(o=>{let i=async(l,c)=>{l.mtime.getTime()!==c.mtime.getTime()&&(y1.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.`),xg=await Promise.resolve(e(n.configFilePath)))};uu.watchFile(o,{persistent:!1},i);let a=()=>{uu.unwatchFile(o,i),t.removeEventListener("abort",a)};t.addEventListener("abort",a),process.once("SIGUSR2",()=>{a(),process.kill(process.pid,"SIGUSR2")})})}function at(r){return function(...e){let t=e[e.length-1],n=r(...e);Promise.resolve(n).catch(t)}}var ls=E1();function ss(r){let e=tt(),t=ut.dirname(e.configFilePath);return ut.join(t,...r)}function v1(r){let e=tt(),t=ut.dirname(e.configFilePath),n=ut.relative(t,r);return n?n.split(ut.sep):[]}function A1(r,e){let t=Lt.statSync(r),n=v1(r);return Nd.parse({name:e,absolutePath:r,relativePath:n.join(ut.sep),pathSegments:n,isDirectory:t.isDirectory(),size:t.size,createdAt:t.birthtime,modifiedAt:t.mtime,accessedAt:t.atime})}ls.post("/",at(async(r,e,t)=>{let n;try{n=HS.parse(r.body).pathSegments}catch(d){e.status(400).json({error:`Failed to parse folder read body: ${d}`});return}let o=ss(n);if(!Lt.existsSync(o)){e.status(404).json({error:`Path not found: ${n.join(ut.sep)}`});return}if(!Lt.statSync(o).isDirectory()){e.status(400).json({error:`Path is not a directory: ${n.join(ut.sep)}`});return}let a=tt(),l=Array.from(a.config.exclude??[]).concat(nl),s=T1("*",{absolute:!1,cwd:o,ignore:l,dotRelative:!1,maxDepth:1,nodir:!1}).map(d=>{let p=ut.join(o,d);return A1(p,d)}),u={absolutePath:o,pathSegments:n,contents:s};e.status(200).json(u)}));ls.put("/",at(async(r,e,t)=>{let n;try{n=GS.parse(r.body).pathSegments}catch(a){e.status(400).json({error:`Failed to parse folder create body: ${a}`});return}let o=ss(n);if(Lt.existsSync(o)){e.status(200).json({success:!0,message:`Folder already exists: ${n.join(ut.sep)}`,pathSegments:n});return}Lt.mkdirSync(o,{recursive:!0});let i={success:!0,message:`Folder created: ${n.join(ut.sep)}`,pathSegments:n};e.status(201).json(i)}));ls.patch("/",at(async(r,e,t)=>{let n,o;try{let s=VS.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=ss(n),a=ss(o);if(!Lt.existsSync(i)){e.status(400).json({error:`Folder not found: ${n.join(ut.sep)}`});return}if(Lt.existsSync(a)){e.status(400).json({error:`Destination already exists: ${o.join(ut.sep)}`});return}let l=ut.dirname(a);Lt.existsSync(l)||Lt.mkdirSync(l,{recursive:!0}),Lt.renameSync(i,a);let c={success:!0,message:`Folder moved from ${n.join(ut.sep)} to ${o.join(ut.sep)}`,pathSegments:o};e.status(200).json(c)}));ls.delete("/",at(async(r,e,t)=>{let n,o=!0;try{let c=jS.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=ss(n);if(!Lt.existsSync(i)){e.status(200).json({success:!0,message:`Folder not found: ${n.join(ut.sep)}`,pathSegments:n});return}if(!Lt.statSync(i).isDirectory()){e.status(400).json({error:`Path is not a directory: ${n.join(ut.sep)}`});return}if(o)Lt.rmSync(i,{recursive:!0,force:!0});else{if(Lt.readdirSync(i).length>0){e.status(409).json({error:`Cannot delete non-empty directory without recursive flag: ${n.join("/")}`});return}Lt.rmdirSync(i)}let l={success:!0,message:`Folder deleted: ${n.join("/")}`,pathSegments:n};e.status(200).json(l)}));var Mg=ls;import{Router as C1}from"express";import{hostname as w1}from"os";var R1="0.4.1",cs=Vo({app:"desktop-server",hostname:w1(),disableConsoleLogs:!0}).child({cliVersion:R1});(async()=>{try{let r=await ns(cs);r.gitBranchName&&cs.addBinding("branch",r.gitBranchName)}catch{}})();var AC=C1();AC.get("/",async(r,e)=>{let t=tt(),n=as();if(!n){e.status(500).json({message:"API client not initialized"});return}let o=await vi(cs,n,t);e.status(200).json(o)});var _g=AC;import F1 from"events";import LC,{Router as B1}from"express";import z1 from"http";import H1 from"path";var pu=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 wC=new pu;import{Router as M1}from"express";import{existsSync as _1}from"fs";import P1 from"path";import{hostname as x1}from"os";var Pg="0.4.1",Nt=Vo({app:"mobile-desktop-server",hostname:x1(),disableConsoleLogs:!0}).child({cliVersion:Pg});(async()=>{try{let r=await ns(Nt);r.gitBranchName&&Nt.addBinding("branch",r.gitBranchName)}catch{}})();var Ig=M1();Ig.get("/",at(async(r,e)=>{let t=as();if(!t){e.status(500).json({message:"API client not initialized"});return}let n=await t.getAndroidAssets();e.status(200).json(n)}));Ig.post("/upload-url",at(async(r,e)=>{let t;try{t=XS.parse(r.body)}catch(i){e.status(400).json({error:`Invalid request body: ${i}`});return}let n=as();if(!n){e.status(500).json({error:"API client not initialized"});return}let o=P1.resolve(t.filePath);if(!_1(o)){e.status(400).json({error:`File not found: ${o}`});return}await uc({tag:t.tag,channel:t.channel,filePath:o,apiClient:n,logger:Nt}),e.sendStatus(204)}));var RC=Ig;import{Router as I1}from"express";var CC=I1();CC.get("/",at(async(r,e)=>{let t=tt(),n=await br(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 xC=CC;import{Router as O1}from"express";var MC=O1();MC.get("/",(r,e)=>{e.status(200).json({userId:du(),orgId:Pi(),cliVersion:Pg??"0.0.0"})});var _C=MC;import{Router as L1}from"express";var mu=L1();async function N1(r){return(await uC(r,Nt)).map(n=>{let o=r.mobileModules[n.moduleId];if(!o){w.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)}mu.get("/",at(async(r,e)=>{let t=tt(),n=await br(t),o=await N1(n);e.status(200).json(o)}));mu.get("/:moduleId",at(async(r,e)=>{if(!r.params.moduleId){e.status(400).json({error:"Missing moduleId in url path."});return}let t=await br(tt()),n=t.mobileModules[r.params.moduleId];if(!n){e.status(404).json({error:"Mobile module not found."});return}try{let o=await pg(n,t,w);e.json(o)}catch(o){e.status(400).json({err:o})}}));mu.patch("/:moduleId/metadata",at(async(r,e)=>{if(!r.params.moduleId){e.status(400).json({error:"Missing moduleId in url path."});return}let t;try{t=JS.parse(r.body)}catch(i){e.status(400).json({error:`Invalid request body: ${i}`});return}let n=tt(),o=await br(n);cC({moduleId:r.params.moduleId,patch:t,momenticFiles:o,logger:w,project:n}),e.status(201).json({message:"ok"})}));var PC=mu;import{Router as D1}from"express";import Og from"path";var gu=D1();gu.patch("/:testPath",at(async(r,e)=>{let t=r.params.testPath;if(!t){e.status(400).json({error:"Missing testPath in path"});return}let n;try{n=YS.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=tt(),i=t.endsWith(".test.yaml")?t:`${t}.test.yaml`,a=await br(o);await pC({filePath:i,steps:n.steps,settings:n.settings,folder:o.rootDir,project:o,momenticFiles:a});let l={message:"ok"};e.status(200).json(l)}));gu.post("/",at((r,e)=>{let t;try{t=KS.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{Zu(n)}catch(g){e.status(400).json({error:g.message});return}let l=tt(),c=Og.join(l.rootDir,...a),{fullPath:s,testId:u}=dC({name:n,description:o,steps:[],settings:i,folder:c}),d=Og.basename(s),p=Og.relative(l.rootDir,s),m={id:u,fileName:d,fullPath:s,relativeFilePath:p};e.status(201).json(m)}));gu.get("/:fileName",at(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=tt(),i=await br(o),l=await nu(n,Nt,i);e.status(200).json(l)}));var IC=gu;var hu=class extends Ri{constructor(t,n){super(t,n);this.client=t;this.orgId=n}async fetchEnvironment(t,n){let o=tt();return Qc(t,o,w)}};var NC="10mb";async function DC(r){let{serverPort:e,apiKey:t,momenticServerUrl:n,staticDir:o,initialProject:i,driverLogLevel:a,regenerateCache:l,alwaysSaveCache:c,noCache:s}=r;n&&EC(n),await TC(t);let u=Pi(),d=du(),p=r.logger.child({orgId:u,userId:d});vC(i,R=>rs({configFilePath:R}));let m=LC();m.use(k1()),m.use(OC.json({limit:NC})),m.use(OC.urlencoded({extended:!1,limit:NC}));let g=B1();if(g.use("/folders",Mg),g.use("/entities",xC),g.use("/identify",_C),g.use("/mobile-tests",IC),g.use("/mobile-modules",PC),g.use("/assets",RC),g.use("/git",_g),m.use("/api",g),m.use((R,D,j)=>{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"),D.on("close",()=>{D.statusCode>=400&&(w.error({url:R.url,method:R.method,statusCode:D.statusCode},"Request completed in error on mobile-desktop-server"),Nt.error({url:R.url,method:R.method,statusCode:D.statusCode},"Request completed in error on mobile-desktop-server"))}),j()}),m.use((R,D,j,ae)=>{if(R instanceof Error&&R.message.includes("BadRequestError: request aborted")){j.status(400).send("Client disconnected");return}w.error({stack:R.stack,msg:R.message,err:R,url:D.url,method:D.method},"Unhandled exception leading to 500 on mobile-desktop-server"),Nt.error({stack:R.stack,msg:R.message,err:R,url:D.url,method:D.method},"Unhandled exception leading to 500 on mobile-desktop-server"),j.status(500).send(`Internal Server Error: ${R.message}`)}),o){let R=LC.static(o,{setHeaders:D=>{D.setHeader("Cache-Control","no-cache")},redirect:!1});m.use(R),m.use("*",(D,j)=>{j.sendFile(H1.join(o,"index.html"))})}let h=z1.createServer(m),f=`http://localhost:${e}`;await new Promise(R=>{try{h.listen(e,()=>{p.info(`Mobile desktop server is running at ${f}`),R()})}catch(D){D.message.includes("EADDRINUSE")?G1(e):w.error(`An unexpected error occurred while starting the server: ${D.message}`),process.exit(1)}});let b={type:"API_KEY",baseUrl:Cg(),apiKey:t,logger:p},x=new Tr(b),A=tt(),v={...b,mode:"interactive"},{dispose:_}=JR({baseServer:h,logger:p,authorization:b,globalStateManager:wC,getOrgId:()=>Pi(),androidDriverFactory:async({socket:R,logger:D,creationOpts:j})=>{let ae=Math.floor(Math.random()*1e4)+4e4,Q=await hl(ae,"appium");return cc({logger:D,driverLogLevel:a,apiClient:x,creationOpts:j,socket:R,appiumPort:Q,orgId:Pi(),onStatusUpdate:me=>{R.emit("connectionStatusUpdate",{message:me})}})},mobileGeneratorFactory:async R=>new Mi({baseUrl:Cg(),apiKey:t,logger:p,mode:"interactive"}),browserGeneratorFactory:async R=>new So(A.config.ai?.agentConfig,v),browserEnricherFactory:async R=>new wi(v,new So(A.config.ai?.agentConfig,v)),storageFactory:async R=>new hu(x,R),cacheStorageFactory:async R=>{let D=await vi(p,x,A);return su({orgId:R,client:x,gitMetadata:D,regenerateCache:l??!1,noCache:s??!1,alwaysSaveCache:c??!1})},localToolsFactory:async()=>new xi({httpClient:x,fakerSeed:void 0}),keepSessionAlive:R=>x.extendAndroidEmulatorTtl(R),settingsFactory:async()=>({emulator:A.config.emulator})});process.once("SIGUSR2",async()=>{return;try{await _(),await At.flush()}catch(R){w.error({err:R},"Error during session dispose on SIGUSR2")}try{h.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 _(),await At.flush()}finally{h.close(()=>process.exit(0))}}),process.once("SIGINT",async()=>{w.info("SIGINT in Momentic mobile app received");try{await _(),await At.flush()}finally{h.close(()=>process.exit(0))}})}F1.setMaxListeners(25);process.on("warning",r=>{Nt.warn({err:r},`Node warning received on mobile-desktop-server: ${r.message}`)});process.on("uncaughtException",r=>{Nt.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=>{Nt.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 G1(r){w.error(U1`Port ${r} is already in use by another process. Please close the other process and try again.
4163
4143
  Using Bash on MacOS or Linux:
4164
4144
  lsof -t -i :58888 | xargs kill -9
4165
4145
 
4166
4146
  Using Command Prompt on Windows:
4167
4147
  for /f "tokens=5" %a in ('netstat -ano ^| findstr :58888') do taskkill /PID %a /F
4168
- `)}import Qz from"open";import fu from"path";import{fileURLToPath as eH}from"url";import{InvalidArgumentError as Og,Option as dt}from"@commander-js/extra-typings";import{z as Nz}from"zod";var OC=58890;function Dz(r){let e=parseInt(r,10);if(isNaN(e))throw new Og("Not a number.");return e}var ls=new dt("--api-key <key>","Momentic API key").env("MOMENTIC_API_KEY").argParser(r=>{if(!r)throw new Og("API key is required.");return r}).makeOptionMandatory(),Lg=new dt("-c, --config <configPath>","Absolute or relative path to a Momentic configuration file."),cs=new dt("--server <server>","Momentic server to use.").env("MOMENTIC_SERVER").default("https://api.momentic.ai").argParser(r=>{try{return Nz.string().url().parse(r),r}catch{throw new Og("Not a valid URL.")}}),Ng=new dt("-y, --yes","Skip all confirmation prompts.").env("CI"),Dg=new dt("--regenerate-cache","Regenerate all caches by starting from an empty cache state. This flag is useful for completely regenerating caches after changing configuration options. Warning: using this option will cause all steps to run without any cached data, resulting in significantly longer execution times.").implies({disableCache:!1,saveCache:!0}),kg=new dt("--save-cache","Always save updated step caches after successful test runs. By default, caches are not saved when running on protected branches.").env("CI").implies({disableCache:!1}),Ug=new dt("--disable-cache","Disable using step caches completely. Using this option may lead to non-deterministic behavior and significantly longer runtimes.").implies({saveCache:!1,regenerateCache:!1}),Fg=new dt("--tag <tag>","Tag identifier for the asset."),LC=new dt("--channel <channel>","Channel name for the asset."),NC=new dt("--channel <channel>","Channel name for the asset.").makeOptionMandatory(),DC=new dt("--env <env>","Environment to run all tests in (overrides test-level configuration)."),kC=new dt("--local-avd-id <localAvdId>","Force tests to use a specific local Android Virtual Device (AVD) instead of remote emulators."),UC=new dt("--local-apk-path <localApkPath>","Path to a local APK file to install when running tests with a local emulator. Overrides remote asset configuration."),FC=new dt("-p, --parallel <parallel>","The number of tests to run in parallel. Defaults to 1.").argParser(Dz),Bg=new dt("--output-dir <outputDir>","Output directory to store run artifacts such as screenshots, results, and logs."),BC=new dt("--upload-results","Upload test results to Momentic Cloud.").default(!1),zg=new dt("--log-level <logLevel>","Log level for Momentic and dependent services.").choices(["error","warn","info","debug"]),zC=new dt("--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 qz}from"crypto";import{existsSync as Kz}from"fs";import Hg from"fs";import us from"path";import{cwd as Uz}from"process";async function HC({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=>Hg.existsSync(p)),d=Uz();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:
4148
+ `)}import lH from"open";import bu from"path";import{fileURLToPath as cH}from"url";import{InvalidArgumentError as Lg,Option as dt}from"@commander-js/extra-typings";import{z as V1}from"zod";var kC=58890;function j1(r){let e=parseInt(r,10);if(isNaN(e))throw new Lg("Not a number.");return e}var us=new dt("--api-key <key>","Momentic API key").env("MOMENTIC_API_KEY").argParser(r=>{if(!r)throw new Lg("API key is required.");return r}).makeOptionMandatory(),Ng=new dt("-c, --config <configPath>","Absolute or relative path to a Momentic configuration file."),ds=new dt("--server <server>","Momentic server to use.").env("MOMENTIC_SERVER").default("https://api.momentic.ai").argParser(r=>{try{return V1.string().url().parse(r),r}catch{throw new Lg("Not a valid URL.")}}),Dg=new dt("-y, --yes","Skip all confirmation prompts.").env("CI"),kg=new dt("--regenerate-cache","Regenerate all caches by starting from an empty cache state. This flag is useful for completely regenerating caches after changing configuration options. Warning: using this option will cause all steps to run without any cached data, resulting in significantly longer execution times.").implies({disableCache:!1,saveCache:!0}),Ug=new dt("--save-cache","Always save updated step caches after successful test runs. By default, caches are not saved when running on protected branches.").env("CI").implies({disableCache:!1}),Fg=new dt("--disable-cache","Disable using step caches completely. Using this option may lead to non-deterministic behavior and significantly longer runtimes.").implies({saveCache:!1,regenerateCache:!1}),Bg=new dt("--tag <tag>","Tag identifier for the asset."),UC=new dt("--channel <channel>","Channel name for the asset."),FC=new dt("--channel <channel>","Channel name for the asset.").makeOptionMandatory(),BC=new dt("--env <env>","Environment to run all tests in (overrides test-level configuration)."),zC=new dt("--local-avd-id <localAvdId>","Force tests to use a specific local Android Virtual Device (AVD) instead of remote emulators."),HC=new dt("--local-apk-path <localApkPath>","Path to a local APK file to install when running tests with a local emulator. Overrides remote asset configuration."),GC=new dt("-p, --parallel <parallel>","The number of tests to run in parallel. Defaults to 1.").argParser(j1),zg=new dt("--output-dir <outputDir>","Output directory to store run artifacts such as screenshots, results, and logs."),VC=new dt("--upload-results","Upload test results to Momentic Cloud.").default(!1),Hg=new dt("--log-level <logLevel>","Log level for Momentic and dependent services.").choices(["error","warn","info","debug"]),jC=new dt("--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 rH}from"crypto";import{existsSync as nH}from"fs";import Gg from"fs";import ps from"path";import{cwd as $1}from"process";async function WC({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=>Gg.existsSync(p)),d=$1();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:
4169
4149
  - ${r.join(`
4170
4150
  - `)}
4171
- `),r.forEach(p=>{if(!Hg.existsSync(p))throw new Error(`Path '${p}' does not exist.`);let m,g;try{m=Hg.statSync(p),g=m.isDirectory()}catch(f){a.warn({err:f},`Skipping path ${p} because it cannot be read`);return}let h=us.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 ul("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=us.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=us.relative(t.rootDir,u),p=await eu(u,a,e),m=us.basename(u,us.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{existsSync as Fz,statSync as Bz}from"fs";import{cloneDeep as zz}from"lodash-es";import Hz from"path";async function GC(r){let{inputs:e,fixtures:t,metadata:n,options:o}=r,{tracer:i,logger:a}=t,{runId:l}=n,{testDefinition:c,runSigIntHandlers:s,project:u}=e,d=new Date,p=await i.startRun({logger:a,testId:c.id,testName:c.name,runId:l,testDescription:c.description,schemaVersion:c.schemaVersion,originalSteps:{steps:zz(c.steps),beforeSteps:void 0,afterSteps:void 0},quarantined:c.quarantined,quarantinedReason:c.quarantinedReason}),m=a.child(p.loggerBindings||{}),g=1+(c.settings?.retries??u.config.retries??1);try{for(let h=0;h<g;h++){let f=new Date,E=await Gz({runTracer:p,testDefinition:c,metadata:n,constants:{attemptNumber:h,totalAttempts:g},fixtures:{...t,logger:m},inputs:e,options:o}),b=new Date;if(E.status!=="FAILED")return await p.finish({logger:a,...E,finishedAt:b}),{...E,startedAt:d,lastAttemptStartedAt:f,finishedAt:b,runId:l,attempts:h+1,testMetadata:c,steps:c.steps,filePath:c.relativeFilePath,quarantined:c.quarantined,quarantinedReason:c.quarantinedReason};if(h!==g-1){a.warn("Retrying failed mobile run");continue}return a.error("Mobile test failed after all exhausting attempts"),await p.finish({logger:a,...E,finishedAt:b}),{...E,startedAt:d,lastAttemptStartedAt:f,finishedAt:b,runId:l,attempts:h+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 Gz(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:C}=a,{regenerateCache:A,alwaysSaveCache:v,noCache:M,logLevel:w,localAvdId:D,localApkPath:j}=l;c!==0&&h("RETRY",`attempt ${c}/${s}`);let ae={...a.project.config.emulator,...t.settings?.emulator},Q=j?Hz.resolve(j):void 0;if(Q&&(!Fz(Q)||!Bz(Q).isFile()))throw new Error(`Local APK path "${Q}" does not exist. Provide a valid file path via --local-apk-path.`);let pe=ou({orgId:u,client:p,gitMetadata:d,regenerateCache:A??!1,alwaysSaveCache:v??!1,noCache:M??!1}),st=new wi(p,u),W={type:"API_KEY",baseUrl:p.baseUrl,apiKey:p.apiKey,logger:m,mode:"runner"},z=new xi(W),re=new fo(b.config.ai?.agentConfig,W),le=new Ai(W,re),Xe=new Ci({httpClient:p,fakerSeed:void 0}),we=Math.floor(Math.random()*1e4)+4e4,Dt=await ml(we,"appium"),wt=ae.region==="local"?Q??t.settings?.defaultApkFilePath?.trim():void 0,Re=f&&!wt?{channel:f,tag:E}:void 0,We;if(D||ae.region==="local"){if(!ae.localEmulatorSettings?.avdId)throw new Error("AVD name is required when region is set to local. Provide --local-avd-id or configure a default local emulator AVD.");We={avdId:D??ae.localEmulatorSettings?.avdId,apkToInstall:Re,apkFilePath:wt}}else We={region:ae.region,apkToInstall:Re};let Rt=await sc({apiClient:p,logger:m,driverLogLevel:w,creationOpts:We,onStatusUpdate:V=>{m.debug({status:V},"Limbar emulator status update")},appiumPort:Dt,orgId:u}),cr=await e.startAttempt({emulatorName:Rt.emulatorName}),Br=m.child(cr.loggerBindings||{}),So=await cc({driver:Rt.driver,onLogs:V=>{cr.appendLogs(V)}}),Su=C||t.settings?.defaultEnv,qg;Su&&(qg=Xc(Su,b,Br).variables);let $C=new Uo({variablesFromEnvironment:qg??{},envName:Su,testName:t.name}),Kg=await Si.init({driver:Rt.driver,generator:z,logger:Br,limbarClient:Rt.limbarClient,orgId:u,adbPort:Rt.adbPort,options:{emulator:ae},fixtures:{storage:st,browserEnricher:le,browserGenerator:re,localCodeEvalTools:Xe,testContext:$C}}),ps;try{ps=await Kc({containerName:"mobile-test",fixtures:{controller:Kg,logger:Br,cacheStorage:pe,usageTracker:g},inputs:{steps:t.steps,orgId:u,testMetadata:t},tracer:cr,callbacks:{}})}finally{await So(),await Rt.cleanup(),await Kg.cleanup()}return await cr.finish({logger:Br,results:ps.results,status:ps.status}),ps}import{randomUUID as Vz}from"crypto";import{debounce as jz}from"ts-debounce";var ds="0.4.0";var mu="assets";function Wz(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 $z(r){switch(r){case"SUCCESS":return"PASSED";case"FAILED":return"FAILED";case"CANCELLED":return"CANCELLED";case"RUNNING":return"RUNNING";case"IDLE":return"PENDING"}}var Gg=class{constructor(e,t,n,o){this.keepalive=e;this.testId=t;this.testName=n;this.diskStorage=o;this.interactionTracer=new lo,Kr.initializeRootTracerContext(this.interactionTracer)}children=[];finished=!1;interactionTracer;getParentStepIdChain(){return[]}attachBeforeScreenshot(e){let{snapshotId:t,screenshot:n}=e;this.diskStorage.storeFile({name:`${mu}/${t}.jpeg`,contents:n})}attachAfterScreenshot(e){let{snapshotId:t,screenshot:n}=e;this.diskStorage.storeFile({name:`${mu}/${t}.jpeg`,contents:n})}async finishInternal(e){this.finished||(this.finished=!0,this.interactionTracer.finish(),await Promise.all(this.children.map(t=>t.finish({status:$z(e.status),finishedAt:e.finishedAt}))))}async finish(e){return await this.finishInternal({status:e.result.status,finishedAt:new Date(e.result.endTime)}),{trace:this.interactionTracer.getRootSpan()}}async startSubSteps(){let e=new Pi(this.keepalive,this.testId,this.testName,this.diskStorage);return this.children.push(e),e}},Pi=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(`${mu}/${t}.jpeg`)}getParentStepIdChain(){return[]}async startStep(e){this.keepalive();let t=new Gg(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:Wz(e.status),finishedAt:e.finishedAt}))))}},Vg=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"),this.logStream=this.diskStorage.createFileStream("assets/logs.logcat")}finished=!1;children=[];logStream;get loggerBindings(){return{runAttemptId:this.runAttemptId}}appendLogs(e){let t=e.join(`
4151
+ `),r.forEach(p=>{if(!Gg.existsSync(p))throw new Error(`Path '${p}' does not exist.`);let m,g;try{m=Gg.statSync(p),g=m.isDirectory()}catch(f){a.warn({err:f},`Skipping path ${p} because it cannot be read`);return}let h=ps.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 pl("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=ps.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=ps.relative(t.rootDir,u),p=await nu(u,a,e),m=ps.basename(u,ps.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{existsSync as q1,statSync as K1}from"fs";import{cloneDeep as Y1}from"lodash-es";import X1 from"path";async function $C(r){let{inputs:e,fixtures:t,metadata:n,options:o}=r,{tracer:i,logger:a}=t,{runId:l}=n,{testDefinition:c,runSigIntHandlers:s,project:u}=e,d=new Date,p=await i.startRun({logger:a,testId:c.id,testName:c.name,runId:l,testDescription:c.description,schemaVersion:c.schemaVersion,originalSteps:{steps:Y1(c.steps),beforeSteps:void 0,afterSteps:void 0},quarantined:c.quarantined,quarantinedReason:c.quarantinedReason}),m=a.child(p.loggerBindings||{}),g=1+(c.settings?.retries??u.config.retries??1);try{for(let h=0;h<g;h++){let f=new Date,E=await J1({runTracer:p,testDefinition:c,metadata:n,constants:{attemptNumber:h,totalAttempts:g},fixtures:{...t,logger:m},inputs:e,options:o}),b=new Date;if(E.status!=="FAILED")return await p.finish({logger:a,...E,finishedAt:b}),{...E,startedAt:d,lastAttemptStartedAt:f,finishedAt:b,runId:l,attempts:h+1,testMetadata:c,steps:c.steps,filePath:c.relativeFilePath,quarantined:c.quarantined,quarantinedReason:c.quarantinedReason};if(h!==g-1){a.warn("Retrying failed mobile run");continue}return a.error("Mobile test failed after all exhausting attempts"),await p.finish({logger:a,...E,finishedAt:b}),{...E,startedAt:d,lastAttemptStartedAt:f,finishedAt:b,runId:l,attempts:h+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 J1(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:x}=a,{regenerateCache:A,alwaysSaveCache:v,noCache:_,logLevel:R,localAvdId:D,localApkPath:j}=l;c!==0&&h("RETRY",`attempt ${c}/${s}`);let ae={...a.project.config.emulator,...t.settings?.emulator},Q=j?X1.resolve(j):void 0;if(Q&&(!q1(Q)||!K1(Q).isFile()))throw new Error(`Local APK path "${Q}" does not exist. Provide a valid file path via --local-apk-path.`);let me=su({orgId:u,client:p,gitMetadata:d,regenerateCache:A??!1,alwaysSaveCache:v??!1,noCache:_??!1}),st=new Ri(p,u),W={type:"API_KEY",baseUrl:p.baseUrl,apiKey:p.apiKey,logger:m,mode:"runner"},z=new Mi(W),re=new So(b.config.ai?.agentConfig,W),le=new wi(W,re),Xe=new xi({httpClient:p,fakerSeed:void 0}),Re=Math.floor(Math.random()*1e4)+4e4,Dt=await hl(Re,"appium"),wt=ae.region==="local"?Q??t.settings?.defaultApkFilePath?.trim():void 0,Ce=f&&!wt?{channel:f,tag:E}:void 0,We;if(D||ae.region==="local"){if(!ae.localEmulatorSettings?.avdId)throw new Error("AVD name is required when region is set to local. Provide --local-avd-id or configure a default local emulator AVD.");We={avdId:D??ae.localEmulatorSettings?.avdId,apkToInstall:Ce,apkFilePath:wt}}else We={region:ae.region,apkToInstall:Ce};let Rt=await cc({apiClient:p,logger:m,driverLogLevel:R,creationOpts:We,onStatusUpdate:V=>{m.debug({status:V},"Limbar emulator status update")},appiumPort:Dt,orgId:u}),ur=await e.startAttempt({emulatorName:Rt.emulatorName}),Hr=m.child(ur.loggerBindings||{}),yo=await dc({driver:Rt.driver,onLogs:V=>{ur.appendLogs(V)}}),Eu=x||t.settings?.defaultEnv,Kg;Eu&&(Kg=Qc(Eu,b,Hr).variables);let XC=new Fo({variablesFromEnvironment:Kg??{},envName:Eu,testName:t.name}),Yg=await yi.init({driver:Rt.driver,generator:z,logger:Hr,limbarClient:Rt.limbarClient,orgId:u,adbPort:Rt.adbPort,options:{emulator:ae},fixtures:{storage:st,browserEnricher:le,browserGenerator:re,localCodeEvalTools:Xe,testContext:XC}}),gs;try{gs=await Jc({containerName:"mobile-test",fixtures:{controller:Yg,logger:Hr,cacheStorage:me,usageTracker:g},inputs:{steps:t.steps,orgId:u,testMetadata:t},tracer:ur,callbacks:{}})}finally{await yo(),await Rt.cleanup(),await Yg.cleanup()}return await ur.finish({logger:Hr,results:gs.results,status:gs.status}),gs}import{randomUUID as Z1}from"crypto";import{debounce as Q1}from"ts-debounce";var ms="0.4.1";var fu="assets";function eH(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 tH(r){switch(r){case"SUCCESS":return"PASSED";case"FAILED":return"FAILED";case"CANCELLED":return"CANCELLED";case"RUNNING":return"RUNNING";case"IDLE":return"PENDING"}}var Vg=class{constructor(e,t,n,o){this.keepalive=e;this.testId=t;this.testName=n;this.diskStorage=o;this.interactionTracer=new co,Yr.initializeRootTracerContext(this.interactionTracer)}children=[];finished=!1;interactionTracer;getParentStepIdChain(){return[]}attachBeforeScreenshot(e){let{snapshotId:t,screenshot:n}=e;this.diskStorage.storeFile({name:`${fu}/${t}.jpeg`,contents:n})}attachAfterScreenshot(e){let{snapshotId:t,screenshot:n}=e;this.diskStorage.storeFile({name:`${fu}/${t}.jpeg`,contents:n})}async finishInternal(e){this.finished||(this.finished=!0,this.interactionTracer.finish(),await Promise.all(this.children.map(t=>t.finish({status:tH(e.status),finishedAt:e.finishedAt}))))}async finish(e){return await this.finishInternal({status:e.result.status,finishedAt:new Date(e.result.endTime)}),{trace:this.interactionTracer.getRootSpan()}}async startSubSteps(){let e=new Ii(this.keepalive,this.testId,this.testName,this.diskStorage);return this.children.push(e),e}},Ii=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(`${fu}/${t}.jpeg`)}getParentStepIdChain(){return[]}async startStep(e){this.keepalive();let t=new Vg(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:eH(e.status),finishedAt:e.finishedAt}))))}},jg=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"),this.logStream=this.diskStorage.createFileStream("assets/logs.logcat")}finished=!1;children=[];logStream;get loggerBindings(){return{runAttemptId:this.runAttemptId}}appendLogs(e){let t=e.join(`
4172
4152
  `);this.logStream.write(t+`
4173
- `)}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:Bc(o,t),beforeResults:i?Bc(i,t):void 0,afterResults:a?Bc(a,t):void 0};await Promise.all(this.children.map(c=>c.finish({status:l.status,finishedAt:l.finishedAt})));try{this.logStream.end()}catch{}this.diskStorage.storeFile({name:"metadata.json",contents:JSON.stringify(l,null,2)})}async startBeforeStepList(){let e=new Pi(this.keepalive,this.testId,this.testName,this.diskStorage);return this.children.push(e),e}async startMainStepList(){let e=new Pi(this.keepalive,this.testId,this.testName,this.diskStorage);return this.children.push(e),e}async startAfterStepList(){let e=new Pi(this.keepalive,this.testId,this.testName,this.diskStorage);return this.children.push(e),e}async getScreenshot(e,t){return this.diskStorage.readFile(`${mu}/${t}.jpeg`)}},jg=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=Vz(),o={id:n,schemaVersion:Dn,runAttemptSchemaVersion:Wy,startedAt:new Date,status:"RUNNING"};t.storeFile({name:"metadata.json",contents:JSON.stringify(o,null,2)});let i=jz(async()=>{await this.client.extendAndroidEmulatorTtl(e.emulatorName)},3e4,{maxWait:6e4}),a=new Vg(()=>void i(),this.testId,this.testName,n,o,t);return this.children.push(a),a}},gu=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:Jt.CLI,startedAt:new Date,status:"RUNNING",cliVersion:ds,labels:a??[]},c=new ns(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:ds,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 jg(this.client,e.testId,e.testName,e.runId,n,t);return this.children.push(o),o}};async function VC(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 Yr(){try{await F(Promise.all([eb(),At.flush()]),{milliseconds:5e3})}catch{}}async function jC(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;Kz(d)&&R.warn(`Output directory ${d} already exists, removing before test execution...`);let m=await VC(l,a,e.ignoreQuarantine),g=await Sr(i),h=await HC({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 gu.start({logger:f,orgId:c,runGroupId:s,outputDir:d,client:a,gitMetadata:u,labels:[]}),b=[],C=new Date,A=new Set,v=async()=>Yz({runResults:b,startTime:C,ranTests:A,apiClient:a,uploadResults:e.uploadResults??!1,outputDir:d}),M=[],w=async()=>{R.warn("SIGINT received. Stopping tests and printing latest results..."),await E.finish({logger:f,status:"CANCELLED"}),await v(),await Promise.allSettled(M.map(Q=>Q())),await Yr(),process.exit(1)};process.once("SIGINT",w);let D={};for(let Q=0;Q<h.length;Q++){let pe=Object.values(D);pe.length===p&&await Promise.race(pe.map(z=>z.promise));let st=h[Q],W=`test-${Q}`;D[W]={done:!1,promise:(async({testDefinition:z})=>{A.add(W);let re=z.relativeFilePath.includes("..")?z.fullFilePath:z.relativeFilePath;fa({status:"START",testLogRef:re,getRunningTestsCount:()=>A.size,getTotalTestsCount:()=>h.length});let le=setInterval(()=>fa({status:"RUN",testLogRef:re,getRunningTestsCount:()=>A.size,getTotalTestsCount:()=>h.length}),5*60*1e3),Xe=qz(),we=f.child({testId:z.id,runId:Xe}),Dt=new Ec({logger:we,reporter:new ru(a),runType:"mobile-test-run",runId:Xe,testMetadata:z,suiteMetadata:void 0});try{let wt=await GC({metadata:{...o,runId:Xe},fixtures:{...t,tracer:E,logger:we,usageTracker:Dt},inputs:{...n,project:i,testDefinition:z,channel:n.channel??z.settings?.defaultChannel,tag:n.tag??z.settings?.defaultTag,logUpdate:(Re,We)=>fa({status:Re,testLogRef:re,getRunningTestsCount:()=>A.size,getTotalTestsCount:()=>h.length,additionalText:We}),runSigIntHandlers:M},options:e});fa({status:wt.status,testLogRef:re,getRunningTestsCount:()=>A.size,getTotalTestsCount:()=>h.length}),b.push(wt)}catch(wt){let Re=`Encountered unexpected fatal error when running test '${z.name}': ${wt.message}
4174
- ${wt.stack}`;R.error(Re),we.error({err:wt},`Encountered unexpected fatal error when running test ${z.name}`)}finally{clearInterval(le),D[W].done=!0,delete D[W]}await Dt.flush(l)})({testDefinition:st})}}await Promise.allSettled(Object.values(D).map(Q=>Q.promise));let ae=b.some(Q=>Q.status==="FAILED"&&!Q.quarantined)?"FAILED":"PASSED";return await E.finish({logger:f,status:ae}),process.off("SIGINT",w),v()}async function Yz({runResults:r,startTime:e,ranTests:t,apiClient:n,uploadResults:o,outputDir:i}){let a=n.getAppUrl(),l=tb({results:r,startTime:e.getTime(),onFailed:c=>{},getDisplayLine:c=>{let s=`${$d}- ${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 au({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 Wg(){Ev(),ib("Chromium")||(jn?(await ul("The Chromium browser is not installed but is required for automating webviews. Install it now?")||process.exit(1),await pl({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)))}pv({serviceName:"mobile-cli"});rr.setApp("mobile-cli");var Mn=new Xz;Mn.name("momentic-mobile").description("Momentic Mobile CLI").version(ds);var tH=Mn.command("assets").description("Manage mobile testing assets");tH.command("upload").description("Upload an asset for mobile tests").argument("<file>","Path to the asset file to upload").addOption(ls).addOption(cs).addOption(Fg).addOption(NC).action(async(r,e)=>{let{apiKey:t,server:n,tag:o,channel:i}=e,a=fu.resolve(r);hu.existsSync(a)||(R.error(`File not found: ${a}`),process.exit(1));let l=new br({baseUrl:n,apiKey:t,logger:R});/\.apk$/i.test(a)||(R.error(`File is not an APK file: ${a}`),process.exit(1)),await lc({tag:o?.toLowerCase(),channel:i.toLowerCase(),filePath:a,apiClient:l,logger:R})});Mn.command("app").addOption(ls).addOption(cs).addOption(Ng).addOption(Lg).addOption(zg).addOption(Dg).addOption(kg).addOption(Ug).action(async r=>{let{apiKey:e,server:t,yes:n,disableCache:o,saveCache:i,regenerateCache:a}=r,l=Kd(r.logLevel);rr.setApp("mobile-desktop-server");let c=new br({baseUrl:t,apiKey:e,logger:rr});await Sg({client:c,skipPrompts:n}),R.debug("API key check complete");let s=eH(import.meta.url),u=fu.dirname(s),d=fu.resolve(u,"..","static");await Wg(),R.debug({appiumHome:Ha},"Resolved resource paths");let p=await es({configFilePath:r.config}),m=OC;await IC({momenticServerUrl:t,serverPort:m,apiKey:e,staticDir:d,initialProject:p,driverLogLevel:l,logger:rr,regenerateCache:a,noCache:o,alwaysSaveCache:i});let g=`http://localhost:${m}`;R.info(`Local app started on: ${g}`),await Qz(g)});var WC=Mn.command("results").description("Merge and upload test results.");WC.command("merge").description("Merge test results files.").addOption(Bg).addArgument(new $g("<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)),hu.existsSync(r)||(R.warn("Results path does not exist, skipping merge."),process.exit(0)),hu.existsSync(t)&&R.warn(`Output directory ${t} already exists, removing before merging...`),pC(rr,t,r),await Yr(),process.exit(0)});var rH=new $g("<results>","Path to the results archive.").argRequired();WC.command("upload").description("Upload test results to Momentic cloud.").addOption(ls).addOption(cs).addArgument(rH).action(async(r,e)=>{let{apiKey:t,server:n}=e,o=rr,i=new br({baseUrl:n,apiKey:t,logger:o});await au({consoleLogger:R,resultsPath:r,client:i}),await Yr(),process.exit(0)});var nH=Mn.command("run").alias("test").description("Run tests on the local machine");nH.addOption(ls).addOption(cs).addOption(Lg).addOption(Ng).addOption(FC).addOption(zg).addOption(Dg).addOption(kg).addOption(Ug).addOption(Bg).addOption(BC).addOption(zC).addOption(Fg).addOption(LC).addOption(DC).addOption(kC).addOption(UC).addArgument(new $g("<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=Kd(e.logLevel);await Wg(),R.debug({appiumHome:Ha},"Resolved resource paths");let c=await es({configFilePath:e.config}),s=a??c.config.outputDir??tC,u=e.parallel??c.config.parallel??1;R.debug("Checking API key and dependencies");let d=new br({baseUrl:n,apiKey:t,logger:R}),{orgId:p,userId:m}=await Sg({client:d,skipPrompts:e.yes});R.debug("API key check and browser installation complete");let g=Zz(),h=rr.child({runGroupId:g,orgId:p,userId:m}),f=await Ti(rr,d,c);h.debug(f,"Got local git metadata");try{let E=await jC({options:{...e,parallel:u,outputDir:s,alwaysSaveCache:e.saveCache,noCache:e.disableCache,logLevel:l},fixtures:{logger:h,project:c,apiClient:d},inputs:{envOverride:e.env,tag:o,channel:i,tests:r},metadata:{gitMetadata:f,runGroupId:g,orgId:p}});await Yr(),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),rr.error({err:E},"Failed to run tests locally"),await Yr(),process.exit(1)}});Mn.command("init").description("Initialize an empty Momentic project in the current working directory").addOption(new Jz("--name <name>","Name of the project")).action(async r=>{R.info(`Welcome to the Momentic Mobile project setup wizard! \u{1F680}
4175
- `),R.info("This wizard will help you bootstrap a new Momentic project."),hu.existsSync(Ei)&&(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 Yy("Choose an identifier for your project, such as a service, product, or team name (default: 'app'):","app"),include:ng};eC(t,Ei),R.success(`Initialized Momentic project file at ${fu.resolve(Ei)}`)});Mn.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: ${Yd.join(", ")}.`).action(async(r,e)=>{!e.all&&r.length===0&&(R.error("No browsers specified"),process.exit(1)),await pl({rawBrowsers:r,force:e.force,all:e.all})});async function oH(){try{await Mn.parseAsync(process.argv),await Yr()}catch(r){rr.error({err:r},"Uncaught error in CLI"),R.error(r),await Yr(),process.exit(1)}}oH();
4153
+ `)}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:Gc(o,t),beforeResults:i?Gc(i,t):void 0,afterResults:a?Gc(a,t):void 0};await Promise.all(this.children.map(c=>c.finish({status:l.status,finishedAt:l.finishedAt})));try{this.logStream.end()}catch{}this.diskStorage.storeFile({name:"metadata.json",contents:JSON.stringify(l,null,2)})}async startBeforeStepList(){let e=new Ii(this.keepalive,this.testId,this.testName,this.diskStorage);return this.children.push(e),e}async startMainStepList(){let e=new Ii(this.keepalive,this.testId,this.testName,this.diskStorage);return this.children.push(e),e}async startAfterStepList(){let e=new Ii(this.keepalive,this.testId,this.testName,this.diskStorage);return this.children.push(e),e}async getScreenshot(e,t){return this.diskStorage.readFile(`${fu}/${t}.jpeg`)}},Wg=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=Z1(),o={id:n,schemaVersion:kn,runAttemptSchemaVersion:Ky,startedAt:new Date,status:"RUNNING"};t.storeFile({name:"metadata.json",contents:JSON.stringify(o,null,2)});let i=Q1(async()=>{await this.client.extendAndroidEmulatorTtl(e.emulatorName)},3e4,{maxWait:6e4}),a=new jg(()=>void i(),this.testId,this.testName,n,o,t);return this.children.push(a),a}},Su=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:Jt.CLI,startedAt:new Date,status:"RUNNING",cliVersion:ms,labels:a??[]},c=new is(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:ms,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 Wg(this.client,e.testId,e.testName,e.runId,n,t);return this.children.push(o),o}};async function qC(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 Xr(){try{await k(Promise.all([nb(),At.flush()]),{milliseconds:5e3})}catch{}}async function KC(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;nH(d)&&w.warn(`Output directory ${d} already exists, removing before test execution...`);let m=await qC(l,a,e.ignoreQuarantine),g=await br(i),h=await WC({tests:n.tests,yes:e.yes,project:i,momenticFiles:g,logger:w,quarantinedTestReasons:m}),f=l.child({orgId:c,runGroupId:s,branch:u.gitBranchName}),E=await Su.start({logger:f,orgId:c,runGroupId:s,outputDir:d,client:a,gitMetadata:u,labels:[]}),b=[],x=new Date,A=new Set,v=async()=>oH({runResults:b,startTime:x,ranTests:A,apiClient:a,uploadResults:e.uploadResults??!1,outputDir:d}),_=[],R=async()=>{w.warn("SIGINT received. Stopping tests and printing latest results..."),await E.finish({logger:f,status:"CANCELLED"}),await v(),await Promise.allSettled(_.map(Q=>Q())),await Xr(),process.exit(1)};process.once("SIGINT",R);let D={};for(let Q=0;Q<h.length;Q++){let me=Object.values(D);me.length===p&&await Promise.race(me.map(z=>z.promise));let st=h[Q],W=`test-${Q}`;D[W]={done:!1,promise:(async({testDefinition:z})=>{A.add(W);let re=z.relativeFilePath.includes("..")?z.fullFilePath:z.relativeFilePath;Sa({status:"START",testLogRef:re,getRunningTestsCount:()=>A.size,getTotalTestsCount:()=>h.length});let le=setInterval(()=>Sa({status:"RUN",testLogRef:re,getRunningTestsCount:()=>A.size,getTotalTestsCount:()=>h.length}),5*60*1e3),Xe=rH(),Re=f.child({testId:z.id,runId:Xe}),Dt=new vc({logger:Re,reporter:new iu(a),runType:"mobile-test-run",runId:Xe,testMetadata:z,suiteMetadata:void 0});try{let wt=await $C({metadata:{...o,runId:Xe},fixtures:{...t,tracer:E,logger:Re,usageTracker:Dt},inputs:{...n,project:i,testDefinition:z,channel:n.channel??z.settings?.defaultChannel,tag:n.tag??z.settings?.defaultTag,logUpdate:(Ce,We)=>Sa({status:Ce,testLogRef:re,getRunningTestsCount:()=>A.size,getTotalTestsCount:()=>h.length,additionalText:We}),runSigIntHandlers:_},options:e});Sa({status:wt.status,testLogRef:re,getRunningTestsCount:()=>A.size,getTotalTestsCount:()=>h.length}),b.push(wt)}catch(wt){let Ce=`Encountered unexpected fatal error when running test '${z.name}': ${wt.message}
4154
+ ${wt.stack}`;w.error(Ce),Re.error({err:wt},`Encountered unexpected fatal error when running test ${z.name}`)}finally{clearInterval(le),D[W].done=!0,delete D[W]}await Dt.flush(l)})({testDefinition:st})}}await Promise.allSettled(Object.values(D).map(Q=>Q.promise));let ae=b.some(Q=>Q.status==="FAILED"&&!Q.quarantined)?"FAILED":"PASSED";return await E.finish({logger:f,status:ae}),process.off("SIGINT",R),v()}async function oH({runResults:r,startTime:e,ranTests:t,apiClient:n,uploadResults:o,outputDir:i}){let a=n.getAppUrl(),l=ob({results:r,startTime:e.getTime(),onFailed:c=>{},getDisplayLine:c=>{let s=`${Yd}- ${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 cu({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 $g(){Av(),lb("Chromium")||(Wn?(await pl("The Chromium browser is not installed but is required for automating webviews. Install it now?")||process.exit(1),await gl({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)))}hv({serviceName:"mobile-cli"});rr.setApp("mobile-cli");var _n=new iH;_n.name("momentic-mobile").description("Momentic Mobile CLI").version(ms);var uH=_n.command("assets").description("Manage mobile testing assets");uH.command("upload").description("Upload an asset for mobile tests").argument("<file>","Path to the asset file to upload").addOption(us).addOption(ds).addOption(Bg).addOption(FC).action(async(r,e)=>{let{apiKey:t,server:n,tag:o,channel:i}=e,a=bu.resolve(r);yu.existsSync(a)||(w.error(`File not found: ${a}`),process.exit(1));let l=new Tr({baseUrl:n,apiKey:t,logger:w});/\.apk$/i.test(a)||(w.error(`File is not an APK file: ${a}`),process.exit(1)),await uc({tag:o?.toLowerCase(),channel:i.toLowerCase(),filePath:a,apiClient:l,logger:w})});_n.command("app").addOption(us).addOption(ds).addOption(Dg).addOption(Ng).addOption(Hg).addOption(kg).addOption(Ug).addOption(Fg).action(async r=>{let{apiKey:e,server:t,yes:n,disableCache:o,saveCache:i,regenerateCache:a}=r,l=Jd(r.logLevel);rr.setApp("mobile-desktop-server");let c=new Tr({baseUrl:t,apiKey:e,logger:rr});await yg({client:c,skipPrompts:n}),w.debug("API key check complete");let s=cH(import.meta.url),u=bu.dirname(s),d=bu.resolve(u,"..","static");await $g(),w.debug({appiumHome:Ga},"Resolved resource paths");let p=await rs({configFilePath:r.config}),m=kC;await DC({momenticServerUrl:t,serverPort:m,apiKey:e,staticDir:d,initialProject:p,driverLogLevel:l,logger:rr,regenerateCache:a,noCache:o,alwaysSaveCache:i});let g=`http://localhost:${m}`;w.info(`Local app started on: ${g}`),await lH(g)});var YC=_n.command("results").description("Merge and upload test results.");YC.command("merge").description("Merge test results files.").addOption(zg).addArgument(new qg("<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)),yu.existsSync(r)||(w.warn("Results path does not exist, skipping merge."),process.exit(0)),yu.existsSync(t)&&w.warn(`Output directory ${t} already exists, removing before merging...`),fC(rr,t,r),await Xr(),process.exit(0)});var dH=new qg("<results>","Path to the results archive.").argRequired();YC.command("upload").description("Upload test results to Momentic cloud.").addOption(us).addOption(ds).addArgument(dH).action(async(r,e)=>{let{apiKey:t,server:n}=e,o=rr,i=new Tr({baseUrl:n,apiKey:t,logger:o});await cu({consoleLogger:w,resultsPath:r,client:i}),await Xr(),process.exit(0)});var pH=_n.command("run").alias("test").description("Run tests on the local machine");pH.addOption(us).addOption(ds).addOption(Ng).addOption(Dg).addOption(GC).addOption(Hg).addOption(kg).addOption(Ug).addOption(Fg).addOption(zg).addOption(VC).addOption(jC).addOption(Bg).addOption(UC).addOption(BC).addOption(zC).addOption(HC).addArgument(new qg("<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=Jd(e.logLevel);await $g(),w.debug({appiumHome:Ga},"Resolved resource paths");let c=await rs({configFilePath:e.config}),s=a??c.config.outputDir??iC,u=e.parallel??c.config.parallel??1;w.debug("Checking API key and dependencies");let d=new Tr({baseUrl:n,apiKey:t,logger:w}),{orgId:p,userId:m}=await yg({client:d,skipPrompts:e.yes});w.debug("API key check and browser installation complete");let g=sH(),h=rr.child({runGroupId:g,orgId:p,userId:m}),f=await vi(rr,d,c);h.debug(f,"Got local git metadata");try{let E=await KC({options:{...e,parallel:u,outputDir:s,alwaysSaveCache:e.saveCache,noCache:e.disableCache,logLevel:l},fixtures:{logger:h,project:c,apiClient:d},inputs:{envOverride:e.env,tag:o,channel:i,tests:r},metadata:{gitMetadata:f,runGroupId:g,orgId:p}});await Xr(),E.failed>0?process.exit(1):process.exit(0)}catch(E){w.error("Failed to run tests locally. Please check the error message below or run with the --verbose flag."),w.error(E),rr.error({err:E},"Failed to run tests locally"),await Xr(),process.exit(1)}});_n.command("init").description("Initialize an empty Momentic project in the current working directory").addOption(new aH("--name <name>","Name of the project")).action(async r=>{w.info(`Welcome to the Momentic Mobile project setup wizard! \u{1F680}
4155
+ `),w.info("This wizard will help you bootstrap a new Momentic project."),yu.existsSync(Ti)&&(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 Zy("Choose an identifier for your project, such as a service, product, or team name (default: 'app'):","app"),include:og};oC(t,Ti),w.success(`Initialized Momentic project file at ${bu.resolve(Ti)}`)});_n.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: ${Zd.join(", ")}.`).action(async(r,e)=>{!e.all&&r.length===0&&(w.error("No browsers specified"),process.exit(1)),await gl({rawBrowsers:r,force:e.force,all:e.all})});async function mH(){try{await _n.parseAsync(process.argv),await Xr()}catch(r){rr.error({err:r},"Uncaught error in CLI"),w.error(r),await Xr(),process.exit(1)}}mH();
4176
4156
  //# sourceMappingURL=cli.js.map