momentic 2.20.2 → 2.20.3
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 +31 -32
- package/npm-shrinkwrap.json +18 -18
- package/package.json +1 -1
package/bin/cli.js
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
2
|
|
|
3
|
-
!function(){try{var e="undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:{},n=(new e.Error).stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="
|
|
3
|
+
!function(){try{var e="undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:{},n=(new e.Error).stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="8836f39a-59f8-54fb-8c63-0560da741b40")}catch(e){}}();
|
|
4
4
|
var XM=Object.defineProperty;var nt=(r,e)=>()=>(r&&(e=r(r=0)),e);var JM=(r,e)=>{for(var t in e)XM(r,t,{get:e[t],enumerable:!0})};var KA,YA=nt(()=>{"use strict";KA=typeof globalThis=="object"?globalThis:global});var XA=nt(()=>{"use strict";YA()});var JA=nt(()=>{"use strict";XA()});var Fn,Qh=nt(()=>{"use strict";Fn="1.9.0"});function NF(r){var e=new Set([r]),t=new Set,n=r.match(QA);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(QA);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 QA,ZA,eR=nt(()=>{"use strict";Qh();QA=/^(\d+)\.(\d+)\.(\d+)(-(.+))?$/;ZA=NF(Fn)});function Ra(r,e,t,n){var o;n===void 0&&(n=!1);var i=cl[ll]=(o=cl[ll])!==null&&o!==void 0?o:{version:Fn};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!==Fn){var a=new Error("@opentelemetry/api: Registration of version v"+i.version+" for "+r+" does not match previously registered API v"+Fn);return t.error(a.stack||a.message),!1}return i[r]=e,t.debug("@opentelemetry/api: Registered a global for "+r+" v"+Fn+"."),!0}function Bn(r){var e,t,n=(e=cl[ll])===null||e===void 0?void 0:e.version;if(!(!n||!ZA(n)))return(t=cl[ll])===null||t===void 0?void 0:t[r]}function wa(r,e){e.debug("@opentelemetry/api: Unregistering a global for "+r+" v"+Fn+".");var t=cl[ll];t&&delete t[r]}var DF,ll,cl,ul=nt(()=>{"use strict";JA();Qh();eR();DF=Fn.split(".")[0],ll=Symbol.for("opentelemetry.js.api."+DF),cl=KA});function dl(r,e,t){var n=Bn("diag");if(n)return t.unshift(e),n[r].apply(n,UF([],kF(t),!1))}var kF,UF,tR,rR=nt(()=>{"use strict";ul();kF=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},UF=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))},tR=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 dl("debug",this._namespace,e)},r.prototype.error=function(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];return dl("error",this._namespace,e)},r.prototype.info=function(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];return dl("info",this._namespace,e)},r.prototype.warn=function(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];return dl("warn",this._namespace,e)},r.prototype.verbose=function(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];return dl("verbose",this._namespace,e)},r}()});var qe,Hu=nt(()=>{"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"})(qe||(qe={}))});function nR(r,e){r<qe.NONE?r=qe.NONE:r>qe.ALL&&(r=qe.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",qe.ERROR),warn:t("warn",qe.WARN),info:t("info",qe.INFO),debug:t("debug",qe.DEBUG),verbose:t("verbose",qe.VERBOSE)}}var oR=nt(()=>{"use strict";Hu()});var FF,BF,zF,En,pl=nt(()=>{"use strict";rR();oR();Hu();ul();FF=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},BF=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))},zF="diag",En=function(){function r(){function e(o){return function(){for(var i=[],a=0;a<arguments.length;a++)i[a]=arguments[a];var l=Bn("diag");if(l)return l[o].apply(l,BF([],FF(i),!1))}}var t=this,n=function(o,i){var a,l,c;if(i===void 0&&(i={logLevel:qe.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=Bn("diag"),d=nR((l=i.logLevel)!==null&&l!==void 0?l:qe.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 Ra("diag",d,t,!0)};t.setLogger=n,t.disable=function(){wa(zF,t)},t.createComponentLogger=function(o){return new tR(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 iR,aR=nt(()=>{"use strict";iR=Symbol("BaggageEntryMetadata")});function Zh(r){return typeof r!="string"&&(HF.error("Cannot create baggage metadata from unknown type: "+typeof r),r=""),{__TYPE__:iR,toString:function(){return r}}}var HF,sR=nt(()=>{"use strict";pl();aR();HF=En.instance()});function eg(r){return Symbol.for(r)}var GF,tg,rg=nt(()=>{"use strict";GF=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}(),tg=new GF});function ig(){return og}var Si,jF,Gu,VF,$F,WF,qF,ng,KF,YF,XF,og,JF,QF,ZF,eB,tB,rB,nB,ag=nt(()=>{"use strict";Si=function(){var r=function(e,t){return r=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(n,o){n.__proto__=o}||function(n,o){for(var i in o)Object.prototype.hasOwnProperty.call(o,i)&&(n[i]=o[i])},r(e,t)};return function(e,t){if(typeof t!="function"&&t!==null)throw new TypeError("Class extends value "+String(t)+" is not a constructor or null");r(e,t);function n(){this.constructor=e}e.prototype=t===null?Object.create(t):(n.prototype=t.prototype,new n)}}(),jF=function(){function r(){}return r.prototype.createGauge=function(e,t){return QF},r.prototype.createHistogram=function(e,t){return ZF},r.prototype.createCounter=function(e,t){return JF},r.prototype.createUpDownCounter=function(e,t){return eB},r.prototype.createObservableGauge=function(e,t){return rB},r.prototype.createObservableCounter=function(e,t){return tB},r.prototype.createObservableUpDownCounter=function(e,t){return nB},r.prototype.addBatchObservableCallback=function(e,t){},r.prototype.removeBatchObservableCallback=function(e){},r}(),Gu=function(){function r(){}return r}(),VF=function(r){Si(e,r);function e(){return r!==null&&r.apply(this,arguments)||this}return e.prototype.add=function(t,n){},e}(Gu),$F=function(r){Si(e,r);function e(){return r!==null&&r.apply(this,arguments)||this}return e.prototype.add=function(t,n){},e}(Gu),WF=function(r){Si(e,r);function e(){return r!==null&&r.apply(this,arguments)||this}return e.prototype.record=function(t,n){},e}(Gu),qF=function(r){Si(e,r);function e(){return r!==null&&r.apply(this,arguments)||this}return e.prototype.record=function(t,n){},e}(Gu),ng=function(){function r(){}return r.prototype.addCallback=function(e){},r.prototype.removeCallback=function(e){},r}(),KF=function(r){Si(e,r);function e(){return r!==null&&r.apply(this,arguments)||this}return e}(ng),YF=function(r){Si(e,r);function e(){return r!==null&&r.apply(this,arguments)||this}return e}(ng),XF=function(r){Si(e,r);function e(){return r!==null&&r.apply(this,arguments)||this}return e}(ng),og=new jF,JF=new VF,QF=new WF,ZF=new qF,eB=new $F,tB=new KF,rB=new YF,nB=new XF});var Sr,lR=nt(()=>{"use strict";(function(r){r[r.INT=0]="INT",r[r.DOUBLE=1]="DOUBLE"})(Sr||(Sr={}))});var oB,iB,cR,uR=nt(()=>{"use strict";rg();oB=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},iB=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))},cR=function(){function r(){}return r.prototype.active=function(){return tg},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,iB([n],oB(o),!1))},r.prototype.bind=function(e,t){return t},r.prototype.enable=function(){return this},r.prototype.disable=function(){return this},r}()});var aB,sB,sg,lB,dR,pR=nt(()=>{"use strict";uR();ul();pl();aB=function(r,e){var t=typeof Symbol=="function"&&r[Symbol.iterator];if(!t)return r;var n=t.call(r),o,i=[],a;try{for(;(e===void 0||e-- >0)&&!(o=n.next()).done;)i.push(o.value)}catch(l){a={error:l}}finally{try{o&&!o.done&&(t=n.return)&&t.call(n)}finally{if(a)throw a.error}}return i},sB=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))},sg="context",lB=new cR,dR=function(){function r(){}return r.getInstance=function(){return this._instance||(this._instance=new r),this._instance},r.prototype.setGlobalContextManager=function(e){return Ra(sg,e,En.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,sB([e,t,n],aB(i),!1))},r.prototype.bind=function(e,t){return this._getContextManager().bind(e,t)},r.prototype._getContextManager=function(){return Bn(sg)||lB},r.prototype.disable=function(){this._getContextManager().disable(),wa(sg,En.instance())},r}()});var Ca,mR=nt(()=>{"use strict";pR();Ca=dR.getInstance()});var V,hR=nt(()=>{"use strict";pl();V=En.instance()});var cB,gR,fR=nt(()=>{"use strict";ag();cB=function(){function r(){}return r.prototype.getMeter=function(e,t,n){return og},r}(),gR=new cB});var lg,SR,yR=nt(()=>{"use strict";fR();ul();pl();lg="metrics",SR=function(){function r(){}return r.getInstance=function(){return this._instance||(this._instance=new r),this._instance},r.prototype.setGlobalMeterProvider=function(e){return Ra(lg,e,En.instance())},r.prototype.getMeterProvider=function(){return Bn(lg)||gR},r.prototype.getMeter=function(e,t,n){return this.getMeterProvider().getMeter(e,t,n)},r.prototype.disable=function(){wa(lg,En.instance())},r}()});var ju,ER=nt(()=>{"use strict";yR();ju=SR.getInstance()});var Ue=nt(()=>{"use strict";sR();rg();Hu();ag();lR();mR();hR();ER()});var Za=(r,e)=>{},Np=!1;try{let r=await import("@sentry/node");Za=r.captureException,r.init({dsn:"https://89e980855f7b9c6e56fc6c7e7143888b@o4506426201800704.ingest.us.sentry.io/4508343221354497",environment:"production",release:process.env.SENTRY_RELEASE_NAME,tracesSampleRate:0}),Np=!0}catch{}import{Command as EW,Option as pr}from"@commander-js/extra-typings";import{execSync as TW}from"child_process";import{existsSync as hk,statSync as gk}from"fs";import{z as OS}from"zod";var OW=OS.object({input:OS.string()});import{z as Tt}from"zod";var DW=Tt.object({srcs:Tt.array(Tt.string()),urls:Tt.array(Tt.string()),desiredSrc:Tt.string().optional(),desiredUrl:Tt.string().optional()}),LS=Tt.object({srcRegex:Tt.string().optional(),urlRegex:Tt.string().optional()}),NS=Tt.object({x:Tt.number(),y:Tt.number(),correlation:Tt.number()}),kW=Tt.object({searchImageBase64String:Tt.string(),pageImageBase64String:Tt.string(),id:Tt.string().uuid(),timeoutMs:Tt.number().max(1e4).min(0).optional()});import{z as L}from"zod";import*as U from"zod";import{extendZodWithOpenApi as QM}from"zod-openapi";QM(U);var Jn=(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))(Jn||{}),ZM=U.object({mPathSelectorTokens:U.string().array(),frameSrcRegex:U.string().optional(),frameUrlRegex:U.string().optional(),indices:U.number().array()}),Dp=U.object({result:U.number(),traceId:U.string()}).array(),ql=U.object({type:U.literal("GCS_TRACES"),traces:Dp}),DS=U.object({text:U.string().optional(),attributes:U.record(U.string(),U.string()).optional(),boundingBox:U.object({x:U.number(),y:U.number(),width:U.number(),height:U.number()}).optional()}),eP=U.object({selectors:U.string().array(),requirements:DS.optional()}),Qn=U.object({id:U.number().int(),dataMomenticId:U.number().int().optional(),selector:U.string().optional(),hybridSelector:U.object({textContent:U.string().nullish(),attributes:U.record(U.string(),U.string().optional()),tagName:U.string(),expandShadowRoot:U.boolean().optional(),classNames:U.string().array(),nthChild:U.number()}).array().optional(),generatedSelectors:U.string().array().optional(),requirements:DS.optional(),additionalElements:eP.array().optional(),role:U.string().optional(),name:U.string().optional(),numChildren:U.number().optional(),content:U.string().optional(),pathFromRoot:U.string().optional(),serializedHtml:U.string().optional().describe("pruned html including 1 neighbor and 1 layer of children. value for text inputs pruned."),nodeOnlySerializedHtml:U.string().optional().describe("outerHtml of the element without any children. value for text inputs pruned."),screenshotUrl:U.string().url().optional(),boundingBox:U.object({x:U.number().optional(),y:U.number().optional(),width:U.number(),height:U.number()}).describe("css pixel bounding box").optional(),frameCache:ZM.optional(),inputDescription:U.string().optional().describe("the description that generated this cache"),targetSource:U.nativeEnum(Jn).optional(),targetUpdateTime:U.string().optional(),targetUpdateLoggerTags:U.record(U.string(),U.string()).optional(),cacheResolutionUpdateSource:U.string().optional(),cacheResolutionUpdateTime:U.string().optional(),cacheResolutionUpdateLoggerTags:U.record(U.string(),U.string()).optional(),memory:ql.optional()}).openapi({ref:"ElementTargetCache"});function Kl(r){return!!(r.serializedHtml||r.screenshotUrl||r.generatedSelectors||r.hybridSelector)}var tP=U.object({type:U.literal("description"),elementDescriptor:U.string().describe("Description of the element.")}).openapi({ref:"DescriptionTarget"}),rP=U.object({x:U.number(),y:U.number()}),nP=U.object({type:U.literal("coordinates"),pixels:rP}).openapi({ref:"CoordinatesTarget"});function Zn(r){return r.type==="description"}function rn(r){return r.type==="coordinates"}var Ft=U.discriminatedUnion("type",[tP,nP]).openapi({ref:"ElementTarget"});function kp(r){if(!r)return!1;switch(r.type){case"description":return!!r.elementDescriptor}return!0}function Bt(r){if(!r)return"";switch(r.type){case"description":return r.elementDescriptor;case"coordinates":return`x: ${r.pixels.x}, y: ${r.pixels.y}`}}function Yl(r){return ql.safeParse(r).success}import{v4 as _e}from"uuid";import*as v from"zod";import{extendZodWithOpenApi as dP}from"zod-openapi";import{z as se}from"zod";import{extendZodWithOpenApi as oP}from"zod-openapi";import{z as ts}from"zod";import kS from"zod";var es=kS.object({updatedAt:kS.coerce.date().optional()});var Up=ts.object({result:ts.boolean(),traceId:ts.string()}).array(),Fp=ts.object({type:ts.literal("GCS_TRACES"),traces:Up}),Bp=es.extend({memory:Fp.optional()});oP(se);var US=se.object({plan:se.string().optional(),evidence:se.string().optional(),thoughts:se.string(),result:se.boolean(),relevantElements:se.array(se.number()).optional(),updatedMemory:Up.optional()}),Mn=(o=>(o.CONTAINS="CONTAINS",o.STARTS_WITH="STARTS_WITH",o.EQUALS="EQUALS",o.EXISTS="EXISTS",o))(Mn||{});var iP=se.object({type:se.literal("ELEMENT_NAME"),negated:se.boolean().optional(),operation:se.nativeEnum(Mn),value:se.string()}).openapi({ref:"ElementNameAssertion"}),aP=se.object({type:se.literal("ELEMENT_STYLE"),negated:se.boolean().optional(),operation:se.nativeEnum(Mn),property:se.string(),value:se.string()}).openapi({ref:"ElementStyleAssertion"}),sP=se.object({type:se.literal("ELEMENT_CONTENT"),negated:se.boolean().optional(),operation:se.nativeEnum(Mn),value:se.string()}).openapi({ref:"ElementContentAssertion"}),lP=se.object({type:se.literal("ELEMENT_ATTRIBUTE"),negated:se.boolean().optional(),operation:se.nativeEnum(Mn),attr:se.string(),value:se.string()}).openapi({ref:"ElementAttributeValueAssertion"}),Go=(i=>(i.EXISTS="EXISTS",i.VISIBLE="VISIBLE",i.ENABLED="ENABLED",i.EDITABLE="EDITABLE",i.FOCUSED="FOCUSED",i))(Go||{}),cP=se.object({type:se.literal("ELEMENT_EXISTENCE"),negated:se.boolean().optional(),condition:se.nativeEnum(Go).describe("Treated as the element exists AND is also ...")}).openapi({ref:"ElementExistenceAssertion"}),FS=se.discriminatedUnion("type",[sP,lP,cP,iP,aP]).openapi({ref:"ManualElementAssertion"});var uP=se.object({type:se.literal("CONTENT"),negated:se.boolean().optional(),value:se.string()}).openapi({ref:"PageContentAssertion"}),BS=se.discriminatedUnion("type",[uP]).openapi({ref:"ManualPageAssertion"});import Jt from"zod";var zp=Jt.discriminatedUnion("type",[Jt.object({type:Jt.literal("SUBSTRING"),url:Jt.string()}),Jt.object({type:Jt.literal("GLOB"),glob:Jt.string()}),Jt.object({type:Jt.literal("REGEX"),regex:Jt.string()}),Jt.object({type:Jt.literal("DOMAIN"),domain:Jt.string()})]),rs=Jt.object({urlMatcher:zp,method:Jt.string().optional()});import{z as xe}from"zod";var ki=xe.object({url:xe.string(),method:xe.union([xe.literal("GET"),xe.literal("POST"),xe.literal("PUT"),xe.literal("DELETE"),xe.literal("PATCH")]),headers:xe.record(xe.string(),xe.string()).optional(),params:xe.record(xe.string(),xe.string()).optional(),body:xe.string().optional(),timeout:xe.number().int().optional().describe("Max seconds to wait for the request to complete")}),zS=xe.object({url:xe.string(),headers:xe.record(xe.string(),xe.string()).optional(),query:xe.string(),variables:xe.string().optional(),timeout:xe.number().int().optional().describe("Max seconds to wait for the request to complete")}),Xl=xe.object({code:xe.string(),fragment:xe.boolean().optional().describe("Agents should not touch this unless explicitly told to"),environment:xe.union([xe.literal("NODE"),xe.literal("BROWSER")]).optional().describe("default NODE, Agents default to using node unless it is necessary to use browser"),timeout:xe.number().int().max(60).optional().describe("Max seconds for the code to complete")});var ze=(W=>(W.AI_EXTRACT="AI_EXTRACT",W.AI_ASSERTION="AI_ASSERTION",W.AUTH_LOAD="AUTH_LOAD",W.AUTH_SAVE="AUTH_SAVE",W.BLUR="BLUR",W.CAPTCHA="CAPTCHA",W.CLICK="CLICK",W.COOKIE="COOKIE",W.COPY="COPY",W.DIALOG="DIALOG",W.DRAG="DRAG",W.ELEMENT_CHECK="ELEMENT_CHECK",W.FILE_UPLOAD="FILE_UPLOAD",W.FOCUS="FOCUS",W.GO_BACK="GO_BACK",W.GO_FORWARD="GO_FORWARD",W.HOVER="HOVER",W.JAVASCRIPT="JAVASCRIPT",W.LOCAL_STORAGE="LOCAL_STORAGE",W.MOUSE_DRAG="MOUSE_DRAG",W.NAVIGATE="NAVIGATE",W.NEW_TAB="NEW_TAB",W.PAGE_CHECK="PAGE_CHECK",W.PASTE="PASTE",W.PRESS="PRESS",W.KEY_DOWN="KEY_DOWN",W.KEY_UP="KEY_UP",W.REFRESH="REFRESH",W.REQUEST="REQUEST",W.GRAPHQL_REQUEST="GRAPHQL_REQUEST",W.SCROLL_DOWN="SCROLL_DOWN",W.SCROLL_UP="SCROLL_UP",W.SCROLL_LEFT="SCROLL_LEFT",W.SCROLL_RIGHT="SCROLL_RIGHT",W.SELECT_OPTION="SELECT_OPTION",W.SWITCH_TAB="TAB",W.TYPE="TYPE",W.VISUAL_DIFF="VISUAL_DIFF",W.WAIT="WAIT",W.WAIT_FOR_URL="WAIT_FOR_URL",W.REGISTER_REQUEST_LISTENER="REGISTER_REQUEST_LISTENER",W.AWAIT_LISTENER="AWAIT_LISTENER",W.RECORD_REQUESTS="RECORD_REQUESTS",W.GET_RECORDED_REQUESTS="GET_RECORDED_REQUESTS",W.SET_HEADER="SET_HEADER",W.MOCK_ROUTE="MOCK_ROUTE",W.REMOVE_ROUTE_MOCK="REMOVE_ROUTE_MOCK",W.OFFLINE_MODE="OFFLINE_MODE",W.SUCCESS="SUCCESS",W))(ze||{});dP(v);var Q=v.object({thoughts:v.string().optional(),id:v.string().uuid().describe("unique identifier to this step, used for step cache")}),Tr=v.object({useSelector:v.boolean().optional(),force:v.boolean().optional(),disableCache:v.boolean().optional().describe("disable element caching for this step"),iframeUrl:v.string().optional().describe("url or url regex for the iframe")}).openapi({ref:"CommonTargetingOptions"}),mr=es.extend({target:Qn}).optional().openapi({ref:"SingleTargetCache"});function HS(r){return mr.safeParse(r).success}var Ql=v.object({loadTimeout:v.number().int().max(60).optional().describe("Max seconds for the page to load")}),pP=Q.merge(Ql).merge(v.object({type:v.literal("NAVIGATE"),url:v.string()})).openapi({ref:"NavigateCommand"}),Zl=Tr.merge(v.object({cache:mr})),Ui=Q.merge(Zl.merge(v.object({target:Ft.optional(),type:v.literal("SCROLL_UP"),deltaY:v.number().optional()}))).openapi({ref:"ScrollUpCommand"}),Fi=Q.merge(Zl.merge(v.object({target:Ft.optional(),type:v.literal("SCROLL_DOWN"),deltaY:v.number().optional()}))).openapi({ref:"ScrollDownCommand"}),Bi=Q.merge(Zl.merge(v.object({target:Ft.optional(),type:v.literal("SCROLL_LEFT"),deltaX:v.number().optional()}))).openapi({ref:"ScrollLeftCommand"}),zi=Q.merge(Zl.merge(v.object({target:Ft.optional(),type:v.literal("SCROLL_RIGHT"),deltaX:v.number().optional()}))).openapi({ref:"ScrollRightCommand"}),pq=v.discriminatedUnion("type",[Ui,Fi,Bi,zi]).openapi({ref:"AllScrollCommands"}),mP=Q.merge(v.object({type:v.literal("DIALOG"),action:v.union([v.literal("ACCEPT"),v.literal("DISMISS")])})).openapi({ref:"DialogCommand"}),hP=Q.merge(v.object({type:v.literal("WAIT"),delay:v.number()})).openapi({ref:"WaitCommand"}),gP=v.object({caseInsensitive:v.boolean().optional().describe("Whether to ignore case when matching the URL"),negated:v.boolean().optional().describe("Wait for the URL to NOT match the provided matcher instead."),timeout:v.number().int().optional().describe("Max seconds to wait for the URL to match")}),GS=Q.extend({type:v.literal("WAIT_FOR_URL"),matcher:zp}).merge(gP).openapi({ref:"WaitUrlCommand"}),fP=Q.merge(Ql).merge(v.object({type:v.literal("REFRESH")})).openapi({ref:"RefreshCommand"}),SP=Q.merge(v.object({type:v.literal("GO_BACK")})).openapi({ref:"GoBackCommand"}),yP=Q.merge(v.object({type:v.literal("GO_FORWARD")})).openapi({ref:"GoForwardCommand"}),EP=Q.extend({type:v.literal("AUTH_SAVE")}).openapi({ref:"AuthSaveCommand"}),TP=Q.extend({type:v.literal("AUTH_LOAD"),storageState:v.string().describe("JSON string auth state. Leave blank or set to the empty string to clear all existing authentication.")}).openapi({ref:"AuthLoadCommand"}),Hp=Q.merge(Tr).extend({type:v.literal("CAPTCHA")}).openapi({ref:"CaptchaCommand"}),bP=Q.extend({type:v.literal("COPY"),value:v.string()}).openapi({ref:"CopyCommand"}),vP=Q.extend({type:v.literal("PASTE")}).openapi({ref:"PasteCommand"}),jS=Q.merge(Xl).extend({type:v.literal("JAVASCRIPT")}).openapi({ref:"JavaScriptCommand"}),os=Q.merge(Tr).extend({type:v.literal("CLICK"),target:Ft,doubleClick:v.boolean().optional(),rightClick:v.boolean().optional(),waitForDownload:v.boolean().optional().describe("Wait for the click to trigger a file download and for the file download to complete."),delayMs:v.number().optional(),downloadTimeoutMs:v.number().optional(),cache:mr,relativePosition:v.object({x:v.number(),y:v.number()}).optional()}).openapi({ref:"ClickCommand"}),Gp=es.extend({fromTarget:Qn.optional(),toTarget:Qn.optional()}),is=Q.merge(Tr).merge(v.object({type:v.literal("DRAG"),fromTarget:Ft,toTarget:Ft,steps:v.number().optional(),hoverSeconds:v.number().optional().describe("Seconds to hover the object before dropping"),cache:Gp.optional()})).openapi({ref:"DragCommand"}),as=Q.merge(Tr).merge(v.object({type:v.literal("MOUSE_DRAG"),target:Ft.optional(),deltaX:v.string().describe("pixels to move horizontally, can be template"),deltaY:v.string().describe("pixels to move vertically, can be template"),steps:v.number().optional(),cache:mr})).openapi({ref:"MouseDragCommand"}),ss=Q.merge(Tr).merge(v.object({type:v.literal("HOVER"),target:Ft,cache:mr})).openapi({ref:"HoverCommand"}),ls=Q.merge(Tr).merge(v.object({type:v.literal("FOCUS"),target:Ft,cache:mr})).openapi({ref:"FocusCommand"}),cs=Q.merge(Tr).extend({type:v.literal("BLUR"),target:Ft.optional(),cache:mr}).openapi({ref:"BlurCommand"}),AP=v.object({type:v.literal("URL"),url:v.string()}).describe("Accessible link to the file, either public http or local file://").openapi({ref:"UrlSource"}),RP=v.object({type:v.literal("USER_FILE"),name:v.string()}).describe("Accessible link to the file, references the google cloud file").openapi({ref:"UploadedFileSource"}),wP=Q.extend({type:v.literal("FILE_UPLOAD"),fileSource:v.discriminatedUnion("type",[AP,RP]),filename:v.string().optional()}).openapi({ref:"FileUploadCommand"}),jp=v.discriminatedUnion("type",[v.object({type:v.literal("VALUE"),value:v.string()}),v.object({type:v.literal("LABEL"),label:v.string()}),v.object({type:v.literal("INDEX"),index:v.coerce.string()})]),us=Q.merge(Tr).extend({type:v.literal("SELECT_OPTION"),target:Ft,cache:mr,choice:jp.describe("new field for selecting options, optional for backcompat")}).openapi({ref:"SelectOptionCommand"}),Vp=v.union([v.literal("MULTIMODAL"),v.literal("VISION_ONLY")]),ec=Q.merge(v.object({type:v.literal("AI_ASSERTION"),assertion:v.string(),disableCache:v.boolean().optional(),iframeUrl:v.string().optional(),contextChoice:Vp.optional(),timeout:v.number().int().optional().describe("Max seconds to wait for assertion to be true"),cache:Bp.optional()})).openapi({ref:"AIAssertionCommand"}),nn=5,$p=600,Hi=Q.merge(Tr).extend({type:v.literal("ELEMENT_CHECK"),target:Ft,assertion:FS,cache:mr.or(Bp).optional(),timeout:v.number().int().min(0).max($p).optional().describe("max seconds to wait for the assertion to be true")}).openapi({ref:"ElementAssertionCommand"}),VS=Q.extend({type:v.literal("PAGE_CHECK"),assertion:BS,iframeUrl:v.string().optional().describe("url or url regex for the iframe"),timeout:v.number().int().min(0).max($p).optional().describe("max seconds to wait for the assertion to be true")}).openapi({ref:"PageAssertionCommand"}),$S=Q.merge(v.object({type:v.literal("AI_EXTRACT"),goal:v.string(),schema:v.string().optional(),envKey:v.string().optional(),disableCache:v.boolean().optional(),iframeUrl:v.string().optional()})).openapi({ref:"AIExtractCommand"}),CP=v.object({clearContent:v.boolean().optional(),forceClearContent:v.boolean().optional(),delay:v.number().min(0).max(1e3).optional().describe("Delay between each press in milliseconds."),force:v.boolean().optional(),pressEnter:v.boolean().optional(),relativePosition:v.object({x:v.number(),y:v.number()}).optional()}),WS=25,ds=Q.merge(Tr).merge(CP).extend({type:v.literal("TYPE"),target:Ft.optional(),value:v.string(),cache:mr}).openapi({ref:"TypeCommand"}),xP=Q.merge(v.object({type:v.literal("PRESS"),value:v.string(),repeat:v.number().optional(),convertMeta:v.boolean().optional(),delayMs:v.number().optional()})).openapi({ref:"PressCommand"}),_P=Q.merge(v.object({type:v.literal("KEY_DOWN"),value:v.string(),convertMeta:v.boolean().optional()})).openapi({ref:"KeyDownCommand"}),IP=Q.merge(v.object({type:v.literal("KEY_UP"),value:v.string(),convertMeta:v.boolean().optional()})).openapi({ref:"KeyUpCommand"}),MP=v.object({type:v.literal("SUBSTRING"),substring:v.string()}),PP=v.object({type:v.literal("REGEX"),pattern:v.string()}),OP=v.object({type:v.literal("INDEX"),index:v.coerce.string()}),LP=v.discriminatedUnion("type",[MP,PP,OP]),NP=Q.merge(Ql).merge(v.object({type:v.literal("TAB"),action:LP})).openapi({ref:"TabCommand"}),qS=Q.merge(Ql).merge(v.object({type:v.literal("NEW_TAB"),url:v.string()})).openapi({ref:"NewTabCommand"}),DP=Q.merge(v.object({type:v.literal("COOKIE"),value:v.string()})).openapi({ref:"CookieCommand"}),kP=Q.merge(v.object({type:v.literal("LOCAL_STORAGE"),key:v.string(),value:v.string()})).openapi({ref:"LocalStorageCommand"}),UP=Q.extend({type:v.literal("REQUEST")}).merge(ki).openapi({ref:"RequestCommand"}),FP=Q.extend({type:v.literal("GRAPHQL_REQUEST")}).merge(zS).openapi({ref:"GraphQLRequestCommand"}),BP=Q.merge(v.object({type:v.literal("SUCCESS"),condition:ec.optional()})).openapi({ref:"SuccessCommand"}),KS=Q.merge(v.object({type:v.literal("FAILURE")})).openapi({ref:"FailureCommand"}),zP=v.object({data:v.string().describe("location at which to find a jpg"),width:v.number(),height:v.number()}),ps=Q.merge(Tr).merge(v.object({type:v.literal("VISUAL_DIFF"),threshold:v.number().optional().describe("default 0.1"),target:Ft.optional(),screenshot:zP.optional(),cache:mr})).openapi({ref:"VisualDiffCommand"}),HP=Q.merge(v.object({type:v.literal("REGISTER_REQUEST_LISTENER"),requestMatcher:rs,key:v.string()})).openapi({ref:"RegisterRequestListenerCommand"}),GP=Q.merge(v.object({type:v.literal("AWAIT_LISTENER"),key:v.string(),timeout:v.number().optional().describe("timeout")})).openapi({ref:"WaitForListenerCommand"}),jP=Q.merge(v.object({type:v.literal("RECORD_REQUESTS"),requestMatcher:rs,key:v.string()})).openapi({ref:"RecordRequestsCommand"}),VP=Q.merge(v.object({type:v.literal("GET_RECORDED_REQUESTS"),key:v.string()})).openapi({ref:"GetRecordedRequestsCommand"}),$P=Q.merge(v.object({type:v.literal("SET_HEADER"),name:v.string(),value:v.string(),requestMatcher:rs.optional()})).openapi({ref:"SetHeaderCommand"}),WP=Q.merge(v.object({type:v.literal("MOCK_ROUTE"),requestMatcher:rs,responseGenerator:v.string().describe("JavaScript code to generate a response"),fetchOriginalResponse:v.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:v.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"})),qP=Q.merge(v.object({type:v.literal("REMOVE_ROUTE_MOCK"),key:v.string().optional().describe("Key of the mock to remove. If not set, all route mocks will be removed.")}).openapi({ref:"RemoveRouteMockCommandOptions"})),KP=Q.merge(v.object({type:v.literal("OFFLINE_MODE"),enable:v.boolean()})).openapi({ref:"OfflineModeCommand"}),YP=v.discriminatedUnion("type",[os,ds,xP,_P,IP,us,pP,Fi,Ui,ec,SP,ss,hP]),Wp=v.discriminatedUnion("type",[...YP.options,BP]),qp=v.discriminatedUnion("type",[...Wp.options,jS,Hi,VS,qS,GS,$S]),XP=v.discriminatedUnion("type",[$S,TP,EP,Hp,DP,bP,mP,is,Hi,wP,yP,jS,kP,as,qS,VS,vP,fP,UP,FP,Bi,zi,NP,ps,ls,cs,GS,HP,GP,jP,VP,$P,WP,qP,KP]),Gi=v.discriminatedUnion("type",[...Wp.options,...XP.options]).openapi({ref:"Command"}),tc=v.discriminatedUnion("type",[...Wp.options,KS]),mq=v.discriminatedUnion("type",[...qp.options,KS]);function Pn(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:_e(),type:r};break;case"AUTH_LOAD":{e={id:_e(),type:r,storageState:""};break}case"AI_EXTRACT":e={id:_e(),type:r,goal:""};break;case"DIALOG":e={id:_e(),type:r,action:"DISMISS"};break;case"DRAG":e={id:_e(),type:r,fromTarget:{type:"description",elementDescriptor:""},toTarget:{type:"description",elementDescriptor:""}};break;case"MOUSE_DRAG":e={id:_e(),type:r,deltaX:"0",deltaY:"0",steps:1};break;case"WAIT_FOR_URL":e={id:_e(),type:r,matcher:{type:"SUBSTRING",url:""}};break;case"WAIT":e={id:_e(),type:r,delay:1};break;case"BLUR":e={id:_e(),type:r};break;case"HOVER":case"FOCUS":case"CLICK":e={id:_e(),type:r,target:{type:"description",elementDescriptor:""}};break;case"COOKIE":case"PRESS":case"COPY":case"TYPE":e={id:_e(),type:r,value:"",clearContent:!0};break;case"KEY_DOWN":case"KEY_UP":e={id:_e(),type:r,value:""};break;case"SELECT_OPTION":e={id:_e(),type:r,target:{type:"description",elementDescriptor:""},choice:{type:"VALUE",value:""}};break;case"NAVIGATE":case"NEW_TAB":return{id:_e(),type:r,url:""};case"TAB":e={id:_e(),type:r,action:{type:"SUBSTRING",substring:""}};break;case"REQUEST":e={id:_e(),type:r,url:"",method:"GET"};break;case"GRAPHQL_REQUEST":e={id:_e(),type:r,url:"",query:""};break;case"LOCAL_STORAGE":e={id:_e(),type:r,key:"",value:""};break;case"JAVASCRIPT":e={id:_e(),type:r,code:""};break;case"AI_ASSERTION":e={id:_e(),type:r,assertion:""};break;case"FILE_UPLOAD":{e={id:_e(),type:r,fileSource:{type:"URL",url:""}};break}case"ELEMENT_CHECK":{e={id:_e(),type:r,target:{type:"description",elementDescriptor:""},assertion:{type:"ELEMENT_EXISTENCE",condition:"EXISTS"}};break}case"PAGE_CHECK":{e={id:_e(),type:r,assertion:{type:"CONTENT",value:""}};break}case"REGISTER_REQUEST_LISTENER":{e={id:_e(),type:r,requestMatcher:{urlMatcher:{type:"REGEX",regex:""}},key:""};break}case"AWAIT_LISTENER":{e={id:_e(),type:r,key:""};break}case"RECORD_REQUESTS":{e={id:_e(),type:r,requestMatcher:{urlMatcher:{type:"REGEX",regex:""}},key:""};break}case"GET_RECORDED_REQUESTS":{e={id:_e(),type:r,key:""};break}case"SET_HEADER":{e={id:_e(),type:r,name:"",value:""};break}case"MOCK_ROUTE":{e={id:_e(),type:r,requestMatcher:{urlMatcher:{type:"REGEX",regex:""}},responseGenerator:""};break}case"REMOVE_ROUTE_MOCK":{e={id:_e(),type:r};break}case"OFFLINE_MODE":{e={id:_e(),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 YS(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 JP}from"zod";var yq=JP.discriminatedUnion("type",[cs,Hp,os,is,ls,ss,as,Ui,Fi,Bi,zi,us,ds,ps,Hi]);function XS(r){return["AI_ASSERTION","ELEMENT_CHECK","PAGE_CHECK"].includes(r)}import{z as QP}from"zod";import{z as eo}from"zod";function ms(r){return eo.object({key:eo.string(),testId:eo.string().optional(),moduleId:eo.string().optional(),organizationId:eo.string(),value:r})}function hs(r){return ms(r).extend({uniqueKey:eo.string()})}function rc(r){return eo.record(eo.string(),hs(r))}var Qt={type:!0,cache:!0},On=QP.discriminatedUnion("type",[ec.pick(Qt),cs.pick(Qt),os.pick(Qt),is.pick(Qt),Hi.pick(Qt),ls.pick(Qt),ss.pick(Qt),as.pick(Qt),Ui.pick(Qt),Fi.pick(Qt),Bi.pick(Qt),zi.pick(Qt),us.pick(Qt),ds.pick(Qt),ps.pick(Qt)]),nc=Object.values(ze).filter(r=>On.options.some(e=>e.shape.type.safeParse(r).success));Gi.options.forEach(r=>{if("target"in r.shape&&!nc.includes(r.shape.type.value))throw new Error(`Command ${r.shape.type.value} has a target but no cache`)});function JS(r){return nc.includes(r.type)}var QS=ms(On),ZS=hs(On),Cq=rc(On);import{v4 as Rt}from"uuid";import{z as _}from"zod";var ty=Symbol("Let zodToJsonSchema decide on which parser to use");var ey={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"},ry=r=>typeof r=="string"?{...ey,name:r}:{...ey,...r};var ny=r=>{let e=ry(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 Kp(r,e,t,n){n?.errorMessages&&t&&(r.errorMessage={...r.errorMessage,[e]:t})}function Se(r,e,t,n,o){r[e]=t,Kp(r,e,n,o)}var oc=(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 fe}from"zod";function Ke(r){if(r.target!=="openAi")return{};let e=[...r.basePath,r.definitionPath,r.openAiAnyTypeName];return r.flags.hasReferencedOpenAiAnyType=!0,{$ref:r.$refStrategy==="relative"?oc(e,r.currentPath):e.join("/")}}import{ZodFirstPartyTypeKind as ZP}from"zod";function oy(r,e){let t={type:"array"};return r.type?._def&&r.type?._def?.typeName!==ZP.ZodAny&&(t.items=Z(r.type._def,{...e,currentPath:[...e.currentPath,"items"]})),r.minLength&&Se(t,"minItems",r.minLength.value,r.minLength.message,e),r.maxLength&&Se(t,"maxItems",r.maxLength.value,r.maxLength.message,e),r.exactLength&&(Se(t,"minItems",r.exactLength.value,r.exactLength.message,e),Se(t,"maxItems",r.exactLength.value,r.exactLength.message,e)),t}function iy(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?Se(t,"minimum",n.value,n.message,e):Se(t,"exclusiveMinimum",n.value,n.message,e):(n.inclusive||(t.exclusiveMinimum=!0),Se(t,"minimum",n.value,n.message,e));break;case"max":e.target==="jsonSchema7"?n.inclusive?Se(t,"maximum",n.value,n.message,e):Se(t,"exclusiveMaximum",n.value,n.message,e):(n.inclusive||(t.exclusiveMaximum=!0),Se(t,"maximum",n.value,n.message,e));break;case"multipleOf":Se(t,"multipleOf",n.value,n.message,e);break}return t}function ay(){return{type:"boolean"}}function ic(r,e){return Z(r.type._def,e)}var sy=(r,e)=>Z(r.innerType._def,e);function Yp(r,e,t){let n=t??e.dateStrategy;if(Array.isArray(n))return{anyOf:n.map((o,i)=>Yp(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 eO(r,e)}}var eO=(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":Se(t,"minimum",n.value,n.message,e);break;case"max":Se(t,"maximum",n.value,n.message,e);break}return t};function ly(r,e){return{...Z(r.innerType._def,e),default:r.defaultValue()}}function cy(r,e){return e.effectStrategy==="input"?Z(r.schema._def,e):Ke(e)}function uy(r){return{type:"string",enum:Array.from(r.values)}}var tO=r=>"type"in r&&r.type==="string"?!1:"allOf"in r;function dy(r,e){let t=[Z(r.left._def,{...e,currentPath:[...e.currentPath,"allOf","0"]}),Z(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(tO(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 py(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 gs}from"zod";var Xp,Gr={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:()=>(Xp===void 0&&(Xp=RegExp("^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$","u")),Xp),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 ac(r,e){let t={type:"string"};if(r.checks)for(let n of r.checks)switch(n.kind){case"min":Se(t,"minLength",typeof t.minLength=="number"?Math.max(t.minLength,n.value):n.value,n.message,e);break;case"max":Se(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":jr(t,"email",n.message,e);break;case"format:idn-email":jr(t,"idn-email",n.message,e);break;case"pattern:zod":Zt(t,Gr.email,n.message,e);break}break;case"url":jr(t,"uri",n.message,e);break;case"uuid":jr(t,"uuid",n.message,e);break;case"regex":Zt(t,n.regex,n.message,e);break;case"cuid":Zt(t,Gr.cuid,n.message,e);break;case"cuid2":Zt(t,Gr.cuid2,n.message,e);break;case"startsWith":Zt(t,RegExp(`^${Jp(n.value,e)}`),n.message,e);break;case"endsWith":Zt(t,RegExp(`${Jp(n.value,e)}$`),n.message,e);break;case"datetime":jr(t,"date-time",n.message,e);break;case"date":jr(t,"date",n.message,e);break;case"time":jr(t,"time",n.message,e);break;case"duration":jr(t,"duration",n.message,e);break;case"length":Se(t,"minLength",typeof t.minLength=="number"?Math.max(t.minLength,n.value):n.value,n.message,e),Se(t,"maxLength",typeof t.maxLength=="number"?Math.min(t.maxLength,n.value):n.value,n.message,e);break;case"includes":{Zt(t,RegExp(Jp(n.value,e)),n.message,e);break}case"ip":{n.version!=="v6"&&jr(t,"ipv4",n.message,e),n.version!=="v4"&&jr(t,"ipv6",n.message,e);break}case"base64url":Zt(t,Gr.base64url,n.message,e);break;case"jwt":Zt(t,Gr.jwt,n.message,e);break;case"cidr":{n.version!=="v6"&&Zt(t,Gr.ipv4Cidr,n.message,e),n.version!=="v4"&&Zt(t,Gr.ipv6Cidr,n.message,e);break}case"emoji":Zt(t,Gr.emoji(),n.message,e);break;case"ulid":{Zt(t,Gr.ulid,n.message,e);break}case"base64":{switch(e.base64Strategy){case"format:binary":{jr(t,"binary",n.message,e);break}case"contentEncoding:base64":{Se(t,"contentEncoding","base64",n.message,e);break}case"pattern:zod":{Zt(t,Gr.base64,n.message,e);break}}break}case"nanoid":Zt(t,Gr.nanoid,n.message,e);case"toLowerCase":case"toUpperCase":case"trim":break;default:}return t}function Jp(r,e){return e.patternStrategy==="escape"?nO(r):r}var rO=new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789");function nO(r){let e="";for(let t=0;t<r.length;t++)rO.has(r[t])||(e+="\\"),e+=r[t];return e}function jr(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}}})):Se(r,"format",e,t,n)}function Zt(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:my(e,n),...t&&n.errorMessages&&{errorMessage:{pattern:t}}})):Se(r,"pattern",my(e,n),t,n)}function my(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
|
|
5
5
|
]))`;continue}else if(n[c]==="$"){o+=`($|(?=[\r
|
|
6
6
|
]))`;continue}}if(t.s&&n[c]==="."){o+=a?`${n[c]}\r
|
|
@@ -24,8 +24,8 @@ ${this.decisions.map(e=>e.toString()).join(`
|
|
|
24
24
|
`);process.stderr.write(`${o}
|
|
25
25
|
`),globalThis.console=e}}var mt=" ".repeat(6);function Lb(r,e="",t=!1){let n=process.stdout?.columns||process.stderr?.columns||80,o=Math.max(n-e.length,20),i=r.split(`
|
|
26
26
|
`),a=[];for(let l of i)if(t){let c=l;for(;c.length>o;){let u=c.slice(0,o+1).lastIndexOf(" "),d=u>-1?u:o;a.push(e+c.slice(0,d)),c=c.slice(d).trimStart()}a.push(e+c)}else{let c=l.split(" "),s="";for(let u of c){if(!s.length){s=u;continue}let d=`${s} ${u}`;d.length<=o?s=d:(a.push(e+s),s=u)}a.push(e+s)}return a.join(`
|
|
27
|
-
`)}import Ak from"fetch-retry";import Rk from"os";import Nb,{multistream as wk}from"pino";import Ck from"pino-pretty";import xk from"pino-std-serializers";var oa=new Map,_k=!0,Db="Log throttle exceeded",Ik=100,Mk=5e3,Pk=Ak(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}}),dh=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??Rk.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=_k?Nb(a):Nb(a,wk([{stream:Ck({colorize:!0})}]))}getLevel(){return jc[this.minLevelValue]}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 Pk(this.site,{method:"POST",headers:{"Content-Type":"application/json","signoz-access-token":"CumAaTMUcwjt05OddAmefKgshbhfRmWxzxih"},body:na(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===Db)return!0;let t=Date.now();return t-this.lastWindowStart>Mk&&(this.logsInCurrentWindow=0,this.droppedLogsInWindow&&this.log("error",void 0,Db),this.droppedLogsInWindow=!1,this.lastWindowStart=t),this.logsInCurrentWindow<Ik?(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(Fs[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=xk.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:wT({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,oa.set("app",this),oa.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=jc[e]):(this.minLevelValue=Fs[e],this.consoleLogger.level=e)}enableConsoleLogs(){this.disableConsoleLogs=!1}},Xc=({app:r,hostname:e,disableConsoleLogs:t})=>(oa.has(r)||oa.set(r,new dh({bindings:{app:r},hostname:e,disableConsoleLogs:t})),oa.get(r));async function Ub(){await Promise.all([...oa.values()].map(r=>r.flush()))}import{hostname as Ok}from"os";var ne=Xc({app:"cli",hostname:Ok(),disableConsoleLogs:!0}).child({cliVersion:"2.20.
|
|
28
|
-
`);console.warn(n),r.warn({stack:n,time:e},"NodeJS event loop blocked")},{threshold:1e3,trimFalsePositives:!0})}function Vk(){process.on("SIGINT",()=>{if("_getActiveHandles"in process){let r=process._getActiveHandles();console.log("Active handles:",r.map(e=>e.constructor?.name))}Gk(),setImmediate(()=>{setTimeout(()=>{process.exit(1)},2e3).unref()})})}import{randomUUID as bW}from"crypto";import DI from"body-parser";import d$ from"cors";import p$ from"dedent";import{Router as D0}from"express";import rr from"fs";import{globSync as k0}from"glob";import _t from"path";import Mh from"fs";import{z as Qk}from"zod";var B="v1",hh="cli",ai="2.20.
|
|
27
|
+
`)}import Ak from"fetch-retry";import Rk from"os";import Nb,{multistream as wk}from"pino";import Ck from"pino-pretty";import xk from"pino-std-serializers";var oa=new Map,_k=!0,Db="Log throttle exceeded",Ik=100,Mk=5e3,Pk=Ak(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}}),dh=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??Rk.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=_k?Nb(a):Nb(a,wk([{stream:Ck({colorize:!0})}]))}getLevel(){return jc[this.minLevelValue]}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 Pk(this.site,{method:"POST",headers:{"Content-Type":"application/json","signoz-access-token":"CumAaTMUcwjt05OddAmefKgshbhfRmWxzxih"},body:na(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===Db)return!0;let t=Date.now();return t-this.lastWindowStart>Mk&&(this.logsInCurrentWindow=0,this.droppedLogsInWindow&&this.log("error",void 0,Db),this.droppedLogsInWindow=!1,this.lastWindowStart=t),this.logsInCurrentWindow<Ik?(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(Fs[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=xk.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:wT({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,oa.set("app",this),oa.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=jc[e]):(this.minLevelValue=Fs[e],this.consoleLogger.level=e)}enableConsoleLogs(){this.disableConsoleLogs=!1}},Xc=({app:r,hostname:e,disableConsoleLogs:t})=>(oa.has(r)||oa.set(r,new dh({bindings:{app:r},hostname:e,disableConsoleLogs:t})),oa.get(r));async function Ub(){await Promise.all([...oa.values()].map(r=>r.flush()))}import{hostname as Ok}from"os";var ne=Xc({app:"cli",hostname:Ok(),disableConsoleLogs:!0}).child({cliVersion:"2.20.3"});var Nk=5;async function Qc({getResults:r,checkDone:e,name:t,timeoutMs:n=18e5}){let o=Date.now(),i=0;for(;Date.now()-o<n;){let a;i>Nk&&(T.error(`Failed to fetch ${t} status too many times.`),process.exit(1));try{a=await r(),i=0}catch(s){i++,ne.warn({err:s},"Failed to fetch run status, retrying..."),T.warn({err:s},"Failed to fetch run status, retrying..."),await new Promise(u=>setTimeout(u,1500*i));continue}if(e(a))return a;let c=Math.max(1e4,Math.floor(n/100));await new Promise(s=>setTimeout(s,c))}T.error(`Timeout elapsed waiting for ${t} to complete (${Math.floor(n/1e3)}s).`),process.exit(1)}function ia({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 Ob(()=>{if(c.forEach(u=>{T.log(""),o(u)}),c.length){T.log("");let u=c.length===1?"":"s";T.error(`${c.length} ${t}${u} failed:`),c.forEach(d=>{T.dimmed(n(d))})}if(s.length){T.log("");let u=s.length===1?"":"s";T.warn(`${s.length} ${t}${u} cancelled:`),s.forEach(d=>{T.dimmed(n(d))})}if(a.length){T.log("");let u=a.length===1?"":"s";T.success(`${a.length} ${t}${u} passed:`),a.forEach(d=>{T.dimmed(n(d))})}if(l.length){T.log("");let u=l.length===1?"":"s";T.warn(`${l.length} quarantined ${t}${u} failed:`),l.forEach(d=>{T.dimmed(n(d))})}if(i.length){T.log("");let u=i.length===1?"":"s";T.warn(`${i.length} quarantined ${t}${u} passed:`),i.forEach(d=>{T.dimmed(n(d))})}T.log(""),T.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 Zc=(r,e)=>{if(!r.failureDetails||!r.failureReason)return;let t=lc[r.failureDetails?.classification?.reason||r.failureReason],n=r.failureDetails?.classification?.summary||ji[r.failureReason],o=r.failureDetails.classification?.rootCause;if(T.error(e),o){T.log(`${mt}- Error type: ${pn.dim(t)}`);let i="- Root cause analysis:",a=Lb(`${i} ${o}`,`${mt} `,!1),l=a.indexOf(":");T.log(`${mt}${i} ${pn.dim(a.slice(l+1))}`)}else T.log(`${mt}Reason: ${pn.red(t)}`),T.log(`${mt}Description: ${pn.red(n)}`)},Gs=({status:r,testLogRef:e,getRunningTestsCount:t,getTotalTestsCount:n,additionalText:o})=>{r=r.toUpperCase();let i=r,a;r.includes("FAIL")?(i=pn.bgRed.white("FAIL"),a=3):r.includes("PASS")?(i=pn.bgGreen.white("PASS"),a=3):r.includes("START")?(i=pn.bgBlue.white("START"),a=2):r.includes("CANCEL")?(i=pn.bgRgb(191,68,11).white("CANCEL"),a=1):r.includes("RETRY")?(i=pn.bgRgb(191,68,11).white("RETRY"),a=2):r.includes("RUN")||r.includes("PROG")?(i=pn.bgMagenta.white("RUNNING"),a=0):(T.warn(`Unknown status tried to be logged in run test locally: ${r}`),a=0),Lk||(i=`${i}`),T.log(`${i}${" ".repeat(a)} ${e} ${o?`${o} `:""}(${t()}/${n()})`)};import Dk from"fs";import{tmpdir as kk}from"os";import Uk from"path";import{registry as js}from"playwright-core/lib/server";import Fb from"proper-lockfile";var Bb=Uk.join(kk(),"momenticBrowserInstallation");var ph=["chrome","chromium","chrome-for-testing"],Fk={Chromium:"chromium","Google Chrome":"chrome","Chrome for Testing":"chrome-for-testing"},zb={chrome:"chrome",chromium:"chromium","chrome-for-testing":"chromium-headless-shell"};function Hb(r){let e=zb[Fk[r]??""]??"",t=js.findExecutable(e);return!t||t.installType==="none"?!1:mh(t)}function mh(r){let e=r.executablePath();return Dk.existsSync(e)}function Bk(r,e){let t=zb[r];if(!t)throw new Error(`Requested install of unknown browser type ${r}`);let n=js.findExecutable(t);if(!n||n.installType==="none")throw new Error(`Requested install of unknown browser type ${r}`);if(!(!e&&mh(n)))return n}async function zk({browser:r,force:e}){let t=Bk(r,e);if(!t){T.info(`Browser '${r}' is already installed, skipping...`);return}T.info(`Installing browser '${r}'...`);try{await js.installDeps([t],!1),await js.install([t],!1)}catch(n){if(n.message.includes("Lock file is already being held")){T.warn("Another process is installing Playwright browsers. Waiting for completion before proceeding..");let o=js.findExecutable(r),i=5*60*1e3,a=Date.now();for(;Date.now()-a<i&&!mh(o);)T.info("Waiting for browser to finish installing..."),await new Promise(l=>setTimeout(l,5e3))}else throw n}}async function Gb({rawBrowsers:r,force:e=!1,all:t=!1}){let n=t?ph:Array.from(new Set(r));try{await Fb.lock(Bb,{stale:1e3*60*5,update:1e3*60,realpath:!1,retries:{retries:30,factor:2,maxTimeout:15e3,minTimeout:500}})}catch(i){T.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 zk({browser:i,force:e})}catch(a){o=a,T.error(`Failed to install the ${i} browser: ${a}`)}}finally{await Fb.unlock(Bb,{realpath:!1})}if(o)throw o}import Hk from"blocked-at";import Gk from"why-is-node-running";function jb(r){jk(r),Vk()}function jk(r){Hk((e,t)=>{console.warn(`Detected the NodeJS event loop was blocked for ${e.toFixed(0)}ms. This can cause the CLI to hang.`);let n=t.join(`
|
|
28
|
+
`);console.warn(n),r.warn({stack:n,time:e},"NodeJS event loop blocked")},{threshold:1e3,trimFalsePositives:!0})}function Vk(){process.on("SIGINT",()=>{if("_getActiveHandles"in process){let r=process._getActiveHandles();console.log("Active handles:",r.map(e=>e.constructor?.name))}Gk(),setImmediate(()=>{setTimeout(()=>{process.exit(1)},2e3).unref()})})}import{randomUUID as bW}from"crypto";import DI from"body-parser";import d$ from"cors";import p$ from"dedent";import{Router as D0}from"express";import rr from"fs";import{globSync as k0}from"glob";import _t from"path";import Mh from"fs";import{z as Qk}from"zod";var B="v1",hh="cli",ai="2.20.3";var ho=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 Ot(r){return Math.ceil(gh(r)/ho)}function gh(r){let e=0;if(typeof r=="string"){let t=r;t=t.replaceAll(`
|
|
29
29
|
`,""),t=t.replaceAll(" ","");let n=$k(t);return t.length-n+ho*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+=gh(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*ho:e+=85*ho:n==="source"&&typeof t[n]=="object"&&t[n]?.type==="base64"?e+=1600*ho:e+=gh(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 go=class extends Error{constructor(e){super(e),this.name="TimeoutError"}};var Vb=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 G(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(Vb(p));s=()=>c(Vb(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 go(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)})})}var eu=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)}};var Wk=9e4,qk=3,Kk=1500,Yk=15e3,Wr=class extends Error{status;rawError;constructor(e,t,n,o={}){super(n,o),this.status=e,this.rawError=t}};async function Xk(r){return r.text().then(e=>{try{return JSON.parse(e).error}catch{return e}})}var fh=class{baseUrl;logger;constructor(e){this.baseUrl=e.baseUrl,this.logger=e.logger}getHeaders(){let e={"Content-Type":"application/json"};return ai&&(e[Wc]=ai),hh&&(e[MT]=hh),e}async sendRequest(e,t){let{retries:n=qk,requestTimeoutMs:o=Wk,initialRetryDelayMs:i=Kk,maxRetryDelayMs:a=Yk}=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 Wr&&d.status>=400&&d.status<500)throw d;if(d instanceof Error&&d.name==="AbortError"&&(s=new go),l===0)throw s;let p=c-l,m=Math.min(i*Math.pow(2,p-1),a);await new Promise(h=>setTimeout(h,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={...this.getHeaders(),...t.extraHeaders};try{let s=await fetch(`${this.baseUrl}${e}`,{method:t.method,body:t.body?JSON.stringify(t.body):void 0,headers:c,signal:i.signal});if(!s.ok){let d=await Xk(s);throw new Wr(s.status,d,`Request to ${t.method} ${e} failed with status ${s.status}: ${d}`)}let u;if(s.status===204)u={};else{let d=await s.text();try{u=JSON.parse(d)}catch{u=d}}return this.logger&&t.logResponse===!0&&u&&this.logger.debug({result:u,status:s.status,...o},"Got response from Momentic server"),u}finally{clearTimeout(a),t.signal&&t.signal.removeEventListener("abort",l)}}},Lt=class extends fh{apiKey;constructor(e){super(e),this.apiKey=e.apiKey}getHeaders(){return{...super.getHeaders(),Authorization:`Bearer ${this.apiKey}`}}};import{createAnthropic as Jk}from"@ai-sdk/anthropic";var Vs=({baseUrl:r,apiKey:e,sessionId:t,extraHeaders:n,loggerTags:o})=>i=>{let a={Authorization:`Bearer ${e}`,[Wc]:ai??"",...t&&{[OT]:t},...n||{}};return o&&(a[PT]=JSON.stringify(o)),Jk({baseURL:`${r}/v1/llm/anthropic/${i}`,headers:a,apiKey:e})(i)};var Dn=class extends Lt{agentConfig;constructor(e,t){super(t),this.agentConfig=e}getAgentConfig(){return this.agentConfig}async rankChunksWithAi(e,t){let n={...e,loggerTags:t.loggerTags},o=await this.sendRequest(`/${B}/web-agent/recommend-chunks-ai`,{method:"POST",body:n,signal:t.abortSignal});return yE.parse(o)}async rankChunksWithRag(e,t){let n=await this.sendRequest(`/${B}/web-agent/recommend-chunks`,{method:"POST",body:{cliVersion:ai,...e},signal:t.abortSignal});return SE.parse(n)}async getScreenshotFromS3(e){let t=await this.sendRequest(`/${B}/s3/visual-diff-screenshot`,{method:"POST",body:{url:e}});return Qk.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(`/${B}/web-agent/locate-element`,{method:"POST",body:n,signal:t.abortSignal});return kT.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(`/${B}/web-agent/assertion`,{method:"POST",body:n,signal:t.abortSignal});return Zm.parse(o)}async getLintStepResult(e,t){let n={...e,disableCache:!!t.disableCache,loggerTags:t.loggerTags},o=await this.sendRequest(`/${B}/web-agent/lint/step`,{method:"POST",body:n,signal:t.abortSignal});return DT.parse(o)}async getLintMcpCopilotMessageResult(e,t){let n={message:e.message,disableCache:!!t.disableCache,loggerTags:t.loggerTags},o=await this.sendRequest(`/${B}/web-agent/lint/mcp-copilot`,{method:"POST",body:n,signal:t.abortSignal});return NT.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(`/${B}/web-agent/visual-assertion`,{method:"POST",body:n,signal:t.abortSignal});return Zm.parse(o)}async getAiActionCommand(e,t){let n=await this.sendRequest(`/${B}/web-agent/next-command-dynamic`,{method:"POST",body:{...e,disableCache:t.disableCache,loggerTags:t.loggerTags},signal:t.abortSignal});return LT.parse(n)}async getMultiturnAiActionCommand(e,t){return await this.sendRequest(`/${B}/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(`/${B}/web-agent/ai-action/evaluate`,{method:"POST",body:{...e,disableCache:t.disableCache,loggerTags:t.loggerTags},signal:t.abortSignal});return fm.parse(n)}async getReverseMappedDescription(e,t){let n=await this.sendRequest(`/${B}/web-agent/reverse-mapped-description`,{method:"POST",body:{...e,disableCache:t.disableCache,loggerTags:t.loggerTags},signal:t.abortSignal});return UT.parse(n)}async getTextExtraction(e,t){let n={...e,disableCache:t.disableCache,loggerTags:t.loggerTags,agentConfigVersion:this.agentConfig?.["text-extraction"]},o=await this.sendRequest(`/${B}/web-agent/text-extraction`,{method:"POST",body:n,signal:t.abortSignal});return mm.parse(o)}async getPageSummary(e,t){let n={...e,disableCache:t.disableCache,loggerTags:t.loggerTags},o=await this.sendRequest(`/${B}/web-agent/page-summary`,{method:"POST",body:n,signal:t.abortSignal});return Yy.parse(o)}async getTestResultClassification(e,t){let n=await this.sendRequest(`/${B}/web-agent/result-classification`,{method:"POST",body:{...e,loggerTags:t.loggerTags},signal:t.abortSignal});return Qp.parse(n)}async getExtractedKeywords(e,t){let n=await this.sendRequest(`/${B}/web-agent/extract-keywords`,{method:"POST",body:e,signal:t.abortSignal});return IE.parse(n)}async getAutohealingProposal(e,t){let n=await this.sendRequest(`/${B}/web-agent/autoheal-section`,{method:"POST",body:{...e,loggerTags:t.loggerTags},signal:t.abortSignal});return Wy.parse(n)}async getFailureRecoveryProposal(e,t){let n=await this.sendRequest(`/${B}/web-agent/failure-recovery`,{method:"POST",body:{...e,loggerTags:t.loggerTags},signal:t.abortSignal});return Ky.parse(n)}async getFailureRecoveryPlan(e,t){let n=await this.sendRequest(`/${B}/web-agent/failure-recovery-plan`,{method:"POST",body:{...e,loggerTags:t.loggerTags},signal:t.abortSignal});return qy.parse(n)}async getIframeRegex(e,t){let n=await this.sendRequest(`/${B}/web-agent/iframe-regex`,{method:"POST",body:e,signal:t.abortSignal});return LS.parse(n)}getVercelAnthropicModelFactory({loggerTags:e}){return Vs({baseUrl:this.baseUrl,apiKey:this.apiKey,loggerTags:e})}};import{z as Sh}from"zod";var Ze=class extends Lt{constructor(e){super(e)}getAppUrl(){return this.baseUrl==="http://localhost:8000"?"http://localhost:3000":this.baseUrl.replace(/\/\/api/,"//app")}async getAuthInfo(){let e=await this.sendRequest(`/${B}/auth/check`,{method:"GET",retries:10,requestTimeoutMs:5e3});return XT.parse(e)}async bulkGetRunStatus(e){let t=await this.sendRequest(`/${B}/runs/status`,{method:"POST",body:e,retries:3,requestTimeoutMs:1e4});return WT.parse(t)}async getTestYAMLExport(e){let t=await this.sendRequest(`/${B}/tests/export`,{method:"POST",body:e,retries:3,requestTimeoutMs:3e4});return BT.parse(t)}async updateStepCaches(e,t){await this.sendRequest(`/${B}/cache`,{method:"PATCH",body:e,extraHeaders:t,retries:3,requestTimeoutMs:1e4,initialRetryDelayMs:3e3})}async getStepCacheForTest(e,t){let n=await this.sendRequest(`/${B}/cache`,{method:"POST",body:e,extraHeaders:t,retries:10,requestTimeoutMs:3e4,initialRetryDelayMs:3e3});return HT.parse(n)}async updateMobileStepCaches(e,t){await this.sendRequest(`/${B}/mobile-cache`,{method:"PATCH",body:e,extraHeaders:t,retries:3,requestTimeoutMs:1e4,initialRetryDelayMs:3e3})}async getMobileStepCacheForTest(e,t){let n=await this.sendRequest(`/${B}/mobile-cache`,{method:"POST",body:e,extraHeaders:t,retries:10,logResponse:!0,requestTimeoutMs:3e4,initialRetryDelayMs:3e3});return GT.parse(n)}async queueTests(e){let t=await this.sendRequest(`/${B}/tests/queue`,{method:"POST",body:e,retries:3,requestTimeoutMs:1e4});return FT.parse(t)}async uploadScreenshot(e){let t=await this.sendRequest(`/${B}/screenshots`,{method:"POST",body:e,retries:3,requestTimeoutMs:5e3});return YT.parse(t)}async getAllEnvironments(){let e=await this.sendRequest(`/${B}/environments`,{method:"GET",retries:3,requestTimeoutMs:5e3});return JT.parse(e)}async acquireCacheLock(e,t){let n=await this.sendRequest(`/${B}/result-cache/lock`,{method:"POST",body:e,signal:t,retries:3,requestTimeoutMs:3e4});return pb.parse(n)}async releaseCacheLock(e){await this.sendRequest(`/${B}/result-cache/lock`,{method:"DELETE",body:{key:e},retries:3,requestTimeoutMs:5e3})}async deleteCacheResult(e){await this.sendRequest(`/${B}/result-cache/entry`,{method:"DELETE",body:e,retries:3,requestTimeoutMs:5e3})}async setCacheResult(e){await this.sendRequest(`/${B}/result-cache/entry`,{method:"PATCH",body:e,retries:3,requestTimeoutMs:5e3})}async getCacheResult(e){try{return await this.sendRequest(`/${B}/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(`/${B}/suites/queue`,{method:"POST",body:e,retries:3,requestTimeoutMs:5e3});return QT.parse(t)}async bulkGetRunGroupStatus(e){let t={runGroupIds:e},n=await this.sendRequest(`/${B}/run-groups/status`,{method:"POST",body:t,retries:3,requestTimeoutMs:5e3});return pE.array().parse(n)}async uploadProposedSteps(e,t){try{await this.sendRequest(`/${B}/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(`/${B}/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(`/${B}/test-fragments/${e}`,{method:"GET",retries:3,requestTimeoutMs:1e4});return ZT.parse(t)}async patchTestFragment(e,t){await this.sendRequest(`/${B}/test-fragments/${e}`,{method:"PATCH",body:t,retries:3,requestTimeoutMs:1e4})}async getPastTestResults(e,t){let n=await this.sendRequest(`/${B}/results/tests/${e}`,{method:"POST",body:t,retries:3,requestTimeoutMs:1e4});return eb.parse(n)}async generateTestResultsUploadUrl(){let e=await this.sendRequest(`/${B}/results/uploads`,{method:"POST",retries:3,requestTimeoutMs:1e4});return tb.parse(e)}async startProcessingResultsUpload(e,t){let n=await this.sendRequest(`/${B}/results/uploads/${e}/process`,{method:"POST",body:t,retries:3,requestTimeoutMs:1e4});return rb.parse(n)}async fetchIconKnowledgeBase(e){try{let t=await this.sendRequest(`/${B}/knowledge-base/icons`,{method:"GET",retries:3,requestTimeoutMs:5e3});return Sb.parse(t)}catch(t){return e.error({err:t},"Failed to fetch icon knowledge base"),null}}async saveNewIcons(e,t){try{await this.sendRequest(`/${B}/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(`/${B}/git/github/${e}/${t}/merge-base-commit?${i.toString()}`,{method:"GET",retries:3,requestTimeoutMs:1e4});return Bs.parse(a)}async getCommitFromGithub(e,t,n){let o=await this.sendRequest(`/${B}/git/github/${e}/${t}/commits/${n}`,{method:"GET",retries:3,requestTimeoutMs:1e4});return Bs.parse(o)}async getMergedBranchFromGithub(e,t,n,o){let i=encodeURIComponent(n),a=await this.sendRequest(`/${B}/git/github/${e}/${t}/${i}/${o}/merged-branch`,{method:"GET",retries:3,requestTimeoutMs:1e4});return nh.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(`/${B}/git/gitlab/${i}/merge-base-commit?${o.toString()}`,{method:"GET",retries:3,requestTimeoutMs:5e3});return Bs.parse(a)}async getCommitFromGitlab(e,t){let n=encodeURIComponent(e),o=await this.sendRequest(`/${B}/git/gitlab/${n}/commits/${t}`,{method:"GET",retries:3,requestTimeoutMs:1e4});return Bs.parse(o)}async getMergedBranchFromGitlab(e,t,n){let o=encodeURIComponent(t),i=encodeURIComponent(e),a=await this.sendRequest(`/${B}/git/gitlab/${i}/${o}/${n}/merged-branch`,{method:"GET",retries:3,requestTimeoutMs:1e4});return nh.parse(a)}async getAgentConfig(){let e=await this.sendRequest(`/${B}/web-agent/agent-config`,{method:"GET",retries:3,requestTimeoutMs:5e3});return Sh.record(Sh.string(),Sh.string()).parse(e)}async getQuarantinedTests(){let e=await this.sendRequest(`/${B}/quarantine`,{method:"GET"});return nb.parse(e)}async quarantineTest(e,t,n){await this.sendRequest(`/${B}/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(`/${B}/quarantine/${e.id}`,{method:"DELETE",body:{testName:e.name,reason:t,...n??{}},retries:3,requestTimeoutMs:1e4})}async createAndroidEmulator(e){let t=await this.sendRequest(`/${B}/limbar/android`,{method:"POST",retries:3,body:e,requestTimeoutMs:9e4,initialRetryDelayMs:5e3,maxRetryDelayMs:15e3});return ob.parse(t)}async extendAndroidEmulatorTtl(e){try{await this.sendRequest(`/${B}/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(`/${B}/limbar/android/upload-url`,{method:"POST",retries:3,body:o,requestTimeoutMs:15e3,logResponse:!0});return ib.parse(i)}async deleteAndroidEmulator(e){await this.sendRequest(`/${B}/limbar/android/${e}`,{method:"DELETE",retries:3,requestTimeoutMs:3e4})}async getAndroidAssets(){let e=await this.sendRequest(`/${B}/limbar/assets`,{method:"GET",retries:3,requestTimeoutMs:1e4});return ab.parse(e)}async deleteAndroidAsset(e,t){await this.sendRequest(`/${B}/limbar/assets/${e}/${t}`,{method:"DELETE",retries:3,requestTimeoutMs:1e4})}};async function yh(r){let e=process.versions.node,t=parseInt(e.split(".")[0]);(isNaN(t)||t<18)&&(T.error(`Node.js version 20 or higher is required to run the CLI. Detected: ${process.versions.node}.`),process.exit(1)),T.debug(`Identified node version ${e}`);let n=await r.client.getAuthInfo();return T.debug("Got auth info from API"),n}var tu=class{apiClient;constructor(e){this.apiClient=e}async reportBillableEvents(e,t){await this.apiClient.reportBillableEvents(e,t)}};var fo=class extends Lt{generator;constructor(e,t){super(e),this.generator=t}async runTemplateMatching(e,t={}){let n=await this.sendRequest(`/${B}/web-agent/template-matching`,{method:"POST",body:e,signal:t?.signal});return NS.parse(n)}async constructIframeRegex(e,t={}){return this.generator.getIframeRegex(e,{abortSignal:t.signal})}};var aa=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 Zk,en as e0}from"@faker-js/faker";var sa="v1",mn=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 Zk({locale:e0}),this.fakerInstance.seed(e.fakerSeed))}async sendAiGenerate(e){let t=typeof e=="string"?{input:e}:e;return this.httpClient.sendRequest(`/${sa}/tools/ai/generate`,{method:"POST",body:t}).catch(n=>{throw n instanceof Wr?new Error(n.rawError):new Error(`Failed to send AI generation: ${n.message}`)})}async sendSms(e){return this.httpClient.sendRequest(`/${sa}/tools/sms/send`,{method:"POST",body:e}).then(()=>{}).catch(t=>{throw t instanceof Wr?new Error(t.rawError):new Error(`Failed to send sms: ${t.message}`)})}async fetchLatestSms(e){return this.httpClient.sendRequest(`/${sa}/tools/sms/fetchLatest`,{method:"POST",body:e}).catch(t=>{throw t instanceof Wr?new Error(t.rawError):t})}async sendEmail(e){return this.httpClient.sendRequest(`/${sa}/tools/email/send`,{method:"POST",body:e}).then(()=>{}).catch(t=>{throw t instanceof Wr?new Error(t.rawError):new Error(`Failed to send email: ${t.message}`)})}async fetchAllEmails(e){return this.httpClient.sendRequest(`/${sa}/tools/email/fetchAll`,{method:"POST",body:e}).catch(t=>{throw t instanceof Wr?new Error(t.rawError):new Error(`Failed to fetch all emails: ${t.message}`)})}async fetchLatestEmail(e){return this.httpClient.sendRequest(`/${sa}/tools/email/fetchLatest`,{method:"POST",body:e}).catch(t=>{throw t instanceof Wr?new Error(t.rawError):new Error(`Failed to fetch latest emails: ${t.message}`)})}};function $b(r,e,t){return fetch(r,{method:"PUT",body:t,headers:{"Content-Type":e}})}var ru=class{constructor(e){this.client=e}async uploadResultsArchive(e,t){let{uploadUrl:n,id:o}=await this.client.generateTestResultsUploadUrl(),i=await $b(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}};import{diff as r0}from"deep-object-diff";import{cloneDeep as n0}from"lodash-es";function $s(r){let e={parentChain:[]};return nu(r,e),e}function nu(r,e){let{onPresetAction:t,onSimpleStepContainer:n,onConditional:o,earlyStop:i}=r;for(let a of r.steps)switch(a.type){case"PRESET_ACTION":if(t(a,e)&&i)return!0;break;case"CONDITIONAL":if(o?.(a,e)&&i)return!0;e.parentChain.push(a);for(let c of a.blocks)if(t(c.assertion,e)&&i||nu({...r,steps:c.steps},e)&&i)return!0;if(nu({...r,steps:a.elseSteps??[]},e)&&i)return!0;e.parentChain.pop();break;case"RESOLVED_MODULE":case"SECTION":case"AI_ACTION":if(n?.(a,e)&&i)return!0;if(a.steps){if(e.parentChain.push(a),nu({...r,steps:a.steps},e)&&i)return!0;e.parentChain.pop()}break;case"AI_ACTION_DYNAMIC":{if(n?.(a,e)&&i)return!0;break}default:return(c=>{throw"If Typescript complains about the line below, you missed a case or break in the switch above"})(a)}}function Wb(r,e,t,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!!t0([r],t,i).result}function t0(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 $s({steps:r,earlyStop:!0,onPresetAction:i,onConditional:i,onSimpleStepContainer:i}),{result:n,parentChain:o}}function qb(r,e){e(r);for(let t in r){let n=r[t];n&&(Array.isArray(n)?iu(n,e):typeof n=="object"&&qb(n,e))}}function iu(r,e){for(let t of r)t&&(Array.isArray(t)?iu(t,e):typeof t=="object"&&qb(t,e))}function Eh(r,e){if(r.length>e.length)return Eh(e,r);for(let t=0;t<r.length;t++)if(r[t]!==e[t])return!1;return!0}function ou(r){for(let e of r.results)switch(e.type){case"PRESET_ACTION":r.onPresetAction(e);break;case"AI_ACTION":case"AI_ACTION_DYNAMIC":case"MODULE":r.onSimpleStepContainer?.(e),ou({...r,results:e.results});break;case"CONDITIONAL":r.onConditional?.(e),e.assertionResult&&r.onPresetAction(e.assertionResult),ou({...r,results:e.results});break;default:throw new Error(`Unsupported result type: ${e.type}`)}}function Ws(r,e){return!r&&!e?!1:!r||!e?!0:Object.keys(r0(r,e)).length>0}function la({steps:r,topLevel:e=!0,...t}){let{stepCacheEntries:n,logger:o,keyPrefix:i}=t,a=[],l=[],c=[],s=0,u=(p,m)=>{try{let h=On.parse(m.value);if(h.type!==p.type){o.warn({parsedCacheEntry:h,command:p},"Not using step cache due to type mismatch"),l.push(m.key);return}p.cache=h.cache,a.push(m.key),c.push(m.uniqueKey)}catch(h){l.push(m.key),o.error({err:h,cacheEntry:m},"Not using step cache due to parsing error")}},d=(p,m)=>{let h=o0(p.id,m),g=h.find(f=>!!n[f]);if(g)u(p,n[g]);else{if(p.type==="AI_ASSERTION")return;l.push(h[0])}};for(let p of r)switch(p.type){case"RESOLVED_MODULE":{s+=p.steps.length;let{cacheKeysHit:m,cacheKeysMissed:h,uniqueKeysHit:g}=la({...t,steps:p.steps,keyPrefix:i?`${i}:${p.id}`:p.id,topLevel:!1});a.push(...m),l.push(...h),c.push(...g);break}case"SECTION":case"AI_ACTION":{if(s+=p.steps?.length??0,!p.steps?.length)break;let{cacheKeysHit:m,cacheKeysMissed:h,uniqueKeysHit:g}=la({...t,steps:p.steps,topLevel:!1});a.push(...m),l.push(...h),c.push(...g);break}case"AI_ACTION_DYNAMIC":continue;case"PRESET_ACTION":{if(!nc.includes(p.command.type)||(p.command.type==="TYPE"||p.command.type==="MOUSE_DRAG"||p.command.type==="VISUAL_DIFF"||p.command.type==="SCROLL_DOWN"||p.command.type==="SCROLL_UP"||p.command.type==="SCROLL_LEFT"||p.command.type==="SCROLL_RIGHT")&&!p.command.target||"cache"in p.command&&p.command.cache)continue;s++,d(p.command,i);break}case"CONDITIONAL":{for(let m of p.blocks){s++,d(m.assertion.command,i),s+=m.steps.length;let{cacheKeysHit:h,cacheKeysMissed:g,uniqueKeysHit:f}=la({...t,steps:m.steps,topLevel:!1});a.push(...h),l.push(...g),c.push(...f)}if(p.elseSteps){s+=p.elseSteps.length;let{cacheKeysHit:m,cacheKeysMissed:h,uniqueKeysHit:g}=la({...t,steps:p.elseSteps,topLevel:!1});a.push(...m),l.push(...h),c.push(...g)}break}default:return(h=>{throw"If Typescript complains about the line below, you missed a case or break in the switch above"})(p)}return e&&s&&l.length>0&&o.warn({totalSteps:s,cacheKeysMissed:l,cacheKeysHit:a,uniqueKeysHit:c,cacheEntries:n.length},"Step cache did not fully resolve"),{cacheKeysHit:a,cacheKeysMissed:l,uniqueKeysHit:c}}function Kb(r,e){return e?`${e}:${r}`:r}function o0(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 Th(r){let{moduleStepParents:e=[],moduleIdParents:t=[]}=r;if(e.length!==t.length)throw new Error(`Invalid cache entry parent length: ${JSON.stringify(e)}
|
|
30
30
|
${JSON.stringify(t)}`);let n=[];return n.push({key:Kb(r.id,e.join(":")),organizationId:r.orgId,value:r.value,testId:r.testId}),n}function Yb(r){let e=new Set;return iu(r,t=>{if("type"in t&&t.type==="RESOLVED_MODULE"&&"moduleId"in t){let n=t.moduleId;typeof n=="string"&&!e.has(n)&&e.add(n)}}),e}function au({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"&&JS(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 su(r,e,t){let n=r.cache&&"memory"in r.cache?r.cache.memory?.traces:void 0;return Ws(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},{changed:!0}):{changed:!1}}function Xb({steps:r}){let e={};return $s({steps:r,onPresetAction:(t,n)=>{let o=t.command;if(!("cache"in o)||!o.cache)return;let i=n.parentChain.filter(c=>c.type==="RESOLVED_MODULE").map(c=>c.id).join(":"),a=Kb(t.id,i),l=On.parse(o);e[a]=l},onSimpleStepContainer:(t,n)=>{},onConditional:(t,n)=>{}}),e}function qs(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 i0(r,e){return Ws(r.memory,e.memory)?{...r,memory:e.memory,updatedAt:e.updatedAt}:r}function bh(r,e){return r?Ws(r.target.memory,e.target.memory)?{target:{...r.target,memory:e.target.memory},updatedAt:e.updatedAt}:r:{target:qs(e.target),updatedAt:e.updatedAt}}function a0(r,e){let t=n0(r);return t.fromTarget?Ws(r.fromTarget?.memory,e.fromTarget?.memory)&&(t.fromTarget={...t.fromTarget,memory:e.fromTarget?.memory},t.updatedAt=e.updatedAt):(t.fromTarget=e.fromTarget,t.fromTarget&&(t.fromTarget=qs(t.fromTarget),t.updatedAt=e.updatedAt)),t.toTarget?Ws(r.toTarget?.memory,e.toTarget?.memory)&&(t.toTarget={...t.toTarget,memory:e.toTarget?.memory},t.updatedAt=e.updatedAt):(t.toTarget=e.toTarget,t.toTarget&&(t.toTarget=qs(t.toTarget),t.updatedAt=e.updatedAt)),t}function Jb({newEntries:r,originalCachesMap:e,logger:t}){let n=[];for(let o of r){let i=e[o.key];if(!i||!i.cache||o.value.type!==i.type)continue;let a=o.value.cache;if(o.value={...i},!a){n.push(o);continue}if("memory"in a&&a.memory)t.debug({cacheKey:o.key,newCacheMemory:a.memory,originalCache:i},"Overwriting assertion cache memory"),o.value.cache=i0(i.cache,a);else if("target"in a&&a.target.memory){t.debug({cacheKey:o.key,newCacheMemory:a.target.memory,originalCache:i},"Overwriting target cache memory");let l=mr.safeParse(o.value.cache);o.value.cache=bh(l.data,a)}else if("fromTarget"in a||"toTarget"in a){let l=Gp.optional().parse(o.value.cache);if(!l)continue;t.debug({cacheKey:o.key,fromTargetMemory:a.fromTarget?.memory,toTargetMemory:a.toTarget?.memory,originalCache:i},"Overwriting drag cache memory"),o.value.cache=a0(l,a)}n.push(o)}return n}function it(r,e,t=!1){return r.length<e?r:r.slice(0,e-3)+(t?"...TRUNCATED...":"[...]")}var Ir={EQUALS:"equals",CONTAINS:"contains",STARTS_WITH:"starts with",EXISTS:"exists"},Mr={EQUALS:"does not equal",CONTAINS:"does not contain",STARTS_WITH:"does not start with",EXISTS:"does not exist"},vh={EXISTS:"exists",VISIBLE:"is visible",ENABLED:"is enabled",EDITABLE:"is editable",FOCUSED:"is focused"},Ah={EXISTS:"does not exist",VISIBLE:"is not visible",ENABLED:"is disabled",EDITABLE:"is not editable",FOCUSED:"is not focused"};function s0(r){switch(r.type){case"ELEMENT_CONTENT":return`content ${r.negated?Mr[r.operation]:Ir[r.operation]} '${r.value}'`;case"ELEMENT_ATTRIBUTE":{let t=r.negated?Mr[r.operation]:Ir[r.operation];return r.operation==="EXISTS"?`attribute '${r.attr}' ${t}`:`attribute '${r.attr}' ${t} '${r.value}'`}case"ELEMENT_NAME":{let t=r.negated?Mr[r.operation]:Ir[r.operation];return r.operation==="EXISTS"?`tag name ${t}`:`tag name ${t} '${r.value}'`}case"ELEMENT_STYLE":{let t=r.negated?Mr[r.operation]:Ir[r.operation];return r.operation==="EXISTS"?`style property '${r.property}' ${t}`:`style property '${r.property}' ${t} '${r.value}'`}case"ELEMENT_EXISTENCE":return r.negated?Ah[r.condition]:vh[r.condition];default:return(t=>{throw"If Typescript complains about the line below, you missed a case or break in the switch above"})(r)}}var ese={CONTENT:"The page"};function l0(r){switch(r.type){case"VALUE":return`the option with value ${r.value}`;case"LABEL":return`the option with label ${r.label}`;case"INDEX":return`the option at index ${r.index}`;default:return(t=>{throw"If Typescript complains about the line below, you missed a case or break in the switch above"})(r)}}function cu(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 lu(r){let e="";return r.method&&(e=` with method ${r.method}`),`${cu(r.urlMatcher)}${e}`}function c0(r){switch(r.type){case"CONTENT":return`${r.negated?Mr.CONTAINS:Ir.CONTAINS} '${r.value}'`;default:return(t=>{throw"If Typescript complains about the line below, you missed a case or break in the switch above"})(r.type)}}function gn(r,e=!0){switch(r.type){case"SUCCESS":return r.condition?.assertion?`Check success condition: ${r.condition.assertion}`:"All commands completed";case"AI_EXTRACT":return`Extract data from page: ${r.goal}`;case"NAVIGATE":return`Go to URL: ${e?it(r.url,30):r.url}`;case"DIALOG":return`Automatically ${r.action.toLowerCase()} the next dialog`;case"CAPTCHA":return"Solve captchas on the page";case"GO_BACK":return"Go back to the previous page";case"GO_FORWARD":return"Go forward to the next page";case"SCROLL_DOWN":return`Scroll down ${r.deltaY?`${r.deltaY}px`:"1 page height"}${r.target?` in the container of: ${Bt(r.target)}`:""}`;case"SCROLL_UP":return`Scroll up ${r.deltaY?`${r.deltaY}px`:"1 page height"}${r.target?` in the container of: ${Bt(r.target)}`:""}`;case"SCROLL_LEFT":return`Scroll left ${r.deltaX?`${r.deltaX}px`:"1 page width"}${r.target?` in the container of: ${Bt(r.target)}`:""}`;case"SCROLL_RIGHT":return`Scroll right ${r.deltaX?`${r.deltaX}px`:"1 page width"}${r.target?` in the container of: ${Bt(r.target)}`:""}`;case"WAIT":return`Wait for ${r.delay} seconds`;case"REFRESH":return"Refresh the page";case"CLICK":{if(r.target?.type==="coordinates")return`Click at coordinates: ${Bt(r.target)}`;let n="";return r.target?.elementDescriptor.length?n=` on element: '${r.target.elementDescriptor}'`:r.cache?.target.nodeOnlySerializedHtml&&(n=` on element: '${r.cache?.target.nodeOnlySerializedHtml}'`),`Click${n}`}case"FOCUS":return`Focus ${Bt(r.target)}`;case"BLUR":return`Focus ${Bt(r.target)}`;case"DRAG":return`Drag ${Bt(r.fromTarget)} onto ${Bt(r.toTarget)}`;case"MOUSE_DRAG":return r.target?.type==="description"&&r.target.elementDescriptor?`Click and drag ${Bt(r.target)} by ${r.deltaX}px horizontally, ${r.deltaY}px vertically`:`Click and drag mouse by ${r.deltaX}px horizontally, ${r.deltaY}px vertically`;case"TYPE":{let n="";return r.target?.type==="coordinates"?n=` in element at coordinates: ${Bt(r.target)}`:r.target?.elementDescriptor.length?n=` in element: '${r.target.elementDescriptor}'`:r.cache?.target.nodeOnlySerializedHtml&&(n=` in element: '${r.cache?.target.nodeOnlySerializedHtml}'`),`Type '${r.value}'${n||""}`}case"HOVER":{let n="";return r.target.type==="coordinates"?n=` over coordinates: ${Bt(r.target)}`:r.target.elementDescriptor.length>0?n=` over element: '${r.target.elementDescriptor}'`:r.cache?.target.nodeOnlySerializedHtml&&(n=` over element: '${r.cache?.target.nodeOnlySerializedHtml}'`),`Hover${n}`}case"PRESS":return`Press ${r.value}`;case"KEY_DOWN":return`Hold down ${r.value} on the keyboard`;case"KEY_UP":return`Release ${r.value} on the keyboard`;case"SELECT_OPTION":{let n="",o=l0(r.choice);return r.target.type==="coordinates"?n=` from element at coordinates: ${Bt(r.target)}`:r.target.elementDescriptor.length>0?n=` from: '${r.target.elementDescriptor}'`:r.cache?.target.nodeOnlySerializedHtml&&(n=` from: '${r.cache?.target.nodeOnlySerializedHtml}'`),`Select option '${o}'${n}`}case"TAB":switch(r.action.type){case"SUBSTRING":return`Switch to tab with substring: ${r.action.substring}`;case"REGEX":return`Switch to tab matching regex: ${r.action.pattern}`;case"INDEX":return`Switch to tab at index: ${r.action.index}`;default:return(o=>{throw"If Typescript complains about the line below, you missed a case or break in the switch above"})(r.action)}return"Switch to unknown tab";case"NEW_TAB":return`Open new tab to: ${r.url}`;case"REQUEST":return`Send ${r.method} request to ${r.url}`;case"GRAPHQL_REQUEST":return`Send GraphQL request to ${r.url}`;case"COOKIE":return`Set cookie: ${r.value}`;case"LOCAL_STORAGE":return`Set local storage: ${r.key}: ${r.value}`;case"JAVASCRIPT":return`Run JavaScript: ${e?it(r.code,30):r.code}`;case"AI_ASSERTION":return`Assertion: '${r.assertion}'`;case"VISUAL_DIFF":return`Visual diff against baseline ${r.target?`for element: ${Bt(r.target)}`:"for entire page"}`;case"FILE_UPLOAD":return r.fileSource.type==="URL"?`Upload file: ${r.fileSource.url}`:`Upload file: ${r.fileSource.name}`;case"AUTH_LOAD":return"Load auth state";case"AUTH_SAVE":return"Save auth state";case"ELEMENT_CHECK":return`Check the element ${Bt(r.target)} ${s0(r.assertion)}`;case"PAGE_CHECK":return`Check the page ${c0(r.assertion)}`;case"WAIT_FOR_URL":return`Wait for page URL to ${cu(r.matcher)}`;case"COPY":return"Copy to clipboard";case"PASTE":return"Paste clipboard contents";case"REGISTER_REQUEST_LISTENER":return r.requestMatcher?`Register a listener for network requests that ${lu(r.requestMatcher)}`:"Register a listener for network requests";case"AWAIT_LISTENER":return r.key?`Wait for the listener ${r.key} to resolve`:"Wait for a listener to resolve";case"RECORD_REQUESTS":return r.requestMatcher?`Start recording requests that match ${lu(r.requestMatcher)}`:"Start recording network requests";case"GET_RECORDED_REQUESTS":return r.key?`Get the requests that were recorded for ${r.key}`:"Get the requests that were recorded";case"SET_HEADER":return r.name?r.requestMatcher?`Set a ${r.name} header for requests that match ${lu(r.requestMatcher)}`:`Set a ${r.name} header for all requests`:"Set a header";case"MOCK_ROUTE":return r.requestMatcher?`Mock requests that ${lu(r.requestMatcher)}`:"Mock a network route";case"REMOVE_ROUTE_MOCK":return r.key?`Remove the mock with key ${r.key}`:"Remove all route mocks";case"OFFLINE_MODE":return r.enable?"Enable offline mode":"Disable offline mode";default:return(n=>{throw"If Typescript complains about the line below, you missed a case or break in the switch above"})(r)}}function u0(r){return typeof r=="object"&&r!==null}function hn(r){if(Array.isArray(r))return r.map(hn);if(u0(r)){let e={};return Object.entries(r).forEach(([t,n])=>{n!==void 0&&(e[t]=hn(n))}),e}return r}function Qb(r){let e=[];for(let t of r){t.sort((a,l)=>a.timestamp-l.timestamp);let n=[],o,i=1;for(let a of t)o&&o.text===a.text&&o.type===a.type&&JSON.stringify(o.args??null)===JSON.stringify(a.args??null)?i++:(o&&(i>1?o.args&&o.args.length?o.args.push(`(repeated ${i} times)`):o.text+=` (repeated ${i} times)`:n.push(o)),o=a,i=1);o&&n.push(o),e.push(n)}return e}import{cloneDeep as use}from"lodash-es";import{cloneDeep as bse}from"lodash-es";import{v4 as Ise}from"uuid";import{cloneDeep as d0}from"lodash-es";import ov from"truncate-json";import{v4 as Zb}from"uuid";import{cloneDeep as jse,unset as Vse}from"lodash-es";function So(r){switch(r.type){case"AI_ACTION":return`AI action: ${it(r.text,100)}`;case"AI_ACTION_DYNAMIC":return`AI action: ${it(r.text,100)}`;case"PRESET_ACTION":return gn(r.command);case"MODULE":return`Module: ${r.id}`;case"RESOLVED_MODULE":return`Module: ${r.name}`;case"CONDITIONAL":return"Conditional step";case"SECTION":return`Section${r.description?`with goal: ${it(r.description,100)}`:""}`;default:return(t=>{throw new Error("You missed a case in the switch above")})(r)}}function si(r,e){return r.split(`
|
|
31
31
|
`).map(t=>" ".repeat(e)+t).join(`
|
|
@@ -35,17 +35,17 @@ ${si(`Sub-steps: ${e}`,2)}`}return`Module: ${r.id}
|
|
|
35
35
|
${si(`Sub-steps: ${e}`,2)}`}case"RESOLVED_MODULE":return`Module: ${r.name}`;case"CONDITIONAL":{let e=["Conditional step"];if("assertionResult"in r&&r.assertionResult&&(e.push(si("Conditional check:",2)),e.push(si(Rh(r.assertionResult),2))),"results"in r&&Array.isArray(r.results)){let t=r.results.length,n="assertionResult"in r&&r.assertionResult?"Branch steps":"Else branch steps";e.push(si(`${n}: ${t}`,2))}return e.join(`
|
|
36
36
|
`)}case"SECTION":{let e="results"in r&&Array.isArray(r.results)?r.results.length:0;return`Section${r.description?`with goal: ${r.description}`:""}
|
|
37
37
|
${si(`Sub-steps: ${e}`,2)}`}default:return(t=>{throw new Error("You missed a case in the switch above")})(r)}}var ev=1e3,tv=5e7,p0="[FAILED]";async function rv(r,e,t){if(t){let n=await e.getScreenshot(r,t);if(n)return`data:image/jpeg;base64,${Buffer.from(n).toString("base64")}`}}function m0(r,e){let t=(()=>{switch(r.type){case"AI_ACTION":case"AI_ACTION_DYNAMIC":return"AI action";case"PRESET_ACTION":return"Preset action";case"MODULE":return"Module";case"CONDITIONAL":return"Conditional step";case"SECTION":return"Section";default:return(i=>{throw new Error("You missed a case in the switch above")})(r)}})();return(o=>e?`${e==="start"?"Start":"End"} of ${t}
|
|
38
|
-
${o}`:o)(Rh(r))}function du(r,e={}){let t=e.followingStepStart??e.precedingStepEnd??new Date;return{type:"PRESET_ACTION",id:Zb(),message:`Starting the ${r.replace("-"," ")} section`,startedAt:t,finishedAt:t,status:"SUCCESS",command:{id:Zb(),type:"SUCCESS"},results:[]}}function uu(r,e={}){let{index:t,includeDomState:n=!1,header:o}=e,i=m0(r,o),a;r.type==="PRESET_ACTION"&&(a=r.results?.[0]?.elementInteracted);let l=r.message!=="Successfully executed preset action."?r.message:void 0,c=i;r.status==="FAILED"&&(c=`${p0} ${c}`);let s={description:c,startedAt:r.startedAt.toISOString(),finishedAt:r.finishedAt.toISOString(),beforeUrl:r.beforeUrl,afterUrl:r.afterUrl,beforeSnapshot:r.beforeSnapshot,afterSnapshot:r.afterSnapshot,elementInteracted:a,message:l,index:t};if(r.status==="FAILED"&&n)try{let u=mE.array().parse(r.details);for(let d of u)"pageState"in d&&(s.pageState=d.pageState)}catch{}return s}async function iv(r,e,t,{addIndices:n=!0,includeDomState:o=!1,flatten:i=!0,maxItemsFromEnd:a=15,indexOffset:l=0}){let c,s=[];for(let u=0;u<t.length;u++){let d=t[u],p=n?u+l:void 0;switch(d.type){case"PRESET_ACTION":{s.push(uu(d,{index:p,includeDomState:o,header:void 0})),d.status==="FAILED"&&(c=p);break}case"CONDITIONAL":case"AI_ACTION":case"AI_ACTION_DYNAMIC":case"MODULE":case"SECTION":{if(i){s.push(uu(d,{index:n?p:void 0,includeDomState:o,header:"start"})),l+=1;let{failureIndex:m,results:h}=await iv(r,e,d.results,{addIndices:n,includeDomState:o,flatten:i,maxItemsFromEnd:a,indexOffset:l+u});s.push(...h),m!==void 0&&(c=m),l+=h.length,s.push(uu(d,{index:n?l+u:void 0,includeDomState:o,header:"end"})),l+=1}else s.push(uu(d,{index:n?l+u:void 0,includeDomState:o,header:void 0}));break}default:return(h=>{throw new Error("You missed a case in the switch above")})(d)}}return{results:s,failureIndex:c}}async function ca(r,e,t,{numStepsWithScreenshots:n=5,addIndices:o=!0,includeBeforeScreenshots:i=!1,includeDomState:a=!1,flatten:l=!0,maxItemsFromEnd:c=20}){let s=await iv(r,e,t,{addIndices:o,includeDomState:a,flatten:l,maxItemsFromEnd:c,indexOffset:0}),{results:u}=s,{failureIndex:d}=s;d!==void 0&&u.length>0&&(u=u.slice(0,d+1));let p=[],m=0;if(c!==void 0&&u.length>c&&(m=u.length-c),d!==void 0&&d<u.length-1&&r.warn("PROCESS_RESULTS_FOR_LLM: Failure index check - should not be possible",{failureIndex:d,flattenedResultsLength:u.length,lastIndex:u.length-1,isLastIndex:d===u.length-1,offset:m}),d!==void 0&&m>d)throw new Error("Failure index is out of bounds");for(let h=m;h<u.length;h++){let g=u[h],f={description:g.description,startedAt:g.startedAt,finishedAt:g.finishedAt,beforeUrl:g.beforeUrl,afterUrl:g.afterUrl,elementInteracted:g.elementInteracted,message:g.message,pageState:g.pageState,index:g.index},S,y;(n===void 0||n>0&&h>=u.length-n)&&(g.afterSnapshot&&(y=await rv(r,e,g.afterSnapshot)),i&&g.beforeSnapshot&&(S=await rv(r,e,g.beforeSnapshot))),f.beforeScreenshot=S,f.afterScreenshot=y,p.push(f)}return{results:p,failureIndex:d!==void 0?d-m:void 0}}function ua({json:r,keysToRedact:e,maxJsonStringSize:t}){try{if(!r)return r;if(typeof r=="string")return it(r,t??2e4);if(typeof r=="object"){let{jsonString:n}=ov(JSON.stringify(r,(o,i)=>e?.includes(o)||typeof i=="string"&&i.length>3e4?"REDACTED":i),t??2e4);return JSON.parse(n)}return r}catch{return r}}function wh(r,e){for(let t=0;t<r.length;t++){let n=r[t];try{if(n.data){let{jsonString:o}=ov(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.details&&(n.details=void 0),n.type){case"PRESET_ACTION":nv(n);break;case"CONDITIONAL":n.assertionResult&&nv(n.assertionResult),wh(n.results,e);break;case"AI_ACTION_DYNAMIC":case"AI_ACTION":case"MODULE":case"SECTION":{wh(n.results,e);break}default:return(i=>{throw new Error("If Typescript complains about the line below, you missed a case or break in the switch above")})(n)}}}function nv(r){let e=r.command;"cache"in e&&e.cache&&(e.cache=void 0)}function pu(r,e){let t=d0(r);if(wh(t,e),t.length>ev)return e.error("Results too long, truncating before insertion"),t.slice(t.length-ev,t.length);let n=JSON.stringify(t);if(n.length>tv)for(e.error({serializedLength:n.length,resultsArrayLength:t.length},"Database content violation: results too large, truncating before insertion");n.length>tv;)t.splice(0,1),n=JSON.stringify(t);try{return bt.array().parse(JSON.parse(n))}catch(o){throw e.error({serialized:n,err:o},"Could not parse serialized results into JSON structure after processing"),o}}import{cloneDeep as dle}from"lodash-es";var h0=/^(?!.*\S+\s+\S+).*$/,g0=/^[a-zA-Z0-9\s.,;:'"!?()\- \u00C0-\u00FF]+$/,f0=/style="([^"]*)/g,S0=/data-[\w-]+/g,y0=r=>{switch(r.type){case"AI_ASSERTION":return{type:r.type,assertion:r.assertion};case"DRAG":if(r.fromTarget.type==="description")return{type:r.type,description:r.fromTarget.elementDescriptor};break;case"CLICK":case"BLUR":case"TYPE":case"SELECT_OPTION":case"ELEMENT_CHECK":case"FOCUS":case"HOVER":case"MOUSE_DRAG":case"VISUAL_DIFF":case"SCROLL_DOWN":case"SCROLL_UP":case"SCROLL_LEFT":case"SCROLL_RIGHT":if(r.target?.type==="description")return{type:r.type,description:r.target.elementDescriptor};break}return{type:"NONE",description:"NONE"}};function av(r){let e=y0(r),t=e.type==="AI_ASSERTION"?e.assertion:e.description;return!t||t==="NONE"?{thoughts:"NONE",category:"NO_DESCRIPTION_PROVIDED"}:h0.test(t)&&g0.test(t)?{thoughts:"The target description is too short. Please provide more details.",category:"FEW_WORDS"}:f0.test(t)?{thoughts:"Style tags are not recommended in the command description as they change frequently. Please remove them and describe the target in a different way.",category:"STYLE_TAG"}:S0.test(t)?{thoughts:"Hardcoded data attributes are not recommended in the command description as they change frequently.",category:"HARDCODED_ATTRIBUTE"}:new RegExp(`\\b${e.type}\\b`,"gi").test(t)?{thoughts:`The element description you provided starts with the command type (${e.type}). This can confuse our AI agents since the element itself is unrelated to the desired action.`,category:"TYPE_IN_DESCRIPTION"}:{thoughts:"NONE",category:"NONE"}}function sv(r,e){if(!(!r.envs||!r.envs.length)){for(let t of r.envs){let n=t;e in t&&(n[e]&&(t.default=!0),delete n.defaultOnCloud,delete n.defaultOnLocal)}r.envs.some(t=>t.default)||(r.envs[0].default=!0)}}import{cloneDeep as Nv}from"lodash-es";import A0 from"diff-lines";import hu,{gte as R0}from"semver";var lv={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 cv={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 E0=["target","fromTarget","toTarget"];function uv(r){for(let e of E0){if(r[e]===void 0)continue;let t=r[e];t.elementDescriptor!==void 0?t.type="description":r[e]={type:"description",elementDescriptor:""}}}var dv={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 uv(e.command),e;case"AI_ACTION":{let t=e.commands;for(let n of t??[])uv(n);return e}default:return e}})};import{v4 as T0}from"uuid";var pv={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=T0()),e;default:return e}})};import{v4 as mv}from"uuid";var hv={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??mv(),e}case"AI_ACTION":return e.commands&&(e.steps=e.commands.map(t=>({type:"PRESET_ACTION",command:{...t,id:t.id??mv()}})),delete e.commands),e;default:return e}})};var gv={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 b0}from"uuid";var fv={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=b0()),e))};import{v4 as Sv}from"uuid";var yv={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=Sv())}return e.id=Sv(),e})};var Ev={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 v0}from"uuid";var Tv={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=v0()),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 bv={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 vv={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&&Av(t),e})};function Av(r){r&&Object.keys(r).forEach(e=>{if(typeof r[e]=="object"&&r[e]){Av(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 Rv={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 wv={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 Cv={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 xv={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 _v={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 Iv={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 mu=new Set(["CLICK","TYPE","SELECT_OPTION"]),Mv={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||mu.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||mu.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||mu.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||mu.has(m))&&(d.target={elementDescriptor:p??""})})}),e}),stopOnFailure:!0};var Pv={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 Ov={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 li=[Iv,Pv,Ov,Mv,lv,cv,dv,pv,hv,gv,fv,yv,Ev,Tv,bv,vv,Rv,wv,Cv,xv,_v];if(ue!==li[li.length-1].toVersion)throw new Error("Please bump LATEST_SCHEMA_VERSION in types package after adding a migration");li.forEach((r,e)=>{if(!hu.valid(r.toVersion)||!hu.valid(r.fromVersion))throw new Error(`Migration '${r.name}' has invalid version`);if(!hu.gt(r.toVersion,r.fromVersion))throw new Error(`Migration '${r.name}' has toVersion <= fromVersion`);if(e===0)return;if(li[e-1].toVersion!==r.fromVersion)throw new Error(`Migration '${r.name}' at index ${e} is not contiguous with previous migration`)});function w0(r){return r.every(e=>e&&typeof e=="object"&&!Array.isArray(e))}var Ks=async({metadata:r,steps:e,logger:t,toVersion:n})=>{let o=e,{schemaVersion:i,id:a}=r,l=li.findIndex(u=>hu.gt(u.toVersion,i));if(l===-1)return{steps:o,newVersion:i};let c=i;for(let u=l;u<li.length;u++){if(n&&R0(c,n)){t.debug("Stopping migration early because toVersion was reached");break}let d=li[u],p={id:a,migration:d.name,toVersion:d.toVersion};try{o=await Lv(o,d),c=d.toVersion}catch(m){throw t.error({err:m,...p},"Migration failed"),new Error(`Step migration ${d.name} failed: ${m}`)}}let s=A0(JSON.stringify(e,void 0,2),JSON.stringify(o,void 0,2),{n_surrounding:1});return s.trim()&&t.debug({diffs:s,id:a},"Migration diffs"),{newVersion:c,steps:o}};async function Lv(r,e){let t=await e.execute(r);for(let n of t)for(let o of Object.keys(n)){if(!e.recursiveKeys.has(o))continue;let i=n[o];!i||!Array.isArray(i)||w0(i)&&(n[o]=await Lv(i,e))}return t}async function Dv({rawSteps:r,metadata:e,logger:t,callbacks:n}){sv(e,"defaultOnCloud");let o={},{resolvedSteps:i,newSchemaVersion:a}=await gu({rawSteps:r.steps,migrationMetadata:e,logger:t,callbacks:n,resolvedModuleCache:o}),l={...e,steps:i,schemaVersion:a};for(let c of["beforeSteps","afterSteps"]){let s=r[c];if(!s)continue;let{resolvedSteps:u}=await gu({rawSteps:s,migrationMetadata:e,logger:t,callbacks:n,resolvedModuleCache:o});l[c]=u}return{resolvedTest:l,moduleIds:Array.from(Object.keys(o))}}async function ci(r,e,t){let{newVersion:n,steps:o}=await Ks({metadata:r,steps:e,logger:t});try{return{steps:He.array().parse(o),newVersion:n}}catch(i){throw t.error({type:"zod",err:i,newVersion:n,id:r.id,steps:o},"Failed to parse test steps while migrating test"),new uc(`Failed to parse test steps while migrating test: ${i}`,r.id,"entity",{cause:i})}}async function gu({rawSteps:r,migrationMetadata:e,logger:t,callbacks:n,resolvedModuleCache:o={}}){let{newVersion:i,steps:a}=await ci(e,r,t),l=[];for(let c of a)l.push(await Ys({step:c,callbacks:n,logger:t,resolvedModuleCache:o}));return{resolvedSteps:l,newSchemaVersion:i}}async function Ys({step:r,callbacks:e,logger:t,resolvedModuleCache:n}){switch(r.type){case"AI_ACTION":return r;case"AI_ACTION_DYNAMIC":return r;case"PRESET_ACTION":return r;case"MODULE":{let c=r.moduleId,s=n[c];if(s)return{...Nv(s),...r,type:"RESOLVED_MODULE"};let u=await e.onFetchModule({id:c,logger:t});if(!u)throw new Error(`Could not find module with id ${c}`);let{newVersion:d,steps:p}=await Ks({metadata:{id:c,schemaVersion:u.schemaVersion},steps:u.steps,logger:t}),m;try{m=He.array().parse(p)}catch(f){throw t.error({type:"zod",err:f,steps:p,newVersion:d,id:c},"Module failed to parse"),f}let h;try{h=await Promise.all(m.map(f=>Ys({step:f,callbacks:e,logger:t,resolvedModuleCache:n})))}catch(f){throw t.error({err:f,...r},`Failed to recursively resolve module '${u.name}': ${f}`),f}let g={...u,steps:h};return n[c]=Nv(g),{...g,...r,type:"RESOLVED_MODULE"}}case"CONDITIONAL":let o=[];for(let c of r.blocks){let s=[];for(let u of c.steps)s.push(await Ys({step:u,callbacks:e,logger:t,resolvedModuleCache:n}));o.push({...c,steps:s})}let i;if(r.elseSteps){i=[];for(let c of r.elseSteps)i.push(await Ys({step:c,callbacks:e,logger:t,resolvedModuleCache:n}))}return{...r,blocks:o,elseSteps:i};case"SECTION":let a=[];for(let c of r.steps)a.push(await Ys({step:c,callbacks:e,logger:t,resolvedModuleCache:n}));return{...r,steps:a};default:return(c=>{throw"If Typescript complains about the line below, you missed a case or break in the switch above"})(r)}}import{diff as Uv}from"deep-object-diff";import{cloneDeep as kv}from"lodash-es";import{v4 as Ch}from"uuid";async function et(r){let e=new Map,t=new Set,n=to.parse({steps:r.stepLists.steps??[],beforeSteps:r.stepLists.beforeSteps??void 0,afterSteps:r.stepLists.afterSteps??void 0}),o=kv(n.steps),i=await ui({...r,steps:o,moduleStepParents:[],moduleIdParents:[],moduleIdReplacements:e,seenModules:t}),a={stepsToSave:{steps:i.stepsToSave,beforeSteps:void 0,afterSteps:void 0},cachesToSave:i.cachesToSave,moduleUpdates:i.moduleUpdates};for(let l of["beforeSteps","afterSteps"]){let c=kv(n[l]);if(!c)continue;let s=await ui({...r,steps:c,moduleStepParents:[],moduleIdParents:[],moduleIdReplacements:e,seenModules:t});a.cachesToSave.push(...s.cachesToSave),a.moduleUpdates.push(...s.moduleUpdates),a.stepsToSave[l]=s.stepsToSave}return a}async function ui({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(delete u.index,delete u.aiSuggested,u.id=c?Ch():u.id,u.type){case"PRESET_ACTION":{let p=u.command;p.id=c?Ch():p.id,"cache"in p&&p.cache&&(n&&(s.cachesToSave=s.cachesToSave.concat(Th({id:p.id,orgId:n.orgId,testId:n.testId,value:On.parse(p),moduleIdParents:o,moduleStepParents:i}))),delete p.cache),p.thoughts&&delete p.thoughts,s.stepsToSave.push({...u,command:p});break}case"RESOLVED_MODULE":{let p=c?Ch():u.id,m=u.moduleId;a.has(m)?m=a.get(m):l!==void 0&&(m=await l(u),a.set(u.moduleId,m));let{cachesToSave:h,stepsToSave:g,moduleUpdates:f}=await ui({...e,steps:u.steps,cacheCreationParams:n?{...n}:void 0,createNewCacheIds:!1,moduleStepParents:[...i,p],moduleIdParents:[...o,m],skipCacheIntermediateEntries:c});s.moduleUpdates=s.moduleUpdates.concat(f),s.cachesToSave=s.cachesToSave.concat(h),t.has(m)||(t.add(m),s.moduleUpdates.push({...ir.parse(u),steps:He.array().parse(g),moduleId:m}));let S=Vr.parse({...u,type:"MODULE",moduleId:m,inputs:u.inputs,id:p,skipped:u.skipped,cacheConfig:u.cacheConfig,envKey:u.envKey});s.stepsToSave.push(S);break}case"AI_ACTION":{if(!u.steps){s.stepsToSave.push(u);break}let{stepsToSave:p,cachesToSave:m}=await ui({...e,steps:u.steps});try{u.steps=hr.array().parse(p)}catch(h){throw new Error(`Only preset actions are allowed in AI actions at the moment: ${h}`)}s.stepsToSave.push(u),s.cachesToSave=s.cachesToSave.concat(m);break}case"AI_ACTION_DYNAMIC":{s.stepsToSave.push(u);break}case"CONDITIONAL":{let p=[];for(let h of u.blocks){let{stepsToSave:g,cachesToSave:f,moduleUpdates:S}=await ui({...e,steps:h.steps});p.push({...h,steps:g}),s.cachesToSave=s.cachesToSave.concat(f),s.moduleUpdates=s.moduleUpdates.concat(S)}let m={...u,elseSteps:void 0,blocks:p};if(u.elseSteps){let{stepsToSave:h,cachesToSave:g,moduleUpdates:f}=await ui({...e,steps:u.elseSteps});m.elseSteps=h,s.cachesToSave=s.cachesToSave.concat(g),s.moduleUpdates=s.moduleUpdates.concat(f)}s.stepsToSave.push(m);break}case"SECTION":{let{stepsToSave:p,cachesToSave:m,moduleUpdates:h}=await ui({...e,steps:u.steps}),g={...u,steps:p};s.moduleUpdates=s.moduleUpdates.concat(h),s.stepsToSave.push(g),s.cachesToSave=s.cachesToSave.concat(m);break}default:return(p=>{throw"If Typescript complains about the line below, you missed a case or break in the switch above"})(u)}return s}async function fu({logger:r,cacheStorage:e,orgId:t,testId:n,originalSteps:o,updatedSteps:i}){let a=Uv(o,i);if(Object.keys(a).length!==0){r.debug("Updating step caches post-success");try{let{cachesToSave:l}=await et({stepLists:i,cacheCreationParams:{testId:n,orgId:t}});await e.saveStepCacheEntries({logger:r,testId:n,entries:l})}catch(l){r.error({err:l},"Failed to save step caches after successful execution. This is not critical, but can impact future performance.")}}}async function Su({logger:r,cacheStorage:e,orgId:t,testId:n,originalSteps:o,updatedSteps:i}){let a=Uv(o,i);if(Object.keys(a).length===0)return;r.debug({changes:a},"Updating memory post-run failure");let l={};for(let u of["steps","beforeSteps","afterSteps"]){let d=o[u];if(!d||!d.length)continue;let p=Xb({steps:d});for(let[m,h]of Object.entries(p))l[m]=h}let{cachesToSave:c}=await et({stepLists:i,cacheCreationParams:{testId:n,orgId:t}}),s=Jb({newEntries:c,originalCachesMap:l,logger:r});if(s.length){r.debug({prunedCaches:s},"Saving pruned memory post-failure");try{await e.saveStepCacheEntries({logger:r,testId:n,entries:c})}catch(u){r.error({err:u},"Failed to save memory after successful execution. This is not critical, but can impact future performance.")}}}import{cloneDeep as C0}from"lodash-es";import{stringify as Fv}from"yaml";async function Bv({test:r,processedModuleNames:e=new Set,createNewCacheIds:t=!1}){let n={id:r.id,name:r.name,description:r.description,baseUrl:r.baseUrl,schemaVersion:r.schemaVersion,advanced:r.advanced,retries:r.retries,envs:r.envs,disabled:r.disabled,labels:r.labels},o={},i=await x0({originalStepLists:{steps:r.steps,beforeSteps:r.beforeSteps,afterSteps:r.afterSteps},modules:o,processedModuleNames:e,createNewCacheIds:t}),a={fileType:pe.TEST,...n,beforeSteps:i.beforeSteps&&i.beforeSteps.length>0?i.beforeSteps:void 0,steps:i.steps,afterSteps:i.afterSteps&&i.afterSteps.length>0?i.afterSteps:void 0};return{test:Fv(a),modules:o}}async function x0({originalStepLists:r,modules:e,processedModuleNames:t,createNewCacheIds:n}){let o=C0(r);Object.values(o).forEach(l=>{_0(l??[])});let{stepsToSave:i,moduleUpdates:a}=await et({stepLists:o,createNewCacheIds:n});for(let l of a)t.has(l.name)||(e[l.name]=I0(l),t.add(l.name));return i}function _0(r){$s({steps:r,onPresetAction:e=>{e.aiSuggested=void 0,e.index=void 0,e.command.thoughts=void 0},onConditional:e=>{e.aiSuggested=void 0,e.index=void 0},onSimpleStepContainer:e=>{e.aiSuggested=void 0,e.index=void 0}})}function I0(r){let e=ir.parse(r),t={fileType:pe.MODULE,...e,schemaVersion:ue,steps:r.steps};return Fv(t)}async function ie(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 Xs({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 Js({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 Xs({promiseGenerator:r,signal:a.signal,codePath:t,logger:n})}finally{i=!0,o?.removeEventListener("abort",l),clearTimeout(c)}}function zv(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}function yu(r){let e=[];for(let t of r)switch(t.type){case"PRESET_ACTION":case"AI_ACTION":case"AI_ACTION_DYNAMIC":e.push(t);break;case"RESOLVED_MODULE":{let n={...t,type:"MODULE"};e.push(Vr.parse(n));break}case"SECTION":{let n={...t,steps:yu(t.steps)};e.push(He.parse(n));break}case"CONDITIONAL":{let n={...t,blocks:t.blocks.map(o=>({assertion:o.assertion,steps:yu(o.steps)})),elseSteps:t.elseSteps?yu(t.elseSteps):void 0};e.push(Wo.parse(n));break}default:return(o=>{throw"If Typescript complains about the line below, you missed a case or break in the switch above"})(t)}return e}function Eu(r){return yu([r])[0]}import M0 from"picomatch";var Tu=(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||M0(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},bu=(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}},da=r=>{try{return new URL(r),!0}catch{return!1}},Hv=r=>!r.toLowerCase().startsWith("http"),pa=(r,e)=>{try{return new URL(r,e),!0}catch{return!1}};function di(r,e){try{return!!new URL(r).origin.trim()}catch(t){return e?.error({url:r,err:t},"Invalid URL in check"),!1}}async function P0(r){let{logger:e,browserStateStorage:t,generator:n,results:o,error:i,maxItemsFromEnd:a,numStepsWithScreenshots:l,disableCache:c}=r,s=[];if(o.length>0){let{results:d}=await ca(e,t,o,{numStepsWithScreenshots:l,maxItemsFromEnd:a,includeBeforeScreenshots:!0,includeContainerTagsInDescription:!0});s=d}return await n.getTestResultClassification({results:s,errorMessage:i.message,errorStack:i.stack},{disableCache:c??!1})}async function Gv(r){let{logger:e,browserStateStorage:t,generator:n,fullResults:o,failureReason:i,error:a,maxItemsFromEnd:l,numStepsWithScreenshots:c,disableCache:s}=r,u=o?.results??[];if(i==="SetupFailureError"){let d=(o?.beforeResults??[]).at(0);u=[du("setup",{followingStepStart:d?.startedAt}),...o?.beforeResults??[]]}else if(i==="TeardownFailureError"){let d=u.at(-1),p=(o?.afterResults??[])[0],m=du("teardown",{precedingStepEnd:d?.finishedAt,followingStepStart:p?.startedAt});u=[...u,m,...o?.afterResults??[]]}else if(u.length<20){let d=(o?.beforeResults??[]).at(-1),p=u.at(0),m=du("main-test-body",{precedingStepEnd:d?.finishedAt,followingStepStart:p?.startedAt});u=[...o?.beforeResults??[],m,...u]}if(!t||!u||u.length===0)return{};try{let d=await P0({logger:e,browserStateStorage:t,generator:n,results:u,error:a,maxItemsFromEnd:l,numStepsWithScreenshots:c,disableCache:s});return{classification:d,aiFailureReason:d.reason}}catch(d){return e.error({err:d},"Failed to classify test result"),{}}}import{v4 as jv}from"uuid";function xh(r,e){return{...r,testId:e?.testId??"",testName:e?.testName??"",suiteId:e?.suiteId??"",suiteName:e?.suiteName??""}}var vu=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:xh({},this.metadata)}]).catch(l=>e.error({err:l},"Failed to report billable event"))]}trackStepExecution(e){if(JE(e.type)){this.creditsUsedV2+=1;return}let t=Om(e.type);if(this.creditsUsedV1+=t??0,e.type==="PRESET_ACTION"){this.creditsUsedV2+=1;let n=Lm(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:jv(),properties:xh({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:jv(),properties:xh({creditsUsed:this.creditsUsedV2},this.metadata)}]).catch(t=>e.error({err:t},"Failed to report credits used"))),await Promise.allSettled(this.asyncWork)}};function ma({orgId:r,client:e,gitMetadata:t,alwaysSaveCache:n,noCache:o}){return o?new qc:new _h(r,e,t,n)}var _h=class{constructor(e,t,n,o){this.orgId=e;this.client=t;let{gitBranchName:i,gitProtectedBranches:a}=n;this.cacheHeaders=eh(n),o?this.writeCaches=!0:i?this.writeCaches=!a.includes(i):this.writeCaches=!0}cacheHeaders;writeCaches;async saveStepCacheEntries({entries:e,testId:t,logger:n}){if(!this.writeCaches){n.debug("Skipping cache storage because branch is protected");return}try{await this.client.updateStepCaches({entries:e,testId:t},this.cacheHeaders)}catch(o){n.error({err:o},"Failed to save step cache entries")}}async resolveStepCacheEntries(e){let{steps:t,beforeSteps:n,afterSteps:o}=e.stepLists,i=await this.client.getStepCacheForTest({testId:e.testId},this.cacheHeaders);if(!this.writeCaches){e.logger.debug("Skipping cache last used at update because branch is protected");return}for(let l of[t,n,o])l&&la({steps:l,stepCacheEntries:i,logger:e.logger});let{cachesToSave:a}=await et({stepLists:e.stepLists,cacheCreationParams:{testId:e.testId,orgId:this.orgId}});this.client.updateStepCaches({entries:a,testId:e.testId},this.cacheHeaders)}};import O0 from"path";var L0=new eu(30,60*1e3),Oh="https://api.momentic.ai",$v,Wv=r=>{Oh=r},qr=()=>Oh;var ha,Ph,Au,qv=async r=>{if($v&&ha&&Au)return ha;let e=new Ze({baseUrl:Oh,apiKey:r,logger:T});$v=e;try{let t=await e.getAuthInfo();return ha=t.orgId,Ph=t.userId,Au=r,ha}catch(t){throw new Error(`Error checking API key against server: ${t}`)}},xt=()=>{if(!ha)throw new Error("Your organization ID is invalid.");return ha},ga=()=>{if(!Ph)throw new Error("Your user ID is invalid.");return Ph},Kr=()=>{if(!Au)throw new Error("Your API key is invalid.");return Au},Lh,Ih,Ru=(r,e)=>{Lh=r,Ih?.abort(),Ih=new AbortController;let t=Ih.signal,n=[r.configFilePath];r.config.environments?.forEach(o=>{if(!o.envFile)return;let i=O0.resolve(r.rootDir,o.envFile);try{if(Mh.lstatSync(i).isSymbolicLink())return;Mh.existsSync(i)&&n.push(i)}catch(a){T.warn({err:a},`Failed to check if env file ${i} exists`)}});try{N0({filesToWatch:n,revalidator:e,signal:t,project:r})}catch(o){T.error({err:o},"Failed to start config file watchers")}},ce=()=>Lh;function N0({filesToWatch:r,revalidator:e,signal:t,project:n}){r.forEach(o=>{Mh.watch(o,{signal:t,persistent:!1,recursive:!1},async(i,a)=>{a&&(L0.increment("setLocalProject")&&T.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.`),Lh=await Promise.resolve(e(n.configFilePath)))})})}function Re(r){return function(...e){let t=e[e.length-1],n=r(...e);Promise.resolve(n).catch(t)}}var Zs=D0();function Qs(r){let e=ce(),t=_t.dirname(e.configFilePath);return _t.join(t,...r)}function U0(r){let e=ce(),t=_t.dirname(e.configFilePath),n=_t.relative(t,r);return n?n.split(_t.sep):[]}function F0(r,e){let t=rr.statSync(r),n=U0(r);return Wm.parse({name:e,absolutePath:r,relativePath:n.join(_t.sep),pathSegments:n,isDirectory:t.isDirectory(),size:t.size,createdAt:t.birthtime,modifiedAt:t.mtime,accessedAt:t.atime})}Zs.post("/",Re(async(r,e,t)=>{let n;try{n=TT.parse(r.body).pathSegments}catch(d){e.status(400).json({error:`Failed to parse folder read body: ${d}`});return}let o=Qs(n);if(!rr.existsSync(o)){e.status(404).json({error:`Path not found: ${n.join(_t.sep)}`});return}if(!rr.statSync(o).isDirectory()){e.status(400).json({error:`Path is not a directory: ${n.join(_t.sep)}`});return}let a=ce(),l=Array.from(a.config.exclude??[]).concat(Hc),s=k0("*",{absolute:!1,cwd:o,ignore:l,dotRelative:!1,maxDepth:1,nodir:!1}).map(d=>{let p=_t.join(o,d);return F0(p,d)}),u={absolutePath:o,pathSegments:n,contents:s};e.status(200).json(u)}));Zs.put("/",Re(async(r,e,t)=>{let n;try{n=bT.parse(r.body).pathSegments}catch(a){e.status(400).json({error:`Failed to parse folder create body: ${a}`});return}let o=Qs(n);if(rr.existsSync(o)){e.status(200).json({success:!0,message:`Folder already exists: ${n.join(_t.sep)}`,pathSegments:n});return}rr.mkdirSync(o,{recursive:!0});let i={success:!0,message:`Folder created: ${n.join(_t.sep)}`,pathSegments:n};e.status(201).json(i)}));Zs.patch("/",Re(async(r,e,t)=>{let n,o;try{let s=vT.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=Qs(n),a=Qs(o);if(!rr.existsSync(i)){e.status(400).json({error:`Folder not found: ${n.join(_t.sep)}`});return}if(rr.existsSync(a)){e.status(400).json({error:`Destination already exists: ${o.join(_t.sep)}`});return}let l=_t.dirname(a);rr.existsSync(l)||rr.mkdirSync(l,{recursive:!0}),rr.renameSync(i,a);let c={success:!0,message:`Folder moved from ${n.join(_t.sep)} to ${o.join(_t.sep)}`,pathSegments:o};e.status(200).json(c)}));Zs.delete("/",Re(async(r,e,t)=>{let n,o=!0;try{let c=AT.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=Qs(n);if(!rr.existsSync(i)){e.status(200).json({success:!0,message:`Folder not found: ${n.join(_t.sep)}`,pathSegments:n});return}if(!rr.statSync(i).isDirectory()){e.status(400).json({error:`Path is not a directory: ${n.join(_t.sep)}`});return}if(o)rr.rmSync(i,{recursive:!0,force:!0});else{if(rr.readdirSync(i).length>0){e.status(409).json({error:`Cannot delete non-empty directory without recursive flag: ${n.join("/")}`});return}rr.rmdirSync(i)}let l={success:!0,message:`Folder deleted: ${n.join("/")}`,pathSegments:n};e.status(200).json(l)}));var Nh=Zs;import m$ from"events";import kI,{Router as h$}from"express";import{diff as G0}from"deep-object-diff";import Xr from"fs";import mi from"path";import fa from"yaml";import{z as Xv}from"zod";import{execSync as B0}from"child_process";function kn(r,e){let t=e.hooks?.postSave;if(!t)return;let n;t.includes("$1")?n=t.replaceAll("$1",r):n=`${t} ${r}`,T.debug({postSaveCommand:n},"Executing post-save hook command");try{B0(n,{encoding:"utf-8"})}catch(o){T.warn({err:o,postSaveCommand:n},"Failed to execute post-save hook command, continuing...")}}import{diff as Kv}from"deep-object-diff";import fn from"fs";import{cloneDeep as z0}from"lodash-es";import el from"path";import{v4 as H0}from"uuid";import tl from"yaml";function nr({content:r,schemaVersion:e,momenticFiles:t,project:n,forceSaveOnNoDiffs:o}){let i=t.modules[r.moduleId]?.fullFilePath;if(!i||!fn.existsSync(i))throw new Error(`Tried to update module ${r.moduleId} that could not be found on disk`);let a=fn.readFileSync(i,"utf-8"),l=tl.parse(a),c;if(r.name&&r.name!==l.name){let m=`${Oe(r.name)}.module.yaml`;if(c=el.join(el.dirname(i),m),fn.existsSync(c))throw new Error(`A conflicting file '${r.name}' already exists at path '${c}'`)}let s={...r,schemaVersion:e},u=hn({fileType:pe.MODULE,...Ym.parse(s),steps:He.array().parse(r.steps)}),d=Kv(u,l);if(d&&Object.keys(d).length===0&&!o){T.debug(`Skipping save for module ${r.moduleId} since there are no changes`);return}let p=tl.stringify(u);fn.writeFileSync(i,p,"utf-8"),c&&fn.renameSync(i,c),kn(c||i,n.config)}function Yv({moduleId:r,content:e,momenticFiles:t,project:n,logger:o}){let i=t.modules[r]?.fullFilePath;if(!i)throw new Error(`Tried to update module ${r} that could not be found on disk`);let a=Un(i,o),l={...a,...e},c=hn({fileType:pe.MODULE,...Ym.parse(l),steps:a.steps}),s=Kv(c,a);if(s&&Object.keys(s).length===0){T.debug(`Skipping save for module ${r} since there are no changes`);return}let u=tl.stringify(c);fn.writeFileSync(i,u,"utf-8");let d;if(e.name){let p=`${Oe(e.name)}.module.yaml`;if(d=el.join(el.dirname(i),p),fn.existsSync(d))throw new Error(`Module with name '${e.name}' already exists at path '${d}'`);fn.renameSync(i,d)}kn(d||i,n.config)}async function wu({name:r,description:e,enabled:t,steps:n,folder:o,project:i}){let a=Oe(r),l=el.join(o,`${a}.module.yaml`),c=H0(),{stepsToSave:s}=await et({stepLists:{steps:n}}),u={fileType:pe.MODULE,schemaVersion:ue,moduleId:c,name:r,description:e,enabled:t,steps:s.steps},d=tl.stringify(u);return fn.writeFileSync(l,d,"utf-8"),kn(l,i.config),{moduleId:c,name:r,description:e,enabled:t,steps:n}}function Un(r,e){let t=fn.readFileSync(r,"utf-8"),n=tl.parse(t);try{return Um.parse(n)}catch(o){throw e.error({err:o,moduleFilePath:r,moduleContents:t},`${r} does not parse as a valid Momentic module`),o}}async function Yr(r,e,t,n){let o=Un(r.fullFilePath,t),{resolvedSteps:i}=await gu({rawSteps:o.steps,migrationMetadata:{id:o.moduleId,schemaVersion:o.schemaVersion},resolvedModuleCache:n,logger:t,callbacks:{onFetchModule:async({id:l})=>{let c=e.modules[l]?.fullFilePath;if(c)return Un(c,t)}}}),a={...o,steps:i};return n&&(n[r.id]=z0(a)),a}async function Cu(r,e){let t={};return await Promise.all(Object.values(r.modules).map(async n=>{await Yr(n,r,e,t)})),Array.from(Object.values(t))}async function Jv({test:r,name:e,folder:t}){let n=await Bv({test:r});if(Object.keys(n.modules).length)throw new Error("A brand new test should not contain any modules in it");let i=`${Oe(e)}.test.yaml`,a=mi.join(t,i);return Xr.writeFileSync(a,n.test,"utf-8"),a}function Dh(r,e,t){let n=mi.join(t.rootDir,r);if(!Xr.existsSync(n))throw new Error(`Test not found at path '${r}' in project '${t.rootDir}'`);let o=Xr.readFileSync(n,"utf-8"),i=fa.parse(o),a,l;if(e.name&&e.name!==i.name){let p=`${Oe(e.name)}.test.yaml`;if(a=mi.join(mi.dirname(r),p),l=mi.join(t.rootDir,a),Xr.existsSync(l))throw new Error(`Test with name '${e.name}' already exists at path '${l}'`)}let c={...i,...e},s=xr.parse(c),u={fileType:pe.TEST,...xr.parse(s),beforeSteps:i.beforeSteps??void 0,steps:i.steps,afterSteps:i.afterSteps??void 0},d=fa.stringify(u);return Xr.writeFileSync(n,d,"utf-8"),l&&Xr.renameSync(n,l),kn(n,t.config),{newRelativeTestPath:a}}function qt({relativeTestPath:r,steps:e,schemaVersion:t,project:n,forceSaveOnNoDiffs:o}){let i=mi.join(n.rootDir,r);if(!Xr.existsSync(i))throw new Error(`Test not found at path '${r}' in project '${n.rootDir}'`);let a=Xr.readFileSync(i,"utf-8"),l=fa.parse(a),c=xr.parse({...l,schemaVersion:t}),s=He.array().or(Xv.undefined()).parse(e.beforeSteps),u=He.array().parse(e.steps),d=He.array().or(Xv.undefined()).parse(e.afterSteps),p=hn({fileType:pe.TEST,...c,beforeSteps:s&&s.length>0?s:void 0,steps:u,afterSteps:d&&d.length>0?d:void 0}),m=G0(p,l);if(m&&Object.keys(m).length===0&&!o){T.debug(`Skipping save for test ${c.name} since there are no changes`);return}let h=fa.stringify(p);Xr.writeFileSync(i,h,"utf-8"),T.debug(`Saving test ${c.name} to ${i}`),kn(i,n.config)}function rl(r,e){let t=mi.join(e.rootDir,r);if(!t)throw new Error(`Could not find test with path ${r} in Momentic project (${e.rootDir})`);let n;try{n=Xr.readFileSync(t,"utf8"),n=n.replace(/\r\n|\r/g,`
|
|
38
|
+
${o}`:o)(Rh(r))}function du(r,e={}){let t=e.followingStepStart??e.precedingStepEnd??new Date;return{type:"PRESET_ACTION",id:Zb(),message:`Starting the ${r.replace("-"," ")} section`,startedAt:t,finishedAt:t,status:"SUCCESS",command:{id:Zb(),type:"SUCCESS"},results:[]}}function uu(r,e={}){let{index:t,includeDomState:n=!1,header:o}=e,i=m0(r,o),a;r.type==="PRESET_ACTION"&&(a=r.results?.[0]?.elementInteracted);let l=r.message!=="Successfully executed preset action."?r.message:void 0,c=i;r.status==="FAILED"&&(c=`${p0} ${c}`);let s={description:c,startedAt:r.startedAt.toISOString(),finishedAt:r.finishedAt.toISOString(),beforeUrl:r.beforeUrl,afterUrl:r.afterUrl,beforeSnapshot:r.beforeSnapshot,afterSnapshot:r.afterSnapshot,elementInteracted:a,message:l,index:t};if(r.status==="FAILED"&&n)try{let u=mE.array().parse(r.details);for(let d of u)"pageState"in d&&(s.pageState=d.pageState)}catch{}return s}async function iv(r,e,t,{addIndices:n=!0,includeDomState:o=!1,flatten:i=!0,maxItemsFromEnd:a=15,indexOffset:l=0}){let c,s=[];for(let u=0;u<t.length;u++){let d=t[u],p=n?u+l:void 0;switch(d.type){case"PRESET_ACTION":{s.push(uu(d,{index:p,includeDomState:o,header:void 0})),d.status==="FAILED"&&(c=p);break}case"CONDITIONAL":case"AI_ACTION":case"AI_ACTION_DYNAMIC":case"MODULE":case"SECTION":{if(i){s.push(uu(d,{index:n?p:void 0,includeDomState:o,header:"start"})),l+=1;let{failureIndex:m,results:h}=await iv(r,e,d.results,{addIndices:n,includeDomState:o,flatten:i,maxItemsFromEnd:a,indexOffset:l+u});s.push(...h),m!==void 0&&(c=m),l+=h.length,s.push(uu(d,{index:n?l+u:void 0,includeDomState:o,header:"end"})),l+=1}else s.push(uu(d,{index:n?l+u:void 0,includeDomState:o,header:void 0}));break}default:return(h=>{throw new Error("You missed a case in the switch above")})(d)}}return{results:s,failureIndex:c}}async function ca(r,e,t,{numStepsWithScreenshots:n=5,addIndices:o=!0,includeBeforeScreenshots:i=!1,includeDomState:a=!1,flatten:l=!0,maxItemsFromEnd:c=20}){let s=await iv(r,e,t,{addIndices:o,includeDomState:a,flatten:l,maxItemsFromEnd:c,indexOffset:0}),{results:u}=s,{failureIndex:d}=s;d!==void 0&&u.length>0&&(u=u.slice(0,d+1));let p=[],m=0;if(c!==void 0&&u.length>c&&(m=u.length-c),d!==void 0&&d<u.length-1&&r.warn("PROCESS_RESULTS_FOR_LLM: Failure index check - should not be possible",{failureIndex:d,flattenedResultsLength:u.length,lastIndex:u.length-1,isLastIndex:d===u.length-1,offset:m}),d!==void 0&&m>d)throw new Error("Failure index is out of bounds");for(let h=m;h<u.length;h++){let g=u[h],f={description:g.description,startedAt:g.startedAt,finishedAt:g.finishedAt,beforeUrl:g.beforeUrl,afterUrl:g.afterUrl,elementInteracted:g.elementInteracted,message:g.message,pageState:g.pageState,index:g.index},y,S;(n===void 0||n>0&&h>=u.length-n)&&(g.afterSnapshot&&(S=await rv(r,e,g.afterSnapshot)),i&&g.beforeSnapshot&&(y=await rv(r,e,g.beforeSnapshot))),f.beforeScreenshot=y,f.afterScreenshot=S,p.push(f)}return{results:p,failureIndex:d!==void 0?d-m:void 0}}function ua({json:r,keysToRedact:e,maxJsonStringSize:t}){try{if(!r)return r;if(typeof r=="string")return it(r,t??2e4);if(typeof r=="object"){let{jsonString:n}=ov(JSON.stringify(r,(o,i)=>e?.includes(o)||typeof i=="string"&&i.length>3e4?"REDACTED":i),t??2e4);return JSON.parse(n)}return r}catch{return r}}function wh(r,e){for(let t=0;t<r.length;t++){let n=r[t];try{if(n.data){let{jsonString:o}=ov(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.details&&(n.details=void 0),n.type){case"PRESET_ACTION":nv(n);break;case"CONDITIONAL":n.assertionResult&&nv(n.assertionResult),wh(n.results,e);break;case"AI_ACTION_DYNAMIC":case"AI_ACTION":case"MODULE":case"SECTION":{wh(n.results,e);break}default:return(i=>{throw new Error("If Typescript complains about the line below, you missed a case or break in the switch above")})(n)}}}function nv(r){let e=r.command;"cache"in e&&e.cache&&(e.cache=void 0)}function pu(r,e){let t=d0(r);if(wh(t,e),t.length>ev)return e.error("Results too long, truncating before insertion"),t.slice(t.length-ev,t.length);let n=JSON.stringify(t);if(n.length>tv)for(e.error({serializedLength:n.length,resultsArrayLength:t.length},"Database content violation: results too large, truncating before insertion");n.length>tv;)t.splice(0,1),n=JSON.stringify(t);try{return bt.array().parse(JSON.parse(n))}catch(o){throw e.error({serialized:n,err:o},"Could not parse serialized results into JSON structure after processing"),o}}import{cloneDeep as dle}from"lodash-es";var h0=/^(?!.*\S+\s+\S+).*$/,g0=/^[a-zA-Z0-9\s.,;:'"!?()\- \u00C0-\u00FF]+$/,f0=/style="([^"]*)/g,S0=/data-[\w-]+/g,y0=r=>{switch(r.type){case"AI_ASSERTION":return{type:r.type,assertion:r.assertion};case"DRAG":if(r.fromTarget.type==="description")return{type:r.type,description:r.fromTarget.elementDescriptor};break;case"CLICK":case"BLUR":case"TYPE":case"SELECT_OPTION":case"ELEMENT_CHECK":case"FOCUS":case"HOVER":case"MOUSE_DRAG":case"VISUAL_DIFF":case"SCROLL_DOWN":case"SCROLL_UP":case"SCROLL_LEFT":case"SCROLL_RIGHT":if(r.target?.type==="description")return{type:r.type,description:r.target.elementDescriptor};break}return{type:"NONE",description:"NONE"}};function av(r){let e=y0(r),t=e.type==="AI_ASSERTION"?e.assertion:e.description;return!t||t==="NONE"?{thoughts:"NONE",category:"NO_DESCRIPTION_PROVIDED"}:h0.test(t)&&g0.test(t)?{thoughts:"The target description is too short. Please provide more details.",category:"FEW_WORDS"}:f0.test(t)?{thoughts:"Style tags are not recommended in the command description as they change frequently. Please remove them and describe the target in a different way.",category:"STYLE_TAG"}:S0.test(t)?{thoughts:"Hardcoded data attributes are not recommended in the command description as they change frequently.",category:"HARDCODED_ATTRIBUTE"}:new RegExp(`\\b${e.type}\\b`,"gi").test(t)?{thoughts:`The element description you provided starts with the command type (${e.type}). This can confuse our AI agents since the element itself is unrelated to the desired action.`,category:"TYPE_IN_DESCRIPTION"}:{thoughts:"NONE",category:"NONE"}}function sv(r,e){if(!(!r.envs||!r.envs.length)){for(let t of r.envs){let n=t;e in t&&(n[e]&&(t.default=!0),delete n.defaultOnCloud,delete n.defaultOnLocal)}r.envs.some(t=>t.default)||(r.envs[0].default=!0)}}import{cloneDeep as Nv}from"lodash-es";import A0 from"diff-lines";import hu,{gte as R0}from"semver";var lv={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 cv={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 E0=["target","fromTarget","toTarget"];function uv(r){for(let e of E0){if(r[e]===void 0)continue;let t=r[e];t.elementDescriptor!==void 0?t.type="description":r[e]={type:"description",elementDescriptor:""}}}var dv={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 uv(e.command),e;case"AI_ACTION":{let t=e.commands;for(let n of t??[])uv(n);return e}default:return e}})};import{v4 as T0}from"uuid";var pv={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=T0()),e;default:return e}})};import{v4 as mv}from"uuid";var hv={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??mv(),e}case"AI_ACTION":return e.commands&&(e.steps=e.commands.map(t=>({type:"PRESET_ACTION",command:{...t,id:t.id??mv()}})),delete e.commands),e;default:return e}})};var gv={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 b0}from"uuid";var fv={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=b0()),e))};import{v4 as Sv}from"uuid";var yv={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=Sv())}return e.id=Sv(),e})};var Ev={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 v0}from"uuid";var Tv={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=v0()),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 bv={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 vv={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&&Av(t),e})};function Av(r){r&&Object.keys(r).forEach(e=>{if(typeof r[e]=="object"&&r[e]){Av(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 Rv={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 wv={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 Cv={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 xv={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 _v={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 Iv={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 mu=new Set(["CLICK","TYPE","SELECT_OPTION"]),Mv={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||mu.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||mu.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||mu.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||mu.has(m))&&(d.target={elementDescriptor:p??""})})}),e}),stopOnFailure:!0};var Pv={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 Ov={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 li=[Iv,Pv,Ov,Mv,lv,cv,dv,pv,hv,gv,fv,yv,Ev,Tv,bv,vv,Rv,wv,Cv,xv,_v];if(ue!==li[li.length-1].toVersion)throw new Error("Please bump LATEST_SCHEMA_VERSION in types package after adding a migration");li.forEach((r,e)=>{if(!hu.valid(r.toVersion)||!hu.valid(r.fromVersion))throw new Error(`Migration '${r.name}' has invalid version`);if(!hu.gt(r.toVersion,r.fromVersion))throw new Error(`Migration '${r.name}' has toVersion <= fromVersion`);if(e===0)return;if(li[e-1].toVersion!==r.fromVersion)throw new Error(`Migration '${r.name}' at index ${e} is not contiguous with previous migration`)});function w0(r){return r.every(e=>e&&typeof e=="object"&&!Array.isArray(e))}var Ks=async({metadata:r,steps:e,logger:t,toVersion:n})=>{let o=e,{schemaVersion:i,id:a}=r,l=li.findIndex(u=>hu.gt(u.toVersion,i));if(l===-1)return{steps:o,newVersion:i};let c=i;for(let u=l;u<li.length;u++){if(n&&R0(c,n)){t.debug("Stopping migration early because toVersion was reached");break}let d=li[u],p={id:a,migration:d.name,toVersion:d.toVersion};try{o=await Lv(o,d),c=d.toVersion}catch(m){throw t.error({err:m,...p},"Migration failed"),new Error(`Step migration ${d.name} failed: ${m}`)}}let s=A0(JSON.stringify(e,void 0,2),JSON.stringify(o,void 0,2),{n_surrounding:1});return s.trim()&&t.debug({diffs:s,id:a},"Migration diffs"),{newVersion:c,steps:o}};async function Lv(r,e){let t=await e.execute(r);for(let n of t)for(let o of Object.keys(n)){if(!e.recursiveKeys.has(o))continue;let i=n[o];!i||!Array.isArray(i)||w0(i)&&(n[o]=await Lv(i,e))}return t}async function Dv({rawSteps:r,metadata:e,logger:t,callbacks:n}){sv(e,"defaultOnCloud");let o={},{resolvedSteps:i,newSchemaVersion:a}=await gu({rawSteps:r.steps,migrationMetadata:e,logger:t,callbacks:n,resolvedModuleCache:o}),l={...e,steps:i,schemaVersion:a};for(let c of["beforeSteps","afterSteps"]){let s=r[c];if(!s)continue;let{resolvedSteps:u}=await gu({rawSteps:s,migrationMetadata:e,logger:t,callbacks:n,resolvedModuleCache:o});l[c]=u}return{resolvedTest:l,moduleIds:Array.from(Object.keys(o))}}async function ci(r,e,t){let{newVersion:n,steps:o}=await Ks({metadata:r,steps:e,logger:t});try{return{steps:He.array().parse(o),newVersion:n}}catch(i){throw t.error({type:"zod",err:i,newVersion:n,id:r.id,steps:o},"Failed to parse test steps while migrating test"),new uc(`Failed to parse test steps while migrating test: ${i}`,r.id,"entity",{cause:i})}}async function gu({rawSteps:r,migrationMetadata:e,logger:t,callbacks:n,resolvedModuleCache:o={}}){let{newVersion:i,steps:a}=await ci(e,r,t),l=[];for(let c of a)l.push(await Ys({step:c,callbacks:n,logger:t,resolvedModuleCache:o}));return{resolvedSteps:l,newSchemaVersion:i}}async function Ys({step:r,callbacks:e,logger:t,resolvedModuleCache:n}){switch(r.type){case"AI_ACTION":return r;case"AI_ACTION_DYNAMIC":return r;case"PRESET_ACTION":return r;case"MODULE":{let c=r.moduleId,s=n[c];if(s)return{...Nv(s),...r,type:"RESOLVED_MODULE"};let u=await e.onFetchModule({id:c,logger:t});if(!u)throw new Error(`Could not find module with id ${c}`);let{newVersion:d,steps:p}=await Ks({metadata:{id:c,schemaVersion:u.schemaVersion},steps:u.steps,logger:t}),m;try{m=He.array().parse(p)}catch(f){throw t.error({type:"zod",err:f,steps:p,newVersion:d,id:c},"Module failed to parse"),f}let h;try{h=await Promise.all(m.map(f=>Ys({step:f,callbacks:e,logger:t,resolvedModuleCache:n})))}catch(f){throw t.error({err:f,...r},`Failed to recursively resolve module '${u.name}': ${f}`),f}let g={...u,steps:h};return n[c]=Nv(g),{...g,...r,type:"RESOLVED_MODULE"}}case"CONDITIONAL":let o=[];for(let c of r.blocks){let s=[];for(let u of c.steps)s.push(await Ys({step:u,callbacks:e,logger:t,resolvedModuleCache:n}));o.push({...c,steps:s})}let i;if(r.elseSteps){i=[];for(let c of r.elseSteps)i.push(await Ys({step:c,callbacks:e,logger:t,resolvedModuleCache:n}))}return{...r,blocks:o,elseSteps:i};case"SECTION":let a=[];for(let c of r.steps)a.push(await Ys({step:c,callbacks:e,logger:t,resolvedModuleCache:n}));return{...r,steps:a};default:return(c=>{throw"If Typescript complains about the line below, you missed a case or break in the switch above"})(r)}}import{diff as Uv}from"deep-object-diff";import{cloneDeep as kv}from"lodash-es";import{v4 as Ch}from"uuid";async function et(r){let e=new Map,t=new Set,n=to.parse({steps:r.stepLists.steps??[],beforeSteps:r.stepLists.beforeSteps??void 0,afterSteps:r.stepLists.afterSteps??void 0}),o=kv(n.steps),i=await ui({...r,steps:o,moduleStepParents:[],moduleIdParents:[],moduleIdReplacements:e,seenModules:t}),a={stepsToSave:{steps:i.stepsToSave,beforeSteps:void 0,afterSteps:void 0},cachesToSave:i.cachesToSave,moduleUpdates:i.moduleUpdates};for(let l of["beforeSteps","afterSteps"]){let c=kv(n[l]);if(!c)continue;let s=await ui({...r,steps:c,moduleStepParents:[],moduleIdParents:[],moduleIdReplacements:e,seenModules:t});a.cachesToSave.push(...s.cachesToSave),a.moduleUpdates.push(...s.moduleUpdates),a.stepsToSave[l]=s.stepsToSave}return a}async function ui({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(delete u.index,delete u.aiSuggested,u.id=c?Ch():u.id,u.type){case"PRESET_ACTION":{let p=u.command;p.id=c?Ch():p.id,"cache"in p&&p.cache&&(n&&(s.cachesToSave=s.cachesToSave.concat(Th({id:p.id,orgId:n.orgId,testId:n.testId,value:On.parse(p),moduleIdParents:o,moduleStepParents:i}))),delete p.cache),p.thoughts&&delete p.thoughts,s.stepsToSave.push({...u,command:p});break}case"RESOLVED_MODULE":{let p=c?Ch():u.id,m=u.moduleId;a.has(m)?m=a.get(m):l!==void 0&&(m=await l(u),a.set(u.moduleId,m));let{cachesToSave:h,stepsToSave:g,moduleUpdates:f}=await ui({...e,steps:u.steps,cacheCreationParams:n?{...n}:void 0,createNewCacheIds:!1,moduleStepParents:[...i,p],moduleIdParents:[...o,m],skipCacheIntermediateEntries:c});s.moduleUpdates=s.moduleUpdates.concat(f),s.cachesToSave=s.cachesToSave.concat(h),t.has(m)||(t.add(m),s.moduleUpdates.push({...ir.parse(u),steps:He.array().parse(g),moduleId:m}));let y=Vr.parse({...u,type:"MODULE",moduleId:m,inputs:u.inputs,id:p,skipped:u.skipped,cacheConfig:u.cacheConfig,envKey:u.envKey});s.stepsToSave.push(y);break}case"AI_ACTION":{if(!u.steps){s.stepsToSave.push(u);break}let{stepsToSave:p,cachesToSave:m}=await ui({...e,steps:u.steps});try{u.steps=hr.array().parse(p)}catch(h){throw new Error(`Only preset actions are allowed in AI actions at the moment: ${h}`)}s.stepsToSave.push(u),s.cachesToSave=s.cachesToSave.concat(m);break}case"AI_ACTION_DYNAMIC":{s.stepsToSave.push(u);break}case"CONDITIONAL":{let p=[];for(let h of u.blocks){let{stepsToSave:g,cachesToSave:f,moduleUpdates:y}=await ui({...e,steps:h.steps});p.push({...h,steps:g}),s.cachesToSave=s.cachesToSave.concat(f),s.moduleUpdates=s.moduleUpdates.concat(y)}let m={...u,elseSteps:void 0,blocks:p};if(u.elseSteps){let{stepsToSave:h,cachesToSave:g,moduleUpdates:f}=await ui({...e,steps:u.elseSteps});m.elseSteps=h,s.cachesToSave=s.cachesToSave.concat(g),s.moduleUpdates=s.moduleUpdates.concat(f)}s.stepsToSave.push(m);break}case"SECTION":{let{stepsToSave:p,cachesToSave:m,moduleUpdates:h}=await ui({...e,steps:u.steps}),g={...u,steps:p};s.moduleUpdates=s.moduleUpdates.concat(h),s.stepsToSave.push(g),s.cachesToSave=s.cachesToSave.concat(m);break}default:return(p=>{throw"If Typescript complains about the line below, you missed a case or break in the switch above"})(u)}return s}async function fu({logger:r,cacheStorage:e,orgId:t,testId:n,originalSteps:o,updatedSteps:i}){let a=Uv(o,i);if(Object.keys(a).length!==0){r.debug("Updating step caches post-success");try{let{cachesToSave:l}=await et({stepLists:i,cacheCreationParams:{testId:n,orgId:t}});await e.saveStepCacheEntries({logger:r,testId:n,entries:l})}catch(l){r.error({err:l},"Failed to save step caches after successful execution. This is not critical, but can impact future performance.")}}}async function Su({logger:r,cacheStorage:e,orgId:t,testId:n,originalSteps:o,updatedSteps:i}){let a=Uv(o,i);if(Object.keys(a).length===0)return;r.debug({changes:a},"Updating memory post-run failure");let l={};for(let u of["steps","beforeSteps","afterSteps"]){let d=o[u];if(!d||!d.length)continue;let p=Xb({steps:d});for(let[m,h]of Object.entries(p))l[m]=h}let{cachesToSave:c}=await et({stepLists:i,cacheCreationParams:{testId:n,orgId:t}}),s=Jb({newEntries:c,originalCachesMap:l,logger:r});if(s.length){r.debug({prunedCaches:s},"Saving pruned memory post-failure");try{await e.saveStepCacheEntries({logger:r,testId:n,entries:c})}catch(u){r.error({err:u},"Failed to save memory after successful execution. This is not critical, but can impact future performance.")}}}import{cloneDeep as C0}from"lodash-es";import{stringify as Fv}from"yaml";async function Bv({test:r,processedModuleNames:e=new Set,createNewCacheIds:t=!1}){let n={id:r.id,name:r.name,description:r.description,baseUrl:r.baseUrl,schemaVersion:r.schemaVersion,advanced:r.advanced,retries:r.retries,envs:r.envs,disabled:r.disabled,labels:r.labels},o={},i=await x0({originalStepLists:{steps:r.steps,beforeSteps:r.beforeSteps,afterSteps:r.afterSteps},modules:o,processedModuleNames:e,createNewCacheIds:t}),a={fileType:pe.TEST,...n,beforeSteps:i.beforeSteps&&i.beforeSteps.length>0?i.beforeSteps:void 0,steps:i.steps,afterSteps:i.afterSteps&&i.afterSteps.length>0?i.afterSteps:void 0};return{test:Fv(a),modules:o}}async function x0({originalStepLists:r,modules:e,processedModuleNames:t,createNewCacheIds:n}){let o=C0(r);Object.values(o).forEach(l=>{_0(l??[])});let{stepsToSave:i,moduleUpdates:a}=await et({stepLists:o,createNewCacheIds:n});for(let l of a)t.has(l.name)||(e[l.name]=I0(l),t.add(l.name));return i}function _0(r){$s({steps:r,onPresetAction:e=>{e.aiSuggested=void 0,e.index=void 0,e.command.thoughts=void 0},onConditional:e=>{e.aiSuggested=void 0,e.index=void 0},onSimpleStepContainer:e=>{e.aiSuggested=void 0,e.index=void 0}})}function I0(r){let e=ir.parse(r),t={fileType:pe.MODULE,...e,schemaVersion:ue,steps:r.steps};return Fv(t)}async function ie(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 Xs({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 Js({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 Xs({promiseGenerator:r,signal:a.signal,codePath:t,logger:n})}finally{i=!0,o?.removeEventListener("abort",l),clearTimeout(c)}}function zv(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}function yu(r){let e=[];for(let t of r)switch(t.type){case"PRESET_ACTION":case"AI_ACTION":case"AI_ACTION_DYNAMIC":e.push(t);break;case"RESOLVED_MODULE":{let n={...t,type:"MODULE"};e.push(Vr.parse(n));break}case"SECTION":{let n={...t,steps:yu(t.steps)};e.push(He.parse(n));break}case"CONDITIONAL":{let n={...t,blocks:t.blocks.map(o=>({assertion:o.assertion,steps:yu(o.steps)})),elseSteps:t.elseSteps?yu(t.elseSteps):void 0};e.push(Wo.parse(n));break}default:return(o=>{throw"If Typescript complains about the line below, you missed a case or break in the switch above"})(t)}return e}function Eu(r){return yu([r])[0]}import M0 from"picomatch";var Tu=(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||M0(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},bu=(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}},da=r=>{try{return new URL(r),!0}catch{return!1}},Hv=r=>!r.toLowerCase().startsWith("http"),pa=(r,e)=>{try{return new URL(r,e),!0}catch{return!1}};function di(r,e){try{return!!new URL(r).origin.trim()}catch(t){return e?.error({url:r,err:t},"Invalid URL in check"),!1}}async function P0(r){let{logger:e,browserStateStorage:t,generator:n,results:o,error:i,maxItemsFromEnd:a,numStepsWithScreenshots:l,disableCache:c}=r,s=[];if(o.length>0){let{results:d}=await ca(e,t,o,{numStepsWithScreenshots:l,maxItemsFromEnd:a,includeBeforeScreenshots:!0,includeContainerTagsInDescription:!0});s=d}return await n.getTestResultClassification({results:s,errorMessage:i.message,errorStack:i.stack},{disableCache:c??!1})}async function Gv(r){let{logger:e,browserStateStorage:t,generator:n,fullResults:o,failureReason:i,error:a,maxItemsFromEnd:l,numStepsWithScreenshots:c,disableCache:s}=r,u=o?.results??[];if(i==="SetupFailureError"){let d=(o?.beforeResults??[]).at(0);u=[du("setup",{followingStepStart:d?.startedAt}),...o?.beforeResults??[]]}else if(i==="TeardownFailureError"){let d=u.at(-1),p=(o?.afterResults??[])[0],m=du("teardown",{precedingStepEnd:d?.finishedAt,followingStepStart:p?.startedAt});u=[...u,m,...o?.afterResults??[]]}else if(u.length<20){let d=(o?.beforeResults??[]).at(-1),p=u.at(0),m=du("main-test-body",{precedingStepEnd:d?.finishedAt,followingStepStart:p?.startedAt});u=[...o?.beforeResults??[],m,...u]}if(!t||!u||u.length===0)return{};try{let d=await P0({logger:e,browserStateStorage:t,generator:n,results:u,error:a,maxItemsFromEnd:l,numStepsWithScreenshots:c,disableCache:s});return{classification:d,aiFailureReason:d.reason}}catch(d){return e.error({err:d},"Failed to classify test result"),{}}}import{v4 as jv}from"uuid";function xh(r,e){return{...r,testId:e?.testId??"",testName:e?.testName??"",suiteId:e?.suiteId??"",suiteName:e?.suiteName??""}}var vu=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:xh({},this.metadata)}]).catch(l=>e.error({err:l},"Failed to report billable event"))]}trackStepExecution(e){if(JE(e.type)){this.creditsUsedV2+=1;return}let t=Om(e.type);if(this.creditsUsedV1+=t??0,e.type==="PRESET_ACTION"){this.creditsUsedV2+=1;let n=Lm(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:jv(),properties:xh({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:jv(),properties:xh({creditsUsed:this.creditsUsedV2},this.metadata)}]).catch(t=>e.error({err:t},"Failed to report credits used"))),await Promise.allSettled(this.asyncWork)}};function ma({orgId:r,client:e,gitMetadata:t,alwaysSaveCache:n,noCache:o}){return o?new qc:new _h(r,e,t,n)}var _h=class{constructor(e,t,n,o){this.orgId=e;this.client=t;let{gitBranchName:i,gitProtectedBranches:a}=n;this.cacheHeaders=eh(n),o?this.writeCaches=!0:i?this.writeCaches=!a.includes(i):this.writeCaches=!0}cacheHeaders;writeCaches;async saveStepCacheEntries({entries:e,testId:t,logger:n}){if(!this.writeCaches){n.debug("Skipping cache storage because branch is protected");return}try{await this.client.updateStepCaches({entries:e,testId:t},this.cacheHeaders)}catch(o){n.error({err:o},"Failed to save step cache entries")}}async resolveStepCacheEntries(e){let{steps:t,beforeSteps:n,afterSteps:o}=e.stepLists,i=await this.client.getStepCacheForTest({testId:e.testId},this.cacheHeaders);if(!this.writeCaches){e.logger.debug("Skipping cache last used at update because branch is protected");return}for(let l of[t,n,o])l&&la({steps:l,stepCacheEntries:i,logger:e.logger});let{cachesToSave:a}=await et({stepLists:e.stepLists,cacheCreationParams:{testId:e.testId,orgId:this.orgId}});this.client.updateStepCaches({entries:a,testId:e.testId},this.cacheHeaders)}};import O0 from"path";var L0=new eu(30,60*1e3),Oh="https://api.momentic.ai",$v,Wv=r=>{Oh=r},qr=()=>Oh;var ha,Ph,Au,qv=async r=>{if($v&&ha&&Au)return ha;let e=new Ze({baseUrl:Oh,apiKey:r,logger:T});$v=e;try{let t=await e.getAuthInfo();return ha=t.orgId,Ph=t.userId,Au=r,ha}catch(t){throw new Error(`Error checking API key against server: ${t}`)}},xt=()=>{if(!ha)throw new Error("Your organization ID is invalid.");return ha},ga=()=>{if(!Ph)throw new Error("Your user ID is invalid.");return Ph},Kr=()=>{if(!Au)throw new Error("Your API key is invalid.");return Au},Lh,Ih,Ru=(r,e)=>{Lh=r,Ih?.abort(),Ih=new AbortController;let t=Ih.signal,n=[r.configFilePath];r.config.environments?.forEach(o=>{if(!o.envFile)return;let i=O0.resolve(r.rootDir,o.envFile);try{if(Mh.lstatSync(i).isSymbolicLink())return;Mh.existsSync(i)&&n.push(i)}catch(a){T.warn({err:a},`Failed to check if env file ${i} exists`)}});try{N0({filesToWatch:n,revalidator:e,signal:t,project:r})}catch(o){T.error({err:o},"Failed to start config file watchers")}},ce=()=>Lh;function N0({filesToWatch:r,revalidator:e,signal:t,project:n}){r.forEach(o=>{Mh.watch(o,{signal:t,persistent:!1,recursive:!1},async(i,a)=>{a&&(L0.increment("setLocalProject")&&T.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.`),Lh=await Promise.resolve(e(n.configFilePath)))})})}function Re(r){return function(...e){let t=e[e.length-1],n=r(...e);Promise.resolve(n).catch(t)}}var Zs=D0();function Qs(r){let e=ce(),t=_t.dirname(e.configFilePath);return _t.join(t,...r)}function U0(r){let e=ce(),t=_t.dirname(e.configFilePath),n=_t.relative(t,r);return n?n.split(_t.sep):[]}function F0(r,e){let t=rr.statSync(r),n=U0(r);return Wm.parse({name:e,absolutePath:r,relativePath:n.join(_t.sep),pathSegments:n,isDirectory:t.isDirectory(),size:t.size,createdAt:t.birthtime,modifiedAt:t.mtime,accessedAt:t.atime})}Zs.post("/",Re(async(r,e,t)=>{let n;try{n=TT.parse(r.body).pathSegments}catch(d){e.status(400).json({error:`Failed to parse folder read body: ${d}`});return}let o=Qs(n);if(!rr.existsSync(o)){e.status(404).json({error:`Path not found: ${n.join(_t.sep)}`});return}if(!rr.statSync(o).isDirectory()){e.status(400).json({error:`Path is not a directory: ${n.join(_t.sep)}`});return}let a=ce(),l=Array.from(a.config.exclude??[]).concat(Hc),s=k0("*",{absolute:!1,cwd:o,ignore:l,dotRelative:!1,maxDepth:1,nodir:!1}).map(d=>{let p=_t.join(o,d);return F0(p,d)}),u={absolutePath:o,pathSegments:n,contents:s};e.status(200).json(u)}));Zs.put("/",Re(async(r,e,t)=>{let n;try{n=bT.parse(r.body).pathSegments}catch(a){e.status(400).json({error:`Failed to parse folder create body: ${a}`});return}let o=Qs(n);if(rr.existsSync(o)){e.status(200).json({success:!0,message:`Folder already exists: ${n.join(_t.sep)}`,pathSegments:n});return}rr.mkdirSync(o,{recursive:!0});let i={success:!0,message:`Folder created: ${n.join(_t.sep)}`,pathSegments:n};e.status(201).json(i)}));Zs.patch("/",Re(async(r,e,t)=>{let n,o;try{let s=vT.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=Qs(n),a=Qs(o);if(!rr.existsSync(i)){e.status(400).json({error:`Folder not found: ${n.join(_t.sep)}`});return}if(rr.existsSync(a)){e.status(400).json({error:`Destination already exists: ${o.join(_t.sep)}`});return}let l=_t.dirname(a);rr.existsSync(l)||rr.mkdirSync(l,{recursive:!0}),rr.renameSync(i,a);let c={success:!0,message:`Folder moved from ${n.join(_t.sep)} to ${o.join(_t.sep)}`,pathSegments:o};e.status(200).json(c)}));Zs.delete("/",Re(async(r,e,t)=>{let n,o=!0;try{let c=AT.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=Qs(n);if(!rr.existsSync(i)){e.status(200).json({success:!0,message:`Folder not found: ${n.join(_t.sep)}`,pathSegments:n});return}if(!rr.statSync(i).isDirectory()){e.status(400).json({error:`Path is not a directory: ${n.join(_t.sep)}`});return}if(o)rr.rmSync(i,{recursive:!0,force:!0});else{if(rr.readdirSync(i).length>0){e.status(409).json({error:`Cannot delete non-empty directory without recursive flag: ${n.join("/")}`});return}rr.rmdirSync(i)}let l={success:!0,message:`Folder deleted: ${n.join("/")}`,pathSegments:n};e.status(200).json(l)}));var Nh=Zs;import m$ from"events";import kI,{Router as h$}from"express";import{diff as G0}from"deep-object-diff";import Xr from"fs";import mi from"path";import fa from"yaml";import{z as Xv}from"zod";import{execSync as B0}from"child_process";function kn(r,e){let t=e.hooks?.postSave;if(!t)return;let n;t.includes("$1")?n=t.replaceAll("$1",r):n=`${t} ${r}`,T.debug({postSaveCommand:n},"Executing post-save hook command");try{B0(n,{encoding:"utf-8"})}catch(o){T.warn({err:o,postSaveCommand:n},"Failed to execute post-save hook command, continuing...")}}import{diff as Kv}from"deep-object-diff";import fn from"fs";import{cloneDeep as z0}from"lodash-es";import el from"path";import{v4 as H0}from"uuid";import tl from"yaml";function nr({content:r,schemaVersion:e,momenticFiles:t,project:n,forceSaveOnNoDiffs:o}){let i=t.modules[r.moduleId]?.fullFilePath;if(!i||!fn.existsSync(i))throw new Error(`Tried to update module ${r.moduleId} that could not be found on disk`);let a=fn.readFileSync(i,"utf-8"),l=tl.parse(a),c;if(r.name&&r.name!==l.name){let m=`${Oe(r.name)}.module.yaml`;if(c=el.join(el.dirname(i),m),fn.existsSync(c))throw new Error(`A conflicting file '${r.name}' already exists at path '${c}'`)}let s={...r,schemaVersion:e},u=hn({fileType:pe.MODULE,...Ym.parse(s),steps:He.array().parse(r.steps)}),d=Kv(u,l);if(d&&Object.keys(d).length===0&&!o){T.debug(`Skipping save for module ${r.moduleId} since there are no changes`);return}let p=tl.stringify(u);fn.writeFileSync(i,p,"utf-8"),c&&fn.renameSync(i,c),kn(c||i,n.config)}function Yv({moduleId:r,content:e,momenticFiles:t,project:n,logger:o}){let i=t.modules[r]?.fullFilePath;if(!i)throw new Error(`Tried to update module ${r} that could not be found on disk`);let a=Un(i,o),l={...a,...e},c=hn({fileType:pe.MODULE,...Ym.parse(l),steps:a.steps}),s=Kv(c,a);if(s&&Object.keys(s).length===0){T.debug(`Skipping save for module ${r} since there are no changes`);return}let u=tl.stringify(c);fn.writeFileSync(i,u,"utf-8");let d;if(e.name){let p=`${Oe(e.name)}.module.yaml`;if(d=el.join(el.dirname(i),p),fn.existsSync(d))throw new Error(`Module with name '${e.name}' already exists at path '${d}'`);fn.renameSync(i,d)}kn(d||i,n.config)}async function wu({name:r,description:e,enabled:t,steps:n,folder:o,project:i}){let a=Oe(r),l=el.join(o,`${a}.module.yaml`),c=H0(),{stepsToSave:s}=await et({stepLists:{steps:n}}),u={fileType:pe.MODULE,schemaVersion:ue,moduleId:c,name:r,description:e,enabled:t,steps:s.steps},d=tl.stringify(u);return fn.writeFileSync(l,d,"utf-8"),kn(l,i.config),{moduleId:c,name:r,description:e,enabled:t,steps:n}}function Un(r,e){let t=fn.readFileSync(r,"utf-8"),n=tl.parse(t);try{return Um.parse(n)}catch(o){throw e.error({err:o,moduleFilePath:r,moduleContents:t},`${r} does not parse as a valid Momentic module`),o}}async function Yr(r,e,t,n){let o=Un(r.fullFilePath,t),{resolvedSteps:i}=await gu({rawSteps:o.steps,migrationMetadata:{id:o.moduleId,schemaVersion:o.schemaVersion},resolvedModuleCache:n,logger:t,callbacks:{onFetchModule:async({id:l})=>{let c=e.modules[l]?.fullFilePath;if(c)return Un(c,t)}}}),a={...o,steps:i};return n&&(n[r.id]=z0(a)),a}async function Cu(r,e){let t={};return await Promise.all(Object.values(r.modules).map(async n=>{await Yr(n,r,e,t)})),Array.from(Object.values(t))}async function Jv({test:r,name:e,folder:t}){let n=await Bv({test:r});if(Object.keys(n.modules).length)throw new Error("A brand new test should not contain any modules in it");let i=`${Oe(e)}.test.yaml`,a=mi.join(t,i);return Xr.writeFileSync(a,n.test,"utf-8"),a}function Dh(r,e,t){let n=mi.join(t.rootDir,r);if(!Xr.existsSync(n))throw new Error(`Test not found at path '${r}' in project '${t.rootDir}'`);let o=Xr.readFileSync(n,"utf-8"),i=fa.parse(o),a,l;if(e.name&&e.name!==i.name){let p=`${Oe(e.name)}.test.yaml`;if(a=mi.join(mi.dirname(r),p),l=mi.join(t.rootDir,a),Xr.existsSync(l))throw new Error(`Test with name '${e.name}' already exists at path '${l}'`)}let c={...i,...e},s=xr.parse(c),u={fileType:pe.TEST,...xr.parse(s),beforeSteps:i.beforeSteps??void 0,steps:i.steps,afterSteps:i.afterSteps??void 0},d=fa.stringify(u);return Xr.writeFileSync(n,d,"utf-8"),l&&Xr.renameSync(n,l),kn(n,t.config),{newRelativeTestPath:a}}function qt({relativeTestPath:r,steps:e,schemaVersion:t,project:n,forceSaveOnNoDiffs:o}){let i=mi.join(n.rootDir,r);if(!Xr.existsSync(i))throw new Error(`Test not found at path '${r}' in project '${n.rootDir}'`);let a=Xr.readFileSync(i,"utf-8"),l=fa.parse(a),c=xr.parse({...l,schemaVersion:t}),s=He.array().or(Xv.undefined()).parse(e.beforeSteps),u=He.array().parse(e.steps),d=He.array().or(Xv.undefined()).parse(e.afterSteps),p=hn({fileType:pe.TEST,...c,beforeSteps:s&&s.length>0?s:void 0,steps:u,afterSteps:d&&d.length>0?d:void 0}),m=G0(p,l);if(m&&Object.keys(m).length===0&&!o){T.debug(`Skipping save for test ${c.name} since there are no changes`);return}let h=fa.stringify(p);Xr.writeFileSync(i,h,"utf-8"),T.debug(`Saving test ${c.name} to ${i}`),kn(i,n.config)}function rl(r,e){let t=mi.join(e.rootDir,r);if(!t)throw new Error(`Could not find test with path ${r} in Momentic project (${e.rootDir})`);let n;try{n=Xr.readFileSync(t,"utf8"),n=n.replace(/\r\n|\r/g,`
|
|
39
39
|
`)}catch(i){throw new Error(`Could not read test file ${t}: ${i}`)}let o;try{o=fa.parse(n)}catch(i){throw new Error(`Could not parse test file ${t} as YAML: ${i}`)}return Vt.parse(o)}function hi(r,e,t){let n=t.project.rootDir,o;try{o=Xr.readFileSync(r,"utf-8")}catch(a){throw e.error({err:a,projectRoot:n},a.message),new Error(a.message)}let i=fa.parse(o);if(!i.steps||!Array.isArray(i.steps))throw new Error(`Test ${r} is missing steps`);return i}async function tt(r,e,t){let n=hi(r,e,t),o;try{o=xr.parse(n)}catch(a){throw new Error(`Test ${r} is missing metadata or has invalid metadata: ${a}`)}let{resolvedTest:i}=await Dv({rawSteps:{steps:n.steps,beforeSteps:n.beforeSteps,afterSteps:n.afterSteps},metadata:o,logger:e,callbacks:{onFetchModule:async({id:a,logger:l})=>{let c=t.modules[a]?.fullFilePath;if(c)return Un(c,l)}}});return i}import j0 from"@dotenvx/dotenvx";import V0 from"fs";import Qv from"path";function xu(r,e){return(r.config.environments??[]).map(t=>nl(t.name,r,e))}function Zv(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 $0(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=Zv(i);l&&(n[o]=l);continue}let a;try{a=V0.readFileSync(Qv.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&&T.debug(n,"Set environment variables with interpolation from project configuration"),n}function W0(r){let{project:e,envFile:t,logger:n}=r,o={};if(!t)return o;let i=j0.config({path:Qv.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 nl(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`);if(!n.baseUrl)throw new Error(`Browser environment ${r} does not have a baseUrl configured`);let o={[wt]:Zv(n.baseUrl)},i=$0({envVariables:n.envVariables,project:e});Object.assign(o,i);let a=W0({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,browser:n.browser}}import{existsSync as iU,readFileSync as aU,readdirSync as sU,writeFileSync as lU}from"fs";import{glob as cU}from"glob";import gi,{dirname as rA}from"path";import{cwd as zh}from"process";import nA from"yaml";import{z as $e}from"zod";import eA from"fs";import{glob as q0}from"glob";import ol from"path";import K0 from"yaml";import{z as kh}from"zod";var tA=!1,Uh=["**/*.test.yaml","**/*.module.yaml"],Fh=kh.string().refine(r=>/^[a-zA-Z0-9-]+$/.test(r)),Bh=15,Y0=kh.object({fileType:kh.nativeEnum(pe)});async function Y(r,e=!1){let t={project:r,tests:{},modules:{},mobileTests:{},mobileModules:{},duplicateEntities:{}},n=r.config.include??Uh,o=Array.from(r.config.exclude??[]).concat(Hc),i=AbortSignal.timeout(5e3),a;try{a=await q0(n,{absolute:!1,cwd:r.rootDir,ignore:o,dotRelative:!1,maxDepth:Bh,nodir:!0,signal:i})}catch(l){throw T.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=X0(r.rootDir,l,t,e?dn:T);c&&(t.duplicateEntities[c.id]=c.paths)}return tA=!0,t}function X0(r,e,t,n){let o=ol.join(r,e),i=J0(o,n);if(!i)return;let a=Q0(i,o,n);if(!a)return;let l=Y0.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=Z0(o,n);if(!s)return;let u=eU(e,o,s);switch(c){case pe.TEST:try{return tU(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 rU(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 oU(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 nU(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 J0(r,e){try{return eA.readFileSync(r,"utf-8")}catch(t){e.warn(`Could not read possible Momentic file at ${r}, skipping: ${t}`);return}}function Q0(r,e,t){try{let n=K0.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 Z0(r,e){try{return eA.statSync(r)}catch(t){e.warn(`Skipping path '${r}' because it could not be stat, skipping: ${t}`);return}}function eU(r,e,t){return{relativePath:r,fullFilePath:e,platformSep:ol.sep,fullPathSegments:e.split(ol.sep),relativePathSegments:r.split(ol.sep),fileName:ol.basename(e),lastModified:t.mtime,createdAt:t.birthtime}}function tU(r,e,t,n,o){let i=xr.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 rU(r,e,t,n,o){let i=ir.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!tA&&Oe(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 nU(r,e,t,n,o){let i=Dc.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 oU(r,e,t,n,o){let i=Ds.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 Sa="momentic.config.yaml",Hh="momentic.workspace.yaml",uU=$e.object({projects:$e.string().array().describe("list of glob patterns to find project (momentic.config.yaml) files")}),dU=$e.union([$e.string(),$e.object({fromFile:$e.string(),json:$e.boolean().optional()})]),pU=$e.object({name:Fh,baseUrl:$e.string().optional().describe("Optional for mobile tests"),envFile:$e.string().optional().describe("path to a file on disk to read environment variables from. can be relative to project root or absolute."),envVariables:$e.record($e.string(),dU).optional(),inheritFromShell:$e.boolean().optional().describe("inherit all environment variables from the shell - might be noisy"),browser:Xo.optional().describe("deprecated: use project-level configuration only")}),mU=$e.object({postSave:$e.string().optional()}),hU=$e.object({name:Fh,include:$e.string().array().optional().describe("list of glob patterns that match momentic files (optional)"),exclude:$e.string().array().optional().describe("opposite of include, takes precedence over include"),goldenFileDir:$e.string().optional(),reporterDir:$e.string().optional(),outputDir:$e.string().optional(),retries:$e.number().optional().describe("number of retries per test"),parallel:$e.number().optional().describe("degree of parallelism"),environments:$e.array(pU).optional(),gitMainBranch:$e.string().optional(),gitProtectedBranches:$e.string().array().optional(),ai:Xm.optional(),browser:Xo.optional(),emulator:Bm.optional(),advanced:Jm.optional(),hooks:mU.optional()});function oA(r,e){let t;try{t=aU(r,"utf-8")}catch(o){T.warn(`Could not read possible Momentic ${e} file at ${r}: ${o}`);return}let n;try{if(n=nA.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){T.warn(`Possible Momentic ${e} file at ${r} does not parse as valid YAML: ${o}`);return}return n}function Gh(r){let e=oA(r,"project configuration");if(e!==void 0)try{return hU.parse(e)}catch(t){T.warn(`Possible Momentic project configuration file at ${r} does not adhere to the required schema: ${t}`);return}}function gU(r){let e=oA(r,"workspace configuration");if(e!==void 0)try{return uU.parse(e)}catch(t){T.warn(`Possible Momentic workspace configuration file at ${r} does not adhere to the required schema: ${t}`);return}}function fU(){let r=[],e=zh(),t=gi.parse(e).root,n=15,o=0;for(;o<n;){o++;let i=gi.basename(e);if(zc.includes(i))return T.warn(`Stopping search for Momentic projects since the current directory name (${i}) is likely a system artifact folder.`),r;for(let a of sU(e))if(a.endsWith(Sa)){let l=gi.join(e,a),c=Gh(l);c&&r.push({configFilePath:l,config:c,rootDir:rA(l)})}if(r.length)return r;if(e=gi.dirname(e),e===t)break}return r}async function vt(r={}){let{configFilePath:e,nameFilter:t}=r,n=await jh(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:
|
|
40
40
|
${n.map(o=>o.configFilePath)}`);if(n.length===0)throw new Error("No valid Momentic project file available.");return T.debug(`Found valid project configuration at ${n[0].configFilePath}`),n[0]}async function SU(r){let e=gU(r);if(!e||!e.projects||!e.projects.length)return;let t=e.projects.map(a=>(a.endsWith("/")||(a+="/"),`${a}*${Sa}`)),n=AbortSignal.timeout(2e3),o;try{o=await cU(t,{absolute:!1,cwd:zh(),dotRelative:!1,maxDepth:Bh,nodir:!0,signal:n})}catch(a){throw T.error({err:a},`Failed to list the available Momentic projects in the current directory. This usually indicates the 'include' or 'exclude' option in your ${Hh} is misconfigured.`),a}let i=[];for(let a of o){let l=gi.join(zh(),a),c=Gh(l);c&&i.push({configFilePath:l,config:c,rootDir:rA(l)})}return i}async function jh(r){if(r){r=gi.resolve(r);let t=Gh(r);return t||(console.error(`No valid Momentic project file found at ${r}.`),process.exit(1)),[{config:t,configFilePath:r,rootDir:gi.dirname(r)}]}if(iU(Hh)){let t=await SU(Hh);if(t)return t}return fU()}function ya(r,e){let t=nA.stringify(r);lU(e,t)}import Ea from"fs";import Vh from"path";import{z as $h}from"zod";var iA="golden/visual-diff",aA="reports",sA="test-results";var yU=$h.object({width:$h.number(),height:$h.number()}),Ta=class{defaultGoldenScreenshotDir;regenerateGoldenFiles;constructor(e,t){let n=Vh.join(e.rootDir,e.config.goldenFileDir??iA);this.defaultGoldenScreenshotDir=n,this.regenerateGoldenFiles=t}async prepareGoldenScreenshotForComparison(e,t,n){if(t.screenshot?.data?.startsWith("https://")){let a=await fetch(t.screenshot.data);return{buffer:Buffer.from(await a.arrayBuffer()),width:t.screenshot.width,height:t.screenshot.height}}let o=t.screenshot?.data;o||(o=Vh.join(this.defaultGoldenScreenshotDir,`${t.id}.jpg`));let i=`${o}.metadata.json`;if(this.regenerateGoldenFiles)return Ea.mkdirSync(Vh.dirname(o),{recursive:!0}),Ea.writeFileSync(o,n.buffer),Ea.writeFileSync(i,JSON.stringify({width:n.width,height:n.height})),{buffer:Buffer.from(n.buffer),width:n.width,height:n.height};if(Ea.existsSync(o)){let a=Ea.readFileSync(o),l=yU.parse(JSON.parse(Ea.readFileSync(i,"utf-8")));return{buffer:a,width:l.width,height:l.height}}else throw new x("UserConfigurationError",`Cannot execute visual diff without a saved baseline screenshot at ${o}`)}};import{execFile as EU}from"node:child_process";import{promisify as TU}from"node:util";import bU from"simple-git";var ke=bU(),lA=TU(EU);async function vU(r){let e=await We(r,ke.raw(["config","--list"])),t={};if(!e)return t;for(let n of e.split(`
|
|
41
|
-
`)){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 AU(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 lA("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 lA("gh",o,{timeout:5e3}),a=i?.toString().trim();if(a)return a}catch{}}}async function RU(r,e,t){let n=e?.includes("github.com"),o=e?.includes("gitlab.com");try{if(n)return AU(r,e,t);if(o)return}catch{}}function _u(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 We(r,e){try{return(await e).trim()}catch(t){r.error({err:t},"Failed to run git command");return}}function wU(){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 CU(r){let[e,t,n]=await Promise.all([We(r,ke.show(["--no-patch","--format=%ci"])),We(r,ke.show(["-s","--pretty=%B"])),We(r,ke.show(["-s","--pretty=%an"]))]),o=process.env.GITHUB_SERVER_URL&&process.env.GITHUB_REPOSITORY?`${process.env.GITHUB_SERVER_URL}/${process.env.GITHUB_REPOSITORY}`:void 0;return{gitCommitSha:process.env.GITHUB_SHA,gitCommitShaShort:process.env.GITHUB_SHA?.slice(0,6),gitCommitTimestamp:e?new Date(e):void 0,gitBranchName:process.env.GITHUB_HEAD_REF||process.env.GITHUB_REF_NAME,gitOriginUrl:o,gitCommitMessage:t,gitCommitAuthorName:n,githubRepository:process.env.GITHUB_REPOSITORY,pipelineId:process.env.GITHUB_RUN_ID}}async function xU(r){let[e,t,n]=await Promise.all([We(r,ke.listRemote(["--get-url","origin"])),We(r,ke.show(["-s","--pretty=%B"])),We(r,ke.show(["-s","--pretty=%an"]))]);return{gitCommitSha:process.env.CI_COMMIT_SHA,gitCommitShaShort:process.env.CI_COMMIT_SHORT_SHA,gitCommitTimestamp:process.env.CI_COMMIT_TIMESTAMP?new Date(process.env.CI_COMMIT_TIMESTAMP):void 0,gitBranchName:process.env.CI_COMMIT_BRANCH||process.env.CI_COMMIT_REF_NAME,gitOriginUrl:e,gitCommitMessage:t,gitCommitAuthorName:n,gitlabProjectPath:process.env.CI_PROJECT_PATH,pipelineId:`${process.env.CI_PIPELINE_ID}:${process.env.CI_JOB_ID}`}}async function _U(r){let[e,t,n,o]=await Promise.all([We(r,ke.show(["--no-patch","--format=%ci"])),We(r,ke.listRemote(["--get-url","origin"])),We(r,ke.show(["-s","--pretty=%B"])),We(r,ke.show(["-s","--pretty=%an"]))]),i=t?.includes("github.com"),a=t?.includes("gitlab.com"),l=t?_u(t):void 0;return{gitCommitSha:process.env.CIRCLE_SHA1,gitCommitShaShort:process.env.CIRCLE_SHA1?.slice(0,6),gitCommitTimestamp:e?new Date(e):void 0,gitBranchName:process.env.CIRCLE_BRANCH,gitOriginUrl:process.env.CIRCLE_REPOSITORY_URL,gitCommitMessage:n,gitCommitAuthorName:o,githubRepository:i?l:void 0,gitlabProjectPath:a?l:void 0,pipelineId:process.env.CIRCLE_PIPELINE_ID}}async function IU(r){let[e,t,n]=await Promise.all([We(r,ke.show(["--no-patch","--format=%ci"])),We(r,ke.show(["-s","--pretty=%B"])),We(r,ke.show(["-s","--pretty=%an"]))]),o=process.env.BUILDKITE_REPO,i=o?.includes("github.com"),a=o?.includes("gitlab.com"),l=o?_u(o):void 0;return{gitCommitSha:process.env.BUILDKITE_COMMIT,gitCommitShaShort:process.env.BUILDKITE_COMMIT?.slice(0,6),gitCommitTimestamp:e?new Date(e):void 0,gitBranchName:process.env.BUILDKITE_BRANCH,gitOriginUrl:o,gitCommitMessage:t,gitCommitAuthorName:n,githubRepository:i?l:void 0,gitlabProjectPath:a?l:void 0,pipelineId:`${process.env.BUILDKITE_PIPELINE_ID}:${process.env.BUILDKITE_BUILD_ID}:${process.env.BUILDKITE_JOB_ID}`}}async function MU(r){let[e,t,n]=await Promise.all([We(r,ke.show(["--no-patch","--format=%ci"])),We(r,ke.show(["-s","--pretty=%B"])),We(r,ke.show(["-s","--pretty=%an"]))]),o=process.env["Build.Repository.Uri"],i=o?.includes("github.com"),a=o?.includes("gitlab.com"),l=o?_u(o):void 0;return{gitCommitSha:process.env["Build.SourceVersion"],gitCommitShaShort:process.env["Build.SourceVersion"]?.slice(0,6),gitCommitTimestamp:e?new Date(e):void 0,gitBranchName:process.env["Build.SourceBranchName"],gitOriginUrl:o,gitCommitMessage:t,gitCommitAuthorName:n,githubRepository:i?l:void 0,gitlabProjectPath:a?l:void 0,pipelineId:`${process.env["System.JobId"]}:${process.env["System.JobAttempt"]}`}}async function PU(r,e){let[t,n,o,i,a,l,c,s,u]=await Promise.all([We(r,ke.revparse(["HEAD"])),We(r,ke.revparse(["--short","HEAD"])),We(r,ke.revparse(["--abbrev-ref","HEAD"])),We(r,ke.listRemote(["--get-url","origin"])),We(r,ke.show(["--no-patch","--format=%ci"])),We(r,ke.show(["-s","--pretty=%B"])),We(r,ke.show(["-s","--pretty=%an"])),e?We(r,ke.raw(["merge-base","--fork-point",e])):Promise.resolve(void 0),vU(r)]),d=s?await We(r,ke.show(["--no-patch","--format=%ci",s])):void 0,p=i?.includes("github.com"),m=i?.includes("gitlab.com"),h=i?_u(i):void 0,g=u["user.email"]||void 0,f=u["user.name"]||void 0,S=u["user.username"]||void 0,y=await RU(r,i,u)??S??void 0;return{gitCommitSha:t,gitCommitShaShort:n,gitBranchName:o,gitOriginUrl:i,gitCommitTimestamp:a?new Date(a):void 0,gitCommitMessage:l,gitCommitAuthorName:c,gitLocalUsername:y,gitLocalEmail:g,gitLocalName:f,lastCommitOnMainSha:s,lastCommitOnMainTimestamp:d?new Date(d):void 0,githubRepository:p?h:void 0,gitlabProjectPath:m?h:void 0,pipelineId:void 0}}async function OU(){let r=process.env._HEAD_REPO_URL;return{gitCommitSha:process.env.COMMIT_SHA,gitCommitShaShort:process.env.COMMIT_SHA?.slice(0,6),gitBranchName:process.env.BRANCH_NAME,gitOriginUrl:r?process.env._HEAD_REPO_URL:void 0,gitCommitTimestamp:void 0,gitCommitMessage:void 0,gitCommitAuthorName:void 0,githubRepository:r?process.env.REPO_FULL_NAME:void 0,pipelineId:`${process.env.PROJECT_ID}:${process.env.BUILD_ID}`}}async function LU(r){let e=r.config.gitProtectedBranches??[];return r.config.gitMainBranch&&e.push(r.config.gitMainBranch),{gitMainBranch:r.config.gitMainBranch,gitProtectedBranches:e}}async function il(r,e){let t=wU();if(!t)return PU(r,e);switch(t){case"GithubActions":return CU(r);case"GitlabCI":return xU(r);case"CircleCI":return _U(r);case"Buildkite":return IU(r);case"AzureDevOps":return MU(r);case"GCPCloudBuild":return OU()}}async function NU(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 DU(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 kU(r,e,t){try{if(t.githubRepository){let[n,o]=t.githubRepository.split("/");return await DU(r,e,n,o,t)}else if(t.gitlabProjectPath)return await NU(r,e,t.gitlabProjectPath,t)}catch(n){r.warn({err:n},"Failed to get remote git metadata")}return t}async function yo(r,e,t){let n=await LU(t),o=await il(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 kU(r,e,i);return{...n,...o,...a}}async function cA(){try{return!!(await ke.show(["--no-patch","--format=%ci"])).trim()}catch{return null}}import{diff as ahe}from"deep-object-diff";import{cloneDeep as lhe}from"lodash-es";import{v4 as The}from"uuid";import vhe from"yaml";import Fhe from"yaml";import{randomUUID as UU}from"crypto";import Eo from"fs";import ba from"path";var uA=new Set([".DS_Store","__MACOSX"]),dA={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 FU(r,e,t){if(dA[t]){let i=dA[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 Wh=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 pA(r,e){try{let t=ba.join(e,"metadata.json");return Kc.parse(JSON.parse(Eo.readFileSync(t,"utf-8")))}catch{throw new Wh(r,e)}}function mA(r,e,t){let n=UU(),o=r.child({runGroupId:n});Eo.rmSync(e,{recursive:!0,force:!0});let i=Eo.readdirSync(t).filter(c=>!uA.has(c)).map(c=>ba.join(t,c));if(i.length===0)throw new Error(`No run groups found in results path: ${t}`);Eo.mkdirSync(e,{recursive:!0});let a={...pA(t,i[0]),id:n};for(let c of i){let s=ba.join(c,"runs");if(!Eo.existsSync(s))continue;let u=pA(t,c);o.info({oldRunGroupId:u.id},"Merging run groups");for(let p in u){if(p==="id")continue;let m=p;a[m]=FU(a,u,m)}let d=Eo.readdirSync(s);for(let p of d){if(uA.has(p))continue;let m=ba.join(s,p),h=ba.join(e,"runs",p);Eo.cpSync(m,h,{recursive:!0})}}let l=ba.join(e,"metadata.json");Eo.writeFileSync(l,JSON.stringify(a,null,2))}import hA from"adm-zip";import qh from"fs";import Iu from"path";function BU(r){let e=new hA,t=Iu.join(r,"metadata.json"),n=Kc.parse(JSON.parse(qh.readFileSync(t,"utf-8")));e.addLocalFile(t);for(let o of qh.readdirSync(Iu.join(r,"runs"))){if(!o.endsWith(".zip"))continue;let i=o.replace(/\.zip$/,""),a=new hA(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 Mu(r){let{client:e,consoleLogger:t,resultsPath:n}=r;if(!qh.existsSync(n)){t.warn("Results path does not exist, skipping upload.");return}let o=new ru(e);try{let{runGroupId:i,buffer:a}=BU(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 zU from"adm-zip";import Nt from"fs";import gr from"path";var al=class r{constructor(e){this.filePath=e;Nt.rmSync(this.filePath,{recursive:!0,force:!0}),Nt.mkdirSync(this.filePath,{recursive:!0})}cd(e){return new r(gr.join(this.filePath,e))}mkdir(e){Nt.mkdirSync(gr.join(this.filePath,e),{recursive:!0})}readFile(e){let t=gr.join(this.filePath,e);if(Nt.existsSync(t))return Nt.readFileSync(t)}storeFile(e){let{name:t,contents:n}=e,o=gr.join(this.filePath,t);try{Nt.writeFileSync(o,n)}catch{}}createFileStream(e){let t=gr.join(this.filePath,e);return Nt.createWriteStream(t)}createRunArchive(e){return new Kh(gr.join(this.filePath,"runs"),e)}},Kh=class{constructor(e,t){this.filePath=e;this.tempPath=gr.join(e,`.${t}`),this.finalPath=gr.join(e,`${t}.zip`),Nt.rmSync(this.tempPath,{recursive:!0,force:!0}),Nt.rmSync(this.finalPath,{recursive:!0,force:!0}),Nt.mkdirSync(this.tempPath,{recursive:!0})}tempPath;finalPath;readFile(e){let t=gr.join(this.tempPath,e);if(Nt.existsSync(t))return Nt.readFileSync(t)}mkdir(e){Nt.mkdirSync(gr.join(this.tempPath,e),{recursive:!0})}cd(e){return new al(gr.join(this.tempPath,e))}storeFile(e){let{name:t,contents:n}=e,o=gr.join(this.tempPath,t);Nt.writeFileSync(o,n)}createFileStream(e){let t=gr.join(this.tempPath,e);return Nt.createWriteStream(t)}close(){let e=new zU;e.addLocalFolder(this.tempPath,void 0,n=>n!==".DS_Store");let t=e.toBuffer();Nt.writeFileSync(this.finalPath,t),Nt.rmSync(this.tempPath,{recursive:!0,force:!0})}};import g$ from"http";import f$ from"path";import{Server as Gj}from"socket.io";var HU=({metadata:r,logger:e,globalE2eStateManager:t})=>{let{sessionId:n}=r;return async()=>{e.info({sessionId:n},"Cancel event received");let o=t.getSession(n);if(!o)throw new Error("No active session found");try{o.controller.setClosed()}catch{}}},gA={event:"cancel",createHandler:HU};var GU=({metadata:r,logger:e,globalE2eStateManager:t})=>{let{sessionId:n}=r;return async(o,i)=>{let a=t.getSession(n);if(!a)throw new Error("No active session found");a.controller.setOpen();let l=a.controller.browser;try{let s=(await l.getBrowserState({skipWait:!0})).serialize();e.debug({a11yTree:s},"Fetched a11y tree from the browser"),i({a11yTree:s})}catch(c){e.error({err:c},"Error fetching a11y tree from the browser"),i({err:c.message})}}},fA={event:"fetchA11yTree",createHandler:GU};var jU=({metadata:r,logger:e,globalE2eStateManager:t})=>{let{sessionId:n}=r;return async(o,i)=>{let a=t.getSession(n);if(!a)throw new Error("No active session found");a.controller.setOpen();let l=a.controller.browser;try{let c=await l.html();i({html:c})}catch(c){e.error({err:c},"Error fetching DOM from the browser"),c.name==="TimeoutError"?i({err:"Timed out fetching DOM tree. This page may be too large for Momentic to process."}):i({err:c.message})}}},SA={event:"fetchDom",createHandler:jU};var VU=({metadata:r,logger:e,globalE2eStateManager:t})=>{let{sessionId:n}=r;return o=>{e.info({sessionId:n,reason:o},`Disconnect event received (${o})`),t.removeSession(n,e)}},yA={event:"disconnect",createHandler:VU};function Sn(r){let{result:e,nestedResults:t}=r;if(!r.nestedResults.length)return;let{firstMetadata:n,lastMetadata:o}=$U(t);WU(e,n,o);let i=[...r.asyncTasks];r.asyncTasks.push((async()=>{try{await qU(i,e,n,o)}catch(a){r.logger.error({result:r.result,err:a},"Error hoisting scalar result metadata")}})())}function $U(r){let e=r[0],t;for(;;){switch(e.type){case"PRESET_ACTION":{t=e;break}case"CONDITIONAL":if(e.assertionResult){t=e;break}break;case"AI_ACTION_DYNAMIC":case"AI_ACTION":case"MODULE":case"SECTION":if(!e.results.length){t=e;break}e=e.results[0];break;default:return(a=>{throw"If Typescript complains about the line below, you missed a case or break in the switch above"})(e)}if(t)break}let n=r[r.length-1],o;for(;;){switch(n.type){case"PRESET_ACTION":{o=n;break}case"AI_ACTION_DYNAMIC":case"CONDITIONAL":case"AI_ACTION":case"MODULE":case"SECTION":if(!n.results.length){o=n;break}n=n.results[n.results.length-1];break;default:return(a=>{throw"If Typescript complains about the line below, you missed a case or break in the switch above"})(n)}if(o)break}return{firstMetadata:t,lastMetadata:o}}function WU(r,e,t){e&&(r.beforeUrl=e.beforeUrl),t&&(r.afterUrl=t.afterUrl,r.data=t.data,t.status!=="SUCCESS"&&(r.message=t.message))}async function qU(r,e,t,n){await Promise.allSettled(r),t&&(e.beforeSnapshot=t.beforeSnapshot),n&&(e.afterSnapshot=n.afterSnapshot)}import{randomUUID as oF}from"crypto";import{faker as KU}from"@faker-js/faker";import YU from"assert";import XU from"axios";import*as JU from"child_process";import QU from"moment";import*as ZU from"otpauth";import eF from"pg";async function EA(r){let e;try{e=new URL(r.url).hostname}catch{}let t=[];return r.headers.getSetCookie()?.forEach(n=>{let o=Pc(n,e);t.push(...o)}),t}function tF(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 rF(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 nF=Object.getPrototypeOf(async function(){}).constructor;async function TA(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=(E,R)=>{o[E]=R,s[E]=R},d={},p=(E,R)=>{o[E]=R,d[E]=R},m;n.includes("Octokit")&&(m=(await import("@octokit/rest")).Octokit);let h;n.includes("createAppAuth")&&(h=(await import("@octokit/auth-app")).createAppAuth);let g=async()=>await Promise.resolve(new nF("axios","moment","faker","assert","pg","Octokit","createAppAuth","OTPAuth","child_process","extractCookiesFromResponse","env","setVariable","setPersistentVariable","sendSms","waitForLatestSms","email","sms","ai","mock",...Object.keys(i??{}),n)(XU,QU,c.fakerInstance??KU,YU,eF,m,h,ZU,JU,EA,o,e.options.disallowVariableUpdates?void 0:u,e.options.disallowVariableUpdates?void 0:p,R=>c.sms.send(R),R=>c.sms.fetchLatest(R),c.email,c.sms,c.ai,tF(a,l),...Object.values(i??{}))),f=!0,S,y;try{let E=await G(g(),{milliseconds:e.options.timeoutMs,message:`Timeout of ${e.options.timeoutMs}ms exceeded for code execution`,signal:e.signal});S=await rF(e.options.responseSerialization??"RAW",E)}catch(E){t.error({err:E,env:o,evalCode:n},`[${r}] Error executing code: ${E}`),f=!1,E instanceof go?y=`Timeout of ${e.options.timeoutMs}ms exceeded for code execution`:y=E instanceof Error?E.message:`${E}`}return{result:S,variableUpdates:s,persistentVariableUpdates:d,success:f,error:y}}async function bA({code:r,fragment:e,context:t,localTools:n,logger:o,signal:i,timeoutMs:a=uo,disallowVariableUpdates:l,additionalBindings:c,responseSerialization:s,mock:u}){let d=oF(),p=await TA(d,{code:r,options:{fragment:e,timeoutMs:a,disallowVariableUpdates:l,responseSerialization:s},bindings:{...t.toObjectCopy(),...u,additionalBindings:c},tools:n,signal:i},o);return T.debug(`[${d}] Got execution result: ${JSON.stringify(p)}`),p}import{createHmac as iF,randomUUID as aF}from"crypto";import sF from"fetch-retry";var lF=sF(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}}),vA=process.env.GCP_JS_EVAL_FUNCTION_ENDPOINT,AA=process.env.MOMENTIC_LAMBDA_AUTH_SECRET;async function RA({orgId:r,code:e,fragment:t,context:n,timeoutMs:o=uo,retries:i=2,signal:a,logger:l,additionalBindings:c,disallowVariableUpdates:s,responseSerialization:u,mock:d}){if(!vA)throw new Error("GCP_JS_EVAL_FUNCTION_ENDPOINT environment variable not set");let p,m,h=0;if(!AA)throw new Error("Missing lambda auth secret.");let g=iF("sha256",AA).update(r).digest("hex");for(;h<=i;){h++,a?.throwIfAborted();let S={id:aF(),orgId:r,momenticLambdaAuthHash:g,code:e,fragment:t,state:{...n.toObjectCopy(),...d,additionalBindings:c},timeoutMs:o,disallowVariableUpdates:s,responseSerialization:u};try{if(p=await G(lF(vA,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(S)}),{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(y){m=y}}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=ZE.parse(await p.json())}catch(S){throw new Error(`Code evaluation server returned invalid response: ${S}`)}if(f.error)throw new Error(`Code evaluation error: ${f.error}`);return f}async function To(r){let e;if(process.env.GCP_JS_EVAL_FUNCTION_ENDPOINT)e=await RA(r);else if(r.localTools)e=await bA({...r,localTools:r.localTools});else throw new Error("No code evaluation environment available");if(e.error){let t=`Failed to evaluate code:
|
|
41
|
+
`)){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 AU(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 lA("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 lA("gh",o,{timeout:5e3}),a=i?.toString().trim();if(a)return a}catch{}}}async function RU(r,e,t){let n=e?.includes("github.com"),o=e?.includes("gitlab.com");try{if(n)return AU(r,e,t);if(o)return}catch{}}function _u(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 We(r,e){try{return(await e).trim()}catch(t){r.error({err:t},"Failed to run git command");return}}function wU(){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 CU(r){let[e,t,n]=await Promise.all([We(r,ke.show(["--no-patch","--format=%ci"])),We(r,ke.show(["-s","--pretty=%B"])),We(r,ke.show(["-s","--pretty=%an"]))]),o=process.env.GITHUB_SERVER_URL&&process.env.GITHUB_REPOSITORY?`${process.env.GITHUB_SERVER_URL}/${process.env.GITHUB_REPOSITORY}`:void 0;return{gitCommitSha:process.env.GITHUB_SHA,gitCommitShaShort:process.env.GITHUB_SHA?.slice(0,6),gitCommitTimestamp:e?new Date(e):void 0,gitBranchName:process.env.GITHUB_HEAD_REF||process.env.GITHUB_REF_NAME,gitOriginUrl:o,gitCommitMessage:t,gitCommitAuthorName:n,githubRepository:process.env.GITHUB_REPOSITORY,pipelineId:process.env.GITHUB_RUN_ID}}async function xU(r){let[e,t,n]=await Promise.all([We(r,ke.listRemote(["--get-url","origin"])),We(r,ke.show(["-s","--pretty=%B"])),We(r,ke.show(["-s","--pretty=%an"]))]);return{gitCommitSha:process.env.CI_COMMIT_SHA,gitCommitShaShort:process.env.CI_COMMIT_SHORT_SHA,gitCommitTimestamp:process.env.CI_COMMIT_TIMESTAMP?new Date(process.env.CI_COMMIT_TIMESTAMP):void 0,gitBranchName:process.env.CI_COMMIT_BRANCH||process.env.CI_COMMIT_REF_NAME,gitOriginUrl:e,gitCommitMessage:t,gitCommitAuthorName:n,gitlabProjectPath:process.env.CI_PROJECT_PATH,pipelineId:`${process.env.CI_PIPELINE_ID}:${process.env.CI_JOB_ID}`}}async function _U(r){let[e,t,n,o]=await Promise.all([We(r,ke.show(["--no-patch","--format=%ci"])),We(r,ke.listRemote(["--get-url","origin"])),We(r,ke.show(["-s","--pretty=%B"])),We(r,ke.show(["-s","--pretty=%an"]))]),i=t?.includes("github.com"),a=t?.includes("gitlab.com"),l=t?_u(t):void 0;return{gitCommitSha:process.env.CIRCLE_SHA1,gitCommitShaShort:process.env.CIRCLE_SHA1?.slice(0,6),gitCommitTimestamp:e?new Date(e):void 0,gitBranchName:process.env.CIRCLE_BRANCH,gitOriginUrl:process.env.CIRCLE_REPOSITORY_URL,gitCommitMessage:n,gitCommitAuthorName:o,githubRepository:i?l:void 0,gitlabProjectPath:a?l:void 0,pipelineId:process.env.CIRCLE_PIPELINE_ID}}async function IU(r){let[e,t,n]=await Promise.all([We(r,ke.show(["--no-patch","--format=%ci"])),We(r,ke.show(["-s","--pretty=%B"])),We(r,ke.show(["-s","--pretty=%an"]))]),o=process.env.BUILDKITE_REPO,i=o?.includes("github.com"),a=o?.includes("gitlab.com"),l=o?_u(o):void 0;return{gitCommitSha:process.env.BUILDKITE_COMMIT,gitCommitShaShort:process.env.BUILDKITE_COMMIT?.slice(0,6),gitCommitTimestamp:e?new Date(e):void 0,gitBranchName:process.env.BUILDKITE_BRANCH,gitOriginUrl:o,gitCommitMessage:t,gitCommitAuthorName:n,githubRepository:i?l:void 0,gitlabProjectPath:a?l:void 0,pipelineId:`${process.env.BUILDKITE_PIPELINE_ID}:${process.env.BUILDKITE_BUILD_ID}:${process.env.BUILDKITE_JOB_ID}`}}async function MU(r){let[e,t,n]=await Promise.all([We(r,ke.show(["--no-patch","--format=%ci"])),We(r,ke.show(["-s","--pretty=%B"])),We(r,ke.show(["-s","--pretty=%an"]))]),o=process.env["Build.Repository.Uri"],i=o?.includes("github.com"),a=o?.includes("gitlab.com"),l=o?_u(o):void 0;return{gitCommitSha:process.env["Build.SourceVersion"],gitCommitShaShort:process.env["Build.SourceVersion"]?.slice(0,6),gitCommitTimestamp:e?new Date(e):void 0,gitBranchName:process.env["Build.SourceBranchName"],gitOriginUrl:o,gitCommitMessage:t,gitCommitAuthorName:n,githubRepository:i?l:void 0,gitlabProjectPath:a?l:void 0,pipelineId:`${process.env["System.JobId"]}:${process.env["System.JobAttempt"]}`}}async function PU(r,e){let[t,n,o,i,a,l,c,s,u]=await Promise.all([We(r,ke.revparse(["HEAD"])),We(r,ke.revparse(["--short","HEAD"])),We(r,ke.revparse(["--abbrev-ref","HEAD"])),We(r,ke.listRemote(["--get-url","origin"])),We(r,ke.show(["--no-patch","--format=%ci"])),We(r,ke.show(["-s","--pretty=%B"])),We(r,ke.show(["-s","--pretty=%an"])),e?We(r,ke.raw(["merge-base","--fork-point",e])):Promise.resolve(void 0),vU(r)]),d=s?await We(r,ke.show(["--no-patch","--format=%ci",s])):void 0,p=i?.includes("github.com"),m=i?.includes("gitlab.com"),h=i?_u(i):void 0,g=u["user.email"]||void 0,f=u["user.name"]||void 0,y=u["user.username"]||void 0,S=await RU(r,i,u)??y??void 0;return{gitCommitSha:t,gitCommitShaShort:n,gitBranchName:o,gitOriginUrl:i,gitCommitTimestamp:a?new Date(a):void 0,gitCommitMessage:l,gitCommitAuthorName:c,gitLocalUsername:S,gitLocalEmail:g,gitLocalName:f,lastCommitOnMainSha:s,lastCommitOnMainTimestamp:d?new Date(d):void 0,githubRepository:p?h:void 0,gitlabProjectPath:m?h:void 0,pipelineId:void 0}}async function OU(){let r=process.env._HEAD_REPO_URL;return{gitCommitSha:process.env.COMMIT_SHA,gitCommitShaShort:process.env.COMMIT_SHA?.slice(0,6),gitBranchName:process.env.BRANCH_NAME,gitOriginUrl:r?process.env._HEAD_REPO_URL:void 0,gitCommitTimestamp:void 0,gitCommitMessage:void 0,gitCommitAuthorName:void 0,githubRepository:r?process.env.REPO_FULL_NAME:void 0,pipelineId:`${process.env.PROJECT_ID}:${process.env.BUILD_ID}`}}async function LU(r){let e=r.config.gitProtectedBranches??[];return r.config.gitMainBranch&&e.push(r.config.gitMainBranch),{gitMainBranch:r.config.gitMainBranch,gitProtectedBranches:e}}async function il(r,e){let t=wU();if(!t)return PU(r,e);switch(t){case"GithubActions":return CU(r);case"GitlabCI":return xU(r);case"CircleCI":return _U(r);case"Buildkite":return IU(r);case"AzureDevOps":return MU(r);case"GCPCloudBuild":return OU()}}async function NU(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 DU(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 kU(r,e,t){try{if(t.githubRepository){let[n,o]=t.githubRepository.split("/");return await DU(r,e,n,o,t)}else if(t.gitlabProjectPath)return await NU(r,e,t.gitlabProjectPath,t)}catch(n){r.warn({err:n},"Failed to get remote git metadata")}return t}async function yo(r,e,t){let n=await LU(t),o=await il(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 kU(r,e,i);return{...n,...o,...a}}async function cA(){try{return!!(await ke.show(["--no-patch","--format=%ci"])).trim()}catch{return null}}import{diff as ahe}from"deep-object-diff";import{cloneDeep as lhe}from"lodash-es";import{v4 as The}from"uuid";import vhe from"yaml";import Fhe from"yaml";import{randomUUID as UU}from"crypto";import Eo from"fs";import ba from"path";var uA=new Set([".DS_Store","__MACOSX"]),dA={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 FU(r,e,t){if(dA[t]){let i=dA[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 Wh=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 pA(r,e){try{let t=ba.join(e,"metadata.json");return Kc.parse(JSON.parse(Eo.readFileSync(t,"utf-8")))}catch{throw new Wh(r,e)}}function mA(r,e,t){let n=UU(),o=r.child({runGroupId:n});Eo.rmSync(e,{recursive:!0,force:!0});let i=Eo.readdirSync(t).filter(c=>!uA.has(c)).map(c=>ba.join(t,c));if(i.length===0)throw new Error(`No run groups found in results path: ${t}`);Eo.mkdirSync(e,{recursive:!0});let a={...pA(t,i[0]),id:n};for(let c of i){let s=ba.join(c,"runs");if(!Eo.existsSync(s))continue;let u=pA(t,c);o.info({oldRunGroupId:u.id},"Merging run groups");for(let p in u){if(p==="id")continue;let m=p;a[m]=FU(a,u,m)}let d=Eo.readdirSync(s);for(let p of d){if(uA.has(p))continue;let m=ba.join(s,p),h=ba.join(e,"runs",p);Eo.cpSync(m,h,{recursive:!0})}}let l=ba.join(e,"metadata.json");Eo.writeFileSync(l,JSON.stringify(a,null,2))}import hA from"adm-zip";import qh from"fs";import Iu from"path";function BU(r){let e=new hA,t=Iu.join(r,"metadata.json"),n=Kc.parse(JSON.parse(qh.readFileSync(t,"utf-8")));e.addLocalFile(t);for(let o of qh.readdirSync(Iu.join(r,"runs"))){if(!o.endsWith(".zip"))continue;let i=o.replace(/\.zip$/,""),a=new hA(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 Mu(r){let{client:e,consoleLogger:t,resultsPath:n}=r;if(!qh.existsSync(n)){t.warn("Results path does not exist, skipping upload.");return}let o=new ru(e);try{let{runGroupId:i,buffer:a}=BU(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 zU from"adm-zip";import Nt from"fs";import gr from"path";var al=class r{constructor(e){this.filePath=e;Nt.rmSync(this.filePath,{recursive:!0,force:!0}),Nt.mkdirSync(this.filePath,{recursive:!0})}cd(e){return new r(gr.join(this.filePath,e))}mkdir(e){Nt.mkdirSync(gr.join(this.filePath,e),{recursive:!0})}readFile(e){let t=gr.join(this.filePath,e);if(Nt.existsSync(t))return Nt.readFileSync(t)}storeFile(e){let{name:t,contents:n}=e,o=gr.join(this.filePath,t);try{Nt.writeFileSync(o,n)}catch{}}createFileStream(e){let t=gr.join(this.filePath,e);return Nt.createWriteStream(t)}createRunArchive(e){return new Kh(gr.join(this.filePath,"runs"),e)}},Kh=class{constructor(e,t){this.filePath=e;this.tempPath=gr.join(e,`.${t}`),this.finalPath=gr.join(e,`${t}.zip`),Nt.rmSync(this.tempPath,{recursive:!0,force:!0}),Nt.rmSync(this.finalPath,{recursive:!0,force:!0}),Nt.mkdirSync(this.tempPath,{recursive:!0})}tempPath;finalPath;readFile(e){let t=gr.join(this.tempPath,e);if(Nt.existsSync(t))return Nt.readFileSync(t)}mkdir(e){Nt.mkdirSync(gr.join(this.tempPath,e),{recursive:!0})}cd(e){return new al(gr.join(this.tempPath,e))}storeFile(e){let{name:t,contents:n}=e,o=gr.join(this.tempPath,t);Nt.writeFileSync(o,n)}createFileStream(e){let t=gr.join(this.tempPath,e);return Nt.createWriteStream(t)}close(){let e=new zU;e.addLocalFolder(this.tempPath,void 0,n=>n!==".DS_Store");let t=e.toBuffer();Nt.writeFileSync(this.finalPath,t),Nt.rmSync(this.tempPath,{recursive:!0,force:!0})}};import g$ from"http";import f$ from"path";import{Server as Gj}from"socket.io";var HU=({metadata:r,logger:e,globalE2eStateManager:t})=>{let{sessionId:n}=r;return async()=>{e.info({sessionId:n},"Cancel event received");let o=t.getSession(n);if(!o)throw new Error("No active session found");try{o.controller.setClosed()}catch{}}},gA={event:"cancel",createHandler:HU};var GU=({metadata:r,logger:e,globalE2eStateManager:t})=>{let{sessionId:n}=r;return async(o,i)=>{let a=t.getSession(n);if(!a)throw new Error("No active session found");a.controller.setOpen();let l=a.controller.browser;try{let s=(await l.getBrowserState({skipWait:!0})).serialize();e.debug({a11yTree:s},"Fetched a11y tree from the browser"),i({a11yTree:s})}catch(c){e.error({err:c},"Error fetching a11y tree from the browser"),i({err:c.message})}}},fA={event:"fetchA11yTree",createHandler:GU};var jU=({metadata:r,logger:e,globalE2eStateManager:t})=>{let{sessionId:n}=r;return async(o,i)=>{let a=t.getSession(n);if(!a)throw new Error("No active session found");a.controller.setOpen();let l=a.controller.browser;try{let c=await l.html();i({html:c})}catch(c){e.error({err:c},"Error fetching DOM from the browser"),c.name==="TimeoutError"?i({err:"Timed out fetching DOM tree. This page may be too large for Momentic to process."}):i({err:c.message})}}},SA={event:"fetchDom",createHandler:jU};var VU=({metadata:r,logger:e,globalE2eStateManager:t})=>{let{sessionId:n}=r;return o=>{e.info({sessionId:n,reason:o},`Disconnect event received (${o})`),t.removeSession(n,e)}},yA={event:"disconnect",createHandler:VU};function Sn(r){let{result:e,nestedResults:t}=r;if(!r.nestedResults.length)return;let{firstMetadata:n,lastMetadata:o}=$U(t);WU(e,n,o);let i=[...r.asyncTasks];r.asyncTasks.push((async()=>{try{await qU(i,e,n,o)}catch(a){r.logger.error({result:r.result,err:a},"Error hoisting scalar result metadata")}})())}function $U(r){let e=r[0],t;for(;;){switch(e.type){case"PRESET_ACTION":{t=e;break}case"CONDITIONAL":if(e.assertionResult){t=e;break}break;case"AI_ACTION_DYNAMIC":case"AI_ACTION":case"MODULE":case"SECTION":if(!e.results.length){t=e;break}e=e.results[0];break;default:return(a=>{throw"If Typescript complains about the line below, you missed a case or break in the switch above"})(e)}if(t)break}let n=r[r.length-1],o;for(;;){switch(n.type){case"PRESET_ACTION":{o=n;break}case"AI_ACTION_DYNAMIC":case"CONDITIONAL":case"AI_ACTION":case"MODULE":case"SECTION":if(!n.results.length){o=n;break}n=n.results[n.results.length-1];break;default:return(a=>{throw"If Typescript complains about the line below, you missed a case or break in the switch above"})(n)}if(o)break}return{firstMetadata:t,lastMetadata:o}}function WU(r,e,t){e&&(r.beforeUrl=e.beforeUrl),t&&(r.afterUrl=t.afterUrl,r.data=t.data,t.status!=="SUCCESS"&&(r.message=t.message))}async function qU(r,e,t,n){await Promise.allSettled(r),t&&(e.beforeSnapshot=t.beforeSnapshot),n&&(e.afterSnapshot=n.afterSnapshot)}import{randomUUID as oF}from"crypto";import{faker as KU}from"@faker-js/faker";import YU from"assert";import XU from"axios";import*as JU from"child_process";import QU from"moment";import*as ZU from"otpauth";import eF from"pg";async function EA(r){let e;try{e=new URL(r.url).hostname}catch{}let t=[];return r.headers.getSetCookie()?.forEach(n=>{let o=Pc(n,e);t.push(...o)}),t}function tF(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 rF(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 nF=Object.getPrototypeOf(async function(){}).constructor;async function TA(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=(E,R)=>{o[E]=R,s[E]=R},d={},p=(E,R)=>{o[E]=R,d[E]=R},m;n.includes("Octokit")&&(m=(await import("@octokit/rest")).Octokit);let h;n.includes("createAppAuth")&&(h=(await import("@octokit/auth-app")).createAppAuth);let g=async()=>await Promise.resolve(new nF("axios","moment","faker","assert","pg","Octokit","createAppAuth","OTPAuth","child_process","extractCookiesFromResponse","env","setVariable","setPersistentVariable","sendSms","waitForLatestSms","email","sms","ai","mock",...Object.keys(i??{}),n)(XU,QU,c.fakerInstance??KU,YU,eF,m,h,ZU,JU,EA,o,e.options.disallowVariableUpdates?void 0:u,e.options.disallowVariableUpdates?void 0:p,R=>c.sms.send(R),R=>c.sms.fetchLatest(R),c.email,c.sms,c.ai,tF(a,l),...Object.values(i??{}))),f=!0,y,S;try{let E=await G(g(),{milliseconds:e.options.timeoutMs,message:`Timeout of ${e.options.timeoutMs}ms exceeded for code execution`,signal:e.signal});y=await rF(e.options.responseSerialization??"RAW",E)}catch(E){t.error({err:E,env:o,evalCode:n},`[${r}] Error executing code: ${E}`),f=!1,E instanceof go?S=`Timeout of ${e.options.timeoutMs}ms exceeded for code execution`:S=E instanceof Error?E.message:`${E}`}return{result:y,variableUpdates:s,persistentVariableUpdates:d,success:f,error:S}}async function bA({code:r,fragment:e,context:t,localTools:n,logger:o,signal:i,timeoutMs:a=uo,disallowVariableUpdates:l,additionalBindings:c,responseSerialization:s,mock:u}){let d=oF(),p=await TA(d,{code:r,options:{fragment:e,timeoutMs:a,disallowVariableUpdates:l,responseSerialization:s},bindings:{...t.toObjectCopy(),...u,additionalBindings:c},tools:n,signal:i},o);return T.debug(`[${d}] Got execution result: ${JSON.stringify(p)}`),p}import{createHmac as iF,randomUUID as aF}from"crypto";import sF from"fetch-retry";var lF=sF(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}}),vA=process.env.GCP_JS_EVAL_FUNCTION_ENDPOINT,AA=process.env.MOMENTIC_LAMBDA_AUTH_SECRET;async function RA({orgId:r,code:e,fragment:t,context:n,timeoutMs:o=uo,retries:i=2,signal:a,logger:l,additionalBindings:c,disallowVariableUpdates:s,responseSerialization:u,mock:d}){if(!vA)throw new Error("GCP_JS_EVAL_FUNCTION_ENDPOINT environment variable not set");let p,m,h=0;if(!AA)throw new Error("Missing lambda auth secret.");let g=iF("sha256",AA).update(r).digest("hex");for(;h<=i;){h++,a?.throwIfAborted();let y={id:aF(),orgId:r,momenticLambdaAuthHash:g,code:e,fragment:t,state:{...n.toObjectCopy(),...d,additionalBindings:c},timeoutMs:o,disallowVariableUpdates:s,responseSerialization:u};try{if(p=await G(lF(vA,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(y)}),{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(S){m=S}}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=ZE.parse(await p.json())}catch(y){throw new Error(`Code evaluation server returned invalid response: ${y}`)}if(f.error)throw new Error(`Code evaluation error: ${f.error}`);return f}async function To(r){let e;if(process.env.GCP_JS_EVAL_FUNCTION_ENDPOINT)e=await RA(r);else if(r.localTools)e=await bA({...r,localTools:r.localTools});else throw new Error("No code evaluation environment available");if(e.error){let t=`Failed to evaluate code:
|
|
42
42
|
${e.error}
|
|
43
43
|
Code received:
|
|
44
|
-
${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 cF}from"lodash-es";async function fr(r){let{orgId:e,s:t,context:n,logger:o,signal:i,retries:a=2,timeoutMs:l=uo,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(),h;try{h=await To({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(h===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 g=typeof h=="string"?h:`${h}`;g=g.replaceAll(/\$/g,"$$$$"),d=d.replace(p[0],g)}return d}async function Pu(r){return wA(r)}async function wA({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 fr({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 wA({obj:s,bannedKeys:e,context:n,prefixPath:u,replacements:i,allowList:c?void 0:t,...a})}return i}function CA(r,e){for(let{path:t,original:n}of e)cF(r,t,n)}import uF from"fetch-retry";var Ofe=process.env.MAILINATOR_API_KEY,Lfe=uF(global.fetch,{retryOn:function(r,e,t){return r>3?!1:!!(e!==null||t&&t.status>=400)},retryDelay:function(r){return 500}});import{hostname as SF}from"os";import{cloneDeep as _A}from"lodash-es";async function IA(r){let{command:e,timeoutMs:t,fixtures:n}=r,{abortSignal:o}=n,i=HS(e.cache)?e.cache:void 0,a=_A(i),l=()=>{if(i){let m=bh(a,i);i.target=m.target,i.updatedAt=m.updatedAt}},c=Date.now(),s=0,u,d=500,p=!1;for(;s<2||Date.now()-c<t;){s++,s>1&&await ie(d,o),o?.throwIfAborted();let{result:m,elementWasFound:h}=await xA({cacheToUse:i,params:r});if(u=m,p=h,m.success)break;l(),d=Math.min(d*2,1e4)}if(!u)throw new x("InternalPlatformError",`Failed to evaluate manual element assertion in ${t}ms.`);if(o?.throwIfAborted(),!u.success&&i?.target&&Kl(i.target)){let m=i?.target?.memory?{target:{id:-1,memory:i.target.memory}}:void 0,{result:h}=await xA({cacheToUse:m,params:r});u=h,u.success||l()}return u.success&&i?.target&&!p&&(i.target=qs(i.target),i.updatedAt=new Date),u}async function xA({cacheToUse:r,params:e}){let{command:t,disableCache:n,fixtures:o,tracer:i,targetingWrapper:a}=e,{logger:l}=o;if(t.target&&!Zn(t.target))throw new Error("Element assertion with x/y is not supported yet");let c=pF(t.assertion),s,u=!1,d=_A(r);try{let{elementInteractedDisplayString:p,result:m,thoughts:h}=await a({ctx:o.ctx,tracer:i,command:t,target:t.target,cache:d?.target,action:async g=>dF(g.locator,e),options:{...t,allowNotActionableNodesOverride:!0,disableCache:n,memory:d?.target?.memory,disableGlobalLocatorRedirect:!0,source:Yo(t),targetName:"target"}});return s={success:m.success,data:m.data,err:m.err,elementInteractedDisplayString:p,thoughts:h},u=!0,m.success||(l.warn({aiThoughts:h,elementString:p,err:m.err},"Element check found an element but failed"),s={...m,thoughts:h}),{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 dF(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:it(c,500,!0)},!Ou(c,n.value,n.operation,!!n.negated)){let s=n.negated?Ir[n.operation]:Mr[n.operation];o=!1,i=new x("AssertionFailureError",`The content ${s} '${n.value}': ${c}`)}break}case"ELEMENT_ATTRIBUTE":{a={elementOuterHtml:it(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(!Ou(c,n.value,n.operation,!!n.negated)){let s=n.negated?Ir[n.operation]:Mr[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},nn*1e3);break}case"EDITABLE":{o=await r.isEditable({timeout:nn*1e3});break}case"EXISTS":{o=!0;break}case"ENABLED":{o=await r.isEnabled({timeout:nn*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?vh[n.condition]:Ah[n.condition];i=new x("AssertionFailureError",`The element ${c}`)}break}case"ELEMENT_NAME":{let c=await r.evaluate(s=>s.tagName);if(!Ou(c,n.value,n.operation,!!n.negated)){let s=n.negated?Ir[n.operation]:Mr[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(!Ou(c,n.value,n.operation,!!n.negated)){let s=n.negated?Ir[n.operation]:Mr[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 Ou(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 pF(r){return r.type==="ELEMENT_EXISTENCE"&&r.negated&&(r.condition==="EXISTS"||r.condition==="VISIBLE")}function MA(r){return r.type==="ELEMENT_EXISTENCE"&&r.negated&&r.condition==="EXISTS"}import{Jimp as mF}from"jimp";async function sl(r,e){let t=await r.screenshot(e),n=await mF.fromBuffer(t);return{buffer:t,width:Math.ceil(n.bitmap.width??0),height:Math.ceil(n.bitmap.height??0)}}import{Jimp as PA}from"jimp";import Yh from"jpeg-js";import hF from"pixelmatch";async function OA({ctx:r,tracer:e,command:t,disableCache:n,browser:o,targetingWrapper:i,logger:a,screenshotStorage:l}){if(t.target&&!Zn(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=>sl(o,{locator:q.locator,...c}),options:{...t,disableCache:n,disableGlobalLocatorRedirect:!0,memory:t.cache?.target?.memory,targetName:"target"}})).result:s=await sl(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 X=`${s.width}x${s.height}`,q=`${u.width}x${u.height}`;return{fail:!0,thoughts:`Current screenshot (${X}) 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 PA.fromBuffer(s.buffer),p={width:s.width,height:s.height},m=await PA.fromBuffer(u.buffer),h={width:u.width,height:u.height},g,f=p.width*p.height,S=h.width*h.height,y=Math.abs(p.height-h.height),E=Math.abs(p.width-h.width);if(f>S){let X=d.cover({w:h.width,h:h.height});s.buffer=await X.getBuffer("image/jpeg"),g="current",s.width=h.width,s.height=h.height}else if(S>f){let X=m.cover({w:p.width,h:p.height});u.buffer=await X.getBuffer("image/jpeg"),g="saved"}let R={data:Buffer.alloc(s.width*s.height*4),width:s.width,height:s.height},A=t.threshold??.1,w=hF(Yh.decode(u.buffer).data,Yh.decode(s.buffer).data,R.data,s.width,s.height,{threshold:A,diffColorAlt:[0,255,0]})/(s.width*s.height)*100,I=w>A*100,P=`Visual diff of ${w.toFixed(2)}% detected, which is ${I?"over":"under"} the threshold of ${A*100}%.`;if(g&&(P+=` The ${g} screenshot was cropped since it was taller by ${y} pixels and wider by ${E} pixels.`),I)throw new x("ActionFailureError",P);return{fail:I,thoughts:P,beforeScreenshotOverride:s.buffer,afterScreenshotOverride:Yh.encode(R,75).data,succeedImmediately:!1,urlAfterCommand:o.url()}}var gF=3e4;async function LA({command:r,logger:e,baseUrl:t,fetchImplementation:n=fetch}){let o=r.timeout??gF/1e3,i=Object.fromEntries(Object.entries(r.headers||{}).filter(([m,h])=>m&&h)),a=new URLSearchParams;Object.entries(r.params||{}).filter(([m,h])=>m&&h).forEach(([m,h])=>{a.append(m,h)});let l=a.toString(),c;if(da(r.url)&&(c=r.url),t&&pa(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 G((async()=>{let m=l?`${c}?${l}`:c;try{return await n(m,{headers:i,method:r.method,body:r.body})}catch(h){throw e.error({err:h},"Failed to make HTTP request"),new Error(`Failed to make HTTP request: ${h}`)}})(),{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(h){m=`Failed to read response body: ${h}`}throw new x("ActionFailureError",`Fetch request failed with status ${u.status}: ${m}`)}let d={};u.headers.forEach((m,h)=>{d[h]=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 fF=5e3;async function Lu({timeout:r=nn,...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 NA(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 ie(l,e.signal),l=Math.min(Math.floor(l*1.5),fF);else return i}return i=await NA(e),i}async function NA({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(DA,{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(DA,{value:r.value,negated:!!r.negated,returnHtml:!0},"checking page content"));if(!i){let c=r.negated?Ir.CONTAINS:Mr.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 DA({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 Xh=async r=>{let{step:e,resolvedInputs:t}=r.moduleParams,{logger:n,context:o,storage:i,codeEvalTools:a,controller:l}=r.fixtures,c=l.browser,{orgId:s,runId:u}=r.inputs,d=l.executeAbortController.signal;Object.keys(t).length>0&&(o.setInputs(t),n.info(ua({json:{inputs:t,moduleId:e.moduleId},maxJsonStringSize:1e3}),"Set module inputs"));let p,m=!1,h,g;if(e.cacheConfig||e.defaultCacheAllInvocations){let f=e.cacheConfig?.cacheKey||e.defaultCacheKey||"",S=await fr({orgId:s,s:f,context:o,logger:n,localTools:a,signal:d});g={orgId:s,cacheKeys:[S,...Object.entries(t).map(([E,R])=>`${E}:${R}`)]},n.info({original:f,keyParams:g},"Module cache key params");let y=Date.now();for(;Date.now()-y<xT;){d?.throwIfAborted();let E=await i.getCacheResult(g);if(E){n.info({cacheResult:it(E,1e3,!0)},"Got result from module execution cache"),p=Nu(e,t,"SUCCESS"),p.message="Used cached module result.",p.data=JSON.parse(E),m=!0;break}else n.info({cacheKey:f,keyParams:g},"No cache result found, continuing with lock acquisition");let R=await i.acquireCacheLock({keyParams:g,clientMetadata:`hostName:${SF()};runId:${u}`},d);if(R.acquired){h=R.keyPrefix,n.info({cacheKeyPrefixIfLockAcquired:h,cacheKey:f,keyParams:g},"Acquired cache lock and proceeding with module execution");break}else n.debug({cacheKeyPrefixIfLockAcquired:h,cacheKey:f,keyParams:g},"Failed to acquire cache lock, retrying...");await ie(2500+Math.random()*1e4,d)}}try{if(!p)p=await yF(r);else if(e.autoAuth){let f=Oc.safeParse(p.data);if(!f.success)throw new x("UserConfigurationError",`Cached authentication module result is not a valid storage state: ${f.error.message}`);n.debug("Automatically loading auth state after cached module result"),await c.loadAuthState(f.data);let S=!1,y=e.advanced?.cacheInvalidation;if(y&&y.type==="PAGE_CHECK"){let E={type:"CONTENT",value:y.substring},R=await Lu({timeout:nn,assertion:E,browser:c,logger:n,signal:d,autoExpandIframes:!!c.userBrowserSettings.autoExpandIframes});R.success?n.debug({invalResult:R},"Cached result still valid after page check, continuing..."):(n.info({invalResult:R},"Invalidating cached result due to page check failure"),S=!0)}if(g&&S)return await i.deleteCacheResult(g),Xh(r)}}finally{try{h!==void 0&&!m&&p?.status==="SUCCESS"&&await EF({step:e,result:p,browser:l.browser,cacheKeyPrefix:h,logger:n,storage:i})}finally{h!==void 0&&await i.releaseCacheLock(h)}}return p},yF=async r=>{let{step:e,tracer:t}=r.moduleParams,n=Nu(e,r.moduleParams.resolvedInputs,"SUCCESS"),o=await t.startSubSteps(),{status:i,results:a}=await r.executeStepList({...r,listParams:{steps:e.steps,containerName:`module ('${e.name}')`,tracer:o}});return n.results=a,n.status=i,n.finishedAt=new Date,Sn({asyncTasks:r.work.asyncTasks,nestedResults:a,result:n,logger:r.fixtures.logger}),n};function Nu(r,e,t){let n={};return Object.entries(e).forEach(([i,a])=>{n[i]=JSON.stringify(a)}),{type:"MODULE",id:r.id,moduleId:r.moduleId,moduleName:r.name,startedAt:new Date,cacheConfig:r.cacheConfig,inputs:n,results:[],finishedAt:new Date,status:t}}async function kA({orgId:r,step:e,context:t,logger:n,codeEvalTools:o,signal:i}){let a={};try{for(let l of e.parameters??[]){let c=e.inputs?.[l]??e.defaultParameters?.[l];if(!c){n.warn(`No value or default found for parameter '${l}' that is required by module '${e.name}'`);continue}a[l]=await To({orgId:r,code:c,fragment:!0,context:t,logger:n,localTools:o,signal:i})}return a}catch(l){throw i?.throwIfAborted(),new x("UserConfigurationError",`Failed to evaluate module inputs: ${l}`)}}async function EF({step:r,result:e,browser:t,cacheKeyPrefix:n,logger:o,storage:i}){let a=r.cacheConfig?.cacheExpiryMs;(!a||a===mb)&&(a=r.defaultCacheTtl??hb);let l;r.autoAuth?l=JSON.stringify(await t.saveAuthState()):e.data!==void 0?l=JSON.stringify(e.data):l='""',o.debug({cacheKeyPrefix:n,ttlMs:a,truncatedCacheResultJson:ua({json:l,maxJsonStringSize:1e4})},"Setting module cache result"),await i.setCacheResult({result:l,keyPrefix:n,ttlMs:a})}async function fi(r,e,t){return TF(r,e,t)}async function TF(r,e,t){let n=new Date;try{return t.throwIfAborted(),await e()}catch(o){let i=new Date,a="FAILED",l;if(t.aborted||o instanceof DOMException&&o.name==="AbortError"?(l="Step aborted by user.",a="CANCELLED"):o instanceof x?l=`${o}`:l=`An unexpected error occurred: ${o.message}`,r.type==="RESOLVED_MODULE"){let c=Nu(r,{},"FAILED");return c.message=l,c.startedAt=n,c.finishedAt=i,c}return{...Eu(r),startedAt:n,finishedAt:i,status:a,data:null,message:l,results:[]}}}async function va(r,e){let t=!1;try{return r&&!r.state.failureRecoveryDisabled&&(r.state.failureRecoveryDisabled=!0,t=!0),await e()}finally{r&&t&&(r.state.failureRecoveryDisabled=void 0)}}import{cloneDeep as nH}from"lodash-es";import{randomUUID as UA}from"crypto";var Du=async r=>{let{step:e,tracer:t}=r.presetParams,{logger:n,controller:o,context:i}=r.fixtures,{collectDebugData:a}=r.options,{testMetadata:l}=r.inputs,c=e.command.type,s=n.child({commandType:c,stepId:e.id,commandId:e.command.id}),u=o.browser.url(),d=new Date,p,m=UA(),h=UA();if(a)try{if(p=await o.browser.screenshot({retries:1,clearHighlights:!0,quality:75}),!o.browser.userBrowserSettings.disableHtmlSnapshots){let E=await o.browser.getRawCondensedHtml();t.attachBeforeHtmlSnapshot({logger:s,snapshotId:m,html:E})}}catch(E){s.debug({err:E},"Failed to take before screenshot, continuing...")}let g,f,S,y=Ic();try{let E=await o.executePresetCommand(y,t,e.command,i,l?.advanced.disableAICaching??!1);E.beforeScreenshotOverride&&(p=E.beforeScreenshotOverride),S=E.afterScreenshotOverride;let R=new Date,A=o.browser.url();f={beforeUrl:u,afterUrl:A,startedAt:d,finishedAt:R,viewport:o.browser.getViewport(),status:E.fail?"FAILED":"SUCCESS",elementInteracted:E.elementInteracted},g={...e,message:E.thoughts??"Successfully executed preset action.",beforeUrl:u,afterUrl:A,finishedAt:R,startedAt:d,status:E.fail?"FAILED":"SUCCESS",data:E.data,results:[f],details:y.details},"assertion"in e.command&&(g.message=E.thoughts||"Assertion passed.")}catch(E){s.error({message:E.message,stack:E.stack},`Failed executing preset step ${gn(e.command)}`);let R=o.browser.url(),A=new Date,C=E instanceof Error?E.message:`${E}`;f={beforeUrl:u,afterUrl:R,startedAt:d,finishedAt:A,viewport:o.browser.getViewport(),status:E instanceof DOMException&&E.name==="AbortError"?"CANCELLED":"FAILED",message:C},g={...e,startedAt:d,finishedAt:A,beforeUrl:u,afterUrl:R,status:E instanceof DOMException&&E.name==="AbortError"?"CANCELLED":"FAILED",message:C,failureReason:E instanceof x?E.reason:void 0,results:[f],details:y.details}}if(a)try{if(S||(S=await o.browser.screenshot({retries:1,quality:75})),!o.browser.userBrowserSettings.disableHtmlSnapshots){let E=await o.browser.getRawCondensedHtml();t.attachAfterHtmlSnapshot({logger:s,snapshotId:h,html:E})}}catch(E){s.debug({err:E},"Failed to store debug data after step, likely because the page is still loading. This is non-fatal and does not affect the test.")}return f.beforeSnapshot=m,g.beforeSnapshot=m,f.afterSnapshot=h,g.afterSnapshot=h,p&&t.attachBeforeScreenshot({logger:s,snapshotId:m,screenshot:p}),S&&t.attachAfterScreenshot({logger:s,snapshotId:h,screenshot:S}),g};async function FA(r){let{step:e,tracer:t}=r.conditionalParams,{logger:n,controller:o}=r.fixtures,i=new Date,a=Eu(e),l=e.elseSteps,c=!0,s=[],u,d=Ic();for(let f=0;f<e.blocks.length;f++){n.info(`Evaluating condition ${f} in conditional step`);let S=e.blocks[f];try{let y=await Du({...r,presetParams:{tracer:t,step:S.assertion}});s.push(y),n.info(`Condition ${f} resolved to true, executing the corresponding ${S.steps.length} steps`),c=!1,l=S.steps,u=y}catch(y){n.info({err:y},`Condition ${f} resolved to false`)}finally{o.throwIfClosed()}}if(l)c&&n.info("No conditions resolved to true, executing the else block steps");else return n.warn("No conditions resolved to true and no else block was provided, causing the entire conditional step to be skipped"),{...a,status:"SUCCESS",startedAt:i,data:s[s.length-1]?.data,message:s[s.length-1]?.message,results:[],finishedAt:new Date,details:d.details};n.info(`Executing ${l.length} steps in the selected conditional block`);let p=await r.conditionalParams.tracer.startSubSteps(),m=await r.executeStepList({...r,listParams:{steps:l,containerName:"conditional block",tracer:p}}),g={...a,assertionResult:u,...m,startedAt:i,finishedAt:new Date};return Sn({asyncTasks:r.work.asyncTasks,nestedResults:[...s,...m.results],result:g,logger:n}),g}import{randomUUID as BA}from"crypto";var zA=async r=>{let{tracer:e}=r.aiStepParams,{controller:t,logger:n}=r.fixtures;await t.browser.waitForDOMStability();let o=await t.browser.screenshot({}),i=await bF(r);i.finishedAt=new Date,Sn({asyncTasks:r.work.asyncTasks,result:i,nestedResults:i.results,logger:r.fixtures.logger});let a=await t.browser.screenshot({}),l=BA();i.beforeSnapshot=l,e.attachBeforeScreenshot({logger:n,snapshotId:l,screenshot:o});let c=BA();return i.afterSnapshot=c,e.attachAfterScreenshot({logger:n,snapshotId:c,screenshot:a}),i},bF=async r=>{let{step:e,tracer:t}=r.aiStepParams,{controller:n,context:o,logger:i}=r.fixtures,a={...e,startedAt:new Date,beforeTestContext:o.toRedactedDisplayCopy(),finishedAt:new Date,results:[],status:"SUCCESS"};if(!("steps"in e&&e.steps&&e.steps.length>0&&e.steps[e.steps.length-1]?.command.type==="SUCCESS"))throw new x("UserConfigurationError","AI action has been fully deprecated. Please delete this step and transition to Dynamic AI Action.");try{let c=await t.startSubSteps(),{status:s}=await r.executeStepList({...r,listParams:{steps:e.steps,containerName:"AI action",results:a.results,tracer:c}});return a.finishedAt=new Date,a.status=s,a}catch(c){i.warn({err:c},"Failed executing saved deprecated AI action steps");let s=n.executeAbortController.signal.aborted;a.message=c instanceof Error?c.message:`${c}`,a.status=s?"CANCELLED":"FAILED"}return a};import{randomUUID as Jh}from"crypto";var HA=15,vF=7,GA=async r=>{let{tracer:e}=r.aiStepParams,{logger:t,controller:n}=r.fixtures;await n.browser.waitForDOMStability();let o=await n.browser.screenshot({quality:75}),i=await AF(r);i.finishedAt=new Date,Sn({asyncTasks:r.work.asyncTasks,result:i,nestedResults:i.results,logger:r.fixtures.logger});let a=await n.browser.screenshot({quality:75}),l=Jh();i.beforeSnapshot=l,e.attachBeforeScreenshot({logger:t,snapshotId:l,screenshot:o});let c=Jh();return i.afterSnapshot=c,e.attachAfterScreenshot({logger:t,snapshotId:c,screenshot:a}),i},AF=async r=>{let{step:e,tracer:t}=r.aiStepParams,{testMetadata:n,orgId:o}=r.inputs,{controller:i,context:a,logger:l,codeEvalTools:c}=r.fixtures,{step:s}=r.callbacks,u=`${e.id}-${Date.now()}`,d=l.child({stepId:e.id,langfuseSessionId:u}),p={...e,startedAt:new Date,beforeTestContext:a.toRedactedDisplayCopy(),results:[],finishedAt:new Date,status:"SUCCESS"},m=await fr({orgId:o,s:e.text,context:a,logger:d,localTools:c});await i.browser.waitForDOMStability({logger:d});let g=`data:image/jpeg;base64,${(await i.browser.screenshot({clearHighlights:!0,retries:2})).toString("base64")}`,f=[],S=0,y=0,E,R;for(;;){if(S>HA)return p.message=`Exceeded the maximum number of commands allowed per AI step (${HA})`,p.status="FAILED",p;if(i.executeAbortController.signal.aborted)return p.message="Test execution was cancelled",p.status="CANCELLED",p;s.onDynamicAIActionStatusUpdateEvent?.({parentStepId:e.id,message:"Evaluating current state..."});let A=await i.evaluateAiAction({goal:m,startingScreenshot:S===0?void 0:g,history:f,logger:d,langfuseSessionId:u,lastError:R}),{evaluation:C,reasoning:w,summary:I}=A;d.info(A,"Got AI evaluation");let P=p.results[S-1]?.id;switch(C.type){case"DONE":return p.message=`Our AI evaluator confirmed all tasks are complete: ${w}`,p.status="SUCCESS",P&&s.onDynamicAIActionEvaluatingEvent?.({stepId:P,status:"SUCCESS",message:`${I}
|
|
45
|
-
${w}`}),p;case"RIGHT_TRACK":{E=void 0,
|
|
46
|
-
${C.feedback}`,
|
|
44
|
+
${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 cF}from"lodash-es";async function fr(r){let{orgId:e,s:t,context:n,logger:o,signal:i,retries:a=2,timeoutMs:l=uo,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(),h;try{h=await To({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(h===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 g=typeof h=="string"?h:`${h}`;g=g.replaceAll(/\$/g,"$$$$"),d=d.replace(p[0],g)}return d}async function Pu(r){return wA(r)}async function wA({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 fr({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 wA({obj:s,bannedKeys:e,context:n,prefixPath:u,replacements:i,allowList:c?void 0:t,...a})}return i}function CA(r,e){for(let{path:t,original:n}of e)cF(r,t,n)}import uF from"fetch-retry";var Ofe=process.env.MAILINATOR_API_KEY,Lfe=uF(global.fetch,{retryOn:function(r,e,t){return r>3?!1:!!(e!==null||t&&t.status>=400)},retryDelay:function(r){return 500}});import{hostname as SF}from"os";import{cloneDeep as _A}from"lodash-es";async function IA(r){let{command:e,timeoutMs:t,fixtures:n}=r,{abortSignal:o}=n,i=HS(e.cache)?e.cache:void 0,a=_A(i),l=()=>{if(i){let m=bh(a,i);i.target=m.target,i.updatedAt=m.updatedAt}},c=Date.now(),s=0,u,d=500,p=!1;for(;s<2||Date.now()-c<t;){s++,s>1&&await ie(d,o),o?.throwIfAborted();let{result:m,elementWasFound:h}=await xA({cacheToUse:i,params:r});if(u=m,p=h,m.success)break;l(),d=Math.min(d*2,1e4)}if(!u)throw new x("InternalPlatformError",`Failed to evaluate manual element assertion in ${t}ms.`);if(o?.throwIfAborted(),!u.success&&i?.target&&Kl(i.target)){let m=i?.target?.memory?{target:{id:-1,memory:i.target.memory}}:void 0,{result:h}=await xA({cacheToUse:m,params:r});u=h,u.success||l()}return u.success&&i?.target&&!p&&(i.target=qs(i.target),i.updatedAt=new Date),u}async function xA({cacheToUse:r,params:e}){let{command:t,disableCache:n,fixtures:o,tracer:i,targetingWrapper:a}=e,{logger:l}=o;if(t.target&&!Zn(t.target))throw new Error("Element assertion with x/y is not supported yet");let c=pF(t.assertion),s,u=!1,d=_A(r);try{let{elementInteractedDisplayString:p,result:m,thoughts:h}=await a({ctx:o.ctx,tracer:i,command:t,target:t.target,cache:d?.target,action:async g=>dF(g.locator,e),options:{...t,allowNotActionableNodesOverride:!0,disableCache:n,memory:d?.target?.memory,disableGlobalLocatorRedirect:!0,source:Yo(t),targetName:"target"}});return s={success:m.success,data:m.data,err:m.err,elementInteractedDisplayString:p,thoughts:h},u=!0,m.success||(l.warn({aiThoughts:h,elementString:p,err:m.err},"Element check found an element but failed"),s={...m,thoughts:h}),{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 dF(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:it(c,500,!0)},!Ou(c,n.value,n.operation,!!n.negated)){let s=n.negated?Ir[n.operation]:Mr[n.operation];o=!1,i=new x("AssertionFailureError",`The content ${s} '${n.value}': ${c}`)}break}case"ELEMENT_ATTRIBUTE":{a={elementOuterHtml:it(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(!Ou(c,n.value,n.operation,!!n.negated)){let s=n.negated?Ir[n.operation]:Mr[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},nn*1e3);break}case"EDITABLE":{o=await r.isEditable({timeout:nn*1e3});break}case"EXISTS":{o=!0;break}case"ENABLED":{o=await r.isEnabled({timeout:nn*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?vh[n.condition]:Ah[n.condition];i=new x("AssertionFailureError",`The element ${c}`)}break}case"ELEMENT_NAME":{let c=await r.evaluate(s=>s.tagName);if(!Ou(c,n.value,n.operation,!!n.negated)){let s=n.negated?Ir[n.operation]:Mr[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(!Ou(c,n.value,n.operation,!!n.negated)){let s=n.negated?Ir[n.operation]:Mr[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 Ou(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 pF(r){return r.type==="ELEMENT_EXISTENCE"&&r.negated&&(r.condition==="EXISTS"||r.condition==="VISIBLE")}function MA(r){return r.type==="ELEMENT_EXISTENCE"&&r.negated&&r.condition==="EXISTS"}import{Jimp as mF}from"jimp";async function sl(r,e){let t=await r.screenshot(e),n=await mF.fromBuffer(t);return{buffer:t,width:Math.ceil(n.bitmap.width??0),height:Math.ceil(n.bitmap.height??0)}}import{Jimp as PA}from"jimp";import Yh from"jpeg-js";import hF from"pixelmatch";async function OA({ctx:r,tracer:e,command:t,disableCache:n,browser:o,targetingWrapper:i,logger:a,screenshotStorage:l}){if(t.target&&!Zn(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=>sl(o,{locator:q.locator,...c}),options:{...t,disableCache:n,disableGlobalLocatorRedirect:!0,memory:t.cache?.target?.memory,targetName:"target"}})).result:s=await sl(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 X=`${s.width}x${s.height}`,q=`${u.width}x${u.height}`;return{fail:!0,thoughts:`Current screenshot (${X}) 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 PA.fromBuffer(s.buffer),p={width:s.width,height:s.height},m=await PA.fromBuffer(u.buffer),h={width:u.width,height:u.height},g,f=p.width*p.height,y=h.width*h.height,S=Math.abs(p.height-h.height),E=Math.abs(p.width-h.width);if(f>y){let X=d.cover({w:h.width,h:h.height});s.buffer=await X.getBuffer("image/jpeg"),g="current",s.width=h.width,s.height=h.height}else if(y>f){let X=m.cover({w:p.width,h:p.height});u.buffer=await X.getBuffer("image/jpeg"),g="saved"}let R={data:Buffer.alloc(s.width*s.height*4),width:s.width,height:s.height},A=t.threshold??.1,w=hF(Yh.decode(u.buffer).data,Yh.decode(s.buffer).data,R.data,s.width,s.height,{threshold:A,diffColorAlt:[0,255,0]})/(s.width*s.height)*100,I=w>A*100,P=`Visual diff of ${w.toFixed(2)}% detected, which is ${I?"over":"under"} the threshold of ${A*100}%.`;if(g&&(P+=` The ${g} screenshot was cropped since it was taller by ${S} pixels and wider by ${E} pixels.`),I)throw new x("ActionFailureError",P);return{fail:I,thoughts:P,beforeScreenshotOverride:s.buffer,afterScreenshotOverride:Yh.encode(R,75).data,succeedImmediately:!1,urlAfterCommand:o.url()}}var gF=3e4;async function LA({command:r,logger:e,baseUrl:t,fetchImplementation:n=fetch}){let o=r.timeout??gF/1e3,i=Object.fromEntries(Object.entries(r.headers||{}).filter(([m,h])=>m&&h)),a=new URLSearchParams;Object.entries(r.params||{}).filter(([m,h])=>m&&h).forEach(([m,h])=>{a.append(m,h)});let l=a.toString(),c;if(da(r.url)&&(c=r.url),t&&pa(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 G((async()=>{let m=l?`${c}?${l}`:c;try{return await n(m,{headers:i,method:r.method,body:r.body})}catch(h){throw e.error({err:h},"Failed to make HTTP request"),new Error(`Failed to make HTTP request: ${h}`)}})(),{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(h){m=`Failed to read response body: ${h}`}throw new x("ActionFailureError",`Fetch request failed with status ${u.status}: ${m}`)}let d={};u.headers.forEach((m,h)=>{d[h]=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 fF=5e3;async function Lu({timeout:r=nn,...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 NA(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 ie(l,e.signal),l=Math.min(Math.floor(l*1.5),fF);else return i}return i=await NA(e),i}async function NA({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(DA,{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(DA,{value:r.value,negated:!!r.negated,returnHtml:!0},"checking page content"));if(!i){let c=r.negated?Ir.CONTAINS:Mr.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 DA({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 Xh=async r=>{let{step:e,resolvedInputs:t}=r.moduleParams,{logger:n,context:o,storage:i,codeEvalTools:a,controller:l}=r.fixtures,c=l.browser,{orgId:s,runId:u}=r.inputs,d=l.executeAbortController.signal;Object.keys(t).length>0&&(o.setInputs(t),n.info(ua({json:{inputs:t,moduleId:e.moduleId},maxJsonStringSize:1e3}),"Set module inputs"));let p,m=!1,h,g;if(e.cacheConfig||e.defaultCacheAllInvocations){let f=e.cacheConfig?.cacheKey||e.defaultCacheKey||"",y=await fr({orgId:s,s:f,context:o,logger:n,localTools:a,signal:d});g={orgId:s,cacheKeys:[y,...Object.entries(t).map(([E,R])=>`${E}:${R}`)]},n.info({original:f,keyParams:g},"Module cache key params");let S=Date.now();for(;Date.now()-S<xT;){d?.throwIfAborted();let E=await i.getCacheResult(g);if(E){n.info({cacheResult:it(E,1e3,!0)},"Got result from module execution cache"),p=Nu(e,t,"SUCCESS"),p.message="Used cached module result.",p.data=JSON.parse(E),m=!0;break}else n.info({cacheKey:f,keyParams:g},"No cache result found, continuing with lock acquisition");let R=await i.acquireCacheLock({keyParams:g,clientMetadata:`hostName:${SF()};runId:${u}`},d);if(R.acquired){h=R.keyPrefix,n.info({cacheKeyPrefixIfLockAcquired:h,cacheKey:f,keyParams:g},"Acquired cache lock and proceeding with module execution");break}else n.debug({cacheKeyPrefixIfLockAcquired:h,cacheKey:f,keyParams:g},"Failed to acquire cache lock, retrying...");await ie(2500+Math.random()*1e4,d)}}try{if(!p)p=await yF(r);else if(e.autoAuth){let f=Oc.safeParse(p.data);if(!f.success)throw new x("UserConfigurationError",`Cached authentication module result is not a valid storage state: ${f.error.message}`);n.debug("Automatically loading auth state after cached module result"),await c.loadAuthState(f.data);let y=!1,S=e.advanced?.cacheInvalidation;if(S&&S.type==="PAGE_CHECK"){let E={type:"CONTENT",value:S.substring},R=await Lu({timeout:nn,assertion:E,browser:c,logger:n,signal:d,autoExpandIframes:!!c.userBrowserSettings.autoExpandIframes});R.success?n.debug({invalResult:R},"Cached result still valid after page check, continuing..."):(n.info({invalResult:R},"Invalidating cached result due to page check failure"),y=!0)}if(g&&y)return await i.deleteCacheResult(g),Xh(r)}}finally{try{h!==void 0&&!m&&p?.status==="SUCCESS"&&await EF({step:e,result:p,browser:l.browser,cacheKeyPrefix:h,logger:n,storage:i})}finally{h!==void 0&&await i.releaseCacheLock(h)}}return p},yF=async r=>{let{step:e,tracer:t}=r.moduleParams,n=Nu(e,r.moduleParams.resolvedInputs,"SUCCESS"),o=await t.startSubSteps(),{status:i,results:a}=await r.executeStepList({...r,listParams:{steps:e.steps,containerName:`module ('${e.name}')`,tracer:o}});return n.results=a,n.status=i,n.finishedAt=new Date,Sn({asyncTasks:r.work.asyncTasks,nestedResults:a,result:n,logger:r.fixtures.logger}),n};function Nu(r,e,t){let n={};return Object.entries(e).forEach(([i,a])=>{n[i]=JSON.stringify(a)}),{type:"MODULE",id:r.id,moduleId:r.moduleId,moduleName:r.name,startedAt:new Date,cacheConfig:r.cacheConfig,inputs:n,results:[],finishedAt:new Date,status:t}}async function kA({orgId:r,step:e,context:t,logger:n,codeEvalTools:o,signal:i}){let a={};try{for(let l of e.parameters??[]){let c=e.inputs?.[l]??e.defaultParameters?.[l];if(!c){n.warn(`No value or default found for parameter '${l}' that is required by module '${e.name}'`);continue}a[l]=await To({orgId:r,code:c,fragment:!0,context:t,logger:n,localTools:o,signal:i})}return a}catch(l){throw i?.throwIfAborted(),new x("UserConfigurationError",`Failed to evaluate module inputs: ${l}`)}}async function EF({step:r,result:e,browser:t,cacheKeyPrefix:n,logger:o,storage:i}){let a=r.cacheConfig?.cacheExpiryMs;(!a||a===mb)&&(a=r.defaultCacheTtl??hb);let l;r.autoAuth?l=JSON.stringify(await t.saveAuthState()):e.data!==void 0?l=JSON.stringify(e.data):l='""',o.debug({cacheKeyPrefix:n,ttlMs:a,truncatedCacheResultJson:ua({json:l,maxJsonStringSize:1e4})},"Setting module cache result"),await i.setCacheResult({result:l,keyPrefix:n,ttlMs:a})}async function fi(r,e,t){return TF(r,e,t)}async function TF(r,e,t){let n=new Date;try{return t.throwIfAborted(),await e()}catch(o){let i=new Date,a="FAILED",l;if(t.aborted||o instanceof DOMException&&o.name==="AbortError"?(l="Step aborted by user.",a="CANCELLED"):o instanceof x?l=`${o}`:l=`An unexpected error occurred: ${o.message}`,r.type==="RESOLVED_MODULE"){let c=Nu(r,{},"FAILED");return c.message=l,c.startedAt=n,c.finishedAt=i,c}return{...Eu(r),startedAt:n,finishedAt:i,status:a,data:null,message:l,results:[]}}}async function va(r,e){let t=!1;try{return r&&!r.state.failureRecoveryDisabled&&(r.state.failureRecoveryDisabled=!0,t=!0),await e()}finally{r&&t&&(r.state.failureRecoveryDisabled=void 0)}}import{cloneDeep as nH}from"lodash-es";import{randomUUID as UA}from"crypto";var Du=async r=>{let{step:e,tracer:t}=r.presetParams,{logger:n,controller:o,context:i}=r.fixtures,{collectDebugData:a}=r.options,{testMetadata:l}=r.inputs,c=e.command.type,s=n.child({commandType:c,stepId:e.id,commandId:e.command.id}),u=o.browser.url(),d=new Date,p,m=UA(),h=UA();if(a)try{if(p=await o.browser.screenshot({retries:1,clearHighlights:!0,quality:75}),!o.browser.userBrowserSettings.disableHtmlSnapshots){let E=await o.browser.getRawCondensedHtml();t.attachBeforeHtmlSnapshot({logger:s,snapshotId:m,html:E})}}catch(E){s.debug({err:E},"Failed to take before screenshot, continuing...")}let g,f,y,S=Ic();try{let E=await o.executePresetCommand(S,t,e.command,i,l?.advanced.disableAICaching??!1);E.beforeScreenshotOverride&&(p=E.beforeScreenshotOverride),y=E.afterScreenshotOverride;let R=new Date,A=o.browser.url();f={beforeUrl:u,afterUrl:A,startedAt:d,finishedAt:R,viewport:o.browser.getViewport(),status:E.fail?"FAILED":"SUCCESS",elementInteracted:E.elementInteracted},g={...e,message:E.thoughts??"Successfully executed preset action.",beforeUrl:u,afterUrl:A,finishedAt:R,startedAt:d,status:E.fail?"FAILED":"SUCCESS",data:E.data,results:[f],details:S.details},"assertion"in e.command&&(g.message=E.thoughts||"Assertion passed.")}catch(E){s.error({message:E.message,stack:E.stack},`Failed executing preset step ${gn(e.command)}`);let R=o.browser.url(),A=new Date,C=E instanceof Error?E.message:`${E}`;f={beforeUrl:u,afterUrl:R,startedAt:d,finishedAt:A,viewport:o.browser.getViewport(),status:E instanceof DOMException&&E.name==="AbortError"?"CANCELLED":"FAILED",message:C},g={...e,startedAt:d,finishedAt:A,beforeUrl:u,afterUrl:R,status:E instanceof DOMException&&E.name==="AbortError"?"CANCELLED":"FAILED",message:C,failureReason:E instanceof x?E.reason:void 0,results:[f],details:S.details}}if(a)try{if(y||(y=await o.browser.screenshot({retries:1,quality:75})),!o.browser.userBrowserSettings.disableHtmlSnapshots){let E=await o.browser.getRawCondensedHtml();t.attachAfterHtmlSnapshot({logger:s,snapshotId:h,html:E})}}catch(E){s.debug({err:E},"Failed to store debug data after step, likely because the page is still loading. This is non-fatal and does not affect the test.")}return f.beforeSnapshot=m,g.beforeSnapshot=m,f.afterSnapshot=h,g.afterSnapshot=h,p&&t.attachBeforeScreenshot({logger:s,snapshotId:m,screenshot:p}),y&&t.attachAfterScreenshot({logger:s,snapshotId:h,screenshot:y}),g};async function FA(r){let{step:e,tracer:t}=r.conditionalParams,{logger:n,controller:o}=r.fixtures,i=new Date,a=Eu(e),l=e.elseSteps,c=!0,s=[],u,d=Ic();for(let f=0;f<e.blocks.length;f++){n.info(`Evaluating condition ${f} in conditional step`);let y=e.blocks[f];try{let S=await Du({...r,presetParams:{tracer:t,step:y.assertion}});s.push(S),n.info(`Condition ${f} resolved to true, executing the corresponding ${y.steps.length} steps`),c=!1,l=y.steps,u=S}catch(S){n.info({err:S},`Condition ${f} resolved to false`)}finally{o.throwIfClosed()}}if(l)c&&n.info("No conditions resolved to true, executing the else block steps");else return n.warn("No conditions resolved to true and no else block was provided, causing the entire conditional step to be skipped"),{...a,status:"SUCCESS",startedAt:i,data:s[s.length-1]?.data,message:s[s.length-1]?.message,results:[],finishedAt:new Date,details:d.details};n.info(`Executing ${l.length} steps in the selected conditional block`);let p=await r.conditionalParams.tracer.startSubSteps(),m=await r.executeStepList({...r,listParams:{steps:l,containerName:"conditional block",tracer:p}}),g={...a,assertionResult:u,...m,startedAt:i,finishedAt:new Date};return Sn({asyncTasks:r.work.asyncTasks,nestedResults:[...s,...m.results],result:g,logger:n}),g}import{randomUUID as BA}from"crypto";var zA=async r=>{let{tracer:e}=r.aiStepParams,{controller:t,logger:n}=r.fixtures;await t.browser.waitForDOMStability();let o=await t.browser.screenshot({}),i=await bF(r);i.finishedAt=new Date,Sn({asyncTasks:r.work.asyncTasks,result:i,nestedResults:i.results,logger:r.fixtures.logger});let a=await t.browser.screenshot({}),l=BA();i.beforeSnapshot=l,e.attachBeforeScreenshot({logger:n,snapshotId:l,screenshot:o});let c=BA();return i.afterSnapshot=c,e.attachAfterScreenshot({logger:n,snapshotId:c,screenshot:a}),i},bF=async r=>{let{step:e,tracer:t}=r.aiStepParams,{controller:n,context:o,logger:i}=r.fixtures,a={...e,startedAt:new Date,beforeTestContext:o.toRedactedDisplayCopy(),finishedAt:new Date,results:[],status:"SUCCESS"};if(!("steps"in e&&e.steps&&e.steps.length>0&&e.steps[e.steps.length-1]?.command.type==="SUCCESS"))throw new x("UserConfigurationError","AI action has been fully deprecated. Please delete this step and transition to Dynamic AI Action.");try{let c=await t.startSubSteps(),{status:s}=await r.executeStepList({...r,listParams:{steps:e.steps,containerName:"AI action",results:a.results,tracer:c}});return a.finishedAt=new Date,a.status=s,a}catch(c){i.warn({err:c},"Failed executing saved deprecated AI action steps");let s=n.executeAbortController.signal.aborted;a.message=c instanceof Error?c.message:`${c}`,a.status=s?"CANCELLED":"FAILED"}return a};import{randomUUID as Jh}from"crypto";var HA=15,vF=7,GA=async r=>{let{tracer:e}=r.aiStepParams,{logger:t,controller:n}=r.fixtures;await n.browser.waitForDOMStability();let o=await n.browser.screenshot({quality:75}),i=await AF(r);i.finishedAt=new Date,Sn({asyncTasks:r.work.asyncTasks,result:i,nestedResults:i.results,logger:r.fixtures.logger});let a=await n.browser.screenshot({quality:75}),l=Jh();i.beforeSnapshot=l,e.attachBeforeScreenshot({logger:t,snapshotId:l,screenshot:o});let c=Jh();return i.afterSnapshot=c,e.attachAfterScreenshot({logger:t,snapshotId:c,screenshot:a}),i},AF=async r=>{let{step:e,tracer:t}=r.aiStepParams,{testMetadata:n,orgId:o}=r.inputs,{controller:i,context:a,logger:l,codeEvalTools:c}=r.fixtures,{step:s}=r.callbacks,u=`${e.id}-${Date.now()}`,d=l.child({stepId:e.id,langfuseSessionId:u}),p={...e,startedAt:new Date,beforeTestContext:a.toRedactedDisplayCopy(),results:[],finishedAt:new Date,status:"SUCCESS"},m=await fr({orgId:o,s:e.text,context:a,logger:d,localTools:c});await i.browser.waitForDOMStability({logger:d});let g=`data:image/jpeg;base64,${(await i.browser.screenshot({clearHighlights:!0,retries:2})).toString("base64")}`,f=[],y=0,S=0,E,R;for(;;){if(y>HA)return p.message=`Exceeded the maximum number of commands allowed per AI step (${HA})`,p.status="FAILED",p;if(i.executeAbortController.signal.aborted)return p.message="Test execution was cancelled",p.status="CANCELLED",p;s.onDynamicAIActionStatusUpdateEvent?.({parentStepId:e.id,message:"Evaluating current state..."});let A=await i.evaluateAiAction({goal:m,startingScreenshot:y===0?void 0:g,history:f,logger:d,langfuseSessionId:u,lastError:R}),{evaluation:C,reasoning:w,summary:I}=A;d.info(A,"Got AI evaluation");let P=p.results[y-1]?.id;switch(C.type){case"DONE":return p.message=`Our AI evaluator confirmed all tasks are complete: ${w}`,p.status="SUCCESS",P&&s.onDynamicAIActionEvaluatingEvent?.({stepId:P,status:"SUCCESS",message:`${I}
|
|
45
|
+
${w}`}),p;case"RIGHT_TRACK":{E=void 0,y===0?s.onDynamicAIActionEvaluatingEvent?.({stepId:e.id,status:"RUNNING",message:w}):P&&s.onDynamicAIActionEvaluatingEvent?.({stepId:P,status:"SUCCESS",message:w});break}case"WRONG_TRACK":{if(E=`${w}
|
|
46
|
+
${C.feedback}`,S++,S>=vF)return p.message=`Our AI agent requires additional information to achieve this goal:
|
|
47
47
|
${w}
|
|
48
|
-
${C.feedback}`,p.status="FAILED",s.onDynamicAIActionStatusUpdateEvent?.({parentStepId:e.id,status:"FAILED",message:p.message}),p;P&&s.onDynamicAIActionEvaluatingEvent?.({stepId:P,status:"FAILED",message:C.feedback});break}case"IMPOSSIBLE":return p.message=`Our AI evaluator determined this task cannot be achieved: ${w}`,p.status="FAILED",s.onDynamicAIActionEvaluatingEvent?.({stepId:P??e.id,status:"FAILED",message:p.message}),p}let X=setTimeout(()=>{s.onDynamicAIActionStatusUpdateEvent?.({parentStepId:e.id,message:"Deciding what to do next..."})},1500);d.info({commandIndex:S,lastActionHint:E},`Generating new sub-command ${S} within AI action`);let q,k;try{({command:q,reasoning:k}=await i.promptToCommand({goal:m,history:f,startingScreenshot:g,disableCache:n?.advanced.disableAICaching??!1,logger:d,actionHint:E,langfuseSessionId:u})),d.info({command:q,reasoning:k},"Got proposed command")}finally{clearTimeout(X)}if(q.type==="FAILURE")return clearTimeout(X),p.status="FAILED",p.message=`Our AI agent determined that no supported actions can fulfill the goals: ${k}`,p;let ee={id:Jh(),type:"PRESET_ACTION",command:q},z={substepIndex:S+1,message:k||"Generated new command."};s.onDynamicCommandGenerated?.({...z,step:ee,parentStepId:e.id}),d.info({commandId:q.id},`Executing sub-command ${S} within AI step: ${gn(q)}`);let j=await t.startSubSteps(),$=(await r.executeStepList({...r,options:{...r.options,disableHealing:!0},listParams:{containerName:"AI action newly generated step",steps:[ee],tracer:j}})).results[0];s.onDynamicAIActionStatusUpdateEvent?.({parentStepId:e.id,message:"Waiting for page to stabilize before next action..."}),await i.browser.waitForDOMStability({logger:d});let rt=await i.browser.screenshot({clearHighlights:!0,retries:1});p.results.push($),f.push({screenshotBase64AfterCommand:`data:image/jpeg;base64,${rt.toString("base64")}`,urlAfterCommand:i.browser.url(),serializedCommand:gn(q),elementInteracted:$.results[0]?.elementInteracted,thoughts:k});let Ne={substepIndex:S,output:{...$,message:$.message??"Successfully executed preset action."},step:ee,parentStepId:e.id};if(s.onDynamicCommandExecuted?.(Ne),await t.finish({output:Tc.parse($),step:$,message:$.message,attempt:1}),$.status==="FAILED")if(p.status="FAILED",p.message=$.message,y<3)y++,R=`The last attempted action resulted in a Momentic error. A different element may need to be targeted. Error: ${$.message}`;else return p;else if($.status==="CANCELLED")return p.status="CANCELLED",p.message=$.message,p;S++}};import{randomUUID as Xz}from"crypto";import Kye,{multistream as Xye}from"pino";import Qye from"pino-pretty";import{PostHog as RF}from"posthog-node";async function jA(r,e){let t,n=0,o=3,i,a;for(;n<o;)try{let l=await G(r.getAllFlagsAndPayloads(e),{milliseconds:5e3});i=l.featureFlags||{},a=l.featureFlagPayloads||{};break}catch(l){t=l,n++,await new Promise(c=>setTimeout(c,100*n))}if(i&&a)return{flags:i,payloads:a};throw t}var ku=class r extends Us{constructor(t,n,o,i){super(o,i);this.client=t;this.orgId=n}static async init(t){let n=new RF("phc_WRWd8LYIv6rolgDsyCdrPpxtZhsu6qXAkEwPicl44bI",{host:"https://us.i.posthog.com"}),{flags:o,payloads:i}=await jA(n,t);return new r(n,t,o,i)}async refresh(){let{flags:t,payloads:n}=await jA(this.client,this.orgId);this.flags=t,this.payloads=n}};import{randomUUID as wF}from"node:crypto";import{PostHog as CF}from"posthog-node";var Uu=class r{bindings;client;options;constructor(e,t={}){this.bindings=e,this.options=t,this.client=new CF("phc_oy1FexHsc0S3axxOMXCm46yZsW35zROAoV4SOzpDSXH",{host:"https://us.i.posthog.com",...t})}async shutdown(){await this.client.shutdown()}identify(e){return this.bindings={...this.bindings,...e},this}child(e){return new r({...this.bindings,...e},this.options)}track(e,t){if(!LE(this.bindings))return console.error(`Cannot track ${e.type} event without required bindings.`,this.bindings),this;let{type:n,...o}=e;return this.client.capture({distinctId:wF(),event:n,timestamp:t?.timestamp,properties:{...this.bindings,...o}}),this}};import{execSync as xF}from"child_process";import Aa from"os";import _F from"v8";var VA,yn,$A=Aa.platform(),IF=Aa.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),{}),Fu=r=>{try{let e=!1,t=MF(),n=PF(),o=`${Math.round(t.freePercentage*100)}%`;t.freePercentage<.05&&(e=!0);let i=`${n?Math.round(n.idle):"unknown"}%`;n&&n?.total>70&&(e=!0);let a=_F.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"),ii&&T.warn(`Low machine resources detected (memory: ${o} free, cpu: ${i} free)`)):r.debug({memory:t,cpu:n},"Got machine resource usage metrics")}catch{}},WA=r=>{Fu(r),setTimeout(()=>Fu(r),5e3)};function qA(r){if(!cn)return Fu(r),{interval:setInterval(()=>Fu(r),2e4),cpuMetadata:IF,platform:$A}}function MF(){let r=Aa.totalmem(),e=$A==="darwin"?OF():(()=>{let n=Aa.freemem();return{availableMemory:n,rawFreeMemory:n,cachedMemory:0}})(),t=e.availableMemory/r;return{totalMemory:r,freeMemory:e.availableMemory,freePercentage:t}}function PF(){let r=Aa.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,!yn)return yn=t,null;let n={user:t.user-yn.user,nice:t.nice-yn.nice,sys:t.sys-yn.sys,idle:t.idle-yn.idle,irq:t.irq-yn.irq,total:t.total-yn.total};return VA={measurementTime:e,intervalMs:e-yn.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},yn=t,VA}function OF(){try{let r=xF("/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=Aa.freemem();return{availableMemory:e,rawFreeMemory:e,cachedMemory:0}}}var Bu=class{increment(e,t,n){}gauge(e,t){}distribution(e,t,n){}async flush(){}async recordDuration({fn:e}){return await e()}};function LF(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 zu(r,e){let t=LF(r);return!e||Object.keys(e).length===0?t:{...e,...t}}var TR="=",Vu=";",cg=",";var bR=8192;var xa={};JM(xa,{getKeyPairs:()=>pB,parseKeyPairsIntoRecord:()=>mB,parsePairKeyValue:()=>vR,serializeKeyPairs:()=>dB});Ue();var uB=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 dB(r){return r.reduce(function(e,t){var n=""+e+(e!==""?cg:"")+t;return n.length>bR?e:n},"")}function pB(r){return r.getAllEntries().map(function(e){var t=uB(e,2),n=t[0],o=t[1],i=encodeURIComponent(n)+"="+encodeURIComponent(o.value);return o.metadata!==void 0&&(i+=Vu+o.metadata.toString()),i})}function vR(r){var e=r.split(Vu);if(!(e.length<=0)){var t=e.shift();if(t){var n=t.indexOf(TR);if(!(n<=0)){var o=decodeURIComponent(t.substring(0,n).trim()),i=decodeURIComponent(t.substring(n+1).trim()),a;return e.length>0&&(a=Zh(e.join(Vu))),{key:o,value:i,metadata:a}}}}}function mB(r){return typeof r!="string"||r.length===0?{}:r.split(cg).map(function(e){return vR(e)}).filter(function(e){return e!==void 0&&e.value.length>0}).reduce(function(e,t){return e[t.key]=t.value,e},{})}Ue();var $u;(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"})($u||($u={}));var hB=",",gB=["OTEL_SDK_DISABLED"];function fB(r){return gB.indexOf(r)>-1}var SB=["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 yB(r){return SB.indexOf(r)>-1}var EB=["OTEL_NO_PATCH_MODULES","OTEL_PROPAGATORS"];function TB(r){return EB.indexOf(r)>-1}var ug=1/0,dg=128,bB=128,vB=128,pg={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:qe.INFO,OTEL_NO_PATCH_MODULES:[],OTEL_PROPAGATORS:["tracecontext","baggage"],OTEL_RESOURCE_ATTRIBUTES:"",OTEL_SERVICE_NAME:"",OTEL_ATTRIBUTE_VALUE_LENGTH_LIMIT:ug,OTEL_ATTRIBUTE_COUNT_LIMIT:dg,OTEL_SPAN_ATTRIBUTE_VALUE_LENGTH_LIMIT:ug,OTEL_SPAN_ATTRIBUTE_COUNT_LIMIT:dg,OTEL_LOGRECORD_ATTRIBUTE_VALUE_LENGTH_LIMIT:ug,OTEL_LOGRECORD_ATTRIBUTE_COUNT_LIMIT:dg,OTEL_SPAN_EVENT_COUNT_LIMIT:128,OTEL_SPAN_LINK_COUNT_LIMIT:128,OTEL_SPAN_ATTRIBUTE_PER_EVENT_COUNT_LIMIT:bB,OTEL_SPAN_ATTRIBUTE_PER_LINK_COUNT_LIMIT:vB,OTEL_TRACES_EXPORTER:"",OTEL_TRACES_SAMPLER:$u.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 AB(r,e,t){if(!(typeof t[r]>"u")){var n=String(t[r]);e[r]=n.toLowerCase()==="true"}}function RB(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 wB(r,e,t,n){n===void 0&&(n=hB);var o=t[r];typeof o=="string"&&(e[r]=o.split(n).map(function(i){return i.trim()}))}var CB={ALL:qe.ALL,VERBOSE:qe.VERBOSE,DEBUG:qe.DEBUG,INFO:qe.INFO,WARN:qe.WARN,ERROR:qe.ERROR,NONE:qe.NONE};function xB(r,e,t){var n=t[r];if(typeof n=="string"){var o=CB[n.toUpperCase()];o!=null&&(e[r]=o)}}function AR(r){var e={};for(var t in pg){var n=t;switch(n){case"OTEL_LOG_LEVEL":xB(n,e,r);break;default:if(fB(n))AB(n,e,r);else if(yB(n))RB(n,e,r);else if(TB(n))wB(n,e,r);else{var o=r[n];typeof o<"u"&&o!==null&&(e[n]=String(o))}}}return e}function Dt(){var r=AR(process.env);return Object.assign({},pg,r)}function RR(r){return r>=48&&r<=57?r-48:r>=97&&r<=102?r-87:r-55}function Wu(r){for(var e=new Uint8Array(r.length/2),t=0,n=0;n<r.length;n+=2){var o=RR(r.charCodeAt(n)),i=RR(r.charCodeAt(n+1));e[t++]=o<<4|i}return e}var wR="1.25.1";var _B="deployment.environment";var IB="process.runtime.name";var MB="service.name";var PB="service.instance.id";var OB="telemetry.sdk.name",LB="telemetry.sdk.language",NB="telemetry.sdk.version";var CR=_B;var xR=IB;var qu=MB;var _R=PB;var hl=OB,gl=LB,fl=NB;var DB="nodejs";var IR=DB;var _a,Ku=(_a={},_a[hl]="opentelemetry",_a[xR]="node",_a[gl]=IR,_a[fl]=wR,_a);var kB=9,UB=6,FB=Math.pow(10,UB),BB=Math.pow(10,kB);function MR(r){var e=r/1e3,t=Math.trunc(e),n=Math.round(r%1e3*FB);return[t,n]}function PR(r){return r[0]*BB+r[1]}function Sl(r){return r[0]*1e6+r[1]/1e3}var yi;(function(r){r[r.SUCCESS=0]="SUCCESS",r[r.FAILED=1]="FAILED"})(yi||(yi={}));var OR=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 zB=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},HB=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))},LR=function(){function r(e,t){this._callback=e,this._that=t,this._isCalled=!1,this._deferred=new OR}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,HB([this._that],zB(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 Pr;(function(r){r[r.DELTA=0]="DELTA",r[r.CUMULATIVE=1]="CUMULATIVE"})(Pr||(Pr={}));var Kt;(function(r){r[r.HISTOGRAM=0]="HISTOGRAM",r[r.EXPONENTIAL_HISTOGRAM=1]="EXPONENTIAL_HISTOGRAM",r[r.GAUGE=2]="GAUGE",r[r.SUM=3]="SUM"})(Kt||(Kt={}));var GB=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 Dbe=function(r){GB(e,r);function e(t){var n=r.call(this,t)||this;return Object.setPrototypeOf(n,e.prototype),n}return e}(Error);function NR(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}Ue();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 DR=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 me;(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"})(me||(me={}));var jB=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 VB(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 mg=function(){function r(e,t,n,o){n===void 0&&(n=!0),o===void 0&&(o=VB(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=NR(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 hg=function(){function r(e,t){this._boundaries=e,this._recordMinMax=t,this.kind=Or.HISTOGRAM}return r.prototype.createAccumulation=function(e){return new mg(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 mg(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 mg(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:Kt.HISTOGRAM,dataPoints:n.map(function(i){var a=jB(i,2),l=a[0],c=a[1],s=c.toPointValue(),u=e.type===me.GAUGE||e.type===me.UP_DOWN_COUNTER||e.type===me.OBSERVABLE_GAUGE||e.type===me.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}();Ue();var gg=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},fg=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))},Sg=function(){function r(e,t,n,o){e===void 0&&(e=new $B),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 $B=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,fg([n,this._counts.length-t],gg(this._counts.slice(t)),!1)),o.splice.apply(o,fg([0,t],gg(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(fg([],gg(this._counts),!1))},r}();var kR=52,WB=2146435072,qB=1048575,yg=1023,Yu=-yg+1,Xu=yg,yl=Math.pow(2,-1022);function Ju(r){var e=new DataView(new ArrayBuffer(8));e.setFloat64(0,r);var t=e.getUint32(0),n=(t&WB)>>20;return n-yg}function Qu(r){var e=new DataView(new ArrayBuffer(8));e.setFloat64(0,r);var t=e.getUint32(0),n=e.getUint32(4),o=(t&qB)*Math.pow(2,32);return o+n}function El(r,e){return r===0||r===Number.POSITIVE_INFINITY||r===Number.NEGATIVE_INFINITY||Number.isNaN(r)?r:r*Math.pow(2,e)}function FR(r){return r--,r|=r>>1,r|=r>>2,r|=r>>4,r|=r>>8,r|=r>>16,r++,r}var KB=function(){var r=function(e,t){return r=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(n,o){n.__proto__=o}||function(n,o){for(var i in o)Object.prototype.hasOwnProperty.call(o,i)&&(n[i]=o[i])},r(e,t)};return function(e,t){if(typeof t!="function"&&t!==null)throw new TypeError("Class extends value "+String(t)+" is not a constructor or null");r(e,t);function n(){this.constructor=e}e.prototype=t===null?Object.create(t):(n.prototype=t.prototype,new n)}}(),bo=function(r){KB(e,r);function e(){return r!==null&&r.apply(this,arguments)||this}return e}(Error);var zR=function(){function r(e){this._shift=-e}return r.prototype.mapToIndex=function(e){if(e<yl)return this._minNormalLowerBoundaryIndex();var t=Ju(e),n=this._rightShift(Qu(e)-1,kR);return t+n>>this._shift},r.prototype.lowerBoundary=function(e){var t=this._minNormalLowerBoundaryIndex();if(e<t)throw new bo("underflow: "+e+" is < minimum lower boundary: "+t);var n=this._maxNormalLowerBoundaryIndex();if(e>n)throw new bo("overflow: "+e+" is > maximum lower boundary: "+n);return El(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=Yu>>this._shift;return this._shift<2&&e--,e},r.prototype._maxNormalLowerBoundaryIndex=function(){return Xu>>this._shift},r.prototype._rightShift=function(e,t){return Math.floor(e*Math.pow(2,-t))},r}();var HR=function(){function r(e){this._scale=e,this._scaleFactor=El(Math.LOG2E,e),this._inverseFactor=El(Math.LN2,-e)}return r.prototype.mapToIndex=function(e){if(e<=yl)return this._minNormalLowerBoundaryIndex()-1;if(Qu(e)===0){var t=Ju(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 bo("overflow: "+e+" is > maximum lower boundary: "+t)}var n=this._minNormalLowerBoundaryIndex();if(e<=n){if(e===n)return yl;if(e===n-1)return Math.exp((e+(1<<this._scale))/this._scaleFactor)/2;throw new bo("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 Yu<<this._scale},r.prototype._maxNormalLowerBoundaryIndex=function(){return(Xu+1<<this._scale)-1},r}();var GR=-10,jR=20,YB=Array.from({length:31},function(r,e){return e>10?new HR(e-10):new zR(e-10)});function Eg(r){if(r>jR||r<GR)throw new bo("expected scale >= "+GR+" && <= "+jR+", got: "+r);return YB[r+10]}var XB=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},Zu=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}(),JB=20,QB=160,Tg=2,ZB=function(){function r(e,t,n,o,i,a,l,c,s,u,d){e===void 0&&(e=e),t===void 0&&(t=QB),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 Sg),u===void 0&&(u=new Sg),d===void 0&&(d=Eg(JB)),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<Tg&&(V.warn("Exponential Histogram Max Size set to "+this._maxSize+", changing to the minimum size of: "+Tg),this._maxSize=Tg)}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=FR(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=Eg(t)}},r.prototype._minScale=function(e){var t=Math.min(this.scale,e.scale),n=Zu.combine(this._highLowAtScale(this.positive,this.scale,t),this._highLowAtScale(e.positive,e.scale,t)),o=Zu.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 Zu(0,-1);var o=t-n;return new Zu(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 VR=function(){function r(e,t){this._maxSize=e,this._recordMinMax=t,this.kind=Or.EXPONENTIAL_HISTOGRAM}return r.prototype.createAccumulation=function(e){return new ZB(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:Kt.EXPONENTIAL_HISTOGRAM,dataPoints:n.map(function(i){var a=XB(i,2),l=a[0],c=a[1],s=c.toPointValue(),u=e.type===me.GAUGE||e.type===me.UP_DOWN_COUNTER||e.type===me.OBSERVABLE_GAUGE||e.type===me.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 e1=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},bg=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=MR(Date.now())},r.prototype.setStartTime=function(e){this.startTime=e},r.prototype.toPointValue=function(){return this._current},r}();var $R=function(){function r(){this.kind=Or.LAST_VALUE}return r.prototype.createAccumulation=function(e){return new bg(e)},r.prototype.merge=function(e,t){var n=Sl(t.sampleTime)>=Sl(e.sampleTime)?t:e;return new bg(e.startTime,n.toPointValue(),n.sampleTime)},r.prototype.diff=function(e,t){var n=Sl(t.sampleTime)>=Sl(e.sampleTime)?t:e;return new bg(t.startTime,n.toPointValue(),n.sampleTime)},r.prototype.toMetricData=function(e,t,n,o){return{descriptor:e,aggregationTemporality:t,dataPointType:Kt.GAUGE,dataPoints:n.map(function(i){var a=e1(i,2),l=a[0],c=a[1];return{attributes:l,startTime:c.startTime,endTime:o,value:c.toPointValue()}})}},r}();var t1=function(r,e){var t=typeof Symbol=="function"&&r[Symbol.iterator];if(!t)return r;var n=t.call(r),o,i=[],a;try{for(;(e===void 0||e-- >0)&&!(o=n.next()).done;)i.push(o.value)}catch(l){a={error:l}}finally{try{o&&!o.done&&(t=n.return)&&t.call(n)}finally{if(a)throw a.error}}return i},Tl=function(){function r(e,t,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 vg=function(){function r(e){this.monotonic=e,this.kind=Or.SUM}return r.prototype.createAccumulation=function(e){return new Tl(e,this.monotonic)},r.prototype.merge=function(e,t){var n=e.toPointValue(),o=t.toPointValue();return t.reset?new Tl(t.startTime,this.monotonic,o,t.reset):new Tl(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 Tl(t.startTime,this.monotonic,o,!0):new Tl(t.startTime,this.monotonic,o-n)},r.prototype.toMetricData=function(e,t,n,o){return{descriptor:e,aggregationTemporality:t,dataPointType:Kt.SUM,dataPoints:n.map(function(i){var a=t1(i,2),l=a[0],c=a[1];return{attributes:l,startTime:c.startTime,endTime:o,value:c.toPointValue()}}),isMonotonic:this.monotonic}},r}();var Ei=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)}}(),Tn=function(){function r(){}return r.Drop=function(){return ZR},r.Sum=function(){return ew},r.LastValue=function(){return tw},r.Histogram=function(){return rw},r.ExponentialHistogram=function(){return r1},r.Default=function(){return n1},r}();var WR=function(r){Ei(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 DR,e}(Tn);var qR=function(r){Ei(e,r);function e(){return r!==null&&r.apply(this,arguments)||this}return e.prototype.createAggregator=function(t){switch(t.type){case me.COUNTER:case me.OBSERVABLE_COUNTER:case me.HISTOGRAM:return e.MONOTONIC_INSTANCE;default:return e.NON_MONOTONIC_INSTANCE}},e.MONOTONIC_INSTANCE=new vg(!0),e.NON_MONOTONIC_INSTANCE=new vg(!1),e}(Tn);var KR=function(r){Ei(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 $R,e}(Tn);var YR=function(r){Ei(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 hg([0,5,10,25,50,75,100,250,500,750,1e3,2500,5e3,7500,1e4],!0),e}(Tn);var XR=function(r){Ei(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 hg(this._boundaries,this._recordMinMax)},e}(Tn);var JR=function(r){Ei(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 VR(this._maxSize,this._recordMinMax)},e}(Tn);var QR=function(r){Ei(e,r);function e(){return r!==null&&r.apply(this,arguments)||this}return e.prototype._resolve=function(t){switch(t.type){case me.COUNTER:case me.UP_DOWN_COUNTER:case me.OBSERVABLE_COUNTER:case me.OBSERVABLE_UP_DOWN_COUNTER:return ew;case me.GAUGE:case me.OBSERVABLE_GAUGE:return tw;case me.HISTOGRAM:return t.advice.explicitBucketBoundaries?new XR(t.advice.explicitBucketBoundaries):rw}return V.warn("Unable to recognize instrument type: "+t.type),ZR},e.prototype.createAggregator=function(t){return this._resolve(t).createAggregator(t)},e}(Tn);var ZR=new WR,ew=new qR,tw=new KR,rw=new YR,r1=new JR,n1=new QR;Ue();function ed(){return"unknown_service:"+process.argv0}var vo=function(){return vo=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},vo.apply(this,arguments)},o1=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())})},i1=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}}},a1=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},Ag=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 V.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[qu]=ed(),e[gl]=Ku[gl],e[hl]=Ku[hl],e[fl]=Ku[fl],e))},Object.defineProperty(r.prototype,"attributes",{get:function(){var e;return this.asyncAttributesPending&&V.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 o1(this,void 0,void 0,function(){return i1(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=vo(vo({},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=a1(a,2),s=c[0],u=c[1];return vo(vo(vo(vo({},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 Ti;(function(r){r[r.DELTA=0]="DELTA",r[r.CUMULATIVE=1]="CUMULATIVE",r[r.LOWMEMORY=2]="LOWMEMORY"})(Ti||(Ti={}));Ue();var s1=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())})},l1=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}}},Rg=function(){return Pr.CUMULATIVE},nw=function(r){switch(r){case me.COUNTER:case me.OBSERVABLE_COUNTER:case me.GAUGE:case me.HISTOGRAM:case me.OBSERVABLE_GAUGE:return Pr.DELTA;case me.UP_DOWN_COUNTER:case me.OBSERVABLE_UP_DOWN_COUNTER:return Pr.CUMULATIVE}},ow=function(r){switch(r){case me.COUNTER:case me.HISTOGRAM:return Pr.DELTA;case me.GAUGE:case me.UP_DOWN_COUNTER:case me.OBSERVABLE_UP_DOWN_COUNTER:case me.OBSERVABLE_COUNTER:case me.OBSERVABLE_GAUGE:return Pr.CUMULATIVE}};function c1(){var r=Dt(),e=r.OTEL_EXPORTER_OTLP_METRICS_TEMPORALITY_PREFERENCE.trim().toLowerCase();return e==="cumulative"?Rg:e==="delta"?nw:e==="lowmemory"?ow:(V.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."),Rg)}function u1(r){return r!=null?r===Ti.DELTA?nw:r===Ti.LOWMEMORY?ow:Rg:c1()}function d1(r){return r?.aggregationPreference?r.aggregationPreference:function(e){return Tn.Default()}}var iw=function(){function r(e,t){this._otlpExporter=e,this._aggregationSelector=d1(t),this._aggregationTemporalitySelector=u1(t?.temporalityPreference)}return r.prototype.export=function(e,t){this._otlpExporter.export([e],t)},r.prototype.shutdown=function(){return s1(this,void 0,void 0,function(){return l1(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}();Ue();Ue();var p1=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},aw=1e4,sw=5,lw=1e3,cw=5e3,uw=1.5;function bl(r){r===void 0&&(r={});var e={};return Object.entries(r).forEach(function(t){var n=p1(t,2),o=n[0],i=n[1];typeof i<"u"?e[o]=String(i):V.warn('Header "'+o+'" has invalid value ('+i+") and will be ignored")}),e}function wg(r,e){return r.endsWith("/")||(r=r+"/"),r+e}function Cg(r){try{var e=new URL(r);return e.pathname===""&&(e.pathname=e.pathname+"/"),e.toString()}catch{return V.warn("Could not parse export URL: '"+r+"'"),r}}function xg(r){return typeof r=="number"?r<=0?_g(r,aw):r:m1()}function m1(){var r,e=Number((r=Dt().OTEL_EXPORTER_OTLP_TRACES_TIMEOUT)!==null&&r!==void 0?r:Dt().OTEL_EXPORTER_OTLP_TIMEOUT);return e<=0?_g(e,aw):e}function _g(r,e){return V.warn("Timeout must be greater than 0",r),e}function dw(r){var e=[429,502,503,504];return e.includes(r)}function pw(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 mw=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 LR(this._shutdown,this),this._concurrencyLimit=typeof e.concurrencyLimit=="number"?e.concurrencyLimit:30,this.timeoutMillis=xg(e.timeoutMillis),this.onInit(e)}return r.prototype.export=function(e,t){if(this._shutdownOnce.isCalled){t({code:yi.FAILED,error:new Error("Exporter has been shutdown")});return}if(this._sendingPromises.length>=this._concurrencyLimit){t({code:yi.FAILED,error:new Error("Concurrent export limit reached")});return}this._export(e).then(function(){t({code:yi.SUCCESS})}).catch(function(n){t({code:yi.FAILED,error:n})})},r.prototype._export=function(e){var t=this;return new Promise(function(n,o){try{V.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 V.debug("shutdown started"),this.onShutdown(),this.forceFlush()},r}();Ue();import*as Ig from"url";import*as rd from"http";import*as nd from"https";import*as hw from"zlib";import{Readable as g1}from"stream";var Ao;(function(r){r.NONE="none",r.GZIP="gzip"})(Ao||(Ao={}));var h1=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)}}(),Ia=function(r){h1(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 td=function(){return td=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},td.apply(this,arguments)};function Mg(r,e,t,n,o){var i=r.timeoutMillis,a=new Ig.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 g=new Ia("Request Timeout");o(g)}else l>=14?s.destroy():s.abort()},i),p={hostname:a.hostname,port:a.port,path:a.pathname,method:"POST",headers:td({"Content-Type":t},r.headers),agent:r.agent},m=a.protocol==="http:"?rd.request:nd.request,h=function(g,f){switch(g===void 0&&(g=sw),f===void 0&&(f=lw),s=m(p,function(y){var E="";y.on("data",function(R){return E+=R}),y.on("aborted",function(){if(u){var R=new Ia("Request Timeout");o(R)}}),y.on("end",function(){if(u===!1)if(y.statusCode&&y.statusCode<299)V.debug("statusCode: "+y.statusCode,E),n(),clearTimeout(d),clearTimeout(c);else if(y.statusCode&&dw(y.statusCode)&&g>0){var R=void 0;f=uw*f,y.headers["retry-after"]?R=pw(y.headers["retry-after"]):R=Math.round(Math.random()*(cw-f)+f),c=setTimeout(function(){h(g-1,f)},R)}else{var A=new Ia(y.statusMessage,y.statusCode,E);o(A),clearTimeout(d),clearTimeout(c)}})}),s.on("error",function(y){if(u){var E=new Ia("Request Timeout",y.code);o(E)}else o(y);clearTimeout(d),clearTimeout(c)}),s.on("abort",function(){if(u){var y=new Ia("Request Timeout");o(y)}clearTimeout(d),clearTimeout(c)}),r.compression){case Ao.GZIP:{s.setHeader("Content-Encoding","gzip");var S=f1(e);S.on("error",o).pipe(hw.createGzip()).on("error",o).pipe(s);break}default:s.end(Buffer.from(e));break}};h()}function f1(r){var e=new g1;return e.push(r),e.push(null),e}function Pg(r){if(r.httpAgentOptions&&r.keepAlive===!1){V.warn("httpAgentOptions is used only when keepAlive is true");return}if(!(r.keepAlive===!1||!r.url))try{var e=new Ig.URL(r.url),t=e.protocol==="http:"?rd.Agent:nd.Agent;return new t(td({keepAlive:!0},r.httpAgentOptions))}catch(n){V.error("collector exporter failed to create http agent. err: "+n.message);return}}function Og(r){if(r)return r;var e=Dt().OTEL_EXPORTER_OTLP_TRACES_COMPRESSION||Dt().OTEL_EXPORTER_OTLP_COMPRESSION;return e===Ao.GZIP?Ao.GZIP:Ao.NONE}Ue();var S1=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)}}(),od=function(r){S1(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&&V.warn("Metadata cannot be set when using http"),i.headers=Object.assign(i.DEFAULT_HEADERS,bl(t.headers),xa.parseKeyPairsIntoRecord(Dt().OTEL_EXPORTER_OTLP_HEADERS)),i.agent=Pg(t),i.compression=Og(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){V.debug("Shutdown already started. Cannot send objects");return}var a=new Promise(function(c,s){var u;Mg(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}(mw);function fw(r){var e=BigInt(1e9);return BigInt(r[0])*e+BigInt(r[1])}function y1(r){var e=Number(BigInt.asUintN(32,r)),t=Number(BigInt.asUintN(32,r>>BigInt(32)));return{low:e,high:t}}function Sw(r){var e=fw(r);return y1(e)}function E1(r){var e=fw(r);return e.toString()}var T1=typeof BigInt<"u"?E1:PR;function gw(r){return r}function yw(r){if(r!==void 0)return Wu(r)}var b1={encodeHrTime:Sw,encodeSpanContext:Wu,encodeOptionalSpanContext:yw};function Ew(r){var e,t;if(r===void 0)return b1;var n=(e=r.useLongBits)!==null&&e!==void 0?e:!0,o=(t=r.useHex)!==null&&t!==void 0?t:!1;return{encodeHrTime:n?Sw:T1,encodeSpanContext:o?gw:Wu,encodeOptionalSpanContext:o?gw:yw}}var v1=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 Tw(r){return{name:r.name,version:r.version}}function Ma(r){return Object.keys(r).map(function(e){return bw(e,r[e])})}function bw(r,e){return{key:r,value:vw(e)}}function vw(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(vw)}}:e==="object"&&r!=null?{kvlistValue:{values:Object.entries(r).map(function(t){var n=v1(t,2),o=n[0],i=n[1];return bw(o,i)})}}:{}}function Aw(r){return{attributes:Ma(r.attributes),droppedAttributesCount:0}}Ue();function ww(r,e){var t=Ew(e);return{resource:Aw(r.resource),schemaUrl:void 0,scopeMetrics:A1(r.scopeMetrics,t)}}function A1(r,e){return Array.from(r.map(function(t){return{scope:Tw(t.scope),metrics:t.metrics.map(function(n){return R1(n,e)}),schemaUrl:t.scope.schemaUrl}}))}function R1(r,e){var t={name:r.descriptor.name,description:r.descriptor.description,unit:r.descriptor.unit},n=_1(r.aggregationTemporality);switch(r.dataPointType){case Kt.SUM:t.sum={aggregationTemporality:n,isMonotonic:r.isMonotonic,dataPoints:Rw(r,e)};break;case Kt.GAUGE:t.gauge={dataPoints:Rw(r,e)};break;case Kt.HISTOGRAM:t.histogram={aggregationTemporality:n,dataPoints:C1(r,e)};break;case Kt.EXPONENTIAL_HISTOGRAM:t.exponentialHistogram={aggregationTemporality:n,dataPoints:x1(r,e)};break}return t}function w1(r,e,t){var n={attributes:Ma(r.attributes),startTimeUnixNano:t.encodeHrTime(r.startTime),timeUnixNano:t.encodeHrTime(r.endTime)};switch(e){case Sr.INT:n.asInt=r.value;break;case Sr.DOUBLE:n.asDouble=r.value;break}return n}function Rw(r,e){return r.dataPoints.map(function(t){return w1(t,r.descriptor.valueType,e)})}function C1(r,e){return r.dataPoints.map(function(t){var n=t.value;return{attributes:Ma(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 x1(r,e){return r.dataPoints.map(function(t){var n=t.value;return{attributes:Ma(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 _1(r){switch(r){case Pr.DELTA:return 1;case Pr.CUMULATIVE:return 2}}function Cw(r,e){return{resourceMetrics:r.map(function(t){return ww(t,e)})}}var Lg={serializeRequest:function(r){var e=Cw(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 xw="0.52.1";var _w=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)}}(),Pa=function(){return Pa=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},Pa.apply(this,arguments)},Iw="v1/metrics",I1="http://localhost:4318/"+Iw,M1={"User-Agent":"OTel-OTLP-Exporter-JavaScript/"+xw},P1=function(r){_w(e,r);function e(t){var n=r.call(this,t,Lg,"application/json")||this;return n.headers=Pa(Pa(Pa(Pa({},n.headers),M1),xa.parseKeyPairsIntoRecord(Dt().OTEL_EXPORTER_OTLP_METRICS_HEADERS)),bl(t?.headers)),n}return e.prototype.getDefaultUrl=function(t){return typeof t.url=="string"?t.url:Dt().OTEL_EXPORTER_OTLP_METRICS_ENDPOINT.length>0?Cg(Dt().OTEL_EXPORTER_OTLP_METRICS_ENDPOINT):Dt().OTEL_EXPORTER_OTLP_ENDPOINT.length>0?wg(Dt().OTEL_EXPORTER_OTLP_ENDPOINT,Iw):I1},e}(od),Mw=function(r){_w(e,r);function e(t){return r.call(this,new P1(t),t)||this}return e}(iw);var Oa;(function(r){r[r.DELTA=0]="DELTA",r[r.CUMULATIVE=1]="CUMULATIVE"})(Oa||(Oa={}));var bn;(function(r){r[r.HISTOGRAM=0]="HISTOGRAM",r[r.EXPONENTIAL_HISTOGRAM=1]="EXPONENTIAL_HISTOGRAM",r[r.GAUGE=2]="GAUGE",r[r.SUM=3]="SUM"})(bn||(bn={}));Ue();var O1=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)}}(),Pw=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())})},Ow=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}}},L1=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},N1=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))},D1=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 Lw(r){return r!=null}function id(r){var e=Object.keys(r);return e.length===0?"":(e=e.sort(),JSON.stringify(e.map(function(t){return[t,r[t]]})))}function Nw(r){var e,t;return r.name+":"+((e=r.version)!==null&&e!==void 0?e:"")+":"+((t=r.schemaUrl)!==null&&t!==void 0?t:"")}var Ng=function(r){O1(e,r);function e(t){var n=r.call(this,t)||this;return Object.setPrototypeOf(n,e.prototype),n}return e}(Error);function Ro(r,e){var t,n=new Promise(function(i,a){t=setTimeout(function(){a(new Ng("Operation timed out."))},e)});return Promise.race([r,n]).then(function(o){return clearTimeout(t),o},function(o){throw clearTimeout(t),o})}function Dw(r){return Pw(this,void 0,void 0,function(){var e=this;return Ow(this,function(t){return[2,Promise.all(r.map(function(n){return Pw(e,void 0,void 0,function(){var o,i;return Ow(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 kw(r){return r.status==="rejected"}function Dg(r,e){var t=[];return r.forEach(function(n){t.push.apply(t,N1([],L1(e(n)),!1))}),t}function Uw(r,e){var t,n;if(r.size!==e.size)return!1;try{for(var o=D1(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 Fw(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 Bw(r,e){return r.toLowerCase()===e.toLowerCase()}Ue();var Lr;(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"})(Lr||(Lr={}));var kg=function(){function r(){this.kind=Lr.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}();Ue();var Te;(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"})(Te||(Te={}));function vn(r,e,t){var n,o,i,a;return U1(r)||V.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:Sr.DOUBLE,advice:(a=t?.advice)!==null&&a!==void 0?a:{}}}function zw(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 Hw(r,e){return Bw(r.name,e.name)&&r.unit===e.unit&&r.type===e.type&&r.valueType===e.valueType}var k1=/^[a-z][a-z0-9_.\-/]{0,254}$/i;function U1(r){return r.match(k1)!=null}var F1=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 B1(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 ad=function(){function r(e,t,n,o){n===void 0&&(n=!0),o===void 0&&(o=B1(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=Fw(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 sd=function(){function r(e,t){this._boundaries=e,this._recordMinMax=t,this.kind=Lr.HISTOGRAM}return r.prototype.createAccumulation=function(e){return new ad(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 ad(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 ad(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:bn.HISTOGRAM,dataPoints:n.map(function(i){var a=F1(i,2),l=a[0],c=a[1],s=c.toPointValue(),u=e.type===Te.GAUGE||e.type===Te.UP_DOWN_COUNTER||e.type===Te.OBSERVABLE_GAUGE||e.type===Te.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}();Ue();var Ug=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},Fg=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))},Bg=function(){function r(e,t,n,o){e===void 0&&(e=new z1),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 z1=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,Fg([n,this._counts.length-t],Ug(this._counts.slice(t)),!1)),o.splice.apply(o,Fg([0,t],Ug(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(Fg([],Ug(this._counts),!1))},r}();var Gw=52,H1=2146435072,G1=1048575,zg=1023,ld=-zg+1,cd=zg,vl=Math.pow(2,-1022);function ud(r){var e=new DataView(new ArrayBuffer(8));e.setFloat64(0,r);var t=e.getUint32(0),n=(t&H1)>>20;return n-zg}function dd(r){var e=new DataView(new ArrayBuffer(8));e.setFloat64(0,r);var t=e.getUint32(0),n=e.getUint32(4),o=(t&G1)*Math.pow(2,32);return o+n}function Al(r,e){return r===0||r===Number.POSITIVE_INFINITY||r===Number.NEGATIVE_INFINITY||Number.isNaN(r)?r:r*Math.pow(2,e)}function Vw(r){return r--,r|=r>>1,r|=r>>2,r|=r>>4,r|=r>>8,r|=r>>16,r++,r}var j1=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)}}(),wo=function(r){j1(e,r);function e(){return r!==null&&r.apply(this,arguments)||this}return e}(Error);var Ww=function(){function r(e){this._shift=-e}return r.prototype.mapToIndex=function(e){if(e<vl)return this._minNormalLowerBoundaryIndex();var t=ud(e),n=this._rightShift(dd(e)-1,Gw);return t+n>>this._shift},r.prototype.lowerBoundary=function(e){var t=this._minNormalLowerBoundaryIndex();if(e<t)throw new wo("underflow: "+e+" is < minimum lower boundary: "+t);var n=this._maxNormalLowerBoundaryIndex();if(e>n)throw new wo("overflow: "+e+" is > maximum lower boundary: "+n);return Al(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=ld>>this._shift;return this._shift<2&&e--,e},r.prototype._maxNormalLowerBoundaryIndex=function(){return cd>>this._shift},r.prototype._rightShift=function(e,t){return Math.floor(e*Math.pow(2,-t))},r}();var qw=function(){function r(e){this._scale=e,this._scaleFactor=Al(Math.LOG2E,e),this._inverseFactor=Al(Math.LN2,-e)}return r.prototype.mapToIndex=function(e){if(e<=vl)return this._minNormalLowerBoundaryIndex()-1;if(dd(e)===0){var t=ud(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 wo("overflow: "+e+" is > maximum lower boundary: "+t)}var n=this._minNormalLowerBoundaryIndex();if(e<=n){if(e===n)return vl;if(e===n-1)return Math.exp((e+(1<<this._scale))/this._scaleFactor)/2;throw new wo("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 ld<<this._scale},r.prototype._maxNormalLowerBoundaryIndex=function(){return(cd+1<<this._scale)-1},r}();var Kw=-10,Yw=20,V1=Array.from({length:31},function(r,e){return e>10?new qw(e-10):new Ww(e-10)});function Hg(r){if(r>Yw||r<Kw)throw new wo("expected scale >= "+Kw+" && <= "+Yw+", got: "+r);return V1[r+10]}var $1=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},pd=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}(),W1=20,q1=160,Gg=2,Xw=function(){function r(e,t,n,o,i,a,l,c,s,u,d){e===void 0&&(e=e),t===void 0&&(t=q1),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 Bg),u===void 0&&(u=new Bg),d===void 0&&(d=Hg(W1)),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<Gg&&(V.warn("Exponential Histogram Max Size set to "+this._maxSize+", changing to the minimum size of: "+Gg),this._maxSize=Gg)}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=Vw(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=Hg(t)}},r.prototype._minScale=function(e){var t=Math.min(this.scale,e.scale),n=pd.combine(this._highLowAtScale(this.positive,this.scale,t),this._highLowAtScale(e.positive,e.scale,t)),o=pd.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 pd(0,-1);var o=t-n;return new pd(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 jg=function(){function r(e,t){this._maxSize=e,this._recordMinMax=t,this.kind=Lr.EXPONENTIAL_HISTOGRAM}return r.prototype.createAccumulation=function(e){return new Xw(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:bn.EXPONENTIAL_HISTOGRAM,dataPoints:n.map(function(i){var a=$1(i,2),l=a[0],c=a[1],s=c.toPointValue(),u=e.type===Te.GAUGE||e.type===Te.UP_DOWN_COUNTER||e.type===Te.OBSERVABLE_GAUGE||e.type===Te.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}();Ue();var K1=eg("OpenTelemetry SDK Context Key SUPPRESS_TRACING");function Jw(r){return r.setValue(K1,!0)}Ue();function Qw(){return function(r){V.error(Y1(r))}}function Y1(r){return typeof r=="string"?r:JSON.stringify(X1(r))}function X1(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 J1=Qw();function md(r){try{J1(r)}catch{}}var Zw="1.30.1";var Q1="process.runtime.name";var Z1="service.name";var ez="telemetry.sdk.name",tz="telemetry.sdk.language",rz="telemetry.sdk.version";var eC=Q1;var tC=Z1;var Rl=ez,wl=tz,Cl=rz;var nz="nodejs";var rC=nz;var La,bi=(La={},La[Rl]="opentelemetry",La[eC]="node",La[wl]=rC,La[Cl]=Zw,La);function xl(r){r.unref()}var uz=9,dz=6,pz=Math.pow(10,dz),BRe=Math.pow(10,uz);function vi(r){var e=r/1e3,t=Math.trunc(e),n=Math.round(r%1e3*pz);return[t,n]}function Na(r){return r[0]*1e6+r[1]/1e3}var _l;(function(r){r[r.SUCCESS=0]="SUCCESS",r[r.FAILED=1]="FAILED"})(_l||(_l={}));Ue();function nC(r,e){return new Promise(function(t){Ca.with(Jw(Ca.active()),function(){r.export(e,function(n){t(n)})})})}var oC={_export:nC};var mz=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},hd=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=vi(Date.now())},r.prototype.setStartTime=function(e){this.startTime=e},r.prototype.toPointValue=function(){return this._current},r}();var Vg=function(){function r(){this.kind=Lr.LAST_VALUE}return r.prototype.createAccumulation=function(e){return new hd(e)},r.prototype.merge=function(e,t){var n=Na(t.sampleTime)>=Na(e.sampleTime)?t:e;return new hd(e.startTime,n.toPointValue(),n.sampleTime)},r.prototype.diff=function(e,t){var n=Na(t.sampleTime)>=Na(e.sampleTime)?t:e;return new hd(t.startTime,n.toPointValue(),n.sampleTime)},r.prototype.toMetricData=function(e,t,n,o){return{descriptor:e,aggregationTemporality:t,dataPointType:bn.GAUGE,dataPoints:n.map(function(i){var a=mz(i,2),l=a[0],c=a[1];return{attributes:l,startTime:c.startTime,endTime:o,value:c.toPointValue()}})}},r}();var hz=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},Da=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 gd=function(){function r(e){this.monotonic=e,this.kind=Lr.SUM}return r.prototype.createAccumulation=function(e){return new Da(e,this.monotonic)},r.prototype.merge=function(e,t){var n=e.toPointValue(),o=t.toPointValue();return t.reset?new Da(t.startTime,this.monotonic,o,t.reset):new Da(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 Da(t.startTime,this.monotonic,o,!0):new Da(t.startTime,this.monotonic,o-n)},r.prototype.toMetricData=function(e,t,n,o){return{descriptor:e,aggregationTemporality:t,dataPointType:bn.SUM,dataPoints:n.map(function(i){var a=hz(i,2),l=a[0],c=a[1];return{attributes:l,startTime:c.startTime,endTime:o,value:c.toPointValue()}}),isMonotonic:this.monotonic}},r}();var Ai=function(){var r=function(e,t){return r=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(n,o){n.__proto__=o}||function(n,o){for(var i in o)Object.prototype.hasOwnProperty.call(o,i)&&(n[i]=o[i])},r(e,t)};return function(e,t){if(typeof t!="function"&&t!==null)throw new TypeError("Class extends value "+String(t)+" is not a constructor or null");r(e,t);function n(){this.constructor=e}e.prototype=t===null?Object.create(t):(n.prototype=t.prototype,new n)}}(),Nr=function(){function r(){}return r.Drop=function(){return dC},r.Sum=function(){return pC},r.LastValue=function(){return mC},r.Histogram=function(){return hC},r.ExponentialHistogram=function(){return gz},r.Default=function(){return fz},r}();var iC=function(r){Ai(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 kg,e}(Nr);var aC=function(r){Ai(e,r);function e(){return r!==null&&r.apply(this,arguments)||this}return e.prototype.createAggregator=function(t){switch(t.type){case Te.COUNTER:case Te.OBSERVABLE_COUNTER:case Te.HISTOGRAM:return e.MONOTONIC_INSTANCE;default:return e.NON_MONOTONIC_INSTANCE}},e.MONOTONIC_INSTANCE=new gd(!0),e.NON_MONOTONIC_INSTANCE=new gd(!1),e}(Nr);var sC=function(r){Ai(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 Vg,e}(Nr);var lC=function(r){Ai(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 sd([0,5,10,25,50,75,100,250,500,750,1e3,2500,5e3,7500,1e4],!0),e}(Nr);var Il=function(r){Ai(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 sd(this._boundaries,this._recordMinMax)},e}(Nr);var cC=function(r){Ai(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 jg(this._maxSize,this._recordMinMax)},e}(Nr);var uC=function(r){Ai(e,r);function e(){return r!==null&&r.apply(this,arguments)||this}return e.prototype._resolve=function(t){switch(t.type){case Te.COUNTER:case Te.UP_DOWN_COUNTER:case Te.OBSERVABLE_COUNTER:case Te.OBSERVABLE_UP_DOWN_COUNTER:return pC;case Te.GAUGE:case Te.OBSERVABLE_GAUGE:return mC;case Te.HISTOGRAM:return t.advice.explicitBucketBoundaries?new Il(t.advice.explicitBucketBoundaries):hC}return V.warn("Unable to recognize instrument type: "+t.type),dC},e.prototype.createAggregator=function(t){return this._resolve(t).createAggregator(t)},e}(Nr);var dC=new iC,pC=new aC,mC=new sC,hC=new lC,gz=new cC,fz=new uC;var gC=function(r){return Nr.Default()},fC=function(r){return Oa.CUMULATIVE};var $g=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())})},Wg=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}}},SC=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},Sz=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))},yC=function(){function r(e){var t,n,o;this._shutdown=!1,this._aggregationSelector=(t=e?.aggregationSelector)!==null&&t!==void 0?t:gC,this._aggregationTemporalitySelector=(n=e?.aggregationTemporalitySelector)!==null&&n!==void 0?n:fC,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 $g(this,void 0,void 0,function(){var t,n,o,i,a,l;return Wg(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(Sz([this._sdkMetricProducer.collect({timeoutMillis:e?.timeoutMillis})],SC(this._metricProducers.map(function(s){return s.collect({timeoutMillis:e?.timeoutMillis})})),!1))];case 1:return t=SC.apply(void 0,[c.sent()]),n=t[0],o=t.slice(1),i=n.errors.concat(Dg(o,function(s){return s.errors})),a=n.resourceMetrics.resource,l=n.resourceMetrics.scopeMetrics.concat(Dg(o,function(s){return s.resourceMetrics.scopeMetrics})),[2,{resourceMetrics:{resource:a,scopeMetrics:l},errors:i}]}})})},r.prototype.shutdown=function(e){return $g(this,void 0,void 0,function(){return Wg(this,function(t){switch(t.label){case 0:return this._shutdown?(V.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,Ro(this.onShutdown(),e.timeoutMillis)];case 3:t.sent(),t.label=4;case 4:return this._shutdown=!0,[2]}})})},r.prototype.forceFlush=function(e){return $g(this,void 0,void 0,function(){return Wg(this,function(t){switch(t.label){case 0:return this._shutdown?(V.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,Ro(this.onForceFlush(),e.timeoutMillis)];case 3:return t.sent(),[2]}})})},r}();Ue();var yz=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)}}(),fd=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())})},Sd=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}}},Ez=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},Tz=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))},qg=function(r){yz(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 fd(this,void 0,void 0,function(){var t;return Sd(this,function(n){switch(n.label){case 0:return n.trys.push([0,2,,3]),[4,Ro(this._doRun(),this._exportTimeout)];case 1:return n.sent(),[3,3];case 2:return t=n.sent(),t instanceof Ng?(V.error("Export took longer than %s milliseconds and timed out.",this._exportTimeout),[2]):(md(t),[3,3]);case 3:return[2]}})})},e.prototype._doRun=function(){var t,n;return fd(this,void 0,void 0,function(){var o,i,a,l,c,s;return Sd(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=V).error.apply(s,Tz(["PeriodicExportingMetricReader: metrics collection errors"],Ez(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(),V.debug("Error while resolving async portion of resource: ",l),md(l),[3,5];case 5:return i.scopeMetrics.length===0?[2]:[4,oC._export(this._exporter,i)];case 6:if(c=u.sent(),c.code!==_l.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),xl(this._interval)},e.prototype.onForceFlush=function(){return fd(this,void 0,void 0,function(){return Sd(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 fd(this,void 0,void 0,function(){return Sd(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}(yC);Ue();Ue();function yd(){return"unknown_service:"+process.argv0}var Co=function(){return Co=Object.assign||function(r){for(var e,t=1,n=arguments.length;t<n;t++){e=arguments[t];for(var o in e)Object.prototype.hasOwnProperty.call(e,o)&&(r[o]=e[o])}return r},Co.apply(this,arguments)},bz=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())})},vz=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}}},Az=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},Ed=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 V.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[tC]=yd(),e[wl]=bi[wl],e[Rl]=bi[Rl],e[Cl]=bi[Cl],e))},Object.defineProperty(r.prototype,"attributes",{get:function(){var e;return this.asyncAttributesPending&&V.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 bz(this,void 0,void 0,function(){return vz(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=Co(Co({},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=Az(a,2),s=c[0],u=c[1];return Co(Co(Co(Co({},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 EC=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}();Ue();var Ri=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)}}(),Td=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=Ca.active()),typeof e!="number"){V.warn("non-number value provided to metric "+this._descriptor.name+": "+e);return}this._descriptor.valueType===Sr.INT&&!Number.isInteger(e)&&(V.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,vi(Date.now()))},r}();var TC=function(r){Ri(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}(Td);var bC=function(r){Ri(e,r);function e(){return r!==null&&r.apply(this,arguments)||this}return e.prototype.add=function(t,n,o){if(t<0){V.warn("negative value provided to counter "+this._descriptor.name+": "+t);return}this._record(t,n,o)},e}(Td);var vC=function(r){Ri(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}(Td);var AC=function(r){Ri(e,r);function e(){return r!==null&&r.apply(this,arguments)||this}return e.prototype.record=function(t,n,o){if(t<0){V.warn("negative value provided to histogram "+this._descriptor.name+": "+t);return}this._record(t,n,o)},e}(Td);var bd=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 RC=function(r){Ri(e,r);function e(){return r!==null&&r.apply(this,arguments)||this}return e}(bd);var wC=function(r){Ri(e,r);function e(){return r!==null&&r.apply(this,arguments)||this}return e}(bd);var CC=function(r){Ri(e,r);function e(){return r!==null&&r.apply(this,arguments)||this}return e}(bd);function Ml(r){return r instanceof bd}var xC=function(){function r(e){this._meterSharedState=e}return r.prototype.createGauge=function(e,t){var n=vn(e,Te.GAUGE,t),o=this._meterSharedState.registerMetricStorage(n);return new vC(o,n)},r.prototype.createHistogram=function(e,t){var n=vn(e,Te.HISTOGRAM,t),o=this._meterSharedState.registerMetricStorage(n);return new AC(o,n)},r.prototype.createCounter=function(e,t){var n=vn(e,Te.COUNTER,t),o=this._meterSharedState.registerMetricStorage(n);return new bC(o,n)},r.prototype.createUpDownCounter=function(e,t){var n=vn(e,Te.UP_DOWN_COUNTER,t),o=this._meterSharedState.registerMetricStorage(n);return new TC(o,n)},r.prototype.createObservableGauge=function(e,t){var n=vn(e,Te.OBSERVABLE_GAUGE,t),o=this._meterSharedState.registerAsyncMetricStorage(n);return new wC(n,o,this._meterSharedState.observableRegistry)},r.prototype.createObservableCounter=function(e,t){var n=vn(e,Te.OBSERVABLE_COUNTER,t),o=this._meterSharedState.registerAsyncMetricStorage(n);return new RC(n,o,this._meterSharedState.observableRegistry)},r.prototype.createObservableUpDownCounter=function(e,t){var n=vn(e,Te.OBSERVABLE_UP_DOWN_COUNTER,t),o=this._meterSharedState.registerAsyncMetricStorage(n);return new CC(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 vd=function(){function r(e){this._instrumentDescriptor=e}return r.prototype.getInstrumentDescriptor=function(){return this._instrumentDescriptor},r.prototype.updateDescription=function(e){this._instrumentDescriptor=vn(this._instrumentDescriptor.name,this._instrumentDescriptor.type,{description:e,valueType:this._instrumentDescriptor.valueType,unit:this._instrumentDescriptor.unit,advice:this._instrumentDescriptor.advice})},r}();var Rz=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)}}(),_C=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}}},wz=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 _C(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 _C(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 Jr=function(r){Rz(e,r);function e(){return r.call(this,id)||this}return e}(wz);var Cz=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},Ad=function(){function r(e,t){this._aggregator=e,this._activeCollectionStorage=new Jr,this._cumulativeMemoStorage=new Jr,this._overflowAttributes={"otel.metric.overflow":!0},this._cardinalityLimit=(t??2e3)-1,this._overflowHashCode=id(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=Cz(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 Jr,e},r}();var Kg=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.")},IC=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},Rd=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===Oa.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=xz(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=Kg(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 Jr,i=this._unreportedAccumulations.get(e);if(this._unreportedAccumulations.set(e,[]),i===void 0)return o;try{for(var a=Kg(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=IC(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=Kg(e.keys()),l=a.next();!l.done;l=a.next()){var c=IC(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 xz(r){return Array.from(r.entries())}var _z=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)}}(),Iz=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},MC=function(r){_z(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 Ad(n,l._aggregationCardinalityLimit),l._temporalMetricStorage=new Rd(n,i),l}return e.prototype.record=function(t,n){var o=this,i=new Jr;Array.from(t.entries()).forEach(function(a){var l=Iz(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}(vd);Ue();function Yg(r,e){var t="";return r.unit!==e.unit&&(t+=" - Unit '"+r.unit+"' does not match '"+e.unit+`'
|
|
48
|
+
${C.feedback}`,p.status="FAILED",s.onDynamicAIActionStatusUpdateEvent?.({parentStepId:e.id,status:"FAILED",message:p.message}),p;P&&s.onDynamicAIActionEvaluatingEvent?.({stepId:P,status:"FAILED",message:C.feedback});break}case"IMPOSSIBLE":return p.message=`Our AI evaluator determined this task cannot be achieved: ${w}`,p.status="FAILED",s.onDynamicAIActionEvaluatingEvent?.({stepId:P??e.id,status:"FAILED",message:p.message}),p}let X=setTimeout(()=>{s.onDynamicAIActionStatusUpdateEvent?.({parentStepId:e.id,message:"Deciding what to do next..."})},1500);d.info({commandIndex:y,lastActionHint:E},`Generating new sub-command ${y} within AI action`);let q,k;try{({command:q,reasoning:k}=await i.promptToCommand({goal:m,history:f,startingScreenshot:g,disableCache:n?.advanced.disableAICaching??!1,logger:d,actionHint:E,langfuseSessionId:u})),d.info({command:q,reasoning:k},"Got proposed command")}finally{clearTimeout(X)}if(q.type==="FAILURE")return clearTimeout(X),p.status="FAILED",p.message=`Our AI agent determined that no supported actions can fulfill the goals: ${k}`,p;let ee={id:Jh(),type:"PRESET_ACTION",command:q},z={substepIndex:y+1,message:k||"Generated new command."};s.onDynamicCommandGenerated?.({...z,step:ee,parentStepId:e.id}),d.info({commandId:q.id},`Executing sub-command ${y} within AI step: ${gn(q)}`);let j=await t.startSubSteps(),$=(await r.executeStepList({...r,options:{...r.options,disableHealing:!0},listParams:{containerName:"AI action newly generated step",steps:[ee],tracer:j}})).results[0];s.onDynamicAIActionStatusUpdateEvent?.({parentStepId:e.id,message:"Waiting for page to stabilize before next action..."}),await i.browser.waitForDOMStability({logger:d});let rt=await i.browser.screenshot({clearHighlights:!0,retries:1});p.results.push($),f.push({screenshotBase64AfterCommand:`data:image/jpeg;base64,${rt.toString("base64")}`,urlAfterCommand:i.browser.url(),serializedCommand:gn(q),elementInteracted:$.results[0]?.elementInteracted,thoughts:k});let Ne={substepIndex:y,output:{...$,message:$.message??"Successfully executed preset action."},step:ee,parentStepId:e.id};if(s.onDynamicCommandExecuted?.(Ne),await t.finish({output:Tc.parse($),step:$,message:$.message,attempt:1}),$.status==="FAILED")if(p.status="FAILED",p.message=$.message,S<3)S++,R=`The last attempted action resulted in a Momentic error. A different element may need to be targeted. Error: ${$.message}`;else return p;else if($.status==="CANCELLED")return p.status="CANCELLED",p.message=$.message,p;y++}};import{randomUUID as Xz}from"crypto";import Kye,{multistream as Xye}from"pino";import Qye from"pino-pretty";import{PostHog as RF}from"posthog-node";async function jA(r,e){let t,n=0,o=3,i,a;for(;n<o;)try{let l=await G(r.getAllFlagsAndPayloads(e),{milliseconds:5e3});i=l.featureFlags||{},a=l.featureFlagPayloads||{};break}catch(l){t=l,n++,await new Promise(c=>setTimeout(c,100*n))}if(i&&a)return{flags:i,payloads:a};throw t}var ku=class r extends Us{constructor(t,n,o,i){super(o,i);this.client=t;this.orgId=n}static async init(t){let n=new RF("phc_WRWd8LYIv6rolgDsyCdrPpxtZhsu6qXAkEwPicl44bI",{host:"https://us.i.posthog.com"}),{flags:o,payloads:i}=await jA(n,t);return new r(n,t,o,i)}async refresh(){let{flags:t,payloads:n}=await jA(this.client,this.orgId);this.flags=t,this.payloads=n}};import{randomUUID as wF}from"node:crypto";import{PostHog as CF}from"posthog-node";var Uu=class r{bindings;client;options;constructor(e,t={}){this.bindings=e,this.options=t,this.client=new CF("phc_oy1FexHsc0S3axxOMXCm46yZsW35zROAoV4SOzpDSXH",{host:"https://us.i.posthog.com",...t})}async shutdown(){await this.client.shutdown()}identify(e){return this.bindings={...this.bindings,...e},this}child(e){return new r({...this.bindings,...e},this.options)}track(e,t){if(!LE(this.bindings))return console.error(`Cannot track ${e.type} event without required bindings.`,this.bindings),this;let{type:n,...o}=e;return this.client.capture({distinctId:wF(),event:n,timestamp:t?.timestamp,properties:{...this.bindings,...o}}),this}};import{execSync as xF}from"child_process";import Aa from"os";import _F from"v8";var VA,yn,$A=Aa.platform(),IF=Aa.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),{}),Fu=r=>{try{let e=!1,t=MF(),n=PF(),o=`${Math.round(t.freePercentage*100)}%`;t.freePercentage<.05&&(e=!0);let i=`${n?Math.round(n.idle):"unknown"}%`;n&&n?.total>70&&(e=!0);let a=_F.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"),ii&&T.warn(`Low machine resources detected (memory: ${o} free, cpu: ${i} free)`)):r.debug({memory:t,cpu:n},"Got machine resource usage metrics")}catch{}},WA=r=>{Fu(r),setTimeout(()=>Fu(r),5e3)};function qA(r){if(!cn)return Fu(r),{interval:setInterval(()=>Fu(r),2e4),cpuMetadata:IF,platform:$A}}function MF(){let r=Aa.totalmem(),e=$A==="darwin"?OF():(()=>{let n=Aa.freemem();return{availableMemory:n,rawFreeMemory:n,cachedMemory:0}})(),t=e.availableMemory/r;return{totalMemory:r,freeMemory:e.availableMemory,freePercentage:t}}function PF(){let r=Aa.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,!yn)return yn=t,null;let n={user:t.user-yn.user,nice:t.nice-yn.nice,sys:t.sys-yn.sys,idle:t.idle-yn.idle,irq:t.irq-yn.irq,total:t.total-yn.total};return VA={measurementTime:e,intervalMs:e-yn.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},yn=t,VA}function OF(){try{let r=xF("/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=Aa.freemem();return{availableMemory:e,rawFreeMemory:e,cachedMemory:0}}}var Bu=class{increment(e,t,n){}gauge(e,t){}distribution(e,t,n){}async flush(){}async recordDuration({fn:e}){return await e()}};function LF(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 zu(r,e){let t=LF(r);return!e||Object.keys(e).length===0?t:{...e,...t}}var TR="=",Vu=";",cg=",";var bR=8192;var xa={};JM(xa,{getKeyPairs:()=>pB,parseKeyPairsIntoRecord:()=>mB,parsePairKeyValue:()=>vR,serializeKeyPairs:()=>dB});Ue();var uB=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 dB(r){return r.reduce(function(e,t){var n=""+e+(e!==""?cg:"")+t;return n.length>bR?e:n},"")}function pB(r){return r.getAllEntries().map(function(e){var t=uB(e,2),n=t[0],o=t[1],i=encodeURIComponent(n)+"="+encodeURIComponent(o.value);return o.metadata!==void 0&&(i+=Vu+o.metadata.toString()),i})}function vR(r){var e=r.split(Vu);if(!(e.length<=0)){var t=e.shift();if(t){var n=t.indexOf(TR);if(!(n<=0)){var o=decodeURIComponent(t.substring(0,n).trim()),i=decodeURIComponent(t.substring(n+1).trim()),a;return e.length>0&&(a=Zh(e.join(Vu))),{key:o,value:i,metadata:a}}}}}function mB(r){return typeof r!="string"||r.length===0?{}:r.split(cg).map(function(e){return vR(e)}).filter(function(e){return e!==void 0&&e.value.length>0}).reduce(function(e,t){return e[t.key]=t.value,e},{})}Ue();var $u;(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"})($u||($u={}));var hB=",",gB=["OTEL_SDK_DISABLED"];function fB(r){return gB.indexOf(r)>-1}var SB=["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 yB(r){return SB.indexOf(r)>-1}var EB=["OTEL_NO_PATCH_MODULES","OTEL_PROPAGATORS"];function TB(r){return EB.indexOf(r)>-1}var ug=1/0,dg=128,bB=128,vB=128,pg={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:qe.INFO,OTEL_NO_PATCH_MODULES:[],OTEL_PROPAGATORS:["tracecontext","baggage"],OTEL_RESOURCE_ATTRIBUTES:"",OTEL_SERVICE_NAME:"",OTEL_ATTRIBUTE_VALUE_LENGTH_LIMIT:ug,OTEL_ATTRIBUTE_COUNT_LIMIT:dg,OTEL_SPAN_ATTRIBUTE_VALUE_LENGTH_LIMIT:ug,OTEL_SPAN_ATTRIBUTE_COUNT_LIMIT:dg,OTEL_LOGRECORD_ATTRIBUTE_VALUE_LENGTH_LIMIT:ug,OTEL_LOGRECORD_ATTRIBUTE_COUNT_LIMIT:dg,OTEL_SPAN_EVENT_COUNT_LIMIT:128,OTEL_SPAN_LINK_COUNT_LIMIT:128,OTEL_SPAN_ATTRIBUTE_PER_EVENT_COUNT_LIMIT:bB,OTEL_SPAN_ATTRIBUTE_PER_LINK_COUNT_LIMIT:vB,OTEL_TRACES_EXPORTER:"",OTEL_TRACES_SAMPLER:$u.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 AB(r,e,t){if(!(typeof t[r]>"u")){var n=String(t[r]);e[r]=n.toLowerCase()==="true"}}function RB(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 wB(r,e,t,n){n===void 0&&(n=hB);var o=t[r];typeof o=="string"&&(e[r]=o.split(n).map(function(i){return i.trim()}))}var CB={ALL:qe.ALL,VERBOSE:qe.VERBOSE,DEBUG:qe.DEBUG,INFO:qe.INFO,WARN:qe.WARN,ERROR:qe.ERROR,NONE:qe.NONE};function xB(r,e,t){var n=t[r];if(typeof n=="string"){var o=CB[n.toUpperCase()];o!=null&&(e[r]=o)}}function AR(r){var e={};for(var t in pg){var n=t;switch(n){case"OTEL_LOG_LEVEL":xB(n,e,r);break;default:if(fB(n))AB(n,e,r);else if(yB(n))RB(n,e,r);else if(TB(n))wB(n,e,r);else{var o=r[n];typeof o<"u"&&o!==null&&(e[n]=String(o))}}}return e}function Dt(){var r=AR(process.env);return Object.assign({},pg,r)}function RR(r){return r>=48&&r<=57?r-48:r>=97&&r<=102?r-87:r-55}function Wu(r){for(var e=new Uint8Array(r.length/2),t=0,n=0;n<r.length;n+=2){var o=RR(r.charCodeAt(n)),i=RR(r.charCodeAt(n+1));e[t++]=o<<4|i}return e}var wR="1.25.1";var _B="deployment.environment";var IB="process.runtime.name";var MB="service.name";var PB="service.instance.id";var OB="telemetry.sdk.name",LB="telemetry.sdk.language",NB="telemetry.sdk.version";var CR=_B;var xR=IB;var qu=MB;var _R=PB;var hl=OB,gl=LB,fl=NB;var DB="nodejs";var IR=DB;var _a,Ku=(_a={},_a[hl]="opentelemetry",_a[xR]="node",_a[gl]=IR,_a[fl]=wR,_a);var kB=9,UB=6,FB=Math.pow(10,UB),BB=Math.pow(10,kB);function MR(r){var e=r/1e3,t=Math.trunc(e),n=Math.round(r%1e3*FB);return[t,n]}function PR(r){return r[0]*BB+r[1]}function Sl(r){return r[0]*1e6+r[1]/1e3}var yi;(function(r){r[r.SUCCESS=0]="SUCCESS",r[r.FAILED=1]="FAILED"})(yi||(yi={}));var OR=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 zB=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},HB=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))},LR=function(){function r(e,t){this._callback=e,this._that=t,this._isCalled=!1,this._deferred=new OR}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,HB([this._that],zB(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 Pr;(function(r){r[r.DELTA=0]="DELTA",r[r.CUMULATIVE=1]="CUMULATIVE"})(Pr||(Pr={}));var Kt;(function(r){r[r.HISTOGRAM=0]="HISTOGRAM",r[r.EXPONENTIAL_HISTOGRAM=1]="EXPONENTIAL_HISTOGRAM",r[r.GAUGE=2]="GAUGE",r[r.SUM=3]="SUM"})(Kt||(Kt={}));var GB=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 Dbe=function(r){GB(e,r);function e(t){var n=r.call(this,t)||this;return Object.setPrototypeOf(n,e.prototype),n}return e}(Error);function NR(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}Ue();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 DR=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 me;(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"})(me||(me={}));var jB=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 VB(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 mg=function(){function r(e,t,n,o){n===void 0&&(n=!0),o===void 0&&(o=VB(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=NR(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 hg=function(){function r(e,t){this._boundaries=e,this._recordMinMax=t,this.kind=Or.HISTOGRAM}return r.prototype.createAccumulation=function(e){return new mg(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 mg(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 mg(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:Kt.HISTOGRAM,dataPoints:n.map(function(i){var a=jB(i,2),l=a[0],c=a[1],s=c.toPointValue(),u=e.type===me.GAUGE||e.type===me.UP_DOWN_COUNTER||e.type===me.OBSERVABLE_GAUGE||e.type===me.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}();Ue();var gg=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},fg=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))},Sg=function(){function r(e,t,n,o){e===void 0&&(e=new $B),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 $B=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,fg([n,this._counts.length-t],gg(this._counts.slice(t)),!1)),o.splice.apply(o,fg([0,t],gg(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(fg([],gg(this._counts),!1))},r}();var kR=52,WB=2146435072,qB=1048575,yg=1023,Yu=-yg+1,Xu=yg,yl=Math.pow(2,-1022);function Ju(r){var e=new DataView(new ArrayBuffer(8));e.setFloat64(0,r);var t=e.getUint32(0),n=(t&WB)>>20;return n-yg}function Qu(r){var e=new DataView(new ArrayBuffer(8));e.setFloat64(0,r);var t=e.getUint32(0),n=e.getUint32(4),o=(t&qB)*Math.pow(2,32);return o+n}function El(r,e){return r===0||r===Number.POSITIVE_INFINITY||r===Number.NEGATIVE_INFINITY||Number.isNaN(r)?r:r*Math.pow(2,e)}function FR(r){return r--,r|=r>>1,r|=r>>2,r|=r>>4,r|=r>>8,r|=r>>16,r++,r}var KB=function(){var r=function(e,t){return r=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(n,o){n.__proto__=o}||function(n,o){for(var i in o)Object.prototype.hasOwnProperty.call(o,i)&&(n[i]=o[i])},r(e,t)};return function(e,t){if(typeof t!="function"&&t!==null)throw new TypeError("Class extends value "+String(t)+" is not a constructor or null");r(e,t);function n(){this.constructor=e}e.prototype=t===null?Object.create(t):(n.prototype=t.prototype,new n)}}(),bo=function(r){KB(e,r);function e(){return r!==null&&r.apply(this,arguments)||this}return e}(Error);var zR=function(){function r(e){this._shift=-e}return r.prototype.mapToIndex=function(e){if(e<yl)return this._minNormalLowerBoundaryIndex();var t=Ju(e),n=this._rightShift(Qu(e)-1,kR);return t+n>>this._shift},r.prototype.lowerBoundary=function(e){var t=this._minNormalLowerBoundaryIndex();if(e<t)throw new bo("underflow: "+e+" is < minimum lower boundary: "+t);var n=this._maxNormalLowerBoundaryIndex();if(e>n)throw new bo("overflow: "+e+" is > maximum lower boundary: "+n);return El(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=Yu>>this._shift;return this._shift<2&&e--,e},r.prototype._maxNormalLowerBoundaryIndex=function(){return Xu>>this._shift},r.prototype._rightShift=function(e,t){return Math.floor(e*Math.pow(2,-t))},r}();var HR=function(){function r(e){this._scale=e,this._scaleFactor=El(Math.LOG2E,e),this._inverseFactor=El(Math.LN2,-e)}return r.prototype.mapToIndex=function(e){if(e<=yl)return this._minNormalLowerBoundaryIndex()-1;if(Qu(e)===0){var t=Ju(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 bo("overflow: "+e+" is > maximum lower boundary: "+t)}var n=this._minNormalLowerBoundaryIndex();if(e<=n){if(e===n)return yl;if(e===n-1)return Math.exp((e+(1<<this._scale))/this._scaleFactor)/2;throw new bo("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 Yu<<this._scale},r.prototype._maxNormalLowerBoundaryIndex=function(){return(Xu+1<<this._scale)-1},r}();var GR=-10,jR=20,YB=Array.from({length:31},function(r,e){return e>10?new HR(e-10):new zR(e-10)});function Eg(r){if(r>jR||r<GR)throw new bo("expected scale >= "+GR+" && <= "+jR+", got: "+r);return YB[r+10]}var XB=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},Zu=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}(),JB=20,QB=160,Tg=2,ZB=function(){function r(e,t,n,o,i,a,l,c,s,u,d){e===void 0&&(e=e),t===void 0&&(t=QB),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 Sg),u===void 0&&(u=new Sg),d===void 0&&(d=Eg(JB)),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<Tg&&(V.warn("Exponential Histogram Max Size set to "+this._maxSize+", changing to the minimum size of: "+Tg),this._maxSize=Tg)}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=FR(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=Eg(t)}},r.prototype._minScale=function(e){var t=Math.min(this.scale,e.scale),n=Zu.combine(this._highLowAtScale(this.positive,this.scale,t),this._highLowAtScale(e.positive,e.scale,t)),o=Zu.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 Zu(0,-1);var o=t-n;return new Zu(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 VR=function(){function r(e,t){this._maxSize=e,this._recordMinMax=t,this.kind=Or.EXPONENTIAL_HISTOGRAM}return r.prototype.createAccumulation=function(e){return new ZB(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:Kt.EXPONENTIAL_HISTOGRAM,dataPoints:n.map(function(i){var a=XB(i,2),l=a[0],c=a[1],s=c.toPointValue(),u=e.type===me.GAUGE||e.type===me.UP_DOWN_COUNTER||e.type===me.OBSERVABLE_GAUGE||e.type===me.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 e1=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},bg=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=MR(Date.now())},r.prototype.setStartTime=function(e){this.startTime=e},r.prototype.toPointValue=function(){return this._current},r}();var $R=function(){function r(){this.kind=Or.LAST_VALUE}return r.prototype.createAccumulation=function(e){return new bg(e)},r.prototype.merge=function(e,t){var n=Sl(t.sampleTime)>=Sl(e.sampleTime)?t:e;return new bg(e.startTime,n.toPointValue(),n.sampleTime)},r.prototype.diff=function(e,t){var n=Sl(t.sampleTime)>=Sl(e.sampleTime)?t:e;return new bg(t.startTime,n.toPointValue(),n.sampleTime)},r.prototype.toMetricData=function(e,t,n,o){return{descriptor:e,aggregationTemporality:t,dataPointType:Kt.GAUGE,dataPoints:n.map(function(i){var a=e1(i,2),l=a[0],c=a[1];return{attributes:l,startTime:c.startTime,endTime:o,value:c.toPointValue()}})}},r}();var t1=function(r,e){var t=typeof Symbol=="function"&&r[Symbol.iterator];if(!t)return r;var n=t.call(r),o,i=[],a;try{for(;(e===void 0||e-- >0)&&!(o=n.next()).done;)i.push(o.value)}catch(l){a={error:l}}finally{try{o&&!o.done&&(t=n.return)&&t.call(n)}finally{if(a)throw a.error}}return i},Tl=function(){function r(e,t,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 vg=function(){function r(e){this.monotonic=e,this.kind=Or.SUM}return r.prototype.createAccumulation=function(e){return new Tl(e,this.monotonic)},r.prototype.merge=function(e,t){var n=e.toPointValue(),o=t.toPointValue();return t.reset?new Tl(t.startTime,this.monotonic,o,t.reset):new Tl(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 Tl(t.startTime,this.monotonic,o,!0):new Tl(t.startTime,this.monotonic,o-n)},r.prototype.toMetricData=function(e,t,n,o){return{descriptor:e,aggregationTemporality:t,dataPointType:Kt.SUM,dataPoints:n.map(function(i){var a=t1(i,2),l=a[0],c=a[1];return{attributes:l,startTime:c.startTime,endTime:o,value:c.toPointValue()}}),isMonotonic:this.monotonic}},r}();var Ei=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)}}(),Tn=function(){function r(){}return r.Drop=function(){return ZR},r.Sum=function(){return ew},r.LastValue=function(){return tw},r.Histogram=function(){return rw},r.ExponentialHistogram=function(){return r1},r.Default=function(){return n1},r}();var WR=function(r){Ei(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 DR,e}(Tn);var qR=function(r){Ei(e,r);function e(){return r!==null&&r.apply(this,arguments)||this}return e.prototype.createAggregator=function(t){switch(t.type){case me.COUNTER:case me.OBSERVABLE_COUNTER:case me.HISTOGRAM:return e.MONOTONIC_INSTANCE;default:return e.NON_MONOTONIC_INSTANCE}},e.MONOTONIC_INSTANCE=new vg(!0),e.NON_MONOTONIC_INSTANCE=new vg(!1),e}(Tn);var KR=function(r){Ei(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 $R,e}(Tn);var YR=function(r){Ei(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 hg([0,5,10,25,50,75,100,250,500,750,1e3,2500,5e3,7500,1e4],!0),e}(Tn);var XR=function(r){Ei(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 hg(this._boundaries,this._recordMinMax)},e}(Tn);var JR=function(r){Ei(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 VR(this._maxSize,this._recordMinMax)},e}(Tn);var QR=function(r){Ei(e,r);function e(){return r!==null&&r.apply(this,arguments)||this}return e.prototype._resolve=function(t){switch(t.type){case me.COUNTER:case me.UP_DOWN_COUNTER:case me.OBSERVABLE_COUNTER:case me.OBSERVABLE_UP_DOWN_COUNTER:return ew;case me.GAUGE:case me.OBSERVABLE_GAUGE:return tw;case me.HISTOGRAM:return t.advice.explicitBucketBoundaries?new XR(t.advice.explicitBucketBoundaries):rw}return V.warn("Unable to recognize instrument type: "+t.type),ZR},e.prototype.createAggregator=function(t){return this._resolve(t).createAggregator(t)},e}(Tn);var ZR=new WR,ew=new qR,tw=new KR,rw=new YR,r1=new JR,n1=new QR;Ue();function ed(){return"unknown_service:"+process.argv0}var vo=function(){return vo=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},vo.apply(this,arguments)},o1=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())})},i1=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}}},a1=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},Ag=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 V.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[qu]=ed(),e[gl]=Ku[gl],e[hl]=Ku[hl],e[fl]=Ku[fl],e))},Object.defineProperty(r.prototype,"attributes",{get:function(){var e;return this.asyncAttributesPending&&V.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 o1(this,void 0,void 0,function(){return i1(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=vo(vo({},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=a1(a,2),s=c[0],u=c[1];return vo(vo(vo(vo({},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 Ti;(function(r){r[r.DELTA=0]="DELTA",r[r.CUMULATIVE=1]="CUMULATIVE",r[r.LOWMEMORY=2]="LOWMEMORY"})(Ti||(Ti={}));Ue();var s1=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())})},l1=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}}},Rg=function(){return Pr.CUMULATIVE},nw=function(r){switch(r){case me.COUNTER:case me.OBSERVABLE_COUNTER:case me.GAUGE:case me.HISTOGRAM:case me.OBSERVABLE_GAUGE:return Pr.DELTA;case me.UP_DOWN_COUNTER:case me.OBSERVABLE_UP_DOWN_COUNTER:return Pr.CUMULATIVE}},ow=function(r){switch(r){case me.COUNTER:case me.HISTOGRAM:return Pr.DELTA;case me.GAUGE:case me.UP_DOWN_COUNTER:case me.OBSERVABLE_UP_DOWN_COUNTER:case me.OBSERVABLE_COUNTER:case me.OBSERVABLE_GAUGE:return Pr.CUMULATIVE}};function c1(){var r=Dt(),e=r.OTEL_EXPORTER_OTLP_METRICS_TEMPORALITY_PREFERENCE.trim().toLowerCase();return e==="cumulative"?Rg:e==="delta"?nw:e==="lowmemory"?ow:(V.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."),Rg)}function u1(r){return r!=null?r===Ti.DELTA?nw:r===Ti.LOWMEMORY?ow:Rg:c1()}function d1(r){return r?.aggregationPreference?r.aggregationPreference:function(e){return Tn.Default()}}var iw=function(){function r(e,t){this._otlpExporter=e,this._aggregationSelector=d1(t),this._aggregationTemporalitySelector=u1(t?.temporalityPreference)}return r.prototype.export=function(e,t){this._otlpExporter.export([e],t)},r.prototype.shutdown=function(){return s1(this,void 0,void 0,function(){return l1(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}();Ue();Ue();var p1=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},aw=1e4,sw=5,lw=1e3,cw=5e3,uw=1.5;function bl(r){r===void 0&&(r={});var e={};return Object.entries(r).forEach(function(t){var n=p1(t,2),o=n[0],i=n[1];typeof i<"u"?e[o]=String(i):V.warn('Header "'+o+'" has invalid value ('+i+") and will be ignored")}),e}function wg(r,e){return r.endsWith("/")||(r=r+"/"),r+e}function Cg(r){try{var e=new URL(r);return e.pathname===""&&(e.pathname=e.pathname+"/"),e.toString()}catch{return V.warn("Could not parse export URL: '"+r+"'"),r}}function xg(r){return typeof r=="number"?r<=0?_g(r,aw):r:m1()}function m1(){var r,e=Number((r=Dt().OTEL_EXPORTER_OTLP_TRACES_TIMEOUT)!==null&&r!==void 0?r:Dt().OTEL_EXPORTER_OTLP_TIMEOUT);return e<=0?_g(e,aw):e}function _g(r,e){return V.warn("Timeout must be greater than 0",r),e}function dw(r){var e=[429,502,503,504];return e.includes(r)}function pw(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 mw=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 LR(this._shutdown,this),this._concurrencyLimit=typeof e.concurrencyLimit=="number"?e.concurrencyLimit:30,this.timeoutMillis=xg(e.timeoutMillis),this.onInit(e)}return r.prototype.export=function(e,t){if(this._shutdownOnce.isCalled){t({code:yi.FAILED,error:new Error("Exporter has been shutdown")});return}if(this._sendingPromises.length>=this._concurrencyLimit){t({code:yi.FAILED,error:new Error("Concurrent export limit reached")});return}this._export(e).then(function(){t({code:yi.SUCCESS})}).catch(function(n){t({code:yi.FAILED,error:n})})},r.prototype._export=function(e){var t=this;return new Promise(function(n,o){try{V.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 V.debug("shutdown started"),this.onShutdown(),this.forceFlush()},r}();Ue();import*as Ig from"url";import*as rd from"http";import*as nd from"https";import*as hw from"zlib";import{Readable as g1}from"stream";var Ao;(function(r){r.NONE="none",r.GZIP="gzip"})(Ao||(Ao={}));var h1=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)}}(),Ia=function(r){h1(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 td=function(){return td=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},td.apply(this,arguments)};function Mg(r,e,t,n,o){var i=r.timeoutMillis,a=new Ig.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 g=new Ia("Request Timeout");o(g)}else l>=14?s.destroy():s.abort()},i),p={hostname:a.hostname,port:a.port,path:a.pathname,method:"POST",headers:td({"Content-Type":t},r.headers),agent:r.agent},m=a.protocol==="http:"?rd.request:nd.request,h=function(g,f){switch(g===void 0&&(g=sw),f===void 0&&(f=lw),s=m(p,function(S){var E="";S.on("data",function(R){return E+=R}),S.on("aborted",function(){if(u){var R=new Ia("Request Timeout");o(R)}}),S.on("end",function(){if(u===!1)if(S.statusCode&&S.statusCode<299)V.debug("statusCode: "+S.statusCode,E),n(),clearTimeout(d),clearTimeout(c);else if(S.statusCode&&dw(S.statusCode)&&g>0){var R=void 0;f=uw*f,S.headers["retry-after"]?R=pw(S.headers["retry-after"]):R=Math.round(Math.random()*(cw-f)+f),c=setTimeout(function(){h(g-1,f)},R)}else{var A=new Ia(S.statusMessage,S.statusCode,E);o(A),clearTimeout(d),clearTimeout(c)}})}),s.on("error",function(S){if(u){var E=new Ia("Request Timeout",S.code);o(E)}else o(S);clearTimeout(d),clearTimeout(c)}),s.on("abort",function(){if(u){var S=new Ia("Request Timeout");o(S)}clearTimeout(d),clearTimeout(c)}),r.compression){case Ao.GZIP:{s.setHeader("Content-Encoding","gzip");var y=f1(e);y.on("error",o).pipe(hw.createGzip()).on("error",o).pipe(s);break}default:s.end(Buffer.from(e));break}};h()}function f1(r){var e=new g1;return e.push(r),e.push(null),e}function Pg(r){if(r.httpAgentOptions&&r.keepAlive===!1){V.warn("httpAgentOptions is used only when keepAlive is true");return}if(!(r.keepAlive===!1||!r.url))try{var e=new Ig.URL(r.url),t=e.protocol==="http:"?rd.Agent:nd.Agent;return new t(td({keepAlive:!0},r.httpAgentOptions))}catch(n){V.error("collector exporter failed to create http agent. err: "+n.message);return}}function Og(r){if(r)return r;var e=Dt().OTEL_EXPORTER_OTLP_TRACES_COMPRESSION||Dt().OTEL_EXPORTER_OTLP_COMPRESSION;return e===Ao.GZIP?Ao.GZIP:Ao.NONE}Ue();var S1=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)}}(),od=function(r){S1(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&&V.warn("Metadata cannot be set when using http"),i.headers=Object.assign(i.DEFAULT_HEADERS,bl(t.headers),xa.parseKeyPairsIntoRecord(Dt().OTEL_EXPORTER_OTLP_HEADERS)),i.agent=Pg(t),i.compression=Og(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){V.debug("Shutdown already started. Cannot send objects");return}var a=new Promise(function(c,s){var u;Mg(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}(mw);function fw(r){var e=BigInt(1e9);return BigInt(r[0])*e+BigInt(r[1])}function y1(r){var e=Number(BigInt.asUintN(32,r)),t=Number(BigInt.asUintN(32,r>>BigInt(32)));return{low:e,high:t}}function Sw(r){var e=fw(r);return y1(e)}function E1(r){var e=fw(r);return e.toString()}var T1=typeof BigInt<"u"?E1:PR;function gw(r){return r}function yw(r){if(r!==void 0)return Wu(r)}var b1={encodeHrTime:Sw,encodeSpanContext:Wu,encodeOptionalSpanContext:yw};function Ew(r){var e,t;if(r===void 0)return b1;var n=(e=r.useLongBits)!==null&&e!==void 0?e:!0,o=(t=r.useHex)!==null&&t!==void 0?t:!1;return{encodeHrTime:n?Sw:T1,encodeSpanContext:o?gw:Wu,encodeOptionalSpanContext:o?gw:yw}}var v1=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 Tw(r){return{name:r.name,version:r.version}}function Ma(r){return Object.keys(r).map(function(e){return bw(e,r[e])})}function bw(r,e){return{key:r,value:vw(e)}}function vw(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(vw)}}:e==="object"&&r!=null?{kvlistValue:{values:Object.entries(r).map(function(t){var n=v1(t,2),o=n[0],i=n[1];return bw(o,i)})}}:{}}function Aw(r){return{attributes:Ma(r.attributes),droppedAttributesCount:0}}Ue();function ww(r,e){var t=Ew(e);return{resource:Aw(r.resource),schemaUrl:void 0,scopeMetrics:A1(r.scopeMetrics,t)}}function A1(r,e){return Array.from(r.map(function(t){return{scope:Tw(t.scope),metrics:t.metrics.map(function(n){return R1(n,e)}),schemaUrl:t.scope.schemaUrl}}))}function R1(r,e){var t={name:r.descriptor.name,description:r.descriptor.description,unit:r.descriptor.unit},n=_1(r.aggregationTemporality);switch(r.dataPointType){case Kt.SUM:t.sum={aggregationTemporality:n,isMonotonic:r.isMonotonic,dataPoints:Rw(r,e)};break;case Kt.GAUGE:t.gauge={dataPoints:Rw(r,e)};break;case Kt.HISTOGRAM:t.histogram={aggregationTemporality:n,dataPoints:C1(r,e)};break;case Kt.EXPONENTIAL_HISTOGRAM:t.exponentialHistogram={aggregationTemporality:n,dataPoints:x1(r,e)};break}return t}function w1(r,e,t){var n={attributes:Ma(r.attributes),startTimeUnixNano:t.encodeHrTime(r.startTime),timeUnixNano:t.encodeHrTime(r.endTime)};switch(e){case Sr.INT:n.asInt=r.value;break;case Sr.DOUBLE:n.asDouble=r.value;break}return n}function Rw(r,e){return r.dataPoints.map(function(t){return w1(t,r.descriptor.valueType,e)})}function C1(r,e){return r.dataPoints.map(function(t){var n=t.value;return{attributes:Ma(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 x1(r,e){return r.dataPoints.map(function(t){var n=t.value;return{attributes:Ma(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 _1(r){switch(r){case Pr.DELTA:return 1;case Pr.CUMULATIVE:return 2}}function Cw(r,e){return{resourceMetrics:r.map(function(t){return ww(t,e)})}}var Lg={serializeRequest:function(r){var e=Cw(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 xw="0.52.1";var _w=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)}}(),Pa=function(){return Pa=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},Pa.apply(this,arguments)},Iw="v1/metrics",I1="http://localhost:4318/"+Iw,M1={"User-Agent":"OTel-OTLP-Exporter-JavaScript/"+xw},P1=function(r){_w(e,r);function e(t){var n=r.call(this,t,Lg,"application/json")||this;return n.headers=Pa(Pa(Pa(Pa({},n.headers),M1),xa.parseKeyPairsIntoRecord(Dt().OTEL_EXPORTER_OTLP_METRICS_HEADERS)),bl(t?.headers)),n}return e.prototype.getDefaultUrl=function(t){return typeof t.url=="string"?t.url:Dt().OTEL_EXPORTER_OTLP_METRICS_ENDPOINT.length>0?Cg(Dt().OTEL_EXPORTER_OTLP_METRICS_ENDPOINT):Dt().OTEL_EXPORTER_OTLP_ENDPOINT.length>0?wg(Dt().OTEL_EXPORTER_OTLP_ENDPOINT,Iw):I1},e}(od),Mw=function(r){_w(e,r);function e(t){return r.call(this,new P1(t),t)||this}return e}(iw);var Oa;(function(r){r[r.DELTA=0]="DELTA",r[r.CUMULATIVE=1]="CUMULATIVE"})(Oa||(Oa={}));var bn;(function(r){r[r.HISTOGRAM=0]="HISTOGRAM",r[r.EXPONENTIAL_HISTOGRAM=1]="EXPONENTIAL_HISTOGRAM",r[r.GAUGE=2]="GAUGE",r[r.SUM=3]="SUM"})(bn||(bn={}));Ue();var O1=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)}}(),Pw=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())})},Ow=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}}},L1=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},N1=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))},D1=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 Lw(r){return r!=null}function id(r){var e=Object.keys(r);return e.length===0?"":(e=e.sort(),JSON.stringify(e.map(function(t){return[t,r[t]]})))}function Nw(r){var e,t;return r.name+":"+((e=r.version)!==null&&e!==void 0?e:"")+":"+((t=r.schemaUrl)!==null&&t!==void 0?t:"")}var Ng=function(r){O1(e,r);function e(t){var n=r.call(this,t)||this;return Object.setPrototypeOf(n,e.prototype),n}return e}(Error);function Ro(r,e){var t,n=new Promise(function(i,a){t=setTimeout(function(){a(new Ng("Operation timed out."))},e)});return Promise.race([r,n]).then(function(o){return clearTimeout(t),o},function(o){throw clearTimeout(t),o})}function Dw(r){return Pw(this,void 0,void 0,function(){var e=this;return Ow(this,function(t){return[2,Promise.all(r.map(function(n){return Pw(e,void 0,void 0,function(){var o,i;return Ow(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 kw(r){return r.status==="rejected"}function Dg(r,e){var t=[];return r.forEach(function(n){t.push.apply(t,N1([],L1(e(n)),!1))}),t}function Uw(r,e){var t,n;if(r.size!==e.size)return!1;try{for(var o=D1(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 Fw(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 Bw(r,e){return r.toLowerCase()===e.toLowerCase()}Ue();var Lr;(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"})(Lr||(Lr={}));var kg=function(){function r(){this.kind=Lr.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}();Ue();var Te;(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"})(Te||(Te={}));function vn(r,e,t){var n,o,i,a;return U1(r)||V.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:Sr.DOUBLE,advice:(a=t?.advice)!==null&&a!==void 0?a:{}}}function zw(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 Hw(r,e){return Bw(r.name,e.name)&&r.unit===e.unit&&r.type===e.type&&r.valueType===e.valueType}var k1=/^[a-z][a-z0-9_.\-/]{0,254}$/i;function U1(r){return r.match(k1)!=null}var F1=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 B1(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 ad=function(){function r(e,t,n,o){n===void 0&&(n=!0),o===void 0&&(o=B1(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=Fw(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 sd=function(){function r(e,t){this._boundaries=e,this._recordMinMax=t,this.kind=Lr.HISTOGRAM}return r.prototype.createAccumulation=function(e){return new ad(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 ad(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 ad(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:bn.HISTOGRAM,dataPoints:n.map(function(i){var a=F1(i,2),l=a[0],c=a[1],s=c.toPointValue(),u=e.type===Te.GAUGE||e.type===Te.UP_DOWN_COUNTER||e.type===Te.OBSERVABLE_GAUGE||e.type===Te.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}();Ue();var Ug=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},Fg=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))},Bg=function(){function r(e,t,n,o){e===void 0&&(e=new z1),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 z1=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,Fg([n,this._counts.length-t],Ug(this._counts.slice(t)),!1)),o.splice.apply(o,Fg([0,t],Ug(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(Fg([],Ug(this._counts),!1))},r}();var Gw=52,H1=2146435072,G1=1048575,zg=1023,ld=-zg+1,cd=zg,vl=Math.pow(2,-1022);function ud(r){var e=new DataView(new ArrayBuffer(8));e.setFloat64(0,r);var t=e.getUint32(0),n=(t&H1)>>20;return n-zg}function dd(r){var e=new DataView(new ArrayBuffer(8));e.setFloat64(0,r);var t=e.getUint32(0),n=e.getUint32(4),o=(t&G1)*Math.pow(2,32);return o+n}function Al(r,e){return r===0||r===Number.POSITIVE_INFINITY||r===Number.NEGATIVE_INFINITY||Number.isNaN(r)?r:r*Math.pow(2,e)}function Vw(r){return r--,r|=r>>1,r|=r>>2,r|=r>>4,r|=r>>8,r|=r>>16,r++,r}var j1=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)}}(),wo=function(r){j1(e,r);function e(){return r!==null&&r.apply(this,arguments)||this}return e}(Error);var Ww=function(){function r(e){this._shift=-e}return r.prototype.mapToIndex=function(e){if(e<vl)return this._minNormalLowerBoundaryIndex();var t=ud(e),n=this._rightShift(dd(e)-1,Gw);return t+n>>this._shift},r.prototype.lowerBoundary=function(e){var t=this._minNormalLowerBoundaryIndex();if(e<t)throw new wo("underflow: "+e+" is < minimum lower boundary: "+t);var n=this._maxNormalLowerBoundaryIndex();if(e>n)throw new wo("overflow: "+e+" is > maximum lower boundary: "+n);return Al(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=ld>>this._shift;return this._shift<2&&e--,e},r.prototype._maxNormalLowerBoundaryIndex=function(){return cd>>this._shift},r.prototype._rightShift=function(e,t){return Math.floor(e*Math.pow(2,-t))},r}();var qw=function(){function r(e){this._scale=e,this._scaleFactor=Al(Math.LOG2E,e),this._inverseFactor=Al(Math.LN2,-e)}return r.prototype.mapToIndex=function(e){if(e<=vl)return this._minNormalLowerBoundaryIndex()-1;if(dd(e)===0){var t=ud(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 wo("overflow: "+e+" is > maximum lower boundary: "+t)}var n=this._minNormalLowerBoundaryIndex();if(e<=n){if(e===n)return vl;if(e===n-1)return Math.exp((e+(1<<this._scale))/this._scaleFactor)/2;throw new wo("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 ld<<this._scale},r.prototype._maxNormalLowerBoundaryIndex=function(){return(cd+1<<this._scale)-1},r}();var Kw=-10,Yw=20,V1=Array.from({length:31},function(r,e){return e>10?new qw(e-10):new Ww(e-10)});function Hg(r){if(r>Yw||r<Kw)throw new wo("expected scale >= "+Kw+" && <= "+Yw+", got: "+r);return V1[r+10]}var $1=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},pd=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}(),W1=20,q1=160,Gg=2,Xw=function(){function r(e,t,n,o,i,a,l,c,s,u,d){e===void 0&&(e=e),t===void 0&&(t=q1),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 Bg),u===void 0&&(u=new Bg),d===void 0&&(d=Hg(W1)),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<Gg&&(V.warn("Exponential Histogram Max Size set to "+this._maxSize+", changing to the minimum size of: "+Gg),this._maxSize=Gg)}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=Vw(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=Hg(t)}},r.prototype._minScale=function(e){var t=Math.min(this.scale,e.scale),n=pd.combine(this._highLowAtScale(this.positive,this.scale,t),this._highLowAtScale(e.positive,e.scale,t)),o=pd.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 pd(0,-1);var o=t-n;return new pd(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 jg=function(){function r(e,t){this._maxSize=e,this._recordMinMax=t,this.kind=Lr.EXPONENTIAL_HISTOGRAM}return r.prototype.createAccumulation=function(e){return new Xw(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:bn.EXPONENTIAL_HISTOGRAM,dataPoints:n.map(function(i){var a=$1(i,2),l=a[0],c=a[1],s=c.toPointValue(),u=e.type===Te.GAUGE||e.type===Te.UP_DOWN_COUNTER||e.type===Te.OBSERVABLE_GAUGE||e.type===Te.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}();Ue();var K1=eg("OpenTelemetry SDK Context Key SUPPRESS_TRACING");function Jw(r){return r.setValue(K1,!0)}Ue();function Qw(){return function(r){V.error(Y1(r))}}function Y1(r){return typeof r=="string"?r:JSON.stringify(X1(r))}function X1(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 J1=Qw();function md(r){try{J1(r)}catch{}}var Zw="1.30.1";var Q1="process.runtime.name";var Z1="service.name";var ez="telemetry.sdk.name",tz="telemetry.sdk.language",rz="telemetry.sdk.version";var eC=Q1;var tC=Z1;var Rl=ez,wl=tz,Cl=rz;var nz="nodejs";var rC=nz;var La,bi=(La={},La[Rl]="opentelemetry",La[eC]="node",La[wl]=rC,La[Cl]=Zw,La);function xl(r){r.unref()}var uz=9,dz=6,pz=Math.pow(10,dz),BRe=Math.pow(10,uz);function vi(r){var e=r/1e3,t=Math.trunc(e),n=Math.round(r%1e3*pz);return[t,n]}function Na(r){return r[0]*1e6+r[1]/1e3}var _l;(function(r){r[r.SUCCESS=0]="SUCCESS",r[r.FAILED=1]="FAILED"})(_l||(_l={}));Ue();function nC(r,e){return new Promise(function(t){Ca.with(Jw(Ca.active()),function(){r.export(e,function(n){t(n)})})})}var oC={_export:nC};var mz=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},hd=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=vi(Date.now())},r.prototype.setStartTime=function(e){this.startTime=e},r.prototype.toPointValue=function(){return this._current},r}();var Vg=function(){function r(){this.kind=Lr.LAST_VALUE}return r.prototype.createAccumulation=function(e){return new hd(e)},r.prototype.merge=function(e,t){var n=Na(t.sampleTime)>=Na(e.sampleTime)?t:e;return new hd(e.startTime,n.toPointValue(),n.sampleTime)},r.prototype.diff=function(e,t){var n=Na(t.sampleTime)>=Na(e.sampleTime)?t:e;return new hd(t.startTime,n.toPointValue(),n.sampleTime)},r.prototype.toMetricData=function(e,t,n,o){return{descriptor:e,aggregationTemporality:t,dataPointType:bn.GAUGE,dataPoints:n.map(function(i){var a=mz(i,2),l=a[0],c=a[1];return{attributes:l,startTime:c.startTime,endTime:o,value:c.toPointValue()}})}},r}();var hz=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},Da=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 gd=function(){function r(e){this.monotonic=e,this.kind=Lr.SUM}return r.prototype.createAccumulation=function(e){return new Da(e,this.monotonic)},r.prototype.merge=function(e,t){var n=e.toPointValue(),o=t.toPointValue();return t.reset?new Da(t.startTime,this.monotonic,o,t.reset):new Da(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 Da(t.startTime,this.monotonic,o,!0):new Da(t.startTime,this.monotonic,o-n)},r.prototype.toMetricData=function(e,t,n,o){return{descriptor:e,aggregationTemporality:t,dataPointType:bn.SUM,dataPoints:n.map(function(i){var a=hz(i,2),l=a[0],c=a[1];return{attributes:l,startTime:c.startTime,endTime:o,value:c.toPointValue()}}),isMonotonic:this.monotonic}},r}();var Ai=function(){var r=function(e,t){return r=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(n,o){n.__proto__=o}||function(n,o){for(var i in o)Object.prototype.hasOwnProperty.call(o,i)&&(n[i]=o[i])},r(e,t)};return function(e,t){if(typeof t!="function"&&t!==null)throw new TypeError("Class extends value "+String(t)+" is not a constructor or null");r(e,t);function n(){this.constructor=e}e.prototype=t===null?Object.create(t):(n.prototype=t.prototype,new n)}}(),Nr=function(){function r(){}return r.Drop=function(){return dC},r.Sum=function(){return pC},r.LastValue=function(){return mC},r.Histogram=function(){return hC},r.ExponentialHistogram=function(){return gz},r.Default=function(){return fz},r}();var iC=function(r){Ai(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 kg,e}(Nr);var aC=function(r){Ai(e,r);function e(){return r!==null&&r.apply(this,arguments)||this}return e.prototype.createAggregator=function(t){switch(t.type){case Te.COUNTER:case Te.OBSERVABLE_COUNTER:case Te.HISTOGRAM:return e.MONOTONIC_INSTANCE;default:return e.NON_MONOTONIC_INSTANCE}},e.MONOTONIC_INSTANCE=new gd(!0),e.NON_MONOTONIC_INSTANCE=new gd(!1),e}(Nr);var sC=function(r){Ai(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 Vg,e}(Nr);var lC=function(r){Ai(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 sd([0,5,10,25,50,75,100,250,500,750,1e3,2500,5e3,7500,1e4],!0),e}(Nr);var Il=function(r){Ai(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 sd(this._boundaries,this._recordMinMax)},e}(Nr);var cC=function(r){Ai(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 jg(this._maxSize,this._recordMinMax)},e}(Nr);var uC=function(r){Ai(e,r);function e(){return r!==null&&r.apply(this,arguments)||this}return e.prototype._resolve=function(t){switch(t.type){case Te.COUNTER:case Te.UP_DOWN_COUNTER:case Te.OBSERVABLE_COUNTER:case Te.OBSERVABLE_UP_DOWN_COUNTER:return pC;case Te.GAUGE:case Te.OBSERVABLE_GAUGE:return mC;case Te.HISTOGRAM:return t.advice.explicitBucketBoundaries?new Il(t.advice.explicitBucketBoundaries):hC}return V.warn("Unable to recognize instrument type: "+t.type),dC},e.prototype.createAggregator=function(t){return this._resolve(t).createAggregator(t)},e}(Nr);var dC=new iC,pC=new aC,mC=new sC,hC=new lC,gz=new cC,fz=new uC;var gC=function(r){return Nr.Default()},fC=function(r){return Oa.CUMULATIVE};var $g=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())})},Wg=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}}},SC=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},Sz=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))},yC=function(){function r(e){var t,n,o;this._shutdown=!1,this._aggregationSelector=(t=e?.aggregationSelector)!==null&&t!==void 0?t:gC,this._aggregationTemporalitySelector=(n=e?.aggregationTemporalitySelector)!==null&&n!==void 0?n:fC,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 $g(this,void 0,void 0,function(){var t,n,o,i,a,l;return Wg(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(Sz([this._sdkMetricProducer.collect({timeoutMillis:e?.timeoutMillis})],SC(this._metricProducers.map(function(s){return s.collect({timeoutMillis:e?.timeoutMillis})})),!1))];case 1:return t=SC.apply(void 0,[c.sent()]),n=t[0],o=t.slice(1),i=n.errors.concat(Dg(o,function(s){return s.errors})),a=n.resourceMetrics.resource,l=n.resourceMetrics.scopeMetrics.concat(Dg(o,function(s){return s.resourceMetrics.scopeMetrics})),[2,{resourceMetrics:{resource:a,scopeMetrics:l},errors:i}]}})})},r.prototype.shutdown=function(e){return $g(this,void 0,void 0,function(){return Wg(this,function(t){switch(t.label){case 0:return this._shutdown?(V.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,Ro(this.onShutdown(),e.timeoutMillis)];case 3:t.sent(),t.label=4;case 4:return this._shutdown=!0,[2]}})})},r.prototype.forceFlush=function(e){return $g(this,void 0,void 0,function(){return Wg(this,function(t){switch(t.label){case 0:return this._shutdown?(V.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,Ro(this.onForceFlush(),e.timeoutMillis)];case 3:return t.sent(),[2]}})})},r}();Ue();var yz=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)}}(),fd=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())})},Sd=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}}},Ez=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},Tz=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))},qg=function(r){yz(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 fd(this,void 0,void 0,function(){var t;return Sd(this,function(n){switch(n.label){case 0:return n.trys.push([0,2,,3]),[4,Ro(this._doRun(),this._exportTimeout)];case 1:return n.sent(),[3,3];case 2:return t=n.sent(),t instanceof Ng?(V.error("Export took longer than %s milliseconds and timed out.",this._exportTimeout),[2]):(md(t),[3,3]);case 3:return[2]}})})},e.prototype._doRun=function(){var t,n;return fd(this,void 0,void 0,function(){var o,i,a,l,c,s;return Sd(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=V).error.apply(s,Tz(["PeriodicExportingMetricReader: metrics collection errors"],Ez(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(),V.debug("Error while resolving async portion of resource: ",l),md(l),[3,5];case 5:return i.scopeMetrics.length===0?[2]:[4,oC._export(this._exporter,i)];case 6:if(c=u.sent(),c.code!==_l.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),xl(this._interval)},e.prototype.onForceFlush=function(){return fd(this,void 0,void 0,function(){return Sd(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 fd(this,void 0,void 0,function(){return Sd(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}(yC);Ue();Ue();function yd(){return"unknown_service:"+process.argv0}var Co=function(){return Co=Object.assign||function(r){for(var e,t=1,n=arguments.length;t<n;t++){e=arguments[t];for(var o in e)Object.prototype.hasOwnProperty.call(e,o)&&(r[o]=e[o])}return r},Co.apply(this,arguments)},bz=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())})},vz=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}}},Az=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},Ed=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 V.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[tC]=yd(),e[wl]=bi[wl],e[Rl]=bi[Rl],e[Cl]=bi[Cl],e))},Object.defineProperty(r.prototype,"attributes",{get:function(){var e;return this.asyncAttributesPending&&V.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 bz(this,void 0,void 0,function(){return vz(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=Co(Co({},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=Az(a,2),s=c[0],u=c[1];return Co(Co(Co(Co({},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 EC=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}();Ue();var Ri=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)}}(),Td=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=Ca.active()),typeof e!="number"){V.warn("non-number value provided to metric "+this._descriptor.name+": "+e);return}this._descriptor.valueType===Sr.INT&&!Number.isInteger(e)&&(V.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,vi(Date.now()))},r}();var TC=function(r){Ri(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}(Td);var bC=function(r){Ri(e,r);function e(){return r!==null&&r.apply(this,arguments)||this}return e.prototype.add=function(t,n,o){if(t<0){V.warn("negative value provided to counter "+this._descriptor.name+": "+t);return}this._record(t,n,o)},e}(Td);var vC=function(r){Ri(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}(Td);var AC=function(r){Ri(e,r);function e(){return r!==null&&r.apply(this,arguments)||this}return e.prototype.record=function(t,n,o){if(t<0){V.warn("negative value provided to histogram "+this._descriptor.name+": "+t);return}this._record(t,n,o)},e}(Td);var bd=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 RC=function(r){Ri(e,r);function e(){return r!==null&&r.apply(this,arguments)||this}return e}(bd);var wC=function(r){Ri(e,r);function e(){return r!==null&&r.apply(this,arguments)||this}return e}(bd);var CC=function(r){Ri(e,r);function e(){return r!==null&&r.apply(this,arguments)||this}return e}(bd);function Ml(r){return r instanceof bd}var xC=function(){function r(e){this._meterSharedState=e}return r.prototype.createGauge=function(e,t){var n=vn(e,Te.GAUGE,t),o=this._meterSharedState.registerMetricStorage(n);return new vC(o,n)},r.prototype.createHistogram=function(e,t){var n=vn(e,Te.HISTOGRAM,t),o=this._meterSharedState.registerMetricStorage(n);return new AC(o,n)},r.prototype.createCounter=function(e,t){var n=vn(e,Te.COUNTER,t),o=this._meterSharedState.registerMetricStorage(n);return new bC(o,n)},r.prototype.createUpDownCounter=function(e,t){var n=vn(e,Te.UP_DOWN_COUNTER,t),o=this._meterSharedState.registerMetricStorage(n);return new TC(o,n)},r.prototype.createObservableGauge=function(e,t){var n=vn(e,Te.OBSERVABLE_GAUGE,t),o=this._meterSharedState.registerAsyncMetricStorage(n);return new wC(n,o,this._meterSharedState.observableRegistry)},r.prototype.createObservableCounter=function(e,t){var n=vn(e,Te.OBSERVABLE_COUNTER,t),o=this._meterSharedState.registerAsyncMetricStorage(n);return new RC(n,o,this._meterSharedState.observableRegistry)},r.prototype.createObservableUpDownCounter=function(e,t){var n=vn(e,Te.OBSERVABLE_UP_DOWN_COUNTER,t),o=this._meterSharedState.registerAsyncMetricStorage(n);return new CC(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 vd=function(){function r(e){this._instrumentDescriptor=e}return r.prototype.getInstrumentDescriptor=function(){return this._instrumentDescriptor},r.prototype.updateDescription=function(e){this._instrumentDescriptor=vn(this._instrumentDescriptor.name,this._instrumentDescriptor.type,{description:e,valueType:this._instrumentDescriptor.valueType,unit:this._instrumentDescriptor.unit,advice:this._instrumentDescriptor.advice})},r}();var Rz=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)}}(),_C=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}}},wz=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 _C(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 _C(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 Jr=function(r){Rz(e,r);function e(){return r.call(this,id)||this}return e}(wz);var Cz=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},Ad=function(){function r(e,t){this._aggregator=e,this._activeCollectionStorage=new Jr,this._cumulativeMemoStorage=new Jr,this._overflowAttributes={"otel.metric.overflow":!0},this._cardinalityLimit=(t??2e3)-1,this._overflowHashCode=id(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=Cz(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 Jr,e},r}();var Kg=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.")},IC=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},Rd=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===Oa.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=xz(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=Kg(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 Jr,i=this._unreportedAccumulations.get(e);if(this._unreportedAccumulations.set(e,[]),i===void 0)return o;try{for(var a=Kg(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=IC(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=Kg(e.keys()),l=a.next();!l.done;l=a.next()){var c=IC(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 xz(r){return Array.from(r.entries())}var _z=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)}}(),Iz=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},MC=function(r){_z(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 Ad(n,l._aggregationCardinalityLimit),l._temporalMetricStorage=new Rd(n,i),l}return e.prototype.record=function(t,n){var o=this,i=new Jr;Array.from(t.entries()).forEach(function(a){var l=Iz(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}(vd);Ue();function Yg(r,e){var t="";return r.unit!==e.unit&&(t+=" - Unit '"+r.unit+"' does not match '"+e.unit+`'
|
|
49
49
|
`),r.type!==e.type&&(t+=" - Type '"+r.type+"' does not match '"+e.type+`'
|
|
50
50
|
`),r.valueType!==e.valueType&&(t+=" - Value Type '"+r.valueType+"' does not match '"+e.valueType+`'
|
|
51
51
|
`),r.description!==e.description&&(t+=" - Description '"+r.description+"' does not match '"+e.description+`'
|
|
@@ -57,7 +57,7 @@ ${C.feedback}`,p.status="FAILED",s.onDynamicAIActionStatusUpdateEvent?.({parentS
|
|
|
57
57
|
To resolve the conflict:`,Xg(s,e))),i=c):V.warn("A view or instrument with the name ",e.name,` has already been registered and is incompatible with another registered view.
|
|
58
58
|
`,`Details:
|
|
59
59
|
`,Yg(s,e),`To resolve the conflict:
|
|
60
|
-
`,Xg(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 OC=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}();Ue();Ue();var LC=function(){function r(e,t){this._instrumentName=e,this._valueType=t,this._buffer=new Jr}return r.prototype.observe=function(e,t){if(t===void 0&&(t={}),typeof e!="number"){V.warn("non-number value provided to metric "+this._instrumentName+": "+e);return}this._valueType===Sr.INT&&!Number.isInteger(e)&&(V.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 NC=function(){function r(){this._buffer=new Map}return r.prototype.observe=function(e,t,n){if(n===void 0&&(n={}),!!Ml(e)){var o=this._buffer.get(e);if(o==null&&(o=new Jr,this._buffer.set(e,o)),typeof t!="number"){V.warn("non-number value provided to metric "+e._descriptor.name+": "+t);return}e._descriptor.valueType===Sr.INT&&!Number.isInteger(t)&&(V.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 Qg=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())})},Zg=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}}},DC=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},kC=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))},UC=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(Ml));if(n.size===0){V.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(Ml)),o=this._findBatchCallback(e,n);o<0||this._batchCallbacks.splice(o,1)},r.prototype.observe=function(e,t){return Qg(this,void 0,void 0,function(){var n,o,i,a;return Zg(this,function(l){switch(l.label){case 0:return n=this._observeCallbacks(e,t),o=this._observeBatchCallbacks(e,t),[4,Dw(kC(kC([],DC(n),!1),DC(o),!1))];case 1:return i=l.sent(),a=i.filter(kw).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 Qg(n,void 0,void 0,function(){var l,c;return Zg(this,function(s){switch(s.label){case 0:return l=new LC(a._descriptor.name,a._descriptor.valueType),c=Promise.resolve(i(l)),t!=null&&(c=Ro(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 Qg(n,void 0,void 0,function(){var l,c;return Zg(this,function(s){switch(s.label){case 0:return l=new NC,c=Promise.resolve(i(l)),t!=null&&(c=Ro(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&&Uw(n.instruments,t)})},r}();var Nz=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)}}(),FC=function(r){Nz(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 Ad(n,l._aggregationCardinalityLimit),l._temporalMetricStorage=new Rd(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}(vd);var BC=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)}}(),ka=function(){function r(){}return r.Noop=function(){return kz},r}();var Dz=function(r){BC(e,r);function e(){return r!==null&&r.apply(this,arguments)||this}return e.prototype.process=function(t,n){return t},e}(ka);var zC=function(r){BC(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}(ka);var kz=new Dz;var Uz=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())})},Fz=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}}},Bz=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},HC=function(){function r(e,t){this._meterProviderSharedState=e,this._instrumentationScope=t,this.metricStorageRegistry=new PC,this.observableRegistry=new UC,this.meter=new xC(this)}return r.prototype.registerMetricStorage=function(e){var t=this._registerMetricStorage(e,FC);return t.length===1?t[0]:new OC(t)},r.prototype.registerAsyncMetricStorage=function(e){var t=this._registerMetricStorage(e,MC);return t},r.prototype.collect=function(e,t,n){return Uz(this,void 0,void 0,function(){var o,i,a;return Fz(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(Lw),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=zw(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=Bz(c,2),u=s[0],d=s[1],p=n.metricStorageRegistry.findOrUpdateCompatibleCollectorStorage(u,e);if(p!=null)return p;var m=d.createAggregator(e),h=u.selectCardinalityLimit(e.type),g=new t(e,m,ka.Noop(),[u],h);return n.metricStorageRegistry.registerForCollector(u,g),g});i=i.concat(l)}return i},r}();var zz=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.")},GC=function(){function r(e){this.resource=e,this.viewRegistry=new EC,this.metricCollectors=[],this.meterSharedStates=new Map}return r.prototype.getMeterSharedState=function(e){var t=Nw(e),n=this.meterSharedStates.get(t);return n==null&&(n=new HC(this,e),this.meterSharedStates.set(t,n)),n},r.prototype.selectAggregations=function(e){var t,n,o=[];try{for(var i=zz(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 wd=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())})},Cd=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}}},Hz=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},Gz=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))},jC=function(){function r(e,t){this._sharedState=e,this._metricReader=t}return r.prototype.collect=function(e){return wd(this,void 0,void 0,function(){var t,n,o,i,a=this;return Cd(this,function(l){switch(l.label){case 0:return t=vi(Date.now()),n=[],o=[],i=Array.from(this._sharedState.meterSharedStates.values()).map(function(c){return wd(a,void 0,void 0,function(){var s;return Cd(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,Gz([],Hz(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 wd(this,void 0,void 0,function(){return Cd(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 wd(this,void 0,void 0,function(){return Cd(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 VC=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())})},$C=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}}},WC=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 jz(r,e){var t=e??Ed.empty();return r?Ed.default().merge(t):t}var ef=function(){function r(e){var t,n,o,i,a;if(this._shutdown=!1,this._sharedState=new GC(jz((a=e?.mergeResourceWithDefaults)!==null&&a!==void 0?a:!0,e?.resource)),e?.views!=null&&e.views.length>0)try{for(var l=WC(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=WC(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?(V.warn("A shutdown MeterProvider cannot provide a Meter"),ig()):this._sharedState.getMeterSharedState({name:e,version:t,schemaUrl:n.schemaUrl}).meter},r.prototype.addMetricReader=function(e){var t=new jC(this._sharedState,e);e.setMetricProducer(t),this._sharedState.metricCollectors.push(t)},r.prototype.shutdown=function(e){return VC(this,void 0,void 0,function(){return $C(this,function(t){switch(t.label){case 0:return this._shutdown?(V.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 VC(this,void 0,void 0,function(){return $C(this,function(t){switch(t.label){case 0:return this._shutdown?(V.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 Vz=/[\^$\\.+?()[\]{}|]/g,xd=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(Vz,"\\$&").replace("*",".*")+"$"},r.hasWildcard=function(e){return e.includes("*")},r}();var Ua=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 qC=function(){function r(e){var t;this._nameFilter=new xd((t=e?.name)!==null&&t!==void 0?t:"*"),this._type=e?.type,this._unitFilter=new Ua(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 KC=function(){function r(e){this._nameFilter=new Ua(e?.name),this._versionFilter=new Ua(e?.version),this._schemaUrlFilter=new Ua(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 $z(r){return r.instrumentName==null&&r.instrumentType==null&&r.instrumentUnit==null&&r.meterName==null&&r.meterVersion==null&&r.meterSchemaUrl==null}var _d=function(){function r(e){var t;if($z(e))throw new Error("Cannot create view with no selector arguments supplied");if(e.name!=null&&(e?.instrumentName==null||xd.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 zC(e.attributeKeys):this.attributesProcessor=ka.Noop(),this.name=e.name,this.description=e.description,this.aggregation=(t=e.aggregation)!==null&&t!==void 0?t:Nr.Default(),this.instrumentSelector=new qC({name:e.instrumentName,type:e.instrumentType,unit:e.instrumentUnit}),this.meterSelector=new KC({name:e.meterName,version:e.meterVersion,schemaUrl:e.meterSchemaUrl}),this.aggregationCardinalityLimit=e.aggregationCardinalityLimit}return r}();var Txe=process.env.APP||"unknown";Ue();import{v4 as Wz}from"uuid";function qz(){return new Mw({url:"https://us-west.metrics.momentic.ai/v1/metrics",headers:{"x-momentic-metrics-api-key":"c60c6a0f-60da-41a7-a61b-07969a0aa303"},temporalityPreference:Ti.DELTA})}var Kz=[new _d({instrumentName:"test_event_duration",instrumentType:Te.HISTOGRAM,aggregation:new Il([100,500,1e3,5e3,7500,1e4,15e3,2e4])}),new _d({instrumentName:"test_step_duration",instrumentType:Te.HISTOGRAM,aggregation:new Il([100,500,1e3,5e3,7500,1e4,15e3,2e4])})],Id=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 Ag({[qu]:e.serviceName,[CR]:t,[_R]:typeof process<"u"&&process.env.SERVICE_INSTANCE_ID?process.env.SERVICE_INSTANCE_ID:Wz()}),o=qz(),i=new qg({exporter:o,exportIntervalMillis:e.exportIntervalMs??15e3});this.provider=new ef({resource:n,readers:[i],views:Kz}),ju.setGlobalMeterProvider(this.provider),this.meter=ju.getMeter("momentic-serverless")}increment(e,t,n){try{let o=zu(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=zu(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 or=new Bu;function YC(r){r.disabled||(or=new Id(r))}var Jz=3;async function XC(r){let{logger:e}=r.fixtures,{results:t}=r.failureRecoveryParams,n=t[t.length-1],o=Zz(r.work,n);if(o)return e.info({failedResult:n,isNotEligible:o},"Skipping failure recovery because of ineligible failure"),{type:"NOT_ELIGIBLE",message:`The failed step is not eligible for failure recovery: ${o}`};e.info({failedResult:n},"Attempting failure recovery"),r.work.state.failureRecoveryAttempts=(r.work.state.failureRecoveryAttempts??0)+1;try{return await Qz(r)}catch(i){return e.warn({err:i},"Error during failure recovery attempt, continuing..."),null}}async function Qz(r){let{fixtures:e,work:t,failureRecoveryParams:n}=r,{controller:o,logger:i}=e,{testMetadata:a}=r.inputs,{results:l,failedStep:c,nextSteps:s,tracer:u}=n;if(!l.length)throw new Error("Attempted failure recovery with no failed results");await Promise.allSettled(t.asyncTasks??[]);let d=o.browser.url(),p=`data:image/jpeg;base64,${(await o.browser.screenshot({})).toString("base64")}`,m=(await o.browser.getBrowserState({})).serialize(),{results:h}=await ca(i,u,l,{numStepsWithScreenshots:8,addIndices:!0,includeBeforeScreenshots:!1}),g=s.map(I=>So(I)),f=a?.description?.trim(),S=a?.advanced?.failureRecoveryInstructions?.trim(),{scenario:y,thoughts:E,instructions:R}=await o.getFailureRecoveryPlan({currentUrl:d,currentScreenshot:p,failedResults:h,currentPageState:m,nextStepsSerialized:g,testDescription:f||void 0,customInstructions:S||void 0});if(y!=="RECOVERABLE")return i.info({scenario:y,thoughts:E,instructions:R},"Failure recovery is not applicable"),{type:"NOT_ELIGIBLE",message:`Momentic's failure recovery agent determined that this failure is not eligible for recovery: ${E}`};if(!R)throw new Error("Momentic's failure recovery agent did not provide any instructions for recovery");let A={id:Xz(),type:"AI_ACTION_DYNAMIC",text:R},C=await va(r.work,()=>r.executeStepList({...r,fixtures:{...r.fixtures},listParams:{steps:[A,c],containerName:"AI-recovered step list",tracer:u}})),w=C.results[0];if(w&&w.type==="AI_ACTION_DYNAMIC")if(ou({results:C.results,onPresetAction:I=>{I.aiSuggested=!0},onSimpleStepContainer:I=>{I.aiSuggested=!0}}),C.status==="SUCCESS"){let I=`The following steps were automatically executed by the failure recovery agent. Analysis: ${E}`;return w.message=I,or.increment("test_event",1,["name:failure_recovery_success",`orgId:${r.inputs.orgId}`]),i.info({thoughts:E},"Failure recovery succeeded"),{type:"ATTEMPTED",status:"SUCCESS",result:C,message:I}}else{let I=`The following steps were unsuccessfully attempted by the failure recovery agent. Analysis: ${E}`;return w.message=I,i.info({thoughts:E,aiActionResult:w},"Failure recovery failed"),{type:"ATTEMPTED",status:"FAILED",result:C,message:I}}return null}function Zz(r,e){if(!e)return"There is no failed result";if(e.type!=="PRESET_ACTION")return"The failed step is not a preset action";let t=e.message;return t?t.includes("AbortError:")?"The user aborted the test":Oy.some(n=>t.includes(n))?"The failed step is an irrecoverable configuration error":(r.state.failureRecoveryAttempts??0)>Jz?"Too many failure recovery attempts":"":"There is no error message available on the failed step"}import{randomUUID as Md}from"crypto";import eH from"fast-json-patch";import{cloneDeep as tH}from"lodash-es";async function JC(r){let e=r.failedResults,t=[],{sectionParams:n,fixtures:o,work:i,startingUrl:a,startingContextSnapshot:l,tracer:c}=r,{step:s}=n,{controller:u,logger:d}=o,p=s?.autohealingConfig,m=p?.restartBehavior??{type:"GO_TO_SECTION_START"},h=p?.attempts??1;for(let g=0;g<h;g++){if(!e.terminalResult?.message)throw new Error("No error message in terminal result");let f=tH(s.steps);await Promise.allSettled(i.asyncTasks??[]);let{results:S}=await ca(d,c,e.results,{numStepsWithScreenshots:4}),y=await u.runSectionAutohealing({results:S,errorMessage:e.terminalResult?.message,goal:s.description});f=eH.applyPatch(f,y.patches).newDocument;let E=ar.fromSnapshot({snapshot:l,environmentVariables:o.context.getVariablesFromEnvironmentCopy()});await rH({logger:d,controller:u,tracer:c,context:E,restartConfig:m,startingUrl:a});let R=await va(r.work,()=>r.executeStepList({...r,fixtures:{...r.fixtures,context:E},listParams:{steps:f,containerName:"auto-healed step list",tracer:c}}));if(t.push(R.results),R.status==="SUCCESS")return{successfulHealing:{proposedStep:{...s,steps:f},listResult:R,context:E},healingAttempts:t};e=R}return{healingAttempts:t}}async function rH({logger:r,controller:e,tracer:t,restartConfig:n,context:o,startingUrl:i}){switch(n.type){case"NAVIGATE_URL":{let a={id:Md(),type:"PRESET_ACTION",command:{id:Md(),type:"NAVIGATE",url:n.url}},l=await t.startStep({logger:r,step:a,attempt:1});await e.executePresetCommand(null,l,a.command,o,!1);break}case"GO_TO_SECTION_START":{let a={id:Md(),type:"PRESET_ACTION",command:{id:Md(),type:"NAVIGATE",url:i}},l=await t.startStep({logger:r,step:a,attempt:1});await e.executePresetCommand(null,l,a.command,o,!1);break}}}function QC(r,e){switch(r||(r="ON_FAILURE"),r){case"ALWAYS":return!0;case"ON_FAILURE":return!0;case"ON_ACTION_FAILURE":return!(!e||e.type==="PRESET_ACTION"&&XS(e.command.type))}}async function ZC(r){let{step:e,tracer:t}=r.sectionParams,{logger:n,controller:o,context:i}=r.fixtures,a=new Date,l=o.browser.url(),c=i.toObjectCopy(),s=await t.startSubSteps(),u=async()=>r.executeStepList({...r,listParams:{steps:e.steps,containerName:"section step list",tracer:s}}),d=e.autohealingConfig?await va(r.work,u):await u(),p,m;if(d.status==="FAILED"&&e.autohealingConfig&&!r.work.state.autoHealingDisabled&&QC(e.autohealingConfig.trigger,d.terminalResult)){let g=await t.startSubSteps(),f=await JC({...r,startingContextSnapshot:c,startingUrl:l,failedResults:d,tracer:g});f.successfulHealing&&(p=f.successfulHealing.proposedStep,d=f.successfulHealing.listResult,r.fixtures.context=f.successfulHealing.context),m=f.healingAttempts}let h={...e,...d,startedAt:a,finishedAt:new Date,proposedStep:p,healingAttempts:m};return Sn({asyncTasks:r.work.asyncTasks,nestedResults:d.results,result:h,logger:n}),h}var oH=60*60*1e3;async function Qr(r){let{results:e=[],containerName:t,steps:n,tracer:o}=r.listParams,{logger:i}=r.fixtures,a=o.getParentStepIdChain(),{fromStep:l,toStep:c}=r.inputs,s=r.work,u="SUCCESS",d,p=0;for(p;p<n.length;p++){let m=n[p];if(m.skipped)continue;if(s.fastForwardingToStep&&l){let E=JSON.stringify(a);if(m.id===l.fromStepId&&E===JSON.stringify(l.parentStepIdChain))s.fastForwardingToStep=!1;else if(!Wb(m,a,l.fromStepId,l.parentStepIdChain))continue}let h=So(m),g=0,f=1,S=Date.now();"retries"in m&&m.retries&&m.retries>0&&(f+=m.retries);let y;for(;g<f&&Date.now()-S<oH;){g++,i.info({step:m,currentAttempt:g},`Executing step ${p+1}/${n.length} in ${t}: ${h}`);let E=Date.now(),{stepResult:R,status:A,failureRecoveryResults:C,shouldStopExecuting:w}=await iH({attempt:g,params:r,step:m,i:p,steps:n,results:e,currentParentIdChain:a,work:s,fromStep:l,toStep:c,lastRetry:g===f});if(A==="FAILED"&&g<f){y=[...y??[],R],Date.now()-E<1e3&&await ie(1e3-(Date.now()-E));continue}else e.push(R),y&&(R.previousAttempts=y);if(C&&e.push(...C),w)return u=A,d=R,{status:u,results:e,terminalResult:d};break}}return{status:u,results:e,terminalResult:d}}async function iH({attempt:r,params:e,step:t,i:n,steps:o,results:i,currentParentIdChain:a,work:l,fromStep:c,toStep:s,lastRetry:u}){let{tracer:d}=e.listParams,{logger:p,context:m,controller:h,codeEvalTools:g,usageTracker:f}=e.fixtures,{orgId:S}=e.inputs,y=new Date,E=await d.startStep({logger:p,step:t,attempt:r}),R=nH(t),A=m.toRedactedDisplayCopy(),C=h.browser.url(),w=h.executeAbortController.signal;f.trackStepExecution(t);let I,P;switch(t.type){case"PRESET_ACTION":{I="Preset action",P=await fi(t,async()=>await Du({...e,presetParams:{tracer:E,step:t}}),w);break}case"AI_ACTION":{I="AI action",P=await fi(t,()=>zA({...e,aiStepParams:{step:t,tracer:E},executeStepList:Qr}),w);break}case"AI_ACTION_DYNAMIC":{I="AI action",P=await fi(t,()=>GA({...e,aiStepParams:{step:t,tracer:E},executeStepList:Qr}),w);break}case"RESOLVED_MODULE":{I=`Module (${t.name})`,P=await fi(t,async()=>{let z=await kA({orgId:S,step:t,context:m,logger:p,codeEvalTools:g,signal:w});return Xh({...e,executeStepList:Qr,moduleParams:{step:t,resolvedInputs:z,tracer:E}})},w);break}case"CONDITIONAL":{I="Conditional step",P=await fi(t,()=>FA({...e,conditionalParams:{step:t,tracer:E},executeStepList:Qr}),w);break}case"SECTION":{I="Section",P=await fi(t,()=>ZC({...e,sectionParams:{step:t,tracer:E},executeStepList:Qr}),w);break}default:return(j=>{throw"If Typescript complains about the line below, you missed a case or break in the switch above"})(t)}P.beforeUrl=P.beforeUrl??C,P.beforeTestContext=A,t.envKey&&m.setVariable(t.envKey,P.data);let X=h.browser.url();m.setCurrentUrl(X),P.afterUrl=P.afterUrl??X,P.afterTestContext=m.toRedactedDisplayCopy(),await aH({step:t,startedAt:y,stepTypeName:I,result:P,callbacks:e.callbacks,globalWorkRef:e.work,tracer:E,attempt:r});let q,k;if(u&&P.status==="FAILED"&&!l.state.failureRecoveryDisabled&&c?.fromStepId===void 0&&s?.toStepId===void 0){let z=await XC({...e,executeStepList:Qr,failureRecoveryParams:{failedStep:R,nextSteps:o.slice(n+1),results:i.concat(P),tracer:d}});z&&(z.type==="ATTEMPTED"?(q=z.result.results,k=z.status):z.type==="NOT_ELIGIBLE"&&(P.message=P.message?`${P.message} ${z.message}`:z.message),P.type==="PRESET_ACTION"&&(P.failureRecoveryStatus={type:z.type,message:z.message}))}return l.fastForwardingToStep&&c&&(c.fromStepId===t.id&&JSON.stringify(a)===JSON.stringify(c.parentStepIdChain)&&(l.fastForwardingToStep=!1),t.type==="RESOLVED_MODULE"&&Eh(a,c.parentStepIdChain)&&(l.fastForwardingToStep=!1)),P.status!=="SUCCESS"&&k!=="SUCCESS"||h.closed?{shouldStopExecuting:!0,status:P.status,stepResult:P,failureRecoveryResults:q}:s&&t.id===s.toStepId&&JSON.stringify(a)===JSON.stringify(s.parentStepIdChain)?(h.setClosed(),{shouldStopExecuting:!0,status:"SUCCESS",stepResult:P,failureRecoveryResults:q}):{shouldStopExecuting:!1,status:"SUCCESS",stepResult:P,failureRecoveryResults:q}}async function aH({stepTypeName:r,step:e,result:t,tracer:n,attempt:o,startedAt:i}){let a=r.toLowerCase(),l=r.charAt(0).toUpperCase()+r.slice(1);n.recordStepDuration({step:e,durationMs:Date.now()-i.getTime()});let c="";switch(t.status){case"SUCCESS":c=t.message??`${l} executed successfully.`;break;case"FAILED":c=t.message??`${l} failed.`;break;case"CANCELLED":c=t.message??`${l} cancelled.`;break;default:throw new Error(`Unexpected ${a} status: ${t.status}`)}await n.finish({step:t,message:c,output:Tc.parse(t),attempt:o})}async function ex({codePath:r,screenshotBuff:e,storage:t,logger:n}){if(e)try{let o=await t.uploadScreenshot(e);return n.info({screenshotUrl:o,codePath:r},"Saved screenshot for debugging"),o}catch(o){n.error({err:o,codePath:r},"Failed to save screenshot for debugging")}}async function An({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 sH=["NAVIGATE","NEW_TAB","TAB","REFRESH","WAIT_FOR_URL"];async function tx({beforeUrl:r,beforePages:e,browser:t,command:n,logger:o}){if(sH.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 ie(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(di(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 xo(r,e={}){let t=await r.getBrowserState(e);return{serializedTree:t.serialize(e.serializationOpts),tree:t}}var rx="MOMENTIC_RUN_ID",nx="FINAL_SCREENSHOT_URL";import{randomUUID as ox}from"crypto";async function ix({browser:r,signal:e}){let t=new Date;try{return await r.navigate({url:r.baseUrl,initialNavigation:!0}),{status:"PASSED",results:[]}}catch(n){let o={id:ox(),type:"PRESET_ACTION",status:e.aborted||n.name==="AbortError"?"CANCELLED":"FAILED",failureReason:"UserInfrastructureError",message:n.message,startedAt:t,finishedAt:new Date,results:[],command:{id:ox(),type:"NAVIGATE",url:r.baseUrl}};return{status:e.aborted||n.name==="AbortError"?"CANCELLED":"FAILED",results:[],failedStepResult:o}}}var Pd=async r=>{let{orgId:e,runId:t,testMetadata:n,steps:o,beforeSteps:i,afterSteps:a}=r.inputs;r.fixtures.logger=r.fixtures.logger.child({orgId:e,runId:t,testId:n?.id});let{logger:l,controller:c}=r.fixtures,{onTestComplete:s,onTestSuccess:u,onTestFailure:d}=r.callbacks.test,p=qA(l);if(r.options.reinitializeBrowser){let h=await ix({browser:c.browser,signal:c.executeAbortController.signal});if(h.status!=="PASSED")return await s?.(),clearInterval(p?.interval),h}let m;try{return l.info({platform:p?.platform,cpuMetadata:p?.cpuMetadata,labels:n?.labels,orgSettings:_T.parse(r.inputs.orgSettings)},`Starting run for Momentic test '${n?.name??"Unnamed test"}'`),m=await cH(r),m}finally{l.info({status:m?.status,labels:n?.labels},"Momentic test final result"),clearInterval(p?.interval),await s?.(),m?.status==="PASSED"?await u?.({steps:o,beforeSteps:i,afterSteps:a}):m?.status==="FAILED"&&await d?.({steps:o,beforeSteps:i,afterSteps:a})}};function lH({beforeStatus:r,mainStatus:e,afterStatus:t}){return r==="FAILED"?"FAILED":r==="CANCELLED"?"CANCELLED":t==="FAILED"?"FAILED":t==="CANCELLED"?"CANCELLED":e==="FAILED"?"FAILED":e==="CANCELLED"?"CANCELLED":"PASSED"}var cH=async r=>{let{tracer:e}=r.testParams,{fromStep:t,toStep:n,steps:o,beforeSteps:i,afterSteps:a}=r.inputs,{logger:l,controller:c,context:s,storage:u}=r.fixtures,{collectDebugData:d,disableHealing:p}=r.options;s.setCurrentUrl(c.browser.url());let m="test",h=o,g=[],f=p||t!==void 0||n!==void 0||void 0,S={results:g,state:{autoHealingDisabled:f,failureRecoveryDisabled:f,failureRecoveryAttempts:0},asyncTasks:[]},y=!1;t?.fromStepId&&t.fromStepId===n?.toStepId?(m="filtered step",S.fastForwardingToStep=!0):t?.fromStepId?(m="partial steps list from step",S.fastForwardingToStep=!0):n?m="partial steps list until step":(m="entire test",y=!0);let E,R,A;if(y&&i&&i.length>0){let k=await ax(i,"beforeSteps",r);E=k.status,R=k.results,A=k.terminalResult?{...k.terminalResult,failureReason:"SetupFailureError"}:void 0}let C,w;if(E===void 0||E==="PASSED"){l.info({fromStep:t,toStep:n},`Starting execution of ${m}`);let k=await e.startMainStepList(),ee=await Qr({...r,work:S,listParams:{steps:h,containerName:m,results:g,tracer:k}});C=ee.status,w=ee.terminalResult}let I,P,X;if(y&&a&&a.length>0){let k=await ax(a,"afterSteps",r);I=k.status,P=k.results,X=k.terminalResult?{...k.terminalResult,failureReason:"TeardownFailureError"}:void 0}let q=lH({beforeStatus:E,mainStatus:C,afterStatus:I});if(d&&uH({tracer:e,work:S,controller:c,storage:u,context:s,logger:l,status:q}),await Promise.allSettled(S.asyncTasks),S.asyncTasks.push(Promise.resolve(r.callbacks.test.onSaveFinalRunResults?.({results:g,beforeResults:R,afterResults:P}))),q==="FAILED"){let k=E==="FAILED"?A:void 0,ee=I==="FAILED"?X:void 0;return{status:"FAILED",results:g,beforeResults:R,afterResults:P,failedStepResult:k??w??ee}}else if(q==="CANCELLED")return{status:"CANCELLED",results:g,beforeResults:R,afterResults:P};return{status:"PASSED",failureRecoveryDetails:S.state.failureRecoveryAttempts?{attempts:S.state.failureRecoveryAttempts}:void 0,results:g,beforeResults:R,afterResults:P}};async function ax(r,e,t){let n=t.fixtures.logger,o=e==="beforeSteps"?await t.testParams.tracer.startBeforeStepList():await t.testParams.tracer.startAfterStepList();n.info(`Starting step execution for ${e}`);let i={results:[],asyncTasks:[],state:{}},a={...t.callbacks,test:{...t.callbacks.test,onSaveFinalRunResults:void 0,onUpdateRun:void 0,onTestComplete:void 0,onTestSuccess:void 0}},{status:l,results:c,terminalResult:s}=await Qr({...t,work:i,callbacks:a,listParams:{steps:r,containerName:e,tracer:o}});await Promise.allSettled(i.asyncTasks);let u;return l==="SUCCESS"?u="PASSED":l==="CANCELLED"?u="CANCELLED":u="FAILED",{status:u,results:c,terminalResult:s}}function uH({tracer:r,work:e,controller:t,storage:n,logger:o,context:i,status:a}){let l=t.browser,c=l.retrieveAndClearDebugData(),s=Qb(c.logsPerPage),u=Hm(c.harPages||{},c.harEntries||{});r.attachConsoleLogs({logger:o,logs:s}),r.attachNetworkLogs({logger:o,logs:u}),a!=="PASSED"&&a!=="SUCCESS"&&(r.attachBrowserCrashDump({crashReportDirFetcher:()=>l.browserCrashDumpDir,logger:o}),e.asyncTasks.push((async()=>{try{let d=await l.screenshot({quality:75}),p=await ex({codePath:"test-complete-final",storage:n,screenshotBuff:d,logger:o}),m=await G(l.html(),{milliseconds:2e3});i.setVariable(nx,p),o.debug({finalPageHtml:m},"Final page state HTML"),o.debug({finalScreenshotUrl:p},"Uploaded final screenshot URL")}catch{}})()))}async function Od({settings:r,customHeaders:e,envVariables:t,envName:n,testName:o,baseUrl:i,logger:a,localTools:l,orgId:c}){let s=Ac.parse(r);e&&(s.extraHeaders={...s.extraHeaders,...e});let u=new ar({baseUrl:i,envName:n,testName:o,variablesFromEnvironment:t,currentUrl:i});await Pu({obj:s,context:u,bannedKeys:[],allowList:lE,localTools:l,logger:a,orgId:c});try{return Ac.parse(s)}catch(d){throw new x("UserConfigurationError",`The templated browser settings configured by the user are invalid: ${d.message}`)}}import{cloneDeep as Cj}from"lodash-es";var tf={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
|
|
60
|
+
`,Xg(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 OC=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}();Ue();Ue();var LC=function(){function r(e,t){this._instrumentName=e,this._valueType=t,this._buffer=new Jr}return r.prototype.observe=function(e,t){if(t===void 0&&(t={}),typeof e!="number"){V.warn("non-number value provided to metric "+this._instrumentName+": "+e);return}this._valueType===Sr.INT&&!Number.isInteger(e)&&(V.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 NC=function(){function r(){this._buffer=new Map}return r.prototype.observe=function(e,t,n){if(n===void 0&&(n={}),!!Ml(e)){var o=this._buffer.get(e);if(o==null&&(o=new Jr,this._buffer.set(e,o)),typeof t!="number"){V.warn("non-number value provided to metric "+e._descriptor.name+": "+t);return}e._descriptor.valueType===Sr.INT&&!Number.isInteger(t)&&(V.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 Qg=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())})},Zg=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}}},DC=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},kC=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))},UC=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(Ml));if(n.size===0){V.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(Ml)),o=this._findBatchCallback(e,n);o<0||this._batchCallbacks.splice(o,1)},r.prototype.observe=function(e,t){return Qg(this,void 0,void 0,function(){var n,o,i,a;return Zg(this,function(l){switch(l.label){case 0:return n=this._observeCallbacks(e,t),o=this._observeBatchCallbacks(e,t),[4,Dw(kC(kC([],DC(n),!1),DC(o),!1))];case 1:return i=l.sent(),a=i.filter(kw).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 Qg(n,void 0,void 0,function(){var l,c;return Zg(this,function(s){switch(s.label){case 0:return l=new LC(a._descriptor.name,a._descriptor.valueType),c=Promise.resolve(i(l)),t!=null&&(c=Ro(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 Qg(n,void 0,void 0,function(){var l,c;return Zg(this,function(s){switch(s.label){case 0:return l=new NC,c=Promise.resolve(i(l)),t!=null&&(c=Ro(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&&Uw(n.instruments,t)})},r}();var Nz=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)}}(),FC=function(r){Nz(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 Ad(n,l._aggregationCardinalityLimit),l._temporalMetricStorage=new Rd(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}(vd);var BC=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)}}(),ka=function(){function r(){}return r.Noop=function(){return kz},r}();var Dz=function(r){BC(e,r);function e(){return r!==null&&r.apply(this,arguments)||this}return e.prototype.process=function(t,n){return t},e}(ka);var zC=function(r){BC(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}(ka);var kz=new Dz;var Uz=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())})},Fz=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}}},Bz=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},HC=function(){function r(e,t){this._meterProviderSharedState=e,this._instrumentationScope=t,this.metricStorageRegistry=new PC,this.observableRegistry=new UC,this.meter=new xC(this)}return r.prototype.registerMetricStorage=function(e){var t=this._registerMetricStorage(e,FC);return t.length===1?t[0]:new OC(t)},r.prototype.registerAsyncMetricStorage=function(e){var t=this._registerMetricStorage(e,MC);return t},r.prototype.collect=function(e,t,n){return Uz(this,void 0,void 0,function(){var o,i,a;return Fz(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(Lw),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=zw(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=Bz(c,2),u=s[0],d=s[1],p=n.metricStorageRegistry.findOrUpdateCompatibleCollectorStorage(u,e);if(p!=null)return p;var m=d.createAggregator(e),h=u.selectCardinalityLimit(e.type),g=new t(e,m,ka.Noop(),[u],h);return n.metricStorageRegistry.registerForCollector(u,g),g});i=i.concat(l)}return i},r}();var zz=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.")},GC=function(){function r(e){this.resource=e,this.viewRegistry=new EC,this.metricCollectors=[],this.meterSharedStates=new Map}return r.prototype.getMeterSharedState=function(e){var t=Nw(e),n=this.meterSharedStates.get(t);return n==null&&(n=new HC(this,e),this.meterSharedStates.set(t,n)),n},r.prototype.selectAggregations=function(e){var t,n,o=[];try{for(var i=zz(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 wd=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())})},Cd=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}}},Hz=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},Gz=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))},jC=function(){function r(e,t){this._sharedState=e,this._metricReader=t}return r.prototype.collect=function(e){return wd(this,void 0,void 0,function(){var t,n,o,i,a=this;return Cd(this,function(l){switch(l.label){case 0:return t=vi(Date.now()),n=[],o=[],i=Array.from(this._sharedState.meterSharedStates.values()).map(function(c){return wd(a,void 0,void 0,function(){var s;return Cd(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,Gz([],Hz(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 wd(this,void 0,void 0,function(){return Cd(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 wd(this,void 0,void 0,function(){return Cd(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 VC=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())})},$C=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}}},WC=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 jz(r,e){var t=e??Ed.empty();return r?Ed.default().merge(t):t}var ef=function(){function r(e){var t,n,o,i,a;if(this._shutdown=!1,this._sharedState=new GC(jz((a=e?.mergeResourceWithDefaults)!==null&&a!==void 0?a:!0,e?.resource)),e?.views!=null&&e.views.length>0)try{for(var l=WC(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=WC(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?(V.warn("A shutdown MeterProvider cannot provide a Meter"),ig()):this._sharedState.getMeterSharedState({name:e,version:t,schemaUrl:n.schemaUrl}).meter},r.prototype.addMetricReader=function(e){var t=new jC(this._sharedState,e);e.setMetricProducer(t),this._sharedState.metricCollectors.push(t)},r.prototype.shutdown=function(e){return VC(this,void 0,void 0,function(){return $C(this,function(t){switch(t.label){case 0:return this._shutdown?(V.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 VC(this,void 0,void 0,function(){return $C(this,function(t){switch(t.label){case 0:return this._shutdown?(V.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 Vz=/[\^$\\.+?()[\]{}|]/g,xd=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(Vz,"\\$&").replace("*",".*")+"$"},r.hasWildcard=function(e){return e.includes("*")},r}();var Ua=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 qC=function(){function r(e){var t;this._nameFilter=new xd((t=e?.name)!==null&&t!==void 0?t:"*"),this._type=e?.type,this._unitFilter=new Ua(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 KC=function(){function r(e){this._nameFilter=new Ua(e?.name),this._versionFilter=new Ua(e?.version),this._schemaUrlFilter=new Ua(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 $z(r){return r.instrumentName==null&&r.instrumentType==null&&r.instrumentUnit==null&&r.meterName==null&&r.meterVersion==null&&r.meterSchemaUrl==null}var _d=function(){function r(e){var t;if($z(e))throw new Error("Cannot create view with no selector arguments supplied");if(e.name!=null&&(e?.instrumentName==null||xd.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 zC(e.attributeKeys):this.attributesProcessor=ka.Noop(),this.name=e.name,this.description=e.description,this.aggregation=(t=e.aggregation)!==null&&t!==void 0?t:Nr.Default(),this.instrumentSelector=new qC({name:e.instrumentName,type:e.instrumentType,unit:e.instrumentUnit}),this.meterSelector=new KC({name:e.meterName,version:e.meterVersion,schemaUrl:e.meterSchemaUrl}),this.aggregationCardinalityLimit=e.aggregationCardinalityLimit}return r}();var Txe=process.env.APP||"unknown";Ue();import{v4 as Wz}from"uuid";function qz(){return new Mw({url:"https://us-west.metrics.momentic.ai/v1/metrics",headers:{"x-momentic-metrics-api-key":"c60c6a0f-60da-41a7-a61b-07969a0aa303"},temporalityPreference:Ti.DELTA})}var Kz=[new _d({instrumentName:"test_event_duration",instrumentType:Te.HISTOGRAM,aggregation:new Il([100,500,1e3,5e3,7500,1e4,15e3,2e4])}),new _d({instrumentName:"test_step_duration",instrumentType:Te.HISTOGRAM,aggregation:new Il([100,500,1e3,5e3,7500,1e4,15e3,2e4])})],Id=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 Ag({[qu]:e.serviceName,[CR]:t,[_R]:typeof process<"u"&&process.env.SERVICE_INSTANCE_ID?process.env.SERVICE_INSTANCE_ID:Wz()}),o=qz(),i=new qg({exporter:o,exportIntervalMillis:e.exportIntervalMs??15e3});this.provider=new ef({resource:n,readers:[i],views:Kz}),ju.setGlobalMeterProvider(this.provider),this.meter=ju.getMeter("momentic-serverless")}increment(e,t,n){try{let o=zu(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=zu(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 or=new Bu;function YC(r){r.disabled||(or=new Id(r))}var Jz=3;async function XC(r){let{logger:e}=r.fixtures,{results:t}=r.failureRecoveryParams,n=t[t.length-1],o=Zz(r.work,n);if(o)return e.info({failedResult:n,isNotEligible:o},"Skipping failure recovery because of ineligible failure"),{type:"NOT_ELIGIBLE",message:`The failed step is not eligible for failure recovery: ${o}`};e.info({failedResult:n},"Attempting failure recovery"),r.work.state.failureRecoveryAttempts=(r.work.state.failureRecoveryAttempts??0)+1;try{return await Qz(r)}catch(i){return e.warn({err:i},"Error during failure recovery attempt, continuing..."),null}}async function Qz(r){let{fixtures:e,work:t,failureRecoveryParams:n}=r,{controller:o,logger:i}=e,{testMetadata:a}=r.inputs,{results:l,failedStep:c,nextSteps:s,tracer:u}=n;if(!l.length)throw new Error("Attempted failure recovery with no failed results");await Promise.allSettled(t.asyncTasks??[]);let d=o.browser.url(),p=`data:image/jpeg;base64,${(await o.browser.screenshot({})).toString("base64")}`,m=(await o.browser.getBrowserState({})).serialize(),{results:h}=await ca(i,u,l,{numStepsWithScreenshots:8,addIndices:!0,includeBeforeScreenshots:!1}),g=s.map(I=>So(I)),f=a?.description?.trim(),y=a?.advanced?.failureRecoveryInstructions?.trim(),{scenario:S,thoughts:E,instructions:R}=await o.getFailureRecoveryPlan({currentUrl:d,currentScreenshot:p,failedResults:h,currentPageState:m,nextStepsSerialized:g,testDescription:f||void 0,customInstructions:y||void 0});if(S!=="RECOVERABLE")return i.info({scenario:S,thoughts:E,instructions:R},"Failure recovery is not applicable"),{type:"NOT_ELIGIBLE",message:`Momentic's failure recovery agent determined that this failure is not eligible for recovery: ${E}`};if(!R)throw new Error("Momentic's failure recovery agent did not provide any instructions for recovery");let A={id:Xz(),type:"AI_ACTION_DYNAMIC",text:R},C=await va(r.work,()=>r.executeStepList({...r,fixtures:{...r.fixtures},listParams:{steps:[A,c],containerName:"AI-recovered step list",tracer:u}})),w=C.results[0];if(w&&w.type==="AI_ACTION_DYNAMIC")if(ou({results:C.results,onPresetAction:I=>{I.aiSuggested=!0},onSimpleStepContainer:I=>{I.aiSuggested=!0}}),C.status==="SUCCESS"){let I=`The following steps were automatically executed by the failure recovery agent. Analysis: ${E}`;return w.message=I,or.increment("test_event",1,["name:failure_recovery_success",`orgId:${r.inputs.orgId}`]),i.info({thoughts:E},"Failure recovery succeeded"),{type:"ATTEMPTED",status:"SUCCESS",result:C,message:I}}else{let I=`The following steps were unsuccessfully attempted by the failure recovery agent. Analysis: ${E}`;return w.message=I,i.info({thoughts:E,aiActionResult:w},"Failure recovery failed"),{type:"ATTEMPTED",status:"FAILED",result:C,message:I}}return null}function Zz(r,e){if(!e)return"There is no failed result";if(e.type!=="PRESET_ACTION")return"The failed step is not a preset action";let t=e.message;return t?t.includes("AbortError:")?"The user aborted the test":Oy.some(n=>t.includes(n))?"The failed step is an irrecoverable configuration error":(r.state.failureRecoveryAttempts??0)>Jz?"Too many failure recovery attempts":"":"There is no error message available on the failed step"}import{randomUUID as Md}from"crypto";import eH from"fast-json-patch";import{cloneDeep as tH}from"lodash-es";async function JC(r){let e=r.failedResults,t=[],{sectionParams:n,fixtures:o,work:i,startingUrl:a,startingContextSnapshot:l,tracer:c}=r,{step:s}=n,{controller:u,logger:d}=o,p=s?.autohealingConfig,m=p?.restartBehavior??{type:"GO_TO_SECTION_START"},h=p?.attempts??1;for(let g=0;g<h;g++){if(!e.terminalResult?.message)throw new Error("No error message in terminal result");let f=tH(s.steps);await Promise.allSettled(i.asyncTasks??[]);let{results:y}=await ca(d,c,e.results,{numStepsWithScreenshots:4}),S=await u.runSectionAutohealing({results:y,errorMessage:e.terminalResult?.message,goal:s.description});f=eH.applyPatch(f,S.patches).newDocument;let E=ar.fromSnapshot({snapshot:l,environmentVariables:o.context.getVariablesFromEnvironmentCopy()});await rH({logger:d,controller:u,tracer:c,context:E,restartConfig:m,startingUrl:a});let R=await va(r.work,()=>r.executeStepList({...r,fixtures:{...r.fixtures,context:E},listParams:{steps:f,containerName:"auto-healed step list",tracer:c}}));if(t.push(R.results),R.status==="SUCCESS")return{successfulHealing:{proposedStep:{...s,steps:f},listResult:R,context:E},healingAttempts:t};e=R}return{healingAttempts:t}}async function rH({logger:r,controller:e,tracer:t,restartConfig:n,context:o,startingUrl:i}){switch(n.type){case"NAVIGATE_URL":{let a={id:Md(),type:"PRESET_ACTION",command:{id:Md(),type:"NAVIGATE",url:n.url}},l=await t.startStep({logger:r,step:a,attempt:1});await e.executePresetCommand(null,l,a.command,o,!1);break}case"GO_TO_SECTION_START":{let a={id:Md(),type:"PRESET_ACTION",command:{id:Md(),type:"NAVIGATE",url:i}},l=await t.startStep({logger:r,step:a,attempt:1});await e.executePresetCommand(null,l,a.command,o,!1);break}}}function QC(r,e){switch(r||(r="ON_FAILURE"),r){case"ALWAYS":return!0;case"ON_FAILURE":return!0;case"ON_ACTION_FAILURE":return!(!e||e.type==="PRESET_ACTION"&&XS(e.command.type))}}async function ZC(r){let{step:e,tracer:t}=r.sectionParams,{logger:n,controller:o,context:i}=r.fixtures,a=new Date,l=o.browser.url(),c=i.toObjectCopy(),s=await t.startSubSteps(),u=async()=>r.executeStepList({...r,listParams:{steps:e.steps,containerName:"section step list",tracer:s}}),d=e.autohealingConfig?await va(r.work,u):await u(),p,m;if(d.status==="FAILED"&&e.autohealingConfig&&!r.work.state.autoHealingDisabled&&QC(e.autohealingConfig.trigger,d.terminalResult)){let g=await t.startSubSteps(),f=await JC({...r,startingContextSnapshot:c,startingUrl:l,failedResults:d,tracer:g});f.successfulHealing&&(p=f.successfulHealing.proposedStep,d=f.successfulHealing.listResult,r.fixtures.context=f.successfulHealing.context),m=f.healingAttempts}let h={...e,...d,startedAt:a,finishedAt:new Date,proposedStep:p,healingAttempts:m};return Sn({asyncTasks:r.work.asyncTasks,nestedResults:d.results,result:h,logger:n}),h}var oH=60*60*1e3;async function Qr(r){let{results:e=[],containerName:t,steps:n,tracer:o}=r.listParams,{logger:i}=r.fixtures,a=o.getParentStepIdChain(),{fromStep:l,toStep:c}=r.inputs,s=r.work,u="SUCCESS",d,p=0;for(p;p<n.length;p++){let m=n[p];if(m.skipped)continue;if(s.fastForwardingToStep&&l){let E=JSON.stringify(a);if(m.id===l.fromStepId&&E===JSON.stringify(l.parentStepIdChain))s.fastForwardingToStep=!1;else if(!Wb(m,a,l.fromStepId,l.parentStepIdChain))continue}let h=So(m),g=0,f=1,y=Date.now();"retries"in m&&m.retries&&m.retries>0&&(f+=m.retries);let S;for(;g<f&&Date.now()-y<oH;){g++,i.info({step:m,currentAttempt:g},`Executing step ${p+1}/${n.length} in ${t}: ${h}`);let E=Date.now(),{stepResult:R,status:A,failureRecoveryResults:C,shouldStopExecuting:w}=await iH({attempt:g,params:r,step:m,i:p,steps:n,results:e,currentParentIdChain:a,work:s,fromStep:l,toStep:c,lastRetry:g===f});if(A==="FAILED"&&g<f){S=[...S??[],R],Date.now()-E<1e3&&await ie(1e3-(Date.now()-E));continue}else e.push(R),S&&(R.previousAttempts=S);if(C&&e.push(...C),w)return u=A,d=R,{status:u,results:e,terminalResult:d};break}}return{status:u,results:e,terminalResult:d}}async function iH({attempt:r,params:e,step:t,i:n,steps:o,results:i,currentParentIdChain:a,work:l,fromStep:c,toStep:s,lastRetry:u}){let{tracer:d}=e.listParams,{logger:p,context:m,controller:h,codeEvalTools:g,usageTracker:f}=e.fixtures,{orgId:y}=e.inputs,S=new Date,E=await d.startStep({logger:p,step:t,attempt:r}),R=nH(t),A=m.toRedactedDisplayCopy(),C=h.browser.url(),w=h.executeAbortController.signal;f.trackStepExecution(t);let I,P;switch(t.type){case"PRESET_ACTION":{I="Preset action",P=await fi(t,async()=>await Du({...e,presetParams:{tracer:E,step:t}}),w);break}case"AI_ACTION":{I="AI action",P=await fi(t,()=>zA({...e,aiStepParams:{step:t,tracer:E},executeStepList:Qr}),w);break}case"AI_ACTION_DYNAMIC":{I="AI action",P=await fi(t,()=>GA({...e,aiStepParams:{step:t,tracer:E},executeStepList:Qr}),w);break}case"RESOLVED_MODULE":{I=`Module (${t.name})`,P=await fi(t,async()=>{let z=await kA({orgId:y,step:t,context:m,logger:p,codeEvalTools:g,signal:w});return Xh({...e,executeStepList:Qr,moduleParams:{step:t,resolvedInputs:z,tracer:E}})},w);break}case"CONDITIONAL":{I="Conditional step",P=await fi(t,()=>FA({...e,conditionalParams:{step:t,tracer:E},executeStepList:Qr}),w);break}case"SECTION":{I="Section",P=await fi(t,()=>ZC({...e,sectionParams:{step:t,tracer:E},executeStepList:Qr}),w);break}default:return(j=>{throw"If Typescript complains about the line below, you missed a case or break in the switch above"})(t)}P.beforeUrl=P.beforeUrl??C,P.beforeTestContext=A,t.envKey&&m.setVariable(t.envKey,P.data);let X=h.browser.url();m.setCurrentUrl(X),P.afterUrl=P.afterUrl??X,P.afterTestContext=m.toRedactedDisplayCopy(),await aH({step:t,startedAt:S,stepTypeName:I,result:P,callbacks:e.callbacks,globalWorkRef:e.work,tracer:E,attempt:r});let q,k;if(u&&P.status==="FAILED"&&!l.state.failureRecoveryDisabled&&c?.fromStepId===void 0&&s?.toStepId===void 0){let z=await XC({...e,executeStepList:Qr,failureRecoveryParams:{failedStep:R,nextSteps:o.slice(n+1),results:i.concat(P),tracer:d}});z&&(z.type==="ATTEMPTED"?(q=z.result.results,k=z.status):z.type==="NOT_ELIGIBLE"&&(P.message=P.message?`${P.message} ${z.message}`:z.message),P.type==="PRESET_ACTION"&&(P.failureRecoveryStatus={type:z.type,message:z.message}))}return l.fastForwardingToStep&&c&&(c.fromStepId===t.id&&JSON.stringify(a)===JSON.stringify(c.parentStepIdChain)&&(l.fastForwardingToStep=!1),t.type==="RESOLVED_MODULE"&&Eh(a,c.parentStepIdChain)&&(l.fastForwardingToStep=!1)),P.status!=="SUCCESS"&&k!=="SUCCESS"||h.closed?{shouldStopExecuting:!0,status:P.status,stepResult:P,failureRecoveryResults:q}:s&&t.id===s.toStepId&&JSON.stringify(a)===JSON.stringify(s.parentStepIdChain)?(h.setClosed(),{shouldStopExecuting:!0,status:"SUCCESS",stepResult:P,failureRecoveryResults:q}):{shouldStopExecuting:!1,status:"SUCCESS",stepResult:P,failureRecoveryResults:q}}async function aH({stepTypeName:r,step:e,result:t,tracer:n,attempt:o,startedAt:i}){let a=r.toLowerCase(),l=r.charAt(0).toUpperCase()+r.slice(1);n.recordStepDuration({step:e,durationMs:Date.now()-i.getTime()});let c="";switch(t.status){case"SUCCESS":c=t.message??`${l} executed successfully.`;break;case"FAILED":c=t.message??`${l} failed.`;break;case"CANCELLED":c=t.message??`${l} cancelled.`;break;default:throw new Error(`Unexpected ${a} status: ${t.status}`)}await n.finish({step:t,message:c,output:Tc.parse(t),attempt:o})}async function ex({codePath:r,screenshotBuff:e,storage:t,logger:n}){if(e)try{let o=await t.uploadScreenshot(e);return n.info({screenshotUrl:o,codePath:r},"Saved screenshot for debugging"),o}catch(o){n.error({err:o,codePath:r},"Failed to save screenshot for debugging")}}async function An({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 sH=["NAVIGATE","NEW_TAB","TAB","REFRESH","WAIT_FOR_URL"];async function tx({beforeUrl:r,beforePages:e,browser:t,command:n,logger:o}){if(sH.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 ie(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(di(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 xo(r,e={}){let t=await r.getBrowserState(e);return{serializedTree:t.serialize(e.serializationOpts),tree:t}}var rx="MOMENTIC_RUN_ID",nx="FINAL_SCREENSHOT_URL";import{randomUUID as ox}from"crypto";async function ix({browser:r,signal:e}){let t=new Date;try{return await r.navigate({url:r.baseUrl,initialNavigation:!0}),{status:"PASSED",results:[]}}catch(n){let o={id:ox(),type:"PRESET_ACTION",status:e.aborted||n.name==="AbortError"?"CANCELLED":"FAILED",failureReason:"UserInfrastructureError",message:n.message,startedAt:t,finishedAt:new Date,results:[],command:{id:ox(),type:"NAVIGATE",url:r.baseUrl}};return{status:e.aborted||n.name==="AbortError"?"CANCELLED":"FAILED",results:[],failedStepResult:o}}}var Pd=async r=>{let{orgId:e,runId:t,testMetadata:n,steps:o,beforeSteps:i,afterSteps:a}=r.inputs;r.fixtures.logger=r.fixtures.logger.child({orgId:e,runId:t,testId:n?.id});let{logger:l,controller:c}=r.fixtures,{onTestComplete:s,onTestSuccess:u,onTestFailure:d}=r.callbacks.test,p=qA(l);if(r.options.reinitializeBrowser){let h=await ix({browser:c.browser,signal:c.executeAbortController.signal});if(h.status!=="PASSED")return await s?.(),clearInterval(p?.interval),h}let m;try{return l.info({platform:p?.platform,cpuMetadata:p?.cpuMetadata,labels:n?.labels,orgSettings:_T.parse(r.inputs.orgSettings)},`Starting run for Momentic test '${n?.name??"Unnamed test"}'`),m=await cH(r),m}finally{l.info({status:m?.status,labels:n?.labels},"Momentic test final result"),clearInterval(p?.interval),await s?.(),m?.status==="PASSED"?await u?.({steps:o,beforeSteps:i,afterSteps:a}):m?.status==="FAILED"&&await d?.({steps:o,beforeSteps:i,afterSteps:a})}};function lH({beforeStatus:r,mainStatus:e,afterStatus:t}){return r==="FAILED"?"FAILED":r==="CANCELLED"?"CANCELLED":t==="FAILED"?"FAILED":t==="CANCELLED"?"CANCELLED":e==="FAILED"?"FAILED":e==="CANCELLED"?"CANCELLED":"PASSED"}var cH=async r=>{let{tracer:e}=r.testParams,{fromStep:t,toStep:n,steps:o,beforeSteps:i,afterSteps:a}=r.inputs,{logger:l,controller:c,context:s,storage:u}=r.fixtures,{collectDebugData:d,disableHealing:p}=r.options;s.setCurrentUrl(c.browser.url());let m="test",h=o,g=[],f=p||t!==void 0||n!==void 0||void 0,y={results:g,state:{autoHealingDisabled:f,failureRecoveryDisabled:f,failureRecoveryAttempts:0},asyncTasks:[]},S=!1;t?.fromStepId&&t.fromStepId===n?.toStepId?(m="filtered step",y.fastForwardingToStep=!0):t?.fromStepId?(m="partial steps list from step",y.fastForwardingToStep=!0):n?m="partial steps list until step":(m="entire test",S=!0);let E,R,A;if(S&&i&&i.length>0){let k=await ax(i,"beforeSteps",r);E=k.status,R=k.results,A=k.terminalResult?{...k.terminalResult,failureReason:"SetupFailureError"}:void 0}let C,w;if(E===void 0||E==="PASSED"){l.info({fromStep:t,toStep:n},`Starting execution of ${m}`);let k=await e.startMainStepList(),ee=await Qr({...r,work:y,listParams:{steps:h,containerName:m,results:g,tracer:k}});C=ee.status,w=ee.terminalResult}let I,P,X;if(S&&a&&a.length>0){let k=await ax(a,"afterSteps",r);I=k.status,P=k.results,X=k.terminalResult?{...k.terminalResult,failureReason:"TeardownFailureError"}:void 0}let q=lH({beforeStatus:E,mainStatus:C,afterStatus:I});if(d&&uH({tracer:e,work:y,controller:c,storage:u,context:s,logger:l,status:q}),await Promise.allSettled(y.asyncTasks),y.asyncTasks.push(Promise.resolve(r.callbacks.test.onSaveFinalRunResults?.({results:g,beforeResults:R,afterResults:P}))),q==="FAILED"){let k=E==="FAILED"?A:void 0,ee=I==="FAILED"?X:void 0;return{status:"FAILED",results:g,beforeResults:R,afterResults:P,failedStepResult:k??w??ee}}else if(q==="CANCELLED")return{status:"CANCELLED",results:g,beforeResults:R,afterResults:P};return{status:"PASSED",failureRecoveryDetails:y.state.failureRecoveryAttempts?{attempts:y.state.failureRecoveryAttempts}:void 0,results:g,beforeResults:R,afterResults:P}};async function ax(r,e,t){let n=t.fixtures.logger,o=e==="beforeSteps"?await t.testParams.tracer.startBeforeStepList():await t.testParams.tracer.startAfterStepList();n.info(`Starting step execution for ${e}`);let i={results:[],asyncTasks:[],state:{}},a={...t.callbacks,test:{...t.callbacks.test,onSaveFinalRunResults:void 0,onUpdateRun:void 0,onTestComplete:void 0,onTestSuccess:void 0}},{status:l,results:c,terminalResult:s}=await Qr({...t,work:i,callbacks:a,listParams:{steps:r,containerName:e,tracer:o}});await Promise.allSettled(i.asyncTasks);let u;return l==="SUCCESS"?u="PASSED":l==="CANCELLED"?u="CANCELLED":u="FAILED",{status:u,results:c,terminalResult:s}}function uH({tracer:r,work:e,controller:t,storage:n,logger:o,context:i,status:a}){let l=t.browser,c=l.retrieveAndClearDebugData(),s=Qb(c.logsPerPage),u=Hm(c.harPages||{},c.harEntries||{});r.attachConsoleLogs({logger:o,logs:s}),r.attachNetworkLogs({logger:o,logs:u}),a!=="PASSED"&&a!=="SUCCESS"&&(r.attachBrowserCrashDump({crashReportDirFetcher:()=>l.browserCrashDumpDir,logger:o}),e.asyncTasks.push((async()=>{try{let d=await l.screenshot({quality:75}),p=await ex({codePath:"test-complete-final",storage:n,screenshotBuff:d,logger:o}),m=await G(l.html(),{milliseconds:2e3});i.setVariable(nx,p),o.debug({finalPageHtml:m},"Final page state HTML"),o.debug({finalScreenshotUrl:p},"Uploaded final screenshot URL")}catch{}})()))}async function Od({settings:r,customHeaders:e,envVariables:t,envName:n,testName:o,baseUrl:i,logger:a,localTools:l,orgId:c}){let s=Ac.parse(r);e&&(s.extraHeaders={...s.extraHeaders,...e});let u=new ar({baseUrl:i,envName:n,testName:o,variablesFromEnvironment:t,currentUrl:i});await Pu({obj:s,context:u,bannedKeys:[],allowList:lE,localTools:l,logger:a,orgId:c});try{return Ac.parse(s)}catch(d){throw new x("UserConfigurationError",`The templated browser settings configured by the user are invalid: ${d.message}`)}}import{cloneDeep as Cj}from"lodash-es";var tf={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
|
|
61
61
|
var momenticConstants = {
|
|
62
62
|
bannedClassSubstrings: [
|
|
63
63
|
"relative",
|
|
@@ -275,7 +275,6 @@ var momenticConstants = {
|
|
|
275
275
|
"y",
|
|
276
276
|
"width",
|
|
277
277
|
"height",
|
|
278
|
-
"data-momentic-id",
|
|
279
278
|
"aria-keyshortcuts",
|
|
280
279
|
"data-ved",
|
|
281
280
|
"aria-controls",
|
|
@@ -4036,27 +4035,27 @@ function registerAllMomenticListeners() {
|
|
|
4036
4035
|
|
|
4037
4036
|
// src/html/index.ts
|
|
4038
4037
|
registerAllMomenticListeners();
|
|
4039
|
-
`};var Dr={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","
|
|
4038
|
+
`};var Dr={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 sx="BoundingBoxMovedError",lx="ZeroOpacityError",Ld="visual_actions",zn="data-momentic-id";function cx(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(`
|
|
4040
4039
|
`,o);a>0&&a<n&&(o=a);let l=i,c=0;for(;c<1e3&&l>n&&r[l]!==`
|
|
4041
4040
|
`;)c++,l--;return l>n&&r[l]===`
|
|
4042
|
-
`&&(i=l),r.slice(o,i)}function Zr(r){let e=typeof r=="string"?r:r.toString();return`[${zn}="${e}"]`}import{execSync as WG}from"child_process";import{randomUUID as zf}from"crypto";import{diff as Hf}from"deep-object-diff";import{existsSync as jd,readFileSync as qG,readdirSync as KG,statSync as E_,writeFileSync as YG}from"fs";import{Jimp as T_}from"jimp";import XG from"js-beautify";import{cloneDeep as Ga}from"lodash-es";import JG from"mime";import{platform as QG}from"os";import{basename as ZG,extname as ej,join as tj}from"path";import{v4 as rj}from"uuid";import{rmSync as jx}from"fs";import{basename as eG,join as tG}from"path";import{errors as rG}from"playwright-core";import{devices as pH}from"playwright-core";var ux=2,rf=8e3;var Fa=250,At=500;var dx=5e3,px=250,oe=3e3,Ce=2e3,ae=1e3,nf=3e4,of=8e3,mx=10,af=.05;var hx=6e4,gx=new Set(["about:blank","chrome-error://chromewebdata/"]);var sf=["button","image","generic","graphics-symbol","tab","link","menuitem","group"],lf=1e4,Ol=500,Nd=pH["Desktop Chrome"].userAgent,Ba=process.env.TWO_CAPTCHA_KEY;import{mkdirSync as mH,rmSync as fx,statSync as hH}from"fs";import*as pf from"node:fs";import gH from"nodejs-file-downloader";import{tmpdir as fH}from"os";import _o,{basename as SH,dirname as yH}from"path";var mf="file://",df=_o.join(fH(),"momentic","downloads"),uf=1e4,EH=50*1024*1024;async function Sx(r){let{uri:e}=r;if(e.startsWith(mf))return bH(r);if(e.startsWith("http"))return AH(r);if(RT)return vH(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 TH(r,e){let t=_o.join(df,r,e.slice(mf.length)),n=_o.join(df,r),o=t.startsWith(n);if(!pf.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 bH({uri:r,orgId:e}){let t=TH(e,r);return{filePath:t,cleanup:()=>{fx(yH(t),{recursive:!0,force:!0})}}}async function vH({uri:r}){let e=_o.resolve(r);if(!pf.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 AH({uri:r,logger:e,orgId:t}){let n=new URL(r);n.search&&(n.search="");let o=SH(n.href),i=gf(o),a=_o.extname(i);if(cT.includes(a))throw new Error(`Downloading files with extension ${a} is not allowed.`);let l=hf(t),c,s;for(let h=1;h<=3;h++){let g=new gH({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:uf});try{let{downloadStatus:f,filePath:S}=await G(g.download(),{milliseconds:uf,message:`Download timed out after ${uf}ms`});if(f!=="COMPLETE"||!S)throw new Error(`Download ended in non-success status: ${f}`);c=S;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=hH(u).size;if(p>EH)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(()=>fx(l,{recursive:!0,force:!0}),10*60*1e3)}}}function yx(r,e){return`${mf}${r}/${e}`}function hf(r){let e=Math.random().toString(36).substring(4),t=_o.join(df,r,e);return mH(t,{recursive:!0}),t}function gf(r){let e=_o.extname(r),t=_o.basename(r,e);return r=(t.length>100?t.slice(t.length-100):t)+e,r=r.trim().replaceAll(" ","_"),r}async function Hn(r,e){try{return await r.evaluate(n=>window.serializeElementOnlyWithText?.(n,{truncateToLength:500}),void 0,{timeout:ae})}catch(t){e.debug({err:t},"Failed to get HTML from locator for Playwright error translation");return}}async function Ex(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 G(t,{milliseconds:oe});return o&&e.warn({err:o},"Failed to fetch indexedDB data"),n}async function Tx(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 G(n,{milliseconds:oe})}catch(n){t.warn({err:n},"Failed to import indexedDB data")}}}async function bx(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 G(t,{milliseconds:oe})}catch(t){e.debug({err:t},"Failed clearing index db data, continuing...")}}async function vx(r,e,t,n,o){try{await RH(r,e,t,n)}catch(i){o.error({err:i,tabIndex:e},"Error handling new console log")}}async function RH(r,e,t,n){let o=n.text();o.length>Ol&&(o=o.slice(0,Ol)+"...(TRUNCATED)");let i=[];for(let a of n.args())try{let l=await a.jsonValue(),c=JSON.stringify(l);c.length>Ol?i.push(c.slice(0,Ol)+"...(TRUNCATED)"):(typeof l!="object"||Object.keys(l).length>0)&&i.push(l)}catch{}ff(r,t,e,{url:r.url(),location:n.location(),type:n.type(),text:n.text(),args:i})}function ff(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>lf&&(i[t]=i[t].slice(Math.floor(lf/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 kr({fn:r,codePath:e,logObject:t,signal:n,logger:o}){n?.throwIfAborted();let i=Date.now(),a=await Xs({promiseGenerator:r,signal:n,codePath:e,logger:o}),l=Date.now();return t[e]=l-i,a}import wH from"truncate-json";var CH="[redacted due to size]",Ax=5e3,xH=5e3;async function wx(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 Sf(r,e){let t=e.timing(),n=new URL(e.url()),o=[...n.searchParams.entries()].map(([l,c])=>({name:l,value:c})),i={...await xx(e),url:n.toString(),method:e.method(),queryString:o,postData:await IH(e)};return{pageref:r,_resourceType:e.resourceType(),startedDateTime:new Date().toISOString(),request:i,timings:_x(t).timings}}async function Cx(r,e,t){await t.finished();let n={};try{n=await LH(t)}catch{}let o={...await xx(t),status:t.status(),statusText:t.statusText(),content:n,redirectURL:t.headers().location,_mocked:!1};r.response=o;let i;try{i=await e.sizes(),r.request.bodySize=i.requestBodySize,r.request.headersSize=i.requestHeadersSize}catch{}r.response&&i&&(r.response.bodySize=i.responseBodySize,r.response.headersSize=i.responseHeadersSize,r.response.content.size=i.responseBodySize);let a=e.timing();r.startedDateTime=new Date(a.startTime).toISOString();let{timings:l,total:c}=_x(a);r.time=c,r.timings=l}function Ll(r,e,t){r.harEntries||(r.harEntries={}),r.harEntries[t]=e}function Rx(r){try{return new Date(r).toISOString()}catch{return}}function _H(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=Rn(i),e.value=Rn(a);continue}i==="Domain"&&(e.domain=Rn(a)),i==="Expires"&&(e.expires=Rx(a)),i==="HttpOnly"&&(e.httpOnly=!0),i==="Max-Age"&&(e.expires=Rx(Date.now()+ +a*1e3)),i==="Path"&&(e.path=Rn(a)),i==="Secure"&&(e.secure=!0)}return e}async function xx(r){let e=await r.allHeaders(),t=e.cookie?.split(";").map(_H)??[];return{headers:Object.entries(e).map(([n,o])=>({name:Rn(n),value:Rn(o)})),cookies:t}}async function IH(r){let e=r.postData();if(!e)return;let t=await r.headerValue("content-type"),n={mimeType:t??"application/octet-stream",text:Rn(e),params:[]};if(t==="application/x-www-form-urlencoded"){let o=new URLSearchParams(e.toString());for(let[i,a]of o.entries())n.params.push({name:Rn(i),value:a?Rn(a):void 0})}return n}var MH=["text"],PH=["json","xml","html","javascript"];function OH(r){let[e,t]=r.split("/");return e?MH.includes(e)?!0:t?!!PH.some(n=>t?.includes(n)):!1:!1}async function LH(r){let t=((await r.headerValue("content-type"))?.toLowerCase()??void 0)?.split(";")[0]??void 0,n={mimeType:t,encoding:await r.headerValue("content-encoding")??void 0};return t&&OH(t)&&(n.text=Rn(await r.text())),n}function Rn(r){try{let e=JSON.parse(r),{jsonString:t}=wH(r,xH);return t}catch{return r.length>Ax?r.slice(0,Ax)+CH:r}}function wi(r){return r<0?0:r}function _x(r){return{timings:{blocked:wi(r.domainLookupStart),dns:wi(r.domainLookupEnd-r.domainLookupStart),connect:wi(r.connectEnd-r.connectStart),send:wi(r.responseStart-r.requestStart),wait:0,receive:wi(r.responseEnd-r.responseStart),ssl:wi(r.connectEnd-r.secureConnectionStart)},total:wi(r.responseEnd)}}function Ix(){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 yt({root:r,fn:e,arg:t,timeout:n,waitForPageLoad:o,codePath:i}){return await o(),await G(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 yf(){return window.lastCursorPos}import{errors as NH}from"playwright-core";async function Ci({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 NH.TimeoutError)t.warn({err:c,rootUrl:(await n.state.getRoot()).url()},`Encountered Playwright error while performing ${e}`),l=await DH(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 DH(r,e,t,n){return r.message.includes("attempt #")?kH(r,e,t,n):UH(r)}async function kH(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(`
|
|
4041
|
+
`&&(i=l),r.slice(o,i)}function Zr(r){let e=typeof r=="string"?r:r.toString();return`[${zn}="${e}"]`}import{execSync as WG}from"child_process";import{randomUUID as zf}from"crypto";import{diff as Hf}from"deep-object-diff";import{existsSync as jd,readFileSync as qG,readdirSync as KG,statSync as E_,writeFileSync as YG}from"fs";import{Jimp as T_}from"jimp";import XG from"js-beautify";import{cloneDeep as Ga}from"lodash-es";import JG from"mime";import{platform as QG}from"os";import{basename as ZG,extname as ej,join as tj}from"path";import{v4 as rj}from"uuid";import{rmSync as jx}from"fs";import{basename as eG,join as tG}from"path";import{errors as rG}from"playwright-core";import{devices as pH}from"playwright-core";var ux=2,rf=8e3;var Fa=250,At=500;var dx=5e3,px=250,oe=3e3,Ce=2e3,ae=1e3,nf=3e4,of=8e3,mx=10,af=.05;var hx=6e4,gx=new Set(["about:blank","chrome-error://chromewebdata/"]);var sf=["button","image","generic","graphics-symbol","tab","link","menuitem","group"],lf=1e4,Ol=500,Nd=pH["Desktop Chrome"].userAgent,Ba=process.env.TWO_CAPTCHA_KEY;import{mkdirSync as mH,rmSync as fx,statSync as hH}from"fs";import*as pf from"node:fs";import gH from"nodejs-file-downloader";import{tmpdir as fH}from"os";import _o,{basename as SH,dirname as yH}from"path";var mf="file://",df=_o.join(fH(),"momentic","downloads"),uf=1e4,EH=50*1024*1024;async function Sx(r){let{uri:e}=r;if(e.startsWith(mf))return bH(r);if(e.startsWith("http"))return AH(r);if(RT)return vH(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 TH(r,e){let t=_o.join(df,r,e.slice(mf.length)),n=_o.join(df,r),o=t.startsWith(n);if(!pf.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 bH({uri:r,orgId:e}){let t=TH(e,r);return{filePath:t,cleanup:()=>{fx(yH(t),{recursive:!0,force:!0})}}}async function vH({uri:r}){let e=_o.resolve(r);if(!pf.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 AH({uri:r,logger:e,orgId:t}){let n=new URL(r);n.search&&(n.search="");let o=SH(n.href),i=gf(o),a=_o.extname(i);if(cT.includes(a))throw new Error(`Downloading files with extension ${a} is not allowed.`);let l=hf(t),c,s;for(let h=1;h<=3;h++){let g=new gH({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:uf});try{let{downloadStatus:f,filePath:y}=await G(g.download(),{milliseconds:uf,message:`Download timed out after ${uf}ms`});if(f!=="COMPLETE"||!y)throw new Error(`Download ended in non-success status: ${f}`);c=y;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=hH(u).size;if(p>EH)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(()=>fx(l,{recursive:!0,force:!0}),10*60*1e3)}}}function yx(r,e){return`${mf}${r}/${e}`}function hf(r){let e=Math.random().toString(36).substring(4),t=_o.join(df,r,e);return mH(t,{recursive:!0}),t}function gf(r){let e=_o.extname(r),t=_o.basename(r,e);return r=(t.length>100?t.slice(t.length-100):t)+e,r=r.trim().replaceAll(" ","_"),r}async function Hn(r,e){try{return await r.evaluate(n=>window.serializeElementOnlyWithText?.(n,{truncateToLength:500}),void 0,{timeout:ae})}catch(t){e.debug({err:t},"Failed to get HTML from locator for Playwright error translation");return}}async function Ex(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 G(t,{milliseconds:oe});return o&&e.warn({err:o},"Failed to fetch indexedDB data"),n}async function Tx(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 G(n,{milliseconds:oe})}catch(n){t.warn({err:n},"Failed to import indexedDB data")}}}async function bx(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 G(t,{milliseconds:oe})}catch(t){e.debug({err:t},"Failed clearing index db data, continuing...")}}async function vx(r,e,t,n,o){try{await RH(r,e,t,n)}catch(i){o.error({err:i,tabIndex:e},"Error handling new console log")}}async function RH(r,e,t,n){let o=n.text();o.length>Ol&&(o=o.slice(0,Ol)+"...(TRUNCATED)");let i=[];for(let a of n.args())try{let l=await a.jsonValue(),c=JSON.stringify(l);c.length>Ol?i.push(c.slice(0,Ol)+"...(TRUNCATED)"):(typeof l!="object"||Object.keys(l).length>0)&&i.push(l)}catch{}ff(r,t,e,{url:r.url(),location:n.location(),type:n.type(),text:n.text(),args:i})}function ff(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>lf&&(i[t]=i[t].slice(Math.floor(lf/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 kr({fn:r,codePath:e,logObject:t,signal:n,logger:o}){n?.throwIfAborted();let i=Date.now(),a=await Xs({promiseGenerator:r,signal:n,codePath:e,logger:o}),l=Date.now();return t[e]=l-i,a}import wH from"truncate-json";var CH="[redacted due to size]",Ax=5e3,xH=5e3;async function wx(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 Sf(r,e){let t=e.timing(),n=new URL(e.url()),o=[...n.searchParams.entries()].map(([l,c])=>({name:l,value:c})),i={...await xx(e),url:n.toString(),method:e.method(),queryString:o,postData:await IH(e)};return{pageref:r,_resourceType:e.resourceType(),startedDateTime:new Date().toISOString(),request:i,timings:_x(t).timings}}async function Cx(r,e,t){await t.finished();let n={};try{n=await LH(t)}catch{}let o={...await xx(t),status:t.status(),statusText:t.statusText(),content:n,redirectURL:t.headers().location,_mocked:!1};r.response=o;let i;try{i=await e.sizes(),r.request.bodySize=i.requestBodySize,r.request.headersSize=i.requestHeadersSize}catch{}r.response&&i&&(r.response.bodySize=i.responseBodySize,r.response.headersSize=i.responseHeadersSize,r.response.content.size=i.responseBodySize);let a=e.timing();r.startedDateTime=new Date(a.startTime).toISOString();let{timings:l,total:c}=_x(a);r.time=c,r.timings=l}function Ll(r,e,t){r.harEntries||(r.harEntries={}),r.harEntries[t]=e}function Rx(r){try{return new Date(r).toISOString()}catch{return}}function _H(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=Rn(i),e.value=Rn(a);continue}i==="Domain"&&(e.domain=Rn(a)),i==="Expires"&&(e.expires=Rx(a)),i==="HttpOnly"&&(e.httpOnly=!0),i==="Max-Age"&&(e.expires=Rx(Date.now()+ +a*1e3)),i==="Path"&&(e.path=Rn(a)),i==="Secure"&&(e.secure=!0)}return e}async function xx(r){let e=await r.allHeaders(),t=e.cookie?.split(";").map(_H)??[];return{headers:Object.entries(e).map(([n,o])=>({name:Rn(n),value:Rn(o)})),cookies:t}}async function IH(r){let e=r.postData();if(!e)return;let t=await r.headerValue("content-type"),n={mimeType:t??"application/octet-stream",text:Rn(e),params:[]};if(t==="application/x-www-form-urlencoded"){let o=new URLSearchParams(e.toString());for(let[i,a]of o.entries())n.params.push({name:Rn(i),value:a?Rn(a):void 0})}return n}var MH=["text"],PH=["json","xml","html","javascript"];function OH(r){let[e,t]=r.split("/");return e?MH.includes(e)?!0:t?!!PH.some(n=>t?.includes(n)):!1:!1}async function LH(r){let t=((await r.headerValue("content-type"))?.toLowerCase()??void 0)?.split(";")[0]??void 0,n={mimeType:t,encoding:await r.headerValue("content-encoding")??void 0};return t&&OH(t)&&(n.text=Rn(await r.text())),n}function Rn(r){try{let e=JSON.parse(r),{jsonString:t}=wH(r,xH);return t}catch{return r.length>Ax?r.slice(0,Ax)+CH:r}}function wi(r){return r<0?0:r}function _x(r){return{timings:{blocked:wi(r.domainLookupStart),dns:wi(r.domainLookupEnd-r.domainLookupStart),connect:wi(r.connectEnd-r.connectStart),send:wi(r.responseStart-r.requestStart),wait:0,receive:wi(r.responseEnd-r.responseStart),ssl:wi(r.connectEnd-r.secureConnectionStart)},total:wi(r.responseEnd)}}function Ix(){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 yt({root:r,fn:e,arg:t,timeout:n,waitForPageLoad:o,codePath:i}){return await o(),await G(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 yf(){return window.lastCursorPos}import{errors as NH}from"playwright-core";async function Ci({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 NH.TimeoutError)t.warn({err:c,rootUrl:(await n.state.getRoot()).url()},`Encountered Playwright error while performing ${e}`),l=await DH(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 DH(r,e,t,n){return r.message.includes("attempt #")?kH(r,e,t,n):UH(r)}async function kH(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(`
|
|
4043
4042
|
`,";").replace(/\s+/g," ");let a="",l=await Hn(e,n);if(l&&(a=`Target element HTML: ${it(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(Zr(s)),d=await Hn(u,n);d&&(c=`Covering element HTML: ${it(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}
|
|
4044
|
-
${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:oe});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 UH(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{existsSync as Dl,mkdirSync as Rf,readdirSync as VH,rmSync as Nx}from"fs";import{homedir as Cf}from"os";import{join as Gn,resolve as $H}from"path";import{chromium as Dx}from"playwright-core";import{addExtra as WH}from"playwright-extra";import qH from"puppeteer-extra-plugin-recaptcha";function Mx(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 BH}from"crypto";function Px(r,e){for(let t of Object.values(e))if(t.matcher.matches({url:r.url(),method:r.method()}))return t}async function Ox(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 FH(t,c,s),d={};u.headers.forEach((m,h)=>{d[h]=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,h])=>({name:m,value:h})),cookies:[],content:{mimeType:p.contentType,text:p.body},_mocked:!0},Ll(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 FH(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 Ef(r){try{await zH(r)}catch(e){r.logger.warn({err:e},"Error handling intercepted request, continuing...")}}async function zH(r){let{pageId:e,route:t,request:n,debugData:o,logger:i,requestRecorders:a,mocks:l}=r,c=BH(),s=await Sf(e,n);try{Ll(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=Px(n,l);u?await Ox({logger:i,route:t,mock:u,entry:s,debugData:o,requestId:c,requestRecorders:a}):await HH({route:t,request:n,debugData:o,logger:i,requestRecorders:a,entry:s,requestId:c})}async function HH({route:r,request:e,debugData:t,logger:n,requestRecorders:o,entry:i,requestId:a}){await r.continue();try{let l=await e.response();if(!l||!i)return;await Cx(i,e,l),Ll(t,i,a);for(let c of Object.values(o))c.onRequestComplete(a,i)}catch(l){l.message.includes("has been closed")||n.warn({err:l},"Failed to add response to HAR")}}async function GH(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 jH(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 Dd(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 Tf(r){let e=r.request(),t=r.status(),n=r.headers(),o=await jH(r);return{request:{url:e.url(),method:e.method(),headers:e.headers(),...await GH(e)},response:{status:t,headers:n,...o},status:t,headers:n,...o}}var Io=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:Tu(t,this.requestMatcher.urlMatcher)}};function Nl(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 bf,platform as vf}from"os";import{join as Af}from"path";function kd(){let r=[];if(vf()==="linux"){let e=bf();["chromium","google-chrome","chrome-canary"].forEach(t=>{r.push(Af(e,".config",t,"Crash Reports"))})}else if(vf()==="darwin"){let e=bf();["Chromium","Google","Chrome for Testing"].forEach(t=>{r.push(Af(e,"Library","Application Support",t,"Crashpad"))})}else if(vf()==="win32"){let e=bf();["Chromium","Google","Google Chrome Canary"].forEach(t=>{r.push(Af(e,"AppData","Local",t,"User Data","Crashpad","reports"))})}return r}function Lx(){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 wf=Gn(Cf(),"momentic","chromium"),KH=Gn(Cf(),"video"),kx=WH(Dx);kx.use(qH({provider:{id:"2captcha",token:Ba},visualFeedback:!0}));var YH=["--enable-crashpad","--crash-on-hang-threads=UI:18,IO:18"],XH=["--disable-dev-shm-usage","--no-first-run","--renderer-process-limit=3","--browser-test","--disable-site-isolation-for-policy","--disable-site-isolation-trials","--disable-backgrounding-occluded-windows","--disable-background-timer-throttling","--disable-renderer-backgrounding","--autoplay-policy=user-gesture-required","--disable-add-to-shelf","--disable-desktop-notifications","--use-fake-device-for-media-stream","--use-fake-ui-for-media-stream","--enable-logging=stderr","--log-level=2"],JH=["--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 Ux({baseUrl:r,logger:e,storage:t,enricher:n,userBrowserSettings:o,contextArgs:i,recordVideo:a,iconKnowledgeBase:l,callbacks: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=[...XH],d={headless:process.env.MOMENTIC_HEADFUL_BROWSER!=="true",handleSIGTERM:!1,chromiumSandbox:!1,channel:s},p={...i??{},geolocation:i?.geolocation||ao,locale:i?.locale||oo,timezoneId:i?.timezoneId||io,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??Nd,viewport:i?.viewport??Gt,serviceWorkers:"block",storageState:{cookies:[Lx()],origins:[]}};o.initialLocalStorage&&(p.storageState.origins=Object.entries(o.initialLocalStorage).map(([y,E])=>({origin:y,localStorage:Object.entries(E).map(([R,A])=>({name:R,value:A}))}))),process.env.MOMENTIC_CHROME_EXTRA_ARGS&&u.push(...process.env.MOMENTIC_CHROME_EXTRA_ARGS.split(","));let m=null,h,g,f={systemDevicePixelRatio:i?.deviceScaleFactor,recordVideo:a,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 y=kd();y.forEach(E=>{if(!Dl(E))return;["new","pending","completed"].forEach(A=>{let C=Gn(E,A);if(!Dl(C))return;let w=VH(C);for(let I=0;I<w.length;I++){let P=Gn(C,w[I]);Nx(P,{force:!0})}})}),y.forEach(E=>{Dl(E)||Rf(E,{recursive:!0});let R=Gn(E,`write-test-${Date.now()}`);Rf(R,{recursive:!0}),Nx(R,{recursive:!0,force:!0})}),u.push(...YH)}catch(y){e.warn({err:y},"Could not create Chrome crash report directory, not enabling crashpad")}o.disableGpu&&u.push(...JH);let S=o.localChromeExtensionPaths?.map(y=>y.startsWith("~")?Gn(Cf(),y.slice(1)):y);if(S?.length){if(s===void 0)throw new x("UserConfigurationError","Chrome extensions are only supported on Chromium and Google Chrome.");for(let A of S){let C=Gn(A,"manifest.json");if(!Dl(C))throw new x("UserConfigurationError",`Chrome extension path ${C} does not exist.`)}if(cn)throw new x("UserConfigurationError","Cannot use persistent browser context on Momentic Cloud");let y=Gn(wf,`momentic-session-${Date.now()}`);if(!Dl(y))try{Rf(y,{recursive:!0})}catch(A){throw new x("UserConfigurationError",`Failed to create browser cache directory. Please make sure you have sufficient permissions to create the ${wf} folder: ${A}`)}let E=[...u],R=S.map(A=>$H(A)).join(",");E.push(`--disable-extensions-except=${R}`),p?.deviceScaleFactor&&E.push(`--force-device-scale-factor=${p.deviceScaleFactor}`,`--device-scale-factor=${p.deviceScaleFactor}`),p.viewport&&E.push(`--window-size=${p.viewport.width},${p.viewport.height}`),h=await Dx.launchPersistentContext(Gn(wf,`momentic-session-${Date.now()}`),{...d,...p,ignoreDefaultArgs:["--disable-extensions","--disable-component-extensions-with-background-pages"],args:E,baseURL:r}),e.info({sharedContextOptions:p,sharedBrowserOptions:d,userBrowserSettings:o,chromeArgs:E,properties:f,baseUrl:r},"Browser initialization context args (persistent)"),g=h.pages()[0]}else{m=await kx.launch({...d,args:u});let y={...p,baseURL:r,recordVideo:a?{dir:KH}:void 0};h=await m.newContext(y),e.info({contextArgs:y,sharedBrowserOptions:d,chromeArgs:u,userBrowserSettings:o,properties:f,baseUrl:r},"Browser initialization context args (standard)"),g=await h.newPage()}return cn&&await h.route("**",Nl),{browser:m,context:h,page:g,baseUrl:r,logger:e,storage:t,enricher:n,userBrowserSettings:o,viewport:p.viewport||Gt,properties:f,clientCallbacks:c,iconKnowledgeBase:l}}async function Fx(r){try{return await QH(r)}catch(e){r.logger.warn({err:e},"Failed to transform locator for Chakra click, continuing...");return}}async function QH({locator:r,logger:e}){let[t,n]=await r.evaluate(c=>[c.id,c.tagName.toLowerCase()],{timeout:ae}),o=await Hn(r,e),i=await r.boundingBox({timeout:ae});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:ae}),{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)},h=s._MOMENTIC_FEATURE_FLAGS?.[Ld],g=c.getAttribute(zn),f=!h&&g?Zr(g):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:ae});if(a.type==="error")throw new Error(a.error);let l=r.page().locator(a.selector);return await l.waitFor({state:"visible",timeout:ae}),e.info({parentElementResult:a,originalElementDisplayString:o},`Redirected click to parent element with selector: ${a.selector}`),{locator:l,relativePoint:a.relativePoint}}var zx=["date","datetime-local","month","time","week"],Bx={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 Hx(r){try{await G(ZH(r),{milliseconds:oe})}catch(e){r.logger.warn({err:e},"Failed to transform native datetime input, continuing...")}}async function ZH({root:r,text:e,options:t,logger:n,callbacks:o}){let i=(await yt({root:r,fn:()=>document.activeElement?.getAttribute("type")??"",timeout:ae,arg:void 0,waitForPageLoad:o.waitForPageLoad,codePath:"transforming native datetime input"})).toLowerCase();if(!Bx[i])return;Bx[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 ur}from"zod";var Gx=ur.object({doubleClick:ur.boolean().optional(),rightClick:ur.boolean().optional(),force:ur.boolean().optional(),waitForDownload:ur.boolean().optional(),delayMs:ur.number().optional(),downloadTimeoutMs:ur.number().optional(),relativePosition:ur.object({x:ur.number(),y:ur.number()}).optional()}),$Pe=ur.object({repeat:ur.number().optional(),convertMeta:ur.boolean().optional().describe("misleading name due to backcompat. converts keyshortcuts + meta/control to platform-specific combos. defaults to true"),delayMs:ur.number().optional()});async function Ud({locator:r,callbacks:e,logger:t,timeoutMs:n=ae}){try{await xf(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 h=d.getBoundingClientRect();return!(!h.height||!h.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 G(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 xf(r,e=ae){let t=await r.state.getRoot();await yt({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 _f(r){let e=!!r.browserCallbacks.state.userBrowserSettings.visualActions;return Ci({action:"clicking element",targetingResult:r.targetingResult,logger:r.logger,retryTimeoutMs:r.retryTimeoutMs,callbacks:r.browserCallbacks,func:async t=>Vx({...r,targetingResult:t,useVisualClick:e})})}async function nG(r,e){let{redirectionAttempts:t=0}=e;if(t>=2)throw r;try{return await oG(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 oG(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:ae});if(!i)throw r;let a=o.page().locator(`[for=${JSON.stringify(i)}]`);return await a.waitFor({state:"visible",timeout:ae}),t.warn({err:r},"Attempting locator redirection due to input being covered by label"),Vx({...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 iG(r){let{logger:e,targetingResult:t,position:n,options:o}=r,i=Gx.safeParse(o),a=Date.now(),{clickX:l,clickY:c,reason:s}=await lG({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 aG(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 Fx({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:oe,position:a,delay:n?.delayMs??25,force:l}):await i.click({button:n?.rightClick?"right":"left",timeout:oe,position:a,delay:n?.delayMs??25,force:l})}catch(s){let u=s;if(uG(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..."),nG(u,{...r,targetingResult:{...i,locator:i}})}return{locatorSource:c}}async function Vx(r){let{options:e,logger:t,browserCallbacks:n,controllerCallbacks:o,useVisualClick:i,targetingResult:a}=r,l;e?.waitForDownload&&(l=(async()=>{let u=e.downloadTimeoutMs??nf;try{return await a.locator.page().waitForEvent("download",{timeout:u})}catch(d){return d instanceof rG.TimeoutError?new x("ActionFailureError",`Download did not complete in ${u}ms`):new x("ActionFailureError",`Download failed: ${d.message}`)}})());try{await Ud({locator:a.locator,callbacks:n,logger:t,timeoutMs:ae})}catch(u){t.warn({err:u},"Error highlighting locator in click, continuing...")}let c,s;if(i?c=await iG(r):s=(await aG(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 G(l,{milliseconds:e.downloadTimeoutMs??nf});if(u instanceof Error)throw u;return{downloadedFile:await cG(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 sG(r){let e=await r.locator.boundingBox({timeout:oe});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 lG({options:r,targetingResult:e,position:t}){let n,o,i;if(r?.relativePosition){let s=await e.locator.boundingBox({timeout:oe}),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:oe});n=(s?.x??0)+t.x,o=(s?.y??0)+t.y,i="predefined position"}else{let[s,u]=await sG(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 cG(r,e,t){t.info("Download detected, saving file to disk");let n=await r.path(),o=gf(r.suggestedFilename()),i=e();await r.saveAs(tG(i,o)),jx(n,{force:!0}),setTimeout(()=>{jx(i,{recursive:!0,force:!0})},5*60*1e3);let a=yx(eG(i),o);return t.info({uri:a,downloadFolder:i},"Saved download to isolated folder"),a}function uG(r){return r.message.includes("locator.click: Timeout")&&r.message.includes("click action done")}import{platform as dG}from"os";var pG={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 mG(){let r=dG();return r==="win32"?"win32":r==="darwin"?"darwin":"linux"}function $x(r){return JSON.stringify(r.split("+").sort())}function Fd(r,e){let t=mG(),n=$x(r);for(let o of Object.values(pG))if(Object.values(o).some(i=>$x(i)===n))return o[t];return process.platform==="darwin"&&!e?r=r.replaceAll("Control","Meta"):r=r.replaceAll("Meta","Control"),r}async function If({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 yt({root:r,fn:([d,p,m,h])=>window.scrollTo(window.scrollX+(d??window.innerWidth)*m,window.scrollY+(p??window.innerHeight)*h),arg:[t,o,s,u],waitForPageLoad:l.waitForPageLoad,timeout:Ce,codePath:"scrolling page"});else{let d=e.viewportSize()||Gt,p=await yt({root:e,fn:()=>document.body.scrollHeight,arg:void 0,waitForPageLoad:l.waitForPageLoad,timeout:Ce,codePath:"computing page height"}),[m,h,g]=await yt({root:e,fn:()=>{let f=document.activeElement;if(!f)return[void 0,void 0,void 0];let S=f.getBoundingClientRect();return[f.scrollTop,S.x,S.y]},arg:void 0,waitForPageLoad:l.waitForPageLoad,timeout:Ce,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<Ce;){a?.throwIfAborted();let S=await G(e.evaluate(()=>document.body.scrollHeight),{milliseconds:ae}),[y,E,R]=await G(e.evaluate(()=>{let A=document.activeElement;if(!A)return[void 0,void 0,void 0];let C=A.getBoundingClientRect();return[A.scrollTop,C.x,C.y]}),{milliseconds:ae});if(S===p&&y===m&&E===h&&R===g)break;p=S,m=y,h=E,g=R,await ie(At)}}catch(f){c.warn({err:f},"Failed to wait for scroll to complete, continuing...")}}}async function Mf(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 ie(At)}throw new Error(`Failed to get tab titles after all retries: ${n?.message}`)}import{randomUUID as bG}from"crypto";import{cloneDeep as Lf}from"lodash-es";function Mo(r,e){let t=r.findIndex(n=>n===e);if(!(t===-1||!r[t+1]))return r[t+1]}import{createHash as hG}from"crypto";var gG="v1";function Pf(r,e){if(r.tagName.toLowerCase()==="svg"&&!SG(r))try{let t=Wx(r,e),n=fG(JSON.stringify(t));return{version:gG,json:t,hash:n}}catch{return}}function fG(r){return hG("md5").update(r).digest("hex")}function Wx(r,e){let t=r.tagName.toLowerCase(),n=yG(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=Wx(a,e);l&&o.children.push(l)}}return o}function SG(r){let e=r.computedStyles.display,t=r.computedStyles.visibility,n=r.computedStyles.opacity;return e==="none"||t==="hidden"||n==="0"}function yG(r){let e={},t=r.attributes;for(let n of Object.keys(t))Dr.visualAttributesForSvgSerialization.includes(n)&&(e[n]=t[n]);return t.id&&r.tagName.toLowerCase()!=="svg"&&(e.id=t.id),e}var xi={r:147,g:196,b:125,a:.55},Kx={showRulers:!1,showStyles:!1,showExtensionLines:!1,contrastAlgorithm:"aa",contentColor:xi,paddingColor:xi,borderColor:xi,marginColor:xi,eventTargetColor:xi,shapeColor:xi,shapeMarginColor:xi,showInfo:!0,showAccessibilityInfo:!0};function Yx({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=EG({allDocuments:i,stringConstants:o,computedStylesToFetch:t,devicePixelRatio:e,frameIndex:u,backendIdToNode:a,frameIndexToIframeNode:l,logger:n});c.roots.push(d)}),c}function EG({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,I)=>{u[w]=I});let d=s.styles,p=s.bounds??[],m=c.nodes,h=m.contentDocumentIndex??{index:[],value:[]},g=m.backendNodeId??[],f=m.attributes??[],S=m.parentIndex??[],y=m.nodeName??[],E=m.nodeType??[],R=m.pseudoType??{index:[],value:[]},A=m.inputChecked??{index:[]},C=e[c.frameId];for(let w=0;w<g.length;w++){let I=g[w],P=E[w],X=f[w]??[],q=S[w]!==void 0&&S[w]>=0?S[w]:void 0,k=q!==void 0?g[q]:void 0,ee=k!==void 0?a[k]:void 0,z=R.index.indexOf(w),j=z!==-1?e[R.value[z]]:void 0,he=u[w],$;he?$=p[he]??[]:$=[];let rt=y[w]!==void 0?e[y[w]]?.toLowerCase():void 0;if(!rt){l.warn({backendNodeId:I,frameId:C,frameIndex:o,nodeBounds:$},"DOM node has no tag name");continue}let Ne={backendNodeId:I,psuedoType:j,nodeType:P,frameIndex:o,parentFrameId:C,ownedFrameId:void 0,bounds:{x:$[0]??null,y:$[1]??null,width:$[2]??null,height:$[3]??null},computedStyles:{},attributes:{},parentBackendNodeId:k??null,tagName:rt,parent:ee??void 0,childrenBackendIds:[],momenticIgnored:void 0,mPathSelector:void 0};ee&&ee.childrenBackendIds.push(I);let ct=h.index.indexOf(w);if(ct!==-1){let J=h.value[ct];i[J]=Ne;let we=r[J]?.frameId;Ne.ownedFrameId=we!==void 0?e[we]:void 0}for(let J of Object.keys(Ne.bounds)){let we=J;Ne.bounds[we]!==null&&(Ne.bounds[we]/=n)}let kt=he!==void 0?d[he]??[]:[];for(let J=0;J<kt.length&&!(J>=t.length);J++){let we=kt[J];if(we===void 0||isNaN(we))continue;let Er=e[we];if(Er===void 0)continue;let Kn=t[J];Ne.computedStyles[Kn]=Er}for(let J=0;J<X.length;J+=2){let we=X[J],Er=X[J+1];if(!we||!Er)continue;let Kn=e[we],Yn=e[Er];!Kn||!Yn||(Ne.attributes[Kn]=Yn)}A.index.includes(w)&&(Ne.attributes.checked="true"),a[Ne.backendNodeId]=Ne}return a[g[0]]}function Of(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=`${Of(t,e)}${a}`}return r.mPathSelector=n,n}function qx(r,e){return r.parentBackendNodeId!==null?e.backendIdToNode[r.parentBackendNodeId]:r.frameIndex===0?void 0:e.frameIndexToIframeNode[r.frameIndex]}var TG=["html","#document","#document-fragment"];function Xx({node:r,domGraph:e}){let t=[],n=r,o=qx(r,e);if(!o)return[r.tagName];let i=()=>{if(n=o,o=qx(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++,TG.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 Jx(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 Qx(r,e){await r.send({method:"DOM.getDocument",params:{depth:0},timeout:Ce});let t=await r.send({method:"DOM.requestNode",params:{objectId:e},timeout:Ce}),o=(await r.send({method:"DOM.getAttributes",params:{nodeId:t.nodeId},timeout:Ce})).attributes,i=Mo(o,zn);if(!i)throw new Error(`Could not find attribute ${zn} for object ${e}`);return i}var vG=["focusable","keyshortcuts","controls","live","relevant","orientation"],AG=["selected","readonly","modal","required","invalid"],RG=["id","name","role","content"],Zx=["absolute","fixed","sticky"],wG=["i"],CG=["path"],xG=["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"],r_=["ariaHiddenElement","ariaHiddenSubtree","hiddenByChildTree","inertElement","inertSubtree","notRendered","notVisible"],n_=["activeAriaModalDialog","activeFullscreenElement","activeModalDialog"],_G=["menulistpopup","statictext","inlinetextbox"],IG=80,e_=100,o_=50,kf=["StaticText","ListMarker","RootWebArea","LineBreak","emphasis","::before","::after"],MG=["cite"],PG={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"]},OG={name:!0,value:!0,title:!0,alt:!0,placeholder:!0,checked:!0,selected:!0,contenteditable:!0},t_={indentLevel:0},Nf=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<o_?t:""),this.role=this.role||(e.domNode.attributes.role??""),kG(this.properties,e.domNode,e.importantProperties)}FG(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&&CG.includes(this.domNode.tagName)||this.domNode?.computedStyles.display==="contents"||this.ignoredReasons.some(n=>n_.includes(n)))return!1;if(e){if(Object.keys(this.domNode?.attributes??{}).some(o=>c_(o,e)))return!0;let n=this.domNode?.attributes.class?.split(" ");if(n&&n.length>0&&n.some(o=>u_(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&&wG.includes(this.domNode.tagName)||xG.includes(this.role.toLowerCase())||this.role.toLowerCase()==="inlinetextbox"&&this.tagName||!this.properties.hidden&&(this.properties.focusable||this.properties.settable)||Dr.alwaysInterestingTruthyPropertyNames.some(n=>!!this.properties[n]))return!0;let t=this.properties.class;return typeof t=="string"&&t.split(" ").some(n=>l_(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=t_){let t=Object.assign({},t_,e),{indentLevel:n,noChildren:o,noProperties:i,noId:a,noContent:l,condensedMode:c}=t,s=Lf(this.properties),u=" ".repeat(n),d=this.role||"",p=this.tagName??"unknown",m=this.name;d==="heading"&&m==="heading"&&(m=""),this.nameSources?.find(A=>!A.superseded&&A.type==="contents")&&this.children.length>0&&(m="");let g=this.nameSources?.find(A=>!A.superseded);if(g&&!g.nativeSource&&g.type==="relatedElement"){let A=g.attributeValue?.relatedNodes??[];A.length===1&&A[0].text&&A[0].text===m&&(m="")}let f=kf.includes(this.role)||MG.includes(this.tagName||"");if(this.role==="StaticText"||this.role==="ListMarker")return`${u}${m}
|
|
4045
|
-
`;let
|
|
4043
|
+
${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:oe});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 UH(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{existsSync as Dl,mkdirSync as Rf,readdirSync as VH,rmSync as Nx}from"fs";import{homedir as Cf}from"os";import{join as Gn,resolve as $H}from"path";import{chromium as Dx}from"playwright-core";import{addExtra as WH}from"playwright-extra";import qH from"puppeteer-extra-plugin-recaptcha";function Mx(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 BH}from"crypto";function Px(r,e){for(let t of Object.values(e))if(t.matcher.matches({url:r.url(),method:r.method()}))return t}async function Ox(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 FH(t,c,s),d={};u.headers.forEach((m,h)=>{d[h]=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,h])=>({name:m,value:h})),cookies:[],content:{mimeType:p.contentType,text:p.body},_mocked:!0},Ll(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 FH(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 Ef(r){try{await zH(r)}catch(e){r.logger.warn({err:e},"Error handling intercepted request, continuing...")}}async function zH(r){let{pageId:e,route:t,request:n,debugData:o,logger:i,requestRecorders:a,mocks:l}=r,c=BH(),s=await Sf(e,n);try{Ll(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=Px(n,l);u?await Ox({logger:i,route:t,mock:u,entry:s,debugData:o,requestId:c,requestRecorders:a}):await HH({route:t,request:n,debugData:o,logger:i,requestRecorders:a,entry:s,requestId:c})}async function HH({route:r,request:e,debugData:t,logger:n,requestRecorders:o,entry:i,requestId:a}){await r.continue();try{let l=await e.response();if(!l||!i)return;await Cx(i,e,l),Ll(t,i,a);for(let c of Object.values(o))c.onRequestComplete(a,i)}catch(l){l.message.includes("has been closed")||n.warn({err:l},"Failed to add response to HAR")}}async function GH(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 jH(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 Dd(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 Tf(r){let e=r.request(),t=r.status(),n=r.headers(),o=await jH(r);return{request:{url:e.url(),method:e.method(),headers:e.headers(),...await GH(e)},response:{status:t,headers:n,...o},status:t,headers:n,...o}}var Io=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:Tu(t,this.requestMatcher.urlMatcher)}};function Nl(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 bf,platform as vf}from"os";import{join as Af}from"path";function kd(){let r=[];if(vf()==="linux"){let e=bf();["chromium","google-chrome","chrome-canary"].forEach(t=>{r.push(Af(e,".config",t,"Crash Reports"))})}else if(vf()==="darwin"){let e=bf();["Chromium","Google","Chrome for Testing"].forEach(t=>{r.push(Af(e,"Library","Application Support",t,"Crashpad"))})}else if(vf()==="win32"){let e=bf();["Chromium","Google","Google Chrome Canary"].forEach(t=>{r.push(Af(e,"AppData","Local",t,"User Data","Crashpad","reports"))})}return r}function Lx(){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 wf=Gn(Cf(),"momentic","chromium"),KH=Gn(Cf(),"video"),kx=WH(Dx);kx.use(qH({provider:{id:"2captcha",token:Ba},visualFeedback:!0}));var YH=["--enable-crashpad","--crash-on-hang-threads=UI:18,IO:18"],XH=["--disable-dev-shm-usage","--no-first-run","--renderer-process-limit=3","--browser-test","--disable-site-isolation-for-policy","--disable-site-isolation-trials","--disable-backgrounding-occluded-windows","--disable-background-timer-throttling","--disable-renderer-backgrounding","--autoplay-policy=user-gesture-required","--disable-add-to-shelf","--disable-desktop-notifications","--use-fake-device-for-media-stream","--use-fake-ui-for-media-stream","--enable-logging=stderr","--log-level=2"],JH=["--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 Ux({baseUrl:r,logger:e,storage:t,enricher:n,userBrowserSettings:o,contextArgs:i,recordVideo:a,iconKnowledgeBase:l,callbacks: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=[...XH],d={headless:process.env.MOMENTIC_HEADFUL_BROWSER!=="true",handleSIGTERM:!1,chromiumSandbox:!1,channel:s},p={...i??{},geolocation:i?.geolocation||ao,locale:i?.locale||oo,timezoneId:i?.timezoneId||io,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??Nd,viewport:i?.viewport??Gt,serviceWorkers:"block",storageState:{cookies:[Lx()],origins:[]}};o.initialLocalStorage&&(p.storageState.origins=Object.entries(o.initialLocalStorage).map(([S,E])=>({origin:S,localStorage:Object.entries(E).map(([R,A])=>({name:R,value:A}))}))),process.env.MOMENTIC_CHROME_EXTRA_ARGS&&u.push(...process.env.MOMENTIC_CHROME_EXTRA_ARGS.split(","));let m=null,h,g,f={systemDevicePixelRatio:i?.deviceScaleFactor,recordVideo:a,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 S=kd();S.forEach(E=>{if(!Dl(E))return;["new","pending","completed"].forEach(A=>{let C=Gn(E,A);if(!Dl(C))return;let w=VH(C);for(let I=0;I<w.length;I++){let P=Gn(C,w[I]);Nx(P,{force:!0})}})}),S.forEach(E=>{Dl(E)||Rf(E,{recursive:!0});let R=Gn(E,`write-test-${Date.now()}`);Rf(R,{recursive:!0}),Nx(R,{recursive:!0,force:!0})}),u.push(...YH)}catch(S){e.warn({err:S},"Could not create Chrome crash report directory, not enabling crashpad")}o.disableGpu&&u.push(...JH);let y=o.localChromeExtensionPaths?.map(S=>S.startsWith("~")?Gn(Cf(),S.slice(1)):S);if(y?.length){if(s===void 0)throw new x("UserConfigurationError","Chrome extensions are only supported on Chromium and Google Chrome.");for(let A of y){let C=Gn(A,"manifest.json");if(!Dl(C))throw new x("UserConfigurationError",`Chrome extension path ${C} does not exist.`)}if(cn)throw new x("UserConfigurationError","Cannot use persistent browser context on Momentic Cloud");let S=Gn(wf,`momentic-session-${Date.now()}`);if(!Dl(S))try{Rf(S,{recursive:!0})}catch(A){throw new x("UserConfigurationError",`Failed to create browser cache directory. Please make sure you have sufficient permissions to create the ${wf} folder: ${A}`)}let E=[...u],R=y.map(A=>$H(A)).join(",");E.push(`--disable-extensions-except=${R}`),p?.deviceScaleFactor&&E.push(`--force-device-scale-factor=${p.deviceScaleFactor}`,`--device-scale-factor=${p.deviceScaleFactor}`),p.viewport&&E.push(`--window-size=${p.viewport.width},${p.viewport.height}`),h=await Dx.launchPersistentContext(Gn(wf,`momentic-session-${Date.now()}`),{...d,...p,ignoreDefaultArgs:["--disable-extensions","--disable-component-extensions-with-background-pages"],args:E,baseURL:r}),e.info({sharedContextOptions:p,sharedBrowserOptions:d,userBrowserSettings:o,chromeArgs:E,properties:f,baseUrl:r},"Browser initialization context args (persistent)"),g=h.pages()[0]}else{m=await kx.launch({...d,args:u});let S={...p,baseURL:r,recordVideo:a?{dir:KH}:void 0};h=await m.newContext(S),e.info({contextArgs:S,sharedBrowserOptions:d,chromeArgs:u,userBrowserSettings:o,properties:f,baseUrl:r},"Browser initialization context args (standard)"),g=await h.newPage()}cn&&await h.route("**",Nl);try{let S=m?.version();e.info({browserVersion:S},"Got browser version")}catch(S){e.warn({err:S},"Could not get browser version string")}return{browser:m,context:h,page:g,baseUrl:r,logger:e,storage:t,enricher:n,userBrowserSettings:o,viewport:p.viewport||Gt,properties:f,clientCallbacks:c,iconKnowledgeBase:l}}async function Fx(r){try{return await QH(r)}catch(e){r.logger.warn({err:e},"Failed to transform locator for Chakra click, continuing...");return}}async function QH({locator:r,logger:e}){let[t,n]=await r.evaluate(c=>[c.id,c.tagName.toLowerCase()],{timeout:ae}),o=await Hn(r,e),i=await r.boundingBox({timeout:ae});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:ae}),{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)},h=s._MOMENTIC_FEATURE_FLAGS?.[Ld],g=c.getAttribute(zn),f=!h&&g?Zr(g):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:ae});if(a.type==="error")throw new Error(a.error);let l=r.page().locator(a.selector);return await l.waitFor({state:"visible",timeout:ae}),e.info({parentElementResult:a,originalElementDisplayString:o},`Redirected click to parent element with selector: ${a.selector}`),{locator:l,relativePoint:a.relativePoint}}var zx=["date","datetime-local","month","time","week"],Bx={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 Hx(r){try{await G(ZH(r),{milliseconds:oe})}catch(e){r.logger.warn({err:e},"Failed to transform native datetime input, continuing...")}}async function ZH({root:r,text:e,options:t,logger:n,callbacks:o}){let i=(await yt({root:r,fn:()=>document.activeElement?.getAttribute("type")??"",timeout:ae,arg:void 0,waitForPageLoad:o.waitForPageLoad,codePath:"transforming native datetime input"})).toLowerCase();if(!Bx[i])return;Bx[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 ur}from"zod";var Gx=ur.object({doubleClick:ur.boolean().optional(),rightClick:ur.boolean().optional(),force:ur.boolean().optional(),waitForDownload:ur.boolean().optional(),delayMs:ur.number().optional(),downloadTimeoutMs:ur.number().optional(),relativePosition:ur.object({x:ur.number(),y:ur.number()}).optional()}),$Pe=ur.object({repeat:ur.number().optional(),convertMeta:ur.boolean().optional().describe("misleading name due to backcompat. converts keyshortcuts + meta/control to platform-specific combos. defaults to true"),delayMs:ur.number().optional()});async function Ud({locator:r,callbacks:e,logger:t,timeoutMs:n=ae}){try{await xf(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 h=d.getBoundingClientRect();return!(!h.height||!h.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 G(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 xf(r,e=ae){let t=await r.state.getRoot();await yt({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 _f(r){let e=!!r.browserCallbacks.state.userBrowserSettings.visualActions;return Ci({action:"clicking element",targetingResult:r.targetingResult,logger:r.logger,retryTimeoutMs:r.retryTimeoutMs,callbacks:r.browserCallbacks,func:async t=>Vx({...r,targetingResult:t,useVisualClick:e})})}async function nG(r,e){let{redirectionAttempts:t=0}=e;if(t>=2)throw r;try{return await oG(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 oG(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:ae});if(!i)throw r;let a=o.page().locator(`[for=${JSON.stringify(i)}]`);return await a.waitFor({state:"visible",timeout:ae}),t.warn({err:r},"Attempting locator redirection due to input being covered by label"),Vx({...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 iG(r){let{logger:e,targetingResult:t,position:n,options:o}=r,i=Gx.safeParse(o),a=Date.now(),{clickX:l,clickY:c,reason:s}=await lG({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 aG(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 Fx({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:oe,position:a,delay:n?.delayMs??25,force:l}):await i.click({button:n?.rightClick?"right":"left",timeout:oe,position:a,delay:n?.delayMs??25,force:l})}catch(s){let u=s;if(uG(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..."),nG(u,{...r,targetingResult:{...i,locator:i}})}return{locatorSource:c}}async function Vx(r){let{options:e,logger:t,browserCallbacks:n,controllerCallbacks:o,useVisualClick:i,targetingResult:a}=r,l;e?.waitForDownload&&(l=(async()=>{let u=e.downloadTimeoutMs??nf;try{return await a.locator.page().waitForEvent("download",{timeout:u})}catch(d){return d instanceof rG.TimeoutError?new x("ActionFailureError",`Download did not complete in ${u}ms`):new x("ActionFailureError",`Download failed: ${d.message}`)}})());try{await Ud({locator:a.locator,callbacks:n,logger:t,timeoutMs:ae})}catch(u){t.warn({err:u},"Error highlighting locator in click, continuing...")}let c,s;if(i?c=await iG(r):s=(await aG(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 G(l,{milliseconds:e.downloadTimeoutMs??nf});if(u instanceof Error)throw u;return{downloadedFile:await cG(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 sG(r){let e=await r.locator.boundingBox({timeout:oe});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 lG({options:r,targetingResult:e,position:t}){let n,o,i;if(r?.relativePosition){let s=await e.locator.boundingBox({timeout:oe}),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:oe});n=(s?.x??0)+t.x,o=(s?.y??0)+t.y,i="predefined position"}else{let[s,u]=await sG(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 cG(r,e,t){t.info("Download detected, saving file to disk");let n=await r.path(),o=gf(r.suggestedFilename()),i=e();await r.saveAs(tG(i,o)),jx(n,{force:!0}),setTimeout(()=>{jx(i,{recursive:!0,force:!0})},5*60*1e3);let a=yx(eG(i),o);return t.info({uri:a,downloadFolder:i},"Saved download to isolated folder"),a}function uG(r){return r.message.includes("locator.click: Timeout")&&r.message.includes("click action done")}import{platform as dG}from"os";var pG={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 mG(){let r=dG();return r==="win32"?"win32":r==="darwin"?"darwin":"linux"}function $x(r){return JSON.stringify(r.split("+").sort())}function Fd(r,e){let t=mG(),n=$x(r);for(let o of Object.values(pG))if(Object.values(o).some(i=>$x(i)===n))return o[t];return process.platform==="darwin"&&!e?r=r.replaceAll("Control","Meta"):r=r.replaceAll("Meta","Control"),r}async function If({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 yt({root:r,fn:([d,p,m,h])=>window.scrollTo(window.scrollX+(d??window.innerWidth)*m,window.scrollY+(p??window.innerHeight)*h),arg:[t,o,s,u],waitForPageLoad:l.waitForPageLoad,timeout:Ce,codePath:"scrolling page"});else{let d=e.viewportSize()||Gt,p=await yt({root:e,fn:()=>document.body.scrollHeight,arg:void 0,waitForPageLoad:l.waitForPageLoad,timeout:Ce,codePath:"computing page height"}),[m,h,g]=await yt({root:e,fn:()=>{let f=document.activeElement;if(!f)return[void 0,void 0,void 0];let y=f.getBoundingClientRect();return[f.scrollTop,y.x,y.y]},arg:void 0,waitForPageLoad:l.waitForPageLoad,timeout:Ce,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<Ce;){a?.throwIfAborted();let y=await G(e.evaluate(()=>document.body.scrollHeight),{milliseconds:ae}),[S,E,R]=await G(e.evaluate(()=>{let A=document.activeElement;if(!A)return[void 0,void 0,void 0];let C=A.getBoundingClientRect();return[A.scrollTop,C.x,C.y]}),{milliseconds:ae});if(y===p&&S===m&&E===h&&R===g)break;p=y,m=S,h=E,g=R,await ie(At)}}catch(f){c.warn({err:f},"Failed to wait for scroll to complete, continuing...")}}}async function Mf(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 ie(At)}throw new Error(`Failed to get tab titles after all retries: ${n?.message}`)}import{randomUUID as bG}from"crypto";import{cloneDeep as Lf}from"lodash-es";function Mo(r,e){let t=r.findIndex(n=>n===e);if(!(t===-1||!r[t+1]))return r[t+1]}import{createHash as hG}from"crypto";var gG="v1";function Pf(r,e){if(r.tagName.toLowerCase()==="svg"&&!SG(r))try{let t=Wx(r,e),n=fG(JSON.stringify(t));return{version:gG,json:t,hash:n}}catch{return}}function fG(r){return hG("md5").update(r).digest("hex")}function Wx(r,e){let t=r.tagName.toLowerCase(),n=yG(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=Wx(a,e);l&&o.children.push(l)}}return o}function SG(r){let e=r.computedStyles.display,t=r.computedStyles.visibility,n=r.computedStyles.opacity;return e==="none"||t==="hidden"||n==="0"}function yG(r){let e={},t=r.attributes;for(let n of Object.keys(t))Dr.visualAttributesForSvgSerialization.includes(n)&&(e[n]=t[n]);return t.id&&r.tagName.toLowerCase()!=="svg"&&(e.id=t.id),e}var xi={r:147,g:196,b:125,a:.55},Kx={showRulers:!1,showStyles:!1,showExtensionLines:!1,contrastAlgorithm:"aa",contentColor:xi,paddingColor:xi,borderColor:xi,marginColor:xi,eventTargetColor:xi,shapeColor:xi,shapeMarginColor:xi,showInfo:!0,showAccessibilityInfo:!0};function Yx({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=EG({allDocuments:i,stringConstants:o,computedStylesToFetch:t,devicePixelRatio:e,frameIndex:u,backendIdToNode:a,frameIndexToIframeNode:l,logger:n});c.roots.push(d)}),c}function EG({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,I)=>{u[w]=I});let d=s.styles,p=s.bounds??[],m=c.nodes,h=m.contentDocumentIndex??{index:[],value:[]},g=m.backendNodeId??[],f=m.attributes??[],y=m.parentIndex??[],S=m.nodeName??[],E=m.nodeType??[],R=m.pseudoType??{index:[],value:[]},A=m.inputChecked??{index:[]},C=e[c.frameId];for(let w=0;w<g.length;w++){let I=g[w],P=E[w],X=f[w]??[],q=y[w]!==void 0&&y[w]>=0?y[w]:void 0,k=q!==void 0?g[q]:void 0,ee=k!==void 0?a[k]:void 0,z=R.index.indexOf(w),j=z!==-1?e[R.value[z]]:void 0,he=u[w],$;he?$=p[he]??[]:$=[];let rt=S[w]!==void 0?e[S[w]]?.toLowerCase():void 0;if(!rt){l.warn({backendNodeId:I,frameId:C,frameIndex:o,nodeBounds:$},"DOM node has no tag name");continue}let Ne={backendNodeId:I,psuedoType:j,nodeType:P,frameIndex:o,parentFrameId:C,ownedFrameId:void 0,bounds:{x:$[0]??null,y:$[1]??null,width:$[2]??null,height:$[3]??null},computedStyles:{},attributes:{},parentBackendNodeId:k??null,tagName:rt,parent:ee??void 0,childrenBackendIds:[],momenticIgnored:void 0,mPathSelector:void 0};ee&&ee.childrenBackendIds.push(I);let ct=h.index.indexOf(w);if(ct!==-1){let J=h.value[ct];i[J]=Ne;let we=r[J]?.frameId;Ne.ownedFrameId=we!==void 0?e[we]:void 0}for(let J of Object.keys(Ne.bounds)){let we=J;Ne.bounds[we]!==null&&(Ne.bounds[we]/=n)}let kt=he!==void 0?d[he]??[]:[];for(let J=0;J<kt.length&&!(J>=t.length);J++){let we=kt[J];if(we===void 0||isNaN(we))continue;let Er=e[we];if(Er===void 0)continue;let Kn=t[J];Ne.computedStyles[Kn]=Er}for(let J=0;J<X.length;J+=2){let we=X[J],Er=X[J+1];if(!we||!Er)continue;let Kn=e[we],Yn=e[Er];!Kn||!Yn||(Ne.attributes[Kn]=Yn)}A.index.includes(w)&&(Ne.attributes.checked="true"),a[Ne.backendNodeId]=Ne}return a[g[0]]}function Of(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=`${Of(t,e)}${a}`}return r.mPathSelector=n,n}function qx(r,e){return r.parentBackendNodeId!==null?e.backendIdToNode[r.parentBackendNodeId]:r.frameIndex===0?void 0:e.frameIndexToIframeNode[r.frameIndex]}var TG=["html","#document","#document-fragment"];function Xx({node:r,domGraph:e}){let t=[],n=r,o=qx(r,e);if(!o)return[r.tagName];let i=()=>{if(n=o,o=qx(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++,TG.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 Jx(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 Qx(r,e){await r.send({method:"DOM.getDocument",params:{depth:0},timeout:Ce});let t=await r.send({method:"DOM.requestNode",params:{objectId:e},timeout:Ce}),o=(await r.send({method:"DOM.getAttributes",params:{nodeId:t.nodeId},timeout:Ce})).attributes,i=Mo(o,zn);if(!i)throw new Error(`Could not find attribute ${zn} for object ${e}`);return i}var vG=["focusable","keyshortcuts","controls","live","relevant","orientation"],AG=["selected","readonly","modal","required","invalid"],RG=["id","name","role","content"],Zx=["absolute","fixed","sticky"],wG=["i"],CG=["path"],xG=["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"],r_=["ariaHiddenElement","ariaHiddenSubtree","hiddenByChildTree","inertElement","inertSubtree","notRendered","notVisible"],n_=["activeAriaModalDialog","activeFullscreenElement","activeModalDialog"],_G=["menulistpopup","statictext","inlinetextbox"],IG=80,e_=100,o_=50,kf=["StaticText","ListMarker","RootWebArea","LineBreak","emphasis","::before","::after"],MG=["cite"],PG={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"]},OG={name:!0,value:!0,title:!0,alt:!0,placeholder:!0,checked:!0,selected:!0,contenteditable:!0},t_={indentLevel:0},Nf=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<o_?t:""),this.role=this.role||(e.domNode.attributes.role??""),kG(this.properties,e.domNode,e.importantProperties)}FG(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&&CG.includes(this.domNode.tagName)||this.domNode?.computedStyles.display==="contents"||this.ignoredReasons.some(n=>n_.includes(n)))return!1;if(e){if(Object.keys(this.domNode?.attributes??{}).some(o=>c_(o,e)))return!0;let n=this.domNode?.attributes.class?.split(" ");if(n&&n.length>0&&n.some(o=>u_(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&&wG.includes(this.domNode.tagName)||xG.includes(this.role.toLowerCase())||this.role.toLowerCase()==="inlinetextbox"&&this.tagName||!this.properties.hidden&&(this.properties.focusable||this.properties.settable)||Dr.alwaysInterestingTruthyPropertyNames.some(n=>!!this.properties[n]))return!0;let t=this.properties.class;return typeof t=="string"&&t.split(" ").some(n=>l_(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=t_){let t=Object.assign({},t_,e),{indentLevel:n,noChildren:o,noProperties:i,noId:a,noContent:l,condensedMode:c}=t,s=Lf(this.properties),u=" ".repeat(n),d=this.role||"",p=this.tagName??"unknown",m=this.name;d==="heading"&&m==="heading"&&(m=""),this.nameSources?.find(A=>!A.superseded&&A.type==="contents")&&this.children.length>0&&(m="");let g=this.nameSources?.find(A=>!A.superseded);if(g&&!g.nativeSource&&g.type==="relatedElement"){let A=g.attributeValue?.relatedNodes??[];A.length===1&&A[0].text&&A[0].text===m&&(m="")}let f=kf.includes(this.role)||MG.includes(this.tagName||"");if(this.role==="StaticText"||this.role==="ListMarker")return`${u}${m}
|
|
4044
|
+
`;let y=`${u}<${p}`;!a&&!f&&(y+=` id="${this.id}"`);let S=l??!1;if((s.multiline||s.contenteditable)&&this.children.length>0&&(S=!0),d&&d!=="generic"&&d!==p&&!(PG[d]??[]).includes(p)&&(y+=` role=${JSON.stringify(d)}`),m&&(y+=` name=${JSON.stringify(m)}`),this.content&&!S&&(y+=` content=${JSON.stringify(this.content)}`),this.flagNotActionableNodes&&this.tagName!=="#document"&&this.isNotActionable()&&(y+=` ${Dr.ineligibleElementAttribute}`),this.shouldSerializeBounds()&&this.domNode?.bounds){let A=this.domNode.bounds,C=Math.round(A.x??0),w=Math.round(A.y??0),I=Math.round((A.x??0)+(A.width??0)),P=Math.round((A.y??0)+(A.height??0));y+=` bounds=[${C} ${w} ${I} ${P}]`}let E=Date.now();if(Object.keys(s).length>0&&!i){if(Date.now()-E>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(([A,C])=>{if(!vG.includes(A)){{if(AG.includes(A)&&(!C||C==="false"))return;if(A==="value"&&S&&(s.type==="text"||this.role==="textbox"))return;if(A==="level"&&`${C}`=="1")return;if(A==="url"&&s.src&&p==="img")return;if(A==="url"&&s.href&&p==="a")return;if(A==="editable"&&C==="plaintext")return;if(A==="type"&&C===p)return;if(c&&!OG[A])return}typeof C=="string"?y+=` ${A}="${it(C,e_,!0)}"`:typeof C=="boolean"?C?y+=` ${A}`:y+=` ${A}={false}`:typeof C<"u"&&(y+=` ${A}={${it(JSON.stringify(C),e_,!0)}}`)}})}if(p==="::before"||p==="::after"){let A="";for(let C of this.children)A+=C.serialize({...e,indentLevel:n,neighbors:0});return A}let R=e.maxLevel!==void 0&&n/2>=e.maxLevel;if(this.children.length===0||o||R)y+=` />
|
|
4046
4045
|
`;else{let A="";for(let w of this.children)A+=w.serialize({...e,indentLevel:n+2,neighbors:0});let C=A.trim();C.length<=IG&&!C.includes(`
|
|
4047
|
-
`)?
|
|
4048
|
-
`:
|
|
4046
|
+
`)?y+=`>${C}</${p}>
|
|
4047
|
+
`:y+=`>
|
|
4049
4048
|
${A}${u}</${p}>
|
|
4050
4049
|
`}if(e.neighbors!==void 0&&e.neighbors>0&&this.parent){let A=this.parent.children.findIndex(I=>I.id===this.id),C=A>0?this.parent.children[A-1]?.serialize({...e,neighbors:0}):"",w=A<this.parent.children.length-1?this.parent.children[A+1]?.serialize({...e,neighbors:0}):"";return`${C||""}
|
|
4051
|
-
${
|
|
4052
|
-
${w||""}`}return S}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:Lf(this.internalProperties),importantProperties:this.importantProperties,parentFrame:this.parentFrame,flagNotActionableNodes:this.flagNotActionableNodes});return e.tagName=this.tagName,e.dataMomenticId=this.dataMomenticId,e.properties=Lf(this.properties),e}},Df=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(kf.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,h=u-m;for(let g of c.children){let f=s+2,S=i(g,f).length;if(h<S)break;let{clone:y,used:E}=a(g,f,h);if(E>h)break;d.children.push(y),y.parent=d,m+=E,h-=E}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 LG(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 NG(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?(Vc({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?(Vc({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 i_({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:h,logger:g,callId:f}){if(!e&&r.parentId)throw new Error(`Got no parent for accessibility node ${r.nodeId}: ${JSON.stringify(r)}`);let S=(j,he={})=>{},y=r.backendDOMNodeId,E=_G.includes(r.role?.value?.toLowerCase()??"");if(!E&&y===void 0)return S("Filtering out node since it doesn't exist in the DOM"),[];let R=y?i.backendIdToNode[y]:void 0;if(!E&&!R)try{let j=await G(h.send({method:"DOM.describeNode",params:{backendNodeId:y}}),{milliseconds:750,fallback:()=>{g.debug("Timeout getting node from CDP while processing a11y tree")}});if(j&&j.node.nodeName.toLowerCase()==="slot"&&j.node.distributedNodes?.length)g.debug({redirectedDomNode:R,parentAXNode:e?.getNodeOnlySerializedForm(),originalAXNode:r,cdpResult:j},"Redirecting node to assigned slot");else return S("Filtering out node since it doesn't exist in the DOM",{cdpResult:j}),[]}catch(j){return S("Filtering out node since it doesn't exist in the DOM",{err:j}),[]}if(R&&e&&s&&u&&r.backendDOMNodeId&&!NG(R,u,g,f))return R.momenticIgnored=!0,[];if(R&&R.computedStyles.display==="none")return R.momenticIgnored=!0,[];if(R&&R.computedStyles.opacity==="0"&&c!==!0){if(c==="inputs-only"&&R.tagName.toLowerCase()!=="input")return R.momenticIgnored=!0,[];if(c===!1)return R.momenticIgnored=!0,[]}let A=r.name?.value?typeof r.name.value=="string"?r.name.value:`${r.name.value}`:"",C=r.value?.value?typeof r.value.value=="string"?r.value.value:`${r.value.value}`:"",w=new Nf({domNode:R,id:parseInt(r.nodeId),role:r.role?.value||"",name:A,nameSources:r.name?.sources,content:C,properties:r.properties,children:[],ignoredReasons:r.ignoredReasons?.filter(j=>(m??r_).includes(j.name)||n_.includes(j.name))??[],pathFromRoot:(e?`${e.pathFromRoot} `:"")+LG(r),backendNodeID:r.backendDOMNodeId,ignoredByCDP:r.ignored,internalProperties:{inCodeMirrorEditor:e?.internalProperties?.inCodeMirrorEditor},importantProperties:p,parentFrame:n.type==="root"?void 0:n,flagNotActionableNodes:l}),I=n,P=a[t],X=t;if(R?.tagName.toLowerCase()==="iframe"&&R.ownedFrameId){let j=n.childFrames.find(rt=>rt.frameId===R.ownedFrameId),he=o[j?.frameId??""]?.root,$=a[j?.frameId??""];if(j&&he&&$){r.childIds&&r.childIds.length>0&&g.debug("Replacing existing node's children with children from the iframe");let rt=he;r.childIds=rt.childIds,I=j,P=$,X=j.frameId}}let q=R?.childrenBackendIds?.length??0,k=(r.childIds??[]).filter(j=>!!P.get(parseInt(j))).length;if(q>k){let j=r.childIds?.map($=>P.get(parseInt($))).filter(Boolean).map($=>$?.backendDOMNodeId).filter($=>$!==void 0)??[],he=0;for(let $ of R?.childrenBackendIds??[]){if(j.includes($)){he=(r.childIds?.findIndex(J=>P.get(parseInt(J))?.backendDOMNodeId===$)??0)+1;continue}let rt=i.backendIdToNode[$];if(!rt||rt?.tagName.toLowerCase()!=="svg")continue;let Ne=Math.floor(-1*Math.random()*1e7),ct={nodeId:Ne.toString(),parentId:r.nodeId,ignored:!1,backendDOMNodeId:$,frameId:X,role:{type:"string",value:"graphics-symbol"}};P.set(Ne,ct),r.childIds||(r.childIds=[]),r.childIds.splice(he,0,Ne.toString()),he++}}if(r.childIds?.length===1&&R){let j=P.get(parseInt(r.childIds[0])),he=j?.role?.value,$=R.childrenBackendIds;if(j&&he==="StaticText"&&$.length===1){let rt=i.backendIdToNode[$[0]];if(rt?.tagName?.toLowerCase()==="span"){let Ne=Math.floor(-1*Math.random()*1e7).toString(),ct={nodeId:Ne,parentId:r.nodeId,ignored:!1,backendDOMNodeId:rt.backendNodeId,frameId:X,childIds:[j.nodeId]};j.parentId=Ne,P.set(parseInt(Ne),ct),r.childIds=[Ne]}}}for(let j of r.childIds??[]){if(!j)continue;let he=P.get(parseInt(j));if(!he)continue;let $=await i_({node:he,parent:w,domGraph:i,axGraph:o,frameId:X,frameContext:I,inputNodeMap:a,cdpClient:h,logger:g,callId:f,filterByViewport:s,showZeroOpacityElements:c,importantProperties:p,viewportDetails:u,useMPaths:d,flagNotActionableNodes:l});$.length&&(w.children=w.children.concat($))}if(w.role==="StaticText"&&(w.children=[]),w.children.length===1&&w.children[0].role==="StaticText"){let j=w.name,he=w.children[0]?.name;(j===he||!he)&&(w.children=[])}let ee=[];for(let j=w.children.length-1;j>=0;j--){let he=w.children[j];if(he.role!=="StaticText"){ee.push(he);continue}if(j===0||w.children[j-1].role!=="StaticText"){ee.push(he);continue}w.children[j-1].name+=he.name}if(w.children=ee.reverse(),!w.isInteresting(p)&&r.parentId)return R&&(R.momenticIgnored=!0),w.children;for(let j of w.children)j.parent=w;return UG(w),R&&d&&Of(R,i),[w]}function a_({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:kf.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=Pf(d,i),m=p?c[p.hash]:void 0,h=m?m.description:void 0;m&&(r.properties["data-momentic-description"]=h)}for(let p of r.children)s=a_({node:p,a11yIdNodeMap:e,dataMomenticIdMap:t,logger:n,callId:o,startId:s,useMPaths:a,domGraph:i,selectorToNodeMap:l,iconKnowledgeBase:c});return s}async function s_({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 h=t??"root",g=r[h]?.root;if(!g)throw new Error("A11y tree has no root");let f=bG(),S=w=>{let I=w.allNodes.filter(X=>!X.ignoredReasons?.find(k=>(m??r_).includes(k.name))),P=new Map;return I.forEach(X=>{P.set(parseInt(X.nodeId),X)}),P},y={};Object.entries(r).forEach(([w,I])=>{y[w]=S(I)});let E=await i_({node:g,domGraph:e,parent:null,inputNodeMap:y,axGraph:r,frameId:h,frameContext:d,cdpClient:o,logger:n,callId:f,showZeroOpacityElements:a,importantProperties:c,filterByViewport:i,viewportDetails:s,useMPaths:u,flagNotActionableNodes:l,allowedA11yIgnoreReasonsOverride:m});if(E.length>1)throw new Error(`Something went horribly wrong processing the a11y tree, we got: ${JSON.stringify(E)}`);if(E.length===0)throw new Error("There are no accessible elements on this page or frame. Are you sure this website loads properly?");let R={},A={},C={};return a_({node:E[0],a11yIdNodeMap:R,dataMomenticIdMap:A,selectorToNodeMap:C,domGraph:e,logger:n,callId:f,useMPaths:u,iconKnowledgeBase:p}),new Df(E[0],R,A,C)}function DG(r,e,t,n){if(r==="class"){if(t.tagName?.toLowerCase()==="svg")return e.split(" ").filter(a=>a.length<o_&&!Dr.bannedClassSubstrings.some(l=>a.includes(l))).slice(0,3).join(" ");let o=e.split(" "),i=[];for(let a of o)if(l_(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 kG(r,e,t){if(!e)return;Object.entries(e.attributes).forEach(([a,l])=>{let c=r[a]||a.startsWith("aria")||RG.includes(a);if((Dr.relevantElementAttributes.includes(a)||c_(a,t))&&!c){let u=DG(a,l,e,t);u!==null&&(r[a]=u)}});let n,o=[];if(e.computedStyles.position&&Zx.includes(e.computedStyles.position))n=e.computedStyles.position;else if(e.attributes.style){for(let a of Zx)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 UG(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(it(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(h=>h.tagName==="th");if(m.length){if(i=m.map(h=>it(h.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,h)=>{m.tagName!=="th"&&(m.properties["col-index"]||(m.properties["col-index"]=h+1),p&&(m.properties.col||(m.properties.col=i[h])))})}}}function FG(r){let e=r.properties.class,t=typeof e=="string"&&e.includes("cm-content");r.internalProperties.inCodeMirrorEditor=r.internalProperties?.inCodeMirrorEditor||t}function l_(r,e){if(e&&u_(r,e))return!0;if(Dr.bannedClassSubstrings.some(t=>r.includes(t)))return!1;if(Dr.alwaysInterestingClassNames.includes(r))return!0;for(let t of Dr.alwaysInterestingClassPrefixes)if(r.startsWith(t))return!0;return!1}function c_(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 u_(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 Bd=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 G(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 ie(At),c=d}if(!l)throw c;let s=new r(l,e,t,n,o);try{await G(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 e.send("Accessibility.enable"),await e.send("Page.enable"),await e.send("DOM.enable"),await e.send("Overlay.enable"),await e.send("DOMSnapshot.enable"),await e.send("CSS.enable")}async send({method:e,params:t,timeout:n=this.defaultTimeoutMs,timeoutMsg:o}){for(;this.cdpInitializingPromise;)await G(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 G(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 G(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 G(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 G(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 za="<empty>";function BG(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 p_(r){let e=r.adFrameStatus?.adFrameType;return e==="child"||e==="root"||BG(r.url)}async function zG(r,e){let t=await r.send({timeout:oe,method:"DOM.getFrameOwner",params:{frameId:e}}),o=(await r.send({timeout:oe,method:"DOM.pushNodesByBackendIdsToFrontend",params:{backendNodeIds:[t.backendNodeId]}})).nodeIds[0],a=(await r.send({timeout:oe,method:"DOM.describeNode",params:{backendNodeId:t.backendNodeId}})).node;return a.nodeId=o,a}async function Ha({cdpClient:r,page:e,logger:t}){let n={type:"root",childFrames:[],page:e},o=[],[i,a]=await Promise.all([r.send({timeout:oe,method:"Page.getFrameTree",params:{}}),r.send({timeout:oe,method:"DOM.getDocument",params:{depth:0}})]),s=(i.frameTree.childFrames??[]).map(async(d,p)=>{if(p_(d.frame))return null;try{return await m_({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 m_({cdpClient:r,rawFrameTree:e,indices:t,parent:n,warnings:o,logger:i}){let a=e.frame.id,l=await zG(r,a),c=l.attributes??[],s=null,u=[];for(let h of["src","name","id","title","srcdoc","sandbox"]){let g=Mo(c,h);g&&(u.push(`${h}=${JSON.stringify(g)}`),h==="src"&&(s=g))}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(h,g)=>{if(p_(h.frame))return null;try{return await m_({cdpClient:r,rawFrameTree:h,indices:[...t,g],parent:d,warnings:o,logger:i})}catch(f){return o.push(`Failed to get child frame (child ${g} of frame with url ${e.frame.url}): ${f}`),null}});return d.childFrames=(await Promise.all(m)).filter(h=>h!==null),d}async function HG(r){try{return await r.owner().count()===1}catch{return!1}}async function GG(r){try{return await r.count()===1}catch{return!1}}async function wn(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,za]){let p=o.frameLocator(d===za?"iframe":`iframe[${d}]`);if(await HG(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,za]){let u=o.locator(s===za?"iframe":`iframe[${s}]`);if(await GG(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:ae}),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 d_(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 h_({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===za?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===za?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 wn(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=d_(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 wn(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=d_(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 wn(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 wn(n,r)).frame,handle:n,mPathSelectorTokens:t.mPathSelectorTokens,frameTree:e},logs:i};throw i.push(`Found ${a.length} frames with indices ${t.indices}`),new an("Failed to find the iframe that previously contained this element",[{type:"AUTO_FRAME",matched:!1,logs:i}])}function zd(r){return r.type==="auto"?JSON.stringify({type:"auto",frameId:r.handle.frameId}):JSON.stringify(r)}function Uf(r){for(;r.parent.type==="frame";)r=r.parent;return r.parent}function g_(r){let e=Uf(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 f_(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 S_({frame:r,logger:e,signal:t}){let n;try{n=await r.frameElement(),await jG({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 jG({frameElementHandle:r,logger:e,signal:t}){let n=await r.boundingBox();await Js({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:Ce,codePath:"scrollIframeIntoView",signal:t}),e.info({oldBb:n,newBb:await r.boundingBox()},"Successfully scrolled iframe into view")}async function y_({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(h=>h.url());i.debug({frameUrl:s,...r},"Passive click event captured on element");let p,m;if(s)try{let h=await n.frameElement();p=await G(h?.boundingBox(),{milliseconds:oe})??void 0;let g=await t.constructIframeRegex({urls:d,srcs:[],desiredUrl:s});if(g.urlRegex)m={type:"url",url:`/${g.urlRegex}/`};else throw new Error(`Got no url regex options: ${JSON.stringify(g)}`)}catch(h){i.warn({err:h},"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(h){i.error({err:h},"Failed to transform passive click action")}})()}import{randomUUID as Cn}from"crypto";import VG from"js-beautify";var $G=["Dead"],Hd=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:Cn(),type:"PRESET_ACTION",command:Pn(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 g=Pn(i);a={id:Cn(),type:"PRESET_ACTION",command:{...g,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 g=Pn(i);a={id:Cn(),type:"PRESET_ACTION",command:{...g,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 g=Pn(i);a={id:Cn(),type:"PRESET_ACTION",command:{...g,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:je(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=VG.html(d,{indent_size:1,indent_with_tabs:!1,preserve_newlines:!1}),d=cx(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,...je(this.logger)}})).phrase}catch(g){this.logger.error({err:g},"Error generating reverse mapping description"),p=l}let m=this.recordedSteps.get(u)?.step??a,h=m?.command;h&&"target"in h&&h.target?(h.target={type:"description",elementDescriptor:p},this.callbacks.onStepRecorded({...m,command:h},u)):this.logger.warn("Could not find existing command to update after description mapping")}recordKeystroke(e){let{key:t,combinable:n}=e;if($G.includes(t)||this.signal.aborted)return;let o="normal";t.length>1&&(o="special");let i;if(o==="normal"){let d=Pn("TYPE");i={id:Cn(),type:"PRESET_ACTION",command:{...d,target:void 0,value:t,clearContent:!1}}}else{let d=Pn("PRESS");i={id:Cn(),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:Cn(),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:Cn(),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=Pn(s);u.deltaY=Math.abs(i);let d={id:Cn(),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=Pn(s);u.deltaX=Math.abs(i);let d={id:Cn(),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 Ff}from"zod";var WLe=Ff.object({type:Ff.literal("url"),url:Ff.string()});var Gd=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 h=m[0]?.trim(),g=m[1]?.trim();if(h===void 0||g===void 0){this.logger.warn({style:p},"Invalid style property passed to importantStyles");continue}this.computedStylesToFetch.includes(h)||this.computedStylesToFetch.push(h)}}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=Uf(e),{frame:o,mPathSelectorTokens:i}=await wn(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 Ha({cdpClient:this.cdpClient,page:t,logger:this.logger}),{resolution:o,logs:i}=await h_({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(zd(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:zd(this.frameConfig),cacheTime:Date.now(),frameTree:this.frameConfig.frameTree,mPathSelectorTokens:this.frameConfig.mPathSelectorTokens},await S_({frame:n.frame,logger:e,signal:t}),this.activeFrameCache=n,n}async executeFunctionInAllFrames(e,t){let n=this.pageGetter(),o=await Ha({cdpClient:this.cdpClient,page:n,logger:this.logger}),i=[G(n.evaluate(e,t),{milliseconds:Ce})],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(wn(c,n).then(({frame:u})=>G(u.evaluate(e,t),{milliseconds:Ce})).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 Ha({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 kr({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 kr({fn:()=>Ha({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 kr({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 kr({fn:()=>this.getDOMTree({devicePixelRatio:e.devicePixelRatio??1,signal:o,logger:n}),codePath:"domFetch",logObject:t,signal:o,logger:n}),u=await kr({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 kr({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:dn,filterByViewport:!1,flagNotActionableNodes:!1}),Math.random()<.1){let n=this.lastA11yTreeRoot?.serialize();this.logger.debug({tree:n&&n.length>4e5?"REDACTED_DUE_TO_SIZE":n},"Refreshed a11y tree during recording")}}async getLocatorFromA11yNode({page:e,root:t,node:n}){if(n.backendNodeId===void 0)throw new Error(`Node with a11y id ${n.id} has no backend node ID: ${n.getNodeOnlySerializedForm()}`);if(this.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=Xx({node:o,domGraph:this.domGraph});return Jx(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:Ce});if(!n||!n.object.objectId)throw new Error(`Could not resolve backend node ${t}`);let o;try{o=await Qx(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(Zr(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 Ha({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 ie(At,t)}finally{c++}if(a)return{source:"url",frame:a.frame,handle:a.handle,frameIdentifierStringified:zd(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=Mo(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 wn(l,o)});break}}else if(n.trim()===d.trim()){a.push({handle:l,matchType:"url",...await wn(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 s_({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 wn(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 yt({root:e,fn:i=>window.addIdsToElement?.(document.body,i),arg:t,timeout:Ce,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(Mo(t,"aria-hidden")==="true")return{shouldUnroll:!1,reason:"aria-hidden"};let n=Mo(t,"style");if(n?.includes("display: none")||n?.includes("visibility: hidden"))return{shouldUnroll:!1,reason:"hidden CSS style"};await this.cdpClient.send({timeout:oe,method:"DOM.pushNodesByBackendIdsToFrontend",params:{backendNodeIds:[e.backendNodeId]}});let[o,i]=await Promise.all([this.cdpClient.send({timeout:oe,method:"DOM.getBoxModel",params:{backendNodeId:e.backendNodeId}}),this.cdpClient.send({timeout:oe,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 kr({fn:()=>this.getRawA11yTreeForFrame({frameId:t,timeoutMs:this.pageLoadTimeoutMs,logTimings:o}),codePath:"a11y-tree-fetch-root",logObject:o,logger:i});break}catch(h){c=h,i.warn({err:h},"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:g}=await this.decideChildFrameUnrollEligibility({handle:m,warnings:l});if(!g)continue}catch(g){if(g.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: ${g}`)}d.push(...m.childFrames);let h=async()=>{try{let g=await kr({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]=g}catch(g){i.warn({err:g,url:m.url,src:m.src},`Error getting raw a11y tree for child frame ${m.frameId}, continuing...`)}};p.push(h())}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 kr({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 kr({fn:()=>this.cdpClient.send({method:"Accessibility.getRootAXNode",params:{frameId:e??void 0},timeout:Ce}),codePath:"cdp-get-root-ax-node",logObject:n,logger:this.logger})).node.backendDOMNodeId;o=(await kr({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:oe}),!o||!o.documents.length)throw new Error("Got empty DOM tree")}catch(l){await ie(At,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 Yx({snapshot:o,devicePixelRatio:e,computedStylesToFetch:this.computedStylesToFetch,logger:n})}constructIframeRegexAsync(e,t){if(t.frameSrcRegex||t.frameUrlRegex)return;let n=g_(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 Bf(r){let e=[],t="";for(let n of r)n==="+"&&t?(e.push(t),t=""):t+=n;return e.push(t),e}var Ur=class r{static USER_AGENT=Nd;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;videos=[];baseUrl;constructor({storage:e,enricher:t,browser:n,context:o,page:i,baseUrl:a,logger:l,userBrowserSettings:c,viewport:s,properties:u,clientCallbacks:d,iconKnowledgeBase:p}){if(Ab(c),this.storage=e,this.enricher=t,this.browser=n,this.context=o,this.page=i,this.baseUrl=a,this.logger=l,this.userControlledBrowserSettings=c,this.viewport=s,this.properties=u,this.clientCallbacks=d,u.recordVideo){let m=this.page.video();m&&this.videos.push(m)}this.iconKnowledgeBase=p}registerAbortSignal(e){this.abortSignal=e}async initialize({grantPermissions:e,runInitScripts:t}){if(this.contextInitialized)return;this.userControlledBrowserSettings.extraHeaders&&await this.context.setExtraHTTPHeaders(this.userControlledBrowserSettings.extraHeaders),e&&await this.context.grantPermissions(["clipboard-read","clipboard-write","microphone","camera","geolocation"]);let n={[Ld]:this.userBrowserSettings.visualActions},o=[this.context.addInitScript({content:tf.htmlUtilsLibJs}),this.context.addInitScript({content:`window._MOMENTIC_BROWSER = true; window._MOMENTIC_FEATURE_FLAGS = ${JSON.stringify(n)}; window.addEventListener('load', (event) => { console.log('[MOMENTIC] Page loaded'); });`}),this.exposeRecordingBindings()],i=a=>this.handleNewPageEvent(a);this.context.on("page",i),this.handleNewPageEventHelper(this.page),this.context.on("close",()=>{this.context.off("page",i)}),await Promise.all(o),t&&(await this.page.addScriptTag({content:tf.htmlUtilsLibJs}),await this.page.addScriptTag({content:`window._MOMENTIC_BROWSER = true; window._MOMENTIC_FEATURE_FLAGS = ${JSON.stringify(n)}; window.addEventListener('load', (event) => { console.log('[MOMENTIC] Page loaded'); });`})),this.properties.systemDevicePixelRatio||(process.env.MOMENTIC_LOCAL_DEV==="1"&&QG()==="darwin"&&WG("system_profiler SPDisplaysDataType").toString().includes("Retina")?(T.warn("[DEV] Setting device pixel ratio to 2 in local dev since a Retina display was detected"),this.properties.systemDevicePixelRatio=2):this.properties.systemDevicePixelRatio=await this.page.evaluate(()=>window.devicePixelRatio)),this.cdpClient=await Bd.init({logger:this.logger,contextGetter:()=>this.context,pageGetter:()=>this.page,defaultTimeoutMs:this.pageLoadTimeout}),await this.initializeScreencast(),this.stateManager=new Gd({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 Ux(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}){let l=e.pages()[0];if(!l)throw new Error("No page found in existing context");let c=l.viewportSize();c||(c=await l.evaluate(()=>({width:window.innerWidth,height:window.innerHeight})));let s=l?.url(),u=new r({browser:e.browser(),context:e,page:l,baseUrl:s,logger:a,storage:t,enricher:n,userBrowserSettings:o,viewport:c,properties:i,clientCallbacks:void 0,iconKnowledgeBase:null});return await u.initialize({grantPermissions:!1,runInitScripts:!0}),u}async handleAvailableTabsChangeHelper(){try{let e=await Mf(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=zf(),o=`${e}-${n}`,i=Date.now(),a=!1,l=async()=>{try{await G(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()||!di(i.url()))){this.logger.info(`Automatically switching to tab ${o} after close: ${i.url()}`),await this.switchToPage({type:"INDEX",index:String(o)});break}}};this.addToPageLoadPromises("page closed handler",async()=>t())}handleNewPageEvent(e){let t=e.url();if(this.logger.info({url:t},"Detected new page event, registering handlers and waiting for load to complete"),this.properties.recordVideo){let n=e.video();n&&this.videos.push(n)}try{this.handleNewPageEventHelper(e)}catch(n){this.logger.warn({err:n},"Error handling new page open, continuing....")}}handleNewPageEventHelper(e){let t=zf(),n="new-page-load-handler";e.on("close",a=>this.handlePageClosedEvent(a)),e.on("framenavigated",a=>this.handleFrameNavigationEvent(a)),e.on("crash",()=>{this.logger.error("Page crashed at the Playwright level!")});let o=this.context.pages().indexOf(e);e.on("console",a=>{vx(e,o,this.debugData,a,this.logger)});let i=async()=>{await wx(t,this.debugData,e),await e.route("**/*",async(a,l)=>{await Ef({pageId:t,route:a,request:l,debugData:this.debugData,logger:this.logger,requestRecorders:this.requestRecorders,mocks:this.mocks})}),await e.route("**/*",Mx(this.customHeaders,this.logger)),cn&&await e.route("**/*",Nl),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"||!di(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){for(this.abortSignal=void 0,this.debugData.logsPerPage=[],this.debugData.harPages={},this.debugData.harEntries={},this.pageLoadPromises={};this.videos.length>0;)this.videos.pop();await this.clearAuthState({closeNonActiveTabs:!0}),await this.stopScreencast(),await this.reinitializeCDPClient(),await this.navigate({url:e.newUrl??this.baseUrl,initialNavigation:!0,loadTimeoutMs:e.timeout}),this.stateManager.reset()}async clearHighlights(){try{await G(xf(this.getBrowserCallbacks()),{milliseconds:ae})}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<rf;){a++,n?.throwIfAborted();try{if(await yt({fn:()=>{let c=window;return!!(c.generateCssSelectors&&c.evaluateCssSelectors&&c.evaluatePrimaryCaches&&c.generateHtmlCacheAttributes&&c.ldist)},timeout:ae,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 ie(At),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),yt({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:oe,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 ie(Fa),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??Ce}),c=Buffer.from(l.data,"base64"),s=await T_.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&&YG(n,c),this.lastScreenshotForRecording=c,!e)return c;let p=await e.boundingBox({timeout:oe});if(!p)throw new Error("Attempted to screenshot an element that is not visible on the page");let{x:m,y:h,width:g,height:f}=p;if(!g||!f)throw new Error("Attempted to screenshot an element with zero width or height");m=Math.floor(m),h=Math.floor(h),g=Math.floor(g),f=Math.floor(f);try{let S=await T_.fromBuffer(c),y=S.bitmap.width,E=S.bitmap.height;m=Math.max(0,Math.min(m,y-1)),h=Math.max(0,Math.min(h,E-1)),g=Math.max(1,Math.min(g,y-m)),f=Math.max(1,Math.min(f,E-h)),c=await S.crop({x:m,y:h,w:g,h:f}).getBuffer("image/jpeg")}catch(S){throw new Error(`Failed taking element screenshot at coordinates (${m}, ${h}) with size (${g}, ${f}): ${S}`)}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}){Hv(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 ie(At),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:ae})}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(gx.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 yt({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:ae,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 Hx({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 ie(Fa),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??WS}),t.pressEnter&&await this.press("Enter",{})}async scrollIntoViewIfNeeded(e){try{await e.scrollIntoViewIfNeeded({timeout:Ce})}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:Ce})}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 Ud({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:ae}),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 bx(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:ae});let n=0;for(let i of e.origins??[])for(let a of i.localStorage)try{await this.cdpClient.send({timeout:ae,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 Tx(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 Ex(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 Mf(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 sn)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(!sf.includes(e?.role??""))return{scrollPerformed:!1};if(await this.scrollIntoViewIfNeeded(t),o||(o=await t.boundingBox({timeout:oe})),!o||!o.width||!o.height)return n.debug("Skipping visual attributes saving for element with no bounding box after action"),e.boundingBox=void 0,e.screenshotUrl=void 0,{scrollPerformed:!0};let{x:i=0,y:a=0,width:l=0,height:c=0}=o;if(e.boundingBox&&Math.abs(e.boundingBox.width-l)<1&&Math.abs(e.boundingBox.height-c)<1&&Math.abs((e.boundingBox.x??0)-i)<1&&Math.abs((e.boundingBox.y??0)-a)<1)return{scrollPerformed:!0};e.boundingBox=o;let s=await this.screenshot({locator:t,quality:75,retries:0});return e.screenshotUrl=await this.storage.uploadScreenshot(s),{scrollPerformed:!0}}async resolveAutoFrameCache(e){return this.stateManager.resolveAutoFrameCache(e)}async getElementRequiredValues({locator:e,requirements:t}){let n={};if(t?.boundingBox){let o=await e.boundingBox({timeout:oe});if(!o||!o.width||!o.height)throw new x("ActionFailureError","Element does not have a bounding box as required");n.boundingBox=o??void 0}if(t?.text){let o=await e.innerText({timeout:oe});n.text=o?.trim()}if(t?.attributes&&t.attributes.length>0){let o={};for(let i of t.attributes){let a=i.trim().toLowerCase();if(!(!a||Dr.bannedAiRequiredCacheAttributes.includes(a)))try{let l=await e.getAttribute(a,{timeout:oe});l!==null&&(o[i]=l)}catch(l){this.logger.warn({err:l,attr:i},"Failed to fetch required attribute, continuing...")}}n.attributes=o}return n}async getAdditionalElementDetails({mainLocator:e,additionalElement:t,root:n,logger:o}){let i=this.stateManager.a11yIdToNodeMap[t.id];if(!i)return;let a=await this.stateManager.getLocatorFromA11yNode({page:this.page,root:n,node:i});if(e.contentFrame!==a.contentFrame)return;let l=await this.fetchHtmlAttributes({locator:a,logger:o});if(!l?.generatedSelectors||l.generatedSelectors.length===0)return;let c={selectors:l.generatedSelectors};return t.requirements&&(c.requirements=await this.getElementRequiredValues({locator:a,requirements:t.requirements})),c}async getAdditionalElementsDetails({mainElementId:e,mainLocator:t,additionalElements:n,root:o,logger:i}){let a=new Set,l=[];for(let c of n)try{if(c.id===e||a.has(c.id))continue;let s=await this.getAdditionalElementDetails({mainLocator:t,additionalElement:c,root:o,logger:i});if(a.add(c.id),!s)continue;l.push(s)}catch(s){this.logger.warn({err:s,additionalElement:c},"Failed to fetch additional element details, continuing...")}return l}async updateCacheWithAdditionalRequirements({mainElementId:e,requirements:t,additionalElements:n,target:o,locator:i,root:a,logger:l}){t&&(o.requirements=await this.getElementRequiredValues({locator:i,requirements:t})),n&&(o.additionalElements=await this.getAdditionalElementsDetails({mainElementId:e,mainLocator:i,additionalElements:n,root:a,logger:l}))}async createTargetFromA11yId({id:e,description:t,targetSource:n,skipSaveToCache:o,logger:i=this.logger,requirements:a,additionalElements:l}){if(e<0)throw new 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 y=c.parentFrame,{cache:E,config:R}=await this.stateManager.getAutoFrameDetailsFromHandle(y);d=E,p=R,u=R.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 h=await this.stateManager.getLocatorFromA11yNode({page:this.page,root:u,node:c}),g={id:e,inputDescription:t??void 0,targetSource:n,targetUpdateTime:new Date().toISOString(),targetUpdateLoggerTags:je(i),frameCache:d},f,S=!1;o||(p&&(i.info({frameConfigSource:m,frameConfig:f_(p)},"A11y node was resolved to a target within an iframe"),f=this.stateManager.frameConfig,this.stateManager.setActiveFrameConfig(p),S=!0),await this.updateCacheWithNewNodeDetails({node:c,target:g,locator:h,logger:i,allowNotActionableNodesOverride:!0}),await this.updateCacheWithAdditionalRequirements({mainElementId:e,requirements:a,additionalElements:l,target:g,root:u,locator:h,logger:i}));try{return{resolution:{locator:h,a11yNode:c,displayString:c.getNodeOnlySerializedForm(),decisions:[]},target:g,frameConfig:p,frameConfigSource:m}}finally{S&&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,h=!1,g=Date.now();for(;Date.now()-g<this.smartWaitingTimeout;)try{let f=await this.stateManager.resolveAutoFrameCache(t.frameCache);this.setActiveFrameConfig(f),h=!0;break}catch(f){m=f,await ie(At,a)}if(!h)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(h){if(h instanceof Ss)break;if(h instanceof sn){if(d++,d>2)throw i.error({err:h},"Got multiple cache disqualification errors, giving up"),h;i.warn({err:h},"Got cache disqualification error, waiting and retrying resolution"),await ie(At,a)}a?.throwIfAborted(),m&&i.warn({err:h},`Could not resolve target using primary cache only (x${u})`),await ie(At,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=je(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=Ga(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 an&&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:Ga(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 an(`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 Ss("Insufficient data to resolve target using primary methods (missing node HTML)");let a=i?n:dn,l=this.userControlledBrowserSettings.hybridSelectorMode,c={ldistThreshold:af,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 yt({fn:E=>window.evaluatePrimaryCaches(E),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:oe,waitForPageLoad:()=>this.waitForPageLoad(),codePath:"evaluating target caches"}),d,p,m=[];if(l==="prefer"&&u?.result){d=u.result;let E={type:"HYBRID_SELECTOR",matched:!0,logs:u.logs,reason:"Discovered a match using Momentic's hybrid text and CSS selector approach"};m.push(E),p="HYBRID_SELECTOR"}else if(s?.result){d=s.result;let E=`${d.workingSelectors.length} CSS selectors matched the following element: ${d.serializedElement}`,R=d.workingSelectors.slice(0,5);m.push({type:"CSS_SELECTOR",matched:!0,logs:s.logs,reason:E,selectors:R}),n.debug({reason:E,workingSelectors:R},"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}),new an("Cache evaluation failed",m);let h,g,f;if(this.userBrowserSettings.visualActions){let E=d.mPath;if(!E)throw new Error("Found element did not have an mPath despite using visual actions");let R=E.join(" > ");h=e.locator(R),g=this.stateManager.getNodeUsingMPathSelector(R)}else if(d.dataMomenticId!==void 0)f=parseInt(d.dataMomenticId),g=this.stateManager.dataMomenticIdToNodeMap[f],"workingSelectors"in d?h=e.locator(d.workingSelectors[0]):h=e.locator(Zr(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 S=Ga(t);await this.updateCacheWithNewNodeDetails({node:g,target:t,locator:h,logger:n,startingBoundingBox:d.boundingBox,allowNotActionableNodesOverride:o});let y=Hf(S,t);return y&&Object.keys(y).length>0&&(t.cacheResolutionUpdateTime=new Date().toISOString(),t.cacheResolutionUpdateLoggerTags=je(n),t.cacheResolutionUpdateSource=p,n.debug({diffs:y},"Updated cache")),{a11yNode:g,displayString:d.serializedElement,locator:h,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:ae}),m=await Hn(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(h){let g=h.message;u=new x("ActionFailureError",`CSS selector '${n}' failed to resolve after ${s} attempts: ${g.includes("locator.waitFor: Timeout")?"the selector did not match any element on the page":g}`),await ie(At,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:oe});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<mx){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 yt({fn:d=>window.findClosestElementByLDist?.(d),arg:{nodeOnlySerializedHtml:t.nodeOnlySerializedHtml},timeout:Ce,root:e,waitForPageLoad:()=>this.waitForPageLoad(),codePath:"finding the closest element on the page"}),u=Math.floor(af*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(Zr(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 h=s.closestNodeSerialized??await Hn(m,o)??"unknown element";o.warn({result:s,originalTarget:t,displayString:h},"Resolved cached target to new node with pure html levenshtein distance");let g=Ga(t);await this.updateCacheWithNewNodeDetails({node:p,target:t,locator:m,logger:o,startingBoundingBox:s.boundingBox,allowNotActionableNodesOverride:a});let f=Hf(g,t);return f&&Object.keys(f).length>0&&(t.cacheResolutionUpdateTime=new Date().toISOString(),t.cacheResolutionUpdateLoggerTags=je(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:h,savedElement:t.nodeOnlySerializedHtml}),{locator:m,a11yNode:p,displayString:h,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&&sf.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=rj(),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,h=d.boundingBox?.height;if(!m||!h)throw i="Rejecting target from screenshot due to no bounding box",new Error(i);let g=d.id,f=this.stateManager.a11yIdToNodeMap[g],S=Ga(t);await this.updateCacheWithNewNodeDetails({target:t,node:f,locator:p,allowNotActionableNodesOverride:o});let y=Hf(S,t);return y&&Object.keys(y).length>0&&(t.cacheResolutionUpdateTime=new Date().toISOString(),t.cacheResolutionUpdateLoggerTags=je(this.logger),t.cacheResolutionUpdateSource="TEMPLATE_MATCHING",this.logger.info({id:s,diffs:y,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:ae})??"",i=zx.some(a=>a===o.toLowerCase());return await _f({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 _f({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(),Tu(l,t,n)){a=!0;break}await ie(At,this.abortSignal)}if(!a)throw new x("ActionFailureError",`The active page URL ${n?.negated?"still does":"does not"} ${cu(t)} in ${o}ms.
|
|
4053
|
-
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:oe});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 ie(n.hoverSeconds?Math.min(n.hoverSeconds*1e3,Ce):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(yf);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 ie(Fa),await this.page.mouse.up()}async hover(e){await this.highlight(e.locator),await Ci({func:async t=>{await this.scrollIntoViewIfNeeded(t.locator);let n=await t.locator.boundingBox({timeout:oe});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 Ci({func:t=>t.locator.focus({timeout:Ce}),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 yt({fn:()=>{let n=document.activeElement;n&&n.nodeType===1&&n.blur()},root:t,arg:void 0,waitForPageLoad:()=>this.waitForPageLoad(),timeout:ae,codePath:"blurring the active element"});return}await this.highlight(e.locator),await Ci({func:t=>t.locator.blur({timeout:Ce}),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 Ci({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:oe})},targetingResult:e})}async press(e,t){let n=t.repeat??1;if(t.convertMeta){let o=Fd(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=Fd(e,this.properties.isAndroid);n!==e&&(this.logger.info({keyString:e,convertedKey:n},"Converted platform dependent keys"),e=n)}for(let n of Bf(e))await this.page.keyboard.down(n)}async keyUp(e,t){if(t.convertMeta){let n=Fd(e,this.properties.isAndroid);n!==e&&(this.logger.info({keyString:e,convertedKey:n},"Converted platform dependent keys"),e=n)}for(let n of Bf(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:dn;o||await this.waitForPageLoad(),e.skipWait||await this.waitForDOMStability({logger:n,signal:l});let d=0,p;for(;d<t;){d++;try{return await G(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 yt({root:e,fn:()=>[window.scrollY,window.scrollX,window.screen.width,window.screen.height,window.devicePixelRatio],arg:void 0,timeout:oe,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 ie(Fa,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<px)){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 ie(n.hoverSeconds?Math.min(n.hoverSeconds*1e3,of):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(yf);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 ie(Fa),await this.page.mouse.up()}async getElementLocation(e){let t=await this.cdpClient.send({method:"DOMSnapshot.captureSnapshot",params:{computedStyles:[],includeDOMRects:!0,includePaintOrder:!0},timeout:oe}),n=await G(this.page.evaluate(()=>window.devicePixelRatio),{milliseconds:Ce});process.platform==="darwin"&&n===1&&(n=ux);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 y=0;y<l.length;y++)if(c[y]===e){d=s.indexOf(y);break}if(d===-1)throw new Error(`Could not find any backend node with ID ${e}`);let[p=0,m=0,h=0,g=0]=u[d];p/=n,m/=n,h/=n,g/=n;let f=p+h/2,S=m+g/2;return{centerX:f,centerY:S}}async scrollVertical(e){return If({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 If({frame:this.stateManager.frameConfig?await this.getActivePageOrFrame():null,page:this.page,deltaX:e?Math.abs(e):null,directionX:e&&e>0?"right":"left",deltaY:0,directionY:null,signal:this.abortSignal,callbacks:this.getBrowserCallbacks(),logger:this.logger})}async goForward(){await this.waitForPageLoad(),await this.page.goForward({waitUntil:"domcontentloaded",timeout:this.pageLoadTimeout}),await this.loadFrameAndRecordUrl({root:this.page,signal:this.abortSignal,codePath:"go-forward"})}async goBack(){await this.waitForPageLoad(),await this.page.goBack({waitUntil:"domcontentloaded",timeout:this.pageLoadTimeout}),await this.loadFrameAndRecordUrl({root:this.page,signal:this.abortSignal,codePath:"go-back"})}async reinitializeCDPClient(e){await this.cdpClient.reinitialize(e),await this.initializeScreencast()}async stopScreencast(){if(this.clientCallbacks?.onScreencastFrame)try{await this.cdpClient.send({method:"Page.stopScreencast",params:{}})}catch{}}async changeActivePage(e,t){await this.stopScreencast(),this.recordUrlVisited(e.url()),this.page=e,await this.reinitializeCDPClient(t??this.pageLoadTimeout)}async createNewTab(e,t){let n=await this.context.newPage();await this.changeActivePage(n,t?.loadTimeoutMs),await this.navigate({url:e,initialNavigation:!0,...t}),this.handleAvailableTabsChange()}async switchToPage(e,t){let n=!0,o,i=Date.now();for(;n||t?.retry&&Date.now()-i<this.smartWaitingTimeout;){n=!1;try{await this.switchToPageHelper(e,t);return}catch(a){this.logger.warn({err:a},"Error switching to page, retrying..."),o=a,await ie(At)}}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)}.
|
|
4054
|
-
Available pages:${JSON.stringify(n.map(i=>i.url))}`);if(!di(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=Pc(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:oe}),n=await fetch("https://api.2captcha.com/createTask",{method:"POST",body:JSON.stringify({clientKey:Ba,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<hx;){await ie(2500);let l=await fetch("https://api.2captcha.com/getTaskResult",{method:"POST",body:JSON.stringify({clientKey:Ba,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 G(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&&y_({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];di(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}}},At);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:ae})}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 Js({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 ${it(i,50)} did not load within the configured timeout (${o}ms): ${l}`);if(!l.message.includes("detached"))throw l}try{await Js({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 XG.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 yt({fn:()=>window.getCondensedHtmlTree(),root:e,arg:void 0,timeout:Ce,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=Ce){let i=await this.getActivePageOrFrame();return yt({root:i,fn:e,arg:t,timeout:o,waitForPageLoad:()=>this.waitForPageLoad(),codePath:n})}async evaluateCodeInPage({code:e,fragment:t,context:n,timeoutMs:o=uo}){let i=Ix(),a={code:e,fragment:t,context:n},{result:l}=await G(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:Ce});let n;try{n=await this.cdpClient.send({method:"DOM.getNodeForLocation",params:{x:e,y:t},timeout:ae})}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:ae,params:{highlightConfig:Kx,backendNodeId:n.backendNodeId}}),async()=>{try{await this.cdpClient.send({timeout:ae,method:"Overlay.hideHighlight",params:{backendNodeId:n?.backendNodeId}})}catch{}}):async()=>{}}async clearAllCdpHighlights(){try{await this.cdpClient.send({method:"Overlay.hideHighlight",params:void 0,timeout:ae})}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[zn],a=parseInt(i??"");if(!i||isNaN(a))throw new Error("No data-momentic-id was found on the DOM node");let l=e.locator(Zr(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 G(this.performTargetRedirectionHelper(e,t,n),{milliseconds:oe})??{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 Hn(e,t);if(n===void 0&&(n=await e.boundingBox({timeout:oe})??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:h,serializedElement:g,foundElementRelativePoint:f,force:S,logs:y}=await e.evaluate(R=>{let A=window;if(!A.performTargetRedirection)throw new Error("performTargetRedirection script is not defined");return A.performTargetRedirection(R)},void 0,{timeout:ae}),E=Date.now()-o;if(h){t.warn({error:h,serializedElement:g,duration:E,force:S,logs:y},"Got error from target redirection with bounding box");return}else{if(p)return t.info({newDataMomenticId:p,serializedElement:g,duration:E,force:S,logs:y},"Redirected target to new element with bounding box with data-momentic-id"),{locator:d.locator(Zr(p)),hints:{relativeXYToLocator:f,force:S}};if(m)return t.info({newMPathSelector:m,serializedElement:g,duration:E,force:S,logs:y},"Redirected target to new element with bounding box with mPath"),{locator:d.locator(m),hints:{relativeXYToLocator:f,force:S}};if(f)return t.info({foundElementRelativePoint:f,serializedElement:g,duration:E,force:S,logs:y},"Chose specific visible point on original element"),{locator:e,hints:{relativeXYToLocator:f,force:S}};if(S)return t.info({serializedElement:g,duration:E,force:S,logs:y},"Forcing click on original element"),{locator:e,hints:{force:S}}}}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:Ce});if("error"in l&&l.error)throw l.error.startsWith(sx)?new dc(l.error):l.error.startsWith(lx)?new pc(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:ae})}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!!Ba}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,ff(e,this.debugData,i,{type:t,text:`[MOMENTIC] ${n}`,args:o})}async setFileChooserHandlerHelper({filePath:e,filename:t}){if(!jd(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()||ZG(e),o=qG(e),i=ej(e),a=Vm[i];this.page.once("filechooser",async c=>{this.logger.info({filePath:e,fileName:n},"File chooser triggered");try{if(!jd(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:JG.getType(e)||"application/octet-stream"},{timeout:of})}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 g=0;g<p.length;g++)m[g]=p.charCodeAt(g);let h=new Uint8Array(m);d.MomenticFile=class extends Blob{kind="file";name=d.momenticFileName;constructor(){super([h],{type:u})}isSameEntry(g){return g.name===this.name}queryPermission(g){return console.info("[MOMENTIC] MomenticFile.queryPermission called"),Promise.resolve("granted")}remove(){return console.info("[MOMENTIC] MomenticFile.remove called"),Promise.resolve()}async requestPermission(g){return console.info("[MOMENTIC] MomenticFile.requestPermission called"),Promise.resolve("granted")}async getFile(){console.info("[MOMENTIC] MomenticFile.getFile called");let g=new Blob([h]);return new File([g],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??zf();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??dx}get userBrowserSettings(){return Ga(this.userControlledBrowserSettings)}get pageLoadTimeout(){return this.userControlledBrowserSettings.pageLoadTimeoutMs??rf}get isInPageLoad(){return Object.values(this.pageLoadPromises).length>0}get devicePixelRatio(){return this.properties.systemDevicePixelRatio??1}get browserCrashDumpDir(){let e=kd();for(let t of e)if(!(!jd(t)||!E_(t).isDirectory()||!["new","pending","completed"].some(o=>{let i=tj(t,o);return jd(i)&&E_(i).isDirectory()&&KG(i).length>0})))return t}};import Tj from"fetch-cookie";import{cloneDeep as N_}from"lodash-es";import{CookieJar as bj}from"tough-cookie";import{randomUUID as lj}from"crypto";var A_={minChunkTokenCount:500,acceptableChunkTokenCount:3e3,maxChunkTokenCount:8e3,maxLineLength:4e3},R_={minChunkTokenCount:5e3,acceptableChunkTokenCount:1e4,maxChunkTokenCount:3e4,maxLineLength:500},v_=/<(\S+) id="(\d+)".*?>/g,nj=/(<\/(\S+)>)|(<(\S+).*?\/>)/g,w_=["h1","h2","section","footer","nav","aside","form","label","dialog"],oj=[...w_,"span","div","h3"],ij=["table","select","form","ul","ol","menu","pre","code","dialog"],aj=["table","form","dialog","nav","section","ul","select"];function Vd(r){return sj(r)}function sj({logger:r,serializedTree:e,options:t}){let{minChunkTokenCount:n,acceptableChunkTokenCount:o,maxChunkTokenCount:i,maxLineLength:a}=t,l=[],c=e.split(`
|
|
4050
|
+
${y}
|
|
4051
|
+
${w||""}`}return y}shallowClone(){let e=new r({id:this.id,role:this.role,name:this.name,nameSources:this.nameSources,content:this.content,properties:[],pathFromRoot:this.pathFromRoot,children:[],ignoredReasons:this.ignoredReasons,backendNodeID:this.backendNodeId,ignoredByCDP:this.ignoredByCDP,internalProperties:Lf(this.internalProperties),importantProperties:this.importantProperties,parentFrame:this.parentFrame,flagNotActionableNodes:this.flagNotActionableNodes});return e.tagName=this.tagName,e.dataMomenticId=this.dataMomenticId,e.properties=Lf(this.properties),e}},Df=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(kf.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,h=u-m;for(let g of c.children){let f=s+2,y=i(g,f).length;if(h<y)break;let{clone:S,used:E}=a(g,f,h);if(E>h)break;d.children.push(S),S.parent=d,m+=E,h-=E}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 LG(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 NG(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?(Vc({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?(Vc({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 i_({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:h,logger:g,callId:f}){if(!e&&r.parentId)throw new Error(`Got no parent for accessibility node ${r.nodeId}: ${JSON.stringify(r)}`);let y=(j,he={})=>{},S=r.backendDOMNodeId,E=_G.includes(r.role?.value?.toLowerCase()??"");if(!E&&S===void 0)return y("Filtering out node since it doesn't exist in the DOM"),[];let R=S?i.backendIdToNode[S]:void 0;if(!E&&!R)try{let j=await G(h.send({method:"DOM.describeNode",params:{backendNodeId:S}}),{milliseconds:750,fallback:()=>{g.debug("Timeout getting node from CDP while processing a11y tree")}});if(j&&j.node.nodeName.toLowerCase()==="slot"&&j.node.distributedNodes?.length)g.debug({redirectedDomNode:R,parentAXNode:e?.getNodeOnlySerializedForm(),originalAXNode:r,cdpResult:j},"Redirecting node to assigned slot");else return y("Filtering out node since it doesn't exist in the DOM",{cdpResult:j}),[]}catch(j){return y("Filtering out node since it doesn't exist in the DOM",{err:j}),[]}if(R&&e&&s&&u&&r.backendDOMNodeId&&!NG(R,u,g,f))return R.momenticIgnored=!0,[];if(R&&R.computedStyles.display==="none")return R.momenticIgnored=!0,[];if(R&&R.computedStyles.opacity==="0"&&c!==!0){if(c==="inputs-only"&&R.tagName.toLowerCase()!=="input")return R.momenticIgnored=!0,[];if(c===!1)return R.momenticIgnored=!0,[]}let A=r.name?.value?typeof r.name.value=="string"?r.name.value:`${r.name.value}`:"",C=r.value?.value?typeof r.value.value=="string"?r.value.value:`${r.value.value}`:"",w=new Nf({domNode:R,id:parseInt(r.nodeId),role:r.role?.value||"",name:A,nameSources:r.name?.sources,content:C,properties:r.properties,children:[],ignoredReasons:r.ignoredReasons?.filter(j=>(m??r_).includes(j.name)||n_.includes(j.name))??[],pathFromRoot:(e?`${e.pathFromRoot} `:"")+LG(r),backendNodeID:r.backendDOMNodeId,ignoredByCDP:r.ignored,internalProperties:{inCodeMirrorEditor:e?.internalProperties?.inCodeMirrorEditor},importantProperties:p,parentFrame:n.type==="root"?void 0:n,flagNotActionableNodes:l}),I=n,P=a[t],X=t;if(R?.tagName.toLowerCase()==="iframe"&&R.ownedFrameId){let j=n.childFrames.find(rt=>rt.frameId===R.ownedFrameId),he=o[j?.frameId??""]?.root,$=a[j?.frameId??""];if(j&&he&&$){r.childIds&&r.childIds.length>0&&g.debug("Replacing existing node's children with children from the iframe");let rt=he;r.childIds=rt.childIds,I=j,P=$,X=j.frameId}}let q=R?.childrenBackendIds?.length??0,k=(r.childIds??[]).filter(j=>!!P.get(parseInt(j))).length;if(q>k){let j=r.childIds?.map($=>P.get(parseInt($))).filter(Boolean).map($=>$?.backendDOMNodeId).filter($=>$!==void 0)??[],he=0;for(let $ of R?.childrenBackendIds??[]){if(j.includes($)){he=(r.childIds?.findIndex(J=>P.get(parseInt(J))?.backendDOMNodeId===$)??0)+1;continue}let rt=i.backendIdToNode[$];if(!rt||rt?.tagName.toLowerCase()!=="svg")continue;let Ne=Math.floor(-1*Math.random()*1e7),ct={nodeId:Ne.toString(),parentId:r.nodeId,ignored:!1,backendDOMNodeId:$,frameId:X,role:{type:"string",value:"graphics-symbol"}};P.set(Ne,ct),r.childIds||(r.childIds=[]),r.childIds.splice(he,0,Ne.toString()),he++}}if(r.childIds?.length===1&&R){let j=P.get(parseInt(r.childIds[0])),he=j?.role?.value,$=R.childrenBackendIds;if(j&&he==="StaticText"&&$.length===1){let rt=i.backendIdToNode[$[0]];if(rt?.tagName?.toLowerCase()==="span"){let Ne=Math.floor(-1*Math.random()*1e7).toString(),ct={nodeId:Ne,parentId:r.nodeId,ignored:!1,backendDOMNodeId:rt.backendNodeId,frameId:X,childIds:[j.nodeId]};j.parentId=Ne,P.set(parseInt(Ne),ct),r.childIds=[Ne]}}}for(let j of r.childIds??[]){if(!j)continue;let he=P.get(parseInt(j));if(!he)continue;let $=await i_({node:he,parent:w,domGraph:i,axGraph:o,frameId:X,frameContext:I,inputNodeMap:a,cdpClient:h,logger:g,callId:f,filterByViewport:s,showZeroOpacityElements:c,importantProperties:p,viewportDetails:u,useMPaths:d,flagNotActionableNodes:l});$.length&&(w.children=w.children.concat($))}if(w.role==="StaticText"&&(w.children=[]),w.children.length===1&&w.children[0].role==="StaticText"){let j=w.name,he=w.children[0]?.name;(j===he||!he)&&(w.children=[])}let ee=[];for(let j=w.children.length-1;j>=0;j--){let he=w.children[j];if(he.role!=="StaticText"){ee.push(he);continue}if(j===0||w.children[j-1].role!=="StaticText"){ee.push(he);continue}w.children[j-1].name+=he.name}if(w.children=ee.reverse(),!w.isInteresting(p)&&r.parentId)return R&&(R.momenticIgnored=!0),w.children;for(let j of w.children)j.parent=w;return UG(w),R&&d&&Of(R,i),[w]}function a_({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:kf.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=Pf(d,i),m=p?c[p.hash]:void 0,h=m?m.description:void 0;m&&(r.properties["data-momentic-description"]=h)}for(let p of r.children)s=a_({node:p,a11yIdNodeMap:e,dataMomenticIdMap:t,logger:n,callId:o,startId:s,useMPaths:a,domGraph:i,selectorToNodeMap:l,iconKnowledgeBase:c});return s}async function s_({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 h=t??"root",g=r[h]?.root;if(!g)throw new Error("A11y tree has no root");let f=bG(),y=w=>{let I=w.allNodes.filter(X=>!X.ignoredReasons?.find(k=>(m??r_).includes(k.name))),P=new Map;return I.forEach(X=>{P.set(parseInt(X.nodeId),X)}),P},S={};Object.entries(r).forEach(([w,I])=>{S[w]=y(I)});let E=await i_({node:g,domGraph:e,parent:null,inputNodeMap:S,axGraph:r,frameId:h,frameContext:d,cdpClient:o,logger:n,callId:f,showZeroOpacityElements:a,importantProperties:c,filterByViewport:i,viewportDetails:s,useMPaths:u,flagNotActionableNodes:l,allowedA11yIgnoreReasonsOverride:m});if(E.length>1)throw new Error(`Something went horribly wrong processing the a11y tree, we got: ${JSON.stringify(E)}`);if(E.length===0)throw new Error("There are no accessible elements on this page or frame. Are you sure this website loads properly?");let R={},A={},C={};return a_({node:E[0],a11yIdNodeMap:R,dataMomenticIdMap:A,selectorToNodeMap:C,domGraph:e,logger:n,callId:f,useMPaths:u,iconKnowledgeBase:p}),new Df(E[0],R,A,C)}function DG(r,e,t,n){if(r==="class"){if(t.tagName?.toLowerCase()==="svg")return e.split(" ").filter(a=>a.length<o_&&!Dr.bannedClassSubstrings.some(l=>a.includes(l))).slice(0,3).join(" ");let o=e.split(" "),i=[];for(let a of o)if(l_(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 kG(r,e,t){if(!e)return;Object.entries(e.attributes).forEach(([a,l])=>{let c=r[a]||a.startsWith("aria")||RG.includes(a);if((Dr.relevantElementAttributes.includes(a)||c_(a,t))&&!c){let u=DG(a,l,e,t);u!==null&&(r[a]=u)}});let n,o=[];if(e.computedStyles.position&&Zx.includes(e.computedStyles.position))n=e.computedStyles.position;else if(e.attributes.style){for(let a of Zx)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 UG(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(it(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(h=>h.tagName==="th");if(m.length){if(i=m.map(h=>it(h.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,h)=>{m.tagName!=="th"&&(m.properties["col-index"]||(m.properties["col-index"]=h+1),p&&(m.properties.col||(m.properties.col=i[h])))})}}}function FG(r){let e=r.properties.class,t=typeof e=="string"&&e.includes("cm-content");r.internalProperties.inCodeMirrorEditor=r.internalProperties?.inCodeMirrorEditor||t}function l_(r,e){if(e&&u_(r,e))return!0;if(Dr.bannedClassSubstrings.some(t=>r.includes(t)))return!1;if(Dr.alwaysInterestingClassNames.includes(r))return!0;for(let t of Dr.alwaysInterestingClassPrefixes)if(r.startsWith(t))return!0;return!1}function c_(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 u_(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 Bd=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 G(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 ie(At),c=d}if(!l)throw c;let s=new r(l,e,t,n,o);try{await G(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 e.send("Accessibility.enable"),await e.send("Page.enable"),await e.send("DOM.enable"),await e.send("Overlay.enable"),await e.send("DOMSnapshot.enable"),await e.send("CSS.enable")}async send({method:e,params:t,timeout:n=this.defaultTimeoutMs,timeoutMsg:o}){for(;this.cdpInitializingPromise;)await G(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 G(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 G(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 G(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 G(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 za="<empty>";function BG(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 p_(r){let e=r.adFrameStatus?.adFrameType;return e==="child"||e==="root"||BG(r.url)}async function zG(r,e){let t=await r.send({timeout:oe,method:"DOM.getFrameOwner",params:{frameId:e}}),o=(await r.send({timeout:oe,method:"DOM.pushNodesByBackendIdsToFrontend",params:{backendNodeIds:[t.backendNodeId]}})).nodeIds[0],a=(await r.send({timeout:oe,method:"DOM.describeNode",params:{backendNodeId:t.backendNodeId}})).node;return a.nodeId=o,a}async function Ha({cdpClient:r,page:e,logger:t}){let n={type:"root",childFrames:[],page:e},o=[],[i,a]=await Promise.all([r.send({timeout:oe,method:"Page.getFrameTree",params:{}}),r.send({timeout:oe,method:"DOM.getDocument",params:{depth:0}})]),s=(i.frameTree.childFrames??[]).map(async(d,p)=>{if(p_(d.frame))return null;try{return await m_({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 m_({cdpClient:r,rawFrameTree:e,indices:t,parent:n,warnings:o,logger:i}){let a=e.frame.id,l=await zG(r,a),c=l.attributes??[],s=null,u=[];for(let h of["src","name","id","title","srcdoc","sandbox"]){let g=Mo(c,h);g&&(u.push(`${h}=${JSON.stringify(g)}`),h==="src"&&(s=g))}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(h,g)=>{if(p_(h.frame))return null;try{return await m_({cdpClient:r,rawFrameTree:h,indices:[...t,g],parent:d,warnings:o,logger:i})}catch(f){return o.push(`Failed to get child frame (child ${g} of frame with url ${e.frame.url}): ${f}`),null}});return d.childFrames=(await Promise.all(m)).filter(h=>h!==null),d}async function HG(r){try{return await r.owner().count()===1}catch{return!1}}async function GG(r){try{return await r.count()===1}catch{return!1}}async function wn(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,za]){let p=o.frameLocator(d===za?"iframe":`iframe[${d}]`);if(await HG(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,za]){let u=o.locator(s===za?"iframe":`iframe[${s}]`);if(await GG(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:ae}),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 d_(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 h_({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===za?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===za?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 wn(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=d_(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 wn(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=d_(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 wn(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 wn(n,r)).frame,handle:n,mPathSelectorTokens:t.mPathSelectorTokens,frameTree:e},logs:i};throw i.push(`Found ${a.length} frames with indices ${t.indices}`),new an("Failed to find the iframe that previously contained this element",[{type:"AUTO_FRAME",matched:!1,logs:i}])}function zd(r){return r.type==="auto"?JSON.stringify({type:"auto",frameId:r.handle.frameId}):JSON.stringify(r)}function Uf(r){for(;r.parent.type==="frame";)r=r.parent;return r.parent}function g_(r){let e=Uf(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 f_(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 S_({frame:r,logger:e,signal:t}){let n;try{n=await r.frameElement(),await jG({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 jG({frameElementHandle:r,logger:e,signal:t}){let n=await r.boundingBox();await Js({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:Ce,codePath:"scrollIframeIntoView",signal:t}),e.info({oldBb:n,newBb:await r.boundingBox()},"Successfully scrolled iframe into view")}async function y_({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(h=>h.url());i.debug({frameUrl:s,...r},"Passive click event captured on element");let p,m;if(s)try{let h=await n.frameElement();p=await G(h?.boundingBox(),{milliseconds:oe})??void 0;let g=await t.constructIframeRegex({urls:d,srcs:[],desiredUrl:s});if(g.urlRegex)m={type:"url",url:`/${g.urlRegex}/`};else throw new Error(`Got no url regex options: ${JSON.stringify(g)}`)}catch(h){i.warn({err:h},"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(h){i.error({err:h},"Failed to transform passive click action")}})()}import{randomUUID as Cn}from"crypto";import VG from"js-beautify";var $G=["Dead"],Hd=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:Cn(),type:"PRESET_ACTION",command:Pn(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 g=Pn(i);a={id:Cn(),type:"PRESET_ACTION",command:{...g,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 g=Pn(i);a={id:Cn(),type:"PRESET_ACTION",command:{...g,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 g=Pn(i);a={id:Cn(),type:"PRESET_ACTION",command:{...g,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:je(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=VG.html(d,{indent_size:1,indent_with_tabs:!1,preserve_newlines:!1}),d=cx(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,...je(this.logger)}})).phrase}catch(g){this.logger.error({err:g},"Error generating reverse mapping description"),p=l}let m=this.recordedSteps.get(u)?.step??a,h=m?.command;h&&"target"in h&&h.target?(h.target={type:"description",elementDescriptor:p},this.callbacks.onStepRecorded({...m,command:h},u)):this.logger.warn("Could not find existing command to update after description mapping")}recordKeystroke(e){let{key:t,combinable:n}=e;if($G.includes(t)||this.signal.aborted)return;let o="normal";t.length>1&&(o="special");let i;if(o==="normal"){let d=Pn("TYPE");i={id:Cn(),type:"PRESET_ACTION",command:{...d,target:void 0,value:t,clearContent:!1}}}else{let d=Pn("PRESS");i={id:Cn(),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:Cn(),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:Cn(),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=Pn(s);u.deltaY=Math.abs(i);let d={id:Cn(),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=Pn(s);u.deltaX=Math.abs(i);let d={id:Cn(),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 Ff}from"zod";var WLe=Ff.object({type:Ff.literal("url"),url:Ff.string()});var Gd=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 h=m[0]?.trim(),g=m[1]?.trim();if(h===void 0||g===void 0){this.logger.warn({style:p},"Invalid style property passed to importantStyles");continue}this.computedStylesToFetch.includes(h)||this.computedStylesToFetch.push(h)}}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=Uf(e),{frame:o,mPathSelectorTokens:i}=await wn(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 Ha({cdpClient:this.cdpClient,page:t,logger:this.logger}),{resolution:o,logs:i}=await h_({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(zd(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:zd(this.frameConfig),cacheTime:Date.now(),frameTree:this.frameConfig.frameTree,mPathSelectorTokens:this.frameConfig.mPathSelectorTokens},await S_({frame:n.frame,logger:e,signal:t}),this.activeFrameCache=n,n}async executeFunctionInAllFrames(e,t){let n=this.pageGetter(),o=await Ha({cdpClient:this.cdpClient,page:n,logger:this.logger}),i=[G(n.evaluate(e,t),{milliseconds:Ce})],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(wn(c,n).then(({frame:u})=>G(u.evaluate(e,t),{milliseconds:Ce})).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 Ha({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 kr({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 kr({fn:()=>Ha({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 kr({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 kr({fn:()=>this.getDOMTree({devicePixelRatio:e.devicePixelRatio??1,signal:o,logger:n}),codePath:"domFetch",logObject:t,signal:o,logger:n}),u=await kr({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 kr({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:dn,filterByViewport:!1,flagNotActionableNodes:!1}),Math.random()<.1){let n=this.lastA11yTreeRoot?.serialize();this.logger.debug({tree:n&&n.length>4e5?"REDACTED_DUE_TO_SIZE":n},"Refreshed a11y tree during recording")}}async getLocatorFromA11yNode({page:e,root:t,node:n}){if(n.backendNodeId===void 0)throw new Error(`Node with a11y id ${n.id} has no backend node ID: ${n.getNodeOnlySerializedForm()}`);if(this.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=Xx({node:o,domGraph:this.domGraph});return Jx(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:Ce});if(!n||!n.object.objectId)throw new Error(`Could not resolve backend node ${t}`);let o;try{o=await Qx(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(Zr(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 Ha({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 ie(At,t)}finally{c++}if(a)return{source:"url",frame:a.frame,handle:a.handle,frameIdentifierStringified:zd(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=Mo(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 wn(l,o)});break}}else if(n.trim()===d.trim()){a.push({handle:l,matchType:"url",...await wn(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 s_({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 wn(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 yt({root:e,fn:i=>window.addIdsToElement?.(document.body,i),arg:t,timeout:Ce,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(Mo(t,"aria-hidden")==="true")return{shouldUnroll:!1,reason:"aria-hidden"};let n=Mo(t,"style");if(n?.includes("display: none")||n?.includes("visibility: hidden"))return{shouldUnroll:!1,reason:"hidden CSS style"};await this.cdpClient.send({timeout:oe,method:"DOM.pushNodesByBackendIdsToFrontend",params:{backendNodeIds:[e.backendNodeId]}});let[o,i]=await Promise.all([this.cdpClient.send({timeout:oe,method:"DOM.getBoxModel",params:{backendNodeId:e.backendNodeId}}),this.cdpClient.send({timeout:oe,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 kr({fn:()=>this.getRawA11yTreeForFrame({frameId:t,timeoutMs:this.pageLoadTimeoutMs,logTimings:o}),codePath:"a11y-tree-fetch-root",logObject:o,logger:i});break}catch(h){c=h,i.warn({err:h},"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:g}=await this.decideChildFrameUnrollEligibility({handle:m,warnings:l});if(!g)continue}catch(g){if(g.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: ${g}`)}d.push(...m.childFrames);let h=async()=>{try{let g=await kr({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]=g}catch(g){i.warn({err:g,url:m.url,src:m.src},`Error getting raw a11y tree for child frame ${m.frameId}, continuing...`)}};p.push(h())}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 kr({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 kr({fn:()=>this.cdpClient.send({method:"Accessibility.getRootAXNode",params:{frameId:e??void 0},timeout:Ce}),codePath:"cdp-get-root-ax-node",logObject:n,logger:this.logger})).node.backendDOMNodeId;o=(await kr({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:oe}),!o||!o.documents.length)throw new Error("Got empty DOM tree")}catch(l){await ie(At,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 Yx({snapshot:o,devicePixelRatio:e,computedStylesToFetch:this.computedStylesToFetch,logger:n})}constructIframeRegexAsync(e,t){if(t.frameSrcRegex||t.frameUrlRegex)return;let n=g_(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 Bf(r){let e=[],t="";for(let n of r)n==="+"&&t?(e.push(t),t=""):t+=n;return e.push(t),e}var Ur=class r{static USER_AGENT=Nd;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;videos=[];baseUrl;constructor({storage:e,enricher:t,browser:n,context:o,page:i,baseUrl:a,logger:l,userBrowserSettings:c,viewport:s,properties:u,clientCallbacks:d,iconKnowledgeBase:p}){if(Ab(c),this.storage=e,this.enricher=t,this.browser=n,this.context=o,this.page=i,this.baseUrl=a,this.logger=l,this.userControlledBrowserSettings=c,this.viewport=s,this.properties=u,this.clientCallbacks=d,u.recordVideo){let m=this.page.video();m&&this.videos.push(m)}this.iconKnowledgeBase=p}registerAbortSignal(e){this.abortSignal=e}async initialize({grantPermissions:e,runInitScripts:t}){if(this.contextInitialized)return;this.userControlledBrowserSettings.extraHeaders&&await this.context.setExtraHTTPHeaders(this.userControlledBrowserSettings.extraHeaders),e&&await this.context.grantPermissions(["clipboard-read","clipboard-write","microphone","camera","geolocation"]);let n={[Ld]:this.userBrowserSettings.visualActions},o=[this.context.addInitScript({content:tf.htmlUtilsLibJs}),this.context.addInitScript({content:`window._MOMENTIC_BROWSER = true; window._MOMENTIC_FEATURE_FLAGS = ${JSON.stringify(n)}; window.addEventListener('load', (event) => { console.log('[MOMENTIC] Page loaded'); });`}),this.exposeRecordingBindings()],i=a=>this.handleNewPageEvent(a);this.context.on("page",i),this.handleNewPageEventHelper(this.page),this.context.on("close",()=>{this.context.off("page",i)}),await Promise.all(o),t&&(await this.page.addScriptTag({content:tf.htmlUtilsLibJs}),await this.page.addScriptTag({content:`window._MOMENTIC_BROWSER = true; window._MOMENTIC_FEATURE_FLAGS = ${JSON.stringify(n)}; window.addEventListener('load', (event) => { console.log('[MOMENTIC] Page loaded'); });`})),this.properties.systemDevicePixelRatio||(process.env.MOMENTIC_LOCAL_DEV==="1"&&QG()==="darwin"&&WG("system_profiler SPDisplaysDataType").toString().includes("Retina")?(T.warn("[DEV] Setting device pixel ratio to 2 in local dev since a Retina display was detected"),this.properties.systemDevicePixelRatio=2):this.properties.systemDevicePixelRatio=await this.page.evaluate(()=>window.devicePixelRatio)),this.cdpClient=await Bd.init({logger:this.logger,contextGetter:()=>this.context,pageGetter:()=>this.page,defaultTimeoutMs:this.pageLoadTimeout}),await this.initializeScreencast(),this.stateManager=new Gd({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 Ux(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}){let l=e.pages()[0];if(!l)throw new Error("No page found in existing context");let c=l.viewportSize();c||(c=await l.evaluate(()=>({width:window.innerWidth,height:window.innerHeight})));let s=l?.url(),u=new r({browser:e.browser(),context:e,page:l,baseUrl:s,logger:a,storage:t,enricher:n,userBrowserSettings:o,viewport:c,properties:i,clientCallbacks:void 0,iconKnowledgeBase:null});return await u.initialize({grantPermissions:!1,runInitScripts:!0}),u}async handleAvailableTabsChangeHelper(){try{let e=await Mf(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=zf(),o=`${e}-${n}`,i=Date.now(),a=!1,l=async()=>{try{await G(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()||!di(i.url()))){this.logger.info(`Automatically switching to tab ${o} after close: ${i.url()}`),await this.switchToPage({type:"INDEX",index:String(o)});break}}};this.addToPageLoadPromises("page closed handler",async()=>t())}handleNewPageEvent(e){let t=e.url();if(this.logger.info({url:t},"Detected new page event, registering handlers and waiting for load to complete"),this.properties.recordVideo){let n=e.video();n&&this.videos.push(n)}try{this.handleNewPageEventHelper(e)}catch(n){this.logger.warn({err:n},"Error handling new page open, continuing....")}}handleNewPageEventHelper(e){let t=zf(),n="new-page-load-handler";e.on("close",a=>this.handlePageClosedEvent(a)),e.on("framenavigated",a=>this.handleFrameNavigationEvent(a)),e.on("crash",()=>{this.logger.error("Page crashed at the Playwright level!")});let o=this.context.pages().indexOf(e);e.on("console",a=>{vx(e,o,this.debugData,a,this.logger)});let i=async()=>{await wx(t,this.debugData,e),await e.route("**/*",async(a,l)=>{await Ef({pageId:t,route:a,request:l,debugData:this.debugData,logger:this.logger,requestRecorders:this.requestRecorders,mocks:this.mocks})}),await e.route("**/*",Mx(this.customHeaders,this.logger)),cn&&await e.route("**/*",Nl),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"||!di(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){for(this.abortSignal=void 0,this.debugData.logsPerPage=[],this.debugData.harPages={},this.debugData.harEntries={},this.pageLoadPromises={};this.videos.length>0;)this.videos.pop();await this.clearAuthState({closeNonActiveTabs:!0}),await this.stopScreencast(),await this.reinitializeCDPClient(),await this.navigate({url:e.newUrl??this.baseUrl,initialNavigation:!0,loadTimeoutMs:e.timeout}),this.stateManager.reset()}async clearHighlights(){try{await G(xf(this.getBrowserCallbacks()),{milliseconds:ae})}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<rf;){a++,n?.throwIfAborted();try{if(await yt({fn:()=>{let c=window;return!!(c.generateCssSelectors&&c.evaluateCssSelectors&&c.evaluatePrimaryCaches&&c.generateHtmlCacheAttributes&&c.ldist)},timeout:ae,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 ie(At),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),yt({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:oe,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 ie(Fa),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??Ce}),c=Buffer.from(l.data,"base64"),s=await T_.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&&YG(n,c),this.lastScreenshotForRecording=c,!e)return c;let p=await e.boundingBox({timeout:oe});if(!p)throw new Error("Attempted to screenshot an element that is not visible on the page");let{x:m,y:h,width:g,height:f}=p;if(!g||!f)throw new Error("Attempted to screenshot an element with zero width or height");m=Math.floor(m),h=Math.floor(h),g=Math.floor(g),f=Math.floor(f);try{let y=await T_.fromBuffer(c),S=y.bitmap.width,E=y.bitmap.height;m=Math.max(0,Math.min(m,S-1)),h=Math.max(0,Math.min(h,E-1)),g=Math.max(1,Math.min(g,S-m)),f=Math.max(1,Math.min(f,E-h)),c=await y.crop({x:m,y:h,w:g,h:f}).getBuffer("image/jpeg")}catch(y){throw new Error(`Failed taking element screenshot at coordinates (${m}, ${h}) with size (${g}, ${f}): ${y}`)}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}){Hv(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 ie(At),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:ae})}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(gx.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 yt({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:ae,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 Hx({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 ie(Fa),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??WS}),t.pressEnter&&await this.press("Enter",{})}async scrollIntoViewIfNeeded(e){try{await e.scrollIntoViewIfNeeded({timeout:Ce})}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:Ce})}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 Ud({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:ae}),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 bx(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:ae});let n=0;for(let i of e.origins??[])for(let a of i.localStorage)try{await this.cdpClient.send({timeout:ae,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 Tx(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 Ex(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 Mf(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 sn)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(!sf.includes(e?.role??""))return{scrollPerformed:!1};if(await this.scrollIntoViewIfNeeded(t),o||(o=await t.boundingBox({timeout:oe})),!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={};if(n?.boundingBox){let i=await t.boundingBox({timeout:oe});if(!i||!i.width||!i.height)throw new x("ActionFailureError","Element does not have a bounding box as required");o.boundingBox=i??void 0}if(n?.text){let i=await t.textContent({timeout:oe});o.text=i?.trim()}if(n?.attributes&&n.attributes.length>0){let i={};for(let a of n.attributes){let l=a.trim().toLowerCase();if(!(!l||Dr.bannedAiRequiredCacheAttributes.includes(l)))try{let c=await t.getAttribute(l,{timeout:oe});c!==null&&(i[a]=c)}catch(c){e.warn({err:c,attr:a},"Failed to fetch required attribute, continuing...")}}o.attributes=i}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 S=c.parentFrame,{cache:E,config:R}=await this.stateManager.getAutoFrameDetailsFromHandle(S);d=E,p=R,u=R.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 h=await this.stateManager.getLocatorFromA11yNode({page:this.page,root:u,node:c}),g={id:e,inputDescription:t??void 0,targetSource:n,targetUpdateTime:new Date().toISOString(),targetUpdateLoggerTags:je(i),frameCache:d},f,y=!1;o||(p&&(i.info({frameConfigSource:m,frameConfig:f_(p)},"A11y node was resolved to a target within an iframe"),f=this.stateManager.frameConfig,this.stateManager.setActiveFrameConfig(p),y=!0),await this.updateCacheWithNewNodeDetails({node:c,target:g,locator:h,logger:i,allowNotActionableNodesOverride:!0}),await this.updateCacheWithAdditionalRequirements({mainElementId:e,requirements:a,additionalElements:l,target:g,root:u,locator:h,logger:i}));try{return{resolution:{locator:h,a11yNode:c,displayString:c.getNodeOnlySerializedForm(),decisions:[]},target:g,frameConfig:p,frameConfigSource:m}}finally{y&&this.stateManager.setActiveFrameConfig(f)}}async resolveTarget(e,t,n={}){let{targetName:o,logger:i=this.logger,signal:a=this.abortSignal,allowNotActionableNodesOverride:l}=n;if(t.frameCache&&this.userBrowserSettings.autoExpandIframes){let m,h=!1,g=Date.now();for(;Date.now()-g<this.smartWaitingTimeout;)try{let f=await this.stateManager.resolveAutoFrameCache(t.frameCache);this.setActiveFrameConfig(f),h=!0;break}catch(f){m=f,await ie(At,a)}if(!h)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(h){if(h instanceof Ss)break;if(h instanceof sn){if(d++,d>2)throw i.error({err:h},"Got multiple cache disqualification errors, giving up"),h;i.warn({err:h},"Got cache disqualification error, waiting and retrying resolution"),await ie(At,a)}a?.throwIfAborted(),m&&i.warn({err:h},`Could not resolve target using primary cache only (x${u})`),await ie(At,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=je(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=Ga(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 an&&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:Ga(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 an(`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 Ss("Insufficient data to resolve target using primary methods (missing node HTML)");let a=i?n:dn,l=this.userControlledBrowserSettings.hybridSelectorMode,c={ldistThreshold:af,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 yt({fn:E=>window.evaluatePrimaryCaches(E),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:oe,waitForPageLoad:()=>this.waitForPageLoad(),codePath:"evaluating target caches"}),d,p,m=[];if(l==="prefer"&&u?.result){d=u.result;let E={type:"HYBRID_SELECTOR",matched:!0,logs:u.logs,reason:"Discovered a match using Momentic's hybrid text and CSS selector approach"};m.push(E),p="HYBRID_SELECTOR"}else if(s?.result){d=s.result;let E=`${d.workingSelectors.length} CSS selectors matched the following element: ${d.serializedElement}`,R=d.workingSelectors.slice(0,5);m.push({type:"CSS_SELECTOR",matched:!0,logs:s.logs,reason:E,selectors:R}),n.debug({reason:E,workingSelectors:R},"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}),new an("Cache evaluation failed",m);let h,g,f;if(this.userBrowserSettings.visualActions){let E=d.mPath;if(!E)throw new Error("Found element did not have an mPath despite using visual actions");let R=E.join(" > ");h=e.locator(R),g=this.stateManager.getNodeUsingMPathSelector(R)}else if(d.dataMomenticId!==void 0)f=parseInt(d.dataMomenticId),g=this.stateManager.dataMomenticIdToNodeMap[f],"workingSelectors"in d?h=e.locator(d.workingSelectors[0]):h=e.locator(Zr(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 y=Ga(t);await this.updateCacheWithNewNodeDetails({node:g,target:t,locator:h,logger:n,startingBoundingBox:d.boundingBox,allowNotActionableNodesOverride:o});let S=Hf(y,t);return S&&Object.keys(S).length>0&&(t.cacheResolutionUpdateTime=new Date().toISOString(),t.cacheResolutionUpdateLoggerTags=je(n),t.cacheResolutionUpdateSource=p,n.debug({diffs:S},"Updated cache")),{a11yNode:g,displayString:d.serializedElement,locator:h,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:ae}),m=await Hn(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(h){let g=h.message;u=new x("ActionFailureError",`CSS selector '${n}' failed to resolve after ${s} attempts: ${g.includes("locator.waitFor: Timeout")?"the selector did not match any element on the page":g}`),await ie(At,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:oe});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<mx){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 yt({fn:d=>window.findClosestElementByLDist?.(d),arg:{nodeOnlySerializedHtml:t.nodeOnlySerializedHtml},timeout:Ce,root:e,waitForPageLoad:()=>this.waitForPageLoad(),codePath:"finding the closest element on the page"}),u=Math.floor(af*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(Zr(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 h=s.closestNodeSerialized??await Hn(m,o)??"unknown element";o.warn({result:s,originalTarget:t,displayString:h},"Resolved cached target to new node with pure html levenshtein distance");let g=Ga(t);await this.updateCacheWithNewNodeDetails({node:p,target:t,locator:m,logger:o,startingBoundingBox:s.boundingBox,allowNotActionableNodesOverride:a});let f=Hf(g,t);return f&&Object.keys(f).length>0&&(t.cacheResolutionUpdateTime=new Date().toISOString(),t.cacheResolutionUpdateLoggerTags=je(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:h,savedElement:t.nodeOnlySerializedHtml}),{locator:m,a11yNode:p,displayString:h,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&&sf.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=rj(),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,h=d.boundingBox?.height;if(!m||!h)throw i="Rejecting target from screenshot due to no bounding box",new Error(i);let g=d.id,f=this.stateManager.a11yIdToNodeMap[g],y=Ga(t);await this.updateCacheWithNewNodeDetails({target:t,node:f,locator:p,allowNotActionableNodesOverride:o});let S=Hf(y,t);return S&&Object.keys(S).length>0&&(t.cacheResolutionUpdateTime=new Date().toISOString(),t.cacheResolutionUpdateLoggerTags=je(this.logger),t.cacheResolutionUpdateSource="TEMPLATE_MATCHING",this.logger.info({id:s,diffs:S,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:ae})??"",i=zx.some(a=>a===o.toLowerCase());return await _f({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 _f({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(),Tu(l,t,n)){a=!0;break}await ie(At,this.abortSignal)}if(!a)throw new x("ActionFailureError",`The active page URL ${n?.negated?"still does":"does not"} ${cu(t)} in ${o}ms.
|
|
4052
|
+
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:oe});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 ie(n.hoverSeconds?Math.min(n.hoverSeconds*1e3,Ce):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(yf);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 ie(Fa),await this.page.mouse.up()}async hover(e){await this.highlight(e.locator),await Ci({func:async t=>{await this.scrollIntoViewIfNeeded(t.locator);let n=await t.locator.boundingBox({timeout:oe});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 Ci({func:t=>t.locator.focus({timeout:Ce}),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 yt({fn:()=>{let n=document.activeElement;n&&n.nodeType===1&&n.blur()},root:t,arg:void 0,waitForPageLoad:()=>this.waitForPageLoad(),timeout:ae,codePath:"blurring the active element"});return}await this.highlight(e.locator),await Ci({func:t=>t.locator.blur({timeout:Ce}),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 Ci({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:oe})},targetingResult:e})}async press(e,t){let n=t.repeat??1;if(t.convertMeta){let o=Fd(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=Fd(e,this.properties.isAndroid);n!==e&&(this.logger.info({keyString:e,convertedKey:n},"Converted platform dependent keys"),e=n)}for(let n of Bf(e))await this.page.keyboard.down(n)}async keyUp(e,t){if(t.convertMeta){let n=Fd(e,this.properties.isAndroid);n!==e&&(this.logger.info({keyString:e,convertedKey:n},"Converted platform dependent keys"),e=n)}for(let n of Bf(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:dn;o||await this.waitForPageLoad(),e.skipWait||await this.waitForDOMStability({logger:n,signal:l});let d=0,p;for(;d<t;){d++;try{return await G(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 yt({root:e,fn:()=>[window.scrollY,window.scrollX,window.screen.width,window.screen.height,window.devicePixelRatio],arg:void 0,timeout:oe,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 ie(Fa,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<px)){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 ie(n.hoverSeconds?Math.min(n.hoverSeconds*1e3,of):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(yf);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 ie(Fa),await this.page.mouse.up()}async getElementLocation(e){let t=await this.cdpClient.send({method:"DOMSnapshot.captureSnapshot",params:{computedStyles:[],includeDOMRects:!0,includePaintOrder:!0},timeout:oe}),n=await G(this.page.evaluate(()=>window.devicePixelRatio),{milliseconds:Ce});process.platform==="darwin"&&n===1&&(n=ux);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 S=0;S<l.length;S++)if(c[S]===e){d=s.indexOf(S);break}if(d===-1)throw new Error(`Could not find any backend node with ID ${e}`);let[p=0,m=0,h=0,g=0]=u[d];p/=n,m/=n,h/=n,g/=n;let f=p+h/2,y=m+g/2;return{centerX:f,centerY:y}}async scrollVertical(e){return If({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 If({frame:this.stateManager.frameConfig?await this.getActivePageOrFrame():null,page:this.page,deltaX:e?Math.abs(e):null,directionX:e&&e>0?"right":"left",deltaY:0,directionY:null,signal:this.abortSignal,callbacks:this.getBrowserCallbacks(),logger:this.logger})}async goForward(){await this.waitForPageLoad(),await this.page.goForward({waitUntil:"domcontentloaded",timeout:this.pageLoadTimeout}),await this.loadFrameAndRecordUrl({root:this.page,signal:this.abortSignal,codePath:"go-forward"})}async goBack(){await this.waitForPageLoad(),await this.page.goBack({waitUntil:"domcontentloaded",timeout:this.pageLoadTimeout}),await this.loadFrameAndRecordUrl({root:this.page,signal:this.abortSignal,codePath:"go-back"})}async reinitializeCDPClient(e){await this.cdpClient.reinitialize(e),await this.initializeScreencast()}async stopScreencast(){if(this.clientCallbacks?.onScreencastFrame)try{await this.cdpClient.send({method:"Page.stopScreencast",params:{}})}catch{}}async changeActivePage(e,t){await this.stopScreencast(),this.recordUrlVisited(e.url()),this.page=e,await this.reinitializeCDPClient(t??this.pageLoadTimeout)}async createNewTab(e,t){let n=await this.context.newPage();await this.changeActivePage(n,t?.loadTimeoutMs),await this.navigate({url:e,initialNavigation:!0,...t}),this.handleAvailableTabsChange()}async switchToPage(e,t){let n=!0,o,i=Date.now();for(;n||t?.retry&&Date.now()-i<this.smartWaitingTimeout;){n=!1;try{await this.switchToPageHelper(e,t);return}catch(a){this.logger.warn({err:a},"Error switching to page, retrying..."),o=a,await ie(At)}}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)}.
|
|
4053
|
+
Available pages:${JSON.stringify(n.map(i=>i.url))}`);if(!di(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=Pc(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:oe}),n=await fetch("https://api.2captcha.com/createTask",{method:"POST",body:JSON.stringify({clientKey:Ba,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<hx;){await ie(2500);let l=await fetch("https://api.2captcha.com/getTaskResult",{method:"POST",body:JSON.stringify({clientKey:Ba,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 G(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&&y_({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];di(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}}},At);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:ae})}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 Js({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 ${it(i,50)} did not load within the configured timeout (${o}ms): ${l}`);if(!l.message.includes("detached"))throw l}try{await Js({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 XG.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 yt({fn:()=>window.getCondensedHtmlTree(),root:e,arg:void 0,timeout:Ce,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=Ce){let i=await this.getActivePageOrFrame();return yt({root:i,fn:e,arg:t,timeout:o,waitForPageLoad:()=>this.waitForPageLoad(),codePath:n})}async evaluateCodeInPage({code:e,fragment:t,context:n,timeoutMs:o=uo}){let i=Ix(),a={code:e,fragment:t,context:n},{result:l}=await G(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:Ce});let n;try{n=await this.cdpClient.send({method:"DOM.getNodeForLocation",params:{x:e,y:t},timeout:ae})}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:ae,params:{highlightConfig:Kx,backendNodeId:n.backendNodeId}}),async()=>{try{await this.cdpClient.send({timeout:ae,method:"Overlay.hideHighlight",params:{backendNodeId:n?.backendNodeId}})}catch{}}):async()=>{}}async clearAllCdpHighlights(){try{await this.cdpClient.send({method:"Overlay.hideHighlight",params:void 0,timeout:ae})}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[zn],a=parseInt(i??"");if(!i||isNaN(a))throw new Error("No data-momentic-id was found on the DOM node");let l=e.locator(Zr(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 G(this.performTargetRedirectionHelper(e,t,n),{milliseconds:oe})??{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 Hn(e,t);if(n===void 0&&(n=await e.boundingBox({timeout:oe})??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:h,serializedElement:g,foundElementRelativePoint:f,force:y,logs:S}=await e.evaluate(R=>{let A=window;if(!A.performTargetRedirection)throw new Error("performTargetRedirection script is not defined");return A.performTargetRedirection(R)},void 0,{timeout:ae}),E=Date.now()-o;if(h){t.warn({error:h,serializedElement:g,duration:E,force:y,logs:S},"Got error from target redirection with bounding box");return}else{if(p)return t.info({newDataMomenticId:p,serializedElement:g,duration:E,force:y,logs:S},"Redirected target to new element with bounding box with data-momentic-id"),{locator:d.locator(Zr(p)),hints:{relativeXYToLocator:f,force:y}};if(m)return t.info({newMPathSelector:m,serializedElement:g,duration:E,force:y,logs:S},"Redirected target to new element with bounding box with mPath"),{locator:d.locator(m),hints:{relativeXYToLocator:f,force:y}};if(f)return t.info({foundElementRelativePoint:f,serializedElement:g,duration:E,force:y,logs:S},"Chose specific visible point on original element"),{locator:e,hints:{relativeXYToLocator:f,force:y}};if(y)return t.info({serializedElement:g,duration:E,force:y,logs:S},"Forcing click on original element"),{locator:e,hints:{force:y}}}}async fetchHtmlAttributes({locator:e,logger:t=this.logger,startingBoundingBox:n,allowNotActionableNodesOverride:o}){let{hybridSelectorMode:i,showZeroOpacityElements:a}=this.userControlledBrowserSettings,l=await e.evaluate((c,s)=>{let u=window;return u.generateHtmlCacheAttributes?u.generateHtmlCacheAttributes(c,s):{warnings:[],error:"generateHtmlCacheAttributes is not defined"}},{generateHybridSelector:i==="test"||i==="prefer",startingBoundingBox:n,showZeroOpacityElements:o?!0:a},{timeout:Ce});if("error"in l&&l.error)throw l.error.startsWith(sx)?new dc(l.error):l.error.startsWith(lx)?new pc(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:ae})}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!!Ba}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,ff(e,this.debugData,i,{type:t,text:`[MOMENTIC] ${n}`,args:o})}async setFileChooserHandlerHelper({filePath:e,filename:t}){if(!jd(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()||ZG(e),o=qG(e),i=ej(e),a=Vm[i];this.page.once("filechooser",async c=>{this.logger.info({filePath:e,fileName:n},"File chooser triggered");try{if(!jd(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:JG.getType(e)||"application/octet-stream"},{timeout:of})}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 g=0;g<p.length;g++)m[g]=p.charCodeAt(g);let h=new Uint8Array(m);d.MomenticFile=class extends Blob{kind="file";name=d.momenticFileName;constructor(){super([h],{type:u})}isSameEntry(g){return g.name===this.name}queryPermission(g){return console.info("[MOMENTIC] MomenticFile.queryPermission called"),Promise.resolve("granted")}remove(){return console.info("[MOMENTIC] MomenticFile.remove called"),Promise.resolve()}async requestPermission(g){return console.info("[MOMENTIC] MomenticFile.requestPermission called"),Promise.resolve("granted")}async getFile(){console.info("[MOMENTIC] MomenticFile.getFile called");let g=new Blob([h]);return new File([g],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??zf();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??dx}get userBrowserSettings(){return Ga(this.userControlledBrowserSettings)}get pageLoadTimeout(){return this.userControlledBrowserSettings.pageLoadTimeoutMs??rf}get isInPageLoad(){return Object.values(this.pageLoadPromises).length>0}get devicePixelRatio(){return this.properties.systemDevicePixelRatio??1}get browserCrashDumpDir(){let e=kd();for(let t of e)if(!(!jd(t)||!E_(t).isDirectory()||!["new","pending","completed"].some(o=>{let i=tj(t,o);return jd(i)&&E_(i).isDirectory()&&KG(i).length>0})))return t}};import Tj from"fetch-cookie";import{cloneDeep as N_}from"lodash-es";import{CookieJar as bj}from"tough-cookie";import{randomUUID as lj}from"crypto";var A_={minChunkTokenCount:500,acceptableChunkTokenCount:3e3,maxChunkTokenCount:8e3,maxLineLength:4e3},R_={minChunkTokenCount:5e3,acceptableChunkTokenCount:1e4,maxChunkTokenCount:3e4,maxLineLength:500},v_=/<(\S+) id="(\d+)".*?>/g,nj=/(<\/(\S+)>)|(<(\S+).*?\/>)/g,w_=["h1","h2","section","footer","nav","aside","form","label","dialog"],oj=[...w_,"span","div","h3"],ij=["table","select","form","ul","ol","menu","pre","code","dialog"],aj=["table","form","dialog","nav","section","ul","select"];function Vd(r){return sj(r)}function sj({logger:r,serializedTree:e,options:t}){let{minChunkTokenCount:n,acceptableChunkTokenCount:o,maxChunkTokenCount:i,maxLineLength:a}=t,l=[],c=e.split(`
|
|
4055
4054
|
`),s=0,u=[],d=0,p=[],m=[],h=!1;for(;s<c.length;){h&&(l.push({ids:p,content:u.join(`
|
|
4056
4055
|
`),tokenLength:d}),u=[],d=0,p=m.length?[m[m.length-1].id]:[],h=!1);let g=c[s],f=Ot(g);d+=f,g.length>a&&(g=g.slice(0,a));let E=Array.from(g.matchAll(v_)).map(z=>z&&z.length>=3?{tagName:z[1],id:z[2]}:void 0).filter(z=>!!z),A=Array.from(g.matchAll(nj)).map(z=>z&&(z[2]||z[4])).filter(z=>!!z);A.reverse();let C=g.replace(/ id="[0-9]+"/g,"");u.push(C);for(let z of E)p.push(z.id),m.push(z);for(let z of A){let j=m[m.length-1];j&&j.tagName===z&&m.pop()}let w=m.some(z=>ij.includes(z.tagName)),I=c[s+1]??"",P=Ot(I),q=Array.from(I.matchAll(v_)).map(z=>z&&z.length>2?z[1]:void 0).filter(z=>!!z),k=q.some(z=>w_.includes(z)),ee=q.some(z=>oj.includes(z));d+P>=i&&(h=!0),d>=n&&(k&&!w||A.some(z=>aj.includes(z)))&&(h=!0),d>=o&&ee&&!w&&(h=!0),s++}return u.length&&l.push({ids:p,content:u.join(`
|
|
4057
|
-
`),tokenLength:d}),l.forEach((g,f)=>{let
|
|
4056
|
+
`),tokenLength:d}),l.forEach((g,f)=>{let y=g.ids[0],S=g.ids[g.ids.length-1];r.debug({tokenLength:g.tokenLength,minId:y,maxId:S},`Chunk for page filtering (index ${f+1}/${l.length})`)}),{chunks:l}}var cj=75e4,$d=3e5,uj=5e3;async function _i(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=Ot(u);if(d>cj)try{let p=Vd({serializedTree:u,options:{minChunkTokenCount:1e4,maxChunkTokenCount:1e5,acceptableChunkTokenCount:5e4,maxLineLength:4e3},logger:i});s=await pj({...r,tokenLimit:$d-1e4,chunks:p.chunks}),u=s.serialize();let m=Ot(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($d*ho),u=s.serialize();let m=Ot(u);i.info({oldTokens:d,newTokens:m},"Filtered page using naive truncation"),d=m}if(d>$d)try{if(o){let p=Vd({serializedTree:u,options:R_,logger:i}),m=lj();s=await G(dj({...r,chunks:p.chunks,callId:m}),{milliseconds:12e3,signal:c}),u=s.serialize();let h=Ot(u);i.info({oldTokens:d,newTokens:h,langfuseCallId:m},"Filtered page using AI chunk ranking"),d=h}else{let p=Vd({serializedTree:u,options:A_,logger:i});s=await G(mj({...r,chunkResult:p,tokenLimit:4e4}),{milliseconds:12e3,signal:c}),u=s.serialize();let m=Ot(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($d*ho),u=s.serialize(),i.info("Filtered page using naive truncation")}if(o&&d>uj&&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:je(i),abortSignal:c});if(i.info(p,"Got AI summaries"),p.category!=="OTHER"){let m=new Set;for(let g of p.relevantSections){let f=Math.min(g.startId,g.endId),y=Math.max(g.startId,g.endId);for(let S=f;S<=y;S++)m.add(S.toString())}s=s.pruneUsingRelevantIds(m),u=s.serialize();let h=Ot(u);i.info({newTokens:h,oldTokens:d},"Filtered page using AI summary"),d=h}}catch(p){i.warn({err:p},"Error filtering page using AI summary, continuing...")}return u}async function dj({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:je(c)}),u=[];return t.forEach((p,m)=>{s.indices.includes(m)&&(u=u.concat(p.ids))}),i.pruneUsingRelevantIds(new Set(u))}async function pj(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:je(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,h)=>m+h.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 mj(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:je(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 jf(r,e){if(!r.description)throw new x("UserConfigurationError","Cannot locate element with empty description");return An({action:async()=>hj(r,e),frameConfig:r.iframeUrl?{type:"url",url:r.iframeUrl}:void 0,browser:e.browser,logger:r.logger})}async function hj(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:h,generator:g,abortSignal:f}=e,y=r.description,S=r.useMemory&&!t;n&&(y=await fr({orgId:p,s:y,context:n,localTools:h,signal:f,logger:s})),a&&(y=fj(y,a));let{serializedTree:E,tree:R}=await xo(m,{allowNotActionableNodesOverride:u,filterByViewport:o,abortSignal:f,skipWait:i,logger:s}),A,C=Date.now(),w;for(;!A&&Date.now()-C<3e3;){f.throwIfAborted();try{A=await m.screenshot({clearHighlights:!0,respectActiveFrame:!0,retries:2})}catch($){w=$}}if(!A)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 I=E,P=!1,q=`data:image/jpeg;base64,${A.toString("base64")}`;I=await _i({type:"locator",description:y,screenshot:q,serializedTree:E,options:{aiPageFiltering:c},tree:R,fixtures:{generator:g,signal:f,logger:s,orgId:p}}),I!==E&&(P=!0);let k=await g.getElementLocation({browserState:I,goal:y,screenshot:q,source:a,memory:S?l:void 0},{disableCache:t,abortSignal:f,loggerTags:je(s),useMemory:S});s.debug({usedRag:P,result:k},"Got locator result");let ee=k.id>0;if(d?.details?.push({type:"AI_LOCATION",matched:ee,pageState:I,ragUsed:P,thoughts:k.thoughts}),!ee)throw new Vi(`Could not find any relevant element: ${k.thoughts}`,k.updatedMemory?{type:"GCS_TRACES",traces:k.updatedMemory}:void 0);let{resolution:z,target:j,frameConfig:he}=await m.createTargetFromA11yId({id:k.id,requirements:k.requirements,additionalElements:k.additionalElements,description:y,targetSource:"AI",logger:s});if(z.a11yNode?.properties?.hidden&&z.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: ${z.displayString}`);return S&&(k.updatedMemory?j.memory={type:"GCS_TRACES",traces:k.updatedMemory}:l&&(j.memory=l)),{thoughts:k.thoughts,target:j,resolution:z,frameConfig:he,screenshot:q}}var gj=["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:"],C_="<select> element:",x_="text input or contenteditable element:",__="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:",I_="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:",Gf=[C_,x_,__,I_,...gj];function M_(r,e){if(r===e)return!0;for(let t of Gf){if(!r.startsWith(t))continue;let n=r.slice(t.length).trim();if(Gf.some(o=>e.startsWith(o)&&e.slice(o.length).trim()===n)||n===e.trim())return!0}return!!Gf.some(t=>e.startsWith(t)&&e.slice(t.length).trim()===r.trim())}function fj(r,e){if(!r||!e)return r;switch(e){case"SELECT_OPTION":return`${C_} ${r}`;case"TYPE":return`${x_} ${r}`;case"NEGATED_ELEMENT_VISIBLE_CHECK":return`${__}
|
|
4058
4057
|
${r}`;case"ELEMENT_CHECK":return`${I_}
|
|
4059
|
-
${r}`;default:return r}}var Sj=15;async function Wd({command:r,aiPageFiltering:e,logger:t,fixtures:n,source:o,useMemory:i,maxRetries:a=Sj}){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=zv(c),u=0,d=Date.now(),p,m,h;try{await An({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 g;for(;u<a&&(!g||g-d<c);){n.abortSignal.throwIfAborted(),u!==0&&await ie(s,n.abortSignal),g=Date.now();try{if(p=await An({action:async()=>{let S=await P_(l,t,n.abortSignal);return m&&m.serializedTree===S.serializedTree&&m.screenshotBuff.equals(S.screenshotBuff)?p:(m=S,O_({command:r,state:S,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&&su(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(),h=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 An({action:async()=>O_({command:r,state:await P_(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(),h=f instanceof Error?f:new Error(`${f}`)}finally{u++}if(!p?.success){let f=`AI check still failing after ${u} attempts.`;throw h&&(f+=` Latest result: ${h.message}`),new x("AssertionFailureError",f)}return{...p,succeedImmediately:!1,urlAfterCommand:l.url()}}async function P_(r,e,t){let[n,o]=await Promise.all([xo(r,{abortSignal:t,skipWait:!0,skipWaitForPageLoad:!0,logger:e}),r.screenshot({retries:1,respectActiveFrame:!0})]);return{...n,screenshotBuff:o}}async function O_({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:h,tree:g}=e,f=e.screenshotBuff,S=f.toString("base64"),y=u.url(),E=r.contextChoice??"MULTIMODAL",R=h;E!=="VISION_ONLY"&&(R=await _i({type:"assertion",serializedTree:h,tree:g,description:r.assertion,screenshot:S,options:{aiPageFiltering:a},fixtures:{generator:d,signal:p,logger:s,orgId:t.orgId}}),R!==h&&(m.ragUsed=!0),m.pageState=R);let A={goal:r.assertion,url:y,memory:o?r.cache?.memory:void 0,browserState:R,screenshot:S,contextChoice:E,source:c},w=await(E==="VISION_ONLY"?(I,P)=>d.getVisualAssertionResult(I,P):(I,P)=>d.getAssertionResult(I,P))(A,{useConsensus:n,attemptNumber:l,useMemory:o,disableCache:!!r.disableCache,abortSignal:p,logger:s,loggerTags:je(s)});return(w.result||i)&&w.relevantElements&&(m.relevantElementsSerialized=w.relevantElements.map(I=>u.getSerializedFormFromA11yId(I)).filter(I=>!!I),await yj(w.relevantElements,u,s)),{success:w.result,thoughts:w.thoughts,afterScreenshotOverride:f,updatedMemory:o?w.updatedMemory:void 0}}async function yj(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 G(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 Ej=3e4;async function L_({command:r,logger:e,baseUrl:t,fetchImplementation:n=fetch}){let o=r.timeout??Ej/1e3,i=new AbortController,a=Object.fromEntries(Object.entries(r.headers||{}).filter(([d,p])=>d&&p));a["Content-Type"]="application/json";let l;if(da(r.url)&&(l=r.url),t&&pa(r.url,t)&&(l=new URL(r.url,t).toString()),!l)throw new x("ActionFailureError",`Invalid URL: ${r.url}`);let s=await G((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 Po=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([xo(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 _i({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:{...je(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([xo(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 _i({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:{...je(a)},langfuseSessionId:l})}catch(h){throw new x("InternalWebAgentError",`Error generating command: ${h instanceof Error?h.message:h}`,{errOptions:{cause:h}})}}async getBrowserState(e){return xo(this.browser,e)}async locateElement(e){return await jf({...e,aiPageFiltering:!!this.options?.aiPageFiltering},this.getControllerFixtures())}async locateElementWithSelector(e,t){return An({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 h=>h,options:{...c,targetName:o[d]}});u.push(m)}try{let d=await l(...u.map(h=>h.result)),p=h=>h==="fromTarget"?"From Target":h==="toTarget"?"To Target":"Target",m=u.map((h,g)=>h.thoughts?`${p(o[g])}: ${h.thoughts}`:void 0).filter(h=>!!h).join(" -------------- ")||void 0;return{result:d,elementInteractedDisplayStrings:u.map(h=>h.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 An({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&&Zp(i)){t.warn({err:i},"Invalid mpath error, retrying element targeting command");continue}if(!this.browser.userBrowserSettings.visualActions&&(tm(i)||em(i))){t.warn({err:i},"Invalid momentic id error, retrying element targeting command");continue}if(rm(i)){t.warn({err:i},"Invalid backend node id error, retrying element targeting command");continue}if(i instanceof sn&&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 ie(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,h=this.logger.child({commandId:c.id}),g=this.shouldUseMemory(),f=l.retriesWithAI??1,S=!1,y=N_(e.cache);if((!y||s)&&!kp(o))throw new x("ActionFailureError","Cannot target element with no cached data or element descriptor");if(u)return this.wrapHardcodedCssTargetingCommandHelper(e);s&&(h.info("Cache explicitly disabled for this step"),S=!0,y=void 0),y&&this.browser.userBrowserSettings.disableSecondaryCacheResolution&&y.targetSource==="HEURISTIC_HEALED"&&(S=!0,y=void 0),y?.inputDescription&&!M_(o.elementDescriptor,y.inputDescription)&&(h.warn({old:y.inputDescription,new:o.elementDescriptor},"Target cache was generated with a different description, clearing it automatically"),S=!0,y=void 0);let E=A=>!!A&&Kl(A),R=!0;if(!E(y)){R=!1,h.info({description:o.elementDescriptor,targetHealingInProgress:p,cacheBustedBeforeAction:S,memory:l.memory,useMemory:g},"Prompting AI for an updated element location"),S&&await ie(this.browser.smartWaitingTimeout,this.executeAbortController.signal),f--;let A;try{A=await jf({description:o.elementDescriptor,disableCache:!!l.disableCache,iframeUrl:l.iframeUrl,source:m,useMemory:g,memory:g?l.memory:void 0,aiPageFiltering:!!this.options?.aiPageFiltering,allowNotActionableNodesOverride:l.allowNotActionableNodesOverride,logger:h},this.getControllerFixtures(t))}catch(I){if(I instanceof Vi&&I.updatedLocatorMemory){let P={id:-1,...i,memory:I.updatedLocatorMemory};au({cmd:c,key:d,newTarget:P,logger:h,updatedWithAI:!0})}throw new x("ActionFailureError",I.message)}A.frameConfig&&this.browser.setActiveFrameConfig(A.frameConfig);let C=l.disableGlobalLocatorRedirect?{locator:A.resolution.locator}:await this.attemptLocatorRedirect(A.resolution.locator,h),w=await a(C);return au({cmd:c,key:d,newTarget:A.target,logger:h,updatedWithAI:!0}),p&&(n.recordTargetAutoHeal({healType:"AI"}),A.target.targetSource="AI_HEALED",A.target.targetUpdateTime=new Date().toUTCString(),A.target.targetUpdateLoggerTags=je(h)),{result:w,elementInteractedDisplayString:A.resolution.displayString,thoughts:A.thoughts}}try{let A=await this.browser.resolveTarget(t,y,{allowNotActionableNodesOverride:l.allowNotActionableNodesOverride,targetName:d,logger:h,signal:this.executeAbortController.signal});(this.browser.userBrowserSettings.visualActions||this.browser.userBrowserSettings.globalLocatorRedirect!==!1)&&await this.browser.scrollIntoViewIfNeeded(A.locator);let C=l.disableGlobalLocatorRedirect?{locator:A.locator}:await this.attemptLocatorRedirect(A.locator,h),w=await a(C);if(or.increment("cache_target_resolution_v2",1,["outcome:hit","platform:web",`hasRequirements:${!!y.requirements}`,`hasAdditionalElements:${!!y.additionalElements}`,`orgId:${this.orgId}`]),au({cmd:c,key:d,newTarget:y,logger:h,updatedWithAI:!1}),R){let I=A.decisions.filter(P=>P.matched);if(I.length!==1)h.warn({decisions:A.decisions},"Expected exactly 1 matching method for element location, got more or less");else{let P=I[0].type;n.recordTargetAutoHeal({healType:P})}}return{result:w,elementInteractedDisplayString:A.displayString}}catch(A){this.throwIfClosed(),or.increment("cache_target_resolution_v2",1,["outcome:miss","platform:web",`hasRequirements:${!!y.requirements}`,`hasAdditionalElements:${!!y.additionalElements}`,`orgId:${this.orgId}`]);let C=!1;if((A instanceof sn||Zp(A)||tm(A)||rm(A)||Ny(A)||em(A))&&(C=!0),A instanceof x&&!C)throw h.error({err:A},"Failed to execute action with cached target (fatal)"),A;if(f>0&&o){h.info({err:A},"Failed to execute action with cached target, retrying with AI");let w;return y.memory&&Yl(y.memory)&&(w=y.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",A.message,{errOptions:{cause:A}})}}async attemptLocatorRedirect(e,t){return this.browser.userBrowserSettings.globalLocatorRedirect!==!1?this.browser.performTargetRedirection(e,t):{locator:e}}async screenshotWithDimensions(e){return sl(this.browser,e)}async executePresetCommand(e,t,n,o,i){this.options?.slowMoMs&&await ie(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&&YS(n)?await this.browser.waitForDOMStability({timeout:Ce}):!this.browser.userBrowserSettings.visualActions&&["PRESS","TYPE"].includes(n.type)&&await this.browser.waitForDOMStability({timeout:ae}),this.options?.autoFollowNewTabs&&await tx({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{CA(n,c)}}createCallbacksForBrowser(e){return{createIsolatedFolder:()=>hf(e)}}async resolveCommandTemplateStrings(e,t){return Pu({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()?Wd({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 Wd({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=vb(n.schema);if(f)throw new x("UserConfigurationError",f)}let h=await this.browser.getCondensedHtml(),g=await this.browser.screenshot({retries:2});try{let f=await this.generator.getTextExtraction({goal:n.goal,browserState:h,returnSchema:n.schema,screenshot:`data:image/jpeg;base64,${g.toString("base64")}`},{disableCache:i,abortSignal:this.executeAbortController.signal,loggerTags:je(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 S=f.message;throw S.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."):S.includes("AIProviderError")&&S.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(!da(n.url)&&!pa(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:h=>this.browser.click(h,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 h,g;if(n.target&&rn(n.target))await this.browser.hoverUsingVisualCoordinates(n.target.pixels);else if(n.target&&n.target.elementDescriptor.trim()){let{elementInteractedDisplayString:y,thoughts:E}=await this.wrapElementTargetingCommand({ctx:e,tracer:t,command:n,target:n.target,cache:n.cache?.target,action:R=>this.browser.hover(R),options:{...n,targetName:"target",disableGlobalLocatorRedirect:!0,disableCache:i}});h=y,g=E}let f=this.browser.getViewport()?.height??Gt.height,S=this.browser.getViewport()?.width??Gt.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??S));break;case"SCROLL_RIGHT":await this.browser.scrollHorizontal(n.deltaX??S);break}return{succeedImmediately:!1,urlAfterCommand:this.browser.url(),elementInteracted:h,thoughts:g}}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 h=n.matcher;await this.browser.waitForUrl({beforeUrl:this.browser.url(),matcher:h},{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 ie(s,this.executeAbortController.signal);break;case"REFRESH":await this.browser.refresh({loadTimeoutMs:n.loadTimeout?n.loadTimeout*1e3:void 0});break;case"CLICK":{if(rn(n.target)){await this.browser.clickUsingVisualCoordinates(n.target.pixels,n);break}let h=this.browser.url(),{elementInteractedDisplayString:g,result:f,thoughts:S}=await this.wrapElementTargetingCommand({ctx:e,tracer:t,target:n.target,command:n,cache:n.cache?.target,action:E=>this.browser.click(E,this.createCallbacksForBrowser(this.orgId),n),options:{disableCache:i,targetName:"target",...n}}),y={urlAfterCommand:this.browser.url(),succeedImmediately:!1,elementInteracted:g,thoughts:S,data:f.downloadedFile?{downloadedFile:f.downloadedFile}:void 0};return bu(h,y.urlAfterCommand)&&(y.succeedImmediately=!0,y.succeedImmediatelyReason="URL changed"),y}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(rn(n.fromTarget)&&rn(n.toTarget)){await this.browser.dragAndDropUsingVisualCoordinates(n.fromTarget.pixels,n.toTarget.pixels,{hoverSeconds:n.hoverSeconds});break}if(rn(n.fromTarget)||rn(n.toTarget))throw new Error("Drag and drop targets must be both coordinates or both descriptions");let{elementInteractedDisplayStrings:h,thoughts:g}=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,S)=>this.browser.dragAndDrop(f.locator,S.locator,{hoverSeconds:n.hoverSeconds,steps:n.steps}),options:{useSelector:!!n.useSelector,disableCache:i}});return{succeedImmediately:!1,urlAfterCommand:this.browser.url(),elementInteracted:h[0],thoughts:g}}case"MOUSE_DRAG":{let h=parseInt(n.deltaX),g=parseInt(n.deltaY),f=n.steps??5;if(isNaN(h)||isNaN(g))throw new x("ActionFailureError",`Invalid pixel values passed to mouse drag command: (${n.deltaX}, ${n.deltaY})`);if(n.target&&rn(n.target)){await this.browser.mouseDragUsingVisualCoordinates(h,g,f,n.target.pixels,{force:n.force});break}let S,y,E;if(n.target?.elementDescriptor){let{elementInteractedDisplayString:R,result:A,thoughts:C}=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}});S=A,y=R,E=C}return await this.browser.mouseDrag(h,g,f,S,{force:n.force}),{succeedImmediately:!1,urlAfterCommand:this.browser.url(),elementInteracted:y,thoughts:E}}case"SELECT_OPTION":{if(!Zn(n.target))throw new Error("Select with x/y is not supported yet");let h=n.target.elementDescriptor,g=n.choice,{elementInteractedDisplayString:f,thoughts:S}=await this.wrapElementTargetingCommand({ctx:e,tracer:t,command:n,target:{type:"description",elementDescriptor:h},cache:n.cache?.target,action:y=>this.browser.selectOption(y,g,n.force),options:{...n,targetName:"target",disableCache:i,source:Yo(n)}});return{succeedImmediately:!1,urlAfterCommand:this.browser.url(),elementInteracted:f,thoughts:S}}case"TAB":{let h={loadTimeoutMs:n.loadTimeout?n.loadTimeout*1e3:void 0,retry:!0};await this.browser.switchToPage(n.action,h);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 h;try{n.environment==="BROWSER"?(h=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:h},"Executed JavaScript in browser")):h=await To({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 g=>{if(!this.options?.scratchPadId){a.warn({updates:g},"Got persistent variable updates but scratch pad is not available");return}await this.storage.savePersistentVariables?.({scratchPadId:this.options?.scratchPadId,orgId:this.orgId,updates:g,logger:a})}}})}catch(g){throw this.throwIfClosed(),new x("ActionFailureError",g instanceof Error?g.message:`${g}`,{errOptions:{cause:g}})}try{JSON.stringify(h)}catch(g){throw new x("ActionFailureError",`Return value is not serializable: ${g instanceof Error?g.message:`${g}`}`,{errOptions:{cause:g}})}return{urlAfterCommand:this.browser.url(),succeedImmediately:!1,data:h}}case"TYPE":{if(n.target&&rn(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 h=this.browser.url(),g,f,S=N_(n.target),y=this.browser.userBrowserSettings.globalLocatorRedirect===void 0||this.browser.userBrowserSettings.globalLocatorRedirect==="always";if(S){let{elementInteractedDisplayString:R,thoughts:A}=await this.wrapElementTargetingCommand({ctx:e,tracer:t,command:n,target:S,cache:n.cache?.target,action:C=>this.browser.typeIntoTarget(n.value,C,{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:!y,source:Yo(n)}});g=R,f=A}else await this.browser.type(n.value,{force:n.force,clearContent:n.clearContent,forceClearContent:n.forceClearContent,delay:n.delay,pressEnter:n.pressEnter},!0);let E={urlAfterCommand:this.browser.url(),succeedImmediately:!1,elementInteracted:g,thoughts:f};return bu(h,E.urlAfterCommand)&&(E.succeedImmediately=!0,E.succeedImmediatelyReason="URL changed"),E}case"HOVER":{if(rn(n.target)){await this.browser.hoverUsingVisualCoordinates(n.target.pixels);break}let{elementInteractedDisplayString:h,thoughts:g}=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:h,thoughts:g}}case"FOCUS":{if(!Zn(n.target))throw new Error("Focus with x/y is not supported yet");let{elementInteractedDisplayString:h,thoughts:g}=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:h,thoughts:g}}case"BLUR":{if(n.target&&!Zn(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:h,thoughts:g}=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:h,thoughts:g}}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 bu(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 h=new bj,g=Tj(fetch,h),f;try{f=new URL(n.url).hostname}catch{}return{data:{...await LA({command:n,baseUrl:this.browser.baseUrl,logger:a,fetchImplementation:g}),cookies:BE(h,f)},succeedImmediately:!1,urlAfterCommand:this.browser.url()}}case"GRAPHQL_REQUEST":return{data:await L_({command:n,baseUrl:this.browser.baseUrl,logger:a}),succeedImmediately:!1,urlAfterCommand:this.browser.url()};case"VISUAL_DIFF":return OA({ctx:e,tracer:t,command:n,disableCache:i,browser:this.browser,logger:a,storage:this.storage,screenshotStorage:this.visualDiffScreenshotStorage,targetingWrapper:h=>this.wrapElementTargetingCommand(h)});case"FILE_UPLOAD":{let h,g;if(n.fileSource.type==="URL"?(g=n.fileSource.url,h=await Sx({uri:n.fileSource.url,logger:a,orgId:this.orgId})):n.fileSource.type==="USER_FILE"&&(g=n.fileSource.name,h=await this.uploadedFileStorage?.getFileForUpload(n.fileSource.name,this.orgId)),!h)throw new x("UserConfigurationError",`Attempted to use non-existent file for upload step: ${g}`);await this.browser.setFileChooserHandler({...h,filename:n.filename});break}case"AUTH_SAVE":return{data:await this.browser.saveAuthState(),succeedImmediately:!1,urlAfterCommand:this.browser.url()};case"AUTH_LOAD":{let h;if(!n.storageState.trim())h=void 0;else if(h=await To({orgId:this.orgId,code:n.storageState,fragment:!1,context:o,logger:a,localTools:this.localCodeEvalTools,signal:this.executeAbortController.signal}),typeof h!="object")throw new x("ActionFailureError",`Credentials must evaluate to an object (received ${typeof h} instead)`);let g;try{g=Oc.optional().parse(h)}catch(f){throw new x("ActionFailureError",`Credentials provided do not follow the required format: ${f}`)}await this.browser.loadAuthState(g);break}case"ELEMENT_CHECK":{let h=(n.timeout??nn)*1e3,g=this.generator.getAgentConfig()?.assertion;if(MA(n.assertion)&&!n.useSelector&&n.target.type==="description"&&g&&g!=="v1"){let S={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 y=await Wd({command:S,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: ${y.thoughts}`,urlAfterCommand:this.browser.url(),afterScreenshotOverride:y.afterScreenshotOverride}}finally{S.cache?.memory&&su(n,S.cache?.memory.traces,a)}}let f=await IA({command:n,tracer:t,timeoutMs:h,targetingWrapper:S=>this.wrapElementTargetingCommand(S),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 h=await An({action:async()=>Lu({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:!h.success,data:h.data,thoughts:h.success?"Page assertion passed.":h.err?.message??`Page assertion still failing after ${n.timeout} seconds.`,urlAfterCommand:this.browser.url(),succeedImmediately:!1}}case"REGISTER_REQUEST_LISTENER":{let h=new Io(n.requestMatcher),g=this.browser.registerRequestListener(h);return this.registeredListeners[n.key]=g.then(async f=>await Tf(f)).catch(f=>{a.error({err:f},"Failed to get request listener response")}),{succeedImmediately:!1,urlAfterCommand:this.browser.url()}}case"AWAIT_LISTENER":{let h=this.registeredListeners[n.key];if(!h)throw new x("ActionFailureError",`No listener registered with key: ${n.key}`);let g=n.timeout??10;return{data:await G(h,{milliseconds:g*1e3,message:`Request listener timed out after ${g} seconds`}),succeedImmediately:!1,urlAfterCommand:this.browser.url()}}case"RECORD_REQUESTS":{let h=new Io(n.requestMatcher);return this.recordedRequests[n.key]={},this.browser.registerRequestRecorder(n.key,h,{onRequestStart:(g,f)=>{this.recordedRequests[n.key][g]=Dd(f)},onRequestComplete:(g,f)=>{this.recordedRequests[n.key][g]=Dd(f)}}),{succeedImmediately:!1,urlAfterCommand:this.browser.url()}}case"GET_RECORDED_REQUESTS":{let h=this.recordedRequests[n.key];if(!h)throw new x("ActionFailureError",`No recorder registered with key: ${n.key}`);return delete this.recordedRequests[n.key],{data:Object.values(h),succeedImmediately:!1,urlAfterCommand:this.browser.url()}}case"SET_HEADER":{let h;return n.requestMatcher&&(h=new Io(n.requestMatcher)),this.browser.setHeader(n.name,n.value,h),{succeedImmediately:!1,urlAfterCommand:this.browser.url()}}case"MOCK_ROUTE":return{data:{key:this.browser.registerMock(n.key,new Io(n.requestMatcher),async(g,f)=>{let S=await To({orgId:this.orgId,code:n.responseGenerator,fragment:!1,context:o,timeoutMs:void 0,logger:a,localTools:this.localCodeEvalTools,mock:{request:g,response:f},disallowVariableUpdates:!0,responseSerialization:"RESPONSE"}),y=QE.parse(S);return new Response(y.body,{status:y.status,headers:y.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(h=>{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:je(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 Hd({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:je(this.logger)})}async getFailureRecoveryPlan(e){return this.generator.getFailureRecoveryPlan(e,{disableCache:!0,abortSignal:this.executeAbortController.signal,loggerTags:je(this.logger)})}};import{cloneDeep as vj}from"lodash-es";var Aj={showOverlay:!1},qd=class{sessions=new Map;sessionCountByIp=new Map;getCurrentConnectionsByIp(e){return this.sessionCountByIp.get(e)??0}getCurrentSessionsByIp(){return Object.fromEntries(this.sessionCountByIp)}reserveCapacityByIp(e){e&&this.sessionCountByIp.set(e,(this.sessionCountByIp.get(e)??0)+1)}releaseCapacityByIp(e){e&&this.sessionCountByIp.set(e,Math.max(this.getCurrentConnectionsByIp(e)-1,0))}registerSession({controller:e,context:t,cleanup:n,clientIp:o,sessionId:i,socket:a}){return this.sessions.set(i,{controller:e,context:t,cleanup:n,clientIp:o,browserBehavior:vj(Aj),socket:a}),i}removeSession(e,t){(async()=>{let o=this.sessions.get(e);if(!o)return;this.releaseCapacityByIp(o.clientIp);let{controller:i}=o;try{i.setClosed(),await i.browser.cleanup()}catch(a){t.error({err:a},"Error cleaning up browser in global state manager")}try{await o.cleanup?.()}catch(a){t.error({err:a},"Error running cleanup function in global state manager")}this.sessions.delete(e)})()}getSession(e){return this.sessions.get(e)}};function D_(r,e,t,n){let o=Date.now(),i=Date.now(),a,l,c,s,u=!1,d=async(g,f)=>{if(!g.closed&&!g.isInPageLoad)try{let S=c;c=void 0;let y=g.url(),E=f.toEditorDisplayCopy();JSON.stringify(E)===JSON.stringify(a)&&y===s&&o>i||(r.emit("browserState",{logsPerPage:S?.logsPerPage,harPages:S?.harPages,harEntries:S?.harEntries,viewport:g.getViewport(),url:y,iframeSrcUrls:l??[],context:E,isInPageLoad:g.isInPageLoad}),o=Date.now()),s=y,a=E}catch(S){if(!r.connected)return;let y=S instanceof Error?S.message:`${S}`;if(y.includes("Frame was detached")||y.includes("Not attached to an active page")||y.includes("browser has been closed")||y.includes("UserInfrastructureError"))return;t.error({err:S,sessionId:e},"Error grabbing browser state")}},p=setInterval(()=>{let g=n.getSession(e),f=g?.controller?.browser;if(!f||f.closed){t.debug("Clearing browser state socket cron due to the browser being closed"),clearInterval(p);return}d(f,g.context)},1e3),m=(g,f)=>!!(JSON.stringify(g)!==JSON.stringify(l)||f.logsPerPage.some(S=>S.length>0)||f.harPages&&Object.keys(f.harPages).length>0||f.harEntries&&Object.keys(f.harEntries).length>0),h=setInterval(async()=>{let f=n.getSession(e)?.controller?.browser;if(!f||f.closed){clearInterval(h);return}else if(u)return;u=!0;try{let S=await f.getAllFrameUrls(),y=f.retrieveAndClearDebugData();m(S,y)&&(l=S,c=y,i=Date.now())}catch(S){t.warn({err:S},"Failed to fetch extended details")}finally{u=!1}},2500);return{timers:[p,h]}}var Rj=4;async function k_({socket:r,logger:e,storageFactory:t,uploadedFileStorage:n,visualDiffScreenshotStorage:o,devicePixelRatio:i,generatorFactory:a,enricherFactory:l,authorization:c,settingsFactory:s,getOrgId:u,branchGetter:d,globalE2eStateManager:p}){let m=r.id,h=r.handshake.query.testId;if(!h)throw new Error("Socket connection request is missing testId");let g=await u({type:"e2e",testId:h}),f=await d?.();e=e.child({testId:h,orgId:g,sessionId:m,branch:f});let S=await a(g,e),y=await l(g,e),E=await s(g,e),R=await t(g),{testMetadata:A,baseUrl:C,envName:w,browserConfig:I,aiSettings:P,environmentVariables:X,localCodeEvalTools:q}=await Ii({testId:h,orgId:g,logger:e,storage:R,authorization:c,settings:E}),k=p.getSession(m);if(k)return e.info("Associating connection with existing session (likely reconnect)"),await k.controller.browser.clearAllCdpHighlights(),{type:"e2e",sessionId:m,orgId:g,testId:h};let ee=r.handshake.headers["x-forwarded-for"]?.split(",")[0];if(e.info({clientIp:ee,event:"connect",args:r.handshake.query},"Websocket event (connect)"),ee&&p.getCurrentConnectionsByIp(ee)>=Rj)throw e.error({clientIp:ee,sessions:p.getCurrentSessionsByIp(),...r.handshake.query},"Socket connection browser creation rate limit triggered"),new Error("You have exceeded the maximum number of connections allowed. Momentic limits the number of simultaneously open tabs to uphold browser reliability. Please close duplicate tabs and try again later.");p.reserveCapacityByIp(ee);try{await wj({socket:r,baseUrl:C,envName:w,testMetadata:A,orgId:g,sessionId:m,logger:e,environmentVariables:X,clientIp:ee,devicePixelRatio:i,storage:R,uploadedFileStorage:n,visualDiffScreenshotStorage:o,localCodeEvalTools:q,generator:S,enricher:y,browserConfig:I,aiSettings:P,globalE2eStateManager:p})}catch(z){throw e.warn({err:z},"Error setting up socket session, possibly due to client closing the connection"),p.releaseCapacityByIp(ee),z}return{type:"e2e",sessionId:m,testId:h,orgId:g}}async function wj({socket:r,baseUrl:e,envName:t,devicePixelRatio:n,testMetadata:o,orgId:i,sessionId:a,logger:l,storage:c,uploadedFileStorage:s,visualDiffScreenshotStorage:u,localCodeEvalTools:d,generator:p,environmentVariables:m,browserConfig:h,aiSettings:g,clientIp:f,enricher:S,globalE2eStateManager:y}){let E={viewport:o.advanced?.viewport??Gt,locale:o.advanced?.locale??oo,timezoneId:o.advanced?.timezone??io,geolocation:o.advanced?.geolocation??ao,colorScheme:o.advanced?.colorScheme};n&&(E.deviceScaleFactor=n);let R=o.id,A=await Od({settings:h,orgId:i,baseUrl:e,envName:t,testName:o.name,localTools:d,envVariables:m,logger:l,customHeaders:void 0});l=l.child({orgId:i,sessionId:a,testId:R});let C=await Ur.init({baseUrl:e,userBrowserSettings:A,enricher:S,storage:c,logger:l,contextArgs:E,iconKnowledgeBase:null,callbacks:{onTabsChange:(q,k)=>{r.emit("tabs",{tabs:q,activeTab:k})},onScreencastFrame:(q,k)=>{let ee=r;cn&&(ee=r.compress(!0)),ee.emit("screenshot",{buffer:q},()=>{k()})},onSvgsCollected:q=>{r.emit("newIconDetected",{numIcons:q.newSvgs.length}),c.saveNewIcons(q,l)}}});await C.navigate({url:e,initialNavigation:!0});let w=new Po({browser:C,generator:p,logger:l,orgId:i,options:{scratchPadId:void 0,slowMoMs:A.slowMoMs,autoFollowNewTabs:A.autoFollowNewTabs,useMemory:g.useMemory,aiPageFiltering:g.aiPageFiltering},storage:c,localCodeEvalTools:d,uploadedFileStorage:s,visualDiffScreenshotStorage:u}),I=D_(r,a,l,y),P=async()=>{I.timers.forEach(q=>clearInterval(q))},X=new ar({baseUrl:e,testName:o.name,currentUrl:w.browser.url(),variablesFromEnvironment:m,envName:t});if(!r.connected)throw await C.cleanup(),new Error("Socket not connected anymore, not proceeding with session setup");r.emit("session",{url:e,userAgent:Ur.USER_AGENT,viewport:w.browser.getViewport(),sessionId:a}),y.registerSession({controller:w,context:X,sessionId:a,cleanup:P,clientIp:f,socket:r})}async function Ii({testId:r,orgId:e,logger:t,storage:n,authorization:o,settings:i}){let a=await n.fetchTestMetadata(r,t);if(!a)throw new Error(`Test metadata could not found for test ${r}`);let l;o?.type==="API_KEY"&&(l=new mn({httpClient:new Lt({...o,logger:t}),fakerSeed:void 0}));let c=a.envs?.find(g=>g.default),s;c&&(s=await n.fetchEnvironment(c.name,t));let u=s&&"browser"in s?s.browser:void 0,d={...i.browser,...u,...a.advanced},p=a.baseUrl||s?.variables?.[wt];if(!p)throw new Error("Base URL is empty in both test options and the configured environment");let m={...s?.variables};await Promise.all((a.parameters??[]).map(async g=>{let f=await fr({orgId:e,s:g.defaultValue,context:ar.dummyContext(a.name,s?.name,m),logger:t,localTools:l});m[g.name]=f}));let h={...i.ai,...a.advanced};return{localCodeEvalTools:l,baseUrl:p,envName:s?.name,testName:a.name,browserConfig:d,environmentVariables:m,testMetadata:a,aiSettings:h}}var Vf=class{parentTracer=null;socket;step;orgId;constructor({step:e,socket:t,parentTracer:n,orgId:o}){this.socket=t,this.parentTracer=n,this.step=e,this.orgId=o}getParentStepIdChain(){return this.parentTracer?this.parentTracer?.getParentStepIdChain()??[]:[]}recordStepDuration(e){let t=e.step.type!=="PRESET_ACTION"?e.step.type:e.step.command.type;or.distribution("test_step_duration",e.durationMs,[`type:${t}`,"platform:browser","executor:editor",`orgId:${this.orgId}`])}attachBeforeScreenshot(){}attachAfterScreenshot(){}attachBeforeHtmlSnapshot(){}attachAfterHtmlSnapshot(){}recordTargetAutoHeal(){}async finish(e){switch(e.step.status){case"SUCCESS":this.socket.emit("success",{...e,parentStepIdChain:this.getParentStepIdChain()});return;case"FAILED":this.socket.emit("failure",{...e,parentStepIdChain:this.getParentStepIdChain()});return;case"CANCELLED":this.socket.emit("cancelled",{...e,parentStepIdChain:this.getParentStepIdChain()});return}}async startSubSteps(){return new jn({parentStep:this.step,socket:this.socket,parentTracer:this,orgId:this.orgId})}},jn=class{stepFrequenciesByType={};parentTracer;parentStep;socket;orgId;recordStepStat(e){e.type!=="PRESET_ACTION"?this.stepFrequenciesByType[e.type]=(this.stepFrequenciesByType[e.type]||0)+1:this.stepFrequenciesByType[e.command.type]=(this.stepFrequenciesByType[e.command.type]||0)+1}sendFinalizedStepStats(){for(let[e,t]of Object.entries(this.stepFrequenciesByType))or.increment("test_step_execution",t,[`type:${e}`,"platform:browser","executor:editor",`orgId:${this.orgId}`])}constructor({parentStep:e,socket:t,parentTracer:n,orgId:o}){this.parentTracer=n,this.parentStep=e,this.socket=t,this.orgId=o}async getScreenshot(){throw new Error("getScreenshot is not supported in the editor")}async getHtmlSnapshot(){throw new Error("getHtmlSnapshot is not supported in the editor")}getParentStepIdChain(){return this.parentStep?[...this.parentTracer?.getParentStepIdChain()??[],this.parentStep.id]:[]}async startStep(e){return this.recordStepStat(e.step),this.socket.emit("started",{stepId:e.step.id,parentStepIdChain:this.getParentStepIdChain(),attempt:e.attempt}),new Vf({step:e.step,parentTracer:this,socket:this.socket,orgId:this.orgId})}async finish(){this.sendFinalizedStepStats()}},Kd=class{constructor(e,t,n,o,i){this.socket=e;this.storage=t;this.orgId=n;this.testId=o;this.stepsBeforeRun=i}children=[];loggerBindings;async getScreenshot(){throw new Error("getScreenshot is not supported in the editor")}async getHtmlSnapshot(){throw new Error("getHtmlSnapshot is not supported in the editor")}attachConsoleLogs(){}attachNetworkLogs(){}attachBrowserCrashDump(){}async finish(){this.socket.emit("finished"),await Promise.all(this.children.map(e=>e.finish()))}async startBeforeStepList(){let e=new jn({orgId:this.orgId,parentStep:null,parentTracer:null,socket:this.socket});return this.children.push(e),e}async startMainStepList(){let e=new jn({orgId:this.orgId,parentStep:null,parentTracer:null,socket:this.socket});return this.children.push(e),e}async startAfterStepList(){let e=new jn({orgId:this.orgId,parentStep:null,parentTracer:null,socket:this.socket});return this.children.push(e),e}};var $f={currentlyExecutingRequests:{}},xj=r=>async(e,t)=>{let{testId:n,orgId:o}=r.metadata,i=await r.settingsFactory(o,r.logger),a=await r.storageFactory(o),l,c=await Ii({testId:n,orgId:o,logger:r.logger,storage:a,authorization:r.authorization,settings:i}),s=`${n}|${c.baseUrl}`;try{let u=$f.currentlyExecutingRequests[s]??0;$f.currentlyExecutingRequests[s]=u+1,l=await _j({...r,...e,...c,done:t})}finally{r.logger.info({result:l,sessionId:r.metadata.sessionId},"Test execution complete"),$f.currentlyExecutingRequests[s]--}},_j=async({socket:r,steps:e,baseUrl:t,testMetadata:n,reInitialize:o,toStep:i,fromStep:a,storageFactory:l,aiSettings:c,browserConfig:s,metadata:u,logger:d,envName:p,testName:m,environmentVariables:h,localCodeEvalTools:g,done:f,cacheStorageFactory:S,globalE2eStateManager:y})=>{let{testId:E,sessionId:R,orgId:A}=u,C=R,w=y.getSession(R);if(!w)throw new Error("No active session found");let{controller:I,context:P}=w;I.setOpen(),d=d.child({testId:E,orgId:A,sessionId:R,runId:C}),d.info({steps:e.map(J=>`${J.type}${"command"in J?` - ${J.command.type}`:""}`),toStep:i,fromStep:a,reInitialize:o,envName:p,testName:m,baseUrl:t,context:P,browserConfig:s,aiSettings:c},"Socket execution parameters");let X=h??{},q=async()=>{o&&(await I.browser.reset({newUrl:t}),P.reset({baseUrl:t,currentUrl:I.browser.url(),variablesFromEnvironment:X,envName:p,testName:m}))},k=await l(A),ee=await S(A),z=async()=>{try{await ee.resolveStepCacheEntries({schemaVersion:n.schemaVersion,testId:E,stepLists:{steps:e},logger:d})}catch(J){d.error({err:J},"Failed to fetch step cache entries from Momentic server. This can drastically reduce test reliability and performance.")}};try{await Xs({promiseGenerator:async()=>Promise.all([q(),z()]),signal:I.executeAbortController.signal,codePath:"resolveStepCacheAndInitBrowser"}),I.setOpen()}catch(J){if(r.emit("finished"),J.name!=="AbortError")throw new Error(`Failed to setup browser for execution: ${J}`)}let j=Cj(e),he={collectDebugData:!1,reinitializeBrowser:!1,disableHealing:!0},$={orgId:A,runId:C,testMetadata:n,steps:e,fromStep:a,toStep:i,orgSettings:{ai:c,browser:s}},rt={controller:I,context:P,storage:k,codeEvalTools:g,usageTracker:new Zi,logger:d},Ne={test:{},step:{onDynamicAIActionStatusUpdateEvent:J=>{r.emit("dynamicCommandStatusUpdate",J)},onDynamicAIActionEvaluatingEvent:J=>{r.emit("dynamicCommandEvaluating",J)},onDynamicCommandGenerated:J=>{r.emit("dynamicCommandGenerated",J)},onDynamicCommandExecuted:J=>{r.emit("dynamicCommandExecuted",J)}}},ct=new Kd(r,k,A,E,j),kt=await Pd({fixtures:rt,options:he,callbacks:Ne,inputs:$,testParams:{tracer:ct}});return kt?.status==="PASSED"?await fu({logger:d,cacheStorage:ee,orgId:A,testId:E,originalSteps:{steps:j},updatedSteps:{steps:e}}):kt?.status==="FAILED"&&await Su({logger:d,cacheStorage:ee,orgId:A,testId:E,originalSteps:{steps:j},updatedSteps:{steps:e}}),await ct.finish(),f?.(kt),kt.status};var U_={event:"execute",createHandler:xj};import{cloneDeep as Ij}from"lodash-es";var Mj=r=>async({command:e},t)=>{let{logger:n,generatorFactory:o,metadata:i}=r,a=Ij(e),l=av(a);if(l.category!=="NO_DESCRIPTION_PROVIDED"){if(l.category!=="NONE"){t?.({result:l});return}"cache"in a&&(a.cache=void 0);try{let s=await(await o(i.orgId,n)).getLintStepResult({command:a},{logger:n});t?.({result:s})}catch(c){n.error({event:"lint",err:c},"Failed to lint step"),t?.({result:void 0})}}},F_={event:"lintStep",createHandler:Mj};var Pj=({metadata:r,logger:e,storageFactory:t,globalE2eStateManager:n})=>{let{sessionId:o,orgId:i}=r;return async(a,l)=>{let{description:c,command:s,testMetadata:u,returnScreenshot:d}=a;e.info({params:a},`Locate handler called - ${c}`);let p=n.getSession(o);if(!p)throw new Error("No active session found");let{controller:m,context:h}=p;m.setOpen();let g=await t(i),f=ei.parse(u.advanced??{}),S={},y;if(c){if("useSelector"in s&&s.useSelector)try{let E=await m.locateElementWithSelector(c,"iframeUrl"in s?s.iframeUrl:void 0);y=E.resolution.locator,S={target:E.target,thoughts:E.thoughts}}catch(E){e.warn({err:E},"Failed resolving target with selector"),l({err:`Failed locating element: ${E.message}`,decisions:E instanceof an?E.decisions:void 0});return}else try{let E=await m.locateElement({description:c,disableCache:f.disableAICaching??!1,skipWait:!0,testContext:h,source:Yo(s),iframeUrl:"iframeUrl"in s?s.iframeUrl:void 0,memory:"cache"in s&&s.cache&&"target"in s.cache&&Yl(s.cache.target.memory)?s.cache.target.memory:void 0,logger:e});S={target:E.target,thoughts:E.thoughts},y=E.resolution.locator}catch(E){(async()=>{try{let R=await m.browser.getCondensedHtml({skipWait:!0});e.warn({err:E,html:R.slice(0,1e5)},"Failed locating element with AI")}catch(R){e.warn({err:R},"Failed grabbing HTML after trying to locate element with AI")}})(),l({err:`${E.message}`});return}if(s.type==="SELECT_OPTION"&&y)try{S.options=await m.browser.getSelectOptions(y)}catch(E){e.warn({err:E},"Failed getting select options"),l({err:`Failed getting select options: ${E.message}`});return}e.info({result:S},"Locate handler result")}if(d)try{let{buffer:E,width:R,height:A}=await m.screenshotWithDimensions({clearHighlights:!0,locator:y}),C=await g.uploadScreenshot(E);S.screenshot={data:C,width:R,height:A},e.info({width:R,height:A},"Captured screenshot during locate")}catch(E){e.error({err:E},"Error capturing screenshot during locate"),l({err:`Error taking screenshot: ${E.message}`});return}if(l({result:S}),y)try{await Promise.all([m.browser.scrollIntoViewIfNeeded(y),m.browser.highlight(y)])}catch(E){e.warn({err:E},"Error highlighting element, continuing...")}}},B_={event:"locate",createHandler:Pj};var Oj=({metadata:r,logger:e,globalE2eStateManager:t})=>{let{sessionId:n}=r;return async({event:o,percentX:i,percentY:a})=>{let l=t.getSession(n);if(!l)throw new Error("No active session found");let c=l.controller.browser;if(c.closed||c.getActivePage().isClosed()){e.warn("Ignoring mouse move because the browser is closed");return}try{await c.clickMouseFromPositionPercentages(o,i,a)}catch(s){e.error({err:s},"Error performing click during cloud recording in control mode")}}},z_={event:"mouseClickEvent",createHandler:Oj};var Lj=({metadata:r,generatorFactory:e,logger:t,socket:n,globalE2eStateManager:o})=>{let{sessionId:i,orgId:a,testId:l}=r;return async({stepId:c,parentStepIdChain:s,attribute:u})=>{let d=o.getSession(i);if(!d)throw new Error("No active session found");let{controller:p}=d,m=await e(a,t);p.setOpen(),d.browserBehavior.showOverlay=!0;let h=new AbortController;h.signal.addEventListener("abort",async()=>{try{d.browserBehavior.showOverlay=!1,await p.stopRecordMode()}catch(S){t.warn({err:S},"Failed to stop record mode in target click socket handler")}},{once:!0});let g=!1,f=(S,y)=>{y.type!=="PRESET_ACTION"||y.command.type!=="CLICK"||(n.emit("targetRecordingUpdate",{type:S,stepId:c,parentStepIdChain:s,command:y.command,attribute:u}),h.abort(),g=!0)};setTimeout(()=>{g||(h.abort(),n.emit("targetRecordingUpdate",{type:"error",err:"Timed out waiting for click event",stepId:c,parentStepIdChain:s,attribute:u}))},1e4),await p.startRecordMode({params:{generator:m,logger:t,testId:l,orgId:a,callbacks:{onActionReceived:S=>f("clickReceived",S),onStepRecorded:S=>f("descriptionGenerated",S)}},abortController:h,isClickToRecord:!0}),n.emit("targetRecordingUpdate",{type:"listenersInitialized",stepId:c,parentStepIdChain:s,attribute:u})}},H_={event:"recordTargetClick",createHandler:Lj};var Nj=({metadata:r,logger:e,globalE2eStateManager:t})=>{let{sessionId:n}=r;return async({key:o})=>{let i=t.getSession(n);if(!i)throw new Error("No active session found");if(o==="Dead")return;let{controller:a}=i;if(a.browser.closed||a.browser.getActivePage().isClosed()){e.debug({sessionId:n},"Browser is closed, ignoring keyboard press socket event");return}try{a.setOpen(),await a.browser.keyDown(o,{})}catch(l){if(l.message.includes("has been closed")){e.debug({sessionId:n,err:l},"Browser is closed, ignoring key down socket event error");return}throw l}}},G_={event:"keyDownEvent",createHandler:Nj};var Dj=({metadata:r,logger:e,globalE2eStateManager:t})=>{let{sessionId:n}=r;return async({key:o})=>{let i=t.getSession(n);if(!i)throw new Error("No active session found");if(o==="Dead")return;let{controller:a}=i;if(a.browser.closed||a.browser.getActivePage().isClosed()){e.debug({sessionId:n},"Browser is closed, ignoring keyboard press socket event");return}try{a.setOpen(),await a.browser.keyUp(o,{})}catch(l){if(l.message.includes("has been closed")){e.debug({sessionId:n,err:l},"Browser is closed, ignoring key up socket event error");return}throw l}}},j_={event:"keyUpEvent",createHandler:Dj};var kj=({metadata:r,logger:e,globalE2eStateManager:t})=>{let{sessionId:n}=r,o,i=0,a=(s,u)=>{let d=async()=>{o=void 0};clearTimeout(o),o=setTimeout(d,Math.min(1e3,250*(i+1)))},l,c=0;return async s=>{let u=t.getSession(n);if(!u)throw new Error("No active session found");let{controller:d,browserBehavior:p}=u,m=d.browser;if(m.closed||m.getActivePage().isClosed()){e.warn("Ignoring mouse move because the page is closed");return}if(s.event==="scroll"){let h=await m.scrollFromPositionPercentages(s.percentX,s.percentY,l?.x??0,l?.y??0),g=u.browserBehavior.recordingState?.transformer;g&&h&&g.recordScroll(h);return}p.showOverlay&&a(m,s);try{let h=await m.moveMouseFromPositionPercentages(s.percentX,s.percentY);c=0,l=h}catch(h){c++,c%5===0&&e.warn({err:h,mouseErrors:c},"Error in socket mouse move handler")}}},V_={event:"mouseMoveEvent",createHandler:kj};var Uj=({metadata:r,generatorFactory:e,socket:t,logger:n,globalE2eStateManager:o})=>{let{sessionId:i,orgId:a,testId:l}=r;return async({stepId:c})=>{let s=o.getSession(i);if(!s)throw new Error("No active session found");let{controller:u,browserBehavior:d}=s,p=await e(a,n);n.info("Starting cloud recording");let m=new AbortController,h=await u.startRecordMode({params:{generator:p,logger:n,testId:l,orgId:a,callbacks:{onActionReceived:(g,f)=>{t.emit("stepRecorded",{stepId:c,step:g,offset:f})},onStepRecorded:(g,f)=>{t.emit("stepRecorded",{stepId:c,step:g,offset:f})}}},abortController:m,isClickToRecord:!1});d.recordingState={transformer:h}}},$_={event:"recordingStart",createHandler:Uj};var Fj=({metadata:r,logger:e,globalE2eStateManager:t})=>{let{sessionId:n}=r;return async()=>{let o=t.getSession(n);if(!o)throw new Error("No active session found");e.info("Stopping cloud recording"),await o.controller.stopRecordMode(),o.browserBehavior.recordingState=void 0,o.browserBehavior.showOverlay=!1}},W_={event:"recordingStop",createHandler:Fj};var Bj=({socket:r,metadata:e,logger:t,storageFactory:n,authorization:o,settingsFactory:i,globalE2eStateManager:a})=>async(l,c)=>{let{testId:s,sessionId:u,orgId:d}=e;t.info({testId:s,sessionId:u},"Refresh event received");let p=await i(d,t),m=await n(d),{baseUrl:h}=await Ii({testId:s,orgId:d,logger:t,storage:m,authorization:o,settings:p}),g=a.getSession(u);if(!g){r.emit("error",{message:"No session to refresh"});return}let{controller:f}=g;f.setOpen(),await f.browser.refresh();let S=f.browser.getViewport();t.info({baseUrl:h,viewport:S},`Session refreshed for test ${s} at ${h}`),c()},q_={event:"refresh",createHandler:Bj};var zj=({socket:r,metadata:e,logger:t,storageFactory:n,authorization:o,settingsFactory:i,globalE2eStateManager:a})=>async()=>{let{testId:l,sessionId:c,orgId:s}=e;t.info({testId:l,sessionId:c},"Reset event received");let u=await i(s,t),d=await n(s),{baseUrl:p,envName:m,testName:h,environmentVariables:g}=await Ii({testId:l,orgId:s,logger:t,storage:d,authorization:o,settings:u}),f=a.getSession(c);if(!f){r.emit("error",{message:"No session to reset"});return}let{controller:S,context:y}=f;await S.browser.reset({newUrl:p});let E=S.browser.baseUrl;y.reset({baseUrl:E,currentUrl:S.browser.url(),variablesFromEnvironment:g,envName:m,testName:h});let R=S.browser.getViewport(),A=Ur.USER_AGENT;t.info({baseUrl:p,viewport:R},`Session reset for test ${l} at ${E}`),r.emit("session",{url:E,userAgent:A,viewport:R,sessionId:c})},K_={event:"reset",createHandler:zj};var Hj=({metadata:r,globalE2eStateManager:e})=>{let{sessionId:t}=r;return async({url:n})=>{let o=e.getSession(t);if(!o)throw new Error("No active session found");await o.controller.browser.switchToPage({type:"SUBSTRING",substring:n})}},Y_={event:"switchTab",createHandler:Hj};async function X_(r){return k_(r)}var J_=[yA,U_,B_,K_,q_,gA,Y_,F_,H_,$_,W_,V_,z_,G_,j_,SA,fA];var Q_=r=>{let{logger:e}=r,t=new Gj(r.baseServer,{cors:{origin:"*",methods:["GET","POST"]},pingTimeout:15*60*1e3,pingInterval:15*60*1e3,maxHttpBufferSize:1e7,perMessageDeflate:!0});return t.on("connection",async n=>{let o;try{e.info({event:"connection",transport:n.conn.transport.name},"Websocket connection established"),o=await X_({...r,socket:n,logger:e}),e=e.child(o)}catch(i){e.error({event:"connection",type:"websocket",err:i},"Failed to setup connection"),n.emit("error",{message:i instanceof Error?i.message:`${i}`}),n.disconnect(!0);return}J_.forEach(i=>jj(i,{...r,socket:n,metadata:o,logger:e}))}),t},jj=(r,e)=>{let t=r.createHandler(e),n=(...o)=>{["mouseMoveEvent","keyDownEvent","keyUpEvent","mouseClickEvent","lintStep"].includes(r.event)||e.logger.debug({...e.metadata,event:r.event},`Websocket event (${r.event})`);let i=a=>{e.logger.error({event:r.event,type:"websocket",err:a instanceof Error?a:new Error(`${a}`)},"Unhandled exception in socket handler"),e.socket.emit("error",{message:a instanceof Error?a.message:`${a}`})};try{let a=t.apply(void 0,o);a&&typeof a.catch=="function"&&a.catch(i)}catch(a){i(a)}};e.socket.on(r.event,n)};import{Router as Kj}from"express";import{Router as $j}from"express";import Ul from"fs";import kl from"path";import{v4 as Wj}from"uuid";import qj from"yaml";import{hostname as Vj}from"os";var Wf="2.20.2",at=Xc({app:"desktop-server",hostname:Vj(),disableConsoleLogs:!0}).child({cliVersion:Wf});(async()=>{try{let r=await il(at);r.gitBranchName&&at.addBinding("branch",r.gitBranchName)}catch{}})();var ja=$j();async function qf(r){return(await Cu(r,at)).map(n=>{let o=r.modules[n.moduleId];if(!o){T.warn(`Found a dangling module with ID ${n.moduleId} that could not be found on disk.`);return}return{...o,content:n}}).filter(n=>n!==void 0)}ja.get("/",Re(async(r,e)=>{let t=ce(),n=await Y(t),o=await qf(n);e.status(200).json(o)}));ja.post("/",Re(async(r,e)=>{let t;try{t=fT.parse(r.body)}catch(l){e.status(400).json({error:`Invalid request body: ${l}`});return}try{ro(t.name)}catch(l){e.status(400).json({error:`Invalid module name: ${l}`});return}let n=ce(),o=(await Y(n)).modules;if(Object.values(o).find(l=>l.name===t.name)){e.status(400).send(`A module with the name "${t.name}" already exists. Please choose a different name.`);return}let i=kl.join(n.rootDir,t.folderPath??"");if(!Ul.existsSync(i)||!Ul.statSync(i).isDirectory()){e.status(400).json({error:`The folder configured for module creation '${i}' does not exist.`});return}let a=await wu({...t,folder:i,project:n});e.status(201).json(a)}));ja.get("/:moduleId",Re(async(r,e)=>{if(!r.params.moduleId){e.status(400).json({error:"Missing moduleId in url path."});return}let t=await Y(ce()),n=t.modules[r.params.moduleId];if(!n){e.status(404).json({error:"Module not found."});return}try{let o=await Yr(n,t,T);e.json(o)}catch(o){e.status(400).json({err:o})}}));ja.post("/:moduleId/duplicate",Re(async(r,e)=>{if(!r.params.moduleId){e.status(400).json({error:"Missing moduleId in url path."});return}let t;try{t=gT.parse(r.body)}catch(g){e.status(400).json({error:`Invalid request body: ${g}`});return}try{ro(t.name)}catch(g){e.status(400).json({error:g.message});return}let n=ce(),o=await Y(n),i=o.modules[r.params.moduleId];if(!i){e.status(404).json({error:"Module not found."});return}if(Object.values(o.modules).find(g=>g.name===t.name)){e.status(400).send(`A module with the name "${t.name}" already exists. Please choose a different name.`);return}let a=await Yr(i,o,T),l=kl.join(n.rootDir,kl.dirname(i.relativePath));if(!Ul.existsSync(l)||!Ul.statSync(l).isDirectory()){e.status(400).json({error:`The folder configured for module creation '${l}' does not exist.`});return}let c=Oe(t.name),s=kl.join(l,`${c}.module.yaml`),u=Wj(),{stepsToSave:d}=await et({stepLists:{steps:a.steps},createNewCacheIds:!0,cacheCreationParams:{orgId:xt()}}),p={fileType:pe.MODULE,schemaVersion:ue,moduleId:u,name:t.name,description:"",enabled:!0,steps:d.steps,parameters:a.parameters,defaultParameters:a.defaultParameters,parameterEnums:a.parameterEnums,defaultCacheKey:a.defaultCacheKey,defaultCacheTtl:a.defaultCacheTtl,defaultCacheAllInvocations:a.defaultCacheAllInvocations,autoAuth:a.autoAuth,advanced:a.advanced},m=qj.stringify(p);Ul.writeFileSync(s,m,"utf-8");let h={relativeFilePath:kl.relative(n.rootDir,s)};e.status(201).json(h)}));ja.patch("/:moduleId/metadata",Re(async(r,e)=>{if(!r.params.moduleId){e.status(400).json({error:"Missing moduleId in url path."});return}let t;try{t=ST.parse(r.body)}catch(i){e.status(400).json({error:`Invalid request body: ${i}`});return}let n=ce(),o=await Y(n);Yv({moduleId:r.params.moduleId,content:t,momenticFiles:o,logger:T,project:n}),e.status(201).json({message:"ok"})}));var Z_=ja;var eI=Kj();eI.get("/",Re(async(r,e)=>{let t=ce(),n=await Y(t),o=new Set;n?.tests&&Object.values(n.tests).forEach(s=>{s.labels?.forEach(u=>o.add(u))});let i=Array.from(o).sort(),a=Object.values(n.tests),l=await qf(n),c={labels:i,tests:a,modules:l};e.status(200).json(c)}));var tI=eI;import{Router as Yj}from"express";var Kf=Yj();Kf.get("/",Re((r,e)=>{let t=xu(ce(),at);e.status(200).json(t)}));Kf.get("/names",Re((r,e)=>{let n=ce().config.environments?.map(o=>o.name)??[];e.status(200).json(n)}));var rI=Kf;import{Router as Xj}from"express";var nI=Xj();nI.get("/",Re((r,e)=>{e.status(200).json({userId:ga(),orgId:xt()})}));var oI=nI;import{StreamableHTTPServerTransport as ZV}from"@modelcontextprotocol/sdk/server/streamableHttp.js";import{isInitializeRequest as e$}from"@modelcontextprotocol/sdk/types.js";import{randomUUID as t$}from"crypto";import{Router as r$}from"express";import{McpServer as JV}from"@modelcontextprotocol/sdk/server/mcp.js";import{SSEServerTransport as QV}from"@modelcontextprotocol/sdk/server/sse.js";import{streamObject as tV}from"ai";import Qd from"dedent";import{z as Oo}from"zod";import{tool as Jj}from"ai";import{z as Qj}from"zod";var Yd=(r,e)=>({builder:n=>Jj({description:r.schema.description,inputSchema:Qj.object(r.schema.inputSchema),execute:async o=>{let i=e(n);n.logger.info({input:o},`Executing tool ${r.schema.name}`);try{await r.handle(n,o,i,void 0)}catch(l){i.addError(String(l))}let a=await i.serialize();return a.isError?n.logger.error({toolName:r.schema.name,input:o,err:a.content.map(l=>l.text).join(`
|
|
4058
|
+
${r}`;default:return r}}var Sj=15;async function Wd({command:r,aiPageFiltering:e,logger:t,fixtures:n,source:o,useMemory:i,maxRetries:a=Sj}){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=zv(c),u=0,d=Date.now(),p,m,h;try{await An({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 g;for(;u<a&&(!g||g-d<c);){n.abortSignal.throwIfAborted(),u!==0&&await ie(s,n.abortSignal),g=Date.now();try{if(p=await An({action:async()=>{let y=await P_(l,t,n.abortSignal);return m&&m.serializedTree===y.serializedTree&&m.screenshotBuff.equals(y.screenshotBuff)?p:(m=y,O_({command:r,state:y,fixtures:n,useMemory:i,useConsensus:!1,highlightElementsOnFailure:!1,attemptNumber:u,aiPageFiltering:e,logger:t,source:o}))},frameConfig:r.iframeUrl?{type:"url",url:r.iframeUrl}:void 0,logger:t,browser:l}),p?.updatedMemory&&su(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(),h=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 An({action:async()=>O_({command:r,state:await P_(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(),h=f instanceof Error?f:new Error(`${f}`)}finally{u++}if(!p?.success){let f=`AI check still failing after ${u} attempts.`;throw h&&(f+=` Latest result: ${h.message}`),new x("AssertionFailureError",f)}return{...p,succeedImmediately:!1,urlAfterCommand:l.url()}}async function P_(r,e,t){let[n,o]=await Promise.all([xo(r,{abortSignal:t,skipWait:!0,skipWaitForPageLoad:!0,logger:e}),r.screenshot({retries:1,respectActiveFrame:!0})]);return{...n,screenshotBuff:o}}async function O_({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:h,tree:g}=e,f=e.screenshotBuff,y=f.toString("base64"),S=u.url(),E=r.contextChoice??"MULTIMODAL",R=h;E!=="VISION_ONLY"&&(R=await _i({type:"assertion",serializedTree:h,tree:g,description:r.assertion,screenshot:y,options:{aiPageFiltering:a},fixtures:{generator:d,signal:p,logger:s,orgId:t.orgId}}),R!==h&&(m.ragUsed=!0),m.pageState=R);let A={goal:r.assertion,url:S,memory:o?r.cache?.memory:void 0,browserState:R,screenshot:y,contextChoice:E,source:c},w=await(E==="VISION_ONLY"?(I,P)=>d.getVisualAssertionResult(I,P):(I,P)=>d.getAssertionResult(I,P))(A,{useConsensus:n,attemptNumber:l,useMemory:o,disableCache:!!r.disableCache,abortSignal:p,logger:s,loggerTags:je(s)});return(w.result||i)&&w.relevantElements&&(m.relevantElementsSerialized=w.relevantElements.map(I=>u.getSerializedFormFromA11yId(I)).filter(I=>!!I),await yj(w.relevantElements,u,s)),{success:w.result,thoughts:w.thoughts,afterScreenshotOverride:f,updatedMemory:o?w.updatedMemory:void 0}}async function yj(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 G(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 Ej=3e4;async function L_({command:r,logger:e,baseUrl:t,fetchImplementation:n=fetch}){let o=r.timeout??Ej/1e3,i=new AbortController,a=Object.fromEntries(Object.entries(r.headers||{}).filter(([d,p])=>d&&p));a["Content-Type"]="application/json";let l;if(da(r.url)&&(l=r.url),t&&pa(r.url,t)&&(l=new URL(r.url,t).toString()),!l)throw new x("ActionFailureError",`Invalid URL: ${r.url}`);let s=await G((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 Po=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([xo(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 _i({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:{...je(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([xo(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 _i({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:{...je(a)},langfuseSessionId:l})}catch(h){throw new x("InternalWebAgentError",`Error generating command: ${h instanceof Error?h.message:h}`,{errOptions:{cause:h}})}}async getBrowserState(e){return xo(this.browser,e)}async locateElement(e){return await jf({...e,aiPageFiltering:!!this.options?.aiPageFiltering},this.getControllerFixtures())}async locateElementWithSelector(e,t){return An({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 h=>h,options:{...c,targetName:o[d]}});u.push(m)}try{let d=await l(...u.map(h=>h.result)),p=h=>h==="fromTarget"?"From Target":h==="toTarget"?"To Target":"Target",m=u.map((h,g)=>h.thoughts?`${p(o[g])}: ${h.thoughts}`:void 0).filter(h=>!!h).join(" -------------- ")||void 0;return{result:d,elementInteractedDisplayStrings:u.map(h=>h.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 An({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&&Zp(i)){t.warn({err:i},"Invalid mpath error, retrying element targeting command");continue}if(!this.browser.userBrowserSettings.visualActions&&(tm(i)||em(i))){t.warn({err:i},"Invalid momentic id error, retrying element targeting command");continue}if(rm(i)){t.warn({err:i},"Invalid backend node id error, retrying element targeting command");continue}if(i instanceof sn&&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 ie(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,h=this.logger.child({commandId:c.id}),g=this.shouldUseMemory(),f=l.retriesWithAI??1,y=!1,S=N_(e.cache);if((!S||s)&&!kp(o))throw new x("ActionFailureError","Cannot target element with no cached data or element descriptor");if(u)return this.wrapHardcodedCssTargetingCommandHelper(e);s&&(h.info("Cache explicitly disabled for this step"),y=!0,S=void 0),S&&this.browser.userBrowserSettings.disableSecondaryCacheResolution&&S.targetSource==="HEURISTIC_HEALED"&&(y=!0,S=void 0),S?.inputDescription&&!M_(o.elementDescriptor,S.inputDescription)&&(h.warn({old:S.inputDescription,new:o.elementDescriptor},"Target cache was generated with a different description, clearing it automatically"),y=!0,S=void 0);let E=A=>!!A&&Kl(A),R=!0;if(!E(S)){R=!1,h.info({description:o.elementDescriptor,targetHealingInProgress:p,cacheBustedBeforeAction:y,memory:l.memory,useMemory:g},"Prompting AI for an updated element location"),y&&await ie(this.browser.smartWaitingTimeout,this.executeAbortController.signal),f--;let A;try{A=await jf({description:o.elementDescriptor,disableCache:!!l.disableCache,iframeUrl:l.iframeUrl,source:m,useMemory:g,memory:g?l.memory:void 0,aiPageFiltering:!!this.options?.aiPageFiltering,allowNotActionableNodesOverride:l.allowNotActionableNodesOverride,logger:h},this.getControllerFixtures(t))}catch(I){if(I instanceof Vi&&I.updatedLocatorMemory){let P={id:-1,...i,memory:I.updatedLocatorMemory};au({cmd:c,key:d,newTarget:P,logger:h,updatedWithAI:!0})}throw new x("ActionFailureError",I.message)}A.frameConfig&&this.browser.setActiveFrameConfig(A.frameConfig);let C=l.disableGlobalLocatorRedirect?{locator:A.resolution.locator}:await this.attemptLocatorRedirect(A.resolution.locator,h),w=await a(C);return au({cmd:c,key:d,newTarget:A.target,logger:h,updatedWithAI:!0}),p&&(n.recordTargetAutoHeal({healType:"AI"}),A.target.targetSource="AI_HEALED",A.target.targetUpdateTime=new Date().toUTCString(),A.target.targetUpdateLoggerTags=je(h)),{result:w,elementInteractedDisplayString:A.resolution.displayString,thoughts:A.thoughts}}try{let A=await this.browser.resolveTarget(t,S,{allowNotActionableNodesOverride:l.allowNotActionableNodesOverride,targetName:d,logger:h,signal:this.executeAbortController.signal});(this.browser.userBrowserSettings.visualActions||this.browser.userBrowserSettings.globalLocatorRedirect!==!1)&&await this.browser.scrollIntoViewIfNeeded(A.locator);let C=l.disableGlobalLocatorRedirect?{locator:A.locator}:await this.attemptLocatorRedirect(A.locator,h),w=await a(C);if(or.increment("cache_target_resolution_v2",1,["outcome:hit","platform:web",`hasRequirements:${!!S.requirements}`,`hasAdditionalElements:${!!S.additionalElements}`,`orgId:${this.orgId}`]),au({cmd:c,key:d,newTarget:S,logger:h,updatedWithAI:!1}),R){let I=A.decisions.filter(P=>P.matched);if(I.length!==1)h.warn({decisions:A.decisions},"Expected exactly 1 matching method for element location, got more or less");else{let P=I[0].type;n.recordTargetAutoHeal({healType:P})}}return{result:w,elementInteractedDisplayString:A.displayString}}catch(A){this.throwIfClosed(),or.increment("cache_target_resolution_v2",1,["outcome:miss","platform:web",`hasRequirements:${!!S.requirements}`,`hasAdditionalElements:${!!S.additionalElements}`,`orgId:${this.orgId}`]);let C=!1;if((A instanceof sn||Zp(A)||tm(A)||rm(A)||Ny(A)||em(A))&&(C=!0),A instanceof x&&!C)throw h.error({err:A},"Failed to execute action with cached target (fatal)"),A;if(f>0&&o){h.info({err:A},"Failed to execute action with cached target, retrying with AI");let w;return S.memory&&Yl(S.memory)&&(w=S.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",A.message,{errOptions:{cause:A}})}}async attemptLocatorRedirect(e,t){return this.browser.userBrowserSettings.globalLocatorRedirect!==!1?this.browser.performTargetRedirection(e,t):{locator:e}}async screenshotWithDimensions(e){return sl(this.browser,e)}async executePresetCommand(e,t,n,o,i){this.options?.slowMoMs&&await ie(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&&YS(n)?await this.browser.waitForDOMStability({timeout:Ce}):!this.browser.userBrowserSettings.visualActions&&["PRESS","TYPE"].includes(n.type)&&await this.browser.waitForDOMStability({timeout:ae}),this.options?.autoFollowNewTabs&&await tx({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{CA(n,c)}}createCallbacksForBrowser(e){return{createIsolatedFolder:()=>hf(e)}}async resolveCommandTemplateStrings(e,t){return Pu({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()?Wd({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 Wd({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=vb(n.schema);if(f)throw new x("UserConfigurationError",f)}let h=await this.browser.getCondensedHtml(),g=await this.browser.screenshot({retries:2});try{let f=await this.generator.getTextExtraction({goal:n.goal,browserState:h,returnSchema:n.schema,screenshot:`data:image/jpeg;base64,${g.toString("base64")}`},{disableCache:i,abortSignal:this.executeAbortController.signal,loggerTags:je(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 y=f.message;throw y.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."):y.includes("AIProviderError")&&y.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(!da(n.url)&&!pa(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:h=>this.browser.click(h,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 h,g;if(n.target&&rn(n.target))await this.browser.hoverUsingVisualCoordinates(n.target.pixels);else if(n.target&&n.target.elementDescriptor.trim()){let{elementInteractedDisplayString:S,thoughts:E}=await this.wrapElementTargetingCommand({ctx:e,tracer:t,command:n,target:n.target,cache:n.cache?.target,action:R=>this.browser.hover(R),options:{...n,targetName:"target",disableGlobalLocatorRedirect:!0,disableCache:i}});h=S,g=E}let f=this.browser.getViewport()?.height??Gt.height,y=this.browser.getViewport()?.width??Gt.width;switch(n.type){case"SCROLL_UP":await this.browser.scrollVertical(-(n.deltaY??f));break;case"SCROLL_DOWN":await this.browser.scrollVertical(n.deltaY??f);break;case"SCROLL_LEFT":await this.browser.scrollHorizontal(-(n.deltaX??y));break;case"SCROLL_RIGHT":await this.browser.scrollHorizontal(n.deltaX??y);break}return{succeedImmediately:!1,urlAfterCommand:this.browser.url(),elementInteracted:h,thoughts:g}}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 h=n.matcher;await this.browser.waitForUrl({beforeUrl:this.browser.url(),matcher:h},{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 ie(s,this.executeAbortController.signal);break;case"REFRESH":await this.browser.refresh({loadTimeoutMs:n.loadTimeout?n.loadTimeout*1e3:void 0});break;case"CLICK":{if(rn(n.target)){await this.browser.clickUsingVisualCoordinates(n.target.pixels,n);break}let h=this.browser.url(),{elementInteractedDisplayString:g,result:f,thoughts:y}=await this.wrapElementTargetingCommand({ctx:e,tracer:t,target:n.target,command:n,cache:n.cache?.target,action:E=>this.browser.click(E,this.createCallbacksForBrowser(this.orgId),n),options:{disableCache:i,targetName:"target",...n}}),S={urlAfterCommand:this.browser.url(),succeedImmediately:!1,elementInteracted:g,thoughts:y,data:f.downloadedFile?{downloadedFile:f.downloadedFile}:void 0};return bu(h,S.urlAfterCommand)&&(S.succeedImmediately=!0,S.succeedImmediatelyReason="URL changed"),S}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(rn(n.fromTarget)&&rn(n.toTarget)){await this.browser.dragAndDropUsingVisualCoordinates(n.fromTarget.pixels,n.toTarget.pixels,{hoverSeconds:n.hoverSeconds});break}if(rn(n.fromTarget)||rn(n.toTarget))throw new Error("Drag and drop targets must be both coordinates or both descriptions");let{elementInteractedDisplayStrings:h,thoughts:g}=await this.wrapMultiElementTargetingCommand({ctx:e,tracer:t,command:n,targetNames:["fromTarget","toTarget"],descriptions:[n.fromTarget,n.toTarget],caches:[n.cache?.fromTarget,n.cache?.toTarget],action:(f,y)=>this.browser.dragAndDrop(f.locator,y.locator,{hoverSeconds:n.hoverSeconds,steps:n.steps}),options:{useSelector:!!n.useSelector,disableCache:i}});return{succeedImmediately:!1,urlAfterCommand:this.browser.url(),elementInteracted:h[0],thoughts:g}}case"MOUSE_DRAG":{let h=parseInt(n.deltaX),g=parseInt(n.deltaY),f=n.steps??5;if(isNaN(h)||isNaN(g))throw new x("ActionFailureError",`Invalid pixel values passed to mouse drag command: (${n.deltaX}, ${n.deltaY})`);if(n.target&&rn(n.target)){await this.browser.mouseDragUsingVisualCoordinates(h,g,f,n.target.pixels,{force:n.force});break}let y,S,E;if(n.target?.elementDescriptor){let{elementInteractedDisplayString:R,result:A,thoughts:C}=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}});y=A,S=R,E=C}return await this.browser.mouseDrag(h,g,f,y,{force:n.force}),{succeedImmediately:!1,urlAfterCommand:this.browser.url(),elementInteracted:S,thoughts:E}}case"SELECT_OPTION":{if(!Zn(n.target))throw new Error("Select with x/y is not supported yet");let h=n.target.elementDescriptor,g=n.choice,{elementInteractedDisplayString:f,thoughts:y}=await this.wrapElementTargetingCommand({ctx:e,tracer:t,command:n,target:{type:"description",elementDescriptor:h},cache:n.cache?.target,action:S=>this.browser.selectOption(S,g,n.force),options:{...n,targetName:"target",disableCache:i,source:Yo(n)}});return{succeedImmediately:!1,urlAfterCommand:this.browser.url(),elementInteracted:f,thoughts:y}}case"TAB":{let h={loadTimeoutMs:n.loadTimeout?n.loadTimeout*1e3:void 0,retry:!0};await this.browser.switchToPage(n.action,h);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 h;try{n.environment==="BROWSER"?(h=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:h},"Executed JavaScript in browser")):h=await To({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 g=>{if(!this.options?.scratchPadId){a.warn({updates:g},"Got persistent variable updates but scratch pad is not available");return}await this.storage.savePersistentVariables?.({scratchPadId:this.options?.scratchPadId,orgId:this.orgId,updates:g,logger:a})}}})}catch(g){throw this.throwIfClosed(),new x("ActionFailureError",g instanceof Error?g.message:`${g}`,{errOptions:{cause:g}})}try{JSON.stringify(h)}catch(g){throw new x("ActionFailureError",`Return value is not serializable: ${g instanceof Error?g.message:`${g}`}`,{errOptions:{cause:g}})}return{urlAfterCommand:this.browser.url(),succeedImmediately:!1,data:h}}case"TYPE":{if(n.target&&rn(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 h=this.browser.url(),g,f,y=N_(n.target),S=this.browser.userBrowserSettings.globalLocatorRedirect===void 0||this.browser.userBrowserSettings.globalLocatorRedirect==="always";if(y){let{elementInteractedDisplayString:R,thoughts:A}=await this.wrapElementTargetingCommand({ctx:e,tracer:t,command:n,target:y,cache:n.cache?.target,action:C=>this.browser.typeIntoTarget(n.value,C,{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:!S,source:Yo(n)}});g=R,f=A}else await this.browser.type(n.value,{force:n.force,clearContent:n.clearContent,forceClearContent:n.forceClearContent,delay:n.delay,pressEnter:n.pressEnter},!0);let E={urlAfterCommand:this.browser.url(),succeedImmediately:!1,elementInteracted:g,thoughts:f};return bu(h,E.urlAfterCommand)&&(E.succeedImmediately=!0,E.succeedImmediatelyReason="URL changed"),E}case"HOVER":{if(rn(n.target)){await this.browser.hoverUsingVisualCoordinates(n.target.pixels);break}let{elementInteractedDisplayString:h,thoughts:g}=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:h,thoughts:g}}case"FOCUS":{if(!Zn(n.target))throw new Error("Focus with x/y is not supported yet");let{elementInteractedDisplayString:h,thoughts:g}=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:h,thoughts:g}}case"BLUR":{if(n.target&&!Zn(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:h,thoughts:g}=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:h,thoughts:g}}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 bu(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 h=new bj,g=Tj(fetch,h),f;try{f=new URL(n.url).hostname}catch{}return{data:{...await LA({command:n,baseUrl:this.browser.baseUrl,logger:a,fetchImplementation:g}),cookies:BE(h,f)},succeedImmediately:!1,urlAfterCommand:this.browser.url()}}case"GRAPHQL_REQUEST":return{data:await L_({command:n,baseUrl:this.browser.baseUrl,logger:a}),succeedImmediately:!1,urlAfterCommand:this.browser.url()};case"VISUAL_DIFF":return OA({ctx:e,tracer:t,command:n,disableCache:i,browser:this.browser,logger:a,storage:this.storage,screenshotStorage:this.visualDiffScreenshotStorage,targetingWrapper:h=>this.wrapElementTargetingCommand(h)});case"FILE_UPLOAD":{let h,g;if(n.fileSource.type==="URL"?(g=n.fileSource.url,h=await Sx({uri:n.fileSource.url,logger:a,orgId:this.orgId})):n.fileSource.type==="USER_FILE"&&(g=n.fileSource.name,h=await this.uploadedFileStorage?.getFileForUpload(n.fileSource.name,this.orgId)),!h)throw new x("UserConfigurationError",`Attempted to use non-existent file for upload step: ${g}`);await this.browser.setFileChooserHandler({...h,filename:n.filename});break}case"AUTH_SAVE":return{data:await this.browser.saveAuthState(),succeedImmediately:!1,urlAfterCommand:this.browser.url()};case"AUTH_LOAD":{let h;if(!n.storageState.trim())h=void 0;else if(h=await To({orgId:this.orgId,code:n.storageState,fragment:!1,context:o,logger:a,localTools:this.localCodeEvalTools,signal:this.executeAbortController.signal}),typeof h!="object")throw new x("ActionFailureError",`Credentials must evaluate to an object (received ${typeof h} instead)`);let g;try{g=Oc.optional().parse(h)}catch(f){throw new x("ActionFailureError",`Credentials provided do not follow the required format: ${f}`)}await this.browser.loadAuthState(g);break}case"ELEMENT_CHECK":{let h=(n.timeout??nn)*1e3,g=this.generator.getAgentConfig()?.assertion;if(MA(n.assertion)&&!n.useSelector&&n.target.type==="description"&&g&&g!=="v1"){let y={id:n.id,type:"AI_ASSERTION",assertion:`There is no element on the page closely matches the following description. If the description has single quotes, remember that requires an exact text substring match. Description: ${n.target.elementDescriptor}`,iframeUrl:n.iframeUrl,timeout:n.timeout,cache:n.cache&&"memory"in n.cache?{memory:n.cache?.memory}:void 0};try{let S=await Wd({command:y,logger:a,aiPageFiltering:!!this.options?.aiPageFiltering,fixtures:this.getControllerFixtures(e),useMemory:this.shouldUseMemory(),source:"NEGATED_CHECK"});return{succeedImmediately:!1,thoughts:`The element described does not exist on the page: ${S.thoughts}`,urlAfterCommand:this.browser.url(),afterScreenshotOverride:S.afterScreenshotOverride}}finally{y.cache?.memory&&su(n,y.cache?.memory.traces,a)}}let f=await IA({command:n,tracer:t,timeoutMs:h,targetingWrapper:y=>this.wrapElementTargetingCommand(y),fixtures:this.getControllerFixtures(e),disableCache:i});return{fail:!f.success,data:f.data,elementInteracted:f.elementInteractedDisplayString,thoughts:f.err?.message??f.thoughts??`Element assertion ${f.success?"succeeded":"failed"}.`,succeedImmediately:!1,urlAfterCommand:this.browser.url()}}case"PAGE_CHECK":{let h=await An({action:async()=>Lu({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:!h.success,data:h.data,thoughts:h.success?"Page assertion passed.":h.err?.message??`Page assertion still failing after ${n.timeout} seconds.`,urlAfterCommand:this.browser.url(),succeedImmediately:!1}}case"REGISTER_REQUEST_LISTENER":{let h=new Io(n.requestMatcher),g=this.browser.registerRequestListener(h);return this.registeredListeners[n.key]=g.then(async f=>await Tf(f)).catch(f=>{a.error({err:f},"Failed to get request listener response")}),{succeedImmediately:!1,urlAfterCommand:this.browser.url()}}case"AWAIT_LISTENER":{let h=this.registeredListeners[n.key];if(!h)throw new x("ActionFailureError",`No listener registered with key: ${n.key}`);let g=n.timeout??10;return{data:await G(h,{milliseconds:g*1e3,message:`Request listener timed out after ${g} seconds`}),succeedImmediately:!1,urlAfterCommand:this.browser.url()}}case"RECORD_REQUESTS":{let h=new Io(n.requestMatcher);return this.recordedRequests[n.key]={},this.browser.registerRequestRecorder(n.key,h,{onRequestStart:(g,f)=>{this.recordedRequests[n.key][g]=Dd(f)},onRequestComplete:(g,f)=>{this.recordedRequests[n.key][g]=Dd(f)}}),{succeedImmediately:!1,urlAfterCommand:this.browser.url()}}case"GET_RECORDED_REQUESTS":{let h=this.recordedRequests[n.key];if(!h)throw new x("ActionFailureError",`No recorder registered with key: ${n.key}`);return delete this.recordedRequests[n.key],{data:Object.values(h),succeedImmediately:!1,urlAfterCommand:this.browser.url()}}case"SET_HEADER":{let h;return n.requestMatcher&&(h=new Io(n.requestMatcher)),this.browser.setHeader(n.name,n.value,h),{succeedImmediately:!1,urlAfterCommand:this.browser.url()}}case"MOCK_ROUTE":return{data:{key:this.browser.registerMock(n.key,new Io(n.requestMatcher),async(g,f)=>{let y=await To({orgId:this.orgId,code:n.responseGenerator,fragment:!1,context:o,timeoutMs:void 0,logger:a,localTools:this.localCodeEvalTools,mock:{request:g,response:f},disallowVariableUpdates:!0,responseSerialization:"RESPONSE"}),S=QE.parse(y);return new Response(S.body,{status:S.status,headers:S.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(h=>{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:je(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 Hd({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:je(this.logger)})}async getFailureRecoveryPlan(e){return this.generator.getFailureRecoveryPlan(e,{disableCache:!0,abortSignal:this.executeAbortController.signal,loggerTags:je(this.logger)})}};import{cloneDeep as vj}from"lodash-es";var Aj={showOverlay:!1},qd=class{sessions=new Map;sessionCountByIp=new Map;getCurrentConnectionsByIp(e){return this.sessionCountByIp.get(e)??0}getCurrentSessionsByIp(){return Object.fromEntries(this.sessionCountByIp)}reserveCapacityByIp(e){e&&this.sessionCountByIp.set(e,(this.sessionCountByIp.get(e)??0)+1)}releaseCapacityByIp(e){e&&this.sessionCountByIp.set(e,Math.max(this.getCurrentConnectionsByIp(e)-1,0))}registerSession({controller:e,context:t,cleanup:n,clientIp:o,sessionId:i,socket:a}){return this.sessions.set(i,{controller:e,context:t,cleanup:n,clientIp:o,browserBehavior:vj(Aj),socket:a}),i}removeSession(e,t){(async()=>{let o=this.sessions.get(e);if(!o)return;this.releaseCapacityByIp(o.clientIp);let{controller:i}=o;try{i.setClosed(),await i.browser.cleanup()}catch(a){t.error({err:a},"Error cleaning up browser in global state manager")}try{await o.cleanup?.()}catch(a){t.error({err:a},"Error running cleanup function in global state manager")}this.sessions.delete(e)})()}getSession(e){return this.sessions.get(e)}};function D_(r,e,t,n){let o=Date.now(),i=Date.now(),a,l,c,s,u=!1,d=async(g,f)=>{if(!g.closed&&!g.isInPageLoad)try{let y=c;c=void 0;let S=g.url(),E=f.toEditorDisplayCopy();JSON.stringify(E)===JSON.stringify(a)&&S===s&&o>i||(r.emit("browserState",{logsPerPage:y?.logsPerPage,harPages:y?.harPages,harEntries:y?.harEntries,viewport:g.getViewport(),url:S,iframeSrcUrls:l??[],context:E,isInPageLoad:g.isInPageLoad}),o=Date.now()),s=S,a=E}catch(y){if(!r.connected)return;let S=y instanceof Error?y.message:`${y}`;if(S.includes("Frame was detached")||S.includes("Not attached to an active page")||S.includes("browser has been closed")||S.includes("UserInfrastructureError"))return;t.error({err:y,sessionId:e},"Error grabbing browser state")}},p=setInterval(()=>{let g=n.getSession(e),f=g?.controller?.browser;if(!f||f.closed){t.debug("Clearing browser state socket cron due to the browser being closed"),clearInterval(p);return}d(f,g.context)},1e3),m=(g,f)=>!!(JSON.stringify(g)!==JSON.stringify(l)||f.logsPerPage.some(y=>y.length>0)||f.harPages&&Object.keys(f.harPages).length>0||f.harEntries&&Object.keys(f.harEntries).length>0),h=setInterval(async()=>{let f=n.getSession(e)?.controller?.browser;if(!f||f.closed){clearInterval(h);return}else if(u)return;u=!0;try{let y=await f.getAllFrameUrls(),S=f.retrieveAndClearDebugData();m(y,S)&&(l=y,c=S,i=Date.now())}catch(y){t.warn({err:y},"Failed to fetch extended details")}finally{u=!1}},2500);return{timers:[p,h]}}var Rj=4;async function k_({socket:r,logger:e,storageFactory:t,uploadedFileStorage:n,visualDiffScreenshotStorage:o,devicePixelRatio:i,generatorFactory:a,enricherFactory:l,authorization:c,settingsFactory:s,getOrgId:u,branchGetter:d,globalE2eStateManager:p}){let m=r.id,h=r.handshake.query.testId;if(!h)throw new Error("Socket connection request is missing testId");let g=await u({type:"e2e",testId:h}),f=await d?.();e=e.child({testId:h,orgId:g,sessionId:m,branch:f});let y=await a(g,e),S=await l(g,e),E=await s(g,e),R=await t(g),{testMetadata:A,baseUrl:C,envName:w,browserConfig:I,aiSettings:P,environmentVariables:X,localCodeEvalTools:q}=await Ii({testId:h,orgId:g,logger:e,storage:R,authorization:c,settings:E}),k=p.getSession(m);if(k)return e.info("Associating connection with existing session (likely reconnect)"),await k.controller.browser.clearAllCdpHighlights(),{type:"e2e",sessionId:m,orgId:g,testId:h};let ee=r.handshake.headers["x-forwarded-for"]?.split(",")[0];if(e.info({clientIp:ee,event:"connect",args:r.handshake.query},"Websocket event (connect)"),ee&&p.getCurrentConnectionsByIp(ee)>=Rj)throw e.error({clientIp:ee,sessions:p.getCurrentSessionsByIp(),...r.handshake.query},"Socket connection browser creation rate limit triggered"),new Error("You have exceeded the maximum number of connections allowed. Momentic limits the number of simultaneously open tabs to uphold browser reliability. Please close duplicate tabs and try again later.");p.reserveCapacityByIp(ee);try{await wj({socket:r,baseUrl:C,envName:w,testMetadata:A,orgId:g,sessionId:m,logger:e,environmentVariables:X,clientIp:ee,devicePixelRatio:i,storage:R,uploadedFileStorage:n,visualDiffScreenshotStorage:o,localCodeEvalTools:q,generator:y,enricher:S,browserConfig:I,aiSettings:P,globalE2eStateManager:p})}catch(z){throw e.warn({err:z},"Error setting up socket session, possibly due to client closing the connection"),p.releaseCapacityByIp(ee),z}return{type:"e2e",sessionId:m,testId:h,orgId:g}}async function wj({socket:r,baseUrl:e,envName:t,devicePixelRatio:n,testMetadata:o,orgId:i,sessionId:a,logger:l,storage:c,uploadedFileStorage:s,visualDiffScreenshotStorage:u,localCodeEvalTools:d,generator:p,environmentVariables:m,browserConfig:h,aiSettings:g,clientIp:f,enricher:y,globalE2eStateManager:S}){let E={viewport:o.advanced?.viewport??Gt,locale:o.advanced?.locale??oo,timezoneId:o.advanced?.timezone??io,geolocation:o.advanced?.geolocation??ao,colorScheme:o.advanced?.colorScheme};n&&(E.deviceScaleFactor=n);let R=o.id,A=await Od({settings:h,orgId:i,baseUrl:e,envName:t,testName:o.name,localTools:d,envVariables:m,logger:l,customHeaders:void 0});l=l.child({orgId:i,sessionId:a,testId:R});let C=await Ur.init({baseUrl:e,userBrowserSettings:A,enricher:y,storage:c,logger:l,contextArgs:E,iconKnowledgeBase:null,callbacks:{onTabsChange:(q,k)=>{r.emit("tabs",{tabs:q,activeTab:k})},onScreencastFrame:(q,k)=>{let ee=r;cn&&(ee=r.compress(!0)),ee.emit("screenshot",{buffer:q},()=>{k()})},onSvgsCollected:q=>{r.emit("newIconDetected",{numIcons:q.newSvgs.length}),c.saveNewIcons(q,l)}}});await C.navigate({url:e,initialNavigation:!0});let w=new Po({browser:C,generator:p,logger:l,orgId:i,options:{scratchPadId:void 0,slowMoMs:A.slowMoMs,autoFollowNewTabs:A.autoFollowNewTabs,useMemory:g.useMemory,aiPageFiltering:g.aiPageFiltering},storage:c,localCodeEvalTools:d,uploadedFileStorage:s,visualDiffScreenshotStorage:u}),I=D_(r,a,l,S),P=async()=>{I.timers.forEach(q=>clearInterval(q))},X=new ar({baseUrl:e,testName:o.name,currentUrl:w.browser.url(),variablesFromEnvironment:m,envName:t});if(!r.connected)throw await C.cleanup(),new Error("Socket not connected anymore, not proceeding with session setup");r.emit("session",{url:e,userAgent:Ur.USER_AGENT,viewport:w.browser.getViewport(),sessionId:a}),S.registerSession({controller:w,context:X,sessionId:a,cleanup:P,clientIp:f,socket:r})}async function Ii({testId:r,orgId:e,logger:t,storage:n,authorization:o,settings:i}){let a=await n.fetchTestMetadata(r,t);if(!a)throw new Error(`Test metadata could not found for test ${r}`);let l;o?.type==="API_KEY"&&(l=new mn({httpClient:new Lt({...o,logger:t}),fakerSeed:void 0}));let c=a.envs?.find(g=>g.default),s;c&&(s=await n.fetchEnvironment(c.name,t));let u=s&&"browser"in s?s.browser:void 0,d={...i.browser,...u,...a.advanced},p=a.baseUrl||s?.variables?.[wt];if(!p)throw new Error("Base URL is empty in both test options and the configured environment");let m={...s?.variables};await Promise.all((a.parameters??[]).map(async g=>{let f=await fr({orgId:e,s:g.defaultValue,context:ar.dummyContext(a.name,s?.name,m),logger:t,localTools:l});m[g.name]=f}));let h={...i.ai,...a.advanced};return{localCodeEvalTools:l,baseUrl:p,envName:s?.name,testName:a.name,browserConfig:d,environmentVariables:m,testMetadata:a,aiSettings:h}}var Vf=class{parentTracer=null;socket;step;orgId;constructor({step:e,socket:t,parentTracer:n,orgId:o}){this.socket=t,this.parentTracer=n,this.step=e,this.orgId=o}getParentStepIdChain(){return this.parentTracer?this.parentTracer?.getParentStepIdChain()??[]:[]}recordStepDuration(e){let t=e.step.type!=="PRESET_ACTION"?e.step.type:e.step.command.type;or.distribution("test_step_duration",e.durationMs,[`type:${t}`,"platform:browser","executor:editor",`orgId:${this.orgId}`])}attachBeforeScreenshot(){}attachAfterScreenshot(){}attachBeforeHtmlSnapshot(){}attachAfterHtmlSnapshot(){}recordTargetAutoHeal(){}async finish(e){switch(e.step.status){case"SUCCESS":this.socket.emit("success",{...e,parentStepIdChain:this.getParentStepIdChain()});return;case"FAILED":this.socket.emit("failure",{...e,parentStepIdChain:this.getParentStepIdChain()});return;case"CANCELLED":this.socket.emit("cancelled",{...e,parentStepIdChain:this.getParentStepIdChain()});return}}async startSubSteps(){return new jn({parentStep:this.step,socket:this.socket,parentTracer:this,orgId:this.orgId})}},jn=class{stepFrequenciesByType={};parentTracer;parentStep;socket;orgId;recordStepStat(e){e.type!=="PRESET_ACTION"?this.stepFrequenciesByType[e.type]=(this.stepFrequenciesByType[e.type]||0)+1:this.stepFrequenciesByType[e.command.type]=(this.stepFrequenciesByType[e.command.type]||0)+1}sendFinalizedStepStats(){for(let[e,t]of Object.entries(this.stepFrequenciesByType))or.increment("test_step_execution",t,[`type:${e}`,"platform:browser","executor:editor",`orgId:${this.orgId}`])}constructor({parentStep:e,socket:t,parentTracer:n,orgId:o}){this.parentTracer=n,this.parentStep=e,this.socket=t,this.orgId=o}async getScreenshot(){throw new Error("getScreenshot is not supported in the editor")}async getHtmlSnapshot(){throw new Error("getHtmlSnapshot is not supported in the editor")}getParentStepIdChain(){return this.parentStep?[...this.parentTracer?.getParentStepIdChain()??[],this.parentStep.id]:[]}async startStep(e){return this.recordStepStat(e.step),this.socket.emit("started",{stepId:e.step.id,parentStepIdChain:this.getParentStepIdChain(),attempt:e.attempt}),new Vf({step:e.step,parentTracer:this,socket:this.socket,orgId:this.orgId})}async finish(){this.sendFinalizedStepStats()}},Kd=class{constructor(e,t,n,o,i){this.socket=e;this.storage=t;this.orgId=n;this.testId=o;this.stepsBeforeRun=i}children=[];loggerBindings;async getScreenshot(){throw new Error("getScreenshot is not supported in the editor")}async getHtmlSnapshot(){throw new Error("getHtmlSnapshot is not supported in the editor")}attachConsoleLogs(){}attachNetworkLogs(){}attachBrowserCrashDump(){}async finish(){this.socket.emit("finished"),await Promise.all(this.children.map(e=>e.finish()))}async startBeforeStepList(){let e=new jn({orgId:this.orgId,parentStep:null,parentTracer:null,socket:this.socket});return this.children.push(e),e}async startMainStepList(){let e=new jn({orgId:this.orgId,parentStep:null,parentTracer:null,socket:this.socket});return this.children.push(e),e}async startAfterStepList(){let e=new jn({orgId:this.orgId,parentStep:null,parentTracer:null,socket:this.socket});return this.children.push(e),e}};var $f={currentlyExecutingRequests:{}},xj=r=>async(e,t)=>{let{testId:n,orgId:o}=r.metadata,i=await r.settingsFactory(o,r.logger),a=await r.storageFactory(o),l,c=await Ii({testId:n,orgId:o,logger:r.logger,storage:a,authorization:r.authorization,settings:i}),s=`${n}|${c.baseUrl}`;try{let u=$f.currentlyExecutingRequests[s]??0;$f.currentlyExecutingRequests[s]=u+1,l=await _j({...r,...e,...c,done:t})}finally{r.logger.info({result:l,sessionId:r.metadata.sessionId},"Test execution complete"),$f.currentlyExecutingRequests[s]--}},_j=async({socket:r,steps:e,baseUrl:t,testMetadata:n,reInitialize:o,toStep:i,fromStep:a,storageFactory:l,aiSettings:c,browserConfig:s,metadata:u,logger:d,envName:p,testName:m,environmentVariables:h,localCodeEvalTools:g,done:f,cacheStorageFactory:y,globalE2eStateManager:S})=>{let{testId:E,sessionId:R,orgId:A}=u,C=R,w=S.getSession(R);if(!w)throw new Error("No active session found");let{controller:I,context:P}=w;I.setOpen(),d=d.child({testId:E,orgId:A,sessionId:R,runId:C}),d.info({steps:e.map(J=>`${J.type}${"command"in J?` - ${J.command.type}`:""}`),toStep:i,fromStep:a,reInitialize:o,envName:p,testName:m,baseUrl:t,context:P,browserConfig:s,aiSettings:c},"Socket execution parameters");let X=h??{},q=async()=>{o&&(await I.browser.reset({newUrl:t}),P.reset({baseUrl:t,currentUrl:I.browser.url(),variablesFromEnvironment:X,envName:p,testName:m}))},k=await l(A),ee=await y(A),z=async()=>{try{await ee.resolveStepCacheEntries({schemaVersion:n.schemaVersion,testId:E,stepLists:{steps:e},logger:d})}catch(J){d.error({err:J},"Failed to fetch step cache entries from Momentic server. This can drastically reduce test reliability and performance.")}};try{await Xs({promiseGenerator:async()=>Promise.all([q(),z()]),signal:I.executeAbortController.signal,codePath:"resolveStepCacheAndInitBrowser"}),I.setOpen()}catch(J){if(r.emit("finished"),J.name!=="AbortError")throw new Error(`Failed to setup browser for execution: ${J}`)}let j=Cj(e),he={collectDebugData:!1,reinitializeBrowser:!1,disableHealing:!0},$={orgId:A,runId:C,testMetadata:n,steps:e,fromStep:a,toStep:i,orgSettings:{ai:c,browser:s}},rt={controller:I,context:P,storage:k,codeEvalTools:g,usageTracker:new Zi,logger:d},Ne={test:{},step:{onDynamicAIActionStatusUpdateEvent:J=>{r.emit("dynamicCommandStatusUpdate",J)},onDynamicAIActionEvaluatingEvent:J=>{r.emit("dynamicCommandEvaluating",J)},onDynamicCommandGenerated:J=>{r.emit("dynamicCommandGenerated",J)},onDynamicCommandExecuted:J=>{r.emit("dynamicCommandExecuted",J)}}},ct=new Kd(r,k,A,E,j),kt=await Pd({fixtures:rt,options:he,callbacks:Ne,inputs:$,testParams:{tracer:ct}});return kt?.status==="PASSED"?await fu({logger:d,cacheStorage:ee,orgId:A,testId:E,originalSteps:{steps:j},updatedSteps:{steps:e}}):kt?.status==="FAILED"&&await Su({logger:d,cacheStorage:ee,orgId:A,testId:E,originalSteps:{steps:j},updatedSteps:{steps:e}}),await ct.finish(),f?.(kt),kt.status};var U_={event:"execute",createHandler:xj};import{cloneDeep as Ij}from"lodash-es";var Mj=r=>async({command:e},t)=>{let{logger:n,generatorFactory:o,metadata:i}=r,a=Ij(e),l=av(a);if(l.category!=="NO_DESCRIPTION_PROVIDED"){if(l.category!=="NONE"){t?.({result:l});return}"cache"in a&&(a.cache=void 0);try{let s=await(await o(i.orgId,n)).getLintStepResult({command:a},{logger:n});t?.({result:s})}catch(c){n.error({event:"lint",err:c},"Failed to lint step"),t?.({result:void 0})}}},F_={event:"lintStep",createHandler:Mj};var Pj=({metadata:r,logger:e,storageFactory:t,globalE2eStateManager:n})=>{let{sessionId:o,orgId:i}=r;return async(a,l)=>{let{description:c,command:s,testMetadata:u,returnScreenshot:d}=a;e.info({params:a},`Locate handler called - ${c}`);let p=n.getSession(o);if(!p)throw new Error("No active session found");let{controller:m,context:h}=p;m.setOpen();let g=await t(i),f=ei.parse(u.advanced??{}),y={},S;if(c){if("useSelector"in s&&s.useSelector)try{let E=await m.locateElementWithSelector(c,"iframeUrl"in s?s.iframeUrl:void 0);S=E.resolution.locator,y={target:E.target,thoughts:E.thoughts}}catch(E){e.warn({err:E},"Failed resolving target with selector"),l({err:`Failed locating element: ${E.message}`,decisions:E instanceof an?E.decisions:void 0});return}else try{let E=await m.locateElement({description:c,disableCache:f.disableAICaching??!1,skipWait:!0,testContext:h,source:Yo(s),iframeUrl:"iframeUrl"in s?s.iframeUrl:void 0,memory:"cache"in s&&s.cache&&"target"in s.cache&&Yl(s.cache.target.memory)?s.cache.target.memory:void 0,logger:e});y={target:E.target,thoughts:E.thoughts},S=E.resolution.locator}catch(E){(async()=>{try{let R=await m.browser.getCondensedHtml({skipWait:!0});e.warn({err:E,html:R.slice(0,1e5)},"Failed locating element with AI")}catch(R){e.warn({err:R},"Failed grabbing HTML after trying to locate element with AI")}})(),l({err:`${E.message}`});return}if(s.type==="SELECT_OPTION"&&S)try{y.options=await m.browser.getSelectOptions(S)}catch(E){e.warn({err:E},"Failed getting select options"),l({err:`Failed getting select options: ${E.message}`});return}e.info({result:y},"Locate handler result")}if(d)try{let{buffer:E,width:R,height:A}=await m.screenshotWithDimensions({clearHighlights:!0,locator:S}),C=await g.uploadScreenshot(E);y.screenshot={data:C,width:R,height:A},e.info({width:R,height:A},"Captured screenshot during locate")}catch(E){e.error({err:E},"Error capturing screenshot during locate"),l({err:`Error taking screenshot: ${E.message}`});return}if(l({result:y}),S)try{await Promise.all([m.browser.scrollIntoViewIfNeeded(S),m.browser.highlight(S)])}catch(E){e.warn({err:E},"Error highlighting element, continuing...")}}},B_={event:"locate",createHandler:Pj};var Oj=({metadata:r,logger:e,globalE2eStateManager:t})=>{let{sessionId:n}=r;return async({event:o,percentX:i,percentY:a})=>{let l=t.getSession(n);if(!l)throw new Error("No active session found");let c=l.controller.browser;if(c.closed||c.getActivePage().isClosed()){e.warn("Ignoring mouse move because the browser is closed");return}try{await c.clickMouseFromPositionPercentages(o,i,a)}catch(s){e.error({err:s},"Error performing click during cloud recording in control mode")}}},z_={event:"mouseClickEvent",createHandler:Oj};var Lj=({metadata:r,generatorFactory:e,logger:t,socket:n,globalE2eStateManager:o})=>{let{sessionId:i,orgId:a,testId:l}=r;return async({stepId:c,parentStepIdChain:s,attribute:u})=>{let d=o.getSession(i);if(!d)throw new Error("No active session found");let{controller:p}=d,m=await e(a,t);p.setOpen(),d.browserBehavior.showOverlay=!0;let h=new AbortController;h.signal.addEventListener("abort",async()=>{try{d.browserBehavior.showOverlay=!1,await p.stopRecordMode()}catch(y){t.warn({err:y},"Failed to stop record mode in target click socket handler")}},{once:!0});let g=!1,f=(y,S)=>{S.type!=="PRESET_ACTION"||S.command.type!=="CLICK"||(n.emit("targetRecordingUpdate",{type:y,stepId:c,parentStepIdChain:s,command:S.command,attribute:u}),h.abort(),g=!0)};setTimeout(()=>{g||(h.abort(),n.emit("targetRecordingUpdate",{type:"error",err:"Timed out waiting for click event",stepId:c,parentStepIdChain:s,attribute:u}))},1e4),await p.startRecordMode({params:{generator:m,logger:t,testId:l,orgId:a,callbacks:{onActionReceived:y=>f("clickReceived",y),onStepRecorded:y=>f("descriptionGenerated",y)}},abortController:h,isClickToRecord:!0}),n.emit("targetRecordingUpdate",{type:"listenersInitialized",stepId:c,parentStepIdChain:s,attribute:u})}},H_={event:"recordTargetClick",createHandler:Lj};var Nj=({metadata:r,logger:e,globalE2eStateManager:t})=>{let{sessionId:n}=r;return async({key:o})=>{let i=t.getSession(n);if(!i)throw new Error("No active session found");if(o==="Dead")return;let{controller:a}=i;if(a.browser.closed||a.browser.getActivePage().isClosed()){e.debug({sessionId:n},"Browser is closed, ignoring keyboard press socket event");return}try{a.setOpen(),await a.browser.keyDown(o,{})}catch(l){if(l.message.includes("has been closed")){e.debug({sessionId:n,err:l},"Browser is closed, ignoring key down socket event error");return}throw l}}},G_={event:"keyDownEvent",createHandler:Nj};var Dj=({metadata:r,logger:e,globalE2eStateManager:t})=>{let{sessionId:n}=r;return async({key:o})=>{let i=t.getSession(n);if(!i)throw new Error("No active session found");if(o==="Dead")return;let{controller:a}=i;if(a.browser.closed||a.browser.getActivePage().isClosed()){e.debug({sessionId:n},"Browser is closed, ignoring keyboard press socket event");return}try{a.setOpen(),await a.browser.keyUp(o,{})}catch(l){if(l.message.includes("has been closed")){e.debug({sessionId:n,err:l},"Browser is closed, ignoring key up socket event error");return}throw l}}},j_={event:"keyUpEvent",createHandler:Dj};var kj=({metadata:r,logger:e,globalE2eStateManager:t})=>{let{sessionId:n}=r,o,i=0,a=(s,u)=>{let d=async()=>{o=void 0};clearTimeout(o),o=setTimeout(d,Math.min(1e3,250*(i+1)))},l,c=0;return async s=>{let u=t.getSession(n);if(!u)throw new Error("No active session found");let{controller:d,browserBehavior:p}=u,m=d.browser;if(m.closed||m.getActivePage().isClosed()){e.warn("Ignoring mouse move because the page is closed");return}if(s.event==="scroll"){let h=await m.scrollFromPositionPercentages(s.percentX,s.percentY,l?.x??0,l?.y??0),g=u.browserBehavior.recordingState?.transformer;g&&h&&g.recordScroll(h);return}p.showOverlay&&a(m,s);try{let h=await m.moveMouseFromPositionPercentages(s.percentX,s.percentY);c=0,l=h}catch(h){c++,c%5===0&&e.warn({err:h,mouseErrors:c},"Error in socket mouse move handler")}}},V_={event:"mouseMoveEvent",createHandler:kj};var Uj=({metadata:r,generatorFactory:e,socket:t,logger:n,globalE2eStateManager:o})=>{let{sessionId:i,orgId:a,testId:l}=r;return async({stepId:c})=>{let s=o.getSession(i);if(!s)throw new Error("No active session found");let{controller:u,browserBehavior:d}=s,p=await e(a,n);n.info("Starting cloud recording");let m=new AbortController,h=await u.startRecordMode({params:{generator:p,logger:n,testId:l,orgId:a,callbacks:{onActionReceived:(g,f)=>{t.emit("stepRecorded",{stepId:c,step:g,offset:f})},onStepRecorded:(g,f)=>{t.emit("stepRecorded",{stepId:c,step:g,offset:f})}}},abortController:m,isClickToRecord:!1});d.recordingState={transformer:h}}},$_={event:"recordingStart",createHandler:Uj};var Fj=({metadata:r,logger:e,globalE2eStateManager:t})=>{let{sessionId:n}=r;return async()=>{let o=t.getSession(n);if(!o)throw new Error("No active session found");e.info("Stopping cloud recording"),await o.controller.stopRecordMode(),o.browserBehavior.recordingState=void 0,o.browserBehavior.showOverlay=!1}},W_={event:"recordingStop",createHandler:Fj};var Bj=({socket:r,metadata:e,logger:t,storageFactory:n,authorization:o,settingsFactory:i,globalE2eStateManager:a})=>async(l,c)=>{let{testId:s,sessionId:u,orgId:d}=e;t.info({testId:s,sessionId:u},"Refresh event received");let p=await i(d,t),m=await n(d),{baseUrl:h}=await Ii({testId:s,orgId:d,logger:t,storage:m,authorization:o,settings:p}),g=a.getSession(u);if(!g){r.emit("error",{message:"No session to refresh"});return}let{controller:f}=g;f.setOpen(),await f.browser.refresh();let y=f.browser.getViewport();t.info({baseUrl:h,viewport:y},`Session refreshed for test ${s} at ${h}`),c()},q_={event:"refresh",createHandler:Bj};var zj=({socket:r,metadata:e,logger:t,storageFactory:n,authorization:o,settingsFactory:i,globalE2eStateManager:a})=>async()=>{let{testId:l,sessionId:c,orgId:s}=e;t.info({testId:l,sessionId:c},"Reset event received");let u=await i(s,t),d=await n(s),{baseUrl:p,envName:m,testName:h,environmentVariables:g}=await Ii({testId:l,orgId:s,logger:t,storage:d,authorization:o,settings:u}),f=a.getSession(c);if(!f){r.emit("error",{message:"No session to reset"});return}let{controller:y,context:S}=f;await y.browser.reset({newUrl:p});let E=y.browser.baseUrl;S.reset({baseUrl:E,currentUrl:y.browser.url(),variablesFromEnvironment:g,envName:m,testName:h});let R=y.browser.getViewport(),A=Ur.USER_AGENT;t.info({baseUrl:p,viewport:R},`Session reset for test ${l} at ${E}`),r.emit("session",{url:E,userAgent:A,viewport:R,sessionId:c})},K_={event:"reset",createHandler:zj};var Hj=({metadata:r,globalE2eStateManager:e})=>{let{sessionId:t}=r;return async({url:n})=>{let o=e.getSession(t);if(!o)throw new Error("No active session found");await o.controller.browser.switchToPage({type:"SUBSTRING",substring:n})}},Y_={event:"switchTab",createHandler:Hj};async function X_(r){return k_(r)}var J_=[yA,U_,B_,K_,q_,gA,Y_,F_,H_,$_,W_,V_,z_,G_,j_,SA,fA];var Q_=r=>{let{logger:e}=r,t=new Gj(r.baseServer,{cors:{origin:"*",methods:["GET","POST"]},pingTimeout:15*60*1e3,pingInterval:15*60*1e3,maxHttpBufferSize:1e7,perMessageDeflate:!0});return t.on("connection",async n=>{let o;try{e.info({event:"connection",transport:n.conn.transport.name},"Websocket connection established"),o=await X_({...r,socket:n,logger:e}),e=e.child(o)}catch(i){e.error({event:"connection",type:"websocket",err:i},"Failed to setup connection"),n.emit("error",{message:i instanceof Error?i.message:`${i}`}),n.disconnect(!0);return}J_.forEach(i=>jj(i,{...r,socket:n,metadata:o,logger:e}))}),t},jj=(r,e)=>{let t=r.createHandler(e),n=(...o)=>{["mouseMoveEvent","keyDownEvent","keyUpEvent","mouseClickEvent","lintStep"].includes(r.event)||e.logger.debug({...e.metadata,event:r.event},`Websocket event (${r.event})`);let i=a=>{e.logger.error({event:r.event,type:"websocket",err:a instanceof Error?a:new Error(`${a}`)},"Unhandled exception in socket handler"),e.socket.emit("error",{message:a instanceof Error?a.message:`${a}`})};try{let a=t.apply(void 0,o);a&&typeof a.catch=="function"&&a.catch(i)}catch(a){i(a)}};e.socket.on(r.event,n)};import{Router as Kj}from"express";import{Router as $j}from"express";import Ul from"fs";import kl from"path";import{v4 as Wj}from"uuid";import qj from"yaml";import{hostname as Vj}from"os";var Wf="2.20.3",at=Xc({app:"desktop-server",hostname:Vj(),disableConsoleLogs:!0}).child({cliVersion:Wf});(async()=>{try{let r=await il(at);r.gitBranchName&&at.addBinding("branch",r.gitBranchName)}catch{}})();var ja=$j();async function qf(r){return(await Cu(r,at)).map(n=>{let o=r.modules[n.moduleId];if(!o){T.warn(`Found a dangling module with ID ${n.moduleId} that could not be found on disk.`);return}return{...o,content:n}}).filter(n=>n!==void 0)}ja.get("/",Re(async(r,e)=>{let t=ce(),n=await Y(t),o=await qf(n);e.status(200).json(o)}));ja.post("/",Re(async(r,e)=>{let t;try{t=fT.parse(r.body)}catch(l){e.status(400).json({error:`Invalid request body: ${l}`});return}try{ro(t.name)}catch(l){e.status(400).json({error:`Invalid module name: ${l}`});return}let n=ce(),o=(await Y(n)).modules;if(Object.values(o).find(l=>l.name===t.name)){e.status(400).send(`A module with the name "${t.name}" already exists. Please choose a different name.`);return}let i=kl.join(n.rootDir,t.folderPath??"");if(!Ul.existsSync(i)||!Ul.statSync(i).isDirectory()){e.status(400).json({error:`The folder configured for module creation '${i}' does not exist.`});return}let a=await wu({...t,folder:i,project:n});e.status(201).json(a)}));ja.get("/:moduleId",Re(async(r,e)=>{if(!r.params.moduleId){e.status(400).json({error:"Missing moduleId in url path."});return}let t=await Y(ce()),n=t.modules[r.params.moduleId];if(!n){e.status(404).json({error:"Module not found."});return}try{let o=await Yr(n,t,T);e.json(o)}catch(o){e.status(400).json({err:o})}}));ja.post("/:moduleId/duplicate",Re(async(r,e)=>{if(!r.params.moduleId){e.status(400).json({error:"Missing moduleId in url path."});return}let t;try{t=gT.parse(r.body)}catch(g){e.status(400).json({error:`Invalid request body: ${g}`});return}try{ro(t.name)}catch(g){e.status(400).json({error:g.message});return}let n=ce(),o=await Y(n),i=o.modules[r.params.moduleId];if(!i){e.status(404).json({error:"Module not found."});return}if(Object.values(o.modules).find(g=>g.name===t.name)){e.status(400).send(`A module with the name "${t.name}" already exists. Please choose a different name.`);return}let a=await Yr(i,o,T),l=kl.join(n.rootDir,kl.dirname(i.relativePath));if(!Ul.existsSync(l)||!Ul.statSync(l).isDirectory()){e.status(400).json({error:`The folder configured for module creation '${l}' does not exist.`});return}let c=Oe(t.name),s=kl.join(l,`${c}.module.yaml`),u=Wj(),{stepsToSave:d}=await et({stepLists:{steps:a.steps},createNewCacheIds:!0,cacheCreationParams:{orgId:xt()}}),p={fileType:pe.MODULE,schemaVersion:ue,moduleId:u,name:t.name,description:"",enabled:!0,steps:d.steps,parameters:a.parameters,defaultParameters:a.defaultParameters,parameterEnums:a.parameterEnums,defaultCacheKey:a.defaultCacheKey,defaultCacheTtl:a.defaultCacheTtl,defaultCacheAllInvocations:a.defaultCacheAllInvocations,autoAuth:a.autoAuth,advanced:a.advanced},m=qj.stringify(p);Ul.writeFileSync(s,m,"utf-8");let h={relativeFilePath:kl.relative(n.rootDir,s)};e.status(201).json(h)}));ja.patch("/:moduleId/metadata",Re(async(r,e)=>{if(!r.params.moduleId){e.status(400).json({error:"Missing moduleId in url path."});return}let t;try{t=ST.parse(r.body)}catch(i){e.status(400).json({error:`Invalid request body: ${i}`});return}let n=ce(),o=await Y(n);Yv({moduleId:r.params.moduleId,content:t,momenticFiles:o,logger:T,project:n}),e.status(201).json({message:"ok"})}));var Z_=ja;var eI=Kj();eI.get("/",Re(async(r,e)=>{let t=ce(),n=await Y(t),o=new Set;n?.tests&&Object.values(n.tests).forEach(s=>{s.labels?.forEach(u=>o.add(u))});let i=Array.from(o).sort(),a=Object.values(n.tests),l=await qf(n),c={labels:i,tests:a,modules:l};e.status(200).json(c)}));var tI=eI;import{Router as Yj}from"express";var Kf=Yj();Kf.get("/",Re((r,e)=>{let t=xu(ce(),at);e.status(200).json(t)}));Kf.get("/names",Re((r,e)=>{let n=ce().config.environments?.map(o=>o.name)??[];e.status(200).json(n)}));var rI=Kf;import{Router as Xj}from"express";var nI=Xj();nI.get("/",Re((r,e)=>{e.status(200).json({userId:ga(),orgId:xt()})}));var oI=nI;import{StreamableHTTPServerTransport as ZV}from"@modelcontextprotocol/sdk/server/streamableHttp.js";import{isInitializeRequest as e$}from"@modelcontextprotocol/sdk/types.js";import{randomUUID as t$}from"crypto";import{Router as r$}from"express";import{McpServer as JV}from"@modelcontextprotocol/sdk/server/mcp.js";import{SSEServerTransport as QV}from"@modelcontextprotocol/sdk/server/sse.js";import{streamObject as tV}from"ai";import Qd from"dedent";import{z as Oo}from"zod";import{tool as Jj}from"ai";import{z as Qj}from"zod";var Yd=(r,e)=>({builder:n=>Jj({description:r.schema.description,inputSchema:Qj.object(r.schema.inputSchema),execute:async o=>{let i=e(n);n.logger.info({input:o},`Executing tool ${r.schema.name}`);try{await r.handle(n,o,i,void 0)}catch(l){i.addError(String(l))}let a=await i.serialize();return a.isError?n.logger.error({toolName:r.schema.name,input:o,err:a.content.map(l=>l.text).join(`
|
|
4060
4059
|
`)},"Tool execution resulted in error"):n.logger.info({toolName:r.schema.name,input:o},"Tool execution completed"),a}}),tool:r});var Fl=class{results=[];isError;addResult(e){this.results.push(e)}addError(e){this.results.push(`Error: ${e}`),this.isError=!0}getResult(){return this.results.join(`
|
|
4061
4060
|
`)}async serialize(){let e=[];return this.results.length&&(e.push("### Result"),e.push(this.results.join(`
|
|
4062
4061
|
`)),e.push("")),{content:[{type:"text",text:e.join(`
|
|
@@ -4133,7 +4132,7 @@ with this test we are editing:
|
|
|
4133
4132
|
|
|
4134
4133
|
to pick which of these modules are relevant:
|
|
4135
4134
|
|
|
4136
|
-
`;let h=aV(d);m+=h;let g=tV({schema:Qf,model:p("claude-sonnet-4-5-20250929"),system:iV,messages:[{role:"user",content:m}]}),f=[];for await(let A of g.textStream)f.push(A);let
|
|
4135
|
+
`;let h=aV(d);m+=h;let g=tV({schema:Qf,model:p("claude-sonnet-4-5-20250929"),system:iV,messages:[{role:"user",content:m}]}),f=[];for await(let A of g.textStream)f.push(A);let y=f.join(""),S;try{let A=JSON.parse(y);S=Qf.parse(A)}catch(A){i.error({rawResponse:y,parseError:A},"Failed to parse AI response as JSON"),t.addError(`Failed to parse AI response: ${String(A)}. Raw response: ${y}`);return}let E=new Set(d.map(A=>A.moduleId)),R=S.recommendations.filter(A=>E.has(A.moduleId)?!0:(i.warn({moduleId:A.moduleId,moduleName:A.moduleName},"AI recommended a module that doesn't exist"),!1));t.addResult(JSON.stringify({recommendations:R,totalModulesAnalyzed:d.length},null,2))}catch(s){i.error({err:s},"Error in module recommendation"),t.addError(`Failed to recommend modules: ${String(s)}`)}}}),Zd=[lV,rV,nV];var cV=en({schema:{name:"momentic_environment_list",description:"List environments defined in the project's momentic.config.yaml file.",inputSchema:{}},handle:async(r,e,t,n)=>{let{project:o,logger:i}=r,a=xu(o,i);t.addResult(JSON.stringify({environments:a},null,2))}}),iI=[cV];import{streamText as jV}from"ai";import VV from"path";import{z as $V}from"zod";var ep=new qd;var Lo=class extends aa{constructor(t,n){super(t,n);this.client=t;this.orgId=n}async fetchTestMetadata(t){let n=ce(),i=(await Y(n)).tests[t];if(i)return rl(i.relativePath,n)}async fetchApiTestMetadata(){throw new Error("API tests are not available in the desktop app")}async fetchEnvironment(t,n){let o=ce();return nl(t,o,dn)}async fetchIconKnowledgeBase(t){try{return await this.client.fetchIconKnowledgeBase(t)}catch(n){return t.error({err:n},"Failed to fetch icon knowledge base"),null}}};var Mi=class{async prepareGoldenScreenshotForComparison(e,t,n){return await new Ta(ce(),!1).prepareGoldenScreenshotForComparison(e,t,n)}};import aI from"path";import{v4 as uV}from"uuid";async function tp({project:r,input:e}){try{ro(e.name)}catch(s){throw new De(`${s} when validating the test entity name`)}if(!e.baseUrl&&!e.environment)throw new De("Either 'baseUrl' or 'environment' must be provided when creating a test.");let t=await Y(r);if(Object.values(t.tests).find(s=>s.name===e.name))throw new De(`A test with the name "${e.name}" already exists. Please use a different name.`);let i={id:uV(),name:e.name,description:e.description,baseUrl:e.baseUrl,schemaVersion:ue,advanced:{browserType:e.browserType??"Chromium",viewport:e.viewport??Gt},retries:0,steps:[]};e.environment&&(i.envs=[{name:e.environment,default:!0}]);let a=aI.join(r.rootDir,...e.pathSegments||[]),l=await Jv({test:i,name:e.name,folder:a});return{...i,relativeFilePath:aI.relative(r.rootDir,l)}}import{pruneMessages as MV,stepCountIs as PV}from"ai";import rp from"dedent";var dV=rp`
|
|
4137
4136
|
<ai-actions>
|
|
4138
4137
|
AI actions (type: AI_ACTION_DYNAMIC) are special steps that dynamically generate up to 15 sub-steps to achieve a complex goal. They are useful for:
|
|
4139
4138
|
- Multi-step workflows that require decision-making (e.g., "Find and click the first available appointment slot")
|
|
@@ -4375,17 +4374,17 @@ ${n}`}import pV from"path";var np=class{_result=[];_includeSnapshot=!1;_includeT
|
|
|
4375
4374
|
`)}setIncludeTest(){this._includeTest=!0}async test(){if(!this._includeTest)return"";let e=await Y(this._project),t=await tt(pV.join(this._project.rootDir,this._testPath),this._logger,e),n=[];return n.push("### Test","```json",JSON.stringify(t,null,2),"```"),n.join(`
|
|
4376
4375
|
`)}addError(e){this._result.push(e),this._isError=!0}async serialize(){let e=[];this._result.length&&(e.push("### Result"),e.push(this._result.join(`
|
|
4377
4376
|
`)),e.push(""));let t=await this.snapshot();t&&e.push(t,"");let n=this.testContext();n&&e.push(n,"");let o=await this.test();return o&&e.push(o,""),{content:[{type:"text",text:e.join(`
|
|
4378
|
-
`)}],isError:this._isError}}};var Et=r=>({builder:Yd(r,t=>new np(t.controller.browser,t.testContext,t.project,t.logger,t.testPath)).builder,name:r.schema.name});var mV=Et({schema:{name:"observe_page",description:"Observe the current page's accessibility snapshot.",inputSchema:{}},handle:async(r,e,t,n)=>{t.setIncludeSnapshot()}}),cI=[mV];import ip from"path";import{z as Fe}from"zod";function No(r,e,t,...n){t?.emit(r,...n),e.info({event:r,args:n},"Emitting copilot event")}import hV from"fs";import Va from"path";function uI(r){let e=r.subDir?Va.join(r.project.rootDir,r.subDir):r.project.rootDir,t=`${Oe(r.name)}.module.yaml`,n=Va.join(e,t),o=Va.relative(r.project.rootDir,n),i=hV.statSync(n);return{type:pe.MODULE,name:r.name,id:r.moduleId,description:r.description??void 0,relativePath:o,fullFilePath:n,platformSep:Va.sep,fullPathSegments:n.split(Va.sep),relativePathSegments:o.split(Va.sep),fileName:t,lastModified:i.mtime,createdAt:i.birthtime}}import{randomUUID as Zf}from"crypto";import{z as dI}from"zod";var gV=["AI_EXTRACT","JAVASCRIPT"];function op(r){let e=r.config.ai?.aiAction??!1,t=e?"The step types that can be ingested for a test change. The PRESET_ACTION's action can be seen as a single step command. The MODULE is a module step to use. The AI_ACTION_DYNAMIC is an AI action that will dynamically generate up to 15 steps to achieve a goal.":"The step types that can be ingested for a test change. The PRESET_ACTION's action can be seen as a single step command. The MODULE is a module step to use.";return e?dI.discriminatedUnion("type",[dm,pm,By]).describe(t):dI.discriminatedUnion("type",[dm,pm]).describe(t)}async function Pi(r,e,t){switch(r.type){case"PRESET_ACTION":{let n=mc(r.action),o=r.envKey&&gV.includes(n.type)?r.envKey:void 0;return{type:"PRESET_ACTION",command:n,id:Zf(),envKey:o}}case"MODULE":{let{selector:n,inputs:o}=r.module,{entity:i,momenticFiles:a}=await xn(e,n,"module"),l=await Yr(i,a,t);zy(o,l);let s=Object.keys(o??{}).length>0?o??{}:(l.parameters?.length??0)>0?{}:void 0,u={id:Zf(),inputs:s};return{...l,...u,type:"RESOLVED_MODULE"}}case"AI_ACTION_DYNAMIC":{if(!(e.config.ai?.aiAction??!1))throw new Error("AI actions are disabled. Enable AI actions in your momentic.config.yaml by setting 'ai.aiAction: true' to use this feature.");return{type:"AI_ACTION_DYNAMIC",text:r.text,id:Zf()}}default:return(o=>{throw new Error("You missed a case in the switch above")})(r)}}async function pI({moduleMetadata:r,steps:e,momenticFiles:t,project:n}){let{stepsToSave:o}=await et({stepLists:{steps:e}});nr({content:{...r,steps:o.steps},schemaVersion:ue,momenticFiles:t,project:n})}var fV=Et({schema:{name:"momentic_module_create",description:"Create a module. If startIndex is provided, the steps will be extracted from the current test, a module will be created with those steps, and the test will be updated to reference the new module. If no startIndex is provided, an unreferenced module will be created. Automatically splices and repairs the test to reference the new module.",inputSchema:{name:Fe.string(),description:Fe.string(),enabled:Fe.boolean().default(!0),parameters:Fe.string().array().optional().describe("Array of parameter names for the module, e.g., ['apiKey', 'userId']."),defaultParameters:Fe.record(Fe.string(),Fe.string()).optional().describe("Default values for parameters, e.g., { 'apiKey': 'default123' }. Keys must match parameters."),parameterEnums:Fe.record(Fe.string(),Fe.string().array()).optional().describe("Enum options for parameters, e.g., { 'role': ['admin', 'user'] }. Keys must match parameters."),moduleInputs:Fe.record(Fe.string(),Fe.string()).optional().describe("Input parameters to pass to the new module when it's inserted into the test. Keys must match the module's defined parameters. Only relevant if startIndex is provided."),subDir:Fe.string().optional().describe("sub directory to create the module in. If not provided, the module will be created in the project's root directory."),startIndex:Fe.number().optional().describe("Start index of steps to extract from the current test (0-based)."),endIndex:Fe.number().optional().describe("End index of steps to extract from the current test (exclusive). If not provided, extracts just the startIndex.")}},handle:async(r,e,t,n)=>{let{project:o,logger:i,testPath:a,socket:l}=r,c=e.startIndex??0,s=e.endIndex??c+1,u=await Y(o);if(Object.values(u.modules).find(g=>g.name===e.name))throw new De(`A module with the name "${e.name}" already exists. Please use a different name.`);if(e.parameters!==void 0){let g=e.defaultParameters?Object.keys(e.defaultParameters):[],f=e.parameterEnums?Object.keys(e.parameterEnums):[],S=new Set([...g,...f]);for(let y of S)if(!e.parameters.includes(y))throw new De(`Default parameter "${y}" is not defined in parameters array. Available parameters: ${e.parameters.join(", ")}`)}let p=[];if(e.startIndex!==void 0){if(!a)throw new De("testPath is required when extracting steps from the current test.");let g=await tt(ip.join(o.rootDir,a),i,u);if(c<0||c>=g.steps.length)throw new De(`startIndex ${c} is out of bounds. Test has ${g.steps.length} steps.`);if(s<=c||s>g.steps.length)throw new De(`endIndex ${s} is out of bounds. Must be between ${c+1} and ${g.steps.length}.`);p=g.steps.slice(c,s);for(let f of p)if(f.type==="RESOLVED_MODULE")throw new De("Modules cannot be nested. Please select steps that do not include module references.")}let m=await wu({name:e.name,description:e.description??"",enabled:e.enabled??!0,steps:p,folder:e.subDir?ip.join(o.rootDir,e.subDir):o.rootDir,project:o}),h=uI({project:o,name:e.name,moduleId:m.moduleId,subDir:e.subDir,description:m.description??void 0});if(u.modules[m.moduleId]=h,e.parameters!==void 0||e.defaultParameters!==void 0||e.parameterEnums!==void 0){let g={moduleId:m.moduleId,name:e.name,description:e.description??m.description,enabled:e.enabled??m.enabled,parameters:e.parameters??[],defaultParameters:e.defaultParameters,parameterEnums:e.parameterEnums};await pI({moduleMetadata:g,steps:p,momenticFiles:u,project:o}),m={...m,name:e.name,description:e.description??m.description,enabled:e.enabled??m.enabled,parameters:e.parameters??[],defaultParameters:e.defaultParameters,parameterEnums:e.parameterEnums}}if(e.startIndex!==void 0){let g=await tt(ip.join(o.rootDir,a),i,u),f={type:"MODULE",module:{selector:{id:m.moduleId},inputs:e.moduleInputs??{}}},S=await Pi(f,o,i);g.steps.splice(c,s-c,S);let{stepsToSave:y,moduleUpdates:E}=await et({stepLists:{steps:g.steps,beforeSteps:g.beforeSteps,afterSteps:g.afterSteps}});E.forEach(R=>{nr({content:R,schemaVersion:ue,momenticFiles:u,project:o})}),qt({relativeTestPath:a,steps:y,schemaVersion:ue,project:o}),No("copilotStepsUpdated",i,l,{steps:g.steps??[],beforeSteps:g.beforeSteps??[],afterSteps:g.afterSteps??[]})}t.addResult(JSON.stringify(m,null,2))}});function SV(r,e,t,n){if(r===void 0&&e!==void 0)throw new De("Validation Error: startIndex is required when endIndex is provided.");if(r!==void 0&&e===void 0&&t===0)throw new De("Validation Error: steps are required when startIndex is provided without an endIndex.");if(r!==void 0&&(r>n||r<0))throw new De(`Validation Error: startIndex is out of bounds for module with ${n} steps.`);if(e!==void 0&&r===void 0)throw new De("Validation Error: startIndex is required when endIndex is provided.");if(e!==void 0&&r!==void 0&&e<r)throw new De("Validation Error: endIndex must be greater than or equal to startIndex.");if(e!==void 0&&(e>n||e<0))throw new De(`Validation Error: endIndex ${e} is out of bounds for module with ${n} steps.`);let o=r??n;if((e??o)===o&&t===0)throw new De("Validation Error: Nothing to insert or delete. Provide steps or a valid delete range.")}function yV(r){return Et({schema:{name:"momentic_module_change",description:"Edit a module's steps and/or metadata. Provide startIndex (and optional endIndex) to replace or remove that range; omit endIndex to insert at startIndex; omit both indices to append new steps. Use an empty steps array with both indices to delete the range. Optionally update metadata like parameters. Omit both indices and steps to only update metadata.",inputSchema:{selector:no,steps:r.array(),startIndex:Fe.number().optional(),endIndex:Fe.number().optional(),description:Fe.string().optional().describe("New description for the module."),enabled:Fe.boolean().optional().describe("New enabled state for the module."),parameters:Fe.string().array().optional().describe("New array of parameter names, e.g., ['apiKey', 'userId']. Replaces all existing parameters, resets default parameters and parameter enums if set."),defaultParameters:Fe.record(Fe.string(),Fe.string()).optional().describe("New default values, e.g., { 'apiKey': 'default123' }. Keys must match parameters."),parameterEnums:Fe.record(Fe.string(),Fe.string().array()).optional().describe("New enum options, e.g., { 'role': ['admin', 'user'] }. Keys must match parameters.")}},handle:async(e,t,n,o)=>{let{project:i,logger:a,socket:l,testPath:c}=e,s=await Promise.all(t.steps.map(y=>Pi(y,i,a))),{entity:u,momenticFiles:d}=await xn(i,t.selector,"module"),p=await Yr(u,d,a),m=s.find(y=>!lm(y));if(m){n.addError(`Validation Error: step type ${m.type} cannot be added to a module.`);return}try{SV(t.startIndex,t.endIndex,t.steps.length,p.steps.length)}catch(y){n.addError(String(y));return}let h=p.steps;if(t.steps.length>0||t.startIndex!==void 0||t.endIndex!==void 0){h=[...p.steps];let y=t.startIndex!==void 0?t.startIndex:h.length,E=t.endIndex!==void 0?t.endIndex:y;h.splice(y,E-y,...s)}let g={moduleId:p.moduleId,name:p.name,description:t.description??p.description,enabled:t.enabled??p.enabled,parameters:t.parameters??p.parameters,defaultParameters:t.defaultParameters??p.defaultParameters,parameterEnums:t.parameterEnums??p.parameterEnums};t.parameters!==void 0&&(g.defaultParameters=t.defaultParameters??{},g.parameterEnums=t.parameterEnums??{}),await pI({moduleMetadata:g,steps:h,momenticFiles:d,project:i});let f=await Y(i);if(c){let y=await tt(ip.join(i.rootDir,c),a,f);No("copilotStepsUpdated",a,l,{steps:y.steps??[],beforeSteps:y.beforeSteps??[],afterSteps:y.afterSteps??[]})}let S={...g,stepCount:h.length};n.addResult(JSON.stringify(S,null,2))}})}function EV(r){let e=op(r);return[fV,yV(e)]}var mI=EV;import{randomUUID as ap}from"crypto";import{z as sp}from"zod";var hI=Et({schema:{name:"preview_preflight",description:"Resolve and validate locators without changing the page. If found, it will return the locator ID and HTML.",inputSchema:{description:sp.string().describe("Description of the element to preview.")}},handle:async({controller:r,logger:e,testContext:t},n,o,i)=>{o.setIncludeSnapshot();try{let a=await r.locateElement({description:n.description,disableCache:!0,skipWait:!0,logger:e,testContext:t});a.resolution.locator&&await Promise.all([r.browser.scrollIntoViewIfNeeded(a.resolution.locator),r.browser.highlight(a.resolution.locator)]),o.addResult(`Found element matching description: ${a.target.id}`),a.target.nodeOnlySerializedHtml&&o.addResult(`HTML: ${a.target.nodeOnlySerializedHtml}`);return}catch(a){o.addError(`Failed to find any element matching description: ${a}`)}}}),gI=Et({schema:{name:"preview_ensure",description:"Confirm page state.",inputSchema:{assertion:sp.string().describe("Assertion to confirm page state.")}},handle:async(r,e,t,n)=>{t.setIncludeSnapshot();let{logger:o,storage:i,controller:a,codeEvalTools:l,socket:c,orgId:s,testContext:u}=r,d={type:"PRESET_ACTION",command:{type:"AI_ASSERTION",assertion:e.assertion,id:ap()},id:ap()},p=await Jd({step:d,controller:a,storage:i,codeEvalTools:l,logger:o,socket:c,orgId:s,testContext:u});if(!p){t.addError("Assertion executed with unknown result.");return}if(p.status==="SUCCESS"){t.addResult(`Assertion is true: ${p.message}`);return}t.addError(`Assertion is false: ${p.message}`)}}),fI=Et({schema:{name:"preview_step",description:"Execute a step without adding it to the test.",inputSchema:{command:$i}},handle:async(r,e,t,n)=>{t.setIncludeSnapshot(),t.setIncludeTestContext();let{logger:o,storage:i,controller:a,codeEvalTools:l,socket:c,orgId:s,testContext:u}=r;t.setIncludeSnapshot();let d=mc(e.command),p={type:"PRESET_ACTION",command:d,id:ap()},m=await Jd({step:p,controller:a,storage:i,codeEvalTools:l,logger:o,socket:c,orgId:s,testContext:u});if(!m){t.addError("Assertion executed with unknown result.");return}if(m.status==="SUCCESS"){t.addResult(`Assertion is true: ${m.message}`);return}t.addError(`Assertion is false: ${m.message}`)}}),TV=Et({schema:{name:"preview_ai_action",description:"Execute an AI action without adding it to the test. This will dynamically generate and run steps to achieve the goal. Note this tool will update and move your test state forward, so if it fails you must rerun the test up to this step before trying again.",inputSchema:{text:sp.string().describe("The goal description for the AI action. Supports handlebars templates (ex: {{env.PASSWORD}})"),retries:sp.number().optional()}},handle:async(r,e,t,n)=>{t.setIncludeSnapshot(),t.setIncludeTestContext();let{project:o,logger:i,storage:a,controller:l,codeEvalTools:c,socket:s,orgId:u,testContext:d}=r;if(!(o.config.ai?.aiAction??!1)){t.addError("AI actions are disabled. Enable AI actions in your momentic.config.yaml by setting 'ai.aiAction: true' to use this feature.");return}let m={type:"AI_ACTION_DYNAMIC",text:e.text,id:ap(),retries:e.retries},h=await Jd({step:m,controller:l,storage:a,codeEvalTools:c,logger:i,socket:s,orgId:u,testContext:d});if(!h){t.addError("AI action executed with unknown result.");return}if(h.status==="SUCCESS"){t.addResult(`AI action completed successfully: ${h.message??"Goal achieved"}`);return}t.addError(`AI action failed: ${h.message??"Unknown error while previewing AI action"}`)}});function SI(r){return r.config.ai?.aiAction??!1?[hI,gI,fI,TV]:[hI,gI,fI]}import CV from"path";import{z as EI}from"zod";import lp from"path";import{z as $a}from"zod";var cp=r=>{throw new Error(`Unknown test section: ${r}`)},Wa=$a.enum(["setup","teardown","main"]).describe("Test section to modify: 'setup' corresponds to beforeSteps (steps that run before the test), 'teardown' corresponds to afterSteps (steps that run after the test), 'main' is synonymous with steps (the main test steps)"),bV=Et({schema:{name:"test_get",description:"Get test contents.",inputSchema:{}},handle:async(r,e,t,n)=>{t.setIncludeTest()}});function vV(r){return Et({schema:{name:"test_insert_step",description:"Insert a step or module into the test.",inputSchema:{index:$a.number(),step:r,targetSection:Wa.default("main")}},handle:async(e,t,n,o)=>{n.setIncludeTest();let{project:i,logger:a,testPath:l,socket:c}=e,s=await Y(i),u=await tt(lp.join(i.rootDir,l),a,s),d=await Pi(t.step,i,a);switch(t.targetSection){case"setup":if(u.beforeSteps||(u.beforeSteps=[]),t.index<0||t.index>u.beforeSteps.length)throw new Error(`Invalid index ${t.index} for inserting into ${t.targetSection} section with ${u.beforeSteps.length} steps (must be 0-${u.beforeSteps.length})`);u.beforeSteps.splice(t.index,0,d);break;case"teardown":if(u.afterSteps||(u.afterSteps=[]),t.index<0||t.index>u.afterSteps.length)throw new Error(`Invalid index ${t.index} for inserting into ${t.targetSection} section with ${u.afterSteps.length} steps (must be 0-${u.afterSteps.length})`);u.afterSteps.splice(t.index,0,d);break;case"main":if(t.index<0||t.index>u.steps.length)throw new Error(`Invalid index ${t.index} for inserting into ${t.targetSection} section with ${u.steps.length} steps (must be 0-${u.steps.length})`);u.steps.splice(t.index,0,d);break;default:return cp(t.targetSection)}let{stepsToSave:p,moduleUpdates:m}=await et({stepLists:{steps:u.steps,beforeSteps:u.beforeSteps,afterSteps:u.afterSteps}});m.forEach(h=>{nr({content:h,schemaVersion:ue,momenticFiles:s,project:i})}),qt({relativeTestPath:l,steps:p,schemaVersion:ue,project:i}),No("copilotStepsUpdated",a,c,{steps:u.steps??[],beforeSteps:u.beforeSteps??[],afterSteps:u.afterSteps??[]})}})}function AV(r){return Et({schema:{name:"test_replace_step",description:"Replace a step in the test.",inputSchema:{index:$a.number(),step:r,targetSection:Wa.default("main")}},handle:async(e,t,n,o)=>{n.setIncludeTest();let{project:i,logger:a,testPath:l,socket:c}=e,s=await Y(i),u=await tt(lp.join(i.rootDir,l),a,s),d=await Pi(t.step,i,a);switch(t.targetSection){case"setup":if(!u.beforeSteps)throw new Error(`Cannot replace step in ${t.targetSection} section: no ${t.targetSection} steps exist`);if(t.index<0||t.index>=u.beforeSteps.length)throw new Error(`Invalid index ${t.index} for ${t.targetSection} section with ${u.beforeSteps.length} steps`);u.beforeSteps.splice(t.index,1,d);break;case"teardown":if(!u.afterSteps)throw new Error(`Cannot replace step in ${t.targetSection} section: no ${t.targetSection} steps exist`);if(t.index<0||t.index>=u.afterSteps.length)throw new Error(`Invalid index ${t.index} for ${t.targetSection} section with ${u.afterSteps.length} steps`);u.afterSteps.splice(t.index,1,d);break;case"main":if(t.index<0||t.index>=u.steps.length)throw new Error(`Invalid index ${t.index} for ${t.targetSection} section with ${u.steps.length} steps`);u.steps.splice(t.index,1,d);break;default:return cp(t.targetSection)}let{stepsToSave:p,moduleUpdates:m}=await et({stepLists:{steps:u.steps,beforeSteps:u.beforeSteps,afterSteps:u.afterSteps}});m.forEach(h=>{nr({content:h,schemaVersion:ue,momenticFiles:s,project:i})}),qt({relativeTestPath:l,steps:p,schemaVersion:ue,project:i}),No("copilotStepsUpdated",a,c,{steps:u.steps??[],beforeSteps:u.beforeSteps??[],afterSteps:u.afterSteps??[]})}})}var RV=Et({schema:{name:"test_remove_step",description:"Remove a step from the test. Never use this as a means to bypass a failure",inputSchema:{index:$a.number(),targetSection:Wa.default("main")}},handle:async(r,e,t,n)=>{t.setIncludeTest();let{project:o,logger:i,testPath:a,socket:l}=r,c=await Y(o),s=await tt(lp.join(o.rootDir,a),i,c);switch(e.targetSection){case"setup":if(!s.beforeSteps)throw new Error(`Cannot remove step from ${e.targetSection} section: no ${e.targetSection} steps exist`);if(e.index<0||e.index>=s.beforeSteps.length)throw new Error(`Invalid index ${e.index} for ${e.targetSection} section with ${s.beforeSteps.length} steps`);s.beforeSteps.splice(e.index,1);break;case"teardown":if(!s.afterSteps)throw new Error(`Cannot remove step from ${e.targetSection} section: no ${e.targetSection} steps exist`);if(e.index<0||e.index>=s.afterSteps.length)throw new Error(`Invalid index ${e.index} for ${e.targetSection} section with ${s.afterSteps.length} steps`);s.afterSteps.splice(e.index,1);break;case"main":if(e.index<0||e.index>=s.steps.length)throw new Error(`Invalid index ${e.index} for ${e.targetSection} section with ${s.steps.length} steps`);s.steps.splice(e.index,1);break;default:return cp(e.targetSection)}let{stepsToSave:u,moduleUpdates:d}=await et({stepLists:{steps:s.steps,beforeSteps:s.beforeSteps,afterSteps:s.afterSteps}});d.forEach(p=>{nr({content:p,schemaVersion:ue,momenticFiles:c,project:o})}),qt({relativeTestPath:a,steps:u,schemaVersion:ue,project:o}),No("copilotStepsUpdated",i,l,{steps:s.steps??[],beforeSteps:s.beforeSteps??[],afterSteps:s.afterSteps??[]})}});function wV(r){return Et({schema:{name:"test_splice_steps",description:"Splice steps in the test. Never use this as a means to bypass a failure",inputSchema:{startIndex:$a.number(),deleteCount:$a.number(),steps:r.array(),targetSection:Wa.default("main")}},handle:async(e,t,n,o)=>{n.setIncludeTest();let{project:i,logger:a,testPath:l,socket:c}=e,s=await Y(i),u=await tt(lp.join(i.rootDir,l),a,s),d=await Promise.all(t.steps.map(h=>Pi(h,i,a)));switch(t.targetSection){case"setup":if(u.beforeSteps||(u.beforeSteps=[]),t.startIndex<0||t.startIndex>u.beforeSteps.length)throw new Error(`Invalid startIndex ${t.startIndex} for splicing ${t.targetSection} section with ${u.beforeSteps.length} steps (must be 0-${u.beforeSteps.length})`);u.beforeSteps.splice(t.startIndex,t.deleteCount,...d);break;case"teardown":if(u.afterSteps||(u.afterSteps=[]),t.startIndex<0||t.startIndex>u.afterSteps.length)throw new Error(`Invalid startIndex ${t.startIndex} for splicing ${t.targetSection} section with ${u.afterSteps.length} steps (must be 0-${u.afterSteps.length})`);u.afterSteps.splice(t.startIndex,t.deleteCount,...d);break;case"main":if(t.startIndex<0||t.startIndex>u.steps.length)throw new Error(`Invalid startIndex ${t.startIndex} for splicing ${t.targetSection} section with ${u.steps.length} steps (must be 0-${u.steps.length})`);u.steps.splice(t.startIndex,t.deleteCount,...d);break;default:return cp(t.targetSection)}let{stepsToSave:p,moduleUpdates:m}=await et({stepLists:{steps:u.steps,beforeSteps:u.beforeSteps,afterSteps:u.afterSteps}});m.forEach(h=>{nr({content:h,schemaVersion:ue,momenticFiles:s,project:i})}),qt({relativeTestPath:l,steps:p,schemaVersion:ue,project:i}),No("copilotStepsUpdated",a,c,{steps:u.steps??[],beforeSteps:u.beforeSteps??[],afterSteps:u.afterSteps??[]})}})}function yI(r){let e=op(r);return[bV,vV(e),AV(e),RV,wV(e)]}var xV=Et({schema:{name:"get_environment_variables",description:"Get the current environment variables.",inputSchema:{}},handle:async(r,e,t,n)=>{t.setIncludeTestContext()}}),_V=Et({schema:{name:"reset_session",description:"Reset the browser session. This will clear any authentication state and also navigate to the starting URL of the test.",inputSchema:{}},handle:async(r,e,t,n)=>{t.setIncludeTestContext(),t.setIncludeSnapshot(),await r.controller.browser.reset({})}}),IV=Et({schema:{name:"run_step",description:"Run the step in the test at the given startIndex. If there is no endIndex, the step at the startIndex will be executed. EndIndex is the last step that is run (end index is inclusive).",inputSchema:{fromIndex:EI.number(),toIndex:EI.number().optional(),targetSection:Wa.default("main")}},handle:async(r,e,t,n)=>{t.setIncludeTestContext(),t.setIncludeSnapshot();let{project:o,logger:i,testPath:a,storage:l,controller:c,codeEvalTools:s,socket:u,orgId:d,testContext:p}=r,m=e.fromIndex,h=e.toIndex??m,g=await Y(o),f=await tt(CV.join(o.rootDir,a),i,g),S;switch(e.targetSection){case"setup":S=f.beforeSteps??[];break;case"teardown":S=f.afterSteps??[];break;case"main":S=f.steps;break;default:return(I=>{throw new Error(`Unknown test section: ${I}`)})(e.targetSection)}if(m<0||m>=S.length){t.addError(`startIndex is out of bounds for ${e.targetSection} section with ${S.length} steps.`);return}if(h<m){t.addError("toIndex must be greater than or equal to fromIndex.");return}else if(h>=S.length){t.addError(`toIndex is out of bounds for ${e.targetSection} section with ${S.length} steps.`);return}let y=S.slice(m,h+1);if(y.length===0){t.addError("No steps were executed.");return}c.setOpen();let{results:E}=await Xf({steps:y,controller:c,storage:l,codeEvalTools:s,logger:i,socket:u,orgId:d,testContext:p});if(!E||E.length===0){t.addError("No steps were executed.");return}let R=E.at(-1);if(!R){t.addError("No steps were executed.");return}if(R.status!=="SUCCESS"){let w=m+E.length-1;t.addError(`Step at index ${w} failed: ${R.message}`);return}let A=e.targetSection==="main"?"":` in ${e.targetSection}`,C=m===h?`Step at index ${h}${A}`:`Steps ${m}-${h}${A}`;if(R.status==="SUCCESS"){t.addResult(`${C} executed successfully. Last step result: ${R.message}`),R.data&&t.addResult(`Data: ${JSON.stringify(R.data,null,2)}`);return}t.addError(`${C} failed: ${R.message}`)}}),TI=[xV,_V,IV];function bI(r){return[...mI(r),...cI,...TI,...SI(r),...yI(r),...Zd]}var OV=15e4,LV=1e5,vI=8;function NV(r){return MV({messages:r,reasoning:"before-last-message",toolCalls:[{type:"before-last-10-messages",tools:["momentic_module_get","momentic_module_recommend","get_environment_variables"]},{type:"before-last-5-messages",tools:["run_step","preview_ai_action"]},{type:"before-last-3-messages",tools:["test_get","reset_session","test_insert_step","test_splice_steps","preview_ensure","momentic_module_create"]},{type:"before-last-2-messages",tools:["observe_page","momentic_module_list","momentic_module_change","test_replace_step","test_remove_step"]},{type:"before-last-1-messages",tools:["preview_preflight","preview_step"]}],emptyMessages:"remove"})}function DV(r){return r.role==="system"||r.role==="user"}function kV(r,e){let t=[...r];for(;Ot(t)>e&&t.length>vI;){let o=t.findIndex(i=>!DV(i));if(o===-1)break;t.splice(o,1)}if(Ot(t)<=e||t.length===0)return t;let n=Math.max(0,t.length-vI);for(let o=t.length-1;o>=n;o--){let i=t[o];if(i&&i.role==="tool"&&(t.splice(o,1),Ot(t)<=e))break}return t}function UV(r,e){let t=kV(r,e);if(Ot(t)<=e)return t;let n=[...t],o=0;for(;o<n.length;){let i=n[o];if(!i||i.role==="system"){o++;continue}if(n.splice(o,1),Ot(n)<=e||o===n.length-1)break}return n}function FV(r){let e=NV(r);return Ot(e)>OV&&(e=UV(e,LV)),e}function up(r,e,t,n,o){let i=Kr(),a=xt(),l=qr(),c=ce(),s=new Ze({apiKey:i,baseUrl:l,logger:t}),u=new Lo(s,a),d=new mn({httpClient:new Lt({baseUrl:s.baseUrl,apiKey:s.apiKey,logger:t}),fakerSeed:c.config.advanced?.fakerConstantSeed?ta:void 0}),p={project:c,apiKey:i,orgId:a,baseUrl:l,sessionId:o,logger:t,storage:u,codeEvalTools:d,testPath:r,testContext:n.context,controller:n.controller,socket:n.socket},h=bI(c).reduce((S,{name:y,builder:E})=>(S[y]=E(p),S),{});return{model:Xd(o)("claude-sonnet-4-5-20250929"),stopWhen:PV(30),maxRetries:4,system:lI(c),messages:e,tools:h,prepareStep:S=>({...S,messages:FV(S.messages)})}}var NHe=new Error("timeout while waiting for mutex to become available"),DHe=new Error("mutex already locked"),BV=new Error("request for lock canceled"),zV=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())})},eS=class{constructor(e,t=BV){this._value=e,this._cancelError=t,this._queue=[],this._weightedWaiters=[]}acquire(e=1,t=0){if(e<=0)throw new Error(`invalid weight ${e}: must be positive`);return new Promise((n,o)=>{let i={resolve:n,reject:o,weight:e,priority:t},a=AI(this._queue,l=>t<=l.priority);a===-1&&e<=this._value?this._dispatchItem(i):this._queue.splice(a+1,0,i)})}runExclusive(e){return zV(this,arguments,void 0,function*(t,n=1,o=0){let[i,a]=yield this.acquire(n,o);try{return yield t(i)}finally{a()}})}waitForUnlock(e=1,t=0){if(e<=0)throw new Error(`invalid weight ${e}: must be positive`);return this._couldLockImmediately(e,t)?Promise.resolve():new Promise(n=>{this._weightedWaiters[e-1]||(this._weightedWaiters[e-1]=[]),HV(this._weightedWaiters[e-1],{resolve:n,priority:t})})}isLocked(){return this._value<=0}getValue(){return this._value}setValue(e){this._value=e,this._dispatchQueue()}release(e=1){if(e<=0)throw new Error(`invalid weight ${e}: must be positive`);this._value+=e,this._dispatchQueue()}cancel(){this._queue.forEach(e=>e.reject(this._cancelError)),this._queue=[]}_dispatchQueue(){for(this._drainUnlockWaiters();this._queue.length>0&&this._queue[0].weight<=this._value;)this._dispatchItem(this._queue.shift()),this._drainUnlockWaiters()}_dispatchItem(e){let t=this._value;this._value-=e.weight,e.resolve([t,this._newReleaser(e.weight)])}_newReleaser(e){let t=!1;return()=>{t||(t=!0,this.release(e))}}_drainUnlockWaiters(){if(this._queue.length===0)for(let e=this._value;e>0;e--){let t=this._weightedWaiters[e-1];t&&(t.forEach(n=>n.resolve()),this._weightedWaiters[e-1]=[])}else{let e=this._queue[0].priority;for(let t=this._value;t>0;t--){let n=this._weightedWaiters[t-1];if(!n)continue;let o=n.findIndex(i=>i.priority<=e);(o===-1?n:n.splice(0,o)).forEach(i=>i.resolve())}}}_couldLockImmediately(e,t){return(this._queue.length===0||this._queue[0].priority<t)&&e<=this._value}};function HV(r,e){let t=AI(r,n=>e.priority<=n.priority);r.splice(t+1,0,e)}function AI(r,e){for(let t=r.length-1;t>=0;t--)if(e(r[t]))return t;return-1}var GV=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())})},dp=class{constructor(e){this._semaphore=new eS(1,e)}acquire(){return GV(this,arguments,void 0,function*(e=0){let[,t]=yield this._semaphore.acquire(1,e);return t})}runExclusive(e,t=0){return this._semaphore.runExclusive(()=>e(),1,t)}isLocked(){return this._semaphore.isLocked()}waitForUnlock(e=0){return this._semaphore.waitForUnlock(1,e)}release(){this._semaphore.isLocked()&&this._semaphore.release()}cancel(){return this._semaphore.cancel()}};var tS=class{mutexes=new Map;activeControllers=new Map;async startOrReplace(e,t){t.throwIfAborted(),this.mutexes.has(e)||this.mutexes.set(e,new dp);let o=await this.mutexes.get(e).acquire();try{let i=this.activeControllers.get(e);i&&!i.signal.aborted&&i.abort(new Error("Superseded by newer momentic_test_edit invocation. Stop executing edit_test requests to this test and ask the user what to do next."));let a=new AbortController;return this.activeControllers.set(e,a),{signal:AbortSignal.any([t,a.signal]),release:()=>{this.activeControllers.get(e)===a&&this.activeControllers.delete(e),this.activeControllers.has(e)||this.mutexes.delete(e)}}}finally{o()}}},RI=new tS;var WV=en({schema:{name:"momentic_test_create",description:"Create a test. You must provide a name and either a baseUrl or environment or the tool will fail.",inputSchema:$m},handle:async(r,e,t,n)=>{let{project:o}=r;try{let i=await tp({project:o,input:e});t.addResult(JSON.stringify(i,null,2))}catch(i){t.addError(String(i));return}}}),qV=en({schema:{name:"momentic_test_list",description:"List tests.",inputSchema:{}},handle:async(r,e,t,n)=>{let{project:o}=r,i=await Y(o),l=Object.values(i.tests).map(c=>({id:c.id,name:c.name,description:c.description,relativePath:c.relativePath,fullFilePath:c.fullFilePath,platformSep:c.platformSep,fullPathSegments:c.fullPathSegments,relativePathSegments:c.relativePathSegments,fileName:c.fileName,lastModified:c.lastModified,createdAt:c.createdAt,type:c.type,labels:c.labels||[]}));t.addResult(JSON.stringify({tests:l},null,2))}}),KV=en({schema:{name:"momentic_test_get",description:"Get a single fully loaded test by id, exact name, or file path. Exactly one selector must be provided.",inputSchema:{selector:no}},handle:async(r,e,t,n)=>{let{project:o,logger:i}=r;try{let a=await xn(o,e.selector,"test"),l=await tt(a.entity.fullFilePath,i,a.momenticFiles);t.addResult(JSON.stringify({test:l},null,2))}catch(a){t.addError(String(a));return}}});async function YV(r,e,t){let n=Kr(),o=xt(),i=qr(),a=new Mi,l=new Ze({apiKey:n,baseUrl:i,logger:r}),c=new Lo(l,o),s=(await tt(t.fullFilePath,r,await Y(e))).advanced?.viewport??Gt,u=new Dn(e.config.ai?.agentConfig,{baseUrl:i,apiKey:n,logger:r}),d=new fo({baseUrl:i,apiKey:n,logger:r},u),p=await Ur.init({baseUrl:"about:blank",userBrowserSettings:{},enricher:d,storage:c,logger:r,contextArgs:{viewport:s,locale:oo,timezoneId:io,geolocation:ao},iconKnowledgeBase:null,callbacks:{}}),m=new Po({browser:p,generator:u,logger:r,orgId:o,options:{scratchPadId:void 0,slowMoMs:void 0,autoFollowNewTabs:!0,useMemory:e.config.ai?.useMemory,aiPageFiltering:!0},storage:c,localCodeEvalTools:new mn({httpClient:new Lt({baseUrl:i,apiKey:n,logger:r}),fakerSeed:e.config.advanced?.fakerConstantSeed?ta:void 0}),visualDiffScreenshotStorage:a}),h=new ar({baseUrl:"about:blank",testName:VV.basename(t.relativePath),currentUrl:p.url(),variablesFromEnvironment:{},envName:void 0});return{controller:m,context:h,socket:void 0}}var XV=en({schema:{name:"momentic_test_edit",description:"Edit a test.",inputSchema:{selector:no,message:$V.string().describe("A single block of natural-language instructions describing the desired edits to the test. The test can also be edited to add modules, edit modules, or create new modules inside of the test. Can only be used to modify steps (including module steps) inside of the passed in test.")}},handle:async(r,e,t,n)=>{let{project:o,logger:i}=r,a=n?.signal;if(!a){t.addError("No response handler available: client abort signal is required for momentic_test_edit");return}let l=Kr(),c=qr(),u=await new Dn(o.config.ai?.agentConfig,{baseUrl:c,apiKey:l,logger:i}).getLintMcpCopilotMessageResult({message:e.message},{logger:i});if(u.category!=="NONE"){t.addError(`${u.thoughts}
|
|
4377
|
+
`)}],isError:this._isError}}};var Et=r=>({builder:Yd(r,t=>new np(t.controller.browser,t.testContext,t.project,t.logger,t.testPath)).builder,name:r.schema.name});var mV=Et({schema:{name:"observe_page",description:"Observe the current page's accessibility snapshot.",inputSchema:{}},handle:async(r,e,t,n)=>{t.setIncludeSnapshot()}}),cI=[mV];import ip from"path";import{z as Fe}from"zod";function No(r,e,t,...n){t?.emit(r,...n),e.info({event:r,args:n},"Emitting copilot event")}import hV from"fs";import Va from"path";function uI(r){let e=r.subDir?Va.join(r.project.rootDir,r.subDir):r.project.rootDir,t=`${Oe(r.name)}.module.yaml`,n=Va.join(e,t),o=Va.relative(r.project.rootDir,n),i=hV.statSync(n);return{type:pe.MODULE,name:r.name,id:r.moduleId,description:r.description??void 0,relativePath:o,fullFilePath:n,platformSep:Va.sep,fullPathSegments:n.split(Va.sep),relativePathSegments:o.split(Va.sep),fileName:t,lastModified:i.mtime,createdAt:i.birthtime}}import{randomUUID as Zf}from"crypto";import{z as dI}from"zod";var gV=["AI_EXTRACT","JAVASCRIPT"];function op(r){let e=r.config.ai?.aiAction??!1,t=e?"The step types that can be ingested for a test change. The PRESET_ACTION's action can be seen as a single step command. The MODULE is a module step to use. The AI_ACTION_DYNAMIC is an AI action that will dynamically generate up to 15 steps to achieve a goal.":"The step types that can be ingested for a test change. The PRESET_ACTION's action can be seen as a single step command. The MODULE is a module step to use.";return e?dI.discriminatedUnion("type",[dm,pm,By]).describe(t):dI.discriminatedUnion("type",[dm,pm]).describe(t)}async function Pi(r,e,t){switch(r.type){case"PRESET_ACTION":{let n=mc(r.action),o=r.envKey&&gV.includes(n.type)?r.envKey:void 0;return{type:"PRESET_ACTION",command:n,id:Zf(),envKey:o}}case"MODULE":{let{selector:n,inputs:o}=r.module,{entity:i,momenticFiles:a}=await xn(e,n,"module"),l=await Yr(i,a,t);zy(o,l);let s=Object.keys(o??{}).length>0?o??{}:(l.parameters?.length??0)>0?{}:void 0,u={id:Zf(),inputs:s};return{...l,...u,type:"RESOLVED_MODULE"}}case"AI_ACTION_DYNAMIC":{if(!(e.config.ai?.aiAction??!1))throw new Error("AI actions are disabled. Enable AI actions in your momentic.config.yaml by setting 'ai.aiAction: true' to use this feature.");return{type:"AI_ACTION_DYNAMIC",text:r.text,id:Zf()}}default:return(o=>{throw new Error("You missed a case in the switch above")})(r)}}async function pI({moduleMetadata:r,steps:e,momenticFiles:t,project:n}){let{stepsToSave:o}=await et({stepLists:{steps:e}});nr({content:{...r,steps:o.steps},schemaVersion:ue,momenticFiles:t,project:n})}var fV=Et({schema:{name:"momentic_module_create",description:"Create a module. If startIndex is provided, the steps will be extracted from the current test, a module will be created with those steps, and the test will be updated to reference the new module. If no startIndex is provided, an unreferenced module will be created. Automatically splices and repairs the test to reference the new module.",inputSchema:{name:Fe.string(),description:Fe.string(),enabled:Fe.boolean().default(!0),parameters:Fe.string().array().optional().describe("Array of parameter names for the module, e.g., ['apiKey', 'userId']."),defaultParameters:Fe.record(Fe.string(),Fe.string()).optional().describe("Default values for parameters, e.g., { 'apiKey': 'default123' }. Keys must match parameters."),parameterEnums:Fe.record(Fe.string(),Fe.string().array()).optional().describe("Enum options for parameters, e.g., { 'role': ['admin', 'user'] }. Keys must match parameters."),moduleInputs:Fe.record(Fe.string(),Fe.string()).optional().describe("Input parameters to pass to the new module when it's inserted into the test. Keys must match the module's defined parameters. Only relevant if startIndex is provided."),subDir:Fe.string().optional().describe("sub directory to create the module in. If not provided, the module will be created in the project's root directory."),startIndex:Fe.number().optional().describe("Start index of steps to extract from the current test (0-based)."),endIndex:Fe.number().optional().describe("End index of steps to extract from the current test (exclusive). If not provided, extracts just the startIndex.")}},handle:async(r,e,t,n)=>{let{project:o,logger:i,testPath:a,socket:l}=r,c=e.startIndex??0,s=e.endIndex??c+1,u=await Y(o);if(Object.values(u.modules).find(g=>g.name===e.name))throw new De(`A module with the name "${e.name}" already exists. Please use a different name.`);if(e.parameters!==void 0){let g=e.defaultParameters?Object.keys(e.defaultParameters):[],f=e.parameterEnums?Object.keys(e.parameterEnums):[],y=new Set([...g,...f]);for(let S of y)if(!e.parameters.includes(S))throw new De(`Default parameter "${S}" is not defined in parameters array. Available parameters: ${e.parameters.join(", ")}`)}let p=[];if(e.startIndex!==void 0){if(!a)throw new De("testPath is required when extracting steps from the current test.");let g=await tt(ip.join(o.rootDir,a),i,u);if(c<0||c>=g.steps.length)throw new De(`startIndex ${c} is out of bounds. Test has ${g.steps.length} steps.`);if(s<=c||s>g.steps.length)throw new De(`endIndex ${s} is out of bounds. Must be between ${c+1} and ${g.steps.length}.`);p=g.steps.slice(c,s);for(let f of p)if(f.type==="RESOLVED_MODULE")throw new De("Modules cannot be nested. Please select steps that do not include module references.")}let m=await wu({name:e.name,description:e.description??"",enabled:e.enabled??!0,steps:p,folder:e.subDir?ip.join(o.rootDir,e.subDir):o.rootDir,project:o}),h=uI({project:o,name:e.name,moduleId:m.moduleId,subDir:e.subDir,description:m.description??void 0});if(u.modules[m.moduleId]=h,e.parameters!==void 0||e.defaultParameters!==void 0||e.parameterEnums!==void 0){let g={moduleId:m.moduleId,name:e.name,description:e.description??m.description,enabled:e.enabled??m.enabled,parameters:e.parameters??[],defaultParameters:e.defaultParameters,parameterEnums:e.parameterEnums};await pI({moduleMetadata:g,steps:p,momenticFiles:u,project:o}),m={...m,name:e.name,description:e.description??m.description,enabled:e.enabled??m.enabled,parameters:e.parameters??[],defaultParameters:e.defaultParameters,parameterEnums:e.parameterEnums}}if(e.startIndex!==void 0){let g=await tt(ip.join(o.rootDir,a),i,u),f={type:"MODULE",module:{selector:{id:m.moduleId},inputs:e.moduleInputs??{}}},y=await Pi(f,o,i);g.steps.splice(c,s-c,y);let{stepsToSave:S,moduleUpdates:E}=await et({stepLists:{steps:g.steps,beforeSteps:g.beforeSteps,afterSteps:g.afterSteps}});E.forEach(R=>{nr({content:R,schemaVersion:ue,momenticFiles:u,project:o})}),qt({relativeTestPath:a,steps:S,schemaVersion:ue,project:o}),No("copilotStepsUpdated",i,l,{steps:g.steps??[],beforeSteps:g.beforeSteps??[],afterSteps:g.afterSteps??[]})}t.addResult(JSON.stringify(m,null,2))}});function SV(r,e,t,n){if(r===void 0&&e!==void 0)throw new De("Validation Error: startIndex is required when endIndex is provided.");if(r!==void 0&&e===void 0&&t===0)throw new De("Validation Error: steps are required when startIndex is provided without an endIndex.");if(r!==void 0&&(r>n||r<0))throw new De(`Validation Error: startIndex is out of bounds for module with ${n} steps.`);if(e!==void 0&&r===void 0)throw new De("Validation Error: startIndex is required when endIndex is provided.");if(e!==void 0&&r!==void 0&&e<r)throw new De("Validation Error: endIndex must be greater than or equal to startIndex.");if(e!==void 0&&(e>n||e<0))throw new De(`Validation Error: endIndex ${e} is out of bounds for module with ${n} steps.`);let o=r??n;if((e??o)===o&&t===0)throw new De("Validation Error: Nothing to insert or delete. Provide steps or a valid delete range.")}function yV(r){return Et({schema:{name:"momentic_module_change",description:"Edit a module's steps and/or metadata. Provide startIndex (and optional endIndex) to replace or remove that range; omit endIndex to insert at startIndex; omit both indices to append new steps. Use an empty steps array with both indices to delete the range. Optionally update metadata like parameters. Omit both indices and steps to only update metadata.",inputSchema:{selector:no,steps:r.array(),startIndex:Fe.number().optional(),endIndex:Fe.number().optional(),description:Fe.string().optional().describe("New description for the module."),enabled:Fe.boolean().optional().describe("New enabled state for the module."),parameters:Fe.string().array().optional().describe("New array of parameter names, e.g., ['apiKey', 'userId']. Replaces all existing parameters, resets default parameters and parameter enums if set."),defaultParameters:Fe.record(Fe.string(),Fe.string()).optional().describe("New default values, e.g., { 'apiKey': 'default123' }. Keys must match parameters."),parameterEnums:Fe.record(Fe.string(),Fe.string().array()).optional().describe("New enum options, e.g., { 'role': ['admin', 'user'] }. Keys must match parameters.")}},handle:async(e,t,n,o)=>{let{project:i,logger:a,socket:l,testPath:c}=e,s=await Promise.all(t.steps.map(S=>Pi(S,i,a))),{entity:u,momenticFiles:d}=await xn(i,t.selector,"module"),p=await Yr(u,d,a),m=s.find(S=>!lm(S));if(m){n.addError(`Validation Error: step type ${m.type} cannot be added to a module.`);return}try{SV(t.startIndex,t.endIndex,t.steps.length,p.steps.length)}catch(S){n.addError(String(S));return}let h=p.steps;if(t.steps.length>0||t.startIndex!==void 0||t.endIndex!==void 0){h=[...p.steps];let S=t.startIndex!==void 0?t.startIndex:h.length,E=t.endIndex!==void 0?t.endIndex:S;h.splice(S,E-S,...s)}let g={moduleId:p.moduleId,name:p.name,description:t.description??p.description,enabled:t.enabled??p.enabled,parameters:t.parameters??p.parameters,defaultParameters:t.defaultParameters??p.defaultParameters,parameterEnums:t.parameterEnums??p.parameterEnums};t.parameters!==void 0&&(g.defaultParameters=t.defaultParameters??{},g.parameterEnums=t.parameterEnums??{}),await pI({moduleMetadata:g,steps:h,momenticFiles:d,project:i});let f=await Y(i);if(c){let S=await tt(ip.join(i.rootDir,c),a,f);No("copilotStepsUpdated",a,l,{steps:S.steps??[],beforeSteps:S.beforeSteps??[],afterSteps:S.afterSteps??[]})}let y={...g,stepCount:h.length};n.addResult(JSON.stringify(y,null,2))}})}function EV(r){let e=op(r);return[fV,yV(e)]}var mI=EV;import{randomUUID as ap}from"crypto";import{z as sp}from"zod";var hI=Et({schema:{name:"preview_preflight",description:"Resolve and validate locators without changing the page. If found, it will return the locator ID and HTML.",inputSchema:{description:sp.string().describe("Description of the element to preview.")}},handle:async({controller:r,logger:e,testContext:t},n,o,i)=>{o.setIncludeSnapshot();try{let a=await r.locateElement({description:n.description,disableCache:!0,skipWait:!0,logger:e,testContext:t});a.resolution.locator&&await Promise.all([r.browser.scrollIntoViewIfNeeded(a.resolution.locator),r.browser.highlight(a.resolution.locator)]),o.addResult(`Found element matching description: ${a.target.id}`),a.target.nodeOnlySerializedHtml&&o.addResult(`HTML: ${a.target.nodeOnlySerializedHtml}`);return}catch(a){o.addError(`Failed to find any element matching description: ${a}`)}}}),gI=Et({schema:{name:"preview_ensure",description:"Confirm page state.",inputSchema:{assertion:sp.string().describe("Assertion to confirm page state.")}},handle:async(r,e,t,n)=>{t.setIncludeSnapshot();let{logger:o,storage:i,controller:a,codeEvalTools:l,socket:c,orgId:s,testContext:u}=r,d={type:"PRESET_ACTION",command:{type:"AI_ASSERTION",assertion:e.assertion,id:ap()},id:ap()},p=await Jd({step:d,controller:a,storage:i,codeEvalTools:l,logger:o,socket:c,orgId:s,testContext:u});if(!p){t.addError("Assertion executed with unknown result.");return}if(p.status==="SUCCESS"){t.addResult(`Assertion is true: ${p.message}`);return}t.addError(`Assertion is false: ${p.message}`)}}),fI=Et({schema:{name:"preview_step",description:"Execute a step without adding it to the test.",inputSchema:{command:$i}},handle:async(r,e,t,n)=>{t.setIncludeSnapshot(),t.setIncludeTestContext();let{logger:o,storage:i,controller:a,codeEvalTools:l,socket:c,orgId:s,testContext:u}=r;t.setIncludeSnapshot();let d=mc(e.command),p={type:"PRESET_ACTION",command:d,id:ap()},m=await Jd({step:p,controller:a,storage:i,codeEvalTools:l,logger:o,socket:c,orgId:s,testContext:u});if(!m){t.addError("Assertion executed with unknown result.");return}if(m.status==="SUCCESS"){t.addResult(`Assertion is true: ${m.message}`);return}t.addError(`Assertion is false: ${m.message}`)}}),TV=Et({schema:{name:"preview_ai_action",description:"Execute an AI action without adding it to the test. This will dynamically generate and run steps to achieve the goal. Note this tool will update and move your test state forward, so if it fails you must rerun the test up to this step before trying again.",inputSchema:{text:sp.string().describe("The goal description for the AI action. Supports handlebars templates (ex: {{env.PASSWORD}})"),retries:sp.number().optional()}},handle:async(r,e,t,n)=>{t.setIncludeSnapshot(),t.setIncludeTestContext();let{project:o,logger:i,storage:a,controller:l,codeEvalTools:c,socket:s,orgId:u,testContext:d}=r;if(!(o.config.ai?.aiAction??!1)){t.addError("AI actions are disabled. Enable AI actions in your momentic.config.yaml by setting 'ai.aiAction: true' to use this feature.");return}let m={type:"AI_ACTION_DYNAMIC",text:e.text,id:ap(),retries:e.retries},h=await Jd({step:m,controller:l,storage:a,codeEvalTools:c,logger:i,socket:s,orgId:u,testContext:d});if(!h){t.addError("AI action executed with unknown result.");return}if(h.status==="SUCCESS"){t.addResult(`AI action completed successfully: ${h.message??"Goal achieved"}`);return}t.addError(`AI action failed: ${h.message??"Unknown error while previewing AI action"}`)}});function SI(r){return r.config.ai?.aiAction??!1?[hI,gI,fI,TV]:[hI,gI,fI]}import CV from"path";import{z as EI}from"zod";import lp from"path";import{z as $a}from"zod";var cp=r=>{throw new Error(`Unknown test section: ${r}`)},Wa=$a.enum(["setup","teardown","main"]).describe("Test section to modify: 'setup' corresponds to beforeSteps (steps that run before the test), 'teardown' corresponds to afterSteps (steps that run after the test), 'main' is synonymous with steps (the main test steps)"),bV=Et({schema:{name:"test_get",description:"Get test contents.",inputSchema:{}},handle:async(r,e,t,n)=>{t.setIncludeTest()}});function vV(r){return Et({schema:{name:"test_insert_step",description:"Insert a step or module into the test.",inputSchema:{index:$a.number(),step:r,targetSection:Wa.default("main")}},handle:async(e,t,n,o)=>{n.setIncludeTest();let{project:i,logger:a,testPath:l,socket:c}=e,s=await Y(i),u=await tt(lp.join(i.rootDir,l),a,s),d=await Pi(t.step,i,a);switch(t.targetSection){case"setup":if(u.beforeSteps||(u.beforeSteps=[]),t.index<0||t.index>u.beforeSteps.length)throw new Error(`Invalid index ${t.index} for inserting into ${t.targetSection} section with ${u.beforeSteps.length} steps (must be 0-${u.beforeSteps.length})`);u.beforeSteps.splice(t.index,0,d);break;case"teardown":if(u.afterSteps||(u.afterSteps=[]),t.index<0||t.index>u.afterSteps.length)throw new Error(`Invalid index ${t.index} for inserting into ${t.targetSection} section with ${u.afterSteps.length} steps (must be 0-${u.afterSteps.length})`);u.afterSteps.splice(t.index,0,d);break;case"main":if(t.index<0||t.index>u.steps.length)throw new Error(`Invalid index ${t.index} for inserting into ${t.targetSection} section with ${u.steps.length} steps (must be 0-${u.steps.length})`);u.steps.splice(t.index,0,d);break;default:return cp(t.targetSection)}let{stepsToSave:p,moduleUpdates:m}=await et({stepLists:{steps:u.steps,beforeSteps:u.beforeSteps,afterSteps:u.afterSteps}});m.forEach(h=>{nr({content:h,schemaVersion:ue,momenticFiles:s,project:i})}),qt({relativeTestPath:l,steps:p,schemaVersion:ue,project:i}),No("copilotStepsUpdated",a,c,{steps:u.steps??[],beforeSteps:u.beforeSteps??[],afterSteps:u.afterSteps??[]})}})}function AV(r){return Et({schema:{name:"test_replace_step",description:"Replace a step in the test.",inputSchema:{index:$a.number(),step:r,targetSection:Wa.default("main")}},handle:async(e,t,n,o)=>{n.setIncludeTest();let{project:i,logger:a,testPath:l,socket:c}=e,s=await Y(i),u=await tt(lp.join(i.rootDir,l),a,s),d=await Pi(t.step,i,a);switch(t.targetSection){case"setup":if(!u.beforeSteps)throw new Error(`Cannot replace step in ${t.targetSection} section: no ${t.targetSection} steps exist`);if(t.index<0||t.index>=u.beforeSteps.length)throw new Error(`Invalid index ${t.index} for ${t.targetSection} section with ${u.beforeSteps.length} steps`);u.beforeSteps.splice(t.index,1,d);break;case"teardown":if(!u.afterSteps)throw new Error(`Cannot replace step in ${t.targetSection} section: no ${t.targetSection} steps exist`);if(t.index<0||t.index>=u.afterSteps.length)throw new Error(`Invalid index ${t.index} for ${t.targetSection} section with ${u.afterSteps.length} steps`);u.afterSteps.splice(t.index,1,d);break;case"main":if(t.index<0||t.index>=u.steps.length)throw new Error(`Invalid index ${t.index} for ${t.targetSection} section with ${u.steps.length} steps`);u.steps.splice(t.index,1,d);break;default:return cp(t.targetSection)}let{stepsToSave:p,moduleUpdates:m}=await et({stepLists:{steps:u.steps,beforeSteps:u.beforeSteps,afterSteps:u.afterSteps}});m.forEach(h=>{nr({content:h,schemaVersion:ue,momenticFiles:s,project:i})}),qt({relativeTestPath:l,steps:p,schemaVersion:ue,project:i}),No("copilotStepsUpdated",a,c,{steps:u.steps??[],beforeSteps:u.beforeSteps??[],afterSteps:u.afterSteps??[]})}})}var RV=Et({schema:{name:"test_remove_step",description:"Remove a step from the test. Never use this as a means to bypass a failure",inputSchema:{index:$a.number(),targetSection:Wa.default("main")}},handle:async(r,e,t,n)=>{t.setIncludeTest();let{project:o,logger:i,testPath:a,socket:l}=r,c=await Y(o),s=await tt(lp.join(o.rootDir,a),i,c);switch(e.targetSection){case"setup":if(!s.beforeSteps)throw new Error(`Cannot remove step from ${e.targetSection} section: no ${e.targetSection} steps exist`);if(e.index<0||e.index>=s.beforeSteps.length)throw new Error(`Invalid index ${e.index} for ${e.targetSection} section with ${s.beforeSteps.length} steps`);s.beforeSteps.splice(e.index,1);break;case"teardown":if(!s.afterSteps)throw new Error(`Cannot remove step from ${e.targetSection} section: no ${e.targetSection} steps exist`);if(e.index<0||e.index>=s.afterSteps.length)throw new Error(`Invalid index ${e.index} for ${e.targetSection} section with ${s.afterSteps.length} steps`);s.afterSteps.splice(e.index,1);break;case"main":if(e.index<0||e.index>=s.steps.length)throw new Error(`Invalid index ${e.index} for ${e.targetSection} section with ${s.steps.length} steps`);s.steps.splice(e.index,1);break;default:return cp(e.targetSection)}let{stepsToSave:u,moduleUpdates:d}=await et({stepLists:{steps:s.steps,beforeSteps:s.beforeSteps,afterSteps:s.afterSteps}});d.forEach(p=>{nr({content:p,schemaVersion:ue,momenticFiles:c,project:o})}),qt({relativeTestPath:a,steps:u,schemaVersion:ue,project:o}),No("copilotStepsUpdated",i,l,{steps:s.steps??[],beforeSteps:s.beforeSteps??[],afterSteps:s.afterSteps??[]})}});function wV(r){return Et({schema:{name:"test_splice_steps",description:"Splice steps in the test. Never use this as a means to bypass a failure",inputSchema:{startIndex:$a.number(),deleteCount:$a.number(),steps:r.array(),targetSection:Wa.default("main")}},handle:async(e,t,n,o)=>{n.setIncludeTest();let{project:i,logger:a,testPath:l,socket:c}=e,s=await Y(i),u=await tt(lp.join(i.rootDir,l),a,s),d=await Promise.all(t.steps.map(h=>Pi(h,i,a)));switch(t.targetSection){case"setup":if(u.beforeSteps||(u.beforeSteps=[]),t.startIndex<0||t.startIndex>u.beforeSteps.length)throw new Error(`Invalid startIndex ${t.startIndex} for splicing ${t.targetSection} section with ${u.beforeSteps.length} steps (must be 0-${u.beforeSteps.length})`);u.beforeSteps.splice(t.startIndex,t.deleteCount,...d);break;case"teardown":if(u.afterSteps||(u.afterSteps=[]),t.startIndex<0||t.startIndex>u.afterSteps.length)throw new Error(`Invalid startIndex ${t.startIndex} for splicing ${t.targetSection} section with ${u.afterSteps.length} steps (must be 0-${u.afterSteps.length})`);u.afterSteps.splice(t.startIndex,t.deleteCount,...d);break;case"main":if(t.startIndex<0||t.startIndex>u.steps.length)throw new Error(`Invalid startIndex ${t.startIndex} for splicing ${t.targetSection} section with ${u.steps.length} steps (must be 0-${u.steps.length})`);u.steps.splice(t.startIndex,t.deleteCount,...d);break;default:return cp(t.targetSection)}let{stepsToSave:p,moduleUpdates:m}=await et({stepLists:{steps:u.steps,beforeSteps:u.beforeSteps,afterSteps:u.afterSteps}});m.forEach(h=>{nr({content:h,schemaVersion:ue,momenticFiles:s,project:i})}),qt({relativeTestPath:l,steps:p,schemaVersion:ue,project:i}),No("copilotStepsUpdated",a,c,{steps:u.steps??[],beforeSteps:u.beforeSteps??[],afterSteps:u.afterSteps??[]})}})}function yI(r){let e=op(r);return[bV,vV(e),AV(e),RV,wV(e)]}var xV=Et({schema:{name:"get_environment_variables",description:"Get the current environment variables.",inputSchema:{}},handle:async(r,e,t,n)=>{t.setIncludeTestContext()}}),_V=Et({schema:{name:"reset_session",description:"Reset the browser session. This will clear any authentication state and also navigate to the starting URL of the test.",inputSchema:{}},handle:async(r,e,t,n)=>{t.setIncludeTestContext(),t.setIncludeSnapshot(),await r.controller.browser.reset({})}}),IV=Et({schema:{name:"run_step",description:"Run the step in the test at the given startIndex. If there is no endIndex, the step at the startIndex will be executed. EndIndex is the last step that is run (end index is inclusive).",inputSchema:{fromIndex:EI.number(),toIndex:EI.number().optional(),targetSection:Wa.default("main")}},handle:async(r,e,t,n)=>{t.setIncludeTestContext(),t.setIncludeSnapshot();let{project:o,logger:i,testPath:a,storage:l,controller:c,codeEvalTools:s,socket:u,orgId:d,testContext:p}=r,m=e.fromIndex,h=e.toIndex??m,g=await Y(o),f=await tt(CV.join(o.rootDir,a),i,g),y;switch(e.targetSection){case"setup":y=f.beforeSteps??[];break;case"teardown":y=f.afterSteps??[];break;case"main":y=f.steps;break;default:return(I=>{throw new Error(`Unknown test section: ${I}`)})(e.targetSection)}if(m<0||m>=y.length){t.addError(`startIndex is out of bounds for ${e.targetSection} section with ${y.length} steps.`);return}if(h<m){t.addError("toIndex must be greater than or equal to fromIndex.");return}else if(h>=y.length){t.addError(`toIndex is out of bounds for ${e.targetSection} section with ${y.length} steps.`);return}let S=y.slice(m,h+1);if(S.length===0){t.addError("No steps were executed.");return}c.setOpen();let{results:E}=await Xf({steps:S,controller:c,storage:l,codeEvalTools:s,logger:i,socket:u,orgId:d,testContext:p});if(!E||E.length===0){t.addError("No steps were executed.");return}let R=E.at(-1);if(!R){t.addError("No steps were executed.");return}if(R.status!=="SUCCESS"){let w=m+E.length-1;t.addError(`Step at index ${w} failed: ${R.message}`);return}let A=e.targetSection==="main"?"":` in ${e.targetSection}`,C=m===h?`Step at index ${h}${A}`:`Steps ${m}-${h}${A}`;if(R.status==="SUCCESS"){t.addResult(`${C} executed successfully. Last step result: ${R.message}`),R.data&&t.addResult(`Data: ${JSON.stringify(R.data,null,2)}`);return}t.addError(`${C} failed: ${R.message}`)}}),TI=[xV,_V,IV];function bI(r){return[...mI(r),...cI,...TI,...SI(r),...yI(r),...Zd]}var OV=15e4,LV=1e5,vI=8;function NV(r){return MV({messages:r,reasoning:"before-last-message",toolCalls:[{type:"before-last-10-messages",tools:["momentic_module_get","momentic_module_recommend","get_environment_variables"]},{type:"before-last-5-messages",tools:["run_step","preview_ai_action"]},{type:"before-last-3-messages",tools:["test_get","reset_session","test_insert_step","test_splice_steps","preview_ensure","momentic_module_create"]},{type:"before-last-2-messages",tools:["observe_page","momentic_module_list","momentic_module_change","test_replace_step","test_remove_step"]},{type:"before-last-1-messages",tools:["preview_preflight","preview_step"]}],emptyMessages:"remove"})}function DV(r){return r.role==="system"||r.role==="user"}function kV(r,e){let t=[...r];for(;Ot(t)>e&&t.length>vI;){let o=t.findIndex(i=>!DV(i));if(o===-1)break;t.splice(o,1)}if(Ot(t)<=e||t.length===0)return t;let n=Math.max(0,t.length-vI);for(let o=t.length-1;o>=n;o--){let i=t[o];if(i&&i.role==="tool"&&(t.splice(o,1),Ot(t)<=e))break}return t}function UV(r,e){let t=kV(r,e);if(Ot(t)<=e)return t;let n=[...t],o=0;for(;o<n.length;){let i=n[o];if(!i||i.role==="system"){o++;continue}if(n.splice(o,1),Ot(n)<=e||o===n.length-1)break}return n}function FV(r){let e=NV(r);return Ot(e)>OV&&(e=UV(e,LV)),e}function up(r,e,t,n,o){let i=Kr(),a=xt(),l=qr(),c=ce(),s=new Ze({apiKey:i,baseUrl:l,logger:t}),u=new Lo(s,a),d=new mn({httpClient:new Lt({baseUrl:s.baseUrl,apiKey:s.apiKey,logger:t}),fakerSeed:c.config.advanced?.fakerConstantSeed?ta:void 0}),p={project:c,apiKey:i,orgId:a,baseUrl:l,sessionId:o,logger:t,storage:u,codeEvalTools:d,testPath:r,testContext:n.context,controller:n.controller,socket:n.socket},h=bI(c).reduce((y,{name:S,builder:E})=>(y[S]=E(p),y),{});return{model:Xd(o)("claude-sonnet-4-5-20250929"),stopWhen:PV(30),maxRetries:4,system:lI(c),messages:e,tools:h,prepareStep:y=>({...y,messages:FV(y.messages)})}}var NHe=new Error("timeout while waiting for mutex to become available"),DHe=new Error("mutex already locked"),BV=new Error("request for lock canceled"),zV=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())})},eS=class{constructor(e,t=BV){this._value=e,this._cancelError=t,this._queue=[],this._weightedWaiters=[]}acquire(e=1,t=0){if(e<=0)throw new Error(`invalid weight ${e}: must be positive`);return new Promise((n,o)=>{let i={resolve:n,reject:o,weight:e,priority:t},a=AI(this._queue,l=>t<=l.priority);a===-1&&e<=this._value?this._dispatchItem(i):this._queue.splice(a+1,0,i)})}runExclusive(e){return zV(this,arguments,void 0,function*(t,n=1,o=0){let[i,a]=yield this.acquire(n,o);try{return yield t(i)}finally{a()}})}waitForUnlock(e=1,t=0){if(e<=0)throw new Error(`invalid weight ${e}: must be positive`);return this._couldLockImmediately(e,t)?Promise.resolve():new Promise(n=>{this._weightedWaiters[e-1]||(this._weightedWaiters[e-1]=[]),HV(this._weightedWaiters[e-1],{resolve:n,priority:t})})}isLocked(){return this._value<=0}getValue(){return this._value}setValue(e){this._value=e,this._dispatchQueue()}release(e=1){if(e<=0)throw new Error(`invalid weight ${e}: must be positive`);this._value+=e,this._dispatchQueue()}cancel(){this._queue.forEach(e=>e.reject(this._cancelError)),this._queue=[]}_dispatchQueue(){for(this._drainUnlockWaiters();this._queue.length>0&&this._queue[0].weight<=this._value;)this._dispatchItem(this._queue.shift()),this._drainUnlockWaiters()}_dispatchItem(e){let t=this._value;this._value-=e.weight,e.resolve([t,this._newReleaser(e.weight)])}_newReleaser(e){let t=!1;return()=>{t||(t=!0,this.release(e))}}_drainUnlockWaiters(){if(this._queue.length===0)for(let e=this._value;e>0;e--){let t=this._weightedWaiters[e-1];t&&(t.forEach(n=>n.resolve()),this._weightedWaiters[e-1]=[])}else{let e=this._queue[0].priority;for(let t=this._value;t>0;t--){let n=this._weightedWaiters[t-1];if(!n)continue;let o=n.findIndex(i=>i.priority<=e);(o===-1?n:n.splice(0,o)).forEach(i=>i.resolve())}}}_couldLockImmediately(e,t){return(this._queue.length===0||this._queue[0].priority<t)&&e<=this._value}};function HV(r,e){let t=AI(r,n=>e.priority<=n.priority);r.splice(t+1,0,e)}function AI(r,e){for(let t=r.length-1;t>=0;t--)if(e(r[t]))return t;return-1}var GV=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())})},dp=class{constructor(e){this._semaphore=new eS(1,e)}acquire(){return GV(this,arguments,void 0,function*(e=0){let[,t]=yield this._semaphore.acquire(1,e);return t})}runExclusive(e,t=0){return this._semaphore.runExclusive(()=>e(),1,t)}isLocked(){return this._semaphore.isLocked()}waitForUnlock(e=0){return this._semaphore.waitForUnlock(1,e)}release(){this._semaphore.isLocked()&&this._semaphore.release()}cancel(){return this._semaphore.cancel()}};var tS=class{mutexes=new Map;activeControllers=new Map;async startOrReplace(e,t){t.throwIfAborted(),this.mutexes.has(e)||this.mutexes.set(e,new dp);let o=await this.mutexes.get(e).acquire();try{let i=this.activeControllers.get(e);i&&!i.signal.aborted&&i.abort(new Error("Superseded by newer momentic_test_edit invocation. Stop executing edit_test requests to this test and ask the user what to do next."));let a=new AbortController;return this.activeControllers.set(e,a),{signal:AbortSignal.any([t,a.signal]),release:()=>{this.activeControllers.get(e)===a&&this.activeControllers.delete(e),this.activeControllers.has(e)||this.mutexes.delete(e)}}}finally{o()}}},RI=new tS;var WV=en({schema:{name:"momentic_test_create",description:"Create a test. You must provide a name and either a baseUrl or environment or the tool will fail.",inputSchema:$m},handle:async(r,e,t,n)=>{let{project:o}=r;try{let i=await tp({project:o,input:e});t.addResult(JSON.stringify(i,null,2))}catch(i){t.addError(String(i));return}}}),qV=en({schema:{name:"momentic_test_list",description:"List tests.",inputSchema:{}},handle:async(r,e,t,n)=>{let{project:o}=r,i=await Y(o),l=Object.values(i.tests).map(c=>({id:c.id,name:c.name,description:c.description,relativePath:c.relativePath,fullFilePath:c.fullFilePath,platformSep:c.platformSep,fullPathSegments:c.fullPathSegments,relativePathSegments:c.relativePathSegments,fileName:c.fileName,lastModified:c.lastModified,createdAt:c.createdAt,type:c.type,labels:c.labels||[]}));t.addResult(JSON.stringify({tests:l},null,2))}}),KV=en({schema:{name:"momentic_test_get",description:"Get a single fully loaded test by id, exact name, or file path. Exactly one selector must be provided.",inputSchema:{selector:no}},handle:async(r,e,t,n)=>{let{project:o,logger:i}=r;try{let a=await xn(o,e.selector,"test"),l=await tt(a.entity.fullFilePath,i,a.momenticFiles);t.addResult(JSON.stringify({test:l},null,2))}catch(a){t.addError(String(a));return}}});async function YV(r,e,t){let n=Kr(),o=xt(),i=qr(),a=new Mi,l=new Ze({apiKey:n,baseUrl:i,logger:r}),c=new Lo(l,o),s=(await tt(t.fullFilePath,r,await Y(e))).advanced?.viewport??Gt,u=new Dn(e.config.ai?.agentConfig,{baseUrl:i,apiKey:n,logger:r}),d=new fo({baseUrl:i,apiKey:n,logger:r},u),p=await Ur.init({baseUrl:"about:blank",userBrowserSettings:{},enricher:d,storage:c,logger:r,contextArgs:{viewport:s,locale:oo,timezoneId:io,geolocation:ao},iconKnowledgeBase:null,callbacks:{}}),m=new Po({browser:p,generator:u,logger:r,orgId:o,options:{scratchPadId:void 0,slowMoMs:void 0,autoFollowNewTabs:!0,useMemory:e.config.ai?.useMemory,aiPageFiltering:!0},storage:c,localCodeEvalTools:new mn({httpClient:new Lt({baseUrl:i,apiKey:n,logger:r}),fakerSeed:e.config.advanced?.fakerConstantSeed?ta:void 0}),visualDiffScreenshotStorage:a}),h=new ar({baseUrl:"about:blank",testName:VV.basename(t.relativePath),currentUrl:p.url(),variablesFromEnvironment:{},envName:void 0});return{controller:m,context:h,socket:void 0}}var XV=en({schema:{name:"momentic_test_edit",description:"Edit a test.",inputSchema:{selector:no,message:$V.string().describe("A single block of natural-language instructions describing the desired edits to the test. The test can also be edited to add modules, edit modules, or create new modules inside of the test. Can only be used to modify steps (including module steps) inside of the passed in test.")}},handle:async(r,e,t,n)=>{let{project:o,logger:i}=r,a=n?.signal;if(!a){t.addError("No response handler available: client abort signal is required for momentic_test_edit");return}let l=Kr(),c=qr(),u=await new Dn(o.config.ai?.agentConfig,{baseUrl:c,apiKey:l,logger:i}).getLintMcpCopilotMessageResult({message:e.message},{logger:i});if(u.category!=="NONE"){t.addError(`${u.thoughts}
|
|
4379
4378
|
|
|
4380
|
-
Category: ${u.category}`);return}let d,p;try{({entity:d,momenticFiles:p}=await xn(o,e.selector,"test"))}catch(A){t.addError(String(A));return}let m=i.child({applicationName:"momentic-mcp-copilot",testId:d.id}),h=up(d.relativePath,[{role:"user",content:e.message}],m,await YV(m,o,d),n?.sessionId),{signal:g,release:f}=await RI.startOrReplace(d.id,a),
|
|
4381
|
-
`).map(A=>A.trim()).filter(A=>A.length>0);t.addResult(JSON.stringify({editedTest:E,messages:R},null,2))}}),wI=[qV,WV,KV,XV];var CI=[...iI,...wI,...Zd];function rS(r,e){let t=new JV({name:e.applicationName,version:e.cliVersion},{capabilities:{logging:{},tools:{}}});for(let n of CI)n.addToolToMcpServer(r,t);return t}async function xI(r,e,t,n){let o=new QV(t,e,n);return await r.connect(o),{close:async()=>{try{await r.close()}catch{}},transport:o}}var nS="mcp-session-id",n$="sessionId",qa=r$(),Bl=new Map;function _I(){let r={applicationName:"momentic-mcp-desktop-server",cliVersion:Wf??"0.0.0"},e=ce(),t=at.child({orgId:xt(),userId:ga(),...r});return{context:{project:e,logger:t},info:r}}qa.get("/sse",async(r,e)=>{let{context:t,info:n}=_I(),o=rS(t,n),{transport:i}=await xI(o,e,"/api/mcp/sse",{enableDnsRebindingProtection:!1}),a=i.sessionId,l={transport:i,close:async()=>{Bl.delete(a);try{await o.close()}catch(c){t.logger.warn({err:c},"Failed to close MCP server on SSE session cleanup")}}};Bl.set(a,l),i.onclose=()=>{let c=Bl.get(a);c&&c.close()}});qa.post("/sse",async(r,e)=>{let t=String(r.query[n$]??"");if(!t||!Bl.has(t)){e.status(400).send("Invalid or missing sessionId");return}await Bl.get(t).transport.handlePostMessage(r,e,r.body)});var II=qa,Vn={};qa.post("/",async(r,e)=>{let t=String(r.headers[nS]??"");try{if(t&&Vn[t]){await Vn[t].handleRequest(r,e,r.body);return}if(!t&&e$(r.body)){let{context:n,info:o}=_I(),i=rS(n,o),a=new ZV({sessionIdGenerator:()=>t$(),enableDnsRebindingProtection:!1,onsessioninitialized:l=>{Vn[l]=a}});a.onclose=()=>{let l=a.sessionId;l&&Vn[l]&&delete Vn[l],i.close().catch(()=>{})},await i.connect(a),await a.handleRequest(r,e,r.body);return}e.status(400).json({jsonrpc:"2.0",error:{code:-32e3,message:"Bad Request: No valid session ID provided"},id:null})}catch{e.headersSent||e.status(500).json({jsonrpc:"2.0",error:{code:-32603,message:"Internal server error"},id:null})}});qa.get("/",async(r,e)=>{let t=String(r.headers[nS]??"");if(!t||!Vn[t]){e.status(400).send("Invalid or missing session ID");return}await Vn[t].handleRequest(r,e)});qa.delete("/",async(r,e)=>{let t=String(r.headers[nS]??"");if(!t||!Vn[t]){e.status(400).send("Invalid or missing session ID");return}let n=Vn[t];try{await n.handleRequest(r,e)}catch{e.headersSent||e.status(500).send("Error processing session termination")}});import{Router as o$}from"express";var pp=o$();pp.get("/",Re(async(r,e)=>{let t=(await jh()).map(n=>({name:n.config.name,configFilePath:n.configFilePath}));e.status(200).json(t)}));pp.get("/current",Re((r,e)=>{let t=ce();if(!t){e.status(404).json({error:"No project found."});return}let n={name:t.config.name,configFilePath:t.configFilePath};e.status(200).json(n)}));pp.post("/set",Re(async(r,e)=>{let t;try{t=ET.parse(r.body)}catch(n){e.status(400).json({error:`Invalid request body: ${n}`});return}try{let n=await vt({configFilePath:t.configFilePath});Ru(n,o=>vt({configFilePath:o}))}catch(n){e.status(400).json({error:`Error setting project: ${n}`});return}e.sendStatus(204)}));var MI=pp;import{Router as i$}from"express";var PI=i$();PI.get("/",Re((r,e)=>{let n={ai:ce().config.ai};e.status(200).json(n)}));var OI=PI;import{convertToModelMessages as a$,streamText as s$}from"ai";import{Router as l$}from"express";import LI from"fs";import Hl from"path";import{v4 as c$}from"uuid";import u$ from"yaml";var zl=new Uu({platform:"local_app"},{flushAt:1,flushInterval:0});var Do=l$();Do.post("/",Re(async(r,e)=>{let t;try{t=mT.parse(r.body)}catch(n){e.status(400).json({error:`Invalid request body: ${n}`});return}try{let n=ce(),o=await tp({project:n,input:t});zl.track({type:"test_editor:test_create"}),e.status(201).json(o)}catch(n){if(n instanceof De){e.status(400).json({error:n.message});return}throw n}}));Do.get("/:testPath",Re(async(r,e)=>{let{testPath:t}=r.params;if(!t){e.status(400).json({error:"Missing testPath in url path."});return}let n=ce(),o=await Y(n),i;try{i=await tt(Hl.join(n.rootDir,t),at,o),e.status(200).json(i)}catch(a){e.status(400).send({error:a.message});return}(async()=>{try{let{stepsToSave:a,moduleUpdates:l}=await et({stepLists:{steps:i.steps,beforeSteps:i.beforeSteps,afterSteps:i.afterSteps}});l.forEach(c=>{nr({content:c,schemaVersion:ue,momenticFiles:o,project:n})}),qt({relativeTestPath:t,steps:a,schemaVersion:ue,project:n})}catch(a){at.error({err:a},"Failed to save migrated test to disk after initial fetch")}})()}));Do.patch("/:testPath/metadata",Re(async(r,e)=>{if(!r.params.testPath){e.status(400).json({error:"Missing testPath in url path."});return}let t;try{t=pT.parse(r.body)}catch(i){e.status(400).json({error:`Invalid request body: ${i}`});return}let o={message:"ok",newRelativeTestPath:Dh(r.params.testPath,t,ce()).newRelativeTestPath};e.status(200).json(o)}));Do.patch("/:testPath",Re(async(r,e)=>{let{testPath:t}=r.params;if(!t){e.status(400).json({error:"Missing testPath in url path."});return}let n;try{n=dT.parse(r.body)}catch(m){at.warn({err:m},"Invalid save request"),e.status(400).json({error:`Invalid request body: ${m}`});return}at.info({testPath:t},"Save received");let o=ce(),i=await Y(o),a;try{a=rl(t,o)}catch(m){e.status(400).json({error:`Existing test file on disk is invalid: ${m}`});return}let{stepsToSave:l,moduleUpdates:c,cachesToSave:s}=await et({stepLists:n.stepLists,cacheCreationParams:{testId:a.id,orgId:xt()}}),u=new Ze({apiKey:Kr(),baseUrl:qr(),logger:at}),d=await yo(at,u,o);await ma({orgId:xt(),client:u,gitMetadata:d}).saveStepCacheEntries({logger:at,testId:a.id,entries:s}),c.forEach(m=>{nr({content:m,schemaVersion:n.schemaVersion,momenticFiles:i,project:o})}),qt({relativeTestPath:t,steps:l,schemaVersion:n.schemaVersion,project:o}),e.status(201).json({message:"ok"})}));Do.patch("/:testPath/environments",Re(async(r,e)=>{let{testPath:t}=r.params;if(!t){e.status(400).json({error:"Missing testPath in url path."});return}let n;try{n=yT.parse(r.body)}catch(o){e.status(400).json({error:`Invalid request body: ${o}`});return}Dh(t,{envs:n.defaultEnv?[{name:n.defaultEnv,default:!0}]:[]},ce()),e.status(201).json({message:"ok"})}));Do.post("/:testPath/duplicate",Re(async(r,e)=>{let{testPath:t}=r.params;if(!t){e.status(400).json({error:"Missing testPath in url path."});return}let n;try{n=hT.parse(r.body)}catch(f){e.status(400).json({error:`Invalid request body: ${f}`});return}try{ro(n.name)}catch(f){e.status(400).json({error:f.message});return}let o=ce(),i=Hl.join(o.rootDir,t);if(!LI.existsSync(i)){e.status(404).json({error:"Test not found."});return}let a=await Y(o),l;try{l=await tt(i,at,a)}catch(f){e.status(400).send({error:f.message});return}let c=c$(),s=xr.parse({...l,name:n.name,id:c}),{stepsToSave:u}=await et({stepLists:{steps:l.steps,beforeSteps:l.beforeSteps,afterSteps:l.afterSteps},createNewCacheIds:!0,cacheCreationParams:{testId:c,orgId:xt()}}),d=hn({fileType:pe.TEST,...s,beforeSteps:u.beforeSteps??void 0,steps:u.steps,afterSteps:u.afterSteps??void 0}),p=Hl.dirname(i),m=Hl.join(p,`${n.name}.test.yaml`),h=u$.stringify(d);LI.writeFileSync(m,h,"utf-8");let g={relativeFilePath:Hl.relative(o.rootDir,m)};zl.track({type:"test_editor:test_create"}),e.status(201).json(g)}));Do.post("/:testPath/chat",Re(async(r,e)=>{let{testPath:t}=r.params;if(!t){e.status(400).json({error:"Missing testPath in url path."});return}let{messages:n}=r.body;if(!n){e.status(400).json({error:"Missing messages in request body."});return}let{sessionId:o}=r.body;if(!o){e.status(401).json({error:"Missing sessionId in request body."});return}let i=a$(n),a=ep.getSession(o);if(!a){e.status(400).json({error:"No active browser session. Start a session first."});return}let l=ce(),c=rl(t,l),s=at.child({orgId:xt(),applicationName:"momentic-desktop-server-copilot",testId:c.id,sessionId:o});s.debug("Initializing copilot with sessionId",o);let u=up(t,i,s,a,o);s$(u).pipeUIMessageStreamToResponse(e,{onError:p=>(s.error({err:p,sessionId:o},"streamText session failed"),p instanceof Error?p.message:String(p))})}));var NI=Do;async function FI(r){let{momenticServerUrl:e,apiKey:t,serverPort:n,staticDir:o,devicePixelRatio:i,alwaysSaveCache:a,noCache:l,initialProject:c}=r;e&&Wv(e),await qv(t);let s=xt(),u=ga();zl.identify({user_id:u,org_id:s});let d=r.logger??at;d=d.child({orgId:s,userId:u}),d.debug({params:r},"Desktop server init and api key check done");let p=S$(o,n,d),m=`http://localhost:${n}`;T.info(`Desktop server is running at ${m}`),Ru(c,R=>vt({configFilePath:R})),await new Promise(R=>{try{p.listen(n,()=>{d.info(`Desktop server is running at ${m}`),R()})}catch(A){A.message.includes("EADDRINUSE")?BI(n):T.error(`An unexpected error occurred while starting the server: ${A.message}`),process.exit(1)}});let g={type:"API_KEY",baseUrl:qr(),apiKey:t,logger:d},f=async()=>{let R=ce();return new Dn(R.config.ai?.agentConfig,g)},S=async()=>new fo(g,await f()),y=new Ze(g),E=new Mi;Q_({baseServer:p,getOrgId:async()=>xt(),generatorFactory:f,enricherFactory:S,cacheStorageFactory:async R=>{let A=ce(),C=await yo(d,y,A);return ma({orgId:R,client:y,gitMetadata:C,alwaysSaveCache:a,noCache:l})},branchGetter:async()=>{try{return(await il(d))?.gitBranchName}catch(R){d.error({err:R},"Failed to get environment git metadata");return}},settingsFactory:async()=>{let R=ce();return{ai:{},browser:{},...R.config}},storageFactory:async R=>new Lo(y,R),logger:d,devicePixelRatio:i,authorization:g,visualDiffScreenshotStorage:E,globalE2eStateManager:ep})}var UI="25mb";function S$(r,e,t){let n=kI();n.use(d$()),n.use(DI.json({limit:UI})),n.use(DI.urlencoded({extended:!1,limit:UI}));let o=h$();if(o.use("/tests",NI),o.use("/modules",Z_),o.use("/environments",rI),o.use("/projects",MI),o.use("/folders",Nh),o.use("/settings",OI),o.use("/identify",oI),o.use("/entities",tI),o.use("/mcp",II),n.use("/api",o),n.use((a,l,c)=>{a.path!=="/healthcheck"&&!a.path.startsWith("/assets")&&t.debug({url:a.url,path:a.path,query:a.query,method:a.method,body:a.body,headers:a.rawHeaders,client:a.ip},"Received desktop-server request"),l.on("close",()=>{l.statusCode>=400&&t.error({url:a.url,method:a.method,statusCode:l.statusCode},"Request completed in error")}),c()}),n.use((a,l,c,s)=>{if(a instanceof Error&&a.message.includes("BadRequestError: request aborted")){c.status(400).send("Client disconnected");return}t.error({stack:a.stack,msg:a.message,err:a,url:l.url,method:l.method},"Unhandled exception leading to 500 on desktop-server"),T.error(`Oh no! We seem to have hit an unexpected snag \u{1F61E}. Please contact Momentic Support with the following error: ${a.message}
|
|
4379
|
+
Category: ${u.category}`);return}let d,p;try{({entity:d,momenticFiles:p}=await xn(o,e.selector,"test"))}catch(A){t.addError(String(A));return}let m=i.child({applicationName:"momentic-mcp-copilot",testId:d.id}),h=up(d.relativePath,[{role:"user",content:e.message}],m,await YV(m,o,d),n?.sessionId),{signal:g,release:f}=await RI.startOrReplace(d.id,a),y=jV({...h,abortSignal:g}),S=[];try{for await(let A of y.textStream)S.push(A)}catch(A){if(g.aborted)i.debug("AI stream was cancelled, returning partial output"),t.addResult(JSON.stringify({aborted:String(A),partialOutput:S.join("")},null,2));else throw A}finally{f()}let E=await tt(d.fullFilePath,i,p),R=S.join("").split(`
|
|
4380
|
+
`).map(A=>A.trim()).filter(A=>A.length>0);t.addResult(JSON.stringify({editedTest:E,messages:R},null,2))}}),wI=[qV,WV,KV,XV];var CI=[...iI,...wI,...Zd];function rS(r,e){let t=new JV({name:e.applicationName,version:e.cliVersion},{capabilities:{logging:{},tools:{}}});for(let n of CI)n.addToolToMcpServer(r,t);return t}async function xI(r,e,t,n){let o=new QV(t,e,n);return await r.connect(o),{close:async()=>{try{await r.close()}catch{}},transport:o}}var nS="mcp-session-id",n$="sessionId",qa=r$(),Bl=new Map;function _I(){let r={applicationName:"momentic-mcp-desktop-server",cliVersion:Wf??"0.0.0"},e=ce(),t=at.child({orgId:xt(),userId:ga(),...r});return{context:{project:e,logger:t},info:r}}qa.get("/sse",async(r,e)=>{let{context:t,info:n}=_I(),o=rS(t,n),{transport:i}=await xI(o,e,"/api/mcp/sse",{enableDnsRebindingProtection:!1}),a=i.sessionId,l={transport:i,close:async()=>{Bl.delete(a);try{await o.close()}catch(c){t.logger.warn({err:c},"Failed to close MCP server on SSE session cleanup")}}};Bl.set(a,l),i.onclose=()=>{let c=Bl.get(a);c&&c.close()}});qa.post("/sse",async(r,e)=>{let t=String(r.query[n$]??"");if(!t||!Bl.has(t)){e.status(400).send("Invalid or missing sessionId");return}await Bl.get(t).transport.handlePostMessage(r,e,r.body)});var II=qa,Vn={};qa.post("/",async(r,e)=>{let t=String(r.headers[nS]??"");try{if(t&&Vn[t]){await Vn[t].handleRequest(r,e,r.body);return}if(!t&&e$(r.body)){let{context:n,info:o}=_I(),i=rS(n,o),a=new ZV({sessionIdGenerator:()=>t$(),enableDnsRebindingProtection:!1,onsessioninitialized:l=>{Vn[l]=a}});a.onclose=()=>{let l=a.sessionId;l&&Vn[l]&&delete Vn[l],i.close().catch(()=>{})},await i.connect(a),await a.handleRequest(r,e,r.body);return}e.status(400).json({jsonrpc:"2.0",error:{code:-32e3,message:"Bad Request: No valid session ID provided"},id:null})}catch{e.headersSent||e.status(500).json({jsonrpc:"2.0",error:{code:-32603,message:"Internal server error"},id:null})}});qa.get("/",async(r,e)=>{let t=String(r.headers[nS]??"");if(!t||!Vn[t]){e.status(400).send("Invalid or missing session ID");return}await Vn[t].handleRequest(r,e)});qa.delete("/",async(r,e)=>{let t=String(r.headers[nS]??"");if(!t||!Vn[t]){e.status(400).send("Invalid or missing session ID");return}let n=Vn[t];try{await n.handleRequest(r,e)}catch{e.headersSent||e.status(500).send("Error processing session termination")}});import{Router as o$}from"express";var pp=o$();pp.get("/",Re(async(r,e)=>{let t=(await jh()).map(n=>({name:n.config.name,configFilePath:n.configFilePath}));e.status(200).json(t)}));pp.get("/current",Re((r,e)=>{let t=ce();if(!t){e.status(404).json({error:"No project found."});return}let n={name:t.config.name,configFilePath:t.configFilePath};e.status(200).json(n)}));pp.post("/set",Re(async(r,e)=>{let t;try{t=ET.parse(r.body)}catch(n){e.status(400).json({error:`Invalid request body: ${n}`});return}try{let n=await vt({configFilePath:t.configFilePath});Ru(n,o=>vt({configFilePath:o}))}catch(n){e.status(400).json({error:`Error setting project: ${n}`});return}e.sendStatus(204)}));var MI=pp;import{Router as i$}from"express";var PI=i$();PI.get("/",Re((r,e)=>{let n={ai:ce().config.ai};e.status(200).json(n)}));var OI=PI;import{convertToModelMessages as a$,streamText as s$}from"ai";import{Router as l$}from"express";import LI from"fs";import Hl from"path";import{v4 as c$}from"uuid";import u$ from"yaml";var zl=new Uu({platform:"local_app"},{flushAt:1,flushInterval:0});var Do=l$();Do.post("/",Re(async(r,e)=>{let t;try{t=mT.parse(r.body)}catch(n){e.status(400).json({error:`Invalid request body: ${n}`});return}try{let n=ce(),o=await tp({project:n,input:t});zl.track({type:"test_editor:test_create"}),e.status(201).json(o)}catch(n){if(n instanceof De){e.status(400).json({error:n.message});return}throw n}}));Do.get("/:testPath",Re(async(r,e)=>{let{testPath:t}=r.params;if(!t){e.status(400).json({error:"Missing testPath in url path."});return}let n=ce(),o=await Y(n),i;try{i=await tt(Hl.join(n.rootDir,t),at,o),e.status(200).json(i)}catch(a){e.status(400).send({error:a.message});return}(async()=>{try{let{stepsToSave:a,moduleUpdates:l}=await et({stepLists:{steps:i.steps,beforeSteps:i.beforeSteps,afterSteps:i.afterSteps}});l.forEach(c=>{nr({content:c,schemaVersion:ue,momenticFiles:o,project:n})}),qt({relativeTestPath:t,steps:a,schemaVersion:ue,project:n})}catch(a){at.error({err:a},"Failed to save migrated test to disk after initial fetch")}})()}));Do.patch("/:testPath/metadata",Re(async(r,e)=>{if(!r.params.testPath){e.status(400).json({error:"Missing testPath in url path."});return}let t;try{t=pT.parse(r.body)}catch(i){e.status(400).json({error:`Invalid request body: ${i}`});return}let o={message:"ok",newRelativeTestPath:Dh(r.params.testPath,t,ce()).newRelativeTestPath};e.status(200).json(o)}));Do.patch("/:testPath",Re(async(r,e)=>{let{testPath:t}=r.params;if(!t){e.status(400).json({error:"Missing testPath in url path."});return}let n;try{n=dT.parse(r.body)}catch(m){at.warn({err:m},"Invalid save request"),e.status(400).json({error:`Invalid request body: ${m}`});return}at.info({testPath:t},"Save received");let o=ce(),i=await Y(o),a;try{a=rl(t,o)}catch(m){e.status(400).json({error:`Existing test file on disk is invalid: ${m}`});return}let{stepsToSave:l,moduleUpdates:c,cachesToSave:s}=await et({stepLists:n.stepLists,cacheCreationParams:{testId:a.id,orgId:xt()}}),u=new Ze({apiKey:Kr(),baseUrl:qr(),logger:at}),d=await yo(at,u,o);await ma({orgId:xt(),client:u,gitMetadata:d}).saveStepCacheEntries({logger:at,testId:a.id,entries:s}),c.forEach(m=>{nr({content:m,schemaVersion:n.schemaVersion,momenticFiles:i,project:o})}),qt({relativeTestPath:t,steps:l,schemaVersion:n.schemaVersion,project:o}),e.status(201).json({message:"ok"})}));Do.patch("/:testPath/environments",Re(async(r,e)=>{let{testPath:t}=r.params;if(!t){e.status(400).json({error:"Missing testPath in url path."});return}let n;try{n=yT.parse(r.body)}catch(o){e.status(400).json({error:`Invalid request body: ${o}`});return}Dh(t,{envs:n.defaultEnv?[{name:n.defaultEnv,default:!0}]:[]},ce()),e.status(201).json({message:"ok"})}));Do.post("/:testPath/duplicate",Re(async(r,e)=>{let{testPath:t}=r.params;if(!t){e.status(400).json({error:"Missing testPath in url path."});return}let n;try{n=hT.parse(r.body)}catch(f){e.status(400).json({error:`Invalid request body: ${f}`});return}try{ro(n.name)}catch(f){e.status(400).json({error:f.message});return}let o=ce(),i=Hl.join(o.rootDir,t);if(!LI.existsSync(i)){e.status(404).json({error:"Test not found."});return}let a=await Y(o),l;try{l=await tt(i,at,a)}catch(f){e.status(400).send({error:f.message});return}let c=c$(),s=xr.parse({...l,name:n.name,id:c}),{stepsToSave:u}=await et({stepLists:{steps:l.steps,beforeSteps:l.beforeSteps,afterSteps:l.afterSteps},createNewCacheIds:!0,cacheCreationParams:{testId:c,orgId:xt()}}),d=hn({fileType:pe.TEST,...s,beforeSteps:u.beforeSteps??void 0,steps:u.steps,afterSteps:u.afterSteps??void 0}),p=Hl.dirname(i),m=Hl.join(p,`${n.name}.test.yaml`),h=u$.stringify(d);LI.writeFileSync(m,h,"utf-8");let g={relativeFilePath:Hl.relative(o.rootDir,m)};zl.track({type:"test_editor:test_create"}),e.status(201).json(g)}));Do.post("/:testPath/chat",Re(async(r,e)=>{let{testPath:t}=r.params;if(!t){e.status(400).json({error:"Missing testPath in url path."});return}let{messages:n}=r.body;if(!n){e.status(400).json({error:"Missing messages in request body."});return}let{sessionId:o}=r.body;if(!o){e.status(401).json({error:"Missing sessionId in request body."});return}let i=a$(n),a=ep.getSession(o);if(!a){e.status(400).json({error:"No active browser session. Start a session first."});return}let l=ce(),c=rl(t,l),s=at.child({orgId:xt(),applicationName:"momentic-desktop-server-copilot",testId:c.id,sessionId:o});s.debug("Initializing copilot with sessionId",o);let u=up(t,i,s,a,o);s$(u).pipeUIMessageStreamToResponse(e,{onError:p=>(s.error({err:p,sessionId:o},"streamText session failed"),p instanceof Error?p.message:String(p))})}));var NI=Do;async function FI(r){let{momenticServerUrl:e,apiKey:t,serverPort:n,staticDir:o,devicePixelRatio:i,alwaysSaveCache:a,noCache:l,initialProject:c}=r;e&&Wv(e),await qv(t);let s=xt(),u=ga();zl.identify({user_id:u,org_id:s});let d=r.logger??at;d=d.child({orgId:s,userId:u}),d.debug({params:r},"Desktop server init and api key check done");let p=S$(o,n,d),m=`http://localhost:${n}`;T.info(`Desktop server is running at ${m}`),Ru(c,R=>vt({configFilePath:R})),await new Promise(R=>{try{p.listen(n,()=>{d.info(`Desktop server is running at ${m}`),R()})}catch(A){A.message.includes("EADDRINUSE")?BI(n):T.error(`An unexpected error occurred while starting the server: ${A.message}`),process.exit(1)}});let g={type:"API_KEY",baseUrl:qr(),apiKey:t,logger:d},f=async()=>{let R=ce();return new Dn(R.config.ai?.agentConfig,g)},y=async()=>new fo(g,await f()),S=new Ze(g),E=new Mi;Q_({baseServer:p,getOrgId:async()=>xt(),generatorFactory:f,enricherFactory:y,cacheStorageFactory:async R=>{let A=ce(),C=await yo(d,S,A);return ma({orgId:R,client:S,gitMetadata:C,alwaysSaveCache:a,noCache:l})},branchGetter:async()=>{try{return(await il(d))?.gitBranchName}catch(R){d.error({err:R},"Failed to get environment git metadata");return}},settingsFactory:async()=>{let R=ce();return{ai:{},browser:{},...R.config}},storageFactory:async R=>new Lo(S,R),logger:d,devicePixelRatio:i,authorization:g,visualDiffScreenshotStorage:E,globalE2eStateManager:ep})}var UI="25mb";function S$(r,e,t){let n=kI();n.use(d$()),n.use(DI.json({limit:UI})),n.use(DI.urlencoded({extended:!1,limit:UI}));let o=h$();if(o.use("/tests",NI),o.use("/modules",Z_),o.use("/environments",rI),o.use("/projects",MI),o.use("/folders",Nh),o.use("/settings",OI),o.use("/identify",oI),o.use("/entities",tI),o.use("/mcp",II),n.use("/api",o),n.use((a,l,c)=>{a.path!=="/healthcheck"&&!a.path.startsWith("/assets")&&t.debug({url:a.url,path:a.path,query:a.query,method:a.method,body:a.body,headers:a.rawHeaders,client:a.ip},"Received desktop-server request"),l.on("close",()=>{l.statusCode>=400&&t.error({url:a.url,method:a.method,statusCode:l.statusCode},"Request completed in error")}),c()}),n.use((a,l,c,s)=>{if(a instanceof Error&&a.message.includes("BadRequestError: request aborted")){c.status(400).send("Client disconnected");return}t.error({stack:a.stack,msg:a.message,err:a,url:l.url,method:l.method},"Unhandled exception leading to 500 on desktop-server"),T.error(`Oh no! We seem to have hit an unexpected snag \u{1F61E}. Please contact Momentic Support with the following error: ${a.message}
|
|
4382
4381
|
${a.stack}`),c.status(500).send(`Internal Server Error: ${a.message}`)}),r){let a=kI.static(r,{setHeaders:l=>{l.setHeader("Cache-Control","no-cache")},redirect:!1});n.use(a),n.use("*",(l,c)=>{c.sendFile(f$.join(r,"index.html"))})}let i=g$.createServer(n);return i.once("error",a=>{"code"in a&&a.code==="EADDRINUSE"?(BI(e),process.exit(1)):console.error("An unexpected server error occurred:",a.message)}),i}m$.setMaxListeners(25);process.on("warning",r=>{at.warn({err:r},`Node warning received on desktop-server: ${r.message}`)});process.on("uncaughtException",r=>{at.error({err:r},"Uncaught exception on desktop-server"),T.error(`Oh no! The Momentic desktop app encountered a fatal error \u{1F61E}. Error logs: ${r.message}`)});process.on("unhandledRejection",(r,e)=>{at.error({reason:`${r}`,stack:r?.stack},"Uncaught exception on desktop-server (promise rejection)"),T.error(`Oh no! The Momentic desktop app encountered an asynchronous error \u{1F61E}. Error logs: ${r}`)});function BI(r){T.error(p$`Port ${r} is already in use by another process. Please close the other process and try again.
|
|
4383
4382
|
Using Bash on MacOS or Linux:
|
|
4384
4383
|
lsof -t -i :58888 | xargs kill -9
|
|
4385
4384
|
|
|
4386
4385
|
Using Command Prompt on Windows:
|
|
4387
4386
|
for /f "tokens=5" %a in ('netstat -ano ^| findstr :58888') do taskkill /PID %a /F
|
|
4388
|
-
`)}import vW from"events";import Ip from"fs";import AW from"open";import{cpus as HM}from"os";import _p from"path";import{fileURLToPath as RW}from"url";import y$ from"diff-lines";import{gt as E$}from"semver";async function zI({test:r,fragment:e,entities:t,client:n,logger:o,yes:i}){E$(e.schemaVersion,ue)&&(T.error(`This version of the CLI does not support the schema version of the fragment (${e.schemaVersion}). Please update to the latest version of the CLI and retry this command.`),process.exit(1)),Yb(e.steps).forEach(h=>{t.modules[h]||(T.error(`The test patch contains a module with id ${h} that could not be found in the current project. This suggests that either this test patch or your local file system may be out of date.`),process.exit(1))}),e.createdAt.getTime()<Date.now()-7*24*60*60*1e3&&!i&&!await Pt("The test patch you are applying is more than 7 days old. Are you sure you want to continue?")&&process.exit(1);let l=r.lastModified.getTime();e.createdAt.getTime()+60*60*1e3<l&&!i&&!await Pt("The test patch you are applying was created before the test was last updated. Are you sure you want to continue?")&&process.exit(1);let c=hi(r.fullFilePath,o,t),s=c.steps;if(!Array.isArray(s))throw new Error(`Test ${r.fullFilePath} is missing steps array`);let u,d;if(e.schemaVersion!==ue){let{steps:h,newVersion:g}=await Ks({metadata:{id:e.id,schemaVersion:e.schemaVersion},steps:e.steps,logger:T});u=g,d=st.array().parse(h)}else d=st.array().parse(e.steps);let{stepsToSave:p}=await et({stepLists:{steps:d}});p.beforeSteps=c.beforeSteps??void 0,p.afterSteps=c.afterSteps??void 0;let m=y$(JSON.stringify(s,void 0,2),JSON.stringify(p,void 0,2),{n_surrounding:5});T.dimmed("=".repeat(30)),T.dimmed(m),T.dimmed("=".repeat(30)),T.dimmed(""),u&&T.warn(`If this patch is applied, your test will also be automatically upgraded to the latest schema version (${u}). Schema upgrades have no impact on functionality, although you may notice minor differences in the test YAML.`),!i&&!await Pt("Do you want to apply this patch?")&&(T.dimmed("Cancelled."),process.exit(1)),qt({relativeTestPath:r.relativePath,steps:p,schemaVersion:u??e.schemaVersion,project:t.project}),T.success("Patch applied successfully."),await n.patchTestFragment(e.id,{applied:!0,appliedAt:new Date})}import{randomUUID as yr}from"crypto";import{z as HI}from"zod";function Gl(r){return HI.string().uuid().safeParse(r).success}async function mp({fix:r,project:e}){let t=await Y(e),n=Object.values(t.tests),o={},i={},a=new Set,l={},c=new Set,s=0;for(let d of n)try{let p=hi(d.fullFilePath,ne,t),m=!1,h=!1;Gl(d.id)||(T.error(`Test '${d.name}' (${d.relativePath}) has an ID that does not parse as a UUID: '${d.id}'`),s++,h=!0,r&&(d.id=yr(),m=!0)),t.duplicateEntities[d.id]&&(T.error(`Test '${d.name}' (${d.relativePath}) has a duplicate ID: '${d.id}'`),s++,h=!0,r&&(d.id=yr(),m=!0));let g=p.steps;if(!g||g.length===0||!Array.isArray(g)){T.debug(`Test ${d.name} (${d.relativePath}) has no steps, skipping...`);continue}let f=Vt.parse(p),
|
|
4387
|
+
`)}import vW from"events";import Ip from"fs";import AW from"open";import{cpus as HM}from"os";import _p from"path";import{fileURLToPath as RW}from"url";import y$ from"diff-lines";import{gt as E$}from"semver";async function zI({test:r,fragment:e,entities:t,client:n,logger:o,yes:i}){E$(e.schemaVersion,ue)&&(T.error(`This version of the CLI does not support the schema version of the fragment (${e.schemaVersion}). Please update to the latest version of the CLI and retry this command.`),process.exit(1)),Yb(e.steps).forEach(h=>{t.modules[h]||(T.error(`The test patch contains a module with id ${h} that could not be found in the current project. This suggests that either this test patch or your local file system may be out of date.`),process.exit(1))}),e.createdAt.getTime()<Date.now()-7*24*60*60*1e3&&!i&&!await Pt("The test patch you are applying is more than 7 days old. Are you sure you want to continue?")&&process.exit(1);let l=r.lastModified.getTime();e.createdAt.getTime()+60*60*1e3<l&&!i&&!await Pt("The test patch you are applying was created before the test was last updated. Are you sure you want to continue?")&&process.exit(1);let c=hi(r.fullFilePath,o,t),s=c.steps;if(!Array.isArray(s))throw new Error(`Test ${r.fullFilePath} is missing steps array`);let u,d;if(e.schemaVersion!==ue){let{steps:h,newVersion:g}=await Ks({metadata:{id:e.id,schemaVersion:e.schemaVersion},steps:e.steps,logger:T});u=g,d=st.array().parse(h)}else d=st.array().parse(e.steps);let{stepsToSave:p}=await et({stepLists:{steps:d}});p.beforeSteps=c.beforeSteps??void 0,p.afterSteps=c.afterSteps??void 0;let m=y$(JSON.stringify(s,void 0,2),JSON.stringify(p,void 0,2),{n_surrounding:5});T.dimmed("=".repeat(30)),T.dimmed(m),T.dimmed("=".repeat(30)),T.dimmed(""),u&&T.warn(`If this patch is applied, your test will also be automatically upgraded to the latest schema version (${u}). Schema upgrades have no impact on functionality, although you may notice minor differences in the test YAML.`),!i&&!await Pt("Do you want to apply this patch?")&&(T.dimmed("Cancelled."),process.exit(1)),qt({relativeTestPath:r.relativePath,steps:p,schemaVersion:u??e.schemaVersion,project:t.project}),T.success("Patch applied successfully."),await n.patchTestFragment(e.id,{applied:!0,appliedAt:new Date})}import{randomUUID as yr}from"crypto";import{z as HI}from"zod";function Gl(r){return HI.string().uuid().safeParse(r).success}async function mp({fix:r,project:e}){let t=await Y(e),n=Object.values(t.tests),o={},i={},a=new Set,l={},c=new Set,s=0;for(let d of n)try{let p=hi(d.fullFilePath,ne,t),m=!1,h=!1;Gl(d.id)||(T.error(`Test '${d.name}' (${d.relativePath}) has an ID that does not parse as a UUID: '${d.id}'`),s++,h=!0,r&&(d.id=yr(),m=!0)),t.duplicateEntities[d.id]&&(T.error(`Test '${d.name}' (${d.relativePath}) has a duplicate ID: '${d.id}'`),s++,h=!0,r&&(d.id=yr(),m=!0));let g=p.steps;if(!g||g.length===0||!Array.isArray(g)){T.debug(`Test ${d.name} (${d.relativePath}) has no steps, skipping...`);continue}let f=Vt.parse(p),y=await ci(f,g,T);y.steps=y.steps.map((S,E)=>{S.id||(T.error(`Step ${E} in test '${d.name}' (${d.relativePath}) does not have an ID`),h=!0,r&&(m=!0,S.id=yr())),Gl(S.id)||(T.error(`Step ${E} in test '${d.name}' (${d.relativePath}) has an ID that does not parse as a UUID: '${S.id}'`),s++,h=!0,r&&(m=!0,S.id=yr()));let R=o[S.id]?.testId,A=o[S.id]?.testRelativePath;if(R?(s++,h=!0,R===d.id?T.error(`Multiple steps in the test '${d.name}' (${d.relativePath}) have the same ID '${S.id}'`):T.error(`Step ${E} in test '${d.name}' (${d.relativePath}) has the ID ${S.id} which is duplicated in ${A}`),r&&(m=!0,S.id=yr())):o[S.id]={testId:d.id,testRelativePath:d.relativePath},S.type==="PRESET_ACTION"){let C=S.command.id;Gl(C)||(T.error(`Command ${E} in test '${d.name}' (${d.relativePath}) has an ID that does not parse as a UUID: '${C}'`),s++,h=!0,r&&(m=!0,S.command.id=yr()));let w=i[C]?.testId,I=i[C]?.testRelativePath;w?(s++,h=!0,w===d.id?T.error(`Multiple commands in the test '${d.name}' (${d.relativePath}) have the same ID '${C}'`):T.error(`Command ${E} in test '${d.name}' (${d.relativePath}) has the ID ${C} which is duplicated in test ${I}`),r&&(m=!0,S.command.id=yr())):i[C]={testId:d.id,testRelativePath:d.relativePath}}return He.parse(S)}),h&&T.dimmed("=".repeat(80)),m&&r&&(qt({relativeTestPath:d.relativePath,steps:{beforeSteps:p.beforeSteps,steps:y.steps,afterSteps:p.afterSteps},schemaVersion:ue,project:e}),a.add(d.fullFilePath))}catch(p){T.error({err:p},`Failed to parse test ${d.name} (${d.relativePath})`);continue}let u=Object.values(t.modules);for(let d of u)try{let p=!1,m=!1;Gl(d.id)||(T.error(`Module '${d.name}' (${d.relativePath}) has an ID that does not parse as a UUID: '${d.id}'`),s++,m=!0,r&&(d.id=yr(),p=!0)),t.duplicateEntities[d.id]&&(T.error(`Module '${d.name}' (${d.relativePath}) has a duplicate ID: '${d.id}'`),s++,m=!0,r&&(d.id=yr(),p=!0));let h=Un(d.fullFilePath,T),g=h.steps;if(!g||g.length===0||!Array.isArray(g)){T.debug(`Module ${d.name} (${d.relativePath}) has no steps, skipping...`);continue}let f,y;try{let E=await ci({id:h.moduleId,schemaVersion:h.schemaVersion},h.steps,T);f=E.steps,y=E.newVersion}catch(E){T.error({err:E},`Failed to migrate module ${d.name} (${d.relativePath})`);continue}let S=f.map((E,R)=>{if(HI.string().uuid().safeParse(E.id)||(T.error(`Step ${R} in module '${d.name}' (${d.relativePath}) has an ID that does not parse as a UUID: '${E.id}'`),s++,m=!0,r&&(p=!0,E.id=yr())),o[E.id]?.testId){let C=o[E.id]?.testRelativePath;s++,m=!0,T.error(`Step ${R} in module '${d.name}' (${d.relativePath}) has the ID ${E.id} which is duplicated in test ${C}`),r&&(p=!0,E.id=yr())}if(E.type==="PRESET_ACTION"){let C=E.command.id;Gl(C)||(T.error(`Command ${R} in module '${d.name}' (${d.relativePath}) has an ID that does not parse as a UUID: '${C}'`),s++,m=!0,r&&(p=!0,E.command.id=yr()));let w=i[C],I=l[C];w||I?(s++,m=!0,I?.moduleId===d.id?T.error(`Multiple commands in module '${d.name}' (${d.relativePath}) have the same ID '${C}'`):w?T.error(`Command in module '${d.name}' (${d.relativePath}) has the ID ${C} which is duplicated in test ${w.testRelativePath}`):T.error(`Command ${R} in module '${d.name}' (${d.relativePath}) has the ID ${C} which is duplicated in module ${I.moduleRelativePath}`),r&&(p=!0,E.command.id=yr())):l[C]={moduleId:d.id,moduleRelativePath:d.relativePath}}return He.parse(E)});m&&T.dimmed("=".repeat(80)),p&&r&&(nr({content:{...h,steps:S},schemaVersion:y,momenticFiles:t,project:e,forceSaveOnNoDiffs:!0}),c.add(d.fullFilePath))}catch(p){T.error({err:p},`Failed to parse module ${d.name} (${d.relativePath})`);continue}return{errors:s,modifiedTestFilePaths:a,modifiedModuleFilePaths:c}}async function GI({fix:r,project:e}){let{errors:t,modifiedTestFilePaths:n,modifiedModuleFilePaths:o}=await mp({fix:r,project:e});t>0?(T.error(`Found errors in ${t} steps`),r?(T.warn(`Modified the following test files:
|
|
4389
4388
|
${[...n].map(i=>`${mt}- ${i}`).join(`
|
|
4390
4389
|
`)}`),o.size>0&&T.warn(`Modified the following module files:
|
|
4391
4390
|
${[...o].map(i=>`${mt}- ${i}`).join(`
|
|
@@ -4396,10 +4395,10 @@ ${r.map(p=>`${mt}- ${p}`).join(`
|
|
|
4396
4395
|
`),r.forEach(p=>{if(!SS.existsSync(p))throw new Error(`Path '${p}' does not exist.`);let m,h;try{m=SS.statSync(p),h=m.isDirectory()}catch(f){l.warn({err:f},`Skipping path ${p} because it cannot be read`);return}let g=yS.resolve(p);Object.values(e.tests).filter(f=>h?f.fullFilePath.startsWith(g):f.fullFilePath===g).forEach(f=>{c.add(f.fullFilePath)})})):(l.info(`Reading all tests from the project and running those matching the following substring filters:
|
|
4397
4396
|
${r.map(p=>`${mt}- ${p}`).join(`
|
|
4398
4397
|
`)}`),Object.values(e.tests).forEach(p=>{r.some(m=>p.relativePath.includes(m))&&c.add(p.fullFilePath)}))}else{!n&&!await Pt("No test paths or substrings were provided. Do you want to run all tests?")&&(l.error("Cancelled by user."),process.exit(1));let u=Object.values(e.tests);l.info(`Reading all ${u.length} tests in the project from local disk.`),u.forEach(d=>{c.add(d.fullFilePath)})}for(let u of c){let d=yS.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)}let s=Array.from(c).map(async u=>{try{let d=await tt(u,ne,e);if(M$.gt(d.schemaVersion,ue)&&l.warn(`Test ${u} has schema version ${d.schemaVersion}, which is greater than what is currently supported by this SDK. Please update your momentic package version to avoid unexpected behavior.`),a&&a.length>0){let p=d.labels||[];if(!a.some(h=>p.includes(h)))return null}return{...d,fullFilePath:u,relativeFilePath:yS.relative(t.rootDir,u)}}catch(d){l.error(`Failed to read and resolve test at '${u}': ${d}`),process.exit(1)}});return Promise.all(s).then(_$)}function hM({testDefinitions:r,quarantinedTestReasons:e,onlyQuarantined:t=!1,skipQuarantined:n=!1}){if(t){let[u,d]=bp(r,h=>h.id in e),[p,m]=bp(u,h=>h.disabled||n);return{testsToSkip:p,quarantinedTestsToSkip:[],testsToRun:m,quarantinedTestsToRun:[]}}let[o,i]=bp(r,u=>u.disabled),[a,l]=bp(i,u=>u.id in e);return{testsToSkip:o,testsToRun:l,quarantinedTestsToRun:n?[]:a,quarantinedTestsToSkip:n?a:[]}}function gM({testsToRun:r,quarantinedTestsToRun:e,quarantinedTestReasons:t,testInputMatrix:n}){let o=[],i=(a,l,c)=>{n?n.forEach((s,u)=>{o.push({inputs:s,inputIndex:u,testDefinition:a,quarantined:l,quarantinedReason:c})}):o.push({inputs:void 0,testDefinition:a,quarantined:l,quarantinedReason:c})};return r.forEach(a=>i(a,!1)),e.forEach(a=>i(a,!0,t[a.id])),o}async function fM({project:r,apiClient:e}){let t=await Y(r),n=await Ka({tests:[],momenticFiles:t,yes:!0,project:r,logger:new oi(40,{})}),o=(await e.getQuarantinedTests()).quarantined,i=new Set(o.map(l=>l.testId)),a=n.filter(l=>i.has(l.id));T.info(a.map(l=>l.relativeFilePath).join(`
|
|
4399
|
-
`))}async function SM({test:r,reason:e,apiClient:t,project:n,logger:o,identity:i}){let a=(await Y(n)).tests,l=Object.values(a),c=(await t.getQuarantinedTests()).quarantined,s=new Set(c.map(m=>m.testId)),u=l.filter(m=>s.has(m.id)),d=await Ep({prompt:"Select a test to unquarantine.",inputtedTest:r,testOptions:u}),p=await Tp({prompt:"Enter a reason for unquarantining the test.",inputtedReason:e});await t.unquarantineTest(d,p,i),T.success(`Test ${d.name} has been successfully removed from quarantine.`)}function yM(r){return r?Oe(r):"Unknown suite"}async function EM({client:r,orgId:e,suitePaths:t,wait:n,waitTimeout:o,...i}){let{suiteRunIds:a,runGroupIds:l}=await r.queueSuiteRuns({paths:t,...i});ne.info({orgId:e,suiteRunIds:a,runGroupIds:l,suitePaths:t},"Queued suites remotely"),T.dimmed(`Queued ${t.length} suites.`),n||process.exit(0);let c=Date.now();T.dimmed(`Waiting for ${t.length} suites to finish. You can view results upon completion at:`);for(let f of l)T.dimmed(`${mt}- ${r.getAppUrl()}/run-groups/${f}`);let s=new Set,u=[],d=f=>(f.status==="FAILED"||f.status==="PASSED"||f.status==="CANCELLED")&&f.runs.every(y=>y.status==="FAILED"&&(y.failureReason||y.finishedAt&&Date.now()-y.finishedAt.getTime()>30*1e3)||y.status==="PASSED"||y.status==="CANCELLED"),p=await Qc({name:"suites",getResults:async()=>{let f=l.filter(E=>!u.some(R=>R.id===E)),S=await r.bulkGetRunGroupStatus(f),y=[];for(let E of S)d(E)?u.push(E):y.push(E);return[...u,...y]},timeoutMs:o?o*1e3:void 0,checkDone:f=>(f.forEach(S=>{S.status==="RUNNING"&&(s.has(S.id)||(s.add(S.id),T.log(`${s.size}/${l.length} ${yM(S.suite?.name)}`)))}),f.every(d))}),m=r.getAppUrl(),g=ia({results:p,startTime:c,onFailed:f=>{let S=yM(f.suite?.name),y=f.runs.filter(R=>R.status==="FAILED").length,E=f.runs.length;T.error(`${S} (${y}/${E} tests failed):`);for(let R of f.runs)if(R.status==="FAILED"){let A=R.testName||R.test?.name;T.error(` ${A?Oe(A):"Unknown test"} (${m}/runs/${R.id})`)}},entity:"suite",getDisplayLine:f=>` ${f.suite?.name?Oe(f.suite.name):"Unknown suite name"} (${m}/run-groups/${f.id})`});process.exit(g.failed>0?1:0)}async function TM({tests:r,client:e,orgId:t,...n}){!n.yes&&!await Pt(`This command will queue ${r.length} tests to run remotely on Momentic's infrastructure. Results will be available on ${e.getAppUrl()}. Continue?`)&&process.exit(1);let{queuedTests:o,runIds:i}=await e.queueTests({testPaths:r,...n});if(ne.info({queuedTests:o,runIds:i,orgId:t},"Queued tests remotely"),T.dimmed(`Queued ${o.length} tests. Processing time may depend on a variety of factors, including how many tests have already been queued from your organization.`),n.wait||process.exit(0),!i.length)return;T.dimmed(`Waiting for ${o.length} tests to complete.`);let a=new Set,l=[],c=m=>m.status==="FAILED"&&m.failureReason||m.status==="PASSED"||m.status==="CANCELLED",s=e.getAppUrl(),u=Date.now(),d=await Qc({name:"runs",getResults:async()=>{let m=i.filter(f=>!l.some(S=>S.id===f)),h=await e.bulkGetRunStatus(m),g=[];for(let f of h)c(f)?l.push(f):g.push(f);return[...l,...g]},timeoutMs:n.waitTimeout?n.waitTimeout*1e3:void 0,checkDone:m=>(m.forEach(h=>{if(h.status==="RUNNING"&&!a.has(h.id)){a.add(h.id);let g=h.testName||h.test?.name;g&&T.log(`${a.size}/${o.length} ${Oe(g)}`)}}),m.every(c))}),p=ia({results:d,startTime:u,onFailed:m=>{let h=m.testName||m.test?.name;Zc(m,h?Oe(h):"Unknown test")},getDisplayLine:m=>{let h=m.testName||m.test?.name,g=` ${h?Oe(h):"Unknown test"}`;return m.id&&(g+=` (${s}/runs/${m.id})`),g},entity:"test"});process.exit(p.failed>0?1:0)}import{randomUUID as hW}from"crypto";import gW from"fs";import{existsSync as V$,mkdirSync as $$,statSync as W$}from"fs";import{randomUUID as bM}from"crypto";import ES from"fs";import{hostname as P$}from"os";import TS from"path";async function vp(r,e,t,n){if(n){let o=await e.getScreenshot(r,n);if(o){let i=`${n}-screenshot.jpeg`,a=TS.join(t,i);return ES.writeFileSync(a,o),i}}}async function O$(r,e,t,n){let o=n.runId??bM(),i={uuid:o,historyId:o,testCaseId:n.test.id,fullName:n.test.name,name:Oe(n.test.name),status:n.status==="PASSED"?"passed":n.status==="CANCELLED"?"skipped":"failed",start:n.lastAttemptStartedAt.getTime(),stop:n.finishedAt.getTime(),parameters:[],labels:[{name:"suite",value:t.suiteName},{name:"host",value:P$()},{name:"platform",value:"momentic"},{name:"attempts",value:n.attempts.toString()}],steps:[]};n.runId&&i.labels?.push({name:"runUrl",value:`https://app.momentic.ai/runs/${n.runId}`});for(let[l,c]of Object.entries(n.parameters))c!=null&&i.parameters.push({name:l,value:JSON.stringify(c)});n.results&&await L$(r,e,t.folder,i.steps,n.results);let a=`${o}-result.json`;ES.writeFileSync(TS.join(t.folder,a),JSON.stringify(i,void 0,2))}async function Ya(r,e,t,n){let o={name:So(n),start:n.startedAt.getTime(),stop:n.finishedAt.getTime(),status:n.status==="SUCCESS"?"passed":n.status==="CANCELLED"?"skipped":"failed",labels:[],steps:[],attachments:[]};n.beforeUrl&&o.labels?.push({name:"URL before step",value:n.beforeUrl}),n.afterUrl&&o.labels?.push({name:"URL after step",value:n.afterUrl});let i=await vp(r,e,t,n.beforeSnapshot);i&&o.attachments.push({name:"Screenshot before step",source:i,type:"image/jpeg"});let a=await vp(r,e,t,n.afterSnapshot);if(a&&o.attachments.push({name:"Screenshot after step",source:a,type:"image/jpeg"}),n.message&&(o.statusDetails={message:n.message}),n.data){let l=`${bM()}-attachment.json`,c=TS.join(t,l);ES.writeFileSync(c,JSON.stringify(n.data,null,2)),o.attachments.push({name:"Step output data",source:l,type:"text/plain"})}return o}async function L$(r,e,t,n,o){for(let i of o)switch(i.type){case"PRESET_ACTION":{n.push(await Ya(r,e,t,i));break}case"CONDITIONAL":{let a=await Ya(r,e,t,i);a.steps=[],i.assertionResult&&a.steps.push(await Ya(r,e,t,i.assertionResult)),a.steps.push(...await Promise.all(i.results.map(l=>Ya(r,e,t,l)))),n.push(a);break}case"AI_ACTION":case"SECTION":case"MODULE":{let a=await Ya(r,e,t,i);if(a.steps=await Promise.all(i.results.map(l=>Ya(r,e,t,l))),i.type==="MODULE"&&i.inputs){a.parameters=[];for(let[l,c]of Object.entries(i.inputs))a.parameters.push({name:l,value:c})}n.push(a)}}}async function vM(r,e,t,n){for(let o of n.runs)await O$(r,e,{folder:t,suiteName:n.suiteName},o)}import N$ from"junit-report-builder";import Ap from"path";function D$(r,e){if(e.name(r.test.name).className(r.test.name).file(Ap.relative(".",r.filePath)).property("id",r.test.id).property("dd_tags[id]",r.test.id),r.test.labels&&(e.property("labels",r.test.labels.join(",")),r.test.labels.forEach(t=>{e.property("dd_tags[label]",t)})),r.baseUrl&&(e.property("base_url",r.baseUrl),e.property("dd_tags[base_url]",r.baseUrl)),r.runId&&(e.property("run_url",`https://app.momentic.ai/runs/${r.runId}`),e.property("dd_tags[run_url]",`https://app.momentic.ai/runs/${r.runId}`)),r.quarantined&&(e.property("quarantined","true"),e.property("dd_tags[quarantined]","true"),r.quarantinedReason&&(e.property("quarantined_reason",r.quarantinedReason),e.property("dd_tags[quarantined_reason]",r.quarantinedReason))),r.beforeResults?.some(t=>t.status==="FAILED")&&(e.property("setup_failed","true"),e.property("dd_tags[setup_failed]","true")),r.results?.some(t=>t.status==="FAILED")&&(e.property("main_failed","true"),e.property("dd_tags[main_failed]","true")),r.afterResults?.some(t=>t.status==="FAILED")&&(e.property("teardown_failed","true"),e.property("dd_tags[teardown_failed]","true")),r.status==="FAILED"){if(r.failureReason){let t=lc[r.failureDetails?.classification?.reason||r.failureReason],n=r.failureDetails?.classification?.summary||ji[r.failureReason];r.runId&&(n+=` Visit https://app.momentic.ai/runs/${r.runId} for more details.`),e.failure(n,t)}r.failureDetails?.errorStack&&e.stacktrace(r.failureDetails.errorStack)}else r.status==="CANCELLED"&&e.skipped();return e.time((r.finishedAt.getTime()-r.lastAttemptStartedAt.getTime())/1e3).property("started_at",r.lastAttemptStartedAt.toISOString()).property("dd_tags[started_at]",r.lastAttemptStartedAt.toISOString()).property("finished_at",r.finishedAt.toISOString()).property("dd_tags[finished_at]",r.finishedAt.toISOString()),e.property("attempts",r.attempts.toString()).property("dd_tags[attempts]",r.attempts.toString()),r.parameters.envName&&(e.property("environment",r.parameters.envName),e.property("dd_tags[environment]",r.parameters.envName)),r.parameters.urlOverride&&e.property("url_override",r.parameters.urlOverride),e}function k$(r,{suiteId:e,suiteName:t,startedAt:n,finishedAt:o,runs:i,testsToSkip:a,quarantinedTestsToSkip:l,quarantinedTestReasons:c}){let s=r.testSuite().name(t);e&&s.property("id",e),s.timestamp(n).property("startedAt",n.toISOString()).property("finishedAt",o.toISOString()).time((o.getTime()-n.getTime())/1e3);for(let u of i){let d=s.testCase();D$(u,d)}for(let u of a){let d=s.testCase();d.name(u.name).className(u.name).file(Ap.relative(".",u.relativeFilePath)).property("id",u.id),u.baseUrl&&d.property("baseUrl",u.baseUrl),u.labels&&(d.property("labels",u.labels.join(",")),u.labels.forEach(p=>{d.property("dd_tags[label]",p)})),d.skipped()}for(let u of l){let d=s.testCase();d.name(u.name).className(u.name).file(Ap.relative(".",u.relativeFilePath)).property("id",u.id).property("quarantined","true");let p=c[u.id];p&&d.property("quarantinedReason",p),u.baseUrl&&d.property("baseUrl",u.baseUrl),u.labels&&(d.property("labels",u.labels.join(",")),u.labels.forEach(m=>{d.property("dd_tags[label]",m)})),d.skipped()}return s}function AM(r,e){let t=N$.newBuilder();k$(t,e),t.writeTo(Ap.join(r,`${e.suiteName}.xml`))}import U$ from"fs";import F$ from"path";function RM(r){return{title:So(r),duration:r.finishedAt.getTime()-r.startedAt.getTime(),error:r.status==="FAILED"?{value:r.failureReason}:void 0,steps:r.results&&r.type!=="PRESET_ACTION"?r.results.map(RM):[]}}async function B$(r,e,t,n){if(n.results?.length){let o=await vp(r,e,t,n.results[n.results.length-1].afterSnapshot);return o?[{name:"Final state screenshot",path:o,contentType:"image/jpeg"}]:[]}return[]}async function z$(r,e,t,n){return{status:n.status==="PASSED"?"passed":n.status==="CANCELLED"?"interrupted":"failed",duration:n.finishedAt.getTime()-n.lastAttemptStartedAt.getTime(),error:n.status==="FAILED"&&n.failureReason?{value:n.failureDetails?.classification?.reason||n.failureReason,message:n.failureDetails?.classification?.summary||ji[n.failureReason]}:void 0,retry:n.attempts-1,steps:n.results?.map(RM)||[],startTime:n.lastAttemptStartedAt.toISOString(),attachments:await B$(r,e,t,n)}}async function H$(r,e,t,n){return{expectedStatus:"passed",status:n.status==="PASSED"?"expected":"unexpected",results:[await z$(r,e,t,n)]}}async function G$(r,e,t,n){return{tags:[],title:n.test.name,ok:n.status==="PASSED",tests:[await H$(r,e,t,n)],id:n.runId,file:n.filePath}}function bS(r,e){return r.reduce((t,n)=>e(n)?t+1:t,0)}async function j$(r,e,t,n){return{suites:[{title:n.suiteName,file:n.projectConfigPath,specs:await Promise.all(n.runs.map(o=>G$(r,e,t,o)))}],errors:[],stats:{startTime:n.startedAt.toISOString(),duration:n.finishedAt.getTime()-n.startedAt.getTime(),expected:bS(n.runs,o=>o.status==="PASSED"),unexpected:bS(n.runs,o=>o.status!=="PASSED"),flaky:bS(n.runs,o=>!!o.isFlake),skipped:0}}}async function wM(r,e,t,n){let o=await j$(r,e,t,n);U$.writeFileSync(F$.join(t,`${n.suiteName}.json`),JSON.stringify(o,null,2))}async function CM(r,e,t,n,o){switch(V$(o)?W$(o).isDirectory()||(T.error(`The specified reporter output directory '${o}' exists on disk but is not a folder. Please move or delete the existing object or specify a different reporter path.`),process.exit(1)):(T.info(`Reporter output directory '${o}' does not exist on disk, creating it now...`),$$(o,{recursive:!0})),t){case"junit":AM(o,n);return;case"allure":case"allure-json":await vM(r,e,o,n);return;case"playwright-json":await wM(r,e,o,n);return;default:throw new Error(`Unknown reporter format requested: '${t}'`)}}import fW from"wait-on";import{execSync as q$}from"child_process";import{platform as K$}from"os";function vS(){return xM()?(T.dimmed("Setting device pixel ratio to 2 automatically since a Mac OS Retina screen was detected."),T.dimmed(`If you are using a low pixel-density monitor, you should manually set --pixel-ratio to 1 to avoid incorrect viewport calculations. Confirm your device's pixel-ratio at https://www.mydevice.io.
|
|
4398
|
+
`))}async function SM({test:r,reason:e,apiClient:t,project:n,logger:o,identity:i}){let a=(await Y(n)).tests,l=Object.values(a),c=(await t.getQuarantinedTests()).quarantined,s=new Set(c.map(m=>m.testId)),u=l.filter(m=>s.has(m.id)),d=await Ep({prompt:"Select a test to unquarantine.",inputtedTest:r,testOptions:u}),p=await Tp({prompt:"Enter a reason for unquarantining the test.",inputtedReason:e});await t.unquarantineTest(d,p,i),T.success(`Test ${d.name} has been successfully removed from quarantine.`)}function yM(r){return r?Oe(r):"Unknown suite"}async function EM({client:r,orgId:e,suitePaths:t,wait:n,waitTimeout:o,...i}){let{suiteRunIds:a,runGroupIds:l}=await r.queueSuiteRuns({paths:t,...i});ne.info({orgId:e,suiteRunIds:a,runGroupIds:l,suitePaths:t},"Queued suites remotely"),T.dimmed(`Queued ${t.length} suites.`),n||process.exit(0);let c=Date.now();T.dimmed(`Waiting for ${t.length} suites to finish. You can view results upon completion at:`);for(let f of l)T.dimmed(`${mt}- ${r.getAppUrl()}/run-groups/${f}`);let s=new Set,u=[],d=f=>(f.status==="FAILED"||f.status==="PASSED"||f.status==="CANCELLED")&&f.runs.every(S=>S.status==="FAILED"&&(S.failureReason||S.finishedAt&&Date.now()-S.finishedAt.getTime()>30*1e3)||S.status==="PASSED"||S.status==="CANCELLED"),p=await Qc({name:"suites",getResults:async()=>{let f=l.filter(E=>!u.some(R=>R.id===E)),y=await r.bulkGetRunGroupStatus(f),S=[];for(let E of y)d(E)?u.push(E):S.push(E);return[...u,...S]},timeoutMs:o?o*1e3:void 0,checkDone:f=>(f.forEach(y=>{y.status==="RUNNING"&&(s.has(y.id)||(s.add(y.id),T.log(`${s.size}/${l.length} ${yM(y.suite?.name)}`)))}),f.every(d))}),m=r.getAppUrl(),g=ia({results:p,startTime:c,onFailed:f=>{let y=yM(f.suite?.name),S=f.runs.filter(R=>R.status==="FAILED").length,E=f.runs.length;T.error(`${y} (${S}/${E} tests failed):`);for(let R of f.runs)if(R.status==="FAILED"){let A=R.testName||R.test?.name;T.error(` ${A?Oe(A):"Unknown test"} (${m}/runs/${R.id})`)}},entity:"suite",getDisplayLine:f=>` ${f.suite?.name?Oe(f.suite.name):"Unknown suite name"} (${m}/run-groups/${f.id})`});process.exit(g.failed>0?1:0)}async function TM({tests:r,client:e,orgId:t,...n}){!n.yes&&!await Pt(`This command will queue ${r.length} tests to run remotely on Momentic's infrastructure. Results will be available on ${e.getAppUrl()}. Continue?`)&&process.exit(1);let{queuedTests:o,runIds:i}=await e.queueTests({testPaths:r,...n});if(ne.info({queuedTests:o,runIds:i,orgId:t},"Queued tests remotely"),T.dimmed(`Queued ${o.length} tests. Processing time may depend on a variety of factors, including how many tests have already been queued from your organization.`),n.wait||process.exit(0),!i.length)return;T.dimmed(`Waiting for ${o.length} tests to complete.`);let a=new Set,l=[],c=m=>m.status==="FAILED"&&m.failureReason||m.status==="PASSED"||m.status==="CANCELLED",s=e.getAppUrl(),u=Date.now(),d=await Qc({name:"runs",getResults:async()=>{let m=i.filter(f=>!l.some(y=>y.id===f)),h=await e.bulkGetRunStatus(m),g=[];for(let f of h)c(f)?l.push(f):g.push(f);return[...l,...g]},timeoutMs:n.waitTimeout?n.waitTimeout*1e3:void 0,checkDone:m=>(m.forEach(h=>{if(h.status==="RUNNING"&&!a.has(h.id)){a.add(h.id);let g=h.testName||h.test?.name;g&&T.log(`${a.size}/${o.length} ${Oe(g)}`)}}),m.every(c))}),p=ia({results:d,startTime:u,onFailed:m=>{let h=m.testName||m.test?.name;Zc(m,h?Oe(h):"Unknown test")},getDisplayLine:m=>{let h=m.testName||m.test?.name,g=` ${h?Oe(h):"Unknown test"}`;return m.id&&(g+=` (${s}/runs/${m.id})`),g},entity:"test"});process.exit(p.failed>0?1:0)}import{randomUUID as hW}from"crypto";import gW from"fs";import{existsSync as V$,mkdirSync as $$,statSync as W$}from"fs";import{randomUUID as bM}from"crypto";import ES from"fs";import{hostname as P$}from"os";import TS from"path";async function vp(r,e,t,n){if(n){let o=await e.getScreenshot(r,n);if(o){let i=`${n}-screenshot.jpeg`,a=TS.join(t,i);return ES.writeFileSync(a,o),i}}}async function O$(r,e,t,n){let o=n.runId??bM(),i={uuid:o,historyId:o,testCaseId:n.test.id,fullName:n.test.name,name:Oe(n.test.name),status:n.status==="PASSED"?"passed":n.status==="CANCELLED"?"skipped":"failed",start:n.lastAttemptStartedAt.getTime(),stop:n.finishedAt.getTime(),parameters:[],labels:[{name:"suite",value:t.suiteName},{name:"host",value:P$()},{name:"platform",value:"momentic"},{name:"attempts",value:n.attempts.toString()}],steps:[]};n.runId&&i.labels?.push({name:"runUrl",value:`https://app.momentic.ai/runs/${n.runId}`});for(let[l,c]of Object.entries(n.parameters))c!=null&&i.parameters.push({name:l,value:JSON.stringify(c)});n.results&&await L$(r,e,t.folder,i.steps,n.results);let a=`${o}-result.json`;ES.writeFileSync(TS.join(t.folder,a),JSON.stringify(i,void 0,2))}async function Ya(r,e,t,n){let o={name:So(n),start:n.startedAt.getTime(),stop:n.finishedAt.getTime(),status:n.status==="SUCCESS"?"passed":n.status==="CANCELLED"?"skipped":"failed",labels:[],steps:[],attachments:[]};n.beforeUrl&&o.labels?.push({name:"URL before step",value:n.beforeUrl}),n.afterUrl&&o.labels?.push({name:"URL after step",value:n.afterUrl});let i=await vp(r,e,t,n.beforeSnapshot);i&&o.attachments.push({name:"Screenshot before step",source:i,type:"image/jpeg"});let a=await vp(r,e,t,n.afterSnapshot);if(a&&o.attachments.push({name:"Screenshot after step",source:a,type:"image/jpeg"}),n.message&&(o.statusDetails={message:n.message}),n.data){let l=`${bM()}-attachment.json`,c=TS.join(t,l);ES.writeFileSync(c,JSON.stringify(n.data,null,2)),o.attachments.push({name:"Step output data",source:l,type:"text/plain"})}return o}async function L$(r,e,t,n,o){for(let i of o)switch(i.type){case"PRESET_ACTION":{n.push(await Ya(r,e,t,i));break}case"CONDITIONAL":{let a=await Ya(r,e,t,i);a.steps=[],i.assertionResult&&a.steps.push(await Ya(r,e,t,i.assertionResult)),a.steps.push(...await Promise.all(i.results.map(l=>Ya(r,e,t,l)))),n.push(a);break}case"AI_ACTION":case"SECTION":case"MODULE":{let a=await Ya(r,e,t,i);if(a.steps=await Promise.all(i.results.map(l=>Ya(r,e,t,l))),i.type==="MODULE"&&i.inputs){a.parameters=[];for(let[l,c]of Object.entries(i.inputs))a.parameters.push({name:l,value:c})}n.push(a)}}}async function vM(r,e,t,n){for(let o of n.runs)await O$(r,e,{folder:t,suiteName:n.suiteName},o)}import N$ from"junit-report-builder";import Ap from"path";function D$(r,e){if(e.name(r.test.name).className(r.test.name).file(Ap.relative(".",r.filePath)).property("id",r.test.id).property("dd_tags[id]",r.test.id),r.test.labels&&(e.property("labels",r.test.labels.join(",")),r.test.labels.forEach(t=>{e.property("dd_tags[label]",t)})),r.baseUrl&&(e.property("base_url",r.baseUrl),e.property("dd_tags[base_url]",r.baseUrl)),r.runId&&(e.property("run_url",`https://app.momentic.ai/runs/${r.runId}`),e.property("dd_tags[run_url]",`https://app.momentic.ai/runs/${r.runId}`)),r.quarantined&&(e.property("quarantined","true"),e.property("dd_tags[quarantined]","true"),r.quarantinedReason&&(e.property("quarantined_reason",r.quarantinedReason),e.property("dd_tags[quarantined_reason]",r.quarantinedReason))),r.beforeResults?.some(t=>t.status==="FAILED")&&(e.property("setup_failed","true"),e.property("dd_tags[setup_failed]","true")),r.results?.some(t=>t.status==="FAILED")&&(e.property("main_failed","true"),e.property("dd_tags[main_failed]","true")),r.afterResults?.some(t=>t.status==="FAILED")&&(e.property("teardown_failed","true"),e.property("dd_tags[teardown_failed]","true")),r.status==="FAILED"){if(r.failureReason){let t=lc[r.failureDetails?.classification?.reason||r.failureReason],n=r.failureDetails?.classification?.summary||ji[r.failureReason];r.runId&&(n+=` Visit https://app.momentic.ai/runs/${r.runId} for more details.`),e.failure(n,t)}r.failureDetails?.errorStack&&e.stacktrace(r.failureDetails.errorStack)}else r.status==="CANCELLED"&&e.skipped();return e.time((r.finishedAt.getTime()-r.lastAttemptStartedAt.getTime())/1e3).property("started_at",r.lastAttemptStartedAt.toISOString()).property("dd_tags[started_at]",r.lastAttemptStartedAt.toISOString()).property("finished_at",r.finishedAt.toISOString()).property("dd_tags[finished_at]",r.finishedAt.toISOString()),e.property("attempts",r.attempts.toString()).property("dd_tags[attempts]",r.attempts.toString()),r.parameters.envName&&(e.property("environment",r.parameters.envName),e.property("dd_tags[environment]",r.parameters.envName)),r.parameters.urlOverride&&e.property("url_override",r.parameters.urlOverride),e}function k$(r,{suiteId:e,suiteName:t,startedAt:n,finishedAt:o,runs:i,testsToSkip:a,quarantinedTestsToSkip:l,quarantinedTestReasons:c}){let s=r.testSuite().name(t);e&&s.property("id",e),s.timestamp(n).property("startedAt",n.toISOString()).property("finishedAt",o.toISOString()).time((o.getTime()-n.getTime())/1e3);for(let u of i){let d=s.testCase();D$(u,d)}for(let u of a){let d=s.testCase();d.name(u.name).className(u.name).file(Ap.relative(".",u.relativeFilePath)).property("id",u.id),u.baseUrl&&d.property("baseUrl",u.baseUrl),u.labels&&(d.property("labels",u.labels.join(",")),u.labels.forEach(p=>{d.property("dd_tags[label]",p)})),d.skipped()}for(let u of l){let d=s.testCase();d.name(u.name).className(u.name).file(Ap.relative(".",u.relativeFilePath)).property("id",u.id).property("quarantined","true");let p=c[u.id];p&&d.property("quarantinedReason",p),u.baseUrl&&d.property("baseUrl",u.baseUrl),u.labels&&(d.property("labels",u.labels.join(",")),u.labels.forEach(m=>{d.property("dd_tags[label]",m)})),d.skipped()}return s}function AM(r,e){let t=N$.newBuilder();k$(t,e),t.writeTo(Ap.join(r,`${e.suiteName}.xml`))}import U$ from"fs";import F$ from"path";function RM(r){return{title:So(r),duration:r.finishedAt.getTime()-r.startedAt.getTime(),error:r.status==="FAILED"?{value:r.failureReason}:void 0,steps:r.results&&r.type!=="PRESET_ACTION"?r.results.map(RM):[]}}async function B$(r,e,t,n){if(n.results?.length){let o=await vp(r,e,t,n.results[n.results.length-1].afterSnapshot);return o?[{name:"Final state screenshot",path:o,contentType:"image/jpeg"}]:[]}return[]}async function z$(r,e,t,n){return{status:n.status==="PASSED"?"passed":n.status==="CANCELLED"?"interrupted":"failed",duration:n.finishedAt.getTime()-n.lastAttemptStartedAt.getTime(),error:n.status==="FAILED"&&n.failureReason?{value:n.failureDetails?.classification?.reason||n.failureReason,message:n.failureDetails?.classification?.summary||ji[n.failureReason]}:void 0,retry:n.attempts-1,steps:n.results?.map(RM)||[],startTime:n.lastAttemptStartedAt.toISOString(),attachments:await B$(r,e,t,n)}}async function H$(r,e,t,n){return{expectedStatus:"passed",status:n.status==="PASSED"?"expected":"unexpected",results:[await z$(r,e,t,n)]}}async function G$(r,e,t,n){return{tags:[],title:n.test.name,ok:n.status==="PASSED",tests:[await H$(r,e,t,n)],id:n.runId,file:n.filePath}}function bS(r,e){return r.reduce((t,n)=>e(n)?t+1:t,0)}async function j$(r,e,t,n){return{suites:[{title:n.suiteName,file:n.projectConfigPath,specs:await Promise.all(n.runs.map(o=>G$(r,e,t,o)))}],errors:[],stats:{startTime:n.startedAt.toISOString(),duration:n.finishedAt.getTime()-n.startedAt.getTime(),expected:bS(n.runs,o=>o.status==="PASSED"),unexpected:bS(n.runs,o=>o.status!=="PASSED"),flaky:bS(n.runs,o=>!!o.isFlake),skipped:0}}}async function wM(r,e,t,n){let o=await j$(r,e,t,n);U$.writeFileSync(F$.join(t,`${n.suiteName}.json`),JSON.stringify(o,null,2))}async function CM(r,e,t,n,o){switch(V$(o)?W$(o).isDirectory()||(T.error(`The specified reporter output directory '${o}' exists on disk but is not a folder. Please move or delete the existing object or specify a different reporter path.`),process.exit(1)):(T.info(`Reporter output directory '${o}' does not exist on disk, creating it now...`),$$(o,{recursive:!0})),t){case"junit":AM(o,n);return;case"allure":case"allure-json":await vM(r,e,o,n);return;case"playwright-json":await wM(r,e,o,n);return;default:throw new Error(`Unknown reporter format requested: '${t}'`)}}import fW from"wait-on";import{execSync as q$}from"child_process";import{platform as K$}from"os";function vS(){return xM()?(T.dimmed("Setting device pixel ratio to 2 automatically since a Mac OS Retina screen was detected."),T.dimmed(`If you are using a low pixel-density monitor, you should manually set --pixel-ratio to 1 to avoid incorrect viewport calculations. Confirm your device's pixel-ratio at https://www.mydevice.io.
|
|
4400
4399
|
`),2):(T.dimmed("Setting device pixel ratio to 1."),T.dimmed(`If you are using Momentic on a high-pixel density (HiDPI) monitor, relaunch with the --pixel-ratio option to avoid incorrect viewport calculations. Confirm your device's pixel-ratio at https://www.mydevice.io.
|
|
4401
|
-
`),1)}function xM(){return K$()==="darwin"&&q$("system_profiler SPDisplaysDataType").toString().includes("Retina")}function AS(r){xM()&&r===1&&(T.warn("If you are using Momentic on a Retina screen, relaunch with the --pixel-ratio option to avoid incorrect viewport calculations."),T.warn("Confirm your device's pixel-ratio at https://www.mydevice.io."))}import Y$ from"@actions/exec";import X$ from"@actions/io";import J$ from"quote";import Q$ from"string-argv";async function _M(r,e=!0){let t=Q$(r),n=await X$.which(t[0],!0),o=t.slice(1),i=Y$.exec(J$(n),o,{delay:100});if(e)return i}import Z$ from"csv-parser";import{createReadStream as eW}from"fs";function RS(r){return new Promise((e,t)=>{let n=[];eW(r).pipe(Z$()).on("data",o=>n.push(o)).on("end",()=>e(n)).on("error",o=>t(o))})}import Rp from"semver";import{z as wp}from"zod";var $n="2.20.2",tW="https://registry.npmjs.org/momentic",rW=wp.object({versions:wp.record(wp.string(),wp.unknown()).optional()});async function IM(r){try{await nW(r)}catch(e){T.warn({err:e},"Failed to check CLI version against NPM servers")}}async function nW(r){if(!$n){r.warn("Unable to check CLI version because CLI_VERSION is not set");return}let e;for(let n=0;n<2;n++)try{let o=await G(fetch(tW),{milliseconds:5e3});if(!o.ok)throw new Error(`Got error status code ${o.statusText}`);let i=await o.json();e=rW.parse(i).versions;break}catch(o){r.warn({err:o},"Failed to fetch npm registry data")}if(!e){r.warn("Failed to fetch npm registry data. Skipping version check.");return}let t;for(let n of Object.keys(e))Rp.valid(n)&&(!t||Rp.gt(n,t))&&Rp.gt(n,$n)&&Rp.lt(n,"2.0.0")&&!n.includes("alpha")&&(t=n);t&&(T.warn(`Update available: v${$n} -> v${t}`),T.warn("This version may be missing critical fixes, features, and security updates."),T.warn(`Run "npx momentic@${t} -V" to update`))}async function Wn(){try{await G(Promise.all([Ub(),or.flush()]),{milliseconds:5e3})}catch{}}import{partition as oW}from"lodash-es";function Cp(r){return r.length===1?"test":"tests"}function MM(r){return r===1?"1 worker":`${r} workers`}function PM(r){r.length!==0&&(T.info(`Skipping ${r.length} disabled ${Cp(r)}:`),r.forEach(e=>{T.info(`${mt}- ${[e.relativeFilePath]}`)}),T.log(""))}function OM(r,e){r.length!==0&&(T.info(`Skipping ${r.length} quarantined ${Cp(r)}:`),r.forEach(t=>{T.info(`${mt}- ${[t.relativeFilePath]}: ${e[t.id]}`)}),T.log(""))}function iW(r,e){r.length!==0&&(T.info(`Running ${r.length} quarantined ${Cp(r)} with ${MM(e)}:`),r.forEach(t=>{T.info(`${mt}- ${[t.testDefinition.relativeFilePath]}${typeof t.inputIndex=="number"?` with input set ${t.inputIndex}`:""}`)}),T.log(""))}function aW(r,e,t){e.length===0&&r.length>0||(T.info(`Running ${e.length} ${Cp(e)} with ${MM(t)}:`),e.forEach(n=>{T.info(`${mt}- ${[n.testDefinition.relativeFilePath]}${typeof n.inputIndex=="number"?` with input set ${n.inputIndex}`:""}`)}),T.log(""))}function LM({logger:r,localTestsToRunWithInputs:e,parallel:t,shardCount:n,shardIndex:o}){r.info({tests:e.length,shardCount:n,shardIndex:o,parallel:t},"Running local tests");let[i,a]=oW(e,l=>l.quarantined);iW(i,t),aW(i,a,t)}import{cloneDeep as Xa}from"lodash-es";async function NM({orgId:r,codeEvalTools:e,logger:t,outputDefinitions:n,testContext:o}){let i={};for(let a of n){let{name:l,value:c}=a;i[l]=await fr({orgId:r,s:c,localTools:e,logger:t,context:o})}return i}async function DM({baseUrl:r,envName:e,testName:t,devicePixelRatio:n,apiClient:o,test:i,storageClient:a,codeEvalTools:l,generator:c,orgId:s,variables:u,logger:d,customHeaders:p,testInputs:m,localBrowserConfig:h,aiSettings:g,visualDiffScreenshotStorage:f}){let S=await Od({settings:h,customHeaders:p,envVariables:u,envName:e,testName:t,baseUrl:r,logger:d,localTools:l,orgId:s}),y={baseUrl:o.baseUrl,apiKey:o.apiKey,logger:ne},E=S.browserType??"Chromium";if(!Hb(E)){let w=`Browser ${E} is required by the test named ${i.name} but does not appear to be installed on this machine. Please install it using 'momentic install-browsers' before running tests. Attempting to continue...`;T.warn(w),ne.warn(w)}let R=await Ur.init({baseUrl:r,logger:d,userBrowserSettings:S,storage:a,enricher:new fo(y,c),contextArgs:{viewport:i.advanced.viewport??Gt,locale:i.advanced.locale??oo,geolocation:i.advanced.geolocation??ao,timezoneId:i.advanced.timezone??io,colorScheme:i.advanced.colorScheme,deviceScaleFactor:n},iconKnowledgeBase:null}),A=new Po({browser:R,generator:c,logger:d,orgId:s,options:{scratchPadId:void 0,slowMoMs:S.slowMoMs,autoFollowNewTabs:S.autoFollowNewTabs,useMemory:g.useMemory,aiPageFiltering:g.aiPageFiltering},storage:a,localCodeEvalTools:l,visualDiffScreenshotStorage:f}),C=new ar({baseUrl:r,currentUrl:A.browser.url(),variablesFromEnvironment:u,envName:e,testName:t});return i.parameters&&await Promise.all(i.parameters.map(async w=>{let{name:I,defaultValue:P,required:X}=w,q=m?.[I];X&&q===void 0&&(T.error(`Required parameter '${I}' is required by test '${i.name}' but not provided`),process.exit(1));let k=await fr({orgId:s,s:q??P,localTools:l,logger:d,context:ar.dummyContext(C.getEnvName())});C.setMomenticSystemVariable(I,k)})),{controller:A,context:C}}async function kM({testAdvancedSettings:r,orgSettings:e,logger:t}){if(r.failureRecovery===!1||r.failureRecovery===void 0&&!e?.failureRecovery)return!1;if(!ii){let n="This test is ineligible for failure recovery since this does not appear to be a CI environment";return t.warn(n),T.warn(n),!1}return!0}async function UM({attemptInputs:r,attemptFixtures:e,attemptMetadata:t}){let{orgId:n,runId:o}=t,{controller:i,context:a,codeEvalTools:l,storageClient:c,logger:s,usageTracker:u,tracer:d}=e,{test:p,orgSettings:m}=r;s.info(`Running test '${p.name}' locally (run link: https://app.momentic.ai/runs/${o})`);let h={controller:i,storage:c,usageTracker:u,context:a,logger:s,codeEvalTools:l},g={orgId:n,runId:o,testMetadata:p,steps:p.steps,beforeSteps:p.beforeSteps,afterSteps:p.afterSteps,orgSettings:m},f={collectDebugData:!0,reinitializeBrowser:!0,disableHealing:!await kM({testAdvancedSettings:p.advanced,orgSettings:m.ai,logger:s})};return await Pd({fixtures:h,inputs:g,options:f,callbacks:{step:{},test:{onTestComplete:async()=>{await i.browser.cleanup()}}},testParams:{tracer:d}})}async function FM(r){let{testDefinition:e,logger:t}=r,n=new Date;try{return await sW(r)}catch(o){let i="Fatal error running test";return T.error(`${i}: ${o.message}`),t.error({err:o},i),{results:[],parameters:r,failureReason:"UnknownError",failureDetails:{errorMessage:o.message,errorStack:o.stack},status:"FAILED",attempts:0,test:e,filePath:e.relativeFilePath,startedAt:n,lastAttemptStartedAt:n,finishedAt:new Date,outputs:{}}}}async function sW(r){let{testDefinition:e,project:t,apiClient:n,orgId:o,urlOverride:i,runSigIntHandlers:a,runGroupTracer:l,logger:c,gitMetadata:s,alwaysSaveCache:u,noCache:d,runId:p,testInputs:m,quarantined:h,quarantinedReason:g,usageTracker:f}=r,S=new aa(n,o),y=ma({orgId:o,client:n,gitMetadata:s,alwaysSaveCache:u,noCache:d}),E=Xa(e.steps),R=Xa(e.beforeSteps)??void 0,A=Xa(e.afterSteps)??void 0;try{await y.resolveStepCacheEntries({testId:e.id,stepLists:{steps:E,beforeSteps:R,afterSteps:A},schemaVersion:e.schemaVersion,logger:c})}catch(k){throw c.error({err:k},"Failed to resolve step cache entries"),new Error(`Failed to resolve step cache entries. Please ensure you are running using a supported version of Momentic. If you believe this is a Momentic issue, please contact Support with the following error: ${k}`)}let C=r.envName??cW(e),w,I={};if(C){try{w=nl(C,t,c)}catch(k){let ee=`Failed to resolve environment ${C} for test ${e.name}: ${k}`;throw new Error(ee)}I=w.variables}let P=e.baseUrl;if(i)P=i;else if(!P){let k=I[wt];typeof k=="string"&&(P=k)}if(!P){let k=`Cannot run test with no base URL and no ${wt} variable defined in its environment`;throw new Error(k)}let X=await l.startRun({logger:c,runId:p,originalSteps:{beforeSteps:e.beforeSteps,steps:e.steps,afterSteps:e.afterSteps},testId:e.id,testName:e.name,testDescription:e.description??void 0,testLabels:e.labels,baseUrl:P,environmentName:C,schemaVersion:e.schemaVersion,resolvedInputs:m,quarantined:h,quarantinedReason:g}),q=c.child(X.loggerBindings||{});Object.entries(X.envVarBindings||{}).forEach(([k,ee])=>{I[k]=ee});try{let k=await lW({...r,variables:I,envName:C,resolvedEnv:w,baseUrl:P,storageClient:S,tracer:X,logger:q,cacheStorage:y,stepsWithCaches:E,beforeStepsWithCaches:R,afterStepsWithCaches:A,usageTracker:f});return await X.finish({logger:c,status:k.status,finishedAt:k.finishedAt,failureDetails:k.failureDetails,failureReason:k.failureReason,isFlake:k.isFlake,failureRecoveryDetails:k.failureRecoveryDetails}),{runId:X.runId,...k}}finally{a?.pop()}}async function lW(r){let{testDefinition:e,stepsWithCaches:t,beforeStepsWithCaches:n,afterStepsWithCaches:o,project:i,regenerateGoldenFiles:a,apiClient:l,generator:c,baseUrl:s,storageClient:u,orgId:d,envName:p,urlOverride:m,customHeaders:h,testInputs:g,variables:f,resolvedEnv:S,retriesOverride:y,devicePixelRatio:E,logUpdate:R,tracer:A,logger:C,cacheStorage:w,gitMetadata:I,quarantined:P,quarantinedReason:X,usageTracker:q}=r,k=i.config.ai?.aiFailureAnalysis??!1,ee=new Date,z=new Ta(i,a),j={...i.config},he={envName:p,urlOverride:m,customHeaders:h,testInputs:g},$,rt=Math.abs(y??i.config.retries??e.retries??0),Ne=[];C.info({...I,labels:e.labels,name:e.name,cwd:process.cwd()},"Starting test run using CLI");for(let ct=0;ct<=rt;ct++){let kt=await A.startAttempt(),J=C.child(kt.loggerBindings||{}),we={...e,steps:Xa(t),beforeSteps:Xa(n),afterSteps:Xa(o)};ct!==0&&R("RETRY",`attempt ${ct+1}/${rt+1}`);let Er=new Date,Kn=j.advanced?.fakerConstantSeed,Yn=new mn({httpClient:new Lt({baseUrl:l.baseUrl,apiKey:l.apiKey,logger:J}),fakerSeed:Kn?ta:void 0}),Mp=kt;try{let{controller:Xt,context:zr}=await DM({baseUrl:s,envName:p,testName:we.name,apiClient:l,devicePixelRatio:E,logger:J,storageClient:u,codeEvalTools:Yn,test:we,generator:c,orgId:d,variables:f,customHeaders:h,testInputs:g,localBrowserConfig:{...i.config.browser||{},...S?.browser||{},...we.advanced},aiSettings:{...i.config.ai||{},...we.advanced||{}},visualDiffScreenshotStorage:z});$=await UM({attemptMetadata:{attemptNumber:ct+1,orgId:d,runId:A.runId},attemptFixtures:{logger:J,storageClient:u,usageTracker:q,codeEvalTools:Yn,apiClient:l,context:zr,controller:Xt,tracer:kt},attemptInputs:{test:we,orgSettings:j}});let Fo=new Date,tn={logger:C,cacheStorage:w,orgId:d,testId:e.id,originalSteps:{steps:e.steps,beforeSteps:e.beforeSteps,afterSteps:e.afterSteps},updatedSteps:{steps:we.steps,beforeSteps:we.beforeSteps,afterSteps:we.afterSteps}};$?.status==="PASSED"?await fu(tn):$?.status==="FAILED"&&await Su(tn),await kt.finish({logger:J,result:$}),Ne.unshift($.status);let Bo=await NM({orgId:d,codeEvalTools:Yn,logger:J,outputDefinitions:e.outputs??[],testContext:zr}),W=dE(Ne),Ni=ct+1;if($.status!=="FAILED")return{...$,parameters:he,test:we,filePath:we.relativeFilePath,startedAt:ee,lastAttemptStartedAt:Er,finishedAt:Fo,attempts:Ni,baseUrl:s,outputs:Bo,isFlake:W,quarantined:P,quarantinedReason:X};let Di=$.failedStepResult,_n=Di?.message||"Unknown failure",Hr=Di?.failureReason??Ly(_n)??"UnknownError",Pp=J.child({errResult:Di,failureReason:Hr,errorMessage:_n,numAttempts:rt+1,name:we.name});if(ct<rt){Pp.warn(`Retrying failed execution attempt for run: ${_n}`);continue}Pp.error(`Test failed after all exhausting attempts: ${_n}`);let Vl=new Error(_n),Ut={errorMessage:_n,errorStack:Vl.stack},zo;if(k){let Xn;try{if($.results&&$.results.length>0){let{classification:It,aiFailureReason:In}=await Gv({logger:J,browserStateStorage:Mp,generator:c,fullResults:$,failureReason:Hr,error:Vl,maxItemsFromEnd:void 0,numStepsWithScreenshots:void 0,disableCache:!1});Xn=It,zo=In}}catch(It){J.warn({err:It},"Failed to classify test results")}Xn&&(Ut.classification=Xn,Hr=zo??Hr)}return{...$,parameters:he,failureDetails:Ut,failureReason:Hr,test:we,filePath:we.relativeFilePath,startedAt:ee,lastAttemptStartedAt:Er,finishedAt:Fo,attempts:ct+1,baseUrl:s,outputs:Bo,quarantined:P,quarantinedReason:X}}catch(Xt){Za(Xt);let zr=`Encountered fatal platform error while running test '${we.name}': ${Xt}`,Fo=new Date,tn=ct+1;J.error({err:Xt},zr),T.error(zr);let Bo={errorMessage:Xt.message,errStack:Xt.stack},W={status:"FAILED",failureDetails:Bo,failureReason:"InternalPlatformError",finishedAt:Fo};return await kt.finish({logger:J,result:{status:"FAILED",results:[]}}),{...W,results:[],parameters:he,test:we,filePath:we.relativeFilePath,startedAt:ee,lastAttemptStartedAt:Er,finishedAt:new Date,attempts:tn,baseUrl:s,outputs:{},quarantined:P,quarantinedReason:X}}}throw new Error("This code should not be reachable")}function cW(r){for(let e of r.envs??[])if(e.default)return e.name}import uW from"adm-zip";import{randomUUID as dW}from"crypto";var qn="assets";function pW(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 mW(r){switch(r){case"SUCCESS":return"PASSED";case"FAILED":return"FAILED";case"CANCELLED":return"CANCELLED";case"RUNNING":return"RUNNING";case"IDLE":return"PENDING"}}var wS=class{constructor(e,t,n,o,i){this.orgId=e;this.testId=t;this.testName=n;this.metadata=o;this.diskStorage=i}children=[];finished=!1;getParentStepIdChain(){return[]}attachBeforeScreenshot(e){let{snapshotId:t,screenshot:n}=e;this.metadata.beforeSnapshotId=t,this.diskStorage.storeFile({name:`${qn}/${t}.jpeg`,contents:n})}attachAfterScreenshot(e){let{snapshotId:t,screenshot:n}=e;this.metadata.afterSnapshotId=t,this.diskStorage.storeFile({name:`${qn}/${t}.jpeg`,contents:n})}attachBeforeHtmlSnapshot(e){let{snapshotId:t,html:n}=e;this.metadata.beforeSnapshotId=t,this.diskStorage.storeFile({name:`${qn}/${t}.html`,contents:n})}attachAfterHtmlSnapshot(e){let{snapshotId:t,html:n}=e;this.metadata.afterSnapshotId=t,this.diskStorage.storeFile({name:`${qn}/${t}.html`,contents:n})}recordTargetAutoHeal(e){let{healType:t}=e,n=t==="AI"?"ai-target-heal":"cache-heal";or.increment("test_event",1,[`name:${n}`,`orgId:${this.orgId}`]),this.metadata.healMetadata={healType:t,healedAt:new Date}}recordStepDuration(e){let t=e.step.type!=="PRESET_ACTION"?e.step.type:e.step.command.type;or.distribution("test_step_duration",e.durationMs,[`type:${t}`,"platform:browser","executor:cli",`orgId:${this.orgId}`])}async finishInternal(e){this.finished||(this.finished=!0,await Promise.all(this.children.map(t=>t.finish({status:mW(e.status),finishedAt:e.finishedAt}))))}async finish(e){await this.finishInternal(e.step)}async startSubSteps(){let e=new Ja(this.orgId,this.testId,this.testName,this.diskStorage);return this.children.push(e),e}},Ja=class{constructor(e,t,n,o){this.orgId=e;this.testId=t;this.testName=n;this.diskStorage=o}children=[];finished=!1;stepFrequenciesByType={};async getScreenshot(e,t){return this.diskStorage.readFile(`${qn}/${t}.jpeg`)}async getHtmlSnapshot(e,t){return this.diskStorage.readFile(`${qn}/${t}.html`)?.toString()}getParentStepIdChain(){return[]}recordStepStat(e){e.type!=="PRESET_ACTION"?this.stepFrequenciesByType[e.type]=(this.stepFrequenciesByType[e.type]||0)+1:this.stepFrequenciesByType[e.command.type]=(this.stepFrequenciesByType[e.command.type]||0)+1}sendFinalizedStepStats(){for(let[e,t]of Object.entries(this.stepFrequenciesByType))or.increment("test_step_execution",t,[`type:${e}`,"platform:browser","executor:cli",`orgId:${this.orgId}`])}async startStep(e){let{step:t}=e;this.recordStepStat(t);let n={step:t,status:"RUNNING",startedAt:new Date},o=new wS(this.orgId,this.testId,this.testName,n,this.diskStorage);return this.children.push(o),o}async finish(e){this.finished||(this.finished=!0,await Promise.all(this.children.map(t=>t.finishInternal({status:pW(e.status),finishedAt:e.finishedAt}))),this.sendFinalizedStepStats())}},CS=class{constructor(e,t,n,o,i,a){this.orgId=e;this.testId=t;this.testName=n;this.runAttemptId=o;this.metadata=i;this.diskStorage=a;this.diskStorage.mkdir("assets")}finished=!1;children=[];get loggerBindings(){return{runAttemptId:this.runAttemptId}}attachNetworkLogs(e){let{logs:t}=e;this.diskStorage.storeFile({name:"network.har",contents:JSON.stringify(t,null,2)})}attachConsoleLogs(e){let{logs:t}=e;this.diskStorage.storeFile({name:"console.json",contents:JSON.stringify(t,null,2)})}attachBrowserCrashDump(e){let{crashReportDirFetcher:t,logger:n}=e,o=t();if(!o)return;let i=new uW;i.addLocalFolder(o,void 0,a=>a!==".DS_Store"),this.diskStorage.storeFile({name:`${qn}/${ah}`,contents:i.toBuffer()}),n.info({browserCrashZipName:ah},"Attached browser crash ZIP")}async finish(e){if(this.finished)return;this.finished=!0;let{logger:t,result:n}=e,o={...this.metadata,status:n.status,finishedAt:new Date,results:pu(n.results,t),beforeResults:n.beforeResults?pu(n.beforeResults,t):void 0,afterResults:n.afterResults?pu(n.afterResults,t):void 0};await Promise.all(this.children.map(i=>i.finish({status:o.status,finishedAt:o.finishedAt}))),this.diskStorage.storeFile({name:"metadata.json",contents:JSON.stringify(o,null,2)})}async startBeforeStepList(){let e=new Ja(this.orgId,this.testId,this.testName,this.diskStorage);return this.children.push(e),e}async startMainStepList(){let e=new Ja(this.orgId,this.testId,this.testName,this.diskStorage);return this.children.push(e),e}async startAfterStepList(){let e=new Ja(this.orgId,this.testId,this.testName,this.diskStorage);return this.children.push(e),e}async getScreenshot(e,t){return this.diskStorage.readFile(`${qn}/${t}.jpeg`)}async getHtmlSnapshot(e,t){return this.diskStorage.readFile(`${qn}/${t}.html`)?.toString()}},xS=class{constructor(e,t,n,o,i,a){this.orgId=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}}get envVarBindings(){return{[rx]: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,result:{status:t.status,results:[],beforeResults:[],afterResults:[]}}))),this.diskStorage.storeFile({name:"metadata.json",contents:JSON.stringify(t,null,2)}),this.diskStorage.close()}async startAttempt(){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 e=this.diskStorage.cd(`attempts/${this.metadata.attempts}`),t=dW(),n={id:t,schemaVersion:ue,runAttemptSchemaVersion:Rb,startedAt:new Date,status:"RUNNING"};e.storeFile({name:"metadata.json",contents:JSON.stringify(n,null,2)});let o=new CS(this.orgId,this.testId,this.testName,t,n,e);return this.children.push(o),o}},xp=class r{constructor(e,t,n,o){this.orgId=e;this.runGroupId=t;this.metadata=n;this.diskStorage=o}children=[];finished=!1;get loggerBindings(){return{orgId:this.orgId,runGroupId:this.runGroupId,branch:this.metadata.gitBranchName}}static async start(e,t,n,o,i){let a={...o,id:t,trigger:Rr.CLI,startedAt:new Date,status:"RUNNING",cliVersion:$n,labels:i??[]},l=new al(n);return l.storeFile({name:"metadata.json",contents:JSON.stringify(a,null,2)}),new r(e,t,a,l)}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",resolvedBaseUrl:e.baseUrl,environmentName:e.environmentName,resolvedInputs:e.resolvedInputs,cliVersion:$n,schemaVersion:e.schemaVersion,startedAt:new Date,attempts:0,quarantined:e.quarantined??!1,quarantinedReason:e.quarantinedReason,executionType:"WEB"};t.storeFile({name:"metadata.json",contents:JSON.stringify(n,null,2)});let o=new xS(this.orgId,e.testId,e.testName,e.runId,n,t);return this.children.push(o),o}};async function BM(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 zM(r){let{logger:e,tests:t,yes:n,start:o,waitOn:i,client:a,debugDataStorage:l,project:c,retriesOverride:s,urlOverride:u,envName:d,orgId:p,devicePixelRatio:m,customHeaders:h,testInputMatrix:g,reporter:f,include:S,exclude:y,labels:E,reporterDir:R=aA,outputDir:A=sA,uploadResults:C=!1,waitOnTimeout:w=60,parallel:I,shardIndex:P=1,shardCount:X=1,regenerateGoldenFiles:q,gitMetadata:k,alwaysSaveCache:ee,noCache:z,ignoreQuarantine:j,skipQuarantined:he,onlyQuarantined:$,runGroupId:rt}=r;o&&(e.info({orgId:p},`Executing start command: ${o}`),await _M(o,!1)),i&&(e.info({orgId:p},`Waiting for url: ${i} with timeout: ${w} seconds.`),await fW({resources:[i],interval:2500,timeout:w*1e3,headers:{Accept:"*/*"},followRedirect:!0,verbose:!1,log:!0,strictSSL:!1}));let Ne=new Dn(c.config.ai?.agentConfig,{baseUrl:a.baseUrl,apiKey:a.apiKey,logger:e}),ct=await Y(c),kt=await Ka({tests:t,momenticFiles:ct,yes:n,project:c,include:S,exclude:y,labels:E,logger:T}),J=await BM(e,a,j),{testsToSkip:we,quarantinedTestsToSkip:Er,testsToRun:Kn,quarantinedTestsToRun:Yn}=hM({testDefinitions:kt,quarantinedTestReasons:J,onlyQuarantined:$,skipQuarantined:he});PM(we),OM(Er,J);let Mp=gM({testsToRun:Kn,quarantinedTestsToRun:Yn,quarantinedTestReasons:J,testInputMatrix:g}),Xt=yW({globalTestsToRunWithInputs:Mp,shardIndex:P,shardCount:X});LM({logger:e,localTestsToRunWithInputs:Xt,parallel:I,shardCount:X,shardIndex:P});let zr=[],Fo=new Date,tn=new Set,Bo=async()=>{let Ut=a.getAppUrl(),zo=ia({results:zr,startTime:Fo.getTime(),onFailed:It=>{Zc(It,It.filePath)},getDisplayLine:It=>{let In=`${mt}- ${It.filePath}${It.failureRecoveryDetails?" [recovered] ":""}`;return It.runId&&(In+=` ( link when uploaded: ${Ut}/runs/${It.runId} )`),In},entity:"test"}),Xn=zr.filter(It=>!!It.failureRecoveryDetails?.attempts);return Xn.length>0&&T.warn(`Our AI agent automatically prevented ${Xn.length} tests from failing due to transient issues. Use the run links above to review the additional steps that were executed.`),T.log(""),C?(T.success(`Test results have been saved to the folder ${A}. Uploading to Momentic Cloud...`),await Mu({client:a,consoleLogger:T,resultsPath:A})):T.success(`Test results have been saved to the folder ${A}. Upload them to Momentic Cloud by running 'npx momentic results upload ${A}'.`),zo};gW.existsSync(A)&&T.warn(`Output directory ${A} already exists, removing before test execution...`);let W=await xp.start(p,rt,A,k,E),Ni=e.child(W.loggerBindings||{}),Di=[],_n=async()=>{T.warn("SIGINT received. Stopping tests and printing latest results..."),await W.finish({logger:Ni,status:"CANCELLED"}),await Bo(),await Promise.allSettled(Di.map(Ut=>Ut())),await Wn(),process.exit(1)};process.once("SIGINT",_n);let Hr={};for(let Ut=0;Ut<Xt.length;Ut++){let zo=Object.values(Hr);zo.length===I&&await Promise.race(zo.map(In=>In.promise));let Xn=Xt[Ut],It=`test-${Ut}`;Hr[It]={done:!1,promise:(async({inputs:In,quarantined:WM,quarantinedReason:qM,testDefinition:Ho})=>{tn.add({inputs:In});let $l=Ho.relativeFilePath.includes("..")?Ho.fullFilePath:Ho.relativeFilePath;Gs({status:"START",testLogRef:$l,getRunningTestsCount:()=>tn.size,getTotalTestsCount:()=>Xt.length});let KM=setInterval(()=>Gs({status:"RUN",testLogRef:$l,getRunningTestsCount:()=>tn.size,getTotalTestsCount:()=>Xt.length}),5*60*1e3),Op=hW(),Lp=Ni.child({testId:Ho.id,runId:Op}),PS=new vu({logger:Lp,reporter:new tu(a),runType:"test-run",runId:Op,testMetadata:Ho,suiteMetadata:void 0});try{let Qa=await FM({testDefinition:Ho,project:c,testInputs:In,quarantined:WM,quarantinedReason:qM,orgId:p,runId:Op,devicePixelRatio:m,apiClient:a,runGroupTracer:W,generator:Ne,retriesOverride:s,urlOverride:u,envName:d,customHeaders:h,regenerateGoldenFiles:q,logUpdate:(Wl,YM)=>Gs({status:Wl,testLogRef:$l,getRunningTestsCount:()=>tn.size,getTotalTestsCount:()=>Xt.length,additionalText:YM}),runSigIntHandlers:Di,logger:Lp,gitMetadata:k,alwaysSaveCache:ee,noCache:z,usageTracker:PS});Gs({status:Qa.status,testLogRef:$l,getRunningTestsCount:()=>tn.size,getTotalTestsCount:()=>Xt.length}),zr.push(Qa)}catch(Qa){let Wl=`Encountered unexpected fatal error when running test '${Ho.name}': ${Qa.message}`;T.error(Wl),Lp.error({err:Qa},Wl)}finally{clearInterval(KM),Hr[It].done=!0,delete Hr[It]}await PS.flush(e)})(Xn)}}await Promise.allSettled(Object.values(Hr).map(Ut=>Ut.promise));let Vl=zr.some(Ut=>!Ut.quarantined&&Ut.status==="FAILED")?"FAILED":"PASSED";return await W.finish({logger:Ni,status:Vl}),process.off("SIGINT",_n),f&&await CM(Ni,l,f,{projectConfigPath:c.configFilePath,suiteName:c.config.name,startedAt:Fo,finishedAt:new Date,runs:zr,testsToSkip:we,quarantinedTestsToSkip:Er,quarantinedTestReasons:J},R),Bo()}function SW(r,e,t){if(t>r.length&&(T.warn(`Shard count ${t} is greater than the number of tests ${r.length}! Some workers won't have any tests to run.`),t=Math.max(t,r.length),e>t))return[];let n=Math.floor((e-1)*(r.length/t)),o=Math.floor(e*(r.length/t));return r.sort().filter((a,l)=>l>=n&&l<o)}function yW({globalTestsToRunWithInputs:r,shardIndex:e,shardCount:t}){return t&&t>1?SW(r,e,t):r}Np||ne.warn("Sentry is not enabled in this environment due to unsupported node version");YC({serviceName:"cli"});var GM=process.argv.some(r=>r.includes("--log-level"))&&process.argv.some(r=>r.includes("debug")),_S=r=>{GM&&T.dimmed(r)};GM&&jb(ne);var Yt=new EW;Yt.name("momentic").description("Momentic CLI").version($n);Yt.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: ${ph.join(", ")}.`).action(async(r,e)=>{!e.all&&r.length===0&&(T.error("No browsers specified"),process.exit(1)),await Gb({rawBrowsers:r,force:e.force,all:e.all})});Yt.addOption(new pr("--log-level <level>").choices(["debug","info","warn","error"]).default("info")).on("option:log-level",r=>{r==="debug"&&T.info("Enabling debug logging"),T.setMinLevel(r.toLowerCase())});Yt.addOption(new pr("--verbose","enable verbose logging")).on("option:verbose",()=>{ne.enableConsoleLogs(),T.setMinLevel(20)});var IS=Yt.command("checks").alias("check").description("Perform various project checks");IS.command("config").addOption(dr).action(async r=>{await vt({configFilePath:r.config})});IS.command("duplicate-ids").description("Checks if any steps in your entire Momentic test repository share the same ID.").addOption(dr).addOption(rM).action(async r=>{let e=await vt({configFilePath:r.config});await GI({project:e,fix:r.fix})});IS.command("duplicate-names").description("Checks if tests or modules with duplicate names or ids exist").addOption(dr).action(async r=>{let e=await vt({configFilePath:r.config});await jI({project:e})});var jM=Yt.command("migrate").description("Migrate and upgrade tooling");jM.command("steps").description("Migrate steps in all tests and modules to the latest schema version. Note that this is always done when a test is loaded through the interactive editor, so is generally not needed.").addOption(dr).action(async r=>{let e=await vt({configFilePath:r.config});await dM(e)});jM.command("v1-v2").description("Migrate from v1 of the Momentic CLI to v2").addOption(Br).addOption(dr).addOption(Fr).addOption(Uo).action(async r=>{!r.yes&&!await Pt("This command will modify your existing Momentic configuration. Please backup your local directory using Git or another version control system before proceeding. Continue?")&&process.exit(1);let e=await vt({configFilePath:r.config}),t=new Ze({baseUrl:r.server,apiKey:r.apiKey,logger:ne}),{orgId:n}=await t.getAuthInfo();await pM({project:e,orgId:n,apiClient:t}),process.exit(0)});Yt.command("import").addOption(Fr).addOption(Br).addOption(dr).addOption(Uo).addArgument(sM).action(async(r,e)=>{let{apiKey:t,server:n,config:o,yes:i}=e,a=await vt({configFilePath:o}),l=new Ze({baseUrl:n,apiKey:t,logger:ne});!r||r.length===0?await KI({client:l,project:a,skipPrompts:i}):await YI({client:l,project:a,paths:r,skipPrompts:i}),process.exit(0)});Yt.command("init").description("Initialize an empty Momentic project in the current working directory").addOption(new pr("--name <name>","Name of the project")).action(async r=>{T.info(`Welcome to the Momentic project setup wizard! \u{1F680}
|
|
4400
|
+
`),1)}function xM(){return K$()==="darwin"&&q$("system_profiler SPDisplaysDataType").toString().includes("Retina")}function AS(r){xM()&&r===1&&(T.warn("If you are using Momentic on a Retina screen, relaunch with the --pixel-ratio option to avoid incorrect viewport calculations."),T.warn("Confirm your device's pixel-ratio at https://www.mydevice.io."))}import Y$ from"@actions/exec";import X$ from"@actions/io";import J$ from"quote";import Q$ from"string-argv";async function _M(r,e=!0){let t=Q$(r),n=await X$.which(t[0],!0),o=t.slice(1),i=Y$.exec(J$(n),o,{delay:100});if(e)return i}import Z$ from"csv-parser";import{createReadStream as eW}from"fs";function RS(r){return new Promise((e,t)=>{let n=[];eW(r).pipe(Z$()).on("data",o=>n.push(o)).on("end",()=>e(n)).on("error",o=>t(o))})}import Rp from"semver";import{z as wp}from"zod";var $n="2.20.3",tW="https://registry.npmjs.org/momentic",rW=wp.object({versions:wp.record(wp.string(),wp.unknown()).optional()});async function IM(r){try{await nW(r)}catch(e){T.warn({err:e},"Failed to check CLI version against NPM servers")}}async function nW(r){if(!$n){r.warn("Unable to check CLI version because CLI_VERSION is not set");return}let e;for(let n=0;n<2;n++)try{let o=await G(fetch(tW),{milliseconds:5e3});if(!o.ok)throw new Error(`Got error status code ${o.statusText}`);let i=await o.json();e=rW.parse(i).versions;break}catch(o){r.warn({err:o},"Failed to fetch npm registry data")}if(!e){r.warn("Failed to fetch npm registry data. Skipping version check.");return}let t;for(let n of Object.keys(e))Rp.valid(n)&&(!t||Rp.gt(n,t))&&Rp.gt(n,$n)&&Rp.lt(n,"2.0.0")&&!n.includes("alpha")&&(t=n);t&&(T.warn(`Update available: v${$n} -> v${t}`),T.warn("This version may be missing critical fixes, features, and security updates."),T.warn(`Run "npx momentic@${t} -V" to update`))}async function Wn(){try{await G(Promise.all([Ub(),or.flush()]),{milliseconds:5e3})}catch{}}import{partition as oW}from"lodash-es";function Cp(r){return r.length===1?"test":"tests"}function MM(r){return r===1?"1 worker":`${r} workers`}function PM(r){r.length!==0&&(T.info(`Skipping ${r.length} disabled ${Cp(r)}:`),r.forEach(e=>{T.info(`${mt}- ${[e.relativeFilePath]}`)}),T.log(""))}function OM(r,e){r.length!==0&&(T.info(`Skipping ${r.length} quarantined ${Cp(r)}:`),r.forEach(t=>{T.info(`${mt}- ${[t.relativeFilePath]}: ${e[t.id]}`)}),T.log(""))}function iW(r,e){r.length!==0&&(T.info(`Running ${r.length} quarantined ${Cp(r)} with ${MM(e)}:`),r.forEach(t=>{T.info(`${mt}- ${[t.testDefinition.relativeFilePath]}${typeof t.inputIndex=="number"?` with input set ${t.inputIndex}`:""}`)}),T.log(""))}function aW(r,e,t){e.length===0&&r.length>0||(T.info(`Running ${e.length} ${Cp(e)} with ${MM(t)}:`),e.forEach(n=>{T.info(`${mt}- ${[n.testDefinition.relativeFilePath]}${typeof n.inputIndex=="number"?` with input set ${n.inputIndex}`:""}`)}),T.log(""))}function LM({logger:r,localTestsToRunWithInputs:e,parallel:t,shardCount:n,shardIndex:o}){r.info({tests:e.length,shardCount:n,shardIndex:o,parallel:t},"Running local tests");let[i,a]=oW(e,l=>l.quarantined);iW(i,t),aW(i,a,t)}import{cloneDeep as Xa}from"lodash-es";async function NM({orgId:r,codeEvalTools:e,logger:t,outputDefinitions:n,testContext:o}){let i={};for(let a of n){let{name:l,value:c}=a;i[l]=await fr({orgId:r,s:c,localTools:e,logger:t,context:o})}return i}async function DM({baseUrl:r,envName:e,testName:t,devicePixelRatio:n,apiClient:o,test:i,storageClient:a,codeEvalTools:l,generator:c,orgId:s,variables:u,logger:d,customHeaders:p,testInputs:m,localBrowserConfig:h,aiSettings:g,visualDiffScreenshotStorage:f}){let y=await Od({settings:h,customHeaders:p,envVariables:u,envName:e,testName:t,baseUrl:r,logger:d,localTools:l,orgId:s}),S={baseUrl:o.baseUrl,apiKey:o.apiKey,logger:ne},E=y.browserType??"Chromium";if(!Hb(E)){let w=`Browser ${E} is required by the test named ${i.name} but does not appear to be installed on this machine. Please install it using 'momentic install-browsers' before running tests. Attempting to continue...`;T.warn(w),ne.warn(w)}let R=await Ur.init({baseUrl:r,logger:d,userBrowserSettings:y,storage:a,enricher:new fo(S,c),contextArgs:{viewport:i.advanced.viewport??Gt,locale:i.advanced.locale??oo,geolocation:i.advanced.geolocation??ao,timezoneId:i.advanced.timezone??io,colorScheme:i.advanced.colorScheme,deviceScaleFactor:n},iconKnowledgeBase:null}),A=new Po({browser:R,generator:c,logger:d,orgId:s,options:{scratchPadId:void 0,slowMoMs:y.slowMoMs,autoFollowNewTabs:y.autoFollowNewTabs,useMemory:g.useMemory,aiPageFiltering:g.aiPageFiltering},storage:a,localCodeEvalTools:l,visualDiffScreenshotStorage:f}),C=new ar({baseUrl:r,currentUrl:A.browser.url(),variablesFromEnvironment:u,envName:e,testName:t});return i.parameters&&await Promise.all(i.parameters.map(async w=>{let{name:I,defaultValue:P,required:X}=w,q=m?.[I];X&&q===void 0&&(T.error(`Required parameter '${I}' is required by test '${i.name}' but not provided`),process.exit(1));let k=await fr({orgId:s,s:q??P,localTools:l,logger:d,context:ar.dummyContext(C.getEnvName())});C.setMomenticSystemVariable(I,k)})),{controller:A,context:C}}async function kM({testAdvancedSettings:r,orgSettings:e,logger:t}){if(r.failureRecovery===!1||r.failureRecovery===void 0&&!e?.failureRecovery)return!1;if(!ii){let n="This test is ineligible for failure recovery since this does not appear to be a CI environment";return t.warn(n),T.warn(n),!1}return!0}async function UM({attemptInputs:r,attemptFixtures:e,attemptMetadata:t}){let{orgId:n,runId:o}=t,{controller:i,context:a,codeEvalTools:l,storageClient:c,logger:s,usageTracker:u,tracer:d}=e,{test:p,orgSettings:m}=r;s.info(`Running test '${p.name}' locally (run link: https://app.momentic.ai/runs/${o})`);let h={controller:i,storage:c,usageTracker:u,context:a,logger:s,codeEvalTools:l},g={orgId:n,runId:o,testMetadata:p,steps:p.steps,beforeSteps:p.beforeSteps,afterSteps:p.afterSteps,orgSettings:m},f={collectDebugData:!0,reinitializeBrowser:!0,disableHealing:!await kM({testAdvancedSettings:p.advanced,orgSettings:m.ai,logger:s})};return await Pd({fixtures:h,inputs:g,options:f,callbacks:{step:{},test:{onTestComplete:async()=>{await i.browser.cleanup()}}},testParams:{tracer:d}})}async function FM(r){let{testDefinition:e,logger:t}=r,n=new Date;try{return await sW(r)}catch(o){let i="Fatal error running test";return T.error(`${i}: ${o.message}`),t.error({err:o},i),{results:[],parameters:r,failureReason:"UnknownError",failureDetails:{errorMessage:o.message,errorStack:o.stack},status:"FAILED",attempts:0,test:e,filePath:e.relativeFilePath,startedAt:n,lastAttemptStartedAt:n,finishedAt:new Date,outputs:{}}}}async function sW(r){let{testDefinition:e,project:t,apiClient:n,orgId:o,urlOverride:i,runSigIntHandlers:a,runGroupTracer:l,logger:c,gitMetadata:s,alwaysSaveCache:u,noCache:d,runId:p,testInputs:m,quarantined:h,quarantinedReason:g,usageTracker:f}=r,y=new aa(n,o),S=ma({orgId:o,client:n,gitMetadata:s,alwaysSaveCache:u,noCache:d}),E=Xa(e.steps),R=Xa(e.beforeSteps)??void 0,A=Xa(e.afterSteps)??void 0;try{await S.resolveStepCacheEntries({testId:e.id,stepLists:{steps:E,beforeSteps:R,afterSteps:A},schemaVersion:e.schemaVersion,logger:c})}catch(k){throw c.error({err:k},"Failed to resolve step cache entries"),new Error(`Failed to resolve step cache entries. Please ensure you are running using a supported version of Momentic. If you believe this is a Momentic issue, please contact Support with the following error: ${k}`)}let C=r.envName??cW(e),w,I={};if(C){try{w=nl(C,t,c)}catch(k){let ee=`Failed to resolve environment ${C} for test ${e.name}: ${k}`;throw new Error(ee)}I=w.variables}let P=e.baseUrl;if(i)P=i;else if(!P){let k=I[wt];typeof k=="string"&&(P=k)}if(!P){let k=`Cannot run test with no base URL and no ${wt} variable defined in its environment`;throw new Error(k)}let X=await l.startRun({logger:c,runId:p,originalSteps:{beforeSteps:e.beforeSteps,steps:e.steps,afterSteps:e.afterSteps},testId:e.id,testName:e.name,testDescription:e.description??void 0,testLabels:e.labels,baseUrl:P,environmentName:C,schemaVersion:e.schemaVersion,resolvedInputs:m,quarantined:h,quarantinedReason:g}),q=c.child(X.loggerBindings||{});Object.entries(X.envVarBindings||{}).forEach(([k,ee])=>{I[k]=ee});try{let k=await lW({...r,variables:I,envName:C,resolvedEnv:w,baseUrl:P,storageClient:y,tracer:X,logger:q,cacheStorage:S,stepsWithCaches:E,beforeStepsWithCaches:R,afterStepsWithCaches:A,usageTracker:f});return await X.finish({logger:c,status:k.status,finishedAt:k.finishedAt,failureDetails:k.failureDetails,failureReason:k.failureReason,isFlake:k.isFlake,failureRecoveryDetails:k.failureRecoveryDetails}),{runId:X.runId,...k}}finally{a?.pop()}}async function lW(r){let{testDefinition:e,stepsWithCaches:t,beforeStepsWithCaches:n,afterStepsWithCaches:o,project:i,regenerateGoldenFiles:a,apiClient:l,generator:c,baseUrl:s,storageClient:u,orgId:d,envName:p,urlOverride:m,customHeaders:h,testInputs:g,variables:f,resolvedEnv:y,retriesOverride:S,devicePixelRatio:E,logUpdate:R,tracer:A,logger:C,cacheStorage:w,gitMetadata:I,quarantined:P,quarantinedReason:X,usageTracker:q}=r,k=i.config.ai?.aiFailureAnalysis??!1,ee=new Date,z=new Ta(i,a),j={...i.config},he={envName:p,urlOverride:m,customHeaders:h,testInputs:g},$,rt=Math.abs(S??i.config.retries??e.retries??0),Ne=[];C.info({...I,labels:e.labels,name:e.name,cwd:process.cwd()},"Starting test run using CLI");for(let ct=0;ct<=rt;ct++){let kt=await A.startAttempt(),J=C.child(kt.loggerBindings||{}),we={...e,steps:Xa(t),beforeSteps:Xa(n),afterSteps:Xa(o)};ct!==0&&R("RETRY",`attempt ${ct+1}/${rt+1}`);let Er=new Date,Kn=j.advanced?.fakerConstantSeed,Yn=new mn({httpClient:new Lt({baseUrl:l.baseUrl,apiKey:l.apiKey,logger:J}),fakerSeed:Kn?ta:void 0}),Mp=kt;try{let{controller:Xt,context:zr}=await DM({baseUrl:s,envName:p,testName:we.name,apiClient:l,devicePixelRatio:E,logger:J,storageClient:u,codeEvalTools:Yn,test:we,generator:c,orgId:d,variables:f,customHeaders:h,testInputs:g,localBrowserConfig:{...i.config.browser||{},...y?.browser||{},...we.advanced},aiSettings:{...i.config.ai||{},...we.advanced||{}},visualDiffScreenshotStorage:z});$=await UM({attemptMetadata:{attemptNumber:ct+1,orgId:d,runId:A.runId},attemptFixtures:{logger:J,storageClient:u,usageTracker:q,codeEvalTools:Yn,apiClient:l,context:zr,controller:Xt,tracer:kt},attemptInputs:{test:we,orgSettings:j}});let Fo=new Date,tn={logger:C,cacheStorage:w,orgId:d,testId:e.id,originalSteps:{steps:e.steps,beforeSteps:e.beforeSteps,afterSteps:e.afterSteps},updatedSteps:{steps:we.steps,beforeSteps:we.beforeSteps,afterSteps:we.afterSteps}};$?.status==="PASSED"?await fu(tn):$?.status==="FAILED"&&await Su(tn),await kt.finish({logger:J,result:$}),Ne.unshift($.status);let Bo=await NM({orgId:d,codeEvalTools:Yn,logger:J,outputDefinitions:e.outputs??[],testContext:zr}),W=dE(Ne),Ni=ct+1;if($.status!=="FAILED")return{...$,parameters:he,test:we,filePath:we.relativeFilePath,startedAt:ee,lastAttemptStartedAt:Er,finishedAt:Fo,attempts:Ni,baseUrl:s,outputs:Bo,isFlake:W,quarantined:P,quarantinedReason:X};let Di=$.failedStepResult,_n=Di?.message||"Unknown failure",Hr=Di?.failureReason??Ly(_n)??"UnknownError",Pp=J.child({errResult:Di,failureReason:Hr,errorMessage:_n,numAttempts:rt+1,name:we.name});if(ct<rt){Pp.warn(`Retrying failed execution attempt for run: ${_n}`);continue}Pp.error(`Test failed after all exhausting attempts: ${_n}`);let Vl=new Error(_n),Ut={errorMessage:_n,errorStack:Vl.stack},zo;if(k){let Xn;try{if($.results&&$.results.length>0){let{classification:It,aiFailureReason:In}=await Gv({logger:J,browserStateStorage:Mp,generator:c,fullResults:$,failureReason:Hr,error:Vl,maxItemsFromEnd:void 0,numStepsWithScreenshots:void 0,disableCache:!1});Xn=It,zo=In}}catch(It){J.warn({err:It},"Failed to classify test results")}Xn&&(Ut.classification=Xn,Hr=zo??Hr)}return{...$,parameters:he,failureDetails:Ut,failureReason:Hr,test:we,filePath:we.relativeFilePath,startedAt:ee,lastAttemptStartedAt:Er,finishedAt:Fo,attempts:ct+1,baseUrl:s,outputs:Bo,quarantined:P,quarantinedReason:X}}catch(Xt){Za(Xt);let zr=`Encountered fatal platform error while running test '${we.name}': ${Xt}`,Fo=new Date,tn=ct+1;J.error({err:Xt},zr),T.error(zr);let Bo={errorMessage:Xt.message,errStack:Xt.stack},W={status:"FAILED",failureDetails:Bo,failureReason:"InternalPlatformError",finishedAt:Fo};return await kt.finish({logger:J,result:{status:"FAILED",results:[]}}),{...W,results:[],parameters:he,test:we,filePath:we.relativeFilePath,startedAt:ee,lastAttemptStartedAt:Er,finishedAt:new Date,attempts:tn,baseUrl:s,outputs:{},quarantined:P,quarantinedReason:X}}}throw new Error("This code should not be reachable")}function cW(r){for(let e of r.envs??[])if(e.default)return e.name}import uW from"adm-zip";import{randomUUID as dW}from"crypto";var qn="assets";function pW(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 mW(r){switch(r){case"SUCCESS":return"PASSED";case"FAILED":return"FAILED";case"CANCELLED":return"CANCELLED";case"RUNNING":return"RUNNING";case"IDLE":return"PENDING"}}var wS=class{constructor(e,t,n,o,i){this.orgId=e;this.testId=t;this.testName=n;this.metadata=o;this.diskStorage=i}children=[];finished=!1;getParentStepIdChain(){return[]}attachBeforeScreenshot(e){let{snapshotId:t,screenshot:n}=e;this.metadata.beforeSnapshotId=t,this.diskStorage.storeFile({name:`${qn}/${t}.jpeg`,contents:n})}attachAfterScreenshot(e){let{snapshotId:t,screenshot:n}=e;this.metadata.afterSnapshotId=t,this.diskStorage.storeFile({name:`${qn}/${t}.jpeg`,contents:n})}attachBeforeHtmlSnapshot(e){let{snapshotId:t,html:n}=e;this.metadata.beforeSnapshotId=t,this.diskStorage.storeFile({name:`${qn}/${t}.html`,contents:n})}attachAfterHtmlSnapshot(e){let{snapshotId:t,html:n}=e;this.metadata.afterSnapshotId=t,this.diskStorage.storeFile({name:`${qn}/${t}.html`,contents:n})}recordTargetAutoHeal(e){let{healType:t}=e,n=t==="AI"?"ai-target-heal":"cache-heal";or.increment("test_event",1,[`name:${n}`,`orgId:${this.orgId}`]),this.metadata.healMetadata={healType:t,healedAt:new Date}}recordStepDuration(e){let t=e.step.type!=="PRESET_ACTION"?e.step.type:e.step.command.type;or.distribution("test_step_duration",e.durationMs,[`type:${t}`,"platform:browser","executor:cli",`orgId:${this.orgId}`])}async finishInternal(e){this.finished||(this.finished=!0,await Promise.all(this.children.map(t=>t.finish({status:mW(e.status),finishedAt:e.finishedAt}))))}async finish(e){await this.finishInternal(e.step)}async startSubSteps(){let e=new Ja(this.orgId,this.testId,this.testName,this.diskStorage);return this.children.push(e),e}},Ja=class{constructor(e,t,n,o){this.orgId=e;this.testId=t;this.testName=n;this.diskStorage=o}children=[];finished=!1;stepFrequenciesByType={};async getScreenshot(e,t){return this.diskStorage.readFile(`${qn}/${t}.jpeg`)}async getHtmlSnapshot(e,t){return this.diskStorage.readFile(`${qn}/${t}.html`)?.toString()}getParentStepIdChain(){return[]}recordStepStat(e){e.type!=="PRESET_ACTION"?this.stepFrequenciesByType[e.type]=(this.stepFrequenciesByType[e.type]||0)+1:this.stepFrequenciesByType[e.command.type]=(this.stepFrequenciesByType[e.command.type]||0)+1}sendFinalizedStepStats(){for(let[e,t]of Object.entries(this.stepFrequenciesByType))or.increment("test_step_execution",t,[`type:${e}`,"platform:browser","executor:cli",`orgId:${this.orgId}`])}async startStep(e){let{step:t}=e;this.recordStepStat(t);let n={step:t,status:"RUNNING",startedAt:new Date},o=new wS(this.orgId,this.testId,this.testName,n,this.diskStorage);return this.children.push(o),o}async finish(e){this.finished||(this.finished=!0,await Promise.all(this.children.map(t=>t.finishInternal({status:pW(e.status),finishedAt:e.finishedAt}))),this.sendFinalizedStepStats())}},CS=class{constructor(e,t,n,o,i,a){this.orgId=e;this.testId=t;this.testName=n;this.runAttemptId=o;this.metadata=i;this.diskStorage=a;this.diskStorage.mkdir("assets")}finished=!1;children=[];get loggerBindings(){return{runAttemptId:this.runAttemptId}}attachNetworkLogs(e){let{logs:t}=e;this.diskStorage.storeFile({name:"network.har",contents:JSON.stringify(t,null,2)})}attachConsoleLogs(e){let{logs:t}=e;this.diskStorage.storeFile({name:"console.json",contents:JSON.stringify(t,null,2)})}attachBrowserCrashDump(e){let{crashReportDirFetcher:t,logger:n}=e,o=t();if(!o)return;let i=new uW;i.addLocalFolder(o,void 0,a=>a!==".DS_Store"),this.diskStorage.storeFile({name:`${qn}/${ah}`,contents:i.toBuffer()}),n.info({browserCrashZipName:ah},"Attached browser crash ZIP")}async finish(e){if(this.finished)return;this.finished=!0;let{logger:t,result:n}=e,o={...this.metadata,status:n.status,finishedAt:new Date,results:pu(n.results,t),beforeResults:n.beforeResults?pu(n.beforeResults,t):void 0,afterResults:n.afterResults?pu(n.afterResults,t):void 0};await Promise.all(this.children.map(i=>i.finish({status:o.status,finishedAt:o.finishedAt}))),this.diskStorage.storeFile({name:"metadata.json",contents:JSON.stringify(o,null,2)})}async startBeforeStepList(){let e=new Ja(this.orgId,this.testId,this.testName,this.diskStorage);return this.children.push(e),e}async startMainStepList(){let e=new Ja(this.orgId,this.testId,this.testName,this.diskStorage);return this.children.push(e),e}async startAfterStepList(){let e=new Ja(this.orgId,this.testId,this.testName,this.diskStorage);return this.children.push(e),e}async getScreenshot(e,t){return this.diskStorage.readFile(`${qn}/${t}.jpeg`)}async getHtmlSnapshot(e,t){return this.diskStorage.readFile(`${qn}/${t}.html`)?.toString()}},xS=class{constructor(e,t,n,o,i,a){this.orgId=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}}get envVarBindings(){return{[rx]: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,result:{status:t.status,results:[],beforeResults:[],afterResults:[]}}))),this.diskStorage.storeFile({name:"metadata.json",contents:JSON.stringify(t,null,2)}),this.diskStorage.close()}async startAttempt(){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 e=this.diskStorage.cd(`attempts/${this.metadata.attempts}`),t=dW(),n={id:t,schemaVersion:ue,runAttemptSchemaVersion:Rb,startedAt:new Date,status:"RUNNING"};e.storeFile({name:"metadata.json",contents:JSON.stringify(n,null,2)});let o=new CS(this.orgId,this.testId,this.testName,t,n,e);return this.children.push(o),o}},xp=class r{constructor(e,t,n,o){this.orgId=e;this.runGroupId=t;this.metadata=n;this.diskStorage=o}children=[];finished=!1;get loggerBindings(){return{orgId:this.orgId,runGroupId:this.runGroupId,branch:this.metadata.gitBranchName}}static async start(e,t,n,o,i){let a={...o,id:t,trigger:Rr.CLI,startedAt:new Date,status:"RUNNING",cliVersion:$n,labels:i??[]},l=new al(n);return l.storeFile({name:"metadata.json",contents:JSON.stringify(a,null,2)}),new r(e,t,a,l)}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",resolvedBaseUrl:e.baseUrl,environmentName:e.environmentName,resolvedInputs:e.resolvedInputs,cliVersion:$n,schemaVersion:e.schemaVersion,startedAt:new Date,attempts:0,quarantined:e.quarantined??!1,quarantinedReason:e.quarantinedReason,executionType:"WEB"};t.storeFile({name:"metadata.json",contents:JSON.stringify(n,null,2)});let o=new xS(this.orgId,e.testId,e.testName,e.runId,n,t);return this.children.push(o),o}};async function BM(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 zM(r){let{logger:e,tests:t,yes:n,start:o,waitOn:i,client:a,debugDataStorage:l,project:c,retriesOverride:s,urlOverride:u,envName:d,orgId:p,devicePixelRatio:m,customHeaders:h,testInputMatrix:g,reporter:f,include:y,exclude:S,labels:E,reporterDir:R=aA,outputDir:A=sA,uploadResults:C=!1,waitOnTimeout:w=60,parallel:I,shardIndex:P=1,shardCount:X=1,regenerateGoldenFiles:q,gitMetadata:k,alwaysSaveCache:ee,noCache:z,ignoreQuarantine:j,skipQuarantined:he,onlyQuarantined:$,runGroupId:rt}=r;o&&(e.info({orgId:p},`Executing start command: ${o}`),await _M(o,!1)),i&&(e.info({orgId:p},`Waiting for url: ${i} with timeout: ${w} seconds.`),await fW({resources:[i],interval:2500,timeout:w*1e3,headers:{Accept:"*/*"},followRedirect:!0,verbose:!1,log:!0,strictSSL:!1}));let Ne=new Dn(c.config.ai?.agentConfig,{baseUrl:a.baseUrl,apiKey:a.apiKey,logger:e}),ct=await Y(c),kt=await Ka({tests:t,momenticFiles:ct,yes:n,project:c,include:y,exclude:S,labels:E,logger:T}),J=await BM(e,a,j),{testsToSkip:we,quarantinedTestsToSkip:Er,testsToRun:Kn,quarantinedTestsToRun:Yn}=hM({testDefinitions:kt,quarantinedTestReasons:J,onlyQuarantined:$,skipQuarantined:he});PM(we),OM(Er,J);let Mp=gM({testsToRun:Kn,quarantinedTestsToRun:Yn,quarantinedTestReasons:J,testInputMatrix:g}),Xt=yW({globalTestsToRunWithInputs:Mp,shardIndex:P,shardCount:X});LM({logger:e,localTestsToRunWithInputs:Xt,parallel:I,shardCount:X,shardIndex:P});let zr=[],Fo=new Date,tn=new Set,Bo=async()=>{let Ut=a.getAppUrl(),zo=ia({results:zr,startTime:Fo.getTime(),onFailed:It=>{Zc(It,It.filePath)},getDisplayLine:It=>{let In=`${mt}- ${It.filePath}${It.failureRecoveryDetails?" [recovered] ":""}`;return It.runId&&(In+=` ( link when uploaded: ${Ut}/runs/${It.runId} )`),In},entity:"test"}),Xn=zr.filter(It=>!!It.failureRecoveryDetails?.attempts);return Xn.length>0&&T.warn(`Our AI agent automatically prevented ${Xn.length} tests from failing due to transient issues. Use the run links above to review the additional steps that were executed.`),T.log(""),C?(T.success(`Test results have been saved to the folder ${A}. Uploading to Momentic Cloud...`),await Mu({client:a,consoleLogger:T,resultsPath:A})):T.success(`Test results have been saved to the folder ${A}. Upload them to Momentic Cloud by running 'npx momentic results upload ${A}'.`),zo};gW.existsSync(A)&&T.warn(`Output directory ${A} already exists, removing before test execution...`);let W=await xp.start(p,rt,A,k,E),Ni=e.child(W.loggerBindings||{}),Di=[],_n=async()=>{T.warn("SIGINT received. Stopping tests and printing latest results..."),await W.finish({logger:Ni,status:"CANCELLED"}),await Bo(),await Promise.allSettled(Di.map(Ut=>Ut())),await Wn(),process.exit(1)};process.once("SIGINT",_n);let Hr={};for(let Ut=0;Ut<Xt.length;Ut++){let zo=Object.values(Hr);zo.length===I&&await Promise.race(zo.map(In=>In.promise));let Xn=Xt[Ut],It=`test-${Ut}`;Hr[It]={done:!1,promise:(async({inputs:In,quarantined:WM,quarantinedReason:qM,testDefinition:Ho})=>{tn.add({inputs:In});let $l=Ho.relativeFilePath.includes("..")?Ho.fullFilePath:Ho.relativeFilePath;Gs({status:"START",testLogRef:$l,getRunningTestsCount:()=>tn.size,getTotalTestsCount:()=>Xt.length});let KM=setInterval(()=>Gs({status:"RUN",testLogRef:$l,getRunningTestsCount:()=>tn.size,getTotalTestsCount:()=>Xt.length}),5*60*1e3),Op=hW(),Lp=Ni.child({testId:Ho.id,runId:Op}),PS=new vu({logger:Lp,reporter:new tu(a),runType:"test-run",runId:Op,testMetadata:Ho,suiteMetadata:void 0});try{let Qa=await FM({testDefinition:Ho,project:c,testInputs:In,quarantined:WM,quarantinedReason:qM,orgId:p,runId:Op,devicePixelRatio:m,apiClient:a,runGroupTracer:W,generator:Ne,retriesOverride:s,urlOverride:u,envName:d,customHeaders:h,regenerateGoldenFiles:q,logUpdate:(Wl,YM)=>Gs({status:Wl,testLogRef:$l,getRunningTestsCount:()=>tn.size,getTotalTestsCount:()=>Xt.length,additionalText:YM}),runSigIntHandlers:Di,logger:Lp,gitMetadata:k,alwaysSaveCache:ee,noCache:z,usageTracker:PS});Gs({status:Qa.status,testLogRef:$l,getRunningTestsCount:()=>tn.size,getTotalTestsCount:()=>Xt.length}),zr.push(Qa)}catch(Qa){let Wl=`Encountered unexpected fatal error when running test '${Ho.name}': ${Qa.message}`;T.error(Wl),Lp.error({err:Qa},Wl)}finally{clearInterval(KM),Hr[It].done=!0,delete Hr[It]}await PS.flush(e)})(Xn)}}await Promise.allSettled(Object.values(Hr).map(Ut=>Ut.promise));let Vl=zr.some(Ut=>!Ut.quarantined&&Ut.status==="FAILED")?"FAILED":"PASSED";return await W.finish({logger:Ni,status:Vl}),process.off("SIGINT",_n),f&&await CM(Ni,l,f,{projectConfigPath:c.configFilePath,suiteName:c.config.name,startedAt:Fo,finishedAt:new Date,runs:zr,testsToSkip:we,quarantinedTestsToSkip:Er,quarantinedTestReasons:J},R),Bo()}function SW(r,e,t){if(t>r.length&&(T.warn(`Shard count ${t} is greater than the number of tests ${r.length}! Some workers won't have any tests to run.`),t=Math.max(t,r.length),e>t))return[];let n=Math.floor((e-1)*(r.length/t)),o=Math.floor(e*(r.length/t));return r.sort().filter((a,l)=>l>=n&&l<o)}function yW({globalTestsToRunWithInputs:r,shardIndex:e,shardCount:t}){return t&&t>1?SW(r,e,t):r}Np||ne.warn("Sentry is not enabled in this environment due to unsupported node version");YC({serviceName:"cli"});var GM=process.argv.some(r=>r.includes("--log-level"))&&process.argv.some(r=>r.includes("debug")),_S=r=>{GM&&T.dimmed(r)};GM&&jb(ne);var Yt=new EW;Yt.name("momentic").description("Momentic CLI").version($n);Yt.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: ${ph.join(", ")}.`).action(async(r,e)=>{!e.all&&r.length===0&&(T.error("No browsers specified"),process.exit(1)),await Gb({rawBrowsers:r,force:e.force,all:e.all})});Yt.addOption(new pr("--log-level <level>").choices(["debug","info","warn","error"]).default("info")).on("option:log-level",r=>{r==="debug"&&T.info("Enabling debug logging"),T.setMinLevel(r.toLowerCase())});Yt.addOption(new pr("--verbose","enable verbose logging")).on("option:verbose",()=>{ne.enableConsoleLogs(),T.setMinLevel(20)});var IS=Yt.command("checks").alias("check").description("Perform various project checks");IS.command("config").addOption(dr).action(async r=>{await vt({configFilePath:r.config})});IS.command("duplicate-ids").description("Checks if any steps in your entire Momentic test repository share the same ID.").addOption(dr).addOption(rM).action(async r=>{let e=await vt({configFilePath:r.config});await GI({project:e,fix:r.fix})});IS.command("duplicate-names").description("Checks if tests or modules with duplicate names or ids exist").addOption(dr).action(async r=>{let e=await vt({configFilePath:r.config});await jI({project:e})});var jM=Yt.command("migrate").description("Migrate and upgrade tooling");jM.command("steps").description("Migrate steps in all tests and modules to the latest schema version. Note that this is always done when a test is loaded through the interactive editor, so is generally not needed.").addOption(dr).action(async r=>{let e=await vt({configFilePath:r.config});await dM(e)});jM.command("v1-v2").description("Migrate from v1 of the Momentic CLI to v2").addOption(Br).addOption(dr).addOption(Fr).addOption(Uo).action(async r=>{!r.yes&&!await Pt("This command will modify your existing Momentic configuration. Please backup your local directory using Git or another version control system before proceeding. Continue?")&&process.exit(1);let e=await vt({configFilePath:r.config}),t=new Ze({baseUrl:r.server,apiKey:r.apiKey,logger:ne}),{orgId:n}=await t.getAuthInfo();await pM({project:e,orgId:n,apiClient:t}),process.exit(0)});Yt.command("import").addOption(Fr).addOption(Br).addOption(dr).addOption(Uo).addArgument(sM).action(async(r,e)=>{let{apiKey:t,server:n,config:o,yes:i}=e,a=await vt({configFilePath:o}),l=new Ze({baseUrl:n,apiKey:t,logger:ne});!r||r.length===0?await KI({client:l,project:a,skipPrompts:i}):await YI({client:l,project:a,paths:r,skipPrompts:i}),process.exit(0)});Yt.command("init").description("Initialize an empty Momentic project in the current working directory").addOption(new pr("--name <name>","Name of the project")).action(async r=>{T.info(`Welcome to the Momentic project setup wizard! \u{1F680}
|
|
4402
4401
|
`),T.info("This wizard will help you bootstrap a new Momentic project. If you need to import existing assets from Momentic Cloud, you can call the 'import' command after initialization."),Ip.existsSync(Sa)&&(T.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 e=r.name??await Mb("Choose an identifier for your project, such as a service, product, or team name (default: 'app'):","app");await cA()||await Pt("A Git repository was not detected in the current directory. Momentic highly recommends initializing your project within a Git repository for seamless version control. Continue?")||process.exit(1),ya({name:e,include:Uh},Sa),T.success(`Initialized Momentic project file at ${_p.resolve(Sa)}`)});Yt.command("app").addOption(Fr).addOption(Br).addOption(Uo).addOption(uS).addOption(dr).addOption(pS).addOption(mS).action(async r=>{let{apiKey:e,yes:t,server:n,pixelRatio:o,disableCache:i,saveCache:a}=r,l=await vt({configFilePath:r.config,nameFilter:void 0}),{errors:c}=await mp({project:l,fix:!1});c>0&&(T.error(`Found ${c} errors`),T.warn("To fix these errors automatically, run the duplicate-ids check with the --fix flag and then commit the resulting changes"),process.exit(1)),WA(ne);let s=new Ze({baseUrl:n,apiKey:e,logger:ne});await yh({client:s,skipPrompts:t});let u=RW(import.meta.url),d=_p.dirname(u),p=_p.resolve(d,"..","static"),m=_p.resolve(d,"..","assets"),h=o??vS();AS(h),await FI({momenticServerUrl:n,apiKey:e,serverPort:hp,appPort:hp,staticDir:p,assetsDir:m,devicePixelRatio:h,noCache:i,alwaysSaveCache:a,initialProject:l});let g=`http://localhost:${hp}`;await AW(g)});var VM=Yt.command("queue").description("Queue tests or suites to run on Momentic Cloud");VM.command("suites").description("Run one or more suites on Momentic Cloud").addOption(Fr).addOption(Br).addOption(iS).addOption(aS).addOption(Uo).addArgument(lM).addOption(yp).addOption(Sp).addOption(fp).action(async(r,e)=>{let{apiKey:t,server:n,wait:o,waitTimeout:i,env:a,urlOverride:l}=e,c=gp(e.customHeaders),s=new Ze({baseUrl:n,apiKey:t,logger:ne});(!r||!Array.isArray(r)||!r.length)&&(T.error("Must pass at least one suite to run."),process.exit(1));let{orgId:u}=await s.getAuthInfo();await EM({client:s,orgId:u,wait:o,suitePaths:r,waitTimeout:i,env:a,urlOverride:l,customHeaders:c}),await Wn()});VM.command("tests").description("Run one or more tests on Momentic Cloud").addOption(Fr).addOption(Br).addOption(Uo).addOption(fp).addOption(dS).addOption(yp).addOption(Sp).addOption(new pr("--all","Run all tests.").default(!1)).addOption(iS).addOption(aS).addArgument(aM).action(async(r,e)=>{let{all:t,apiKey:n,env:o,server:i,inputCsv:a,urlOverride:l,wait:c,waitTimeout:s,yes:u}=e,d=gp(e.customHeaders);for(let g of r)(g.endsWith(".yaml")||Ip.existsSync(g))&&T.warn("Are you trying to run a test on your local machine? If so, please use the 'run' command instead of the 'queue' command");let p=new Ze({baseUrl:i,apiKey:n,logger:ne}),{orgId:m}=await p.getAuthInfo(),h;a&&(h=await RS(a)),await TM({client:p,orgId:m,tests:r,all:t,customHeaders:d,env:o,urlOverride:l,wait:c,waitTimeout:s,testInputMatrix:h,yes:u}),await Wn(),process.exit(0)});var wW=Yt.command("list").description("List test paths");wW.addOption(dr).addOption(Li).addOption(lS).addOption(cS).addOption(new pr("--labels <labels...>","Only run tests with the specified label(s).")).addArgument(hS).action(async(r,e)=>{let t=await vt({configFilePath:e.config,nameFilter:e.filter}),n=await Y(t),o=await Ka({tests:r,momenticFiles:n,yes:!0,project:t,include:e.include,exclude:e.exclude,labels:e.labels,logger:new oi(40,{})});T.info(o.map(i=>i.relativeFilePath).join(`
|
|
4403
|
-
`)),process.exit(0)});var CW=Yt.command("run").alias("test").description("Run tests on the local machine");CW.addOption(Fr).addOption(Br).addOption(dr).addOption(Li).addOption(Uo).addOption(fp).addOption(dS).addOption(pS).addOption(mS).addOption(nM).addOption(oM).addOption(iM).addOption(Sp).addOption(yp).addOption(uS).addOption(new pr("--start <start>","Arbitrary setup command that will run before Momentic steps begin.")).addOption(new pr("--wait-on <waitOn>","URL to wait to become accessible before Momentic tests begin.")).addOption(new pr("--wait-on-timeout <waitOnTimeout>","Max time in seconds to wait for the --wait-on URL to become accessible.").default(60).argParser(ko)).addOption(new pr("--retries <retries>","Number of retries to attempt when running tests locally. Defaults to each test's own retry configuration.").argParser(ko)).addOption(new pr("-p, --parallel <parallel>","The number of tests to run in parallel. Defaults to 1.").argParser(ko)).addOption(new pr("--labels <labels...>","Only run tests with the specified label(s).")).addOption(new pr("--update-golden-files","Update locally stored golden files for steps that this is enabled for.").default(!1)).addOption(JI).addOption(QI).addOption(sS).addOption(ZI).addOption(tM).addOption(eM).addOption(lS).addOption(cS).addArgument(hS).action(async(r,e)=>{if(e.shardIndex>e.shardCount)throw new Error("Shard index cannot be greater than shard count");let t=gp(e.customHeaders),n=await vt({configFilePath:e.config,nameFilter:e.filter}),o=e.parallel??n.config.parallel??1;HM().length<o*2&&T.warn(`You requested to run tests in parallel ${o} at a time on a machine with ${HM().length} cores. This may cause performance issues and test failures as Chrome requires at least 2 cores per browser instance.`),T.debug({projectName:n.config.name},"Identified project config");let{errors:i}=await mp({project:n,fix:!1});i>0&&(T.error(`Found ${i} errors`),T.warn("To fix these errors automatically, run the duplicate-ids check with the --fix flag and then commit the resulting changes"),process.exit(1));let a=new Ze({baseUrl:e.server,apiKey:e.apiKey,logger:ne});T.debug("Checking API key and dependencies");let{orgId:l,userId:c}=await yh({client:a,skipPrompts:e.yes});T.debug("API key check and browser installation complete");let s=new ks,u=e.outputDir??n.config.outputDir,d=e.reporterDir??n.config.reporterDir,p=bW(),m=ne.child({cliVersion:$n,orgId:l,userId:c,runGroupId:p}),h=await yo(ne,a,n);m.info({gitMetadata:h,config:n.config},"Got local metadata");let g;e.inputCsv&&(g=await RS(e.inputCsv));let f=e.pixelRatio??vS();AS(f);try{let
|
|
4402
|
+
`)),process.exit(0)});var CW=Yt.command("run").alias("test").description("Run tests on the local machine");CW.addOption(Fr).addOption(Br).addOption(dr).addOption(Li).addOption(Uo).addOption(fp).addOption(dS).addOption(pS).addOption(mS).addOption(nM).addOption(oM).addOption(iM).addOption(Sp).addOption(yp).addOption(uS).addOption(new pr("--start <start>","Arbitrary setup command that will run before Momentic steps begin.")).addOption(new pr("--wait-on <waitOn>","URL to wait to become accessible before Momentic tests begin.")).addOption(new pr("--wait-on-timeout <waitOnTimeout>","Max time in seconds to wait for the --wait-on URL to become accessible.").default(60).argParser(ko)).addOption(new pr("--retries <retries>","Number of retries to attempt when running tests locally. Defaults to each test's own retry configuration.").argParser(ko)).addOption(new pr("-p, --parallel <parallel>","The number of tests to run in parallel. Defaults to 1.").argParser(ko)).addOption(new pr("--labels <labels...>","Only run tests with the specified label(s).")).addOption(new pr("--update-golden-files","Update locally stored golden files for steps that this is enabled for.").default(!1)).addOption(JI).addOption(QI).addOption(sS).addOption(ZI).addOption(tM).addOption(eM).addOption(lS).addOption(cS).addArgument(hS).action(async(r,e)=>{if(e.shardIndex>e.shardCount)throw new Error("Shard index cannot be greater than shard count");let t=gp(e.customHeaders),n=await vt({configFilePath:e.config,nameFilter:e.filter}),o=e.parallel??n.config.parallel??1;HM().length<o*2&&T.warn(`You requested to run tests in parallel ${o} at a time on a machine with ${HM().length} cores. This may cause performance issues and test failures as Chrome requires at least 2 cores per browser instance.`),T.debug({projectName:n.config.name},"Identified project config");let{errors:i}=await mp({project:n,fix:!1});i>0&&(T.error(`Found ${i} errors`),T.warn("To fix these errors automatically, run the duplicate-ids check with the --fix flag and then commit the resulting changes"),process.exit(1));let a=new Ze({baseUrl:e.server,apiKey:e.apiKey,logger:ne});T.debug("Checking API key and dependencies");let{orgId:l,userId:c}=await yh({client:a,skipPrompts:e.yes});T.debug("API key check and browser installation complete");let s=new ks,u=e.outputDir??n.config.outputDir,d=e.reporterDir??n.config.reporterDir,p=bW(),m=ne.child({cliVersion:$n,orgId:l,userId:c,runGroupId:p}),h=await yo(ne,a,n);m.info({gitMetadata:h,config:n.config},"Got local metadata");let g;e.inputCsv&&(g=await RS(e.inputCsv));let f=e.pixelRatio??vS();AS(f);try{let y=await zM({...e,parallel:o,retriesOverride:e.retries,devicePixelRatio:f,tests:r,project:n,client:a,debugDataStorage:s,outputDir:u,uploadResults:e.uploadResults,reporterDir:d,customHeaders:t,envName:e.env,orgId:l,testInputMatrix:g,logger:m,regenerateGoldenFiles:e.updateGoldenFiles,gitMetadata:h,alwaysSaveCache:e.saveCache,noCache:e.disableCache,runGroupId:p});await Wn(),y.failed>0?process.exit(1):process.exit(0)}catch(y){T.error("Failed to run tests locally. Please check the error message below or run with the --verbose flag."),T.error(y),await Wn(),process.exit(1)}});var xW=Yt.command("apply").description("Apply an operation to local resources");xW.command("patch").addOption(Fr).addOption(Br).addOption(dr).addOption(Li).addOption(Uo).addOption(new pr("--from <from>","Name or ID of the patch to apply").makeOptionMandatory()).addOption(new pr("--to <to>","Name or ID of the test to apply the patch to").makeOptionMandatory()).action(async r=>{let{apiKey:e,server:t,config:n,yes:o}=r,i=await vt({configFilePath:n}),a=ne,l=new Ze({baseUrl:t,apiKey:e,logger:a}),c=await Y(i),s=c.tests[r.to]??Object.values(c.tests).find(d=>Oe(d.name)===r.to.trim());s||(T.error(`No test matching '${r.to}' could be found in the current project.`),process.exit(1));let u=await l.fetchTestFragment(r.from);await zI({client:l,test:s,fragment:u,yes:o,entities:c,logger:ne}),process.exit(0)});var $M=Yt.command("results").description("Merge and upload test results.");$M.command("merge").description("Merge test results files.").addOption(sS).addArgument(cM).action(async(r,e)=>{let{outputDir:t}=e;t||(T.error("Output directory is required."),process.exit(1)),Ip.existsSync(r)||(T.warn("Results path does not exist, skipping merge."),process.exit(0)),Ip.existsSync(t)&&T.warn(`Output directory ${t} already exists, removing before merging...`),mA(ne,t,r)});$M.command("upload").description("Upload test results to Momentic cloud.").addOption(Fr).addOption(Br).addArgument(uM).action(async(r,e)=>{let{apiKey:t,server:n}=e,o=ne,i=new Ze({baseUrl:n,apiKey:t,logger:o});await Mu({consoleLogger:T,resultsPath:r,client:i}),process.exit(0)});var MS=Yt.command("quarantine").description("Manage test quarantines");MS.command("add").description("Add a test to the quarantine. This will prevent it from running.").addOption(Fr).addOption(Br).addOption(dr).addOption(Li).addOption(gS).addArgument(fS).action(async(r,e)=>{let{apiKey:t,server:n,config:o,reason:i}=e,a=ne,l=await vt({configFilePath:o}),c=new Ze({baseUrl:n,apiKey:t,logger:a}),s=await yo(ne,c,l);await mM({test:r,reason:i,apiClient:c,project:l,logger:a,identity:s})});MS.command("list").description("List quarantined tests.").addOption(Fr).addOption(Br).addOption(dr).addOption(Li).action(async r=>{let{apiKey:e,server:t,config:n}=r,o=ne,i=await vt({configFilePath:n}),a=new Ze({baseUrl:t,apiKey:e,logger:o});await fM({apiClient:a,project:i})});MS.command("remove").description("Remove a test from the quarantine. This will allow it to run again.").addOption(Fr).addOption(Br).addOption(dr).addOption(Li).addOption(gS).addArgument(fS).action(async(r,e)=>{let{apiKey:t,server:n,config:o,reason:i}=e,a=ne,l=await vt({configFilePath:o}),c=new Ze({baseUrl:n,apiKey:t,logger:a}),s=await yo(ne,c,l);await SM({test:r,reason:i,apiClient:c,project:l,logger:a,identity:s})});async function _W(){_S("Main program started"),await IM(ne),_S("CLI version check complete");try{await Yt.parseAsync(process.argv),await Wn()}catch(r){let e={};try{e.playwrightVersion=TW("npx playwright --version").toString()}catch(t){ne.error({err:t},"Error fetching debug information")}ne.error({err:r,debugInfo:e},"Uncaught error in CLI"),Za(r,e),T.error(r),await Wn(),process.exit(1)}}vW.setMaxListeners(25);process.on("warning",r=>{ne.warn({err:r},`Node warning received on CLI: ${r.message}`)});_S("CLI parsing setup complete");_W();
|
|
4404
4403
|
//# sourceMappingURL=cli.js.map
|
|
4405
|
-
//# debugId=
|
|
4404
|
+
//# debugId=8836f39a-59f8-54fb-8c63-0560da741b40
|