momentic 2.71.1 → 2.71.2
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 +26 -25
- package/npm-shrinkwrap.json +2 -2
- package/package.json +1 -1
- package/run-viewer-static/assets/{index-FcUpuw1w.js → index-8lAqdVnW.js} +196 -196
- package/run-viewer-static/index.html +1 -1
- package/static/assets/{index-g3te9w00.js → index-b8X_qfJQ.js} +3 -3
- package/static/index.html +1 -1
package/bin/cli.js
CHANGED
|
@@ -1,14 +1,14 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
2
|
|
|
3
|
-
!function(){try{var e="undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof globalThis?globalThis:"undefined"!=typeof self?self:{},n=(new e.Error).stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="
|
|
4
|
-
var w1=Object.create;var vS=Object.defineProperty;var x1=Object.getOwnPropertyDescriptor;var _1=Object.getOwnPropertyNames;var I1=Object.getPrototypeOf,P1=Object.prototype.hasOwnProperty;var Mt=(t,e)=>()=>(t&&(e=t(t=0)),e);var M1=(t,e)=>()=>(e||t((e={exports:{}}).exports,e),e.exports),O1=(t,e)=>{for(var r in e)vS(t,r,{get:e[r],enumerable:!0})},L1=(t,e,r,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of _1(e))!P1.call(t,o)&&o!==r&&vS(t,o,{get:()=>e[o],enumerable:!(n=x1(e,o))||n.enumerable});return t};var N1=(t,e,r)=>(r=t!=null?w1(I1(t)):{},L1(e||!t||!t.__esModule?vS(r,"default",{value:t,enumerable:!0}):r,t));var qI,KI=Mt(()=>{"use strict";qI=typeof globalThis=="object"?globalThis:global});var YI=Mt(()=>{"use strict";KI()});var XI=Mt(()=>{"use strict";YI()});var Si,ME=Mt(()=>{"use strict";Si="1.9.0"});function J$(t){var e=new Set([t]),r=new Set,n=t.match(JI);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===t};function i(s){return r.add(s),!1}function a(s){return e.add(s),!0}return function(c){if(e.has(c))return!0;if(r.has(c))return!1;var l=c.match(JI);if(!l)return i(c);var u={major:+l[1],minor:+l[2],patch:+l[3],prerelease:l[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 JI,QI,ZI=Mt(()=>{"use strict";ME();JI=/^(\d+)\.(\d+)\.(\d+)(-(.+))?$/;QI=J$(Si)});function Yl(t,e,r,n){var o;n===void 0&&(n=!1);var i=ud[cd]=(o=ud[cd])!==null&&o!==void 0?o:{version:Si};if(!n&&i[t]){var a=new Error("@opentelemetry/api: Attempted duplicate registration of API: "+t);return r.error(a.stack||a.message),!1}if(i.version!==Si){var a=new Error("@opentelemetry/api: Registration of version v"+i.version+" for "+t+" does not match previously registered API v"+Si);return r.error(a.stack||a.message),!1}return i[t]=e,r.debug("@opentelemetry/api: Registered a global for "+t+" v"+Si+"."),!0}function yi(t){var e,r,n=(e=ud[cd])===null||e===void 0?void 0:e.version;if(!(!n||!QI(n)))return(r=ud[cd])===null||r===void 0?void 0:r[t]}function Xl(t,e){e.debug("@opentelemetry/api: Unregistering a global for "+t+" v"+Si+".");var r=ud[cd];r&&delete r[t]}var Q$,cd,ud,dd=Mt(()=>{"use strict";XI();ME();ZI();Q$=Si.split(".")[0],cd=Symbol.for("opentelemetry.js.api."+Q$),ud=qI});function pd(t,e,r){var n=yi("diag");if(n)return r.unshift(e),n[t].apply(n,eq([],Z$(r),!1))}var Z$,eq,eP,tP=Mt(()=>{"use strict";dd();Z$=function(t,e){var r=typeof Symbol=="function"&&t[Symbol.iterator];if(!r)return t;var n=r.call(t),o,i=[],a;try{for(;(e===void 0||e-- >0)&&!(o=n.next()).done;)i.push(o.value)}catch(s){a={error:s}}finally{try{o&&!o.done&&(r=n.return)&&r.call(n)}finally{if(a)throw a.error}}return i},eq=function(t,e,r){if(r||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 t.concat(i||Array.prototype.slice.call(e))},eP=function(){function t(e){this._namespace=e.namespace||"DiagComponentLogger"}return t.prototype.debug=function(){for(var e=[],r=0;r<arguments.length;r++)e[r]=arguments[r];return pd("debug",this._namespace,e)},t.prototype.error=function(){for(var e=[],r=0;r<arguments.length;r++)e[r]=arguments[r];return pd("error",this._namespace,e)},t.prototype.info=function(){for(var e=[],r=0;r<arguments.length;r++)e[r]=arguments[r];return pd("info",this._namespace,e)},t.prototype.warn=function(){for(var e=[],r=0;r<arguments.length;r++)e[r]=arguments[r];return pd("warn",this._namespace,e)},t.prototype.verbose=function(){for(var e=[],r=0;r<arguments.length;r++)e[r]=arguments[r];return pd("verbose",this._namespace,e)},t}()});var At,lf=Mt(()=>{"use strict";(function(t){t[t.NONE=0]="NONE",t[t.ERROR=30]="ERROR",t[t.WARN=50]="WARN",t[t.INFO=60]="INFO",t[t.DEBUG=70]="DEBUG",t[t.VERBOSE=80]="VERBOSE",t[t.ALL=9999]="ALL"})(At||(At={}))});function rP(t,e){t<At.NONE?t=At.NONE:t>At.ALL&&(t=At.ALL),e=e||{};function r(n,o){var i=e[n];return typeof i=="function"&&t>=o?i.bind(e):function(){}}return{error:r("error",At.ERROR),warn:r("warn",At.WARN),info:r("info",At.INFO),debug:r("debug",At.DEBUG),verbose:r("verbose",At.VERBOSE)}}var nP=Mt(()=>{"use strict";lf()});var tq,rq,nq,Go,md=Mt(()=>{"use strict";tP();nP();lf();dd();tq=function(t,e){var r=typeof Symbol=="function"&&t[Symbol.iterator];if(!r)return t;var n=r.call(t),o,i=[],a;try{for(;(e===void 0||e-- >0)&&!(o=n.next()).done;)i.push(o.value)}catch(s){a={error:s}}finally{try{o&&!o.done&&(r=n.return)&&r.call(n)}finally{if(a)throw a.error}}return i},rq=function(t,e,r){if(r||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 t.concat(i||Array.prototype.slice.call(e))},nq="diag",Go=function(){function t(){function e(o){return function(){for(var i=[],a=0;a<arguments.length;a++)i[a]=arguments[a];var s=yi("diag");if(s)return s[o].apply(s,rq([],tq(i),!1))}}var r=this,n=function(o,i){var a,s,c;if(i===void 0&&(i={logLevel:At.INFO}),o===r){var l=new Error("Cannot use diag as the logger for itself. Please use a DiagLogger implementation like ConsoleDiagLogger or a custom implementation");return r.error((a=l.stack)!==null&&a!==void 0?a:l.message),!1}typeof i=="number"&&(i={logLevel:i});var u=yi("diag"),d=rP((s=i.logLevel)!==null&&s!==void 0?s:At.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 Yl("diag",d,r,!0)};r.setLogger=n,r.disable=function(){Xl(nq,r)},r.createComponentLogger=function(o){return new eP(o)},r.verbose=e("verbose"),r.debug=e("debug"),r.info=e("info"),r.warn=e("warn"),r.error=e("error")}return t.instance=function(){return this._instance||(this._instance=new t),this._instance},t}()});var oP,iP=Mt(()=>{"use strict";oP=Symbol("BaggageEntryMetadata")});function OE(t){return typeof t!="string"&&(oq.error("Cannot create baggage metadata from unknown type: "+typeof t),t=""),{__TYPE__:oP,toString:function(){return t}}}var oq,aP=Mt(()=>{"use strict";md();iP();oq=Go.instance()});function LE(t){return Symbol.for(t)}var iq,NE,DE=Mt(()=>{"use strict";iq=function(){function t(e){var r=this;r._currentContext=e?new Map(e):new Map,r.getValue=function(n){return r._currentContext.get(n)},r.setValue=function(n,o){var i=new t(r._currentContext);return i._currentContext.set(n,o),i},r.deleteValue=function(n){var o=new t(r._currentContext);return o._currentContext.delete(n),o}}return t}(),NE=new iq});function UE(){return FE}var ds,aq,cf,sq,lq,cq,uq,kE,dq,pq,mq,FE,fq,hq,gq,Sq,yq,Eq,Tq,BE=Mt(()=>{"use strict";ds=function(){var t=function(e,r){return t=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])},t(e,r)};return function(e,r){if(typeof r!="function"&&r!==null)throw new TypeError("Class extends value "+String(r)+" is not a constructor or null");t(e,r);function n(){this.constructor=e}e.prototype=r===null?Object.create(r):(n.prototype=r.prototype,new n)}}(),aq=function(){function t(){}return t.prototype.createGauge=function(e,r){return hq},t.prototype.createHistogram=function(e,r){return gq},t.prototype.createCounter=function(e,r){return fq},t.prototype.createUpDownCounter=function(e,r){return Sq},t.prototype.createObservableGauge=function(e,r){return Eq},t.prototype.createObservableCounter=function(e,r){return yq},t.prototype.createObservableUpDownCounter=function(e,r){return Tq},t.prototype.addBatchObservableCallback=function(e,r){},t.prototype.removeBatchObservableCallback=function(e){},t}(),cf=function(){function t(){}return t}(),sq=function(t){ds(e,t);function e(){return t!==null&&t.apply(this,arguments)||this}return e.prototype.add=function(r,n){},e}(cf),lq=function(t){ds(e,t);function e(){return t!==null&&t.apply(this,arguments)||this}return e.prototype.add=function(r,n){},e}(cf),cq=function(t){ds(e,t);function e(){return t!==null&&t.apply(this,arguments)||this}return e.prototype.record=function(r,n){},e}(cf),uq=function(t){ds(e,t);function e(){return t!==null&&t.apply(this,arguments)||this}return e.prototype.record=function(r,n){},e}(cf),kE=function(){function t(){}return t.prototype.addCallback=function(e){},t.prototype.removeCallback=function(e){},t}(),dq=function(t){ds(e,t);function e(){return t!==null&&t.apply(this,arguments)||this}return e}(kE),pq=function(t){ds(e,t);function e(){return t!==null&&t.apply(this,arguments)||this}return e}(kE),mq=function(t){ds(e,t);function e(){return t!==null&&t.apply(this,arguments)||this}return e}(kE),FE=new aq,fq=new sq,hq=new cq,gq=new uq,Sq=new lq,yq=new dq,Eq=new pq,Tq=new mq});var En,sP=Mt(()=>{"use strict";(function(t){t[t.INT=0]="INT",t[t.DOUBLE=1]="DOUBLE"})(En||(En={}))});var bq,vq,lP,cP=Mt(()=>{"use strict";DE();bq=function(t,e){var r=typeof Symbol=="function"&&t[Symbol.iterator];if(!r)return t;var n=r.call(t),o,i=[],a;try{for(;(e===void 0||e-- >0)&&!(o=n.next()).done;)i.push(o.value)}catch(s){a={error:s}}finally{try{o&&!o.done&&(r=n.return)&&r.call(n)}finally{if(a)throw a.error}}return i},vq=function(t,e,r){if(r||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 t.concat(i||Array.prototype.slice.call(e))},lP=function(){function t(){}return t.prototype.active=function(){return NE},t.prototype.with=function(e,r,n){for(var o=[],i=3;i<arguments.length;i++)o[i-3]=arguments[i];return r.call.apply(r,vq([n],bq(o),!1))},t.prototype.bind=function(e,r){return r},t.prototype.enable=function(){return this},t.prototype.disable=function(){return this},t}()});var Aq,Cq,zE,Rq,uP,dP=Mt(()=>{"use strict";cP();dd();md();Aq=function(t,e){var r=typeof Symbol=="function"&&t[Symbol.iterator];if(!r)return t;var n=r.call(t),o,i=[],a;try{for(;(e===void 0||e-- >0)&&!(o=n.next()).done;)i.push(o.value)}catch(s){a={error:s}}finally{try{o&&!o.done&&(r=n.return)&&r.call(n)}finally{if(a)throw a.error}}return i},Cq=function(t,e,r){if(r||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 t.concat(i||Array.prototype.slice.call(e))},zE="context",Rq=new lP,uP=function(){function t(){}return t.getInstance=function(){return this._instance||(this._instance=new t),this._instance},t.prototype.setGlobalContextManager=function(e){return Yl(zE,e,Go.instance())},t.prototype.active=function(){return this._getContextManager().active()},t.prototype.with=function(e,r,n){for(var o,i=[],a=3;a<arguments.length;a++)i[a-3]=arguments[a];return(o=this._getContextManager()).with.apply(o,Cq([e,r,n],Aq(i),!1))},t.prototype.bind=function(e,r){return this._getContextManager().bind(e,r)},t.prototype._getContextManager=function(){return yi(zE)||Rq},t.prototype.disable=function(){this._getContextManager().disable(),Xl(zE,Go.instance())},t}()});var Jl,pP=Mt(()=>{"use strict";dP();Jl=uP.getInstance()});var ie,mP=Mt(()=>{"use strict";md();ie=Go.instance()});var wq,fP,hP=Mt(()=>{"use strict";BE();wq=function(){function t(){}return t.prototype.getMeter=function(e,r,n){return FE},t}(),fP=new wq});var HE,gP,SP=Mt(()=>{"use strict";hP();dd();md();HE="metrics",gP=function(){function t(){}return t.getInstance=function(){return this._instance||(this._instance=new t),this._instance},t.prototype.setGlobalMeterProvider=function(e){return Yl(HE,e,Go.instance())},t.prototype.getMeterProvider=function(){return yi(HE)||fP},t.prototype.getMeter=function(e,r,n){return this.getMeterProvider().getMeter(e,r,n)},t.prototype.disable=function(){Xl(HE,Go.instance())},t}()});var uf,yP=Mt(()=>{"use strict";SP();uf=gP.getInstance()});var yt=Mt(()=>{"use strict";aP();DE();lf();BE();sP();pP();mP();yP()});var PU=M1((sp,$v)=>{"use strict";(function(t,e){if(typeof sp=="object"&&typeof $v=="object")$v.exports=e();else if(typeof define=="function"&&define.amd)define([],e);else{var r=e();for(var n in r)(typeof sp=="object"?sp:t)[n]=r[n]}})(typeof self<"u"?self:sp,function(){return function(t){var e={};function r(n){if(e[n])return e[n].exports;var o=e[n]={i:n,l:!1,exports:{}};return t[n].call(o.exports,o,o.exports,r),o.l=!0,o.exports}return r.m=t,r.c=e,r.d=function(n,o,i){r.o(n,o)||Object.defineProperty(n,o,{enumerable:!0,get:i})},r.r=function(n){typeof Symbol<"u"&&Symbol.toStringTag&&Object.defineProperty(n,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(n,"__esModule",{value:!0})},r.t=function(n,o){if(1&o&&(n=r(n)),8&o||4&o&&typeof n=="object"&&n&&n.__esModule)return n;var i=Object.create(null);if(r.r(i),Object.defineProperty(i,"default",{enumerable:!0,value:n}),2&o&&typeof n!="string")for(var a in n)r.d(i,a,function(s){return n[s]}.bind(null,a));return i},r.n=function(n){var o=n&&n.__esModule?function(){return n.default}:function(){return n};return r.d(o,"a",o),o},r.o=function(n,o){return Object.prototype.hasOwnProperty.call(n,o)},r.p="",r(r.s=0)}([function(t,e,r){"use strict";var n;r.r(e),function(g){g[g.Empty=0]="Empty",g[g.InsideToken=1]="InsideToken",g[g.InsideSingleQuotedToken=2]="InsideSingleQuotedToken",g[g.InsideDoubleQuotedToken=3]="InsideDoubleQuotedToken",g[g.AfterEscapeInsideToken=4]="AfterEscapeInsideToken",g[g.AfterEscapeInsideSingleQuotedToken=5]="AfterEscapeInsideSingleQuotedToken",g[g.AfterEscapeInsideDoubleQuotedToken=6]="AfterEscapeInsideDoubleQuotedToken"}(n||(n={}));var o=function(g){return[null,null]},i={onCharacter:o,onWhitespace:o,onDoubleQuote:o,onSingleQuote:o,onEscape:o},a=function(){return(a=Object.assign||function(g){for(var E,y=1,b=arguments.length;y<b;y++)for(var C in E=arguments[y])Object.prototype.hasOwnProperty.call(E,C)&&(g[C]=E[C]);return g}).apply(this,arguments)},s=a({},i,{stateHandle:n.AfterEscapeInsideDoubleQuotedToken,onCharacter:function(g){return["\\"+g,n.InsideDoubleQuotedToken]},onWhitespace:function(g){return["\\"+g,n.InsideDoubleQuotedToken]},onSingleQuote:function(g){return["\\"+g,n.InsideDoubleQuotedToken]},onDoubleQuote:function(g){return[g,n.InsideDoubleQuotedToken]},onEscape:function(g){return[g,n.InsideDoubleQuotedToken]}}),c=a({},i,{stateHandle:n.AfterEscapeInsideSingleQuotedToken,onCharacter:function(g){return["\\"+g,n.InsideSingleQuotedToken]},onWhitespace:function(g){return["\\"+g,n.InsideSingleQuotedToken]},onSingleQuote:function(g){return[g,n.InsideSingleQuotedToken]},onDoubleQuote:function(g){return["\\"+g,n.InsideSingleQuotedToken]},onEscape:function(g){return[g,n.InsideSingleQuotedToken]}}),l=a({},i,{stateHandle:n.AfterEscapeInsideToken,onCharacter:function(g){return[g,n.InsideToken]},onWhitespace:function(g){return[g,n.InsideToken]},onSingleQuote:function(g){return[g,n.InsideToken]},onDoubleQuote:function(g){return[g,n.InsideToken]},onEscape:function(g){return[g,n.InsideToken]}}),u=a({},i,{stateHandle:n.Empty,onCharacter:function(g){return[g,n.InsideToken]},onSingleQuote:function(){return[null,n.InsideSingleQuotedToken]},onDoubleQuote:function(){return[null,n.InsideDoubleQuotedToken]},onEscape:function(){return[null,n.AfterEscapeInsideToken]}}),d=a({},i,{stateHandle:n.InsideDoubleQuotedToken,onCharacter:function(g){return[g,null]},onWhitespace:function(g){return[g,null]},onSingleQuote:function(g){return[g,null]},onDoubleQuote:function(){return["",n.Empty]},onEscape:function(){return["",n.AfterEscapeInsideDoubleQuotedToken]}}),p=a({},i,{stateHandle:n.InsideSingleQuotedToken,onCharacter:function(g){return[g,null]},onWhitespace:function(g){return[g,null]},onSingleQuote:function(){return["",n.Empty]},onDoubleQuote:function(g){return[g,null]},onEscape:function(){return["",n.AfterEscapeInsideSingleQuotedToken]}}),m=[u,a({},i,{stateHandle:n.InsideToken,onCharacter:function(g){return[g,null]},onWhitespace:function(){return[null,n.Empty]},onSingleQuote:function(){return["",n.InsideSingleQuotedToken]},onDoubleQuote:function(){return["",n.InsideDoubleQuotedToken]},onEscape:function(){return["",n.AfterEscapeInsideToken]}}),p,d,l,c,s];function f(g){for(var E=0,y=m;E<y.length;E++){var b=y[E];if(b.stateHandle===g)return b}throw new Error("State with handle = "+g+" cannot be found")}var h=function(){function g(){this.currentState=f(n.Empty)}return g.prototype.handleCharacter=function(E){var y=this.performTransition(E),b=y[0],C=y[1];return C!==null&&(this.currentState=f(C)),b},g.prototype.performTransition=function(E){var y=this.currentState;switch(E){case" ":return y.onWhitespace(E);case"'":return y.onSingleQuote(E);case'"':return y.onDoubleQuote(E);case"\\":return y.onEscape(E);default:return y.onCharacter(E)}},g}();function S(g){for(var E=new h,y=[],b=0,C=0,I=g;C<I.length;C++){var _=I[C],R=E.handleCharacter(_);R!==null?y[b]=y[b]?y[b]+R:R:y[b]&&b++}return y}r.d(e,"default",function(){return S}),S.default=S}]).default})});import hRe,{multistream as SRe}from"pino";import ERe from"pino-pretty";import{z as AS}from"zod";var ere=AS.object({input:AS.string(),agentConfigVersion:AS.string().optional()}),Dp="finish";import{z as er}from"zod";var nre=er.object({srcs:er.array(er.string()),urls:er.array(er.string()),desiredSrc:er.string().optional(),desiredUrl:er.string().optional()}),ZA=er.object({srcRegex:er.string().optional(),urlRegex:er.string().optional()}),eC=er.object({x:er.number(),y:er.number(),correlation:er.number()}),ore=er.object({searchImageBase64String:er.string(),pageImageBase64String:er.string(),id:er.string().uuid(),timeoutMs:er.number().max(1e4).min(0).optional()});import{z as D}from"zod";import*as j from"zod";import{extendZodWithOpenApi as D1}from"zod-openapi";import Qc from"zod";var Zc=Qc.object({updatedAt:Qc.coerce.date().optional()}),Na=Qc.object({contentType:Qc.enum(["image/jpeg","image/png"]),id:Qc.string()});D1(j);var Lo=(s=>(s.AI="AI",s.AI_HEALED="AI_HEALED",s.CLICK_TO_FIND="CLICK_TO_FIND",s.XY_PERCENT="XY_PERCENT",s.RECORDING="RECORDING",s.USER_CSS_SELECTOR="USER_CSS_SELECTOR",s.HEURISTIC_HEALED="HEURISTIC_HEALED",s))(Lo||{}),k1=j.object({mPathSelectorTokens:j.string().array(),frameSrcRegex:j.string().optional(),frameUrlRegex:j.string().optional(),indices:j.number().array()}),eu=j.object({result:j.number(),traceId:j.string()}).array(),lo=j.object({type:j.literal("GCS_TRACES"),traces:eu}),en=(o=>(o.PRECISE="precise",o.NARROW="narrow",o.BROAD="broad",o.IRRELEVANT="irrelevant",o))(en||{}),tC=j.object({attributes:j.record(j.string(),j.string()).optional(),text:j.string().optional(),position:j.object({x1:j.number(),y1:j.number(),x2:j.number(),y2:j.number(),tolerance:j.nativeEnum(en)}).optional(),shape:j.object({width:j.number(),height:j.number(),tolerance:j.nativeEnum(en)}).optional(),boundingBox:j.object({x:j.number(),y:j.number(),width:j.number(),height:j.number()}).optional()}),F1=j.object({selectors:j.string().array(),requirements:tC.optional(),relativeAngleRadians:j.number().min(0).max(2*Math.PI).optional(),relativeDistance:j.number().optional()}),li=j.object({id:j.number().int(),dataMomenticId:j.number().int().optional(),selector:j.string().optional(),hybridSelector:j.object({textContent:j.string().nullish(),attributes:j.record(j.string(),j.string().optional()),tagName:j.string(),expandShadowRoot:j.boolean().optional(),classNames:j.string().array(),nthChild:j.number()}).array().optional(),generatedSelectors:j.string().array().optional(),requirements:tC.optional(),additionalElements:F1.array().optional(),role:j.string().optional(),name:j.string().optional(),numChildren:j.number().optional(),content:j.string().optional(),pathFromRoot:j.string().optional(),serializedHtml:j.string().optional().describe("pruned html including 1 neighbor and 1 layer of children. value for text inputs pruned."),nodeOnlySerializedHtml:j.string().optional().describe("outerHtml of the element without any children. value for text inputs pruned."),screenshotUrl:j.string().url().optional().or(Na.optional()),boundingBox:j.object({x:j.number().optional(),y:j.number().optional(),width:j.number(),height:j.number()}).describe("css pixel bounding box").optional(),frameCache:k1.optional(),inputDescription:j.string().optional().describe("the description that generated this cache"),targetSource:j.nativeEnum(Lo).optional(),targetUpdateTime:j.string().optional(),targetUpdateLoggerTags:j.record(j.string(),j.string()).optional(),cacheResolutionUpdateSource:j.string().optional(),cacheResolutionUpdateTime:j.string().optional(),cacheResolutionUpdateLoggerTags:j.record(j.string(),j.string()).optional(),memory:lo.optional()}).openapi({ref:"ElementTargetCache"});function rl(t){return!!(t.serializedHtml||t.screenshotUrl||t.generatedSelectors||t.hybridSelector)}var U1=j.object({type:j.literal("description"),elementDescriptor:j.string().describe("Description of the element.")}).openapi({ref:"DescriptionTarget"}),B1=j.object({x:j.number(),y:j.number()}),z1=j.object({type:j.literal("coordinates"),pixels:B1}).openapi({ref:"CoordinatesTarget"});function zi(t){return t.type==="description"}function No(t){return t.type==="coordinates"}var xr=j.discriminatedUnion("type",[U1,z1]).openapi({ref:"ElementTarget"});function CS(t){if(!t)return!1;switch(t.type){case"description":return!!t.elementDescriptor}return!0}function _r(t){if(!t)return"";switch(t.type){case"description":return t.elementDescriptor;case"coordinates":return`x: ${t.pixels.x}, y: ${t.pixels.y}`}}function kp(t){return lo.safeParse(t).success}import{v4 as lt}from"uuid";import*as w from"zod";import{extendZodWithOpenApi as J1}from"zod-openapi";import{z as He}from"zod";import{extendZodWithOpenApi as H1}from"zod-openapi";import{z as tu}from"zod";var ru=tu.object({result:tu.boolean(),traceId:tu.string()}).array(),Da=tu.object({type:tu.literal("GCS_TRACES"),traces:ru}),RS=Zc.extend({memory:Da.optional()});var nl=(b=>(b.MissingScript="missing-script",b.EvaluationError="evaluation-error",b.NoSelectors="no-selectors",b.NoSelectorsMatched="no-selectors-matched",b.NotEnoughSelectorsMatched="not-enough-selectors-matched",b.CandidateHasNoBoundingBox="candidate-has-no-bounding-box",b.AdditionalElementsDoNotExist="additional-elements-do-not-exist",b.BoundingBoxChanged="bounding-box-changed",b.FailedLdistCheck="failing-ldist",b.FailedTextRequirements="failed-text-requirements",b.FailedAttributeRequirements="failed-attribute-requirements",b.FailedBoundingBoxRequirements="failed-bounding-box-requirements",b.FailedPositionRequirements="failed-position-requirements",b.FailedShapeRequirements="failed-shape-requirements",b.NoWinnerFound="no-winner-found",b.AmbiguousWinner="ambiguous-winner",b.WeakWinner="weak-winner",b.SecondaryResolutionFailed="secondary-resolution-failed",b.CouldNotFindIframe="could-not-find-iframe",b.Unknown="unknown",b))(nl||{});H1(He);var rC=He.object({thoughts:He.string(),result:He.boolean(),relevantElements:He.array(He.number()).optional(),updatedMemory:ru.optional()}),On=(o=>(o.CONTAINS="CONTAINS",o.STARTS_WITH="STARTS_WITH",o.EQUALS="EQUALS",o.EXISTS="EXISTS",o))(On||{});var wS=["EXISTS","VISIBLE","ENABLED","EDITABLE","FOCUSED","CONTENT_CONTAINS","CONTENT_EQUALS","CONTENT_STARTS_WITH","ATTRIBUTE_CONTAINS","ATTRIBUTE_EQUALS","ATTRIBUTE_STARTS_WITH","NAME_CONTAINS","NAME_EQUALS","NAME_STARTS_WITH","STYLE_CONTAINS","STYLE_EQUALS","STYLE_STARTS_WITH"],G1=He.object({type:He.literal("ELEMENT_NAME"),negated:He.boolean().optional(),operation:He.nativeEnum(On),value:He.string()}).openapi({ref:"ElementNameAssertion"}),j1=He.object({type:He.literal("ELEMENT_STYLE"),negated:He.boolean().optional(),operation:He.nativeEnum(On),property:He.string(),value:He.string()}).openapi({ref:"ElementStyleAssertion"}),V1=He.object({type:He.literal("ELEMENT_CONTENT"),negated:He.boolean().optional(),operation:He.nativeEnum(On),value:He.string()}).openapi({ref:"ElementContentAssertion"}),W1=He.object({type:He.literal("ELEMENT_ATTRIBUTE"),negated:He.boolean().optional(),operation:He.nativeEnum(On),attr:He.string(),value:He.string()}).openapi({ref:"ElementAttributeValueAssertion"}),co=(i=>(i.EXISTS="EXISTS",i.VISIBLE="VISIBLE",i.ENABLED="ENABLED",i.EDITABLE="EDITABLE",i.FOCUSED="FOCUSED",i))(co||{});var $1=He.object({type:He.literal("ELEMENT_EXISTENCE"),negated:He.boolean().optional(),condition:He.nativeEnum(co).describe("Treated as the element exists AND is also ...")}).openapi({ref:"ElementExistenceAssertion"}),Fp=He.discriminatedUnion("type",[V1,W1,$1,G1,j1]).openapi({ref:"ManualElementAssertion"});var q1=He.object({type:He.literal("CONTENT"),negated:He.boolean().optional(),value:He.string()}).openapi({ref:"PageContentAssertion"}),nC=He.discriminatedUnion("type",[q1]).openapi({ref:"ManualPageAssertion"});import Hr from"zod";var xS=Hr.discriminatedUnion("type",[Hr.object({type:Hr.literal("SUBSTRING"),url:Hr.string()}),Hr.object({type:Hr.literal("GLOB"),glob:Hr.string()}),Hr.object({type:Hr.literal("REGEX"),regex:Hr.string()}),Hr.object({type:Hr.literal("DOMAIN"),domain:Hr.string()})]),Do=Hr.object({urlMatcher:xS,method:Hr.string().optional()});import{z as Fe}from"zod";var K1=Fe.object({type:Fe.literal("json"),content:Fe.string().describe("The JSON content to send in the request body")}),Y1=Fe.object({type:Fe.literal("form-urlencoded"),content:Fe.record(Fe.string(),Fe.string()).describe("The form fields to send in the request body")}),X1=Fe.discriminatedUnion("type",[K1,Y1]),ka=Fe.object({url:Fe.string(),method:Fe.union([Fe.literal("GET"),Fe.literal("POST"),Fe.literal("PUT"),Fe.literal("DELETE"),Fe.literal("PATCH")]),headers:Fe.record(Fe.string(),Fe.string()).optional(),params:Fe.record(Fe.string(),Fe.string()).optional(),body:X1.optional(),timeout:Fe.number().int().optional().describe("Max seconds to wait for the request to complete")}),oC=Fe.object({url:Fe.string(),headers:Fe.record(Fe.string(),Fe.string()).optional(),query:Fe.string(),variables:Fe.string().optional(),timeout:Fe.number().int().optional().describe("Max seconds to wait for the request to complete")}),Up=Fe.object({code:Fe.string(),fragment:Fe.boolean().optional().describe("Agents should not touch this unless explicitly told to"),environment:Fe.union([Fe.literal("NODE"),Fe.literal("BROWSER")]).optional().describe("default NODE, Agents default to using node unless it is necessary to use browser"),timeout:Fe.number().int().max(60).optional().describe("Max seconds for the code to complete")});var rt=(ce=>(ce.AI_EXTRACT="AI_EXTRACT",ce.AI_ASSERTION="AI_ASSERTION",ce.AUTH_LOAD="AUTH_LOAD",ce.AUTH_SAVE="AUTH_SAVE",ce.BLUR="BLUR",ce.CAPTCHA="CAPTCHA",ce.CLICK="CLICK",ce.COOKIE="COOKIE",ce.COPY="COPY",ce.DIALOG="DIALOG",ce.DRAG="DRAG",ce.ELEMENT_CHECK="ELEMENT_CHECK",ce.FILE_UPLOAD="FILE_UPLOAD",ce.FOCUS="FOCUS",ce.GO_BACK="GO_BACK",ce.GO_FORWARD="GO_FORWARD",ce.HOVER="HOVER",ce.JAVASCRIPT="JAVASCRIPT",ce.LOCAL_STORAGE="LOCAL_STORAGE",ce.MOUSE_DRAG="MOUSE_DRAG",ce.NAVIGATE="NAVIGATE",ce.NEW_TAB="NEW_TAB",ce.PAGE_CHECK="PAGE_CHECK",ce.PASTE="PASTE",ce.PRESS="PRESS",ce.KEY_DOWN="KEY_DOWN",ce.KEY_UP="KEY_UP",ce.REFRESH="REFRESH",ce.REQUEST="REQUEST",ce.GRAPHQL_REQUEST="GRAPHQL_REQUEST",ce.SCROLL_DOWN="SCROLL_DOWN",ce.SCROLL_UP="SCROLL_UP",ce.SCROLL_LEFT="SCROLL_LEFT",ce.SCROLL_RIGHT="SCROLL_RIGHT",ce.SELECT_OPTION="SELECT_OPTION",ce.SWITCH_TAB="TAB",ce.TYPE="TYPE",ce.VISUAL_DIFF="VISUAL_DIFF",ce.WAIT="WAIT",ce.WAIT_FOR_URL="WAIT_FOR_URL",ce.REGISTER_REQUEST_LISTENER="REGISTER_REQUEST_LISTENER",ce.AWAIT_LISTENER="AWAIT_LISTENER",ce.RECORD_REQUESTS="RECORD_REQUESTS",ce.GET_RECORDED_REQUESTS="GET_RECORDED_REQUESTS",ce.SET_HEADER="SET_HEADER",ce.MOCK_ROUTE="MOCK_ROUTE",ce.REMOVE_ROUTE_MOCK="REMOVE_ROUTE_MOCK",ce.OFFLINE_MODE="OFFLINE_MODE",ce.SUCCESS="SUCCESS",ce))(rt||{});J1(w);var he=w.object({thoughts:w.string().optional(),id:w.string().uuid().describe("unique identifier to this step, used for step cache")}),Ln=w.object({useSelector:w.boolean().optional(),force:w.boolean().optional(),disableCache:w.boolean().optional().describe("disable element caching for this step"),iframeUrl:w.string().optional().describe("url or url regex for the iframe")}).openapi({ref:"CommonTargetingOptions"}),mn=Zc.extend({target:li}).optional().openapi({ref:"SingleTargetCache"});function Bp(t){return!!t&&mn.safeParse(t).success}var zp=w.object({loadTimeout:w.number().int().max(60).optional().describe("Max seconds for the page to load")}),iC=he.merge(zp).merge(w.object({type:w.literal("NAVIGATE"),url:w.string()})).openapi({ref:"NavigateCommand"}),Hp=Ln.merge(w.object({cache:mn})),Fa=he.merge(Hp.merge(w.object({target:xr.optional(),type:w.literal("SCROLL_UP"),deltaY:w.number().optional()}))).openapi({ref:"ScrollUpCommand"}),Ua=he.merge(Hp.merge(w.object({target:xr.optional(),type:w.literal("SCROLL_DOWN"),deltaY:w.number().optional()}))).openapi({ref:"ScrollDownCommand"}),ol=he.merge(Hp.merge(w.object({target:xr.optional(),type:w.literal("SCROLL_LEFT"),deltaX:w.number().optional()}))).openapi({ref:"ScrollLeftCommand"}),il=he.merge(Hp.merge(w.object({target:xr.optional(),type:w.literal("SCROLL_RIGHT"),deltaX:w.number().optional()}))).openapi({ref:"ScrollRightCommand"}),Bre=w.discriminatedUnion("type",[Fa,Ua,ol,il]).openapi({ref:"AllScrollCommands"}),Q1=he.merge(w.object({type:w.literal("DIALOG"),action:w.union([w.literal("ACCEPT"),w.literal("DISMISS")])})).openapi({ref:"DialogCommand"}),aC=he.merge(w.object({type:w.literal("WAIT"),delay:w.number()})).openapi({ref:"WaitCommand"}),Z1=w.object({caseInsensitive:w.boolean().optional().describe("Whether to ignore case when matching the URL"),negated:w.boolean().optional().describe("Wait for the URL to NOT match the provided matcher instead."),timeout:w.number().int().optional().describe("Max seconds to wait for the URL to match")}),sC=he.extend({type:w.literal("WAIT_FOR_URL"),matcher:xS}).merge(Z1).openapi({ref:"WaitUrlCommand"}),lC=he.merge(zp).merge(w.object({type:w.literal("REFRESH")})).openapi({ref:"RefreshCommand"}),cC=he.merge(w.object({type:w.literal("GO_BACK")})).openapi({ref:"GoBackCommand"}),uC=he.merge(w.object({type:w.literal("GO_FORWARD")})).openapi({ref:"GoForwardCommand"}),eH=he.extend({type:w.literal("AUTH_SAVE")}).openapi({ref:"AuthSaveCommand"}),tH=he.extend({type:w.literal("AUTH_LOAD"),storageState:w.string().describe("JSON string auth state. Leave blank or set to the empty string to clear all existing authentication.")}).openapi({ref:"AuthLoadCommand"}),_S=he.merge(Ln).extend({type:w.literal("CAPTCHA")}).openapi({ref:"CaptchaCommand"}),dC=he.extend({type:w.literal("COPY"),value:w.string()}).openapi({ref:"CopyCommand"}),pC=he.extend({type:w.literal("PASTE")}).openapi({ref:"PasteCommand"}),mC=he.merge(Up).extend({type:w.literal("JAVASCRIPT")}).openapi({ref:"JavaScriptCommand"}),al=he.merge(Ln).extend({type:w.literal("CLICK"),target:xr,doubleClick:w.boolean().optional(),rightClick:w.boolean().optional(),waitForDownload:w.boolean().optional().describe("Wait for the click to trigger a file download and for the file download to complete."),delayMs:w.number().optional(),downloadTimeoutMs:w.number().optional(),cache:mn,relativePosition:w.object({x:w.number(),y:w.number()}).optional()}).openapi({ref:"ClickCommand"}),IS=Zc.extend({fromTarget:li.optional(),toTarget:li.optional()}),sl=he.merge(Ln).merge(w.object({type:w.literal("DRAG"),fromTarget:xr,toTarget:xr,steps:w.number().optional(),hoverSeconds:w.number().optional().describe("Seconds to hover the object before dropping"),cache:IS.optional()})).openapi({ref:"DragCommand"}),ll=he.merge(Ln).merge(w.object({type:w.literal("MOUSE_DRAG"),target:xr.optional(),deltaX:w.string().describe("pixels to move horizontally, can be template"),deltaY:w.string().describe("pixels to move vertically, can be template"),steps:w.number().optional(),cache:mn})).openapi({ref:"MouseDragCommand"}),cl=he.merge(Ln).merge(w.object({type:w.literal("HOVER"),target:xr,cache:mn})).openapi({ref:"HoverCommand"}),ou=he.merge(Ln).merge(w.object({type:w.literal("FOCUS"),target:xr,cache:mn})).openapi({ref:"FocusCommand"}),iu=he.merge(Ln).extend({type:w.literal("BLUR"),target:xr.optional(),cache:mn}).openapi({ref:"BlurCommand"}),rH=w.object({type:w.literal("URL"),url:w.string()}).describe("Accessible link to the file, either public http or local file://").openapi({ref:"UrlSource"}),nH=w.object({type:w.literal("USER_FILE"),name:w.string()}).describe("Accessible link to the file, references the google cloud file").openapi({ref:"UploadedFileSource"}),oH=he.extend({type:w.literal("FILE_UPLOAD"),fileSource:w.discriminatedUnion("type",[rH,nH]),filename:w.string().optional()}).openapi({ref:"FileUploadCommand"}),PS=w.discriminatedUnion("type",[w.object({type:w.literal("VALUE"),value:w.string()}),w.object({type:w.literal("LABEL"),label:w.string()}),w.object({type:w.literal("INDEX"),index:w.coerce.string()})]),ul=he.merge(Ln).extend({type:w.literal("SELECT_OPTION"),target:xr,cache:mn,choice:PS.describe("new field for selecting options, optional for backcompat")}).openapi({ref:"SelectOptionCommand"}),MS=w.union([w.literal("MULTIMODAL"),w.literal("VISION_ONLY")]),au=he.merge(w.object({type:w.literal("AI_ASSERTION"),assertion:w.string(),disableCache:w.boolean().optional(),iframeUrl:w.string().optional(),contextChoice:MS.optional(),timeout:w.number().int().optional().describe("Max seconds to wait for assertion to be true"),cache:RS.optional(),source:w.string().optional()})).openapi({ref:"AIAssertionCommand"}),Nn=5,Ba=600,dl=he.merge(Ln).extend({type:w.literal("ELEMENT_CHECK"),target:xr,assertion:Fp,cache:mn.or(RS).optional(),timeout:w.number().int().min(0).max(Ba).optional().describe("max seconds to wait for the assertion to be true")}).openapi({ref:"ElementAssertionCommand"}),fC=he.extend({type:w.literal("PAGE_CHECK"),assertion:nC,iframeUrl:w.string().optional().describe("url or url regex for the iframe"),timeout:w.number().int().min(0).max(Ba).optional().describe("max seconds to wait for the assertion to be true")}).openapi({ref:"PageAssertionCommand"}),hC=he.merge(w.object({type:w.literal("AI_EXTRACT"),goal:w.string(),schema:w.string().optional(),envKey:w.string().optional(),disableCache:w.boolean().optional(),iframeUrl:w.string().optional()})).openapi({ref:"AIExtractCommand"}),iH=w.object({clearContent:w.boolean().optional(),forceClearContent:w.boolean().optional(),delay:w.number().min(0).max(1e3).optional().describe("Delay between each press in milliseconds."),force:w.boolean().optional(),pressEnter:w.boolean().optional(),relativePosition:w.object({x:w.number(),y:w.number()}).optional()}),gC=25,pl=he.merge(Ln).merge(iH).extend({type:w.literal("TYPE"),target:xr.optional(),value:w.string(),cache:mn}).openapi({ref:"TypeCommand"}),SC=he.merge(w.object({type:w.literal("PRESS"),value:w.string(),repeat:w.number().optional(),convertMeta:w.boolean().optional(),delayMs:w.number().optional()})).openapi({ref:"PressCommand"}),yC=he.merge(w.object({type:w.literal("KEY_DOWN"),value:w.string(),convertMeta:w.boolean().optional()})).openapi({ref:"KeyDownCommand"}),EC=he.merge(w.object({type:w.literal("KEY_UP"),value:w.string(),convertMeta:w.boolean().optional()})).openapi({ref:"KeyUpCommand"}),aH=w.object({type:w.literal("SUBSTRING"),substring:w.string()}),sH=w.object({type:w.literal("REGEX"),pattern:w.string()}),lH=w.object({type:w.literal("INDEX"),index:w.coerce.string()}),cH=w.discriminatedUnion("type",[aH,sH,lH]),uH=he.merge(zp).merge(w.object({type:w.literal("TAB"),action:cH})).openapi({ref:"TabCommand"}),TC=he.merge(zp).merge(w.object({type:w.literal("NEW_TAB"),url:w.string()})).openapi({ref:"NewTabCommand"}),dH=he.merge(w.object({type:w.literal("COOKIE"),value:w.string()})).openapi({ref:"CookieCommand"}),bC=he.merge(w.object({type:w.literal("LOCAL_STORAGE"),key:w.string(),value:w.string()})).openapi({ref:"LocalStorageCommand"}),vC=he.extend({type:w.literal("REQUEST")}).merge(ka).openapi({ref:"RequestCommand"}),su=w.object({status:w.number().optional(),headers:w.record(w.string(),w.string()),json:w.unknown().optional(),text:w.string().optional(),cookies:w.record(w.string(),w.unknown()).array().optional(),request:w.object({url:w.string(),method:w.string(),headers:w.record(w.string(),w.string()),json:w.unknown().optional()})}),AC=he.extend({type:w.literal("GRAPHQL_REQUEST")}).merge(oC).openapi({ref:"GraphQLRequestCommand"}),CC=he.merge(w.object({type:w.literal("SUCCESS"),condition:au.optional()})).openapi({ref:"SuccessCommand"}),RC=he.merge(w.object({type:w.literal("FAILURE")})).openapi({ref:"FailureCommand"}),pH=w.object({data:w.union([w.string().describe("location at which to find a jpg - public URL or local"),Na]),width:w.number(),height:w.number()});function wC(t){return t?Na.safeParse(t).success:!1}var lu=he.merge(Ln).merge(w.object({type:w.literal("VISUAL_DIFF"),threshold:w.number().optional().describe("default 0.1"),target:xr.optional(),screenshot:pH.optional(),cache:mn})).openapi({ref:"VisualDiffCommand"}),xC=he.merge(w.object({type:w.literal("REGISTER_REQUEST_LISTENER"),requestMatcher:Do,key:w.string()})).openapi({ref:"RegisterRequestListenerCommand"}),mH=he.merge(w.object({type:w.literal("AWAIT_LISTENER"),key:w.string(),timeout:w.number().optional().describe("timeout")})).openapi({ref:"WaitForListenerCommand"}),_C=he.merge(w.object({type:w.literal("RECORD_REQUESTS"),requestMatcher:Do,key:w.string()})).openapi({ref:"RecordRequestsCommand"}),fH=he.merge(w.object({type:w.literal("GET_RECORDED_REQUESTS"),key:w.string()})).openapi({ref:"GetRecordedRequestsCommand"}),IC=he.merge(w.object({type:w.literal("SET_HEADER"),name:w.string(),value:w.string(),requestMatcher:Do.optional()})).openapi({ref:"SetHeaderCommand"}),PC=he.merge(w.object({type:w.literal("MOCK_ROUTE"),requestMatcher:Do,responseGenerator:w.string().describe("JavaScript code to generate a response"),fetchOriginalResponse:w.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:w.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"})),hH=he.merge(w.object({type:w.literal("REMOVE_ROUTE_MOCK"),key:w.string().optional().describe("Key of the mock to remove. If not set, all route mocks will be removed.")}).openapi({ref:"RemoveRouteMockCommandOptions"})),gH=he.merge(w.object({type:w.literal("OFFLINE_MODE"),enable:w.boolean()})).openapi({ref:"OfflineModeCommand"}),SH=["CLICK","TYPE","PRESS","KEY_DOWN","KEY_UP","SELECT_OPTION","NAVIGATE","SCROLL_DOWN","SCROLL_UP","AI_ASSERTION","GO_BACK","HOVER","WAIT"],zre=[...SH,"DRAG"],yH=w.discriminatedUnion("type",[al,pl,SC,yC,EC,ul,iC,Ua,Fa,au,cC,cl,aC]),EH=w.discriminatedUnion("type",[...yH.options,sl]),TH=w.discriminatedUnion("type",[...EH.options]),MC=w.discriminatedUnion("type",[...TH.options,CC]),OS=w.discriminatedUnion("type",[CC,al,pl,SC,yC,EC,ul,iC,Ua,Fa,au,cC,cl,aC,mC,dl,fC,TC,sC,hC,dC,uC,bC,sl,ll,pC,lC,vC,AC,IC,xC,_C,PC]),bH=w.discriminatedUnion("type",[hC,tH,eH,_S,dH,dC,Q1,dl,oH,uC,mC,bC,ll,TC,fC,pC,lC,vC,AC,ol,il,uH,lu,ou,iu,sC,xC,mH,_C,fH,IC,PC,hH,gH]),ml=w.discriminatedUnion("type",[...MC.options,...bH.options]).openapi({ref:"Command"}),Gp=w.discriminatedUnion("type",[...MC.options,RC]),Hre=w.discriminatedUnion("type",[...OS.options,RC]);function ci(t){let e;switch(t){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:lt(),type:t};break;case"AUTH_LOAD":{e={id:lt(),type:t,storageState:""};break}case"AI_EXTRACT":e={id:lt(),type:t,goal:""};break;case"DIALOG":e={id:lt(),type:t,action:"DISMISS"};break;case"DRAG":e={id:lt(),type:t,fromTarget:{type:"description",elementDescriptor:""},toTarget:{type:"description",elementDescriptor:""}};break;case"MOUSE_DRAG":e={id:lt(),type:t,deltaX:"0",deltaY:"0",steps:1};break;case"WAIT_FOR_URL":e={id:lt(),type:t,matcher:{type:"SUBSTRING",url:""}};break;case"WAIT":e={id:lt(),type:t,delay:1};break;case"BLUR":e={id:lt(),type:t};break;case"HOVER":case"FOCUS":case"CLICK":e={id:lt(),type:t,target:{type:"description",elementDescriptor:""}};break;case"COOKIE":case"PRESS":case"COPY":case"TYPE":e={id:lt(),type:t,value:"",clearContent:!0};break;case"KEY_DOWN":case"KEY_UP":e={id:lt(),type:t,value:""};break;case"SELECT_OPTION":e={id:lt(),type:t,target:{type:"description",elementDescriptor:""},choice:{type:"VALUE",value:""}};break;case"NAVIGATE":case"NEW_TAB":return{id:lt(),type:t,url:""};case"TAB":e={id:lt(),type:t,action:{type:"SUBSTRING",substring:""}};break;case"REQUEST":e={id:lt(),type:t,url:"",method:"GET"};break;case"GRAPHQL_REQUEST":e={id:lt(),type:t,url:"",query:""};break;case"LOCAL_STORAGE":e={id:lt(),type:t,key:"",value:""};break;case"JAVASCRIPT":e={id:lt(),type:t,code:""};break;case"AI_ASSERTION":e={id:lt(),type:t,assertion:""};break;case"FILE_UPLOAD":{e={id:lt(),type:t,fileSource:{type:"URL",url:""}};break}case"ELEMENT_CHECK":{e={id:lt(),type:t,target:{type:"description",elementDescriptor:""},assertion:{type:"ELEMENT_EXISTENCE",condition:"EXISTS"}};break}case"PAGE_CHECK":{e={id:lt(),type:t,assertion:{type:"CONTENT",value:""}};break}case"REGISTER_REQUEST_LISTENER":{e={id:lt(),type:t,requestMatcher:{urlMatcher:{type:"REGEX",regex:""}},key:""};break}case"AWAIT_LISTENER":{e={id:lt(),type:t,key:""};break}case"RECORD_REQUESTS":{e={id:lt(),type:t,requestMatcher:{urlMatcher:{type:"REGEX",regex:""}},key:""};break}case"GET_RECORDED_REQUESTS":{e={id:lt(),type:t,key:""};break}case"SET_HEADER":{e={id:lt(),type:t,name:"",value:""};break}case"MOCK_ROUTE":{e={id:lt(),type:t,requestMatcher:{urlMatcher:{type:"REGEX",regex:""}},responseGenerator:""};break}case"REMOVE_ROUTE_MOCK":{e={id:lt(),type:t};break}case"OFFLINE_MODE":{e={id:lt(),type:t,enable:!0};break}default:return(n=>{throw"If Typescript complains about the line below, you missed a case or break in the switch above"})(t)}return e}var Vre={AI_ASSERTION:"AI Check",ELEMENT_CHECK:"Element Check",JAVASCRIPT:"JavaScript",PAGE_CHECK:"Page Check"};import{z as vH}from"zod";var Yre=vH.discriminatedUnion("type",[iu,_S,al,sl,ou,cl,ll,Fa,Ua,ol,il,ul,pl,lu,dl]);function OC(t){return["AI_ASSERTION","ELEMENT_CHECK","PAGE_CHECK"].includes(t)}import{z as AH}from"zod";import{z as Gr}from"zod";function fl(t){return Gr.object({key:Gr.string(),testId:Gr.string().optional(),environment:Gr.string().optional(),moduleId:Gr.string().optional(),organizationId:Gr.string(),value:t})}function za(t){return Gr.object({key:Gr.string(),testId:Gr.string().optional(),environment:Gr.string().optional(),moduleId:Gr.string().optional(),organizationId:Gr.string(),value:t,uniqueKey:Gr.string()})}function LC(t){return Gr.record(Gr.string(),za(t))}var jr={type:!0,cache:!0},po=AH.discriminatedUnion("type",[au.pick(jr),iu.pick(jr),al.pick(jr),sl.pick(jr),dl.pick(jr),ou.pick(jr),cl.pick(jr),ll.pick(jr),Fa.pick(jr),Ua.pick(jr),ol.pick(jr),il.pick(jr),ul.pick(jr),pl.pick(jr),lu.pick(jr)]),jp=Object.values(rt).filter(t=>po.options.some(e=>e.shape.type.safeParse(t).success));ml.options.forEach(t=>{if("target"in t.shape&&!jp.includes(t.shape.type.value))throw new Error(`Command ${t.shape.type.value} has a target but no cache`)});function Hi(t){return jp.includes(t.type)}var NC=fl(po),DC=za(po),nne=LC(po);import{v4 as ct}from"uuid";import{z as O}from"zod";var FC=Symbol("Let zodToJsonSchema decide on which parser to use");var kC={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"},UC=t=>typeof t=="string"?{...kC,name:t}:{...kC,...t};var BC=t=>{let e=UC(t),r=e.name!==void 0?[...e.basePath,e.definitionPath,e.name]:e.basePath;return{...e,flags:{hasReferencedOpenAiAnyType:!1},currentPath:r,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 LS(t,e,r,n){n?.errorMessages&&r&&(t.errorMessage={...t.errorMessage,[e]:r})}function Ke(t,e,r,n,o){t[e]=r,LS(t,e,n,o)}var Vp=(t,e)=>{let r=0;for(;r<t.length&&r<e.length&&t[r]===e[r];r++);return[(t.length-r).toString(),...e.slice(r)].join("/")};import{ZodFirstPartyTypeKind as Ve}from"zod";function wt(t){if(t.target!=="openAi")return{};let e=[...t.basePath,t.definitionPath,t.openAiAnyTypeName];return t.flags.hasReferencedOpenAiAnyType=!0,{$ref:t.$refStrategy==="relative"?Vp(e,t.currentPath):e.join("/")}}import{ZodFirstPartyTypeKind as CH}from"zod";function zC(t,e){let r={type:"array"};return t.type?._def&&t.type?._def?.typeName!==CH.ZodAny&&(r.items=Se(t.type._def,{...e,currentPath:[...e.currentPath,"items"]})),t.minLength&&Ke(r,"minItems",t.minLength.value,t.minLength.message,e),t.maxLength&&Ke(r,"maxItems",t.maxLength.value,t.maxLength.message,e),t.exactLength&&(Ke(r,"minItems",t.exactLength.value,t.exactLength.message,e),Ke(r,"maxItems",t.exactLength.value,t.exactLength.message,e)),r}function HC(t,e){let r={type:"integer",format:"int64"};if(!t.checks)return r;for(let n of t.checks)switch(n.kind){case"min":e.target==="jsonSchema7"?n.inclusive?Ke(r,"minimum",n.value,n.message,e):Ke(r,"exclusiveMinimum",n.value,n.message,e):(n.inclusive||(r.exclusiveMinimum=!0),Ke(r,"minimum",n.value,n.message,e));break;case"max":e.target==="jsonSchema7"?n.inclusive?Ke(r,"maximum",n.value,n.message,e):Ke(r,"exclusiveMaximum",n.value,n.message,e):(n.inclusive||(r.exclusiveMaximum=!0),Ke(r,"maximum",n.value,n.message,e));break;case"multipleOf":Ke(r,"multipleOf",n.value,n.message,e);break}return r}function GC(){return{type:"boolean"}}function Wp(t,e){return Se(t.type._def,e)}var jC=(t,e)=>Se(t.innerType._def,e);function NS(t,e,r){let n=r??e.dateStrategy;if(Array.isArray(n))return{anyOf:n.map((o,i)=>NS(t,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 RH(t,e)}}var RH=(t,e)=>{let r={type:"integer",format:"unix-time"};if(e.target==="openApi3")return r;for(let n of t.checks)switch(n.kind){case"min":Ke(r,"minimum",n.value,n.message,e);break;case"max":Ke(r,"maximum",n.value,n.message,e);break}return r};function VC(t,e){return{...Se(t.innerType._def,e),default:t.defaultValue()}}function WC(t,e){return e.effectStrategy==="input"?Se(t.schema._def,e):wt(e)}function $C(t){return{type:"string",enum:Array.from(t.values)}}var wH=t=>"type"in t&&t.type==="string"?!1:"allOf"in t;function qC(t,e){let r=[Se(t.left._def,{...e,currentPath:[...e.currentPath,"allOf","0"]}),Se(t.right._def,{...e,currentPath:[...e.currentPath,"allOf","1"]})].filter(i=>!!i),n=e.target==="jsonSchema2019-09"?{unevaluatedProperties:!1}:void 0,o=[];return r.forEach(i=>{if(wH(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:s,...c}=i;a=c}else n=void 0;o.push(a)}}),o.length?{allOf:o,...n}:void 0}function KC(t,e){let r=typeof t.value;return r!=="bigint"&&r!=="number"&&r!=="boolean"&&r!=="string"?{type:Array.isArray(t.value)?"array":"object"}:e.target==="openApi3"?{type:r==="bigint"?"integer":r,enum:[t.value]}:{type:r==="bigint"?"integer":r,const:t.value}}import{ZodFirstPartyTypeKind as cu}from"zod";var DS,mo={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:()=>(DS===void 0&&(DS=RegExp("^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$","u")),DS),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 $p(t,e){let r={type:"string"};if(t.checks)for(let n of t.checks)switch(n.kind){case"min":Ke(r,"minLength",typeof r.minLength=="number"?Math.max(r.minLength,n.value):n.value,n.message,e);break;case"max":Ke(r,"maxLength",typeof r.maxLength=="number"?Math.min(r.maxLength,n.value):n.value,n.message,e);break;case"email":switch(e.emailStrategy){case"format:email":fo(r,"email",n.message,e);break;case"format:idn-email":fo(r,"idn-email",n.message,e);break;case"pattern:zod":Vr(r,mo.email,n.message,e);break}break;case"url":fo(r,"uri",n.message,e);break;case"uuid":fo(r,"uuid",n.message,e);break;case"regex":Vr(r,n.regex,n.message,e);break;case"cuid":Vr(r,mo.cuid,n.message,e);break;case"cuid2":Vr(r,mo.cuid2,n.message,e);break;case"startsWith":Vr(r,RegExp(`^${kS(n.value,e)}`),n.message,e);break;case"endsWith":Vr(r,RegExp(`${kS(n.value,e)}$`),n.message,e);break;case"datetime":fo(r,"date-time",n.message,e);break;case"date":fo(r,"date",n.message,e);break;case"time":fo(r,"time",n.message,e);break;case"duration":fo(r,"duration",n.message,e);break;case"length":Ke(r,"minLength",typeof r.minLength=="number"?Math.max(r.minLength,n.value):n.value,n.message,e),Ke(r,"maxLength",typeof r.maxLength=="number"?Math.min(r.maxLength,n.value):n.value,n.message,e);break;case"includes":{Vr(r,RegExp(kS(n.value,e)),n.message,e);break}case"ip":{n.version!=="v6"&&fo(r,"ipv4",n.message,e),n.version!=="v4"&&fo(r,"ipv6",n.message,e);break}case"base64url":Vr(r,mo.base64url,n.message,e);break;case"jwt":Vr(r,mo.jwt,n.message,e);break;case"cidr":{n.version!=="v6"&&Vr(r,mo.ipv4Cidr,n.message,e),n.version!=="v4"&&Vr(r,mo.ipv6Cidr,n.message,e);break}case"emoji":Vr(r,mo.emoji(),n.message,e);break;case"ulid":{Vr(r,mo.ulid,n.message,e);break}case"base64":{switch(e.base64Strategy){case"format:binary":{fo(r,"binary",n.message,e);break}case"contentEncoding:base64":{Ke(r,"contentEncoding","base64",n.message,e);break}case"pattern:zod":{Vr(r,mo.base64,n.message,e);break}}break}case"nanoid":Vr(r,mo.nanoid,n.message,e);case"toLowerCase":case"toUpperCase":case"trim":break;default:}return r}function kS(t,e){return e.patternStrategy==="escape"?_H(t):t}var xH=new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789");function _H(t){let e="";for(let r=0;r<t.length;r++)xH.has(t[r])||(e+="\\"),e+=t[r];return e}function fo(t,e,r,n){t.format||t.anyOf?.some(o=>o.format)?(t.anyOf||(t.anyOf=[]),t.format&&(t.anyOf.push({format:t.format,...t.errorMessage&&n.errorMessages&&{errorMessage:{format:t.errorMessage.format}}}),delete t.format,t.errorMessage&&(delete t.errorMessage.format,Object.keys(t.errorMessage).length===0&&delete t.errorMessage)),t.anyOf.push({format:e,...r&&n.errorMessages&&{errorMessage:{format:r}}})):Ke(t,"format",e,r,n)}function Vr(t,e,r,n){t.pattern||t.allOf?.some(o=>o.pattern)?(t.allOf||(t.allOf=[]),t.pattern&&(t.allOf.push({pattern:t.pattern,...t.errorMessage&&n.errorMessages&&{errorMessage:{pattern:t.errorMessage.pattern}}}),delete t.pattern,t.errorMessage&&(delete t.errorMessage.pattern,Object.keys(t.errorMessage).length===0&&delete t.errorMessage)),t.allOf.push({pattern:YC(e,n),...r&&n.errorMessages&&{errorMessage:{pattern:r}}})):Ke(t,"pattern",YC(e,n),r,n)}function YC(t,e){if(!e.applyRegexFlags||!t.flags)return t.source;let r={i:t.flags.includes("i"),m:t.flags.includes("m"),s:t.flags.includes("s")},n=r.i?t.source.toLowerCase():t.source,o="",i=!1,a=!1,s=!1;for(let c=0;c<n.length;c++){if(i){o+=n[c],i=!1;continue}if(r.i){if(a){if(n[c].match(/[a-z]/)){s?(o+=n[c],o+=`${n[c-2]}-${n[c]}`.toUpperCase(),s=!1):n[c+1]==="-"&&n[c+2]?.match(/[a-z]/)?(o+=n[c],s=!0):o+=`${n[c]}${n[c].toUpperCase()}`;continue}}else if(n[c].match(/[a-z]/)){o+=`[${n[c]}${n[c].toUpperCase()}]`;continue}}if(r.m){if(n[c]==="^"){o+=`(^|(?<=[\r
|
|
3
|
+
!function(){try{var e="undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof globalThis?globalThis:"undefined"!=typeof self?self:{},n=(new e.Error).stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="58b67399-a7d2-5cb5-8cb3-2de3e5b859f3")}catch(e){}}();
|
|
4
|
+
var w1=Object.create;var vS=Object.defineProperty;var x1=Object.getOwnPropertyDescriptor;var _1=Object.getOwnPropertyNames;var I1=Object.getPrototypeOf,P1=Object.prototype.hasOwnProperty;var Mt=(t,e)=>()=>(t&&(e=t(t=0)),e);var M1=(t,e)=>()=>(e||t((e={exports:{}}).exports,e),e.exports),O1=(t,e)=>{for(var r in e)vS(t,r,{get:e[r],enumerable:!0})},L1=(t,e,r,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of _1(e))!P1.call(t,o)&&o!==r&&vS(t,o,{get:()=>e[o],enumerable:!(n=x1(e,o))||n.enumerable});return t};var N1=(t,e,r)=>(r=t!=null?w1(I1(t)):{},L1(e||!t||!t.__esModule?vS(r,"default",{value:t,enumerable:!0}):r,t));var qI,KI=Mt(()=>{"use strict";qI=typeof globalThis=="object"?globalThis:global});var YI=Mt(()=>{"use strict";KI()});var XI=Mt(()=>{"use strict";YI()});var Si,ME=Mt(()=>{"use strict";Si="1.9.0"});function J$(t){var e=new Set([t]),r=new Set,n=t.match(JI);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===t};function i(s){return r.add(s),!1}function a(s){return e.add(s),!0}return function(c){if(e.has(c))return!0;if(r.has(c))return!1;var l=c.match(JI);if(!l)return i(c);var u={major:+l[1],minor:+l[2],patch:+l[3],prerelease:l[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 JI,QI,ZI=Mt(()=>{"use strict";ME();JI=/^(\d+)\.(\d+)\.(\d+)(-(.+))?$/;QI=J$(Si)});function Yl(t,e,r,n){var o;n===void 0&&(n=!1);var i=ud[cd]=(o=ud[cd])!==null&&o!==void 0?o:{version:Si};if(!n&&i[t]){var a=new Error("@opentelemetry/api: Attempted duplicate registration of API: "+t);return r.error(a.stack||a.message),!1}if(i.version!==Si){var a=new Error("@opentelemetry/api: Registration of version v"+i.version+" for "+t+" does not match previously registered API v"+Si);return r.error(a.stack||a.message),!1}return i[t]=e,r.debug("@opentelemetry/api: Registered a global for "+t+" v"+Si+"."),!0}function yi(t){var e,r,n=(e=ud[cd])===null||e===void 0?void 0:e.version;if(!(!n||!QI(n)))return(r=ud[cd])===null||r===void 0?void 0:r[t]}function Xl(t,e){e.debug("@opentelemetry/api: Unregistering a global for "+t+" v"+Si+".");var r=ud[cd];r&&delete r[t]}var Q$,cd,ud,dd=Mt(()=>{"use strict";XI();ME();ZI();Q$=Si.split(".")[0],cd=Symbol.for("opentelemetry.js.api."+Q$),ud=qI});function pd(t,e,r){var n=yi("diag");if(n)return r.unshift(e),n[t].apply(n,eq([],Z$(r),!1))}var Z$,eq,eP,tP=Mt(()=>{"use strict";dd();Z$=function(t,e){var r=typeof Symbol=="function"&&t[Symbol.iterator];if(!r)return t;var n=r.call(t),o,i=[],a;try{for(;(e===void 0||e-- >0)&&!(o=n.next()).done;)i.push(o.value)}catch(s){a={error:s}}finally{try{o&&!o.done&&(r=n.return)&&r.call(n)}finally{if(a)throw a.error}}return i},eq=function(t,e,r){if(r||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 t.concat(i||Array.prototype.slice.call(e))},eP=function(){function t(e){this._namespace=e.namespace||"DiagComponentLogger"}return t.prototype.debug=function(){for(var e=[],r=0;r<arguments.length;r++)e[r]=arguments[r];return pd("debug",this._namespace,e)},t.prototype.error=function(){for(var e=[],r=0;r<arguments.length;r++)e[r]=arguments[r];return pd("error",this._namespace,e)},t.prototype.info=function(){for(var e=[],r=0;r<arguments.length;r++)e[r]=arguments[r];return pd("info",this._namespace,e)},t.prototype.warn=function(){for(var e=[],r=0;r<arguments.length;r++)e[r]=arguments[r];return pd("warn",this._namespace,e)},t.prototype.verbose=function(){for(var e=[],r=0;r<arguments.length;r++)e[r]=arguments[r];return pd("verbose",this._namespace,e)},t}()});var At,lf=Mt(()=>{"use strict";(function(t){t[t.NONE=0]="NONE",t[t.ERROR=30]="ERROR",t[t.WARN=50]="WARN",t[t.INFO=60]="INFO",t[t.DEBUG=70]="DEBUG",t[t.VERBOSE=80]="VERBOSE",t[t.ALL=9999]="ALL"})(At||(At={}))});function rP(t,e){t<At.NONE?t=At.NONE:t>At.ALL&&(t=At.ALL),e=e||{};function r(n,o){var i=e[n];return typeof i=="function"&&t>=o?i.bind(e):function(){}}return{error:r("error",At.ERROR),warn:r("warn",At.WARN),info:r("info",At.INFO),debug:r("debug",At.DEBUG),verbose:r("verbose",At.VERBOSE)}}var nP=Mt(()=>{"use strict";lf()});var tq,rq,nq,Go,md=Mt(()=>{"use strict";tP();nP();lf();dd();tq=function(t,e){var r=typeof Symbol=="function"&&t[Symbol.iterator];if(!r)return t;var n=r.call(t),o,i=[],a;try{for(;(e===void 0||e-- >0)&&!(o=n.next()).done;)i.push(o.value)}catch(s){a={error:s}}finally{try{o&&!o.done&&(r=n.return)&&r.call(n)}finally{if(a)throw a.error}}return i},rq=function(t,e,r){if(r||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 t.concat(i||Array.prototype.slice.call(e))},nq="diag",Go=function(){function t(){function e(o){return function(){for(var i=[],a=0;a<arguments.length;a++)i[a]=arguments[a];var s=yi("diag");if(s)return s[o].apply(s,rq([],tq(i),!1))}}var r=this,n=function(o,i){var a,s,c;if(i===void 0&&(i={logLevel:At.INFO}),o===r){var l=new Error("Cannot use diag as the logger for itself. Please use a DiagLogger implementation like ConsoleDiagLogger or a custom implementation");return r.error((a=l.stack)!==null&&a!==void 0?a:l.message),!1}typeof i=="number"&&(i={logLevel:i});var u=yi("diag"),d=rP((s=i.logLevel)!==null&&s!==void 0?s:At.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 Yl("diag",d,r,!0)};r.setLogger=n,r.disable=function(){Xl(nq,r)},r.createComponentLogger=function(o){return new eP(o)},r.verbose=e("verbose"),r.debug=e("debug"),r.info=e("info"),r.warn=e("warn"),r.error=e("error")}return t.instance=function(){return this._instance||(this._instance=new t),this._instance},t}()});var oP,iP=Mt(()=>{"use strict";oP=Symbol("BaggageEntryMetadata")});function OE(t){return typeof t!="string"&&(oq.error("Cannot create baggage metadata from unknown type: "+typeof t),t=""),{__TYPE__:oP,toString:function(){return t}}}var oq,aP=Mt(()=>{"use strict";md();iP();oq=Go.instance()});function LE(t){return Symbol.for(t)}var iq,NE,DE=Mt(()=>{"use strict";iq=function(){function t(e){var r=this;r._currentContext=e?new Map(e):new Map,r.getValue=function(n){return r._currentContext.get(n)},r.setValue=function(n,o){var i=new t(r._currentContext);return i._currentContext.set(n,o),i},r.deleteValue=function(n){var o=new t(r._currentContext);return o._currentContext.delete(n),o}}return t}(),NE=new iq});function UE(){return FE}var ds,aq,cf,sq,lq,cq,uq,kE,dq,pq,mq,FE,fq,hq,gq,Sq,yq,Eq,Tq,BE=Mt(()=>{"use strict";ds=function(){var t=function(e,r){return t=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])},t(e,r)};return function(e,r){if(typeof r!="function"&&r!==null)throw new TypeError("Class extends value "+String(r)+" is not a constructor or null");t(e,r);function n(){this.constructor=e}e.prototype=r===null?Object.create(r):(n.prototype=r.prototype,new n)}}(),aq=function(){function t(){}return t.prototype.createGauge=function(e,r){return hq},t.prototype.createHistogram=function(e,r){return gq},t.prototype.createCounter=function(e,r){return fq},t.prototype.createUpDownCounter=function(e,r){return Sq},t.prototype.createObservableGauge=function(e,r){return Eq},t.prototype.createObservableCounter=function(e,r){return yq},t.prototype.createObservableUpDownCounter=function(e,r){return Tq},t.prototype.addBatchObservableCallback=function(e,r){},t.prototype.removeBatchObservableCallback=function(e){},t}(),cf=function(){function t(){}return t}(),sq=function(t){ds(e,t);function e(){return t!==null&&t.apply(this,arguments)||this}return e.prototype.add=function(r,n){},e}(cf),lq=function(t){ds(e,t);function e(){return t!==null&&t.apply(this,arguments)||this}return e.prototype.add=function(r,n){},e}(cf),cq=function(t){ds(e,t);function e(){return t!==null&&t.apply(this,arguments)||this}return e.prototype.record=function(r,n){},e}(cf),uq=function(t){ds(e,t);function e(){return t!==null&&t.apply(this,arguments)||this}return e.prototype.record=function(r,n){},e}(cf),kE=function(){function t(){}return t.prototype.addCallback=function(e){},t.prototype.removeCallback=function(e){},t}(),dq=function(t){ds(e,t);function e(){return t!==null&&t.apply(this,arguments)||this}return e}(kE),pq=function(t){ds(e,t);function e(){return t!==null&&t.apply(this,arguments)||this}return e}(kE),mq=function(t){ds(e,t);function e(){return t!==null&&t.apply(this,arguments)||this}return e}(kE),FE=new aq,fq=new sq,hq=new cq,gq=new uq,Sq=new lq,yq=new dq,Eq=new pq,Tq=new mq});var En,sP=Mt(()=>{"use strict";(function(t){t[t.INT=0]="INT",t[t.DOUBLE=1]="DOUBLE"})(En||(En={}))});var bq,vq,lP,cP=Mt(()=>{"use strict";DE();bq=function(t,e){var r=typeof Symbol=="function"&&t[Symbol.iterator];if(!r)return t;var n=r.call(t),o,i=[],a;try{for(;(e===void 0||e-- >0)&&!(o=n.next()).done;)i.push(o.value)}catch(s){a={error:s}}finally{try{o&&!o.done&&(r=n.return)&&r.call(n)}finally{if(a)throw a.error}}return i},vq=function(t,e,r){if(r||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 t.concat(i||Array.prototype.slice.call(e))},lP=function(){function t(){}return t.prototype.active=function(){return NE},t.prototype.with=function(e,r,n){for(var o=[],i=3;i<arguments.length;i++)o[i-3]=arguments[i];return r.call.apply(r,vq([n],bq(o),!1))},t.prototype.bind=function(e,r){return r},t.prototype.enable=function(){return this},t.prototype.disable=function(){return this},t}()});var Aq,Cq,zE,Rq,uP,dP=Mt(()=>{"use strict";cP();dd();md();Aq=function(t,e){var r=typeof Symbol=="function"&&t[Symbol.iterator];if(!r)return t;var n=r.call(t),o,i=[],a;try{for(;(e===void 0||e-- >0)&&!(o=n.next()).done;)i.push(o.value)}catch(s){a={error:s}}finally{try{o&&!o.done&&(r=n.return)&&r.call(n)}finally{if(a)throw a.error}}return i},Cq=function(t,e,r){if(r||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 t.concat(i||Array.prototype.slice.call(e))},zE="context",Rq=new lP,uP=function(){function t(){}return t.getInstance=function(){return this._instance||(this._instance=new t),this._instance},t.prototype.setGlobalContextManager=function(e){return Yl(zE,e,Go.instance())},t.prototype.active=function(){return this._getContextManager().active()},t.prototype.with=function(e,r,n){for(var o,i=[],a=3;a<arguments.length;a++)i[a-3]=arguments[a];return(o=this._getContextManager()).with.apply(o,Cq([e,r,n],Aq(i),!1))},t.prototype.bind=function(e,r){return this._getContextManager().bind(e,r)},t.prototype._getContextManager=function(){return yi(zE)||Rq},t.prototype.disable=function(){this._getContextManager().disable(),Xl(zE,Go.instance())},t}()});var Jl,pP=Mt(()=>{"use strict";dP();Jl=uP.getInstance()});var ie,mP=Mt(()=>{"use strict";md();ie=Go.instance()});var wq,fP,hP=Mt(()=>{"use strict";BE();wq=function(){function t(){}return t.prototype.getMeter=function(e,r,n){return FE},t}(),fP=new wq});var HE,gP,SP=Mt(()=>{"use strict";hP();dd();md();HE="metrics",gP=function(){function t(){}return t.getInstance=function(){return this._instance||(this._instance=new t),this._instance},t.prototype.setGlobalMeterProvider=function(e){return Yl(HE,e,Go.instance())},t.prototype.getMeterProvider=function(){return yi(HE)||fP},t.prototype.getMeter=function(e,r,n){return this.getMeterProvider().getMeter(e,r,n)},t.prototype.disable=function(){Xl(HE,Go.instance())},t}()});var uf,yP=Mt(()=>{"use strict";SP();uf=gP.getInstance()});var yt=Mt(()=>{"use strict";aP();DE();lf();BE();sP();pP();mP();yP()});var PU=M1((sp,$v)=>{"use strict";(function(t,e){if(typeof sp=="object"&&typeof $v=="object")$v.exports=e();else if(typeof define=="function"&&define.amd)define([],e);else{var r=e();for(var n in r)(typeof sp=="object"?sp:t)[n]=r[n]}})(typeof self<"u"?self:sp,function(){return function(t){var e={};function r(n){if(e[n])return e[n].exports;var o=e[n]={i:n,l:!1,exports:{}};return t[n].call(o.exports,o,o.exports,r),o.l=!0,o.exports}return r.m=t,r.c=e,r.d=function(n,o,i){r.o(n,o)||Object.defineProperty(n,o,{enumerable:!0,get:i})},r.r=function(n){typeof Symbol<"u"&&Symbol.toStringTag&&Object.defineProperty(n,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(n,"__esModule",{value:!0})},r.t=function(n,o){if(1&o&&(n=r(n)),8&o||4&o&&typeof n=="object"&&n&&n.__esModule)return n;var i=Object.create(null);if(r.r(i),Object.defineProperty(i,"default",{enumerable:!0,value:n}),2&o&&typeof n!="string")for(var a in n)r.d(i,a,function(s){return n[s]}.bind(null,a));return i},r.n=function(n){var o=n&&n.__esModule?function(){return n.default}:function(){return n};return r.d(o,"a",o),o},r.o=function(n,o){return Object.prototype.hasOwnProperty.call(n,o)},r.p="",r(r.s=0)}([function(t,e,r){"use strict";var n;r.r(e),function(g){g[g.Empty=0]="Empty",g[g.InsideToken=1]="InsideToken",g[g.InsideSingleQuotedToken=2]="InsideSingleQuotedToken",g[g.InsideDoubleQuotedToken=3]="InsideDoubleQuotedToken",g[g.AfterEscapeInsideToken=4]="AfterEscapeInsideToken",g[g.AfterEscapeInsideSingleQuotedToken=5]="AfterEscapeInsideSingleQuotedToken",g[g.AfterEscapeInsideDoubleQuotedToken=6]="AfterEscapeInsideDoubleQuotedToken"}(n||(n={}));var o=function(g){return[null,null]},i={onCharacter:o,onWhitespace:o,onDoubleQuote:o,onSingleQuote:o,onEscape:o},a=function(){return(a=Object.assign||function(g){for(var E,y=1,b=arguments.length;y<b;y++)for(var C in E=arguments[y])Object.prototype.hasOwnProperty.call(E,C)&&(g[C]=E[C]);return g}).apply(this,arguments)},s=a({},i,{stateHandle:n.AfterEscapeInsideDoubleQuotedToken,onCharacter:function(g){return["\\"+g,n.InsideDoubleQuotedToken]},onWhitespace:function(g){return["\\"+g,n.InsideDoubleQuotedToken]},onSingleQuote:function(g){return["\\"+g,n.InsideDoubleQuotedToken]},onDoubleQuote:function(g){return[g,n.InsideDoubleQuotedToken]},onEscape:function(g){return[g,n.InsideDoubleQuotedToken]}}),c=a({},i,{stateHandle:n.AfterEscapeInsideSingleQuotedToken,onCharacter:function(g){return["\\"+g,n.InsideSingleQuotedToken]},onWhitespace:function(g){return["\\"+g,n.InsideSingleQuotedToken]},onSingleQuote:function(g){return[g,n.InsideSingleQuotedToken]},onDoubleQuote:function(g){return["\\"+g,n.InsideSingleQuotedToken]},onEscape:function(g){return[g,n.InsideSingleQuotedToken]}}),l=a({},i,{stateHandle:n.AfterEscapeInsideToken,onCharacter:function(g){return[g,n.InsideToken]},onWhitespace:function(g){return[g,n.InsideToken]},onSingleQuote:function(g){return[g,n.InsideToken]},onDoubleQuote:function(g){return[g,n.InsideToken]},onEscape:function(g){return[g,n.InsideToken]}}),u=a({},i,{stateHandle:n.Empty,onCharacter:function(g){return[g,n.InsideToken]},onSingleQuote:function(){return[null,n.InsideSingleQuotedToken]},onDoubleQuote:function(){return[null,n.InsideDoubleQuotedToken]},onEscape:function(){return[null,n.AfterEscapeInsideToken]}}),d=a({},i,{stateHandle:n.InsideDoubleQuotedToken,onCharacter:function(g){return[g,null]},onWhitespace:function(g){return[g,null]},onSingleQuote:function(g){return[g,null]},onDoubleQuote:function(){return["",n.Empty]},onEscape:function(){return["",n.AfterEscapeInsideDoubleQuotedToken]}}),p=a({},i,{stateHandle:n.InsideSingleQuotedToken,onCharacter:function(g){return[g,null]},onWhitespace:function(g){return[g,null]},onSingleQuote:function(){return["",n.Empty]},onDoubleQuote:function(g){return[g,null]},onEscape:function(){return["",n.AfterEscapeInsideSingleQuotedToken]}}),m=[u,a({},i,{stateHandle:n.InsideToken,onCharacter:function(g){return[g,null]},onWhitespace:function(){return[null,n.Empty]},onSingleQuote:function(){return["",n.InsideSingleQuotedToken]},onDoubleQuote:function(){return["",n.InsideDoubleQuotedToken]},onEscape:function(){return["",n.AfterEscapeInsideToken]}}),p,d,l,c,s];function f(g){for(var E=0,y=m;E<y.length;E++){var b=y[E];if(b.stateHandle===g)return b}throw new Error("State with handle = "+g+" cannot be found")}var h=function(){function g(){this.currentState=f(n.Empty)}return g.prototype.handleCharacter=function(E){var y=this.performTransition(E),b=y[0],C=y[1];return C!==null&&(this.currentState=f(C)),b},g.prototype.performTransition=function(E){var y=this.currentState;switch(E){case" ":return y.onWhitespace(E);case"'":return y.onSingleQuote(E);case'"':return y.onDoubleQuote(E);case"\\":return y.onEscape(E);default:return y.onCharacter(E)}},g}();function S(g){for(var E=new h,y=[],b=0,C=0,I=g;C<I.length;C++){var _=I[C],R=E.handleCharacter(_);R!==null?y[b]=y[b]?y[b]+R:R:y[b]&&b++}return y}r.d(e,"default",function(){return S}),S.default=S}]).default})});import gRe,{multistream as yRe}from"pino";import TRe from"pino-pretty";import{z as AS}from"zod";var ere=AS.object({input:AS.string(),agentConfigVersion:AS.string().optional()}),Dp="finish";import{z as er}from"zod";var nre=er.object({srcs:er.array(er.string()),urls:er.array(er.string()),desiredSrc:er.string().optional(),desiredUrl:er.string().optional()}),ZA=er.object({srcRegex:er.string().optional(),urlRegex:er.string().optional()}),eC=er.object({x:er.number(),y:er.number(),correlation:er.number()}),ore=er.object({searchImageBase64String:er.string(),pageImageBase64String:er.string(),id:er.string().uuid(),timeoutMs:er.number().max(1e4).min(0).optional()});import{z as D}from"zod";import*as j from"zod";import{extendZodWithOpenApi as D1}from"zod-openapi";import Qc from"zod";var Zc=Qc.object({updatedAt:Qc.coerce.date().optional()}),Na=Qc.object({contentType:Qc.enum(["image/jpeg","image/png"]),id:Qc.string()});D1(j);var Lo=(s=>(s.AI="AI",s.AI_HEALED="AI_HEALED",s.CLICK_TO_FIND="CLICK_TO_FIND",s.XY_PERCENT="XY_PERCENT",s.RECORDING="RECORDING",s.USER_CSS_SELECTOR="USER_CSS_SELECTOR",s.HEURISTIC_HEALED="HEURISTIC_HEALED",s))(Lo||{}),k1=j.object({mPathSelectorTokens:j.string().array(),frameSrcRegex:j.string().optional(),frameUrlRegex:j.string().optional(),indices:j.number().array()}),eu=j.object({result:j.number(),traceId:j.string()}).array(),lo=j.object({type:j.literal("GCS_TRACES"),traces:eu}),en=(o=>(o.PRECISE="precise",o.NARROW="narrow",o.BROAD="broad",o.IRRELEVANT="irrelevant",o))(en||{}),tC=j.object({attributes:j.record(j.string(),j.string()).optional(),text:j.string().optional(),position:j.object({x1:j.number(),y1:j.number(),x2:j.number(),y2:j.number(),tolerance:j.nativeEnum(en)}).optional(),shape:j.object({width:j.number(),height:j.number(),tolerance:j.nativeEnum(en)}).optional(),boundingBox:j.object({x:j.number(),y:j.number(),width:j.number(),height:j.number()}).optional()}),F1=j.object({selectors:j.string().array(),requirements:tC.optional(),relativeAngleRadians:j.number().min(0).max(2*Math.PI).optional(),relativeDistance:j.number().optional()}),li=j.object({id:j.number().int(),dataMomenticId:j.number().int().optional(),selector:j.string().optional(),hybridSelector:j.object({textContent:j.string().nullish(),attributes:j.record(j.string(),j.string().optional()),tagName:j.string(),expandShadowRoot:j.boolean().optional(),classNames:j.string().array(),nthChild:j.number()}).array().optional(),generatedSelectors:j.string().array().optional(),requirements:tC.optional(),additionalElements:F1.array().optional(),role:j.string().optional(),name:j.string().optional(),numChildren:j.number().optional(),content:j.string().optional(),pathFromRoot:j.string().optional(),serializedHtml:j.string().optional().describe("pruned html including 1 neighbor and 1 layer of children. value for text inputs pruned."),nodeOnlySerializedHtml:j.string().optional().describe("outerHtml of the element without any children. value for text inputs pruned."),screenshotUrl:j.string().url().optional().or(Na.optional()),boundingBox:j.object({x:j.number().optional(),y:j.number().optional(),width:j.number(),height:j.number()}).describe("css pixel bounding box").optional(),frameCache:k1.optional(),inputDescription:j.string().optional().describe("the description that generated this cache"),targetSource:j.nativeEnum(Lo).optional(),targetUpdateTime:j.string().optional(),targetUpdateLoggerTags:j.record(j.string(),j.string()).optional(),cacheResolutionUpdateSource:j.string().optional(),cacheResolutionUpdateTime:j.string().optional(),cacheResolutionUpdateLoggerTags:j.record(j.string(),j.string()).optional(),memory:lo.optional()}).openapi({ref:"ElementTargetCache"});function rl(t){return!!(t.serializedHtml||t.screenshotUrl||t.generatedSelectors||t.hybridSelector)}var U1=j.object({type:j.literal("description"),elementDescriptor:j.string().describe("Description of the element.")}).openapi({ref:"DescriptionTarget"}),B1=j.object({x:j.number(),y:j.number()}),z1=j.object({type:j.literal("coordinates"),pixels:B1}).openapi({ref:"CoordinatesTarget"});function zi(t){return t.type==="description"}function No(t){return t.type==="coordinates"}var xr=j.discriminatedUnion("type",[U1,z1]).openapi({ref:"ElementTarget"});function CS(t){if(!t)return!1;switch(t.type){case"description":return!!t.elementDescriptor}return!0}function _r(t){if(!t)return"";switch(t.type){case"description":return t.elementDescriptor;case"coordinates":return`x: ${t.pixels.x}, y: ${t.pixels.y}`}}function kp(t){return lo.safeParse(t).success}import{v4 as lt}from"uuid";import*as w from"zod";import{extendZodWithOpenApi as J1}from"zod-openapi";import{z as He}from"zod";import{extendZodWithOpenApi as H1}from"zod-openapi";import{z as tu}from"zod";var ru=tu.object({result:tu.boolean(),traceId:tu.string()}).array(),Da=tu.object({type:tu.literal("GCS_TRACES"),traces:ru}),RS=Zc.extend({memory:Da.optional()});var nl=(b=>(b.MissingScript="missing-script",b.EvaluationError="evaluation-error",b.NoSelectors="no-selectors",b.NoSelectorsMatched="no-selectors-matched",b.NotEnoughSelectorsMatched="not-enough-selectors-matched",b.CandidateHasNoBoundingBox="candidate-has-no-bounding-box",b.AdditionalElementsDoNotExist="additional-elements-do-not-exist",b.BoundingBoxChanged="bounding-box-changed",b.FailedLdistCheck="failing-ldist",b.FailedTextRequirements="failed-text-requirements",b.FailedAttributeRequirements="failed-attribute-requirements",b.FailedBoundingBoxRequirements="failed-bounding-box-requirements",b.FailedPositionRequirements="failed-position-requirements",b.FailedShapeRequirements="failed-shape-requirements",b.NoWinnerFound="no-winner-found",b.AmbiguousWinner="ambiguous-winner",b.WeakWinner="weak-winner",b.SecondaryResolutionFailed="secondary-resolution-failed",b.CouldNotFindIframe="could-not-find-iframe",b.Unknown="unknown",b))(nl||{});H1(He);var rC=He.object({thoughts:He.string(),result:He.boolean(),relevantElements:He.array(He.number()).optional(),updatedMemory:ru.optional()}),On=(o=>(o.CONTAINS="CONTAINS",o.STARTS_WITH="STARTS_WITH",o.EQUALS="EQUALS",o.EXISTS="EXISTS",o))(On||{});var wS=["EXISTS","VISIBLE","ENABLED","EDITABLE","FOCUSED","CONTENT_CONTAINS","CONTENT_EQUALS","CONTENT_STARTS_WITH","ATTRIBUTE_CONTAINS","ATTRIBUTE_EQUALS","ATTRIBUTE_STARTS_WITH","NAME_CONTAINS","NAME_EQUALS","NAME_STARTS_WITH","STYLE_CONTAINS","STYLE_EQUALS","STYLE_STARTS_WITH"],G1=He.object({type:He.literal("ELEMENT_NAME"),negated:He.boolean().optional(),operation:He.nativeEnum(On),value:He.string()}).openapi({ref:"ElementNameAssertion"}),j1=He.object({type:He.literal("ELEMENT_STYLE"),negated:He.boolean().optional(),operation:He.nativeEnum(On),property:He.string(),value:He.string()}).openapi({ref:"ElementStyleAssertion"}),V1=He.object({type:He.literal("ELEMENT_CONTENT"),negated:He.boolean().optional(),operation:He.nativeEnum(On),value:He.string()}).openapi({ref:"ElementContentAssertion"}),W1=He.object({type:He.literal("ELEMENT_ATTRIBUTE"),negated:He.boolean().optional(),operation:He.nativeEnum(On),attr:He.string(),value:He.string()}).openapi({ref:"ElementAttributeValueAssertion"}),co=(i=>(i.EXISTS="EXISTS",i.VISIBLE="VISIBLE",i.ENABLED="ENABLED",i.EDITABLE="EDITABLE",i.FOCUSED="FOCUSED",i))(co||{});var $1=He.object({type:He.literal("ELEMENT_EXISTENCE"),negated:He.boolean().optional(),condition:He.nativeEnum(co).describe("Treated as the element exists AND is also ...")}).openapi({ref:"ElementExistenceAssertion"}),Fp=He.discriminatedUnion("type",[V1,W1,$1,G1,j1]).openapi({ref:"ManualElementAssertion"});var q1=He.object({type:He.literal("CONTENT"),negated:He.boolean().optional(),value:He.string()}).openapi({ref:"PageContentAssertion"}),nC=He.discriminatedUnion("type",[q1]).openapi({ref:"ManualPageAssertion"});import Hr from"zod";var xS=Hr.discriminatedUnion("type",[Hr.object({type:Hr.literal("SUBSTRING"),url:Hr.string()}),Hr.object({type:Hr.literal("GLOB"),glob:Hr.string()}),Hr.object({type:Hr.literal("REGEX"),regex:Hr.string()}),Hr.object({type:Hr.literal("DOMAIN"),domain:Hr.string()})]),Do=Hr.object({urlMatcher:xS,method:Hr.string().optional()});import{z as Fe}from"zod";var K1=Fe.object({type:Fe.literal("json"),content:Fe.string().describe("The JSON content to send in the request body")}),Y1=Fe.object({type:Fe.literal("form-urlencoded"),content:Fe.record(Fe.string(),Fe.string()).describe("The form fields to send in the request body")}),X1=Fe.discriminatedUnion("type",[K1,Y1]),ka=Fe.object({url:Fe.string(),method:Fe.union([Fe.literal("GET"),Fe.literal("POST"),Fe.literal("PUT"),Fe.literal("DELETE"),Fe.literal("PATCH")]),headers:Fe.record(Fe.string(),Fe.string()).optional(),params:Fe.record(Fe.string(),Fe.string()).optional(),body:X1.optional(),timeout:Fe.number().int().optional().describe("Max seconds to wait for the request to complete")}),oC=Fe.object({url:Fe.string(),headers:Fe.record(Fe.string(),Fe.string()).optional(),query:Fe.string(),variables:Fe.string().optional(),timeout:Fe.number().int().optional().describe("Max seconds to wait for the request to complete")}),Up=Fe.object({code:Fe.string(),fragment:Fe.boolean().optional().describe("Agents should not touch this unless explicitly told to"),environment:Fe.union([Fe.literal("NODE"),Fe.literal("BROWSER")]).optional().describe("default NODE, Agents default to using node unless it is necessary to use browser"),timeout:Fe.number().int().max(60).optional().describe("Max seconds for the code to complete")});var rt=(ce=>(ce.AI_EXTRACT="AI_EXTRACT",ce.AI_ASSERTION="AI_ASSERTION",ce.AUTH_LOAD="AUTH_LOAD",ce.AUTH_SAVE="AUTH_SAVE",ce.BLUR="BLUR",ce.CAPTCHA="CAPTCHA",ce.CLICK="CLICK",ce.COOKIE="COOKIE",ce.COPY="COPY",ce.DIALOG="DIALOG",ce.DRAG="DRAG",ce.ELEMENT_CHECK="ELEMENT_CHECK",ce.FILE_UPLOAD="FILE_UPLOAD",ce.FOCUS="FOCUS",ce.GO_BACK="GO_BACK",ce.GO_FORWARD="GO_FORWARD",ce.HOVER="HOVER",ce.JAVASCRIPT="JAVASCRIPT",ce.LOCAL_STORAGE="LOCAL_STORAGE",ce.MOUSE_DRAG="MOUSE_DRAG",ce.NAVIGATE="NAVIGATE",ce.NEW_TAB="NEW_TAB",ce.PAGE_CHECK="PAGE_CHECK",ce.PASTE="PASTE",ce.PRESS="PRESS",ce.KEY_DOWN="KEY_DOWN",ce.KEY_UP="KEY_UP",ce.REFRESH="REFRESH",ce.REQUEST="REQUEST",ce.GRAPHQL_REQUEST="GRAPHQL_REQUEST",ce.SCROLL_DOWN="SCROLL_DOWN",ce.SCROLL_UP="SCROLL_UP",ce.SCROLL_LEFT="SCROLL_LEFT",ce.SCROLL_RIGHT="SCROLL_RIGHT",ce.SELECT_OPTION="SELECT_OPTION",ce.SWITCH_TAB="TAB",ce.TYPE="TYPE",ce.VISUAL_DIFF="VISUAL_DIFF",ce.WAIT="WAIT",ce.WAIT_FOR_URL="WAIT_FOR_URL",ce.REGISTER_REQUEST_LISTENER="REGISTER_REQUEST_LISTENER",ce.AWAIT_LISTENER="AWAIT_LISTENER",ce.RECORD_REQUESTS="RECORD_REQUESTS",ce.GET_RECORDED_REQUESTS="GET_RECORDED_REQUESTS",ce.SET_HEADER="SET_HEADER",ce.MOCK_ROUTE="MOCK_ROUTE",ce.REMOVE_ROUTE_MOCK="REMOVE_ROUTE_MOCK",ce.OFFLINE_MODE="OFFLINE_MODE",ce.SUCCESS="SUCCESS",ce))(rt||{});J1(w);var he=w.object({thoughts:w.string().optional(),id:w.string().uuid().describe("unique identifier to this step, used for step cache")}),Ln=w.object({useSelector:w.boolean().optional(),force:w.boolean().optional(),disableCache:w.boolean().optional().describe("disable element caching for this step"),iframeUrl:w.string().optional().describe("url or url regex for the iframe")}).openapi({ref:"CommonTargetingOptions"}),mn=Zc.extend({target:li}).optional().openapi({ref:"SingleTargetCache"});function Bp(t){return!!t&&mn.safeParse(t).success}var zp=w.object({loadTimeout:w.number().int().max(60).optional().describe("Max seconds for the page to load")}),iC=he.merge(zp).merge(w.object({type:w.literal("NAVIGATE"),url:w.string()})).openapi({ref:"NavigateCommand"}),Hp=Ln.merge(w.object({cache:mn})),Fa=he.merge(Hp.merge(w.object({target:xr.optional(),type:w.literal("SCROLL_UP"),deltaY:w.number().optional()}))).openapi({ref:"ScrollUpCommand"}),Ua=he.merge(Hp.merge(w.object({target:xr.optional(),type:w.literal("SCROLL_DOWN"),deltaY:w.number().optional()}))).openapi({ref:"ScrollDownCommand"}),ol=he.merge(Hp.merge(w.object({target:xr.optional(),type:w.literal("SCROLL_LEFT"),deltaX:w.number().optional()}))).openapi({ref:"ScrollLeftCommand"}),il=he.merge(Hp.merge(w.object({target:xr.optional(),type:w.literal("SCROLL_RIGHT"),deltaX:w.number().optional()}))).openapi({ref:"ScrollRightCommand"}),Bre=w.discriminatedUnion("type",[Fa,Ua,ol,il]).openapi({ref:"AllScrollCommands"}),Q1=he.merge(w.object({type:w.literal("DIALOG"),action:w.union([w.literal("ACCEPT"),w.literal("DISMISS")])})).openapi({ref:"DialogCommand"}),aC=he.merge(w.object({type:w.literal("WAIT"),delay:w.number()})).openapi({ref:"WaitCommand"}),Z1=w.object({caseInsensitive:w.boolean().optional().describe("Whether to ignore case when matching the URL"),negated:w.boolean().optional().describe("Wait for the URL to NOT match the provided matcher instead."),timeout:w.number().int().optional().describe("Max seconds to wait for the URL to match")}),sC=he.extend({type:w.literal("WAIT_FOR_URL"),matcher:xS}).merge(Z1).openapi({ref:"WaitUrlCommand"}),lC=he.merge(zp).merge(w.object({type:w.literal("REFRESH")})).openapi({ref:"RefreshCommand"}),cC=he.merge(w.object({type:w.literal("GO_BACK")})).openapi({ref:"GoBackCommand"}),uC=he.merge(w.object({type:w.literal("GO_FORWARD")})).openapi({ref:"GoForwardCommand"}),eH=he.extend({type:w.literal("AUTH_SAVE")}).openapi({ref:"AuthSaveCommand"}),tH=he.extend({type:w.literal("AUTH_LOAD"),storageState:w.string().describe("JSON string auth state. Leave blank or set to the empty string to clear all existing authentication.")}).openapi({ref:"AuthLoadCommand"}),_S=he.merge(Ln).extend({type:w.literal("CAPTCHA")}).openapi({ref:"CaptchaCommand"}),dC=he.extend({type:w.literal("COPY"),value:w.string()}).openapi({ref:"CopyCommand"}),pC=he.extend({type:w.literal("PASTE")}).openapi({ref:"PasteCommand"}),mC=he.merge(Up).extend({type:w.literal("JAVASCRIPT")}).openapi({ref:"JavaScriptCommand"}),al=he.merge(Ln).extend({type:w.literal("CLICK"),target:xr,doubleClick:w.boolean().optional(),rightClick:w.boolean().optional(),waitForDownload:w.boolean().optional().describe("Wait for the click to trigger a file download and for the file download to complete."),delayMs:w.number().optional(),downloadTimeoutMs:w.number().optional(),cache:mn,relativePosition:w.object({x:w.number(),y:w.number()}).optional()}).openapi({ref:"ClickCommand"}),IS=Zc.extend({fromTarget:li.optional(),toTarget:li.optional()}),sl=he.merge(Ln).merge(w.object({type:w.literal("DRAG"),fromTarget:xr,toTarget:xr,steps:w.number().optional(),hoverSeconds:w.number().optional().describe("Seconds to hover the object before dropping"),cache:IS.optional()})).openapi({ref:"DragCommand"}),ll=he.merge(Ln).merge(w.object({type:w.literal("MOUSE_DRAG"),target:xr.optional(),deltaX:w.string().describe("pixels to move horizontally, can be template"),deltaY:w.string().describe("pixels to move vertically, can be template"),steps:w.number().optional(),cache:mn})).openapi({ref:"MouseDragCommand"}),cl=he.merge(Ln).merge(w.object({type:w.literal("HOVER"),target:xr,cache:mn})).openapi({ref:"HoverCommand"}),ou=he.merge(Ln).merge(w.object({type:w.literal("FOCUS"),target:xr,cache:mn})).openapi({ref:"FocusCommand"}),iu=he.merge(Ln).extend({type:w.literal("BLUR"),target:xr.optional(),cache:mn}).openapi({ref:"BlurCommand"}),rH=w.object({type:w.literal("URL"),url:w.string()}).describe("Accessible link to the file, either public http or local file://").openapi({ref:"UrlSource"}),nH=w.object({type:w.literal("USER_FILE"),name:w.string()}).describe("Accessible link to the file, references the google cloud file").openapi({ref:"UploadedFileSource"}),oH=he.extend({type:w.literal("FILE_UPLOAD"),fileSource:w.discriminatedUnion("type",[rH,nH]),filename:w.string().optional()}).openapi({ref:"FileUploadCommand"}),PS=w.discriminatedUnion("type",[w.object({type:w.literal("VALUE"),value:w.string()}),w.object({type:w.literal("LABEL"),label:w.string()}),w.object({type:w.literal("INDEX"),index:w.coerce.string()})]),ul=he.merge(Ln).extend({type:w.literal("SELECT_OPTION"),target:xr,cache:mn,choice:PS.describe("new field for selecting options, optional for backcompat")}).openapi({ref:"SelectOptionCommand"}),MS=w.union([w.literal("MULTIMODAL"),w.literal("VISION_ONLY")]),au=he.merge(w.object({type:w.literal("AI_ASSERTION"),assertion:w.string(),disableCache:w.boolean().optional(),iframeUrl:w.string().optional(),contextChoice:MS.optional(),timeout:w.number().int().optional().describe("Max seconds to wait for assertion to be true"),cache:RS.optional(),source:w.string().optional()})).openapi({ref:"AIAssertionCommand"}),Nn=5,Ba=600,dl=he.merge(Ln).extend({type:w.literal("ELEMENT_CHECK"),target:xr,assertion:Fp,cache:mn.or(RS).optional(),timeout:w.number().int().min(0).max(Ba).optional().describe("max seconds to wait for the assertion to be true")}).openapi({ref:"ElementAssertionCommand"}),fC=he.extend({type:w.literal("PAGE_CHECK"),assertion:nC,iframeUrl:w.string().optional().describe("url or url regex for the iframe"),timeout:w.number().int().min(0).max(Ba).optional().describe("max seconds to wait for the assertion to be true")}).openapi({ref:"PageAssertionCommand"}),hC=he.merge(w.object({type:w.literal("AI_EXTRACT"),goal:w.string(),schema:w.string().optional(),envKey:w.string().optional(),disableCache:w.boolean().optional(),iframeUrl:w.string().optional()})).openapi({ref:"AIExtractCommand"}),iH=w.object({clearContent:w.boolean().optional(),forceClearContent:w.boolean().optional(),delay:w.number().min(0).max(1e3).optional().describe("Delay between each press in milliseconds."),force:w.boolean().optional(),pressEnter:w.boolean().optional(),relativePosition:w.object({x:w.number(),y:w.number()}).optional()}),gC=25,pl=he.merge(Ln).merge(iH).extend({type:w.literal("TYPE"),target:xr.optional(),value:w.string(),cache:mn}).openapi({ref:"TypeCommand"}),SC=he.merge(w.object({type:w.literal("PRESS"),value:w.string(),repeat:w.number().optional(),convertMeta:w.boolean().optional(),delayMs:w.number().optional()})).openapi({ref:"PressCommand"}),yC=he.merge(w.object({type:w.literal("KEY_DOWN"),value:w.string(),convertMeta:w.boolean().optional()})).openapi({ref:"KeyDownCommand"}),EC=he.merge(w.object({type:w.literal("KEY_UP"),value:w.string(),convertMeta:w.boolean().optional()})).openapi({ref:"KeyUpCommand"}),aH=w.object({type:w.literal("SUBSTRING"),substring:w.string()}),sH=w.object({type:w.literal("REGEX"),pattern:w.string()}),lH=w.object({type:w.literal("INDEX"),index:w.coerce.string()}),cH=w.discriminatedUnion("type",[aH,sH,lH]),uH=he.merge(zp).merge(w.object({type:w.literal("TAB"),action:cH})).openapi({ref:"TabCommand"}),TC=he.merge(zp).merge(w.object({type:w.literal("NEW_TAB"),url:w.string()})).openapi({ref:"NewTabCommand"}),dH=he.merge(w.object({type:w.literal("COOKIE"),value:w.string()})).openapi({ref:"CookieCommand"}),bC=he.merge(w.object({type:w.literal("LOCAL_STORAGE"),key:w.string(),value:w.string()})).openapi({ref:"LocalStorageCommand"}),vC=he.extend({type:w.literal("REQUEST")}).merge(ka).openapi({ref:"RequestCommand"}),su=w.object({status:w.number().optional(),headers:w.record(w.string(),w.string()),json:w.unknown().optional(),text:w.string().optional(),cookies:w.record(w.string(),w.unknown()).array().optional(),request:w.object({url:w.string(),method:w.string(),headers:w.record(w.string(),w.string()),json:w.unknown().optional()})}),AC=he.extend({type:w.literal("GRAPHQL_REQUEST")}).merge(oC).openapi({ref:"GraphQLRequestCommand"}),CC=he.merge(w.object({type:w.literal("SUCCESS"),condition:au.optional()})).openapi({ref:"SuccessCommand"}),RC=he.merge(w.object({type:w.literal("FAILURE")})).openapi({ref:"FailureCommand"}),pH=w.object({data:w.union([w.string().describe("location at which to find a jpg - public URL or local"),Na]),width:w.number(),height:w.number()});function wC(t){return t?Na.safeParse(t).success:!1}var lu=he.merge(Ln).merge(w.object({type:w.literal("VISUAL_DIFF"),threshold:w.number().optional().describe("default 0.1"),target:xr.optional(),screenshot:pH.optional(),cache:mn})).openapi({ref:"VisualDiffCommand"}),xC=he.merge(w.object({type:w.literal("REGISTER_REQUEST_LISTENER"),requestMatcher:Do,key:w.string()})).openapi({ref:"RegisterRequestListenerCommand"}),mH=he.merge(w.object({type:w.literal("AWAIT_LISTENER"),key:w.string(),timeout:w.number().optional().describe("timeout")})).openapi({ref:"WaitForListenerCommand"}),_C=he.merge(w.object({type:w.literal("RECORD_REQUESTS"),requestMatcher:Do,key:w.string()})).openapi({ref:"RecordRequestsCommand"}),fH=he.merge(w.object({type:w.literal("GET_RECORDED_REQUESTS"),key:w.string()})).openapi({ref:"GetRecordedRequestsCommand"}),IC=he.merge(w.object({type:w.literal("SET_HEADER"),name:w.string(),value:w.string(),requestMatcher:Do.optional()})).openapi({ref:"SetHeaderCommand"}),PC=he.merge(w.object({type:w.literal("MOCK_ROUTE"),requestMatcher:Do,responseGenerator:w.string().describe("JavaScript code to generate a response"),fetchOriginalResponse:w.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:w.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"})),hH=he.merge(w.object({type:w.literal("REMOVE_ROUTE_MOCK"),key:w.string().optional().describe("Key of the mock to remove. If not set, all route mocks will be removed.")}).openapi({ref:"RemoveRouteMockCommandOptions"})),gH=he.merge(w.object({type:w.literal("OFFLINE_MODE"),enable:w.boolean()})).openapi({ref:"OfflineModeCommand"}),SH=["CLICK","TYPE","PRESS","KEY_DOWN","KEY_UP","SELECT_OPTION","NAVIGATE","SCROLL_DOWN","SCROLL_UP","AI_ASSERTION","GO_BACK","HOVER","WAIT"],zre=[...SH,"DRAG"],yH=w.discriminatedUnion("type",[al,pl,SC,yC,EC,ul,iC,Ua,Fa,au,cC,cl,aC]),EH=w.discriminatedUnion("type",[...yH.options,sl]),TH=w.discriminatedUnion("type",[...EH.options]),MC=w.discriminatedUnion("type",[...TH.options,CC]),OS=w.discriminatedUnion("type",[CC,al,pl,SC,yC,EC,ul,iC,Ua,Fa,au,cC,cl,aC,mC,dl,fC,TC,sC,hC,dC,uC,bC,sl,ll,pC,lC,vC,AC,IC,xC,_C,PC]),bH=w.discriminatedUnion("type",[hC,tH,eH,_S,dH,dC,Q1,dl,oH,uC,mC,bC,ll,TC,fC,pC,lC,vC,AC,ol,il,uH,lu,ou,iu,sC,xC,mH,_C,fH,IC,PC,hH,gH]),ml=w.discriminatedUnion("type",[...MC.options,...bH.options]).openapi({ref:"Command"}),Gp=w.discriminatedUnion("type",[...MC.options,RC]),Hre=w.discriminatedUnion("type",[...OS.options,RC]);function ci(t){let e;switch(t){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:lt(),type:t};break;case"AUTH_LOAD":{e={id:lt(),type:t,storageState:""};break}case"AI_EXTRACT":e={id:lt(),type:t,goal:""};break;case"DIALOG":e={id:lt(),type:t,action:"DISMISS"};break;case"DRAG":e={id:lt(),type:t,fromTarget:{type:"description",elementDescriptor:""},toTarget:{type:"description",elementDescriptor:""}};break;case"MOUSE_DRAG":e={id:lt(),type:t,deltaX:"0",deltaY:"0",steps:1};break;case"WAIT_FOR_URL":e={id:lt(),type:t,matcher:{type:"SUBSTRING",url:""}};break;case"WAIT":e={id:lt(),type:t,delay:1};break;case"BLUR":e={id:lt(),type:t};break;case"HOVER":case"FOCUS":case"CLICK":e={id:lt(),type:t,target:{type:"description",elementDescriptor:""}};break;case"COOKIE":case"PRESS":case"COPY":case"TYPE":e={id:lt(),type:t,value:"",clearContent:!0};break;case"KEY_DOWN":case"KEY_UP":e={id:lt(),type:t,value:""};break;case"SELECT_OPTION":e={id:lt(),type:t,target:{type:"description",elementDescriptor:""},choice:{type:"VALUE",value:""}};break;case"NAVIGATE":case"NEW_TAB":return{id:lt(),type:t,url:""};case"TAB":e={id:lt(),type:t,action:{type:"SUBSTRING",substring:""}};break;case"REQUEST":e={id:lt(),type:t,url:"",method:"GET"};break;case"GRAPHQL_REQUEST":e={id:lt(),type:t,url:"",query:""};break;case"LOCAL_STORAGE":e={id:lt(),type:t,key:"",value:""};break;case"JAVASCRIPT":e={id:lt(),type:t,code:""};break;case"AI_ASSERTION":e={id:lt(),type:t,assertion:""};break;case"FILE_UPLOAD":{e={id:lt(),type:t,fileSource:{type:"URL",url:""}};break}case"ELEMENT_CHECK":{e={id:lt(),type:t,target:{type:"description",elementDescriptor:""},assertion:{type:"ELEMENT_EXISTENCE",condition:"EXISTS"}};break}case"PAGE_CHECK":{e={id:lt(),type:t,assertion:{type:"CONTENT",value:""}};break}case"REGISTER_REQUEST_LISTENER":{e={id:lt(),type:t,requestMatcher:{urlMatcher:{type:"REGEX",regex:""}},key:""};break}case"AWAIT_LISTENER":{e={id:lt(),type:t,key:""};break}case"RECORD_REQUESTS":{e={id:lt(),type:t,requestMatcher:{urlMatcher:{type:"REGEX",regex:""}},key:""};break}case"GET_RECORDED_REQUESTS":{e={id:lt(),type:t,key:""};break}case"SET_HEADER":{e={id:lt(),type:t,name:"",value:""};break}case"MOCK_ROUTE":{e={id:lt(),type:t,requestMatcher:{urlMatcher:{type:"REGEX",regex:""}},responseGenerator:""};break}case"REMOVE_ROUTE_MOCK":{e={id:lt(),type:t};break}case"OFFLINE_MODE":{e={id:lt(),type:t,enable:!0};break}default:return(n=>{throw"If Typescript complains about the line below, you missed a case or break in the switch above"})(t)}return e}var Wre={AI_ASSERTION:"AI Check",ELEMENT_CHECK:"Element Check",JAVASCRIPT:"JavaScript",PAGE_CHECK:"Page Check"};import{z as vH}from"zod";var Xre=vH.discriminatedUnion("type",[iu,_S,al,sl,ou,cl,ll,Fa,Ua,ol,il,ul,pl,lu,dl]);function OC(t){return["AI_ASSERTION","ELEMENT_CHECK","PAGE_CHECK"].includes(t)}import{z as AH}from"zod";import{z as Gr}from"zod";function fl(t){return Gr.object({key:Gr.string(),testId:Gr.string().optional(),environment:Gr.string().optional(),moduleId:Gr.string().optional(),organizationId:Gr.string(),value:t})}function za(t){return Gr.object({key:Gr.string(),testId:Gr.string().optional(),environment:Gr.string().optional(),moduleId:Gr.string().optional(),organizationId:Gr.string(),value:t,uniqueKey:Gr.string()})}function LC(t){return Gr.record(Gr.string(),za(t))}var jr={type:!0,cache:!0},po=AH.discriminatedUnion("type",[au.pick(jr),iu.pick(jr),al.pick(jr),sl.pick(jr),dl.pick(jr),ou.pick(jr),cl.pick(jr),ll.pick(jr),Fa.pick(jr),Ua.pick(jr),ol.pick(jr),il.pick(jr),ul.pick(jr),pl.pick(jr),lu.pick(jr)]),jp=Object.values(rt).filter(t=>po.options.some(e=>e.shape.type.safeParse(t).success));ml.options.forEach(t=>{if("target"in t.shape&&!jp.includes(t.shape.type.value))throw new Error(`Command ${t.shape.type.value} has a target but no cache`)});function Hi(t){return jp.includes(t.type)}var NC=fl(po),DC=za(po),one=LC(po);import{v4 as ct}from"uuid";import{z as O}from"zod";var FC=Symbol("Let zodToJsonSchema decide on which parser to use");var kC={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"},UC=t=>typeof t=="string"?{...kC,name:t}:{...kC,...t};var BC=t=>{let e=UC(t),r=e.name!==void 0?[...e.basePath,e.definitionPath,e.name]:e.basePath;return{...e,flags:{hasReferencedOpenAiAnyType:!1},currentPath:r,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 LS(t,e,r,n){n?.errorMessages&&r&&(t.errorMessage={...t.errorMessage,[e]:r})}function Ke(t,e,r,n,o){t[e]=r,LS(t,e,n,o)}var Vp=(t,e)=>{let r=0;for(;r<t.length&&r<e.length&&t[r]===e[r];r++);return[(t.length-r).toString(),...e.slice(r)].join("/")};import{ZodFirstPartyTypeKind as Ve}from"zod";function wt(t){if(t.target!=="openAi")return{};let e=[...t.basePath,t.definitionPath,t.openAiAnyTypeName];return t.flags.hasReferencedOpenAiAnyType=!0,{$ref:t.$refStrategy==="relative"?Vp(e,t.currentPath):e.join("/")}}import{ZodFirstPartyTypeKind as CH}from"zod";function zC(t,e){let r={type:"array"};return t.type?._def&&t.type?._def?.typeName!==CH.ZodAny&&(r.items=Se(t.type._def,{...e,currentPath:[...e.currentPath,"items"]})),t.minLength&&Ke(r,"minItems",t.minLength.value,t.minLength.message,e),t.maxLength&&Ke(r,"maxItems",t.maxLength.value,t.maxLength.message,e),t.exactLength&&(Ke(r,"minItems",t.exactLength.value,t.exactLength.message,e),Ke(r,"maxItems",t.exactLength.value,t.exactLength.message,e)),r}function HC(t,e){let r={type:"integer",format:"int64"};if(!t.checks)return r;for(let n of t.checks)switch(n.kind){case"min":e.target==="jsonSchema7"?n.inclusive?Ke(r,"minimum",n.value,n.message,e):Ke(r,"exclusiveMinimum",n.value,n.message,e):(n.inclusive||(r.exclusiveMinimum=!0),Ke(r,"minimum",n.value,n.message,e));break;case"max":e.target==="jsonSchema7"?n.inclusive?Ke(r,"maximum",n.value,n.message,e):Ke(r,"exclusiveMaximum",n.value,n.message,e):(n.inclusive||(r.exclusiveMaximum=!0),Ke(r,"maximum",n.value,n.message,e));break;case"multipleOf":Ke(r,"multipleOf",n.value,n.message,e);break}return r}function GC(){return{type:"boolean"}}function Wp(t,e){return Se(t.type._def,e)}var jC=(t,e)=>Se(t.innerType._def,e);function NS(t,e,r){let n=r??e.dateStrategy;if(Array.isArray(n))return{anyOf:n.map((o,i)=>NS(t,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 RH(t,e)}}var RH=(t,e)=>{let r={type:"integer",format:"unix-time"};if(e.target==="openApi3")return r;for(let n of t.checks)switch(n.kind){case"min":Ke(r,"minimum",n.value,n.message,e);break;case"max":Ke(r,"maximum",n.value,n.message,e);break}return r};function VC(t,e){return{...Se(t.innerType._def,e),default:t.defaultValue()}}function WC(t,e){return e.effectStrategy==="input"?Se(t.schema._def,e):wt(e)}function $C(t){return{type:"string",enum:Array.from(t.values)}}var wH=t=>"type"in t&&t.type==="string"?!1:"allOf"in t;function qC(t,e){let r=[Se(t.left._def,{...e,currentPath:[...e.currentPath,"allOf","0"]}),Se(t.right._def,{...e,currentPath:[...e.currentPath,"allOf","1"]})].filter(i=>!!i),n=e.target==="jsonSchema2019-09"?{unevaluatedProperties:!1}:void 0,o=[];return r.forEach(i=>{if(wH(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:s,...c}=i;a=c}else n=void 0;o.push(a)}}),o.length?{allOf:o,...n}:void 0}function KC(t,e){let r=typeof t.value;return r!=="bigint"&&r!=="number"&&r!=="boolean"&&r!=="string"?{type:Array.isArray(t.value)?"array":"object"}:e.target==="openApi3"?{type:r==="bigint"?"integer":r,enum:[t.value]}:{type:r==="bigint"?"integer":r,const:t.value}}import{ZodFirstPartyTypeKind as cu}from"zod";var DS,mo={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:()=>(DS===void 0&&(DS=RegExp("^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$","u")),DS),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 $p(t,e){let r={type:"string"};if(t.checks)for(let n of t.checks)switch(n.kind){case"min":Ke(r,"minLength",typeof r.minLength=="number"?Math.max(r.minLength,n.value):n.value,n.message,e);break;case"max":Ke(r,"maxLength",typeof r.maxLength=="number"?Math.min(r.maxLength,n.value):n.value,n.message,e);break;case"email":switch(e.emailStrategy){case"format:email":fo(r,"email",n.message,e);break;case"format:idn-email":fo(r,"idn-email",n.message,e);break;case"pattern:zod":Vr(r,mo.email,n.message,e);break}break;case"url":fo(r,"uri",n.message,e);break;case"uuid":fo(r,"uuid",n.message,e);break;case"regex":Vr(r,n.regex,n.message,e);break;case"cuid":Vr(r,mo.cuid,n.message,e);break;case"cuid2":Vr(r,mo.cuid2,n.message,e);break;case"startsWith":Vr(r,RegExp(`^${kS(n.value,e)}`),n.message,e);break;case"endsWith":Vr(r,RegExp(`${kS(n.value,e)}$`),n.message,e);break;case"datetime":fo(r,"date-time",n.message,e);break;case"date":fo(r,"date",n.message,e);break;case"time":fo(r,"time",n.message,e);break;case"duration":fo(r,"duration",n.message,e);break;case"length":Ke(r,"minLength",typeof r.minLength=="number"?Math.max(r.minLength,n.value):n.value,n.message,e),Ke(r,"maxLength",typeof r.maxLength=="number"?Math.min(r.maxLength,n.value):n.value,n.message,e);break;case"includes":{Vr(r,RegExp(kS(n.value,e)),n.message,e);break}case"ip":{n.version!=="v6"&&fo(r,"ipv4",n.message,e),n.version!=="v4"&&fo(r,"ipv6",n.message,e);break}case"base64url":Vr(r,mo.base64url,n.message,e);break;case"jwt":Vr(r,mo.jwt,n.message,e);break;case"cidr":{n.version!=="v6"&&Vr(r,mo.ipv4Cidr,n.message,e),n.version!=="v4"&&Vr(r,mo.ipv6Cidr,n.message,e);break}case"emoji":Vr(r,mo.emoji(),n.message,e);break;case"ulid":{Vr(r,mo.ulid,n.message,e);break}case"base64":{switch(e.base64Strategy){case"format:binary":{fo(r,"binary",n.message,e);break}case"contentEncoding:base64":{Ke(r,"contentEncoding","base64",n.message,e);break}case"pattern:zod":{Vr(r,mo.base64,n.message,e);break}}break}case"nanoid":Vr(r,mo.nanoid,n.message,e);case"toLowerCase":case"toUpperCase":case"trim":break;default:}return r}function kS(t,e){return e.patternStrategy==="escape"?_H(t):t}var xH=new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789");function _H(t){let e="";for(let r=0;r<t.length;r++)xH.has(t[r])||(e+="\\"),e+=t[r];return e}function fo(t,e,r,n){t.format||t.anyOf?.some(o=>o.format)?(t.anyOf||(t.anyOf=[]),t.format&&(t.anyOf.push({format:t.format,...t.errorMessage&&n.errorMessages&&{errorMessage:{format:t.errorMessage.format}}}),delete t.format,t.errorMessage&&(delete t.errorMessage.format,Object.keys(t.errorMessage).length===0&&delete t.errorMessage)),t.anyOf.push({format:e,...r&&n.errorMessages&&{errorMessage:{format:r}}})):Ke(t,"format",e,r,n)}function Vr(t,e,r,n){t.pattern||t.allOf?.some(o=>o.pattern)?(t.allOf||(t.allOf=[]),t.pattern&&(t.allOf.push({pattern:t.pattern,...t.errorMessage&&n.errorMessages&&{errorMessage:{pattern:t.errorMessage.pattern}}}),delete t.pattern,t.errorMessage&&(delete t.errorMessage.pattern,Object.keys(t.errorMessage).length===0&&delete t.errorMessage)),t.allOf.push({pattern:YC(e,n),...r&&n.errorMessages&&{errorMessage:{pattern:r}}})):Ke(t,"pattern",YC(e,n),r,n)}function YC(t,e){if(!e.applyRegexFlags||!t.flags)return t.source;let r={i:t.flags.includes("i"),m:t.flags.includes("m"),s:t.flags.includes("s")},n=r.i?t.source.toLowerCase():t.source,o="",i=!1,a=!1,s=!1;for(let c=0;c<n.length;c++){if(i){o+=n[c],i=!1;continue}if(r.i){if(a){if(n[c].match(/[a-z]/)){s?(o+=n[c],o+=`${n[c-2]}-${n[c]}`.toUpperCase(),s=!1):n[c+1]==="-"&&n[c+2]?.match(/[a-z]/)?(o+=n[c],s=!0):o+=`${n[c]}${n[c].toUpperCase()}`;continue}}else if(n[c].match(/[a-z]/)){o+=`[${n[c]}${n[c].toUpperCase()}]`;continue}}if(r.m){if(n[c]==="^"){o+=`(^|(?<=[\r
|
|
5
5
|
]))`;continue}else if(n[c]==="$"){o+=`($|(?=[\r
|
|
6
6
|
]))`;continue}}if(r.s&&n[c]==="."){o+=a?`${n[c]}\r
|
|
7
7
|
`:`[${n[c]}\r
|
|
8
8
|
]`;continue}o+=n[c],n[c]==="\\"?i=!0:a&&n[c]==="]"?a=!1:!a&&n[c]==="["&&(a=!0)}try{new RegExp(o)}catch{return console.warn(`Could not convert regex pattern at ${e.currentPath.join("/")} to a flag-independent form! Falling back to the flag-ignorant source`),t.source}return o}function qp(t,e){if(e.target==="openAi"&&console.warn("Warning: OpenAI may not support records in schemas! Try an array of key-value pairs instead."),e.target==="openApi3"&&t.keyType?._def.typeName===cu.ZodEnum)return{type:"object",required:t.keyType._def.values,properties:t.keyType._def.values.reduce((n,o)=>({...n,[o]:Se(t.valueType._def,{...e,currentPath:[...e.currentPath,"properties",o]})??wt(e)}),{}),additionalProperties:e.rejectedAdditionalProperties};let r={type:"object",additionalProperties:Se(t.valueType._def,{...e,currentPath:[...e.currentPath,"additionalProperties"]})??e.allowedAdditionalProperties};if(e.target==="openApi3")return r;if(t.keyType?._def.typeName===cu.ZodString&&t.keyType._def.checks?.length){let{type:n,...o}=$p(t.keyType._def,e);return{...r,propertyNames:o}}else{if(t.keyType?._def.typeName===cu.ZodEnum)return{...r,propertyNames:{enum:t.keyType._def.values}};if(t.keyType?._def.typeName===cu.ZodBranded&&t.keyType._def.type._def.typeName===cu.ZodString&&t.keyType._def.type._def.checks?.length){let{type:n,...o}=Wp(t.keyType._def,e);return{...r,propertyNames:o}}}return r}function XC(t,e){if(e.mapStrategy==="record")return qp(t,e);let r=Se(t.keyType._def,{...e,currentPath:[...e.currentPath,"items","items","0"]})||wt(e),n=Se(t.valueType._def,{...e,currentPath:[...e.currentPath,"items","items","1"]})||wt(e);return{type:"array",maxItems:125,items:{type:"array",items:[r,n],minItems:2,maxItems:2}}}function JC(t){let e=t.values,n=Object.keys(t.values).filter(i=>typeof e[e[i]]!="number").map(i=>e[i]),o=Array.from(new Set(n.map(i=>typeof i)));return{type:o.length===1?o[0]==="string"?"string":"number":["string","number"],enum:n}}function QC(t){return t.target==="openAi"?void 0:{not:wt({...t,currentPath:[...t.currentPath,"not"]})}}function ZC(t){return t.target==="openApi3"?{enum:["null"],nullable:!0}:{type:"null"}}var uu={ZodString:"string",ZodNumber:"number",ZodBigInt:"integer",ZodBoolean:"boolean",ZodNull:"null"};function tR(t,e){if(e.target==="openApi3")return eR(t,e);let r=t.options instanceof Map?Array.from(t.options.values()):t.options;if(r.every(n=>n._def.typeName in uu&&(!n._def.checks||!n._def.checks.length))){let n=r.reduce((o,i)=>{let a=uu[i._def.typeName];return a&&!o.includes(a)?[...o,a]:o},[]);return{type:n.length>1?n:n[0]}}else if(r.every(n=>n._def.typeName==="ZodLiteral"&&!n.description)){let n=r.reduce((o,i)=>{let a=typeof i._def.value;switch(a){case"string":case"number":case"boolean":return[...o,a];case"bigint":return[...o,"integer"];case"object":if(i._def.value===null)return[...o,"null"];case"symbol":case"undefined":case"function":default:return o}},[]);if(n.length===r.length){let o=n.filter((i,a,s)=>s.indexOf(i)===a);return{type:o.length>1?o:o[0],enum:r.reduce((i,a)=>i.includes(a._def.value)?i:[...i,a._def.value],[])}}}else if(r.every(n=>n._def.typeName==="ZodEnum"))return{type:"string",enum:r.reduce((n,o)=>[...n,...o._def.values.filter(i=>!n.includes(i))],[])};return eR(t,e)}var eR=(t,e)=>{let r=(t.options instanceof Map?Array.from(t.options.values()):t.options).map((n,o)=>Se(n._def,{...e,currentPath:[...e.currentPath,"anyOf",`${o}`]})).filter(n=>!!n&&(!e.strictUnions||typeof n=="object"&&Object.keys(n).length>0));return r.length?{anyOf:r}:void 0};function rR(t,e){if(["ZodString","ZodNumber","ZodBigInt","ZodBoolean","ZodNull"].includes(t.innerType._def.typeName)&&(!t.innerType._def.checks||!t.innerType._def.checks.length))return e.target==="openApi3"?{type:uu[t.innerType._def.typeName],nullable:!0}:{type:[uu[t.innerType._def.typeName],"null"]};if(e.target==="openApi3"){let n=Se(t.innerType._def,{...e,currentPath:[...e.currentPath]});return n&&"$ref"in n?{allOf:[n],nullable:!0}:n&&{...n,nullable:!0}}let r=Se(t.innerType._def,{...e,currentPath:[...e.currentPath,"anyOf","0"]});return r&&{anyOf:[r,{type:"null"}]}}function nR(t,e){let r={type:"number"};if(!t.checks)return r;for(let n of t.checks)switch(n.kind){case"int":r.type="integer",LS(r,"type",n.message,e);break;case"min":e.target==="jsonSchema7"?n.inclusive?Ke(r,"minimum",n.value,n.message,e):Ke(r,"exclusiveMinimum",n.value,n.message,e):(n.inclusive||(r.exclusiveMinimum=!0),Ke(r,"minimum",n.value,n.message,e));break;case"max":e.target==="jsonSchema7"?n.inclusive?Ke(r,"maximum",n.value,n.message,e):Ke(r,"exclusiveMaximum",n.value,n.message,e):(n.inclusive||(r.exclusiveMaximum=!0),Ke(r,"maximum",n.value,n.message,e));break;case"multipleOf":Ke(r,"multipleOf",n.value,n.message,e);break}return r}function oR(t,e){let r=e.target==="openAi",n={type:"object",properties:{}},o=[],i=t.shape();for(let s in i){let c=i[s];if(c===void 0||c._def===void 0)continue;let l=PH(c);l&&r&&(c._def.typeName==="ZodOptional"&&(c=c._def.innerType),c.isNullable()||(c=c.nullable()),l=!1);let u=Se(c._def,{...e,currentPath:[...e.currentPath,"properties",s],propertyPath:[...e.currentPath,"properties",s]});u!==void 0&&(n.properties[s]=u,l||o.push(s))}o.length&&(n.required=o);let a=IH(t,e);return a!==void 0&&(n.additionalProperties=a),n}function IH(t,e){if(t.catchall._def.typeName!=="ZodNever")return Se(t.catchall._def,{...e,currentPath:[...e.currentPath,"additionalProperties"]});switch(t.unknownKeys){case"passthrough":return e.allowedAdditionalProperties;case"strict":return e.rejectedAdditionalProperties;case"strip":return e.removeAdditionalStrategy==="strict"?e.allowedAdditionalProperties:e.rejectedAdditionalProperties}}function PH(t){try{return t.isOptional()}catch{return!0}}var iR=(t,e)=>{if(e.currentPath.toString()===e.propertyPath?.toString())return Se(t.innerType._def,e);let r=Se(t.innerType._def,{...e,currentPath:[...e.currentPath,"anyOf","1"]});return r?{anyOf:[{not:wt(e)},r]}:wt(e)};var aR=(t,e)=>{if(e.pipeStrategy==="input")return Se(t.in._def,e);if(e.pipeStrategy==="output")return Se(t.out._def,e);let r=Se(t.in._def,{...e,currentPath:[...e.currentPath,"allOf","0"]}),n=Se(t.out._def,{...e,currentPath:[...e.currentPath,"allOf",r?"1":"0"]});return{allOf:[r,n].filter(o=>o!==void 0)}};function sR(t,e){return Se(t.type._def,e)}function lR(t,e){let n={type:"array",uniqueItems:!0,items:Se(t.valueType._def,{...e,currentPath:[...e.currentPath,"items"]})};return t.minSize&&Ke(n,"minItems",t.minSize.value,t.minSize.message,e),t.maxSize&&Ke(n,"maxItems",t.maxSize.value,t.maxSize.message,e),n}function cR(t,e){return t.rest?{type:"array",minItems:t.items.length,items:t.items.map((r,n)=>Se(r._def,{...e,currentPath:[...e.currentPath,"items",`${n}`]})).reduce((r,n)=>n===void 0?r:[...r,n],[]),additionalItems:Se(t.rest._def,{...e,currentPath:[...e.currentPath,"additionalItems"]})}:{type:"array",minItems:t.items.length,maxItems:t.items.length,items:t.items.map((r,n)=>Se(r._def,{...e,currentPath:[...e.currentPath,"items",`${n}`]})).reduce((r,n)=>n===void 0?r:[...r,n],[])}}function uR(t){return{not:wt(t)}}function dR(t){return wt(t)}var pR=(t,e)=>Se(t.innerType._def,e);var mR=(t,e,r)=>{switch(e){case Ve.ZodString:return $p(t,r);case Ve.ZodNumber:return nR(t,r);case Ve.ZodObject:return oR(t,r);case Ve.ZodBigInt:return HC(t,r);case Ve.ZodBoolean:return GC();case Ve.ZodDate:return NS(t,r);case Ve.ZodUndefined:return uR(r);case Ve.ZodNull:return ZC(r);case Ve.ZodArray:return zC(t,r);case Ve.ZodUnion:case Ve.ZodDiscriminatedUnion:return tR(t,r);case Ve.ZodIntersection:return qC(t,r);case Ve.ZodTuple:return cR(t,r);case Ve.ZodRecord:return qp(t,r);case Ve.ZodLiteral:return KC(t,r);case Ve.ZodEnum:return $C(t);case Ve.ZodNativeEnum:return JC(t);case Ve.ZodNullable:return rR(t,r);case Ve.ZodOptional:return iR(t,r);case Ve.ZodMap:return XC(t,r);case Ve.ZodSet:return lR(t,r);case Ve.ZodLazy:return()=>t.getter()._def;case Ve.ZodPromise:return sR(t,r);case Ve.ZodNaN:case Ve.ZodNever:return QC(r);case Ve.ZodEffects:return WC(t,r);case Ve.ZodAny:return wt(r);case Ve.ZodUnknown:return dR(r);case Ve.ZodDefault:return VC(t,r);case Ve.ZodBranded:return Wp(t,r);case Ve.ZodReadonly:return pR(t,r);case Ve.ZodCatch:return jC(t,r);case Ve.ZodPipeline:return aR(t,r);case Ve.ZodFunction:case Ve.ZodVoid:case Ve.ZodSymbol:return;default:return(n=>{})(e)}};function Se(t,e,r=!1){let n=e.seen.get(t);if(e.override){let s=e.override?.(t,e,n,r);if(s!==FC)return s}if(n&&!r){let s=MH(n,e);if(s!==void 0)return s}let o={def:t,path:e.currentPath,jsonSchema:void 0};e.seen.set(t,o);let i=mR(t,t.typeName,e),a=typeof i=="function"?Se(i(),e):i;if(a&&OH(t,e,a),e.postProcess){let s=e.postProcess(a,t,e);return o.jsonSchema=a,s}return o.jsonSchema=a,a}var MH=(t,e)=>{switch(e.$refStrategy){case"root":return{$ref:t.path.join("/")};case"relative":return{$ref:Vp(e.currentPath,t.path)};case"none":case"seen":return t.path.length<e.currentPath.length&&t.path.every((r,n)=>e.currentPath[n]===r)?(console.warn(`Recursive reference detected at ${e.currentPath.join("/")}! Defaulting to any`),wt(e)):e.$refStrategy==="seen"?wt(e):void 0}},OH=(t,e,r)=>(t.description&&(r.description=t.description,e.markdownDescription&&(r.markdownDescription=t.description)),r);var hl=(t,e)=>{let r=BC(e),n=typeof e=="object"&&e.definitions?Object.entries(e.definitions).reduce((c,[l,u])=>({...c,[l]:Se(u._def,{...r,currentPath:[...r.basePath,r.definitionPath,l]},!0)??wt(r)}),{}):void 0,o=typeof e=="string"?e:e?.nameStrategy==="title"?void 0:e?.name,i=Se(t._def,o===void 0?r:{...r,currentPath:[...r.basePath,r.definitionPath,o]},!1)??wt(r),a=typeof e=="object"&&e.name!==void 0&&e.nameStrategy==="title"?e.name:void 0;a!==void 0&&(i.title=a),r.flags.hasReferencedOpenAiAnyType&&(n||(n={}),n[r.openAiAnyTypeName]||(n[r.openAiAnyTypeName]={type:["string","number","integer","boolean","array","null"],items:{$ref:r.$refStrategy==="relative"?"1":[...r.basePath,r.definitionPath,r.openAiAnyTypeName].join("/")}}));let s=o===void 0?n?{...i,[r.definitionPath]:n}:i:{$ref:[...r.$refStrategy==="relative"?[]:r.basePath,r.definitionPath,o].join("/"),[r.definitionPath]:{...n,[o]:i}};return r.target==="jsonSchema7"?s.$schema="http://json-schema.org/draft-07/schema#":(r.target==="jsonSchema2019-09"||r.target==="openAi")&&(s.$schema="https://json-schema.org/draft/2019-09/schema#"),r.target==="openAi"&&("anyOf"in s||"oneOf"in s||"allOf"in s||"type"in s&&Array.isArray(s.type))&&console.warn("Warning: OpenAI may not support schemas with unions as roots! Try wrapping it in an object property."),s};import{z as ko}from"zod";import{extendZodWithOpenApi as LH}from"zod-openapi";LH(ko);var Ne=(m=>(m.AI_PROVIDER="AIProviderError",m.USER_INFRA="UserInfrastructureError",m.ACTION_FAILURE="ActionFailureError",m.NO_MATCHING_ELEMENT="NoMatchingElementError",m.ASSERTION_FAILURE="AssertionFailureError",m.CONFIG_ERROR="UserConfigurationError",m.SETUP_FAILURE="SetupFailureError",m.TEARDOWN_FAILURE="TeardownFailureError",m.WEB_AGENT_PLATFORM="InternalWebAgentError",m.UNKNOWN_PLATFORM="InternalPlatformError",m.JOB_TIMEOUT="JobTimeoutError",m.CONCURRENCY_ERROR="ConcurrencyError",m.UNKNOWN="UnknownError",m))(Ne||{});var fR=["JobTimeoutError","UserConfigurationError","UserInfrastructureError"],gl={ActionFailureError:"Action failure",NoMatchingElementError:"No matching element",AssertionFailureError:"Assertion failure",SetupFailureError:"Setup failure",TeardownFailureError:"Teardown failure",UserInfrastructureError:"Infrastructure failure",UserConfigurationError:"Configuration error",AIProviderError:"AI provider error",InternalWebAgentError:"Momentic AI agent error",JobTimeoutError:"Job timeout",InternalPlatformError:"Unknown Momentic platform error",UnknownError:"Unknown error",ConcurrencyError:"Concurrency error"},Gi={ActionFailureError:"A browser action such as a click or type failed to execute because of the underlying page state is incorrect, suggesting a bug in the application itself.",NoMatchingElementError:"The AI agent failed to find a matching element for the given description.",AssertionFailureError:"An AI check failed for a legitimate reason, such as a missing element, a change in the page structure, or an unexpected state (e.g. loading state).",SetupFailureError:"A setup step failed to execute, preventing the main test from running. This indicates an issue with test preparation, prerequisite steps, or initial state. This can only apply to failures that occur before teardown.",TeardownFailureError:"A teardown step failed to execute after the main test completed. This indicates an issue with cleanup or post-test operations or an uncaught error in the test. This can only apply to failures that occur after setup.",AIProviderError:"The AI provider failed to return a response or returned a malformed response.",UserInfrastructureError:"The user's web application exhibited an infrastructure failure, such as a page load timeout, a 5XX status code, maintenance page, or session crash.",UserConfigurationError:"The error message suggests a user-caused misconfiguration in the test, such as an undefined variable, a missing base URL, an empty test/module input parameter, or an invalid step option",JobTimeoutError:"The test took too long to complete, suggesting a problem with the test itself.",InternalWebAgentError:"The AI testing framework failed to find the correct element or evaluate the assertion correctly, even though the test steps and application state look valid. In other words, the AI agent failed to understand the page.",ConcurrencyError:"The AI test executed correctly, but the application state did not match expectations because another process modified the same resource concurrently. This failure is due to a concurrency error, such as a race condition or deadlock. Commonly caused by tests running simultaneously when using constants rather than random values, or underlying operations that allow for race conditions. For example, in Notion, if multiple tests are running at the same time where one creates a page and enters text to check if it renders, but another test deletes all pages before it can validate the render, this would be a concurrency error.",UnknownError:"An unknown error occurred. Please refer to the failure details in the run for more information or reach out to Momentic Support for assistance.",InternalPlatformError:"An unknown error occurred with the Momentic platform."},FS=ko.object({reason:ko.nativeEnum(Ne),previousStepsDescription:ko.array(ko.string()).optional(),summary:ko.string(),rootCause:ko.string().optional()}).openapi({ref:"TestResultClassification"}),Kp=ko.object({errorMessage:ko.string(),errorStack:ko.string().optional(),classification:FS.optional()}).openapi({ref:"TestFailureDetails"});var Yp=class extends Error{constructor(e,r={}){super(e,r),this.name="CommandParseError"}},or=class extends Error{constructor(e,r={}){super(e,r),this.name="ValidationError"}};var du=class extends Error{constructor(e,r,n,o={}){super(`The ${n} with id ${r} is invalid: ${e}`,o),this.name="InvalidEntityError"}};var Ha=class extends du{zodIssues;constructor(e,r,n,o,i={}){super(e,r,n,i),this.zodIssues=o,this.name="SchemaValidationError"}};function hR(t){for(let e of Object.values(Ne))if(t.includes(e))return e}var L=class t extends Error{reason;constructor(e,r,n){let o=!1;for(let i of Object.values(Ne))if(r.startsWith(i)){o=!0,e=i;break}if(n?.errOptions?.cause)super(o?r:`${e}: ${r}`,n?.errOptions);else{let i=o?r:`${e}${r?`: ${r}`:""}`;super(i,n?.errOptions)}this.name="TestFailureError",this.stack=this.stack?.slice(this.name.length+2),this.reason=e}toString(){return this.message}toJSON(){return{message:this.message,stack:this.stack,reason:this.reason}}static fromMessage(e){let r,n=e;for(let o of Object.values(Ne))if(e.startsWith(o)){r=o,e.startsWith(`${o}: `)?n=e.slice(`${o}: `.length):e===o&&(n="");break}return r||(r="UnknownError"),new t(r,n)}};var Sl=class extends Error{updatedLocatorMemory;constructor(e,r,n={}){super(e,n),this.updatedLocatorMemory=r,this.name="NoElementsFoundUsingAIError"}},fn=class extends Error{decisions;cacheMissReason;constructor(e,r=[],n,o={}){super(e,o),this.decisions=r,this.name="NoElementsFoundUsingCacheError",this.cacheMissReason=n}toString(){return`${this.message}
|
|
9
9
|
Decisions:
|
|
10
10
|
${this.decisions.map(e=>e.toString()).join(`
|
|
11
|
-
`)}`}};function NH(t){return t instanceof Error?t.message.includes("Timeout")&&t.message.includes("exceeded")&&t.message.includes("waiting for locator"):!1}function DH(t){return!(t instanceof Error)||t.message.includes("locator resolved to visible")?!1:!!(t.message.includes("Timeout")&&t.message.includes("exceeded")&&t.message.includes("body >")||t.message.includes("Element is not attached to the DOM"))}var yl=class extends Error{constructor(e,r={}){super(e,r),this.name="CacheAttributesDisqualifyElementError"}},ji=class extends yl{constructor(e,r={}){super(e,r),this.name="ElementMovedError"}},Xp=class extends yl{constructor(e,r={}){super(e,r),this.name="ZeroOpacityError"}},pu=class extends Error{constructor(e,r={}){super(e,r),this.name="IsInvalidMomenticIdError"}};function kH(t){return t instanceof Error?t.message.includes("Could not find attribute data-momentic-id for object"):!1}var US="Element to be clicked has no bounding box";function FH(t){return t instanceof Error?t.message.startsWith(US):!1}function BS(t){return t instanceof ji||DH(t)||UH(t)||BH(t)||NH(t)||kH(t)||FH(t)}function UH(t){return t instanceof Error?t instanceof pu?!0:t.message.includes("Timeout")&&t.message.includes("exceeded")&&t.message.includes("waiting for locator")&&t.message.includes("data-momentic-id")&&!t.message.includes("locator resolved")&&!t.message.includes("waiting for element to be"):!1}function BH(t){return t instanceof Error?t.message.includes("Protocol error (DOM.resolveNode): No node with given id found")||t.message.includes("Could not resolve backend node"):!1}var mu=class extends Error{constructor(e,r={}){super(e,r),this.name="InsufficientCacheDataError"}};function Yt(t){return t instanceof Error?t.message:String(t)}var zH={CLICK:"Click on an element on the page.",TYPE:"Focus the element then type the specified text into an input on the page.",PRESS:"Press one or more keyboard keys.",KEY_DOWN:"Hold down one or more keyboard keys.",KEY_UP:"Release one or more keyboard keys.",SELECT_OPTION:"Choose an option from a native <select> component. Never use this command for non <select> elements. Instead, use a series of CLICK commands for those.",NAVIGATE:"Go to the specified fully qualified URL.",SCROLL_UP:"Scroll up.",SCROLL_DOWN:"Scroll down.",GO_BACK:"Go back to the previous page.",HOVER:"Hover over an element.",AI_ASSERTION:"Verify a statement about the current page, retrying until it is true. Only generate an assertion if the goal includes language like 'check that', 'verify that', etc..",WAIT:"Wait a fixed amount of seconds.",DRAG:"Drag an element from one location and drop it onto another element.",JAVASCRIPT:"Execute JavaScript code in NODE or BROWSER environment.",ELEMENT_CHECK:"Perform a manual assertion on a specific element.",PAGE_CHECK:"Perform a manual case sensitive assertion on the page's html.",NEW_TAB:"Open a new browser tab with the specified URL.",WAIT_FOR_URL:"Wait for the URL to match a pattern.",AI_EXTRACT:"Extract data from the page and optionally store it in an environment variable.",COPY:"Copy the specified text value to the browser clipboard.",GO_FORWARD:"Navigate forward to the next page in the browser history (if available). Only use this after having navigated back with GO_BACK. Do not use this to navigate to a different page - use NAVIGATE instead.",LOCAL_STORAGE:"Set or get a value in the browser's localStorage. Use this to store data that persists across page reloads or to read stored values.",MOUSE_DRAG:"Drag the mouse from a starting point (or element) in a specific direction by pixel amounts. Prefer using DRAG (drag and drop between elements) instead unless the user explicitly requests dragging in a direction or by pixels. Use this when dragging needs to move a specific distance rather than to a target element.",PASTE:"Paste the contents of the browser clipboard into the currently focused element. Use this after copying text with COPY or when pasting content that was previously copied.",REFRESH:"Reload the current page. Use this to refresh the page content or retry a failed operation.",REQUEST:"Make an HTTP API request to a specified URL. Use this to interact with REST APIs, send data to a server, or retrieve data from an endpoint. Supports GET, POST, PUT, DELETE, and PATCH methods with custom headers, query parameters, and request body.",GRAPHQL_REQUEST:"Make a GraphQL request to a specified URL. Provide the GraphQL query (or mutation), optional variables JSON, and any required headers. Use this for GraphQL APIs instead of REQUEST.",SET_HEADER:"Set a header for subsequent network requests. Optionally scope it to matching requests.",REGISTER_REQUEST_LISTENER:"Register a request listener for matching requests and save them under a key.",RECORD_REQUESTS:"Record matching requests and store them under a key for later retrieval.",MOCK_ROUTE:"Mock matching network requests with a generated response."};OS.options.forEach(t=>{let e=t.shape.type.value;if(e!=="SUCCESS"&&!zH[e])throw new Error(`Command type ${e} is missing a description`)});var gR=O.object({type:O.literal("CLICK"),description:O.string().describe("Description of the element to click in the Current Page. Never click on <select> elements, see SELECT_OPTION."),doubleClick:O.boolean().nullish(),rightClick:O.boolean().nullish(),waitForDownload:O.boolean().nullish().describe("Wait for the click to trigger a file download and for the download to complete."),downloadTimeoutMs:O.number().int().nullish().describe("Max milliseconds to wait for a download to start and complete when waitForDownload is enabled."),delayMs:O.number().int().nullish().describe("Delay before performing the click, in milliseconds.")}),SR=O.object({type:O.literal("TYPE"),description:O.string().describe("Description of the element to type into, which must be an <input>, <textarea>, or contenteditable element."),text:O.string().describe("The text to enter, truncated to 500 characters. If the PM provided text in the goals, use it exactly without modification."),pressEnter:O.boolean().nullish().describe("Press enter after typing (useful for form submissions)."),clearContent:O.boolean().nullish().describe("Clear existing content before typing. Disable to append to the existing text.")}),yR=O.object({type:O.literal("GO_BACK")}),HH=O.object({type:O.literal("GO_FORWARD")}),GH=O.object({type:O.literal("LOCAL_STORAGE"),key:O.string().describe("The localStorage key to set or get."),value:O.string().describe("The value to store in localStorage. If reading, this can be empty.")}),ER=O.object({type:O.literal("PRESS"),keys:O.array(O.string()).describe('The keys to press. Only use key names supported by the Playwright press method, such as "a", "ArrowLeft", "Meta", "Control", and "Enter". Multiple keys will be pressed together. Do not suggest platform-specific key combinations, such as CTRL+C.')}),TR=O.object({type:O.literal("SELECT_OPTION"),description:O.string().describe("Description of the <select> element to choose from. Only use this command to interact with native HTML <select> elements. You must use CLICK to select from any other HTML element, such as <input>, <div>, or custom elements."),option:O.discriminatedUnion("type",[O.object({type:O.literal("VALUE"),value:O.string()}),O.object({type:O.literal("LABEL"),label:O.string()}),O.object({type:O.literal("INDEX"),index:O.string().describe("Zero-based index of the option within the select.")})]).describe("Which option to select. Choose 1 of 3 strategies for selecting. By value is exactly matching the 'value' attribute. By label is exactly matching the 'label' attribute. By index is using the zero-based index of the option within the select.")}),bR=O.object({type:O.literal("NAVIGATE"),url:O.string().describe("The URL to navigate to. Only navigate to URLs relevant to the user goal.")}),vR=O.object({type:O.literal("SCROLL"),y:O.number().describe("Scroll up or down by the specified pixels. Positive values scroll down.")}),AR=O.object({type:O.literal("WAIT"),timeout:O.number().describe("The number of seconds to wait.")}),CR=O.object({type:O.literal("AI_ASSERTION"),assertion:O.string().describe("The assertion to verify. This should be a statement verifiable based on the current page HTML or screenshot. Be specific enough that the assertion is not ambiguous or open to interpretation. Make sure the assertion aligns with what the user intends to verify."),timeout:O.number().describe("The max amount of seconds to wait for the assertion to be true. Respect user wishes but allow no more than 60. If unspecified, choose 5 for quick checks like form status, 10 for page loads, and 30 for actions that explicitly trigger a long time, like image generation.")}),RR=O.object({type:O.literal("HOVER"),description:O.string().describe("Description of the element to hover over. Prefer elements that have visible bounding boxes according to the screenshot, element class attribute, or child contents.")}),jH=O.object({type:O.literal("COPY"),value:O.string().describe("The text value to copy to the browser clipboard. This should be the exact text that needs to be copied.")}),VH=O.object({type:O.literal("PASTE")}),WH=O.object({type:O.literal("REFRESH")}),$H=O.object({type:O.literal("REQUEST"),url:O.string().describe("The URL to send the HTTP request to. Can be a full URL or relative path."),method:O.enum(["GET","POST","PUT","DELETE","PATCH"]).describe("The HTTP method to use. GET for retrieving data, POST for creating resources, PUT for updating resources, DELETE for removing resources, PATCH for partial updates."),headers:O.record(O.string(),O.string()).nullish().describe("Optional HTTP headers as key-value pairs. Common headers include 'Content-Type', 'Authorization', 'Accept', etc."),params:O.record(O.string(),O.string()).nullish().describe("Optional URL query parameters as key-value pairs. These will be appended to the URL as ?key1=value1&key2=value2."),body:O.string().nullish().describe("Optional request body as a string. For JSON data, stringify the object. Typically used with POST, PUT, or PATCH requests."),timeout:O.number().int().nullish().describe("Optional maximum number of seconds to wait for the request to complete. Defaults to 30 seconds if not specified.")}),qH=O.object({type:O.literal("GRAPHQL_REQUEST"),url:O.string().describe("The URL of the GraphQL endpoint. Can be a full URL or relative path."),headers:O.record(O.string(),O.string()).nullish().describe("Optional HTTP headers as key-value pairs. Common headers include 'Content-Type', 'Authorization', 'Accept', etc."),query:O.string().describe("The GraphQL query or mutation string. Include any required fields and arguments."),variables:O.string().nullish().describe("Optional JSON string of variables to pass with the GraphQL request."),timeout:O.number().int().nullish().describe("Optional maximum number of seconds to wait for the request to complete. Defaults to 30 seconds if not specified.")}),KH=O.object({type:O.literal("SET_HEADER"),name:O.string().describe("The header name to set."),value:O.string().describe("The header value to set."),requestMatcher:Do.nullish().describe("Optional request matcher to scope the header to matching requests.")}),YH=O.object({type:O.literal("REGISTER_REQUEST_LISTENER"),requestMatcher:Do.describe("Request matcher to define which requests should be captured."),key:O.string().describe("Identifier for the listener. Used to retrieve recorded data.")}),XH=O.object({type:O.literal("RECORD_REQUESTS"),requestMatcher:Do.describe("Request matcher to define which requests should be recorded."),key:O.string().describe("Identifier for the recording. Used to retrieve recorded data.")}),JH=O.object({type:O.literal("MOCK_ROUTE"),requestMatcher:Do.describe("Request matcher defining which requests should be mocked."),responseGenerator:O.string().describe("JavaScript code to generate the mocked response."),fetchOriginalResponse:O.boolean().nullish().describe("Whether to fetch the real response and pass it to the response generator."),key:O.string().nullish().describe("Optional key to reference this mock for removal.")}),wR=O.object({type:O.literal("DRAG"),fromDescription:O.string().describe("Description of the element to drag. Prefer precise identifiers or text that clearly distinguishes the element."),toDescription:O.string().describe("Description of the element to drop onto. Ensure the drop target is interactable and visible."),steps:O.number().int().positive().nullish().describe("Optional number of intermediate mouse move steps during the drag. Do not use this unless the user tells you to."),hoverSeconds:O.number().positive().nullish().describe("Optional seconds to hover over the destination before releasing the drag.")}),QH=O.object({type:O.literal("MOUSE_DRAG"),description:O.string().nullish().describe("Optional description of the element to start the drag from. If not provided, starts from current mouse position."),deltaX:O.number().describe("Number of pixels to move horizontally (positive = right, negative = left)."),deltaY:O.number().describe("Number of pixels to move vertically (positive = down, negative = up)."),steps:O.number().int().positive().nullish().describe("Optional number of intermediate mouse move steps during the drag.")}),ZH=O.object({type:O.literal("JAVASCRIPT"),code:O.string().describe("JavaScript code to execute. Defaults to NODE environment unless BROWSER is specified."),environment:O.union([O.literal("NODE"),O.literal("BROWSER")]).nullish().describe("Execution environment. Default is NODE."),timeout:O.number().nullish().describe("Max seconds for the code to complete. Max 60 seconds.")}),eG=O.object({type:O.literal("AI_EXTRACT"),goal:O.string().describe("Description of what data to extract from the page. Be specific about what you want to extract and where to find it."),schema:O.string().nullish().describe("JSON schema defining the expected structure of the extracted data."),iframeUrl:O.string().nullish().describe("URL or URL regex for the iframe to extract data from.")}),tG=O.object({type:O.literal("ELEMENT_CHECK"),description:O.string().describe("Description of the element to check."),assertionType:O.enum(["EXISTS","VISIBLE","CONTENT_CONTAINS","CONTENT_EQUALS"]).describe("The type of assertion. EXISTS checks if element exists, VISIBLE checks if visible, CONTENT_CONTAINS checks if text contains value, CONTENT_EQUALS checks if text equals value."),value:O.string().nullish().describe("The value to check against (required for CONTENT assertions)."),negated:O.boolean().nullish().describe("If true, asserts the opposite (e.g., does NOT exist)."),timeout:O.number().nullish().describe("Max seconds to wait for the assertion to be true.")}),rG=O.object({type:O.literal("PAGE_CHECK"),value:O.string().describe("The text content to check for on the page."),negated:O.boolean().nullish().describe("If true, checks that the content is NOT present."),timeout:O.number().nullish().describe("Max seconds to wait for the assertion to be true.")}),nG=O.object({type:O.literal("NEW_TAB"),url:O.string().describe("The URL to open in the new tab.")}),oG=O.object({type:O.literal("WAIT_FOR_URL"),matcher:O.discriminatedUnion("type",[O.object({type:O.literal("SUBSTRING"),url:O.string()}),O.object({type:O.literal("GLOB"),glob:O.string()}),O.object({type:O.literal("REGEX"),regex:O.string()}),O.object({type:O.literal("DOMAIN"),domain:O.string()})]).describe("How to match the URL."),caseInsensitive:O.boolean().nullish(),negated:O.boolean().nullish().describe("Wait for the URL to NOT match instead."),timeout:O.number().nullish().describe("Max seconds to wait for the URL.")}),zS=O.object({type:O.literal("SUCCESS")}),HS=O.object({type:O.literal("FAILURE")}),xR=O.discriminatedUnion("type",[gR,SR,ER,TR,bR,vR,AR,CR,RR,yR]),iG=O.discriminatedUnion("type",[...xR.options,wR]),hu=O.discriminatedUnion("type",[gR,SR,ER,TR,bR,vR,AR,CR,RR,yR,wR,ZH,tG,rG,nG,oG,eG,jH,HH,GH,QH,VH,WH,$H,qH,KH,YH,XH,JH]),dae=hl(hu),aG=O.discriminatedUnion("type",[...hu.options,zS,HS]),pae=hl(O.discriminatedUnion("type",[...xR.options,zS,HS])),mae=hl(O.discriminatedUnion("type",[...iG.options,zS,HS])),fae=O.object({command:O.unknown(),thoughts:O.string()});function sG(t){let e=aG.safeParse(t);if(e.success&&e.data)return e.data;let r=typeof t=="object"&&t!==null&&"type"in t&&typeof t.type=="string"?t.type:null,n="Failed to parse command.";if(r){let o=hu.options.find(i=>i.shape.type.value===r);if(o){let i=hl(o);n+=`
|
|
11
|
+
`)}`}};function NH(t){return t instanceof Error?t.message.includes("Timeout")&&t.message.includes("exceeded")&&t.message.includes("waiting for locator"):!1}function DH(t){return!(t instanceof Error)||t.message.includes("locator resolved to visible")?!1:!!(t.message.includes("Timeout")&&t.message.includes("exceeded")&&t.message.includes("body >")||t.message.includes("Element is not attached to the DOM"))}var yl=class extends Error{constructor(e,r={}){super(e,r),this.name="CacheAttributesDisqualifyElementError"}},ji=class extends yl{constructor(e,r={}){super(e,r),this.name="ElementMovedError"}},Xp=class extends yl{constructor(e,r={}){super(e,r),this.name="ZeroOpacityError"}},pu=class extends Error{constructor(e,r={}){super(e,r),this.name="IsInvalidMomenticIdError"}};function kH(t){return t instanceof Error?t.message.includes("Could not find attribute data-momentic-id for object"):!1}var US="Element to be clicked has no bounding box";function FH(t){return t instanceof Error?t.message.startsWith(US):!1}function BS(t){return t instanceof ji||DH(t)||UH(t)||BH(t)||NH(t)||kH(t)||FH(t)}function UH(t){return t instanceof Error?t instanceof pu?!0:t.message.includes("Timeout")&&t.message.includes("exceeded")&&t.message.includes("waiting for locator")&&t.message.includes("data-momentic-id")&&!t.message.includes("locator resolved")&&!t.message.includes("waiting for element to be"):!1}function BH(t){return t instanceof Error?t.message.includes("Protocol error (DOM.resolveNode): No node with given id found")||t.message.includes("Could not resolve backend node"):!1}var mu=class extends Error{constructor(e,r={}){super(e,r),this.name="InsufficientCacheDataError"}};function Yt(t){return t instanceof Error?t.message:String(t)}var zH={CLICK:"Click on an element on the page.",TYPE:"Focus the element then type the specified text into an input on the page.",PRESS:"Press one or more keyboard keys.",KEY_DOWN:"Hold down one or more keyboard keys.",KEY_UP:"Release one or more keyboard keys.",SELECT_OPTION:"Choose an option from a native <select> component. Never use this command for non <select> elements. Instead, use a series of CLICK commands for those.",NAVIGATE:"Go to the specified fully qualified URL.",SCROLL_UP:"Scroll up.",SCROLL_DOWN:"Scroll down.",GO_BACK:"Go back to the previous page.",HOVER:"Hover over an element.",AI_ASSERTION:"Verify a statement about the current page, retrying until it is true. Only generate an assertion if the goal includes language like 'check that', 'verify that', etc..",WAIT:"Wait a fixed amount of seconds.",DRAG:"Drag an element from one location and drop it onto another element.",JAVASCRIPT:"Execute JavaScript code in NODE or BROWSER environment.",ELEMENT_CHECK:"Perform a manual assertion on a specific element.",PAGE_CHECK:"Perform a manual case sensitive assertion on the page's html.",NEW_TAB:"Open a new browser tab with the specified URL.",WAIT_FOR_URL:"Wait for the URL to match a pattern.",AI_EXTRACT:"Extract data from the page and optionally store it in an environment variable.",COPY:"Copy the specified text value to the browser clipboard.",GO_FORWARD:"Navigate forward to the next page in the browser history (if available). Only use this after having navigated back with GO_BACK. Do not use this to navigate to a different page - use NAVIGATE instead.",LOCAL_STORAGE:"Set or get a value in the browser's localStorage. Use this to store data that persists across page reloads or to read stored values.",MOUSE_DRAG:"Drag the mouse from a starting point (or element) in a specific direction by pixel amounts. Prefer using DRAG (drag and drop between elements) instead unless the user explicitly requests dragging in a direction or by pixels. Use this when dragging needs to move a specific distance rather than to a target element.",PASTE:"Paste the contents of the browser clipboard into the currently focused element. Use this after copying text with COPY or when pasting content that was previously copied.",REFRESH:"Reload the current page. Use this to refresh the page content or retry a failed operation.",REQUEST:"Make an HTTP API request to a specified URL. Use this to interact with REST APIs, send data to a server, or retrieve data from an endpoint. Supports GET, POST, PUT, DELETE, and PATCH methods with custom headers, query parameters, and request body.",GRAPHQL_REQUEST:"Make a GraphQL request to a specified URL. Provide the GraphQL query (or mutation), optional variables JSON, and any required headers. Use this for GraphQL APIs instead of REQUEST.",SET_HEADER:"Set a header for subsequent network requests. Optionally scope it to matching requests.",REGISTER_REQUEST_LISTENER:"Register a request listener for matching requests and save them under a key.",RECORD_REQUESTS:"Record matching requests and store them under a key for later retrieval.",MOCK_ROUTE:"Mock matching network requests with a generated response."};OS.options.forEach(t=>{let e=t.shape.type.value;if(e!=="SUCCESS"&&!zH[e])throw new Error(`Command type ${e} is missing a description`)});var gR=O.object({type:O.literal("CLICK"),description:O.string().describe("Description of the element to click in the Current Page. Never click on <select> elements, see SELECT_OPTION."),doubleClick:O.boolean().nullish(),rightClick:O.boolean().nullish(),waitForDownload:O.boolean().nullish().describe("Wait for the click to trigger a file download and for the download to complete."),downloadTimeoutMs:O.number().int().nullish().describe("Max milliseconds to wait for a download to start and complete when waitForDownload is enabled."),delayMs:O.number().int().nullish().describe("Delay before performing the click, in milliseconds.")}),SR=O.object({type:O.literal("TYPE"),description:O.string().describe("Description of the element to type into, which must be an <input>, <textarea>, or contenteditable element."),text:O.string().describe("The text to enter, truncated to 500 characters. If the PM provided text in the goals, use it exactly without modification."),pressEnter:O.boolean().nullish().describe("Press enter after typing (useful for form submissions)."),clearContent:O.boolean().nullish().describe("Clear existing content before typing. Disable to append to the existing text.")}),yR=O.object({type:O.literal("GO_BACK")}),HH=O.object({type:O.literal("GO_FORWARD")}),GH=O.object({type:O.literal("LOCAL_STORAGE"),key:O.string().describe("The localStorage key to set or get."),value:O.string().describe("The value to store in localStorage. If reading, this can be empty.")}),ER=O.object({type:O.literal("PRESS"),keys:O.array(O.string()).describe('The keys to press. Only use key names supported by the Playwright press method, such as "a", "ArrowLeft", "Meta", "Control", and "Enter". Multiple keys will be pressed together. Do not suggest platform-specific key combinations, such as CTRL+C.')}),TR=O.object({type:O.literal("SELECT_OPTION"),description:O.string().describe("Description of the <select> element to choose from. Only use this command to interact with native HTML <select> elements. You must use CLICK to select from any other HTML element, such as <input>, <div>, or custom elements."),option:O.discriminatedUnion("type",[O.object({type:O.literal("VALUE"),value:O.string()}),O.object({type:O.literal("LABEL"),label:O.string()}),O.object({type:O.literal("INDEX"),index:O.string().describe("Zero-based index of the option within the select.")})]).describe("Which option to select. Choose 1 of 3 strategies for selecting. By value is exactly matching the 'value' attribute. By label is exactly matching the 'label' attribute. By index is using the zero-based index of the option within the select.")}),bR=O.object({type:O.literal("NAVIGATE"),url:O.string().describe("The URL to navigate to. Only navigate to URLs relevant to the user goal.")}),vR=O.object({type:O.literal("SCROLL"),y:O.number().describe("Scroll up or down by the specified pixels. Positive values scroll down.")}),AR=O.object({type:O.literal("WAIT"),timeout:O.number().describe("The number of seconds to wait.")}),CR=O.object({type:O.literal("AI_ASSERTION"),assertion:O.string().describe("The assertion to verify. This should be a statement verifiable based on the current page HTML or screenshot. Be specific enough that the assertion is not ambiguous or open to interpretation. Make sure the assertion aligns with what the user intends to verify."),timeout:O.number().describe("The max amount of seconds to wait for the assertion to be true. Respect user wishes but allow no more than 60. If unspecified, choose 5 for quick checks like form status, 10 for page loads, and 30 for actions that explicitly trigger a long time, like image generation.")}),RR=O.object({type:O.literal("HOVER"),description:O.string().describe("Description of the element to hover over. Prefer elements that have visible bounding boxes according to the screenshot, element class attribute, or child contents.")}),jH=O.object({type:O.literal("COPY"),value:O.string().describe("The text value to copy to the browser clipboard. This should be the exact text that needs to be copied.")}),VH=O.object({type:O.literal("PASTE")}),WH=O.object({type:O.literal("REFRESH")}),$H=O.object({type:O.literal("REQUEST"),url:O.string().describe("The URL to send the HTTP request to. Can be a full URL or relative path."),method:O.enum(["GET","POST","PUT","DELETE","PATCH"]).describe("The HTTP method to use. GET for retrieving data, POST for creating resources, PUT for updating resources, DELETE for removing resources, PATCH for partial updates."),headers:O.record(O.string(),O.string()).nullish().describe("Optional HTTP headers as key-value pairs. Common headers include 'Content-Type', 'Authorization', 'Accept', etc."),params:O.record(O.string(),O.string()).nullish().describe("Optional URL query parameters as key-value pairs. These will be appended to the URL as ?key1=value1&key2=value2."),body:O.string().nullish().describe("Optional request body as a string. For JSON data, stringify the object. Typically used with POST, PUT, or PATCH requests."),timeout:O.number().int().nullish().describe("Optional maximum number of seconds to wait for the request to complete. Defaults to 30 seconds if not specified.")}),qH=O.object({type:O.literal("GRAPHQL_REQUEST"),url:O.string().describe("The URL of the GraphQL endpoint. Can be a full URL or relative path."),headers:O.record(O.string(),O.string()).nullish().describe("Optional HTTP headers as key-value pairs. Common headers include 'Content-Type', 'Authorization', 'Accept', etc."),query:O.string().describe("The GraphQL query or mutation string. Include any required fields and arguments."),variables:O.string().nullish().describe("Optional JSON string of variables to pass with the GraphQL request."),timeout:O.number().int().nullish().describe("Optional maximum number of seconds to wait for the request to complete. Defaults to 30 seconds if not specified.")}),KH=O.object({type:O.literal("SET_HEADER"),name:O.string().describe("The header name to set."),value:O.string().describe("The header value to set."),requestMatcher:Do.nullish().describe("Optional request matcher to scope the header to matching requests.")}),YH=O.object({type:O.literal("REGISTER_REQUEST_LISTENER"),requestMatcher:Do.describe("Request matcher to define which requests should be captured."),key:O.string().describe("Identifier for the listener. Used to retrieve recorded data.")}),XH=O.object({type:O.literal("RECORD_REQUESTS"),requestMatcher:Do.describe("Request matcher to define which requests should be recorded."),key:O.string().describe("Identifier for the recording. Used to retrieve recorded data.")}),JH=O.object({type:O.literal("MOCK_ROUTE"),requestMatcher:Do.describe("Request matcher defining which requests should be mocked."),responseGenerator:O.string().describe("JavaScript code to generate the mocked response."),fetchOriginalResponse:O.boolean().nullish().describe("Whether to fetch the real response and pass it to the response generator."),key:O.string().nullish().describe("Optional key to reference this mock for removal.")}),wR=O.object({type:O.literal("DRAG"),fromDescription:O.string().describe("Description of the element to drag. Prefer precise identifiers or text that clearly distinguishes the element."),toDescription:O.string().describe("Description of the element to drop onto. Ensure the drop target is interactable and visible."),steps:O.number().int().positive().nullish().describe("Optional number of intermediate mouse move steps during the drag. Do not use this unless the user tells you to."),hoverSeconds:O.number().positive().nullish().describe("Optional seconds to hover over the destination before releasing the drag.")}),QH=O.object({type:O.literal("MOUSE_DRAG"),description:O.string().nullish().describe("Optional description of the element to start the drag from. If not provided, starts from current mouse position."),deltaX:O.number().describe("Number of pixels to move horizontally (positive = right, negative = left)."),deltaY:O.number().describe("Number of pixels to move vertically (positive = down, negative = up)."),steps:O.number().int().positive().nullish().describe("Optional number of intermediate mouse move steps during the drag.")}),ZH=O.object({type:O.literal("JAVASCRIPT"),code:O.string().describe("JavaScript code to execute. Defaults to NODE environment unless BROWSER is specified."),environment:O.union([O.literal("NODE"),O.literal("BROWSER")]).nullish().describe("Execution environment. Default is NODE."),timeout:O.number().nullish().describe("Max seconds for the code to complete. Max 60 seconds.")}),eG=O.object({type:O.literal("AI_EXTRACT"),goal:O.string().describe("Description of what data to extract from the page. Be specific about what you want to extract and where to find it."),schema:O.string().nullish().describe("JSON schema defining the expected structure of the extracted data."),iframeUrl:O.string().nullish().describe("URL or URL regex for the iframe to extract data from.")}),tG=O.object({type:O.literal("ELEMENT_CHECK"),description:O.string().describe("Description of the element to check."),assertionType:O.enum(["EXISTS","VISIBLE","CONTENT_CONTAINS","CONTENT_EQUALS"]).describe("The type of assertion. EXISTS checks if element exists, VISIBLE checks if visible, CONTENT_CONTAINS checks if text contains value, CONTENT_EQUALS checks if text equals value."),value:O.string().nullish().describe("The value to check against (required for CONTENT assertions)."),negated:O.boolean().nullish().describe("If true, asserts the opposite (e.g., does NOT exist)."),timeout:O.number().nullish().describe("Max seconds to wait for the assertion to be true.")}),rG=O.object({type:O.literal("PAGE_CHECK"),value:O.string().describe("The text content to check for on the page."),negated:O.boolean().nullish().describe("If true, checks that the content is NOT present."),timeout:O.number().nullish().describe("Max seconds to wait for the assertion to be true.")}),nG=O.object({type:O.literal("NEW_TAB"),url:O.string().describe("The URL to open in the new tab.")}),oG=O.object({type:O.literal("WAIT_FOR_URL"),matcher:O.discriminatedUnion("type",[O.object({type:O.literal("SUBSTRING"),url:O.string()}),O.object({type:O.literal("GLOB"),glob:O.string()}),O.object({type:O.literal("REGEX"),regex:O.string()}),O.object({type:O.literal("DOMAIN"),domain:O.string()})]).describe("How to match the URL."),caseInsensitive:O.boolean().nullish(),negated:O.boolean().nullish().describe("Wait for the URL to NOT match instead."),timeout:O.number().nullish().describe("Max seconds to wait for the URL.")}),zS=O.object({type:O.literal("SUCCESS")}),HS=O.object({type:O.literal("FAILURE")}),xR=O.discriminatedUnion("type",[gR,SR,ER,TR,bR,vR,AR,CR,RR,yR]),iG=O.discriminatedUnion("type",[...xR.options,wR]),hu=O.discriminatedUnion("type",[gR,SR,ER,TR,bR,vR,AR,CR,RR,yR,wR,ZH,tG,rG,nG,oG,eG,jH,HH,GH,QH,VH,WH,$H,qH,KH,YH,XH,JH]),pae=hl(hu),aG=O.discriminatedUnion("type",[...hu.options,zS,HS]),mae=hl(O.discriminatedUnion("type",[...xR.options,zS,HS])),fae=hl(O.discriminatedUnion("type",[...iG.options,zS,HS])),hae=O.object({command:O.unknown(),thoughts:O.string()});function sG(t){let e=aG.safeParse(t);if(e.success&&e.data)return e.data;let r=typeof t=="object"&&t!==null&&"type"in t&&typeof t.type=="string"?t.type:null,n="Failed to parse command.";if(r){let o=hu.options.find(i=>i.shape.type.value===r);if(o){let i=hl(o);n+=`
|
|
12
12
|
|
|
13
13
|
Attempted to create a ${r} command, but validation failed.`,n+=`
|
|
14
14
|
|
|
@@ -17,11 +17,11 @@ ${JSON.stringify(i,null,2)}`}else n+=`
|
|
|
17
17
|
|
|
18
18
|
Unknown command type: "${r}".`;n+=`
|
|
19
19
|
|
|
20
|
-
Parse error: ${e.error.message}`}throw new Yp(n,{cause:e.error})}var _R=t=>{let e=sG(t);switch(e.type){case"CLICK":return{id:ct(),type:"CLICK",doubleClick:e.doubleClick??void 0,rightClick:e.rightClick??void 0,waitForDownload:e.waitForDownload??void 0,downloadTimeoutMs:e.waitForDownload===!0?e.downloadTimeoutMs??void 0:void 0,delayMs:e.delayMs??void 0,target:{type:"description",elementDescriptor:e.description}};case"TYPE":return{id:ct(),type:"TYPE",value:e.text,target:{type:"description",elementDescriptor:e.description},pressEnter:e.pressEnter??void 0,clearContent:e.clearContent??void 0};case"PRESS":return{id:ct(),type:"PRESS",value:e.keys.join("+")};case"SELECT_OPTION":return{id:ct(),type:"SELECT_OPTION",target:{type:"description",elementDescriptor:`<select> element matching description: ${e.description}`},choice:PS.parse(e.option)};case"NAVIGATE":return{id:ct(),type:"NAVIGATE",url:e.url};case"SCROLL":return e.y>0?{id:ct(),type:"SCROLL_DOWN",deltaY:e.y}:{id:ct(),type:"SCROLL_UP",deltaY:-e.y};case"WAIT":return{id:ct(),type:"WAIT",delay:e.timeout};case"AI_ASSERTION":return{id:ct(),type:"AI_ASSERTION",assertion:e.assertion,timeout:e.timeout};case"HOVER":return{id:ct(),type:"HOVER",target:{type:"description",elementDescriptor:e.description}};case"DRAG":return{id:ct(),type:"DRAG",fromTarget:{type:"description",elementDescriptor:e.fromDescription},toTarget:{type:"description",elementDescriptor:e.toDescription},steps:e.steps??void 0,hoverSeconds:e.hoverSeconds??void 0};case"JAVASCRIPT":return{id:ct(),type:"JAVASCRIPT",code:e.code,environment:e.environment??void 0,timeout:e.timeout??void 0};case"AI_EXTRACT":return{id:ct(),type:"AI_EXTRACT",goal:e.goal,schema:e.schema??void 0,iframeUrl:e.iframeUrl??void 0};case"COPY":return{id:ct(),type:"COPY",value:e.value};case"PASTE":return{id:ct(),type:"PASTE"};case"REFRESH":return{id:ct(),type:"REFRESH"};case"GO_FORWARD":return{id:ct(),type:"GO_FORWARD"};case"LOCAL_STORAGE":return{id:ct(),type:"LOCAL_STORAGE",key:e.key,value:e.value};case"MOUSE_DRAG":return{id:ct(),type:"MOUSE_DRAG",target:e.description?{type:"description",elementDescriptor:e.description}:void 0,deltaX:e.deltaX.toString(),deltaY:e.deltaY.toString(),steps:e.steps??void 0};case"ELEMENT_CHECK":{let r;switch(e.assertionType){case"EXISTS":r={type:"ELEMENT_EXISTENCE",condition:"EXISTS",negated:e.negated??void 0};break;case"VISIBLE":r={type:"ELEMENT_EXISTENCE",condition:"VISIBLE",negated:e.negated??void 0};break;case"CONTENT_CONTAINS":r={type:"ELEMENT_CONTENT",operation:"CONTAINS",value:e.value??"",negated:e.negated??void 0};break;case"CONTENT_EQUALS":r={type:"ELEMENT_CONTENT",operation:"EQUALS",value:e.value??"",negated:e.negated??void 0};break;default:return(o=>{throw"If Typescript complains about the line below, you missed a case or break in the switch above"})(e.assertionType)}return{id:ct(),type:"ELEMENT_CHECK",target:{type:"description",elementDescriptor:e.description},assertion:r,timeout:e.timeout??void 0}}case"PAGE_CHECK":return{id:ct(),type:"PAGE_CHECK",assertion:{type:"CONTENT",value:e.value??void 0,negated:e.negated??void 0},timeout:e.timeout??void 0};case"NEW_TAB":return{id:ct(),type:"NEW_TAB",url:e.url};case"WAIT_FOR_URL":return{id:ct(),type:"WAIT_FOR_URL",matcher:e.matcher,caseInsensitive:e.caseInsensitive??void 0,negated:e.negated??void 0,timeout:e.timeout??void 0};case"GO_BACK":return{id:ct(),type:"GO_BACK"};case"REQUEST":return{id:ct(),type:"REQUEST",url:e.url,method:e.method,headers:e.headers??void 0,params:e.params??void 0,body:e.body?{type:"json",content:e.body}:void 0,timeout:e.timeout??void 0};case"GRAPHQL_REQUEST":return{id:ct(),type:"GRAPHQL_REQUEST",url:e.url,headers:e.headers??void 0,query:e.query,variables:e.variables??void 0,timeout:e.timeout??void 0};case"SET_HEADER":return{id:ct(),type:"SET_HEADER",name:e.name,value:e.value,requestMatcher:e.requestMatcher??void 0};case"REGISTER_REQUEST_LISTENER":return{id:ct(),type:"REGISTER_REQUEST_LISTENER",requestMatcher:e.requestMatcher,key:e.key};case"RECORD_REQUESTS":return{id:ct(),type:"RECORD_REQUESTS",requestMatcher:e.requestMatcher,key:e.key};case"MOCK_ROUTE":return{id:ct(),type:"MOCK_ROUTE",requestMatcher:e.requestMatcher,responseGenerator:e.responseGenerator,fetchOriginalResponse:e.fetchOriginalResponse??void 0,key:e.key??void 0};case"SUCCESS":case"FAILURE":return{id:ct(),type:e.type};default:return(n=>{throw"If Typescript complains about the line below, you missed a case or break in the switch above"})(e)}};import{z as GS}from"zod";import{extendZodWithOpenApi as uG}from"zod-openapi";import{z as IR}from"zod";import{extendZodWithOpenApi as lG}from"zod-openapi";import{z as Vi}from"zod";var Dn=Vi.object({index:Vi.number().optional().describe("global index within a test (in-order traversal)"),id:Vi.string(),skipped:Vi.boolean().optional(),comment:Vi.string().optional(),envKey:Vi.string().optional().describe("key in the environment to save the result of this step to"),aiSuggested:Vi.boolean().optional(),retries:Vi.number().optional()});lG(IR);var cG=Dn.extend({type:IR.literal("PRESET_ACTION")}),hn=cG.extend({command:ml}).openapi({ref:"PresetAction"});uG(GS);var Ga=Dn.extend({type:GS.literal("AI_ACTION"),text:GS.string(),steps:hn.array().optional()}).openapi({ref:"AIAction"});import{z as Wr}from"zod";import{z as gu}from"zod";import{extendZodWithOpenApi as dG}from"zod-openapi";dG(gu);var Su=30,jS=(r=>(r.V2="2",r.V3="3",r))(jS||{}),pG=gu.nativeEnum(jS),El=Dn.extend({type:gu.literal("AI_ACTION_DYNAMIC"),text:gu.string(),retries:gu.number().optional(),version:pG.optional()}).openapi({ref:"AIActionDynamic"});import{z as PR}from"zod";var VS=Dn.extend({type:PR.literal("CONDITIONAL"),skipped:PR.boolean().optional()});import{z as Ye}from"zod";var mG=Ye.object({cacheKey:Ye.string(),cacheExpiryMs:Ye.number()}),WS=Dn.extend({id:Ye.string().uuid().describe("ID of the module step itself. Used to 'namespace' step cache entries."),inputs:Ye.record(Ye.string()).optional(),cacheConfig:mG.optional()}),ho=WS.extend({type:Ye.literal("MODULE"),moduleId:Ye.string().uuid()}),fG=Ye.union([ho.pick({type:!0,moduleId:!0}),Ye.record(Ye.unknown())]),hG=Ye.object({type:Ye.literal("URL_REGEX"),regex:Ye.string()}),gG=Ye.object({type:Ye.literal("PAGE_CHECK"),substring:Ye.string()}),$S=Ye.object({cacheInvalidation:Ye.discriminatedUnion("type",[gG,hG]).optional()}),tn=Ye.object({moduleId:Ye.string().uuid(),name:Ye.string(),description:Ye.string().nullish(),enabled:Ye.boolean().nullish(),parameters:Ye.string().array().nullish(),defaultParameters:Ye.record(Ye.string(),Ye.string()).nullish(),parameterEnums:Ye.record(Ye.string(),Ye.string().array()).nullish(),defaultCacheKey:Ye.string().nullish(),defaultCacheTtl:Ye.number().nullish(),defaultCacheAllInvocations:Ye.boolean().nullish(),autoAuth:Ye.boolean().nullish(),advanced:$S.nullish()});var qS=t=>t.type==="RESOLVED_MODULE";import{z as kn}from"zod";var KS=(n=>(n.ALWAYS="ALWAYS",n.ON_FAILURE="ON_FAILURE",n.ON_ACTION_FAILURE="ON_ACTION_FAILURE",n))(KS||{});var SG=kn.discriminatedUnion("type",[kn.object({type:kn.literal("NAVIGATE_URL"),url:kn.string().url()}),kn.object({type:kn.literal("GO_TO_SECTION_START")})]),yG=kn.object({trigger:kn.nativeEnum(KS).optional(),attempts:kn.number().int().optional(),restartBehavior:SG}),yu=Dn.extend({type:kn.literal("SECTION"),description:kn.string().describe("user provided goal of what the section should accomplish"),plan:kn.string().array().optional(),autohealingConfig:yG.optional()});var MR=tn.merge(WS).extend({type:Wr.literal("RESOLVED_MODULE"),steps:Wr.lazy(()=>Nt.array())}),YS=tn.extend({steps:Wr.lazy(()=>Nt.array())}),XS=yu.extend({steps:Wr.lazy(()=>bt.array())}),EG=yu.extend({steps:Wr.lazy(()=>Nt.array())}),ja=VS.extend({blocks:Wr.object({assertion:Wr.lazy(()=>hn),steps:Wr.lazy(()=>bt.array())}).array(),elseSteps:Wr.lazy(()=>bt.array().optional())}),TG=VS.extend({blocks:Wr.object({assertion:Wr.lazy(()=>hn),steps:Wr.lazy(()=>Nt.array())}).array(),elseSteps:Wr.lazy(()=>Nt.array().optional())}),bt=Wr.discriminatedUnion("type",[hn,Ga,El,ho,ja,XS]),Nt=Wr.discriminatedUnion("type",[hn,Ga,El,MR,TG,EG]);import{z as Fn}from"zod";var bG=Fn.object({steps:bt.array(),beforeSteps:bt.array().nullish(),afterSteps:bt.array().nullish()}),Wi=Fn.object({steps:Nt.array(),beforeSteps:Nt.array().nullish(),afterSteps:Nt.array().nullish()}),Va=Fn.object({steps:Fn.record(Fn.string(),Fn.unknown()).array(),beforeSteps:Fn.record(Fn.string(),Fn.unknown()).array().nullish(),afterSteps:Fn.record(Fn.string(),Fn.unknown()).array().nullish()});var De="1.0.22",JS="0.0.3";import{z as Qp}from"zod";import{z as Wa}from"zod";var vG=/^[a-f0-9]{8}-[a-f0-9]{4}-[1-5][a-f0-9]{3}-[89ab][a-f0-9]{3}-[a-f0-9]{12}$/,dt=t=>{let e=t.trim().toLowerCase().replace(/[^a-z0-9]/g,"-");for(;e.includes("--");)e=e.replaceAll("--","-");return e.startsWith("-")&&(e=e.slice(1)),e.endsWith("-")&&(e=e.slice(0,e.length-1)),e};var ui=Wa.string().min(1).max(255).superRefine((t,e)=>{try{go(t)}catch(r){return e.addIssue({code:Wa.ZodIssueCode.custom,message:r.message,fatal:!0}),Wa.NEVER}});function go(t){if(t=t.toLowerCase().trim(),t.length===0||t.length>255)throw new Error("Name must be between 1 and 255 characters long");if(/[<>:"/\\|?*]/.test(t))throw new Error('Name contains one of the following invalid characters: <>:"/\\|?*');if(t.endsWith("-")||t.startsWith("-"))throw new Error("Name cannot start or end with a dash.");if(t.includes("\0"))throw new Error("Name cannot contain null characters");if(/^(con|prn|aux|nul|com[0-9]|lpt[0-9])(\..*)?$/i.test(t))throw new Error(`"${t}" is a reserved name on Windows and cannot be used as a filename.`);if(/^\.+$/.test(t)||/^\s|\s$/.test(t))throw new Error("Name cannot start or end with a space or dot.");if(t.endsWith(".yaml"))throw new Error('Name cannot end with ".yaml".');if(t==="none")throw new Error("Name cannot be 'none'.");if(t.match(vG))throw new Error("Name cannot be a UUID. Please choose a different name.")}var Jp=Wa.preprocess(t=>t===null?"":t,Wa.union([Wa.string().url(),Wa.literal("")])).optional();var OR=["CLICK","TYPE","PRESS","SELECT_OPTION","DRAG","NAVIGATE","SCROLL","WAIT","AI_ASSERTION","HOVER","BLUR","GO_BACK","GO_FORWARD","REFRESH","NEW_TAB","SWITCH_TAB","WAIT_FOR_URL","COPY","PASTE","ELEMENT_CHECK","PAGE_CHECK","AI_EXTRACT","COOKIE","LOCAL_STORAGE","REQUEST","GRAPHQL_REQUEST","JAVASCRIPT","SET_HEADER","MOCK_ROUTE","REMOVE_ROUTE_MOCK","FILE_UPLOAD","DIALOG","MOUSE_DRAG","MODULE","AI_ACTION_DYNAMIC","CONDITIONAL"],$a=Qp.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)"),LR=Qp.object({id:Qp.string().optional().describe("Recommended way of selecting an entity. The id of the entity to resolve."),name:ui.optional().describe("1-255 chars; Only letters/numbers/dashes. Cannot start/end with '-'. Not '.yaml', 'none', or UUID."),path:Qp.string().optional().describe("The path of the entity to resolve.")}).describe("A selector for a single entity. Exactly one of id, name, or path must be provided. Id is recommended.").refine(t=>[t.id,t.name,t.path].filter(Boolean).length===1,"Exactly one of id, name, or path must be provided.");function NR(t,e){let r=e.parameters??[],n=e.defaultParameters??{},o=e.parameterEnums??{},i=t??{},a=new Set([...r,...Object.keys(n)]),s=Object.keys(i).filter(u=>!a.has(u));if(s.length>0){let u=a.size>0?Array.from(a).join(", "):"none";throw new Error(`Module "${e.name}" received unknown parameters: ${s.join(", ")}. Valid parameters are: ${u}`)}let l=r.filter(u=>!(u in n)).filter(u=>!(u in i));if(l.length>0)throw new Error(`Module "${e.name}" is missing required parameters: ${l.join(", ")}. Please call momentic_module_get to inspect the module's parameter requirements.`);for(let[u,d]of Object.entries(i))if(u in o){let p=o[u];if(p&&!p.includes(d))throw new Error(`Module "${e.name}" parameter "${u}" must be one of: ${p.join(", ")}. Received: "${d}"`)}}var DR=D.object({phrase:D.string()}),Zp=D.object({thoughts:D.string().optional(),result:D.union([D.literal("NOT_FOUND"),D.string(),D.number(),D.array(D.unknown()),D.record(D.unknown(),D.unknown()),D.unknown()])}),cle=D.object({text:D.string()}),AG=D.boolean().or(D.nativeEnum(en)).transform(t=>!(!t||t==="irrelevant")),kR=D.object({attributes:D.array(D.string()).nullish(),text:AG.nullish(),position:D.nativeEnum(en).nullish(),shape:D.nativeEnum(en).nullish()}),CG=D.object({id:D.number().int(),requirements:kR}),RG=CG.array(),em=D.object({thoughts:D.string(),review:D.string().optional(),id:D.number().int(),updatedMemory:eu.optional(),requirements:kR.nullish().transform(t=>{if(t!==null)return t}),additionalElements:RG.nullish().transform(t=>{if(t!==null)return t})});var FR=(m=>(m.NO_DESCRIPTION_PROVIDED="NO_DESCRIPTION_PROVIDED",m.FEW_WORDS="FEW_WORDS",m.STYLE_TAG="STYLE_TAG",m.TYPE_IN_DESCRIPTION="TYPE_IN_DESCRIPTION",m.HARDCODED_ATTRIBUTE="HARDCODED_ATTRIBUTE",m.NONE="NONE",m.AMBIGUOUS_DESCRIPTION="AMBIGUOUS_DESCRIPTION",m.AMBIGUOUS_ASSERTION="AMBIGUOUS_ASSERTION",m.PREFER_PAGE_CHECK="PREFER_PAGE_CHECK",m.PREFER_ASSERTION="PREFER_ASSERTION",m.HTML_ELEMENTS="HTML_ELEMENTS",m.MULTIPLE_ELEMENTS_DESCRIPTION="MULTIPLE_ELEMENTS_DESCRIPTION",m.NEEDS_DATE_VARIABLE="NEEDS_DATE_VARIABLE",m))(FR||{}),UR=(o=>(o.NONE="NONE",o.AMBIGUOUS_DESCRIPTION="AMBIGUOUS_DESCRIPTION",o.COPILOT_MISUSE="COPILOT_MISUSE",o.IRRELEVANT_MESSAGE="IRRELEVANT_MESSAGE",o))(UR||{});var BR=D.object({thoughts:D.string(),category:D.nativeEnum(FR)}),zR=D.object({thoughts:D.string(),category:D.nativeEnum(UR)}),HR=D.object({anyUntestedSteps:D.boolean().describe("True if any steps (especially new/edited) were not fully run (preview + add) or if their immediately following step, if any, was not run."),possibleErrors:D.object({error:D.string(),solutionFound:D.object({description:D.string(),passedSuccessfully:D.boolean().describe("Whether the solution passed successfully")})}).array().describe("Information about any errors we encountered and how we solved them"),safeToContinue:D.boolean().describe("Whether it is safe to continue or if we are stuck and need intervention"),finalReport:D.string().describe("A final summary report of the session, are we stuck, can we go forward, do we need help, or are we good to go?")}),GR=D.object({summary:D.string().describe("Single large block of text summary of the full chat thread; high-signal only."),errorsRanInto:D.array(D.object({error:D.string(),workAround:D.string()})).default([]).describe("List of encountered errors and mitigations."),untestedSteps:D.array(D.string()).default([]).describe("Steps added/discussed but not validated.")}),wG=D.discriminatedUnion("op",[D.object({op:D.literal("replace"),path:D.string(),value:D.string()}),D.object({op:D.literal("add"),path:D.string(),value:D.string()}),D.object({op:D.literal("remove"),path:D.string()})]),ule=D.object({thoughts:D.string(),patches:wG.array()}),xG=[D.literal("add"),D.literal("replace"),D.literal("remove")],_G=D.object({op:D.union(xG),path:D.string(),value:Nt.optional()}),jR=D.object({patches:_G.array(),thoughts:D.string()}),QS=(n=>(n.LEGITIMATE="LEGITIMATE",n.RECOVERABLE="RECOVERABLE",n.INELIGIBLE="INELIGIBLE",n))(QS||{}),VR=D.object({thoughts:D.string(),scenario:D.nativeEnum(QS),instructions:D.string().nullish()}),WR=D.object({reasoning:D.string(),scenario:D.string(),patch:D.null().optional()}),dle=D.object({thoughts:D.string(),evaluation:D.number().min(0).max(10)}),ple=D.object({observations:D.string(),reasoning:D.string(),command:Gp});var ZS=D.object({summary:D.string(),reasoning:D.string(),evaluation:D.discriminatedUnion("type",[D.object({type:D.literal("DONE")}),D.object({type:D.literal("RIGHT_TRACK")}),D.object({type:D.literal("WRONG_TRACK"),feedback:D.string()}),D.object({type:D.literal("IMPOSSIBLE")})])}),IG=D.object({startId:D.number().int(),endId:D.number().int()}),$R=(n=>(n.SIMPLE_CONTENT_BASED_LOCATOR="SIMPLE_CONTENT_BASED_LOCATOR",n.SIMPLE_CONTENT_BASED_ASSERTION="SIMPLE_CONTENT_BASED_ASSERTION",n.OTHER="OTHER",n))($R||{}),qR=D.object({categoryThoughts:D.string(),category:D.nativeEnum($R),relevantSections:IG.array()}),di=D.boolean().nullish().transform(t=>t??!1),KR=D.object({thoughts:D.string().optional(),isPageReady:di,descriptionLabels:D.object({usesTextContent:di,usesAppearance:di,usesPosition:di,usesRelativeElements:di,usesSingleQuotes:di,isAmbiguous:di,targetDoesNotExist:di,usesIcon:di}).optional()});import{z as N}from"zod";import*as Ue from"zod";var Ele=Ue.object({thoughts:Ue.string().optional().describe("only provided if a description was provided"),target:li.optional().describe("only provided if a description was provided"),pageState:Ue.string().optional().describe("serialized a11y tree, only provided if a description was provided"),options:Ue.object({label:Ue.string(),value:Ue.string()}).array().optional().describe("list of options, provided for <select> elements only"),screenshot:Ue.object({data:Ue.string().or(Na),height:Ue.number().int(),width:Ue.number().int()}).optional().describe("only provided if returnScreenshot is true")}),YR=Ue.union([Ue.literal("ELEMENT_CHECK"),Ue.literal("NEGATED_CHECK"),Ue.literal("NEGATED_ELEMENT_VISIBLE_CHECK"),Ue.literal("SELECT_OPTION"),Ue.literal("TYPE")]);function qa(t){if(!("useSelector"in t&&t.useSelector)){if(t.type==="SELECT_OPTION")return"SELECT_OPTION";if(t.type==="TYPE")return"TYPE";if(t.type==="ELEMENT_CHECK"&&t.assertion.type==="ELEMENT_EXISTENCE"&&t.assertion.condition==="EXISTS"&&t.assertion.negated)return"NEGATED_CHECK";if(t.type==="ELEMENT_CHECK"&&t.assertion.type==="ELEMENT_EXISTENCE"&&t.assertion.condition==="VISIBLE"&&t.assertion.negated)return"NEGATED_ELEMENT_VISIBLE_CHECK";if(t.type==="ELEMENT_CHECK")return"ELEMENT_CHECK"}}var Eu=(a=>(a.USER_SELECTOR="USER_SELECTOR",a.CSS_SELECTOR="CSS_SELECTOR",a.HYBRID_SELECTOR="HYBRID_SELECTOR",a.HTML_DISTANCE="HTML_DISTANCE",a.TEMPLATE_MATCHING="TEMPLATE_MATCHING",a.AUTO_FRAME="AUTO_FRAME",a))(Eu||{}),Tl=Ue.object({matched:Ue.boolean(),reason:Ue.string().optional().describe("Human understandable description"),logs:Ue.string().array().optional().describe("Logs for debugging")}),PG=Tl.extend({type:Ue.literal("USER_SELECTOR")}),MG=Tl.extend({type:Ue.literal("CSS_SELECTOR"),selectors:Ue.string().array()}),OG=Tl.extend({type:Ue.literal("HYBRID_SELECTOR")}),LG=Tl.extend({type:Ue.literal("HTML_DISTANCE"),distance:Ue.number().optional(),closestElement:Ue.string().optional(),savedElement:Ue.string().optional()}),NG=Tl.extend({type:Ue.literal("TEMPLATE_MATCHING")}),DG=Tl.extend({type:Ue.literal("AUTO_FRAME"),logs:Ue.string().array().optional()}),XR=Ue.discriminatedUnion("type",[PG,MG,OG,LG,NG,DG]);import{z as vu}from"zod";import{z as YG}from"zod";import*as ue from"zod";import{extendZodWithOpenApi as HG}from"zod-openapi";import{cloneDeep as Tu}from"lodash-es";import nw from"truncate-json";import*as Xa from"zod";import{extendZodWithOpenApi as UG}from"zod-openapi";import{z as Pr}from"zod";import{z as Ce}from"zod";import{z as ey}from"zod";var So=(o=>(o.CHROMIUM="Chromium",o.GOOGLE_CHROME="Google Chrome",o.CHROME_FOR_TESTING="Chrome for Testing",o.ORG_DEFAULT="Org Default",o))(So||{});var tm=ey.object({width:ey.number().min(200).max(1e4),height:ey.number().min(200).max(1e4)}),JR={"Desktop Large":{width:1920,height:1080},"Desktop Small":{width:1280,height:800},iPad:{width:768,height:1024},"Pixel 8":{width:448,height:998},"iPhone 15":{width:393,height:852}},vle=Object.keys(JR);var Ir=JR["Desktop Large"],$i="en-us",qi="America/Los_Angeles",kG="Chromium",Ki={latitude:37.7749,longitude:-122.4194};function rm({configuredBrowserType:t,orgDefaultBrowserType:e,browserTypeOverride:r}){let n=r??t;return n==="Org Default"&&e?e:n??kG}var nm=(a=>(a.ClipboardRead="clipboard-read",a.ClipboardWrite="clipboard-write",a.Microphone="microphone",a.Camera="camera",a.Geolocation="geolocation",a.LocalNetworkAccess="local-network-access",a))(nm||{});var ty=Ce.object({autoFollowNewTabs:Ce.boolean().optional().describe("Deprecated: Auto-follow new tabs that are opened."),showZeroOpacityElements:Ce.union([Ce.boolean(),Ce.literal("inputs-only")]).optional(),ignoreHrefForCaching:Ce.boolean().optional(),disableSecondaryCacheResolution:Ce.boolean().optional(),hybridSelectorMode:Ce.enum(["off","test","prefer"]).optional(),globalLocatorRedirect:Ce.union([Ce.boolean(),Ce.literal("always")]).optional(),enableForceClickForMissingRedirectElement:Ce.boolean().optional(),visualActions:Ce.boolean().optional(),autoExpandIframes:Ce.boolean().optional(),disableHtmlSnapshots:Ce.boolean().optional(),defaultBrowserType:Ce.nativeEnum(So).optional(),importantAttributes:Ce.string().array().optional(),importantClasses:Ce.string().array().optional(),importantStyles:Ce.string().array().optional()});var QR=1e4,ZR=6e4,FG=Ce.object({server:Ce.string(),username:Ce.string().optional(),password:Ce.string().optional()}),Ka=ty.extend({pageLoadTimeoutMs:Ce.number().optional().refine(t=>t===void 0||t<=ZR&&t>=-1,{message:`Page load timeout must be between 0 and ${ZR/1e3} seconds`}).describe("global page load timeout default for all tests in ms, can still be overridden by individual tests"),smartWaitingTimeoutMs:Ce.number().optional().refine(t=>t===void 0||t<=QR&&t>=-1,{message:`Smart waiting timeout must be between 0 and ${QR/1e3} seconds`}),ignorePageLoadTimeouts:Ce.boolean().optional(),localChromeExtensionPaths:Ce.string().array().optional(),extraHeaders:Ce.record(Ce.string(),Ce.string()).optional().describe("HTTP headers to be sent on every request"),initialLocalStorage:Ce.record(Ce.string(),Ce.record(Ce.string(),Ce.string())).optional().describe("Initial local storage key-value pairs to set per domain on browser startup"),userAgent:Ce.string().optional(),disableGpu:Ce.boolean().optional(),disableZygote:Ce.boolean().optional(),disableBrowserMonitoring:Ce.boolean().optional().describe("Disable console logs and network request recording, which power the console and network tab in the run viewer"),disableConsoleLogs:Ce.boolean().optional().describe("Disable console log recording in the run viewer."),disableNetworkLogs:Ce.boolean().optional().describe("Disable network request recording in the run viewer."),bustCacheOnBoundingBoxChange:Ce.boolean().optional().describe("This setting is deprecated. Bust the cache if no elements are matched that have the same bounding box and location as the original element. This will improve accuracy on sites that use many same components, at the expense of stability and speed."),allowPartialAccessibilityTree:Ce.boolean().optional().describe("Allow fetching the partial accessibility tree if fetching the full tree takes too long."),ignoreHttpsErrors:Ce.boolean().optional().describe("Ignore HTTPS errors, such as self-signed certificates and certificate errors. This can be useful for testing sites that use self-signed certificates or certificate errors."),proxy:FG.optional().describe("HTTP proxy server to use for the entire browser. This can dramatically increase network latency."),disableFullStory:Ce.boolean().optional().describe("Disable FullStory, a third-party analytics tool that can significantly impact browser performance. This can be useful for testing sites that use FullStory."),grantedPermissions:Ce.nativeEnum(nm).array().optional().describe("List of permissions to grant to sites. If not provided, all permissions are granted.")});var ir="BASE_URL",om="CURRENT_URL",Ya="ENV_NAME",bl="TEST_NAME",Mle={[ir]:"https://www.google.com"},ew=Pr.string().describe("Name of the fixture (must be available locally in the fixtures directory)."),tw=Pr.object({name:Pr.string(),variables:Pr.record(Pr.string().describe("variable name"),Pr.string().describe("variable value"))}),rw=Pr.object({name:Pr.string(),variables:Pr.record(Pr.string().describe("variable name"),Pr.unknown().describe("variable value")),browser:Ka.optional()});var Ole=Pr.object({name:Pr.string(),variables:Pr.record(Pr.string().describe("variable name"),Pr.unknown().describe("variable value"))});UG(Xa);var ry=Xa.object({env:Xa.record(Xa.unknown())}).openapi({ref:"TestContextSnapshot"}),BG="\u2022\u2022\u2022\u2022\u2022\u2022\u2022\u2022\u2022\u2022\u2022\u2022\u2022\u2022\u2022",zG=[ir,Ya,bl],ow=[om,ir,Ya,bl],$r=class t{env={};varsFromMomenticEnvironment={};constructor(e){this.reset(e)}static dummyContext(e=void 0,r=void 0,n={}){return new t({baseUrl:"about:blank",currentUrl:"about:blank",testName:e,envName:r,variablesFromEnvironment:n})}static fromSnapshot({snapshot:e,environmentVariables:r}){let n=e.env[ir]??"about:blank",o=e.env[om]??"about:blank",i=e.env[Ya],a=e.env[bl],s={};for(let[l,u]of Object.entries(e.env))ow.includes(l)||(r??{})[l]===void 0&&(s[l]=u);return new t({baseUrl:n,currentUrl:o,dynamicVariables:s,envName:i,testName:a,variablesFromEnvironment:r??{}})}setEnvVariables(e){let r=Tu(e);this.env=Object.assign(this.env,r)}setInputs(e){e&&this.setEnvVariables(e)}setMomenticSystemVariable(e,r){this.varsFromMomenticEnvironment[e]=r}getVariable(e){return this.env[e]}setVariable(e,r){zG.includes(e)||(this.env[e]=r)}getEnvName(){return this.env[Ya]}toObjectCopy(){let e={env:Object.assign({},this.env,this.varsFromMomenticEnvironment)};return Tu(e)}toEditorDisplayCopy(){return this.toObjectCopy()}toRedactedDisplayCopy(){let e=this.toObjectCopy();e.env=Object.fromEntries(Object.entries(e.env).map(([n,o])=>ow.includes(n)||this.varsFromMomenticEnvironment[n]===void 0?[n,o]:[n,BG]));for(let[n,o]of Object.entries(e.env)){if(!o){e.env[n]=o;continue}let{jsonString:i}=nw(JSON.stringify(o),5e3);try{e.env[n]=JSON.parse(i)}catch{e.env[n]=void 0}}let{jsonString:r}=nw(JSON.stringify(e.env),25e3);try{e.env=JSON.parse(r)}catch{e.env={}}return e}setCurrentUrl(e){this.env[om]=e}reset(e){this.env={},this.varsFromMomenticEnvironment={},this.setEnvVariables(e.dynamicVariables??{}),this.setCurrentUrl(e.currentUrl),this.varsFromMomenticEnvironment=Tu(e.variablesFromEnvironment),this.setMomenticSystemVariable(ir,e.baseUrl),e.envName&&this.setMomenticSystemVariable(Ya,e.envName),e.testName&&this.setMomenticSystemVariable(bl,e.testName)}getDynamicVariablesCopy(){return Tu(this.env)}getVariablesFromEnvironmentCopy(){return Tu(this.varsFromMomenticEnvironment)}};var at=(i=>(i.SUCCESS="SUCCESS",i.FAILED="FAILED",i.RUNNING="RUNNING",i.IDLE="IDLE",i.CANCELLED="CANCELLED",i))(at||{}),im=(n=>(n.SUCCESS="SUCCESS",n.FAILED="FAILED",n.CANCELLED="CANCELLED",n))(im||{});HG(ue);var ny=ue.object({beforeUrl:ue.string().optional(),afterUrl:ue.string().optional(),message:ue.string().optional(),beforeSnapshot:ue.string().optional(),afterSnapshot:ue.string().optional(),startedAt:ue.coerce.date(),finishedAt:ue.coerce.date()}),GG=ny.extend({viewport:ue.object({height:ue.number(),width:ue.number()}).nullish(),status:ue.nativeEnum(im),message:ue.string().optional(),elementInteracted:ue.string().optional()}),Ja=ny.extend({status:ue.nativeEnum(at),message:ue.string().optional(),data:ue.unknown().optional(),beforeTestContext:ry.optional(),afterTestContext:ry.optional(),failureReason:ue.nativeEnum(Ne).optional(),details:ue.unknown().describe("Parse using StepExecutionLogSchema.array() to get type safety. We don't explicitly type it because it's non-critical information."),trace:ue.unknown().optional().describe("Web interaction trace from step execution (WebSectionSpan)")}).openapi({ref:"StepResultMetadata"}),oy=(r=>(r.NOT_ELIGIBLE="NOT_ELIGIBLE",r.ATTEMPTED="ATTEMPTED",r))(oy||{}),am=Ja.merge(hn).extend({results:GG.array().describe("Command that was executed. Array is just for consistency with other result types. There should only ever be one item."),previousAttempts:ue.lazy(()=>mr.array()).optional(),failureRecoveryStatus:ue.object({type:ue.nativeEnum(oy),message:ue.string()}).optional()}),jG=Ja.merge(Ga).extend({results:ue.lazy(()=>am.array()),previousAttempts:ue.lazy(()=>mr.array()).optional()}),VG=Ja.merge(El).extend({results:ue.lazy(()=>am.array()),previousAttempts:ue.lazy(()=>mr.array()).optional()}),WG=Ja.merge(ho).extend({moduleName:ue.string().optional(),results:ue.lazy(()=>mr.array()),previousAttempts:ue.lazy(()=>mr.array()).optional()}),$G=Ja.merge(ja).extend({assertionResult:am.optional(),results:ue.lazy(()=>mr.array()).describe("results for the block actually executed"),previousAttempts:ue.lazy(()=>mr.array()).optional()}),qG=Ja.merge(yu).extend({results:ue.lazy(()=>mr.array()),healingAttempts:ue.lazy(()=>mr.array().array()).optional(),previousAttempts:ue.lazy(()=>mr.array()).optional()}),mr=ue.discriminatedUnion("type",[jG,VG,am,WG,$G,qG]),sm=Ja.pick({startedAt:!0,finishedAt:!0,status:!0,message:!0,data:!0}),KG=ny.extend({index:ue.number().optional(),userFacingStepReference:ue.string().optional(),description:ue.string(),pageState:ue.string().optional(),elementInteracted:ue.string().optional(),startedAt:ue.coerce.date().or(ue.string()).optional().catch(void 0),finishedAt:ue.coerce.date().or(ue.string()).optional().catch(void 0)}),lm=KG.extend({beforeScreenshot:ue.string().optional(),afterScreenshot:ue.string().optional()});var iy=YG.object({results:mr.array().describe("main results"),beforeResults:mr.array().optional(),afterResults:mr.array().optional()}),bu=iy.partial();import{z as ee}from"zod";import{extendZodWithOpenApi as rj}from"zod-openapi";import{z as Yi}from"zod";import XG from"zod";var gn=(r=>(r.ANDROID="ANDROID",r.IOS="IOS",r))(gn||{});var iw=XG.nativeEnum(gn);var vl=(n=>(n.WEB="WEB",n.ANDROID="ANDROID",n.IOS="IOS",n))(vl||{});var cm=Yi.object({fromStepId:Yi.string(),parentStepIdChain:Yi.array(Yi.string())}),um=Yi.object({toStepId:Yi.string(),parentStepIdChain:Yi.array(Yi.string())});import{z as St}from"zod";import{isValidCron as JG}from"cron-validator";import{z as Be}from"zod";var aw=["Africa/Abidjan","Africa/Accra","Africa/Algiers","Africa/Bissau","Africa/Cairo","Africa/Casablanca","Africa/Ceuta","Africa/El_Aaiun","Africa/Johannesburg","Africa/Juba","Africa/Khartoum","Africa/Lagos","Africa/Maputo","Africa/Monrovia","Africa/Nairobi","Africa/Ndjamena","Africa/Sao_Tome","Africa/Tripoli","Africa/Tunis","Africa/Windhoek","America/Adak","America/Anchorage","America/Argentina/Buenos_Aires","America/Argentina/Catamarca","America/Argentina/Cordoba","America/Argentina/Jujuy","America/Argentina/La_Rioja","America/Argentina/Mendoza","America/Argentina/Rio_Gallegos","America/Argentina/Salta","America/Argentina/San_Juan","America/Argentina/San_Luis","America/Argentina/Tucuman","America/Argentina/Ushuaia","America/Araguaina","America/Asuncion","America/Atikokan","America/Bahia","America/Bahia_Banderas","America/Barbados","America/Belem","America/Belize","America/Blanc-Sablon","America/Boa_Vista","America/Bogota","America/Boise","America/Cambridge_Bay","America/Campo_Grande","America/Cancun","America/Caracas","America/Cayenne","America/Chicago","America/Chihuahua","America/Costa_Rica","America/Creston","America/Cuiaba","America/Curacao","America/Danmarkshavn","America/Dawson","America/Dawson_Creek","America/Denver","America/Detroit","America/Dominica","America/Edmonton","America/Eirunepe","America/El_Salvador","America/Fort_Nelson","America/Fortaleza","America/Glace_Bay","America/Goose_Bay","America/Grand_Turk","America/Grenada","America/Guadeloupe","America/Guatemala","America/Guayaquil","America/Guyana","America/Halifax","America/Havana","America/Hermosillo","America/Indiana/Indianapolis","America/Indiana/Knox","America/Indiana/Marengo","America/Indiana/Petersburg","America/Indiana/Tell_City","America/Indiana/Vevay","America/Indiana/Vincennes","America/Indiana/Winamac","America/Inuvik","America/Iqaluit","America/Jamaica","America/Juneau","America/Kentucky/Louisville","America/Kentucky/Monticello","America/La_Paz","America/Lima","America/Los_Angeles","America/Maceio","America/Managua","America/Manaus","America/Marigot","America/Martinique","America/Matamoros","America/Mazatlan","America/Menominee","America/Merida","America/Metlakatla","America/Mexico_City","America/Miquelon","America/Moncton","America/Monterrey","America/Montevideo","America/Montserrat","America/Nassau","America/New_York","America/Nipigon","America/Nome","America/Noronha","America/North_Dakota/Beulah","America/North_Dakota/Center","America/North_Dakota/New_Salem","America/Ojinaga","America/Panama","America/Pangnirtung","America/Paramaribo","America/Phoenix","America/Port-au-Prince","America/Port_of_Spain","America/Porto_Velho","America/Puerto_Rico","America/Punta_Arenas","America/Rainy_River","America/Rankin_Inlet","America/Recife","America/Regina","America/Resolute","America/Rio_Branco","America/Santarem","America/Santiago","America/Santo_Domingo","America/Sao_Paulo","America/Scoresbysund","America/Sitka","America/St_Barthelemy","America/St_Johns","America/St_Kitts","America/St_Lucia","America/St_Thomas","America/St_Vincent","America/Swift_Current","America/Tegucigalpa","America/Thule","America/Thunder_Bay","America/Tijuana","America/Toronto","America/Tortola","America/Vancouver","America/Whitehorse","America/Winnipeg","America/Yakutat","America/Yellowknife","Antarctica/Casey","Antarctica/Davis","Antarctica/DumontDUrville","Antarctica/Macquarie","Antarctica/Mawson","Antarctica/Palmer","Antarctica/Rothera","Antarctica/Syowa","Antarctica/Troll","Antarctica/Vostok","Arctic/Longyearbyen","Asia/Aden","Asia/Almaty","Asia/Amman","Asia/Anadyr","Asia/Aqtau","Asia/Aqtobe","Asia/Ashgabat","Asia/Atyrau","Asia/Baghdad","Asia/Bahrain","Asia/Baku","Asia/Bangkok","Asia/Barnaul","Asia/Beirut","Asia/Bishkek","Asia/Brunei","Asia/Chita","Asia/Choibalsan","Asia/Colombo","Asia/Damascus","Asia/Dhaka","Asia/Dili","Asia/Dubai","Asia/Dushanbe","Asia/Famagusta","Asia/Gaza","Asia/Hebron","Asia/Ho_Chi_Minh","Asia/Hong_Kong","Asia/Hovd","Asia/Irkutsk","Asia/Jakarta","Asia/Jayapura","Asia/Jerusalem","Asia/Kabul","Asia/Kamchatka","Asia/Karachi","Asia/Kathmandu","Asia/Khandyga","Asia/Kolkata","Asia/Krasnoyarsk","Asia/Kuala_Lumpur","Asia/Kuching","Asia/Kuwait","Asia/Macau","Asia/Magadan","Asia/Makassar","Asia/Manila","Asia/Muscat","Asia/Nicosia","Asia/Novokuznetsk","Asia/Novosibirsk","Asia/Omsk","Asia/Oral","Asia/Phnom_Penh","Asia/Pontianak","Asia/Pyongyang","Asia/Qatar","Asia/Qostanay","Asia/Qyzylorda","Asia/Riyadh","Asia/Sakhalin","Asia/Samarkand","Asia/Seoul","Asia/Shanghai","Asia/Singapore","Asia/Srednekolymsk","Asia/Taipei","Asia/Tashkent","Asia/Tbilisi","Asia/Tehran","Asia/Thimphu","Asia/Tokyo","Asia/Tomsk","Asia/Ulaanbaatar","Asia/Urumqi","Asia/Ust-Nera","Asia/Vientiane","Asia/Vladivostok","Asia/Yakutsk","Asia/Yangon","Asia/Yekaterinburg","Asia/Yerevan","Atlantic/Azores","Atlantic/Bermuda","Atlantic/Canary","Atlantic/Cape_Verde","Atlantic/Faroe","Atlantic/Madeira","Atlantic/Reykjavik","Atlantic/South_Georgia","Atlantic/Stanley","Australia/Adelaide","Australia/Brisbane","Australia/Broken_Hill","Australia/Currie","Australia/Darwin","Australia/Eucla","Australia/Hobart","Australia/Lindeman","Australia/Lord_Howe","Australia/Melbourne","Australia/Perth","Australia/Sydney","Europe/Amsterdam","Europe/Andorra","Europe/Astrakhan","Europe/Athens","Europe/Belgrade","Europe/Berlin","Europe/Bratislava","Europe/Brussels","Europe/Bucharest","Europe/Budapest","Europe/Busingen","Europe/Chisinau","Europe/Copenhagen","Europe/Dublin","Europe/Gibraltar","Europe/Guernsey","Europe/Helsinki","Europe/Isle_of_Man","Europe/Istanbul","Europe/Jersey","Europe/Kaliningrad","Europe/Kiev","Europe/Kirov","Europe/Lisbon","Europe/Ljubljana","Europe/London","Europe/Luxembourg","Europe/Madrid","Europe/Malta","Europe/Mariehamn","Europe/Minsk","Europe/Monaco","Europe/Moscow","Europe/Oslo","Europe/Paris","Europe/Podgorica","Europe/Prague","Europe/Riga","Europe/Rome","Europe/Samara","Europe/San_Marino","Europe/Sarajevo","Europe/Saratov","Europe/Simferopol","Europe/Skopje","Europe/Sofia","Europe/Stockholm","Europe/Tallinn","Europe/Tirane","Europe/Ulyanovsk","Europe/Uzhgorod","Europe/Vaduz","Europe/Vatican","Europe/Vienna","Europe/Vilnius","Europe/Volgograd","Europe/Warsaw","Europe/Zagreb","Europe/Zaporozhye","Europe/Zurich","Indian/Antananarivo","Indian/Chagos","Indian/Christmas","Indian/Cocos","Indian/Comoro","Indian/Kerguelen","Indian/Mahe","Indian/Maldives","Indian/Mauritius","Indian/Mayotte","Indian/Reunion","Pacific/Apia","Pacific/Auckland","Pacific/Bougainville","Pacific/Chatham","Pacific/Chuuk","Pacific/Easter","Pacific/Efate","Pacific/Enderbury","Pacific/Fakaofo","Pacific/Fiji","Pacific/Funafuti","Pacific/Galapagos","Pacific/Gambier","Pacific/Guadalcanal","Pacific/Guam","Pacific/Honolulu","Pacific/Kiritimati","Pacific/Kosrae","Pacific/Kwajalein","Pacific/Majuro","Pacific/Marquesas","Pacific/Midway","Pacific/Nauru","Pacific/Niue","Pacific/Norfolk","Pacific/Noumea","Pacific/Pago_Pago","Pacific/Palau","Pacific/Pitcairn","Pacific/Pohnpei","Pacific/Port_Moresby","Pacific/Rarotonga","Pacific/Saipan","Pacific/Tahiti","Pacific/Tarawa","Pacific/Tongatapu","Pacific/Wake","Pacific/Wallis"];var sw=1e4,Al=Ka.extend({browserType:Be.nativeEnum(So).optional(),slowMoMs:Be.number().optional().refine(t=>t===void 0||t<=sw&&t>=-1,{message:`Slow motion must be between 0 and ${sw} milliseconds`}),basicAuthorization:Be.object({username:Be.string().optional(),password:Be.string().optional()}).optional(),geolocation:Be.object({latitude:Be.coerce.number().refine(t=>t>=-90&&t<=90,{message:"Latitude must be between -90 and 90 degrees"}),longitude:Be.coerce.number().refine(t=>t>=-180&&t<=180,{message:"Longitude must be between -180 and 180 degrees"})}).optional(),disableJavaScript:Be.boolean().optional(),locale:Be.string().optional(),timezone:Be.enum(aw).optional(),colorScheme:Be.enum(["light","dark"]).optional()}),lw=["extraHeaders","basicAuthorization","localChromeExtensionPaths","proxy"],ay=Be.object({useMemory:Be.boolean().optional(),failureRecovery:Be.boolean().optional().describe("undefined means inherit org settings")}),sy=ay.extend({disableAICaching:Be.boolean().optional(),failureRecoveryInstructions:Be.string().optional()}),QG=Be.object({viewport:tm.optional()}),Qa=QG.merge(sy).merge(Al),Cl=Be.object({cron:Be.string().refine(t=>JG(t),{message:"Invalid cron expression."}).default("0 0 */1 * *"),enabled:Be.boolean().default(!1),env:Be.string().optional(),timeZone:Be.string().default("America/Los_Angeles"),jobKey:Be.string().optional()}),Rl=Be.object({onSuccess:Be.boolean().default(!1),failureMessage:Be.string().optional(),onFailure:Be.boolean().default(!0),successMessage:Be.string().optional()}),ZG=Be.object({name:Be.string(),required:Be.boolean().optional(),defaultValue:Be.string().describe("this is not optional because we need a value when the editor is first loaded")}),dm=ZG.array(),ej=Be.object({name:Be.string(),value:Be.string()}),cw=ej.array(),pm=Be.object({name:Be.string(),default:Be.boolean().optional(),fixtures:ew.array().optional()});var pi=ay.extend({agentConfig:St.record(St.string(),St.string()).optional(),aiFailureAnalysis:St.boolean().optional(),aiPageFiltering:St.boolean().optional().describe("rag v2 feature flag")}),tj=St.object({cliOnly:St.boolean().optional(),neverShowUsageBanner:St.boolean().optional(),hideInternalTraceInfo:St.boolean().optional()}),ly=St.object({fakerConstantSeed:St.boolean().optional(),isolateCachesByEnvironment:St.boolean().optional()}),uw=St.object({ai:pi.optional(),githubAppInstallationId:St.number().nullish(),githubAppSummaryMessageEnabled:St.boolean().nullish(),githubReleaseAppInstallationId:St.number().nullish(),gitlabAppAccessToken:St.string().nullish(),gitlabAppBaseUrl:St.string().nullish(),browser:ty.optional(),internal:tj.optional(),advanced:ly.optional()}),Sce=St.object({globalOverrides:St.record(St.string()).optional(),agentConfig:St.record(St.string(),St.string()).optional()}),yce=St.record(St.string(),St.string()).nullish();rj(ee);var rn={WEBHOOK:"WEBHOOK",CRON:"CRON",MANUAL:"MANUAL",CLI:"CLI"},nt=(s=>(s.PENDING="PENDING",s.RUNNING="RUNNING",s.PASSED="PASSED",s.FAILED="FAILED",s.CANCELLED="CANCELLED",s.RETRYING="RETRYING",s.WAITING_FOR_USER="WAITING_FOR_USER",s))(nt||{}),mm=(r=>(r.BEFORE_ALL="BEFORE_ALL",r.AFTER_ALL="AFTER_ALL",r))(mm||{});var nj=ee.object({attempts:ee.number().int().nonnegative()}),Xt=ee.string().pipe(ee.coerce.date()).or(ee.date()),Za=ee.object({id:ee.string(),runKey:ee.string(),organizationId:ee.string(),executionType:ee.nativeEnum(vl).optional().default("WEB"),createdAt:Xt,createdBy:ee.string(),flake:ee.boolean().nullish(),scheduledAt:Xt.or(ee.null()),startedAt:Xt.or(ee.null()),updatedAt:Xt.nullish(),finishedAt:Xt.or(ee.null()),resolvedBaseUrl:ee.string().nullish(),environmentName:ee.string().nullish(),gitBranchName:ee.string().nullish(),githubRepository:ee.string().nullish(),gitlabProjectPath:ee.string().nullish(),labels:ee.array(ee.string()).optional(),gitOriginUrl:ee.string().nullish(),gitCommitSha:ee.string().nullish(),gitCommitShaShort:ee.string().nullish(),gitCommitAuthorName:ee.string().nullish(),cliVersion:ee.string().nullish(),section:ee.nativeEnum(mm).nullish(),status:ee.nativeEnum(nt),trigger:ee.nativeEnum(rn),attempts:ee.number(),runAttempts:ee.array(ee.object({id:ee.string(),status:ee.nativeEnum(nt),startedAt:Xt.or(ee.null()),finishedAt:Xt.or(ee.null())})).optional(),videos:ee.array(ee.string()).optional(),failureReason:ee.nativeEnum(Ne).nullish(),failureDetails:Kp.nullish(),failureRecoveryDetails:nj.nullish(),pipelineId:ee.string().nullish(),resolvedInputs:ee.record(ee.string(),ee.string()).nullish(),quarantined:ee.boolean().nullish().default(!1),quarantinedReason:ee.string().nullish(),localTestId:ee.string().nullish(),testId:ee.string().nullish(),testName:ee.string().nullish(),description:ee.string().nullish(),directory:ee.string().nullish(),test:ee.object({name:ee.string(),id:ee.string()}).nullish().default(null),suiteId:ee.string().nullish(),aiSettings:pi.nullish()}).openapi({ref:"RunMetadata"}),oj={id:!0,status:!0,testName:!0,localTestId:!0,testId:!0,test:{select:{name:!0,id:!0}},finishedAt:!0,failureReason:!0,failureDetails:!0},fm=Za.pick({...oj,test:!0}),dw=Za.omit({failureReason:!0,failureDetails:!0,test:!0}),cy=Za.extend({stepsSnapshot:ee.array(ee.record(ee.unknown())).nullish(),resolvedInputs:ee.record(ee.string(),ee.string()).nullish(),test:ee.object({name:ee.string(),id:ee.string(),description:ee.string().nullish(),baseUrl:ee.string().nullish(),advanced:Qa.nullish()}).nullish()}).merge(iy),pw=t=>t.includes("PASSED")&&t.includes("FAILED");var ij=vu.object({id:vu.string().uuid(),startedAt:Xt.or(vu.null()),finishedAt:Xt.or(vu.null()),status:vu.nativeEnum(nt)}).merge(bu),Lce=ij.array();var hm=(i=>(i.JUNIT="junit",i.ALLURE="allure",i.ALLURE_JSON="allure-json",i.PLAYWRIGHT_JSON="playwright-json",i.BUILDKITE_JSON="buildkite-json",i))(hm||{});import{z as Dt}from"zod";var mw=Dt.object({id:Dt.string(),status:Dt.nativeEnum(nt),trigger:Dt.nativeEnum(rn),createdAt:Xt,startedAt:Xt.nullish(),finishedAt:Xt.nullish(),gitCommitSha:Dt.string().nullish(),gitCommitShaShort:Dt.string().nullish(),gitCommitTimestamp:Xt.nullish(),gitBranchName:Dt.string().nullish(),gitOriginUrl:Dt.string().nullish(),gitCommitMessage:Dt.string().nullish(),gitCommitAuthorName:Dt.string().nullish(),githubRepository:Dt.string().nullish(),gitlabProjectPath:Dt.string().nullish(),pipelineId:Dt.string().nullish(),ciProvider:Dt.string().nullish(),cliVersion:Dt.string().nullish(),labels:Dt.string().array().optional(),localSuiteName:Dt.string().optional(),suite:Dt.object({id:Dt.string(),name:Dt.string()}).nullish(),runs:Dt.object({status:Dt.nativeEnum(nt)}).array()}).openapi({ref:"RunGroup"}),fw=mw.pick({id:!0,createdAt:!0,startedAt:!0,finishedAt:!0,status:!0,trigger:!0,suite:!0,localSuiteName:!0}).extend({runs:fm.array()}),Bce=mw.extend({runs:Za.array()});import{z as ar}from"zod";var aj=ar.object({type:ar.literal("TARGETING"),name:ar.string().optional().describe("Target name to disambiguate for steps with multiple targets"),elementLocationDecisions:XR.array(),pageState:ar.string().optional(),targetSource:ar.nativeEnum(Lo).optional(),targetUpdateTime:ar.string().optional()}),sj=ar.object({type:ar.literal("AI_LOCATION"),matched:ar.boolean(),pageState:ar.string().optional(),ragUsed:ar.boolean().optional(),thoughts:ar.string().optional()}),lj=ar.object({type:ar.literal("ASSERTION"),relevantElementsSerialized:ar.string().array().optional(),pageState:ar.string().optional(),ragUsed:ar.boolean().optional()}),hw=ar.discriminatedUnion("type",[aj,sj,lj]);import{z as Ht}from"zod";var cj=Ht.object({id:Ht.string(),name:Ht.string()}),Kce=cj.merge(Ht.object({createdAt:Xt,createdBy:Ht.string(),schedule:Cl,notification:Rl,environment:Ht.object({name:Ht.string()}).nullish(),beforeTests:Ht.object({id:Ht.string()}).array().nullish(),afterTests:Ht.object({id:Ht.string()}).array().nullish()})),gw=Ht.object({id:Ht.string().uuid(),orgId:Ht.string(),createdAt:Xt,startedAt:Xt.or(Ht.null()),finishedAt:Xt.or(Ht.null()),status:Ht.nativeEnum(nt),trigger:Ht.nativeEnum(rn),suite:Ht.object({id:Ht.string(),name:Ht.string()}).nullish(),runs:Za.array()}),Yce=gw.pick({id:!0,createdAt:!0,startedAt:!0,finishedAt:!0,status:!0,trigger:!0,suite:!0}),Sw=gw.extend({runs:fm.array()});import{z as qr}from"zod";var uy=qr.object({content:qr.string(),ids:qr.string().array(),tokenLength:qr.number()}),uj=qr.object({chunks:uy.array()}),due=qr.object({ids:qr.string().array(),score:qr.number(),tokenLength:qr.number()}),pue=uj.extend({description:qr.string().describe("Input to pass to RAG engine"),tokenLimit:qr.number()}),yw=qr.object({ids:qr.number().array()}),Ew=qr.object({indices:qr.number().array()});var Gt=N.object({disableCache:N.boolean().optional(),useMemory:N.boolean().optional(),clientMode:N.enum(["interactive","runner"]).optional(),loggerTags:N.record(N.string(),N.string()).optional(),langfuseSessionId:N.string().optional(),agentConfigVersion:N.string().optional()}),bue=Gt.extend({chunks:uy.array(),description:N.string().describe("Input to pass to AI"),type:N.union([N.literal("locator"),N.literal("assertion"),N.literal("ai-action")]),softTokenLimit:N.number(),hardTokenLimit:N.number(),callId:N.string().optional()}),dj=N.object({screenshotBase64AfterCommand:N.string(),urlAfterCommand:N.string(),serializedCommand:N.string(),elementInteracted:N.string().optional(),thoughts:N.string().optional()}),Tw=N.object({goal:N.string(),browserState:N.string(),screenshot:N.string(),source:YR.optional().catch(void 0),isTieBreakerCall:N.boolean().optional(),memory:N.discriminatedUnion("type",[lo,N.object({type:N.literal("RESOLVED_TRACES"),traces:N.unknown().array()})]).optional(),firstPassModelResults:em.array().optional()}),bw=N.object({target:N.string().or(N.number()),browserState:N.string().optional(),screenshot:N.string().optional(),boundingBox:N.object({x:N.number(),y:N.number(),height:N.number(),width:N.number()}).optional()}),vw=N.object({goal:N.string(),browserState:N.string(),screenshot:N.string().optional(),returnSchema:N.string().optional()}),Aw=N.object({goal:N.string(),emulatorState:N.string(),screenshot:N.string().optional(),returnSchema:N.string().optional()}),dy=N.union([N.literal("NEGATED_CHECK"),N.literal("CONDITIONAL_CHECK")]),Cw=N.object({goal:N.string(),browserState:N.string(),screenshot:N.string(),url:N.string(),contextChoice:MS.optional(),memory:N.discriminatedUnion("type",[Da,N.object({type:N.literal("RESOLVED_TRACES"),traces:N.unknown().array()})]).optional(),source:dy.optional()}),Rw=N.object({command:ml}),ww=N.object({message:N.string()}),xw=N.object({messagesAndToolCalls:N.array(N.string())}),_w=N.object({messagesAndToolCalls:N.array(N.string()).describe("Chat history to condense for summarization")}),py=N.object({goal:N.string(),browserState:N.string(),startingScreenshot:N.string().optional(),screenshot:N.string(),url:N.string(),history:dj.array(),actionHint:N.string().optional(),lastError:N.string().optional()}),Iw=N.object({results:lm.array(),errorMessage:N.string(),errorStack:N.string().optional()}),Pw=N.object({results:lm.array(),goal:N.string(),errorMessage:N.string()}),Mw=N.object({failedResults:lm.array(),nextStepsSerialized:N.string().array(),currentUrl:N.string(),currentPageState:N.string(),currentScreenshot:N.string(),customInstructions:N.string().optional(),testDescription:N.string().optional()}),vue=N.object({description:N.string(),type:N.union([N.literal("locator"),N.literal("assertion"),N.literal("ai-action")]),excerpt:N.string()}),Ow=N.object({type:N.string(),browserContext:N.string(),currentStep:N.string(),screenshot:N.string()}),Lw=N.object({description:N.string(),browserState:N.string(),screenshot:N.string()}),pj=N.enum(["locator","assertion"]),Aue=N.object({completionType:pj,currentGoal:N.string(),pastGoal:N.string().optional(),currentScreenshot:N.string(),pastScreenshot:N.string(),pastResult:N.union([N.boolean(),N.number()])});import{z as Au}from"zod";var wue=Au.object({goal:Au.string()}),Nw=Au.object({keywords:Au.array(Au.string())});import{z as wl}from"zod";var Cu=(o=>(o.LOCATOR="locator",o.ASSERTION="assertion",o.VISUAL_ASSERTION="visual-assertion",o.TEXT_EXTRACTION="text-extraction",o))(Cu||{}),Iue=wl.nativeEnum(Cu),Pue=new Set(Object.values(Cu));var mj=wl.enum(["v1","v2","v3","v4"]),fj=wl.string().regex(/^v\d+\.\d+$/).describe("pinned sub-version like v3.1"),Mue=wl.union([mj,fj,wl.string().describe("for people with special configurations")]),xl={locator:"v3",assertion:"v3","visual-assertion":"v3","text-extraction":"v3"};var Dw=(a=>(a.ANDROID_LOCATOR="android-locator",a.IOS_LOCATOR="ios-locator",a.ANDROID_ASSERTION="android-assertion",a.IOS_ASSERTION="ios-assertion",a.ANDROID_TEXT_EXTRACTION="android-text-extraction",a.IOS_TEXT_EXTRACTION="ios-text-extraction",a))(Dw||{}),Oue=wl.nativeEnum(Dw);import{z as _e}from"zod";import Ku from"zod";import fr from"zod";import tr from"zod";import{v4 as jpe}from"uuid";import Ij from"zod";import*as U from"zod";var gm=U.discriminatedUnion("type",[U.object({type:U.literal("SCREEN")}),U.object({type:U.literal("OPEN_APP")}),U.object({type:U.literal("OPEN_WEBVIEW")})]),mi=U.object({type:U.literal("description"),description:U.string()}),my=U.object({type:U.literal("CUSTOM_COORDINATES"),startX:U.number().describe("Starting X coordinate in pixels"),startY:U.number().describe("Starting Y coordinate in pixels"),deltaPixels:U.number().describe("Number of pixels to scroll in the specified direction")}),Sm=U.discriminatedUnion("type",[...gm.options,U.object({type:U.literal("CUSTOM"),target:mi}),my]);var hj=U.object({type:U.literal("coordinates"),xPercent:U.number(),yPercent:U.number()}),_l=U.discriminatedUnion("type",[mi,hj]);var fy=U.object({requiredText:U.string().optional(),requiredAttributes:U.record(U.string(),U.string()).optional(),requiredBounds:U.boolean().optional(),position:U.object({x1:U.number(),y1:U.number(),x2:U.number(),y2:U.number(),tolerance:U.nativeEnum(en),preciseTolerance:U.boolean().optional()}).optional(),shape:U.object({width:U.number(),height:U.number(),tolerance:U.nativeEnum(en),preciseTolerance:U.boolean().optional()}).optional()}),kw=U.object({xPath:U.string(),requirements:fy.optional()}),gj=U.object({type:U.literal("CUSTOM"),target:mi,cache:U.lazy(()=>Fw).optional()}),Sj=U.object({pixelDelta:U.number().describe("Number of pixels to scroll in the specified direction"),scrollableElement:U.union([gm,gj,my]),direction:U.enum(["up","down"])}),Fw=U.object({type:U.literal("NATIVE"),bounds:U.number().array().optional(),resolvedDescription:U.string().optional(),xPath:U.string().optional(),elementOnlySerializedXml:U.string().optional(),scrollDetails:Sj.optional(),requirements:fy.optional(),requiredRelatedElements:kw.array().optional(),memory:lo.optional()}),yj=U.object({type:U.literal("WEBVIEW"),resolvedDescription:U.string().optional(),xPath:U.string().optional(),browserCache:li.optional(),memory:lo.optional()}),ym=U.union([Fw,yj]);var Ej=U.object({left:U.number(),top:U.number(),right:U.number(),bottom:U.number()}),kue=U.object({newViewportBounds:Ej}),Tj=U.object({type:U.literal("CUSTOM"),target:mi,cache:U.lazy(()=>Bw).optional()}),Uw=U.object({pixelDelta:U.number().describe("Number of pixels to scroll in the specified direction"),scrollableElement:U.union([gm,Tj,my]),direction:U.enum(["up","down"])}),Bw=U.object({type:U.literal("NATIVE"),bounds:U.tuple([U.number(),U.number(),U.number(),U.number()]).optional(),resolvedDescription:U.string().optional(),xPath:U.string().optional(),elementOnlySerializedXml:U.string().optional(),scrollDetails:Uw.optional(),requirements:fy.optional(),requiredRelatedElements:kw.array().optional(),memory:lo.optional()}),bj=U.object({type:U.literal("WEBVIEW"),resolvedDescription:U.string().optional(),xPath:U.string().optional(),scrollDetails:Uw.optional(),browserCache:li.optional(),memory:lo.optional()}),Em=U.discriminatedUnion("type",[Bw,bj]);import hy from"zod";import Xi from"zod";var Ge=(R=>(R.AI_CHECK="AI_CHECK",R.AI_EXTRACT="AI_EXTRACT",R.TAP="TAP",R.TYPE="TYPE",R.PRESS="PRESS",R.PRESS_KEYBOARD="PRESS_KEYBOARD",R.OPEN_APP="OPEN_APP",R.KILL_APP="KILL_APP",R.OPEN_NOTIFICATION_DRAWER="OPEN_NOTIFICATION_DRAWER",R.SWIPE="SWIPE",R.SCROLL_TO="SCROLL_TO",R.SCREEN_CHECK="SCREEN_CHECK",R.ELEMENT_CHECK="ELEMENT_CHECK",R.DRAG_AND_DROP="DRAG_AND_DROP",R.JAVASCRIPT="JAVASCRIPT",R.REQUEST="REQUEST",R.WAIT="WAIT",R.ADD_FILE="ADD_FILE",R.INSTALL_APP="INSTALL_APP",R.UNINSTALL_APP="UNINSTALL_APP",R.TOGGLE_SETTINGS="TOGGLE_SETTINGS",R.ROTATE_ORIENTATION="ROTATE_ORIENTATION",R.ADB="ADB",R.STATE="STATE",R))(Ge||{}),ge=Xi.object({id:Xi.string().uuid(),disableCache:Xi.boolean().optional()}),Il=Xi.object({updatedAt:Xi.coerce.date().optional(),updatedAtLoggerTags:Xi.record(Xi.string(),Xi.string()).optional()}),Un=Il.extend({target:ym}),Tm=Il.extend({fromTarget:ym,toTarget:ym}),yo=Il.extend({target:Em}),zw=Il.extend({fromTarget:Em,toTarget:Em});var gy=ge.extend({type:hy.literal("ADB"),command:hy.string(),jsonArgs:hy.string().optional()});import Hw from"zod";var vj=Hw.string().trim(),Sy=ge.extend({type:Hw.literal("INSTALL_APP"),uri:vj});import Aj from"zod";var yy=ge.extend({type:Aj.literal("OPEN_NOTIFICATION_DRAWER")});import Gw from"zod";var Ru=(o=>(o.AIRPLANE_MODE="AIRPLANE_MODE",o.DATA="DATA",o.WIFI="WIFI",o.LOCATION="LOCATION",o))(Ru||{}),Ey=ge.extend({type:Gw.literal("TOGGLE_SETTINGS"),settingsType:Gw.nativeEnum(Ru)});import jw from"zod";var Ty=ge.extend({type:jw.literal("UNINSTALL_APP"),packageName:jw.string()});import $w from"zod";import by from"zod";var vy=ge.extend({type:by.literal("ADD_FILE"),file:by.string(),storageLocation:by.string()});import Ay from"zod";var Pl=ge.extend({type:Ay.literal("AI_CHECK"),assertion:Ay.string(),timeoutSecs:Ay.number().optional(),cache:Il.extend({memory:Da.optional()}).optional()});import Cy from"zod";var Ry=ge.extend({type:Cy.literal("AI_EXTRACT"),goal:Cy.string(),schema:Cy.string().optional()});import wy from"zod";var xy=ge.extend({type:wy.literal("JAVASCRIPT"),code:wy.string(),timeout:wy.number().int().max(60).optional().describe("Max seconds for the code to complete")});import Cj from"zod";var _y=ge.extend({type:Cj.literal("KILL_APP")});import wu from"zod";var es=(r=>(r.HOME="HOME",r.POWER="POWER",r))(es||{}),Ml=(a=>(a.BACK="BACK",a.APP_SWITCHER="APP_SWITCHER",a.SEARCH="SEARCH",a.VOLUME_UP="VOLUME_UP",a.VOLUME_DOWN="VOLUME_DOWN",a.VOLUME_MUTE="VOLUME_MUTE",a))(Ml||{}),xu=ge.extend({type:wu.literal("PRESS"),key:wu.nativeEnum(es),longPress:wu.boolean().optional()}),Iy=xu.extend({key:wu.nativeEnum(Ml).or(wu.nativeEnum(es))}),Py=xu;import Rj from"zod";var My=ge.extend({type:Rj.literal("REQUEST")}).merge(ka);import Vw from"zod";var _u=(r=>(r.PORTRAIT="PORTRAIT",r.LANDSCAPE="LANDSCAPE",r))(_u||{}),Oy=ge.extend({type:Vw.literal("ROTATE_ORIENTATION"),orientation:Vw.nativeEnum(_u)});import Ol from"zod";var wj=Ol.object({type:Ol.literal("CONTENT"),negated:Ol.boolean().optional(),value:Ol.string()}),Ly=ge.extend({type:Ol.literal("SCREEN_CHECK"),assertion:wj,timeout:Ol.number().int().min(0).max(Ba).optional().describe("max seconds to wait for the assertion to be true")});import xj from"zod";var Ny=ge.extend({type:xj.literal("STATE")});import Ww from"zod";var Dy=ge.extend({type:Ww.literal("WAIT"),timeoutSecs:Ww.number()});var Iu=$w.discriminatedUnion("type",[Ny,Pl,Ry,xy,Dy,My,Oy,Ly,vy,_y]),_j=$w.discriminatedUnion("type",[...Iu.options,xu]);import ky from"zod";var qw=ge.extend({type:ky.literal("DRAG_AND_DROP"),fromTarget:mi,toTarget:mi,hoverDuration:ky.number().optional(),dragDuration:ky.number().optional()}),Pu=qw.extend({cache:Tm.optional()}),Mu=qw.extend({cache:zw.optional()});import Kw from"zod";var Yw=ge.extend({type:Kw.literal("ELEMENT_CHECK"),target:_l,assertion:Fp,timeout:Kw.number().int().min(0).max(Ba).optional().describe("max seconds to wait for the assertion to be true")}),Ou=Yw.extend({cache:Un.optional()}),Lu=Yw.extend({cache:yo.optional()});import Nu from"zod";var ts=(r=>(r.ENTER="ENTER",r.BACKSPACE="BACKSPACE",r))(ts||{}),bm=(e=>(e.CLOSE_KEYBOARD="CLOSE_KEYBOARD",e))(bm||{}),Fy=ge.extend({type:Nu.literal("PRESS_KEYBOARD"),key:Nu.nativeEnum(ts)}),Uy=ge.extend({type:Nu.literal("PRESS_KEYBOARD"),key:Nu.nativeEnum(bm).or(Nu.nativeEnum(ts))});import rs from"zod";var By=ge.extend({type:rs.literal("OPEN_APP"),packageName:rs.string(),activityName:rs.string().optional(),intentExtras:rs.string().optional()}),zy=ge.extend({type:rs.literal("OPEN_APP"),packageName:rs.string(),intentExtras:rs.string().optional()});import vm from"zod";var Xw=ge.extend({type:vm.literal("SCROLL_TO"),target:mi,direction:vm.enum(["down","up"]),scrollableElement:Sm,scrollStepPercent:vm.number().min(.1).max(1).optional().describe("How much of the container height to scroll at each step (0.1 to 1.0). Default is 0.8 (80%)."),maxScrollAttempts:vm.number().int().min(1).max(50).optional().describe("Maximum number of scroll attempts before giving up. Default is 5.")}),Du=Xw.extend({cache:Un.optional()}),ku=Xw.extend({cache:yo.optional()});import Am from"zod";var Jw=ge.extend({type:Am.literal("SWIPE"),direction:Am.enum(["up","down","left","right"]),scrollableElement:Sm,viewportPercent:Am.number().optional(),durationMs:Am.number().optional()}),Fu=Jw.extend({cache:Un.optional()}),Uu=Jw.extend({cache:yo.optional()});import Fo from"zod";var Qw=ge.extend({type:Fo.literal("TAP"),target:_l,longPress:Fo.boolean().optional(),longPressDurationMs:Fo.number().optional(),iterations:Fo.number().optional(),tapDelayMs:Fo.number().optional(),relativePosition:Fo.object({x:Fo.number(),y:Fo.number()}).optional(),doubleTap:Fo.boolean().optional(),doubleTapDelayMs:Fo.number().optional()}),Bu=Qw.extend({cache:Un.optional()}),zu=Qw.extend({cache:yo.optional()});import Hu from"zod";var Zw=ge.extend({type:Hu.literal("TYPE"),target:_l.optional(),keyPressDelayMs:Hu.number().optional(),text:Hu.string(),clearContent:Hu.boolean().optional(),forceClearContent:Hu.boolean().optional()});var Gu=Zw.extend({cache:Un.optional()}),ju=Zw.extend({cache:yo.optional()});var Hy=Ij.discriminatedUnion("type",[...Iu.options,Bu,Gu,Iy,Uy,Ty,Sy,gy,Pu,yy,Du,Fu,Ey,Ou,By]);import{v4 as _me}from"uuid";import Pj from"zod";var Gy=Pj.discriminatedUnion("type",[...Iu.options,zu,ju,Py,Fy,zy,Uu,Mu,ku,Lu]);var Sn=(n=>(n.PRESET="MOBILE_PRESET_STEP",n.MODULE="MOBILE_MODULE_STEP",n.AI_ACTION="MOBILE_AI_ACTION_STEP",n))(Sn||{}),Ll=tr.object({id:tr.string().uuid(),envKey:tr.string().optional(),skipped:tr.boolean().optional(),retries:tr.number().optional()}),rx=Ll.extend({type:tr.literal("MOBILE_PRESET_STEP"),keyPressDelayMs:tr.number().optional()}),Vu=rx.extend({command:Hy}),jy=rx.extend({command:Gy}),Nl=tr.object({moduleId:tr.string(),inputs:tr.record(tr.string(),tr.string()).optional()}),Wu=Ll.merge(Nl.extend({type:tr.literal("MOBILE_MODULE_STEP")})),jfe=Nl.extend({steps:tr.lazy(()=>$u.array())}),Vfe=Nl.extend({steps:tr.lazy(()=>Vy.array())}),ns=Ll.extend({type:tr.literal("MOBILE_AI_ACTION_STEP"),text:tr.string()}),$u=tr.discriminatedUnion("type",[Vu,Wu,ns]),Vy=tr.discriminatedUnion("type",[jy,Wu,ns]);var qu=fr.object({message:fr.string().optional(),startTime:fr.number(),endTime:fr.number(),status:fr.nativeEnum(at),trace:fr.unknown(),beforeSnapshot:fr.string().optional(),afterSnapshot:fr.string().optional(),data:fr.unknown().optional().describe("output data from the step"),aiSuggested:fr.boolean().optional()}),Oj=qu.merge(Vu).extend({previousAttempts:fr.lazy(()=>Eo.array()).optional()}),Lj=qu.merge(Wu).extend({steps:fr.lazy(()=>Eo.array()),name:fr.string().optional(),previousAttempts:fr.lazy(()=>Eo.array()).optional()}),Nj=qu.merge(ns).extend({steps:fr.lazy(()=>Eo.array()),previousAttempts:fr.lazy(()=>Eo.array()).optional()}),Eo=fr.discriminatedUnion("type",[Oj,Lj,Nj]);var Dj=qu.extend({index:Ku.number().optional(),userFacingStepReference:Ku.string().optional(),description:Ku.string()}),nx=Dj.extend({beforeScreenshot:Ku.string().optional(),afterScreenshot:Ku.string().optional()});var ox=_e.object({attributesRequired:_e.array(_e.string()).optional(),textRequired:_e.boolean().optional(),boundsRequired:_e.boolean().optional(),positionSpecificity:_e.nativeEnum(en).optional(),shapeSpecificity:_e.nativeEnum(en).optional()}),kj=_e.object({thoughts:_e.string(),id:_e.number(),updatedMemory:eu.optional(),inWebview:_e.boolean().optional(),requirements:ox.optional(),additionalElements:_e.object({id:_e.number(),requirements:ox}).array().optional()}),ix=_e.object({description:_e.string(),screenXml:_e.string(),screenshot:_e.string(),memory:_e.discriminatedUnion("type",[lo,_e.object({type:_e.literal("RESOLVED_TRACES"),traces:_e.unknown().array()})]).optional()}),ax=_e.object({assertion:_e.string(),screenXml:_e.string(),screenshot:_e.string(),memory:_e.discriminatedUnion("type",[Da,_e.object({type:_e.literal("RESOLVED_TRACES"),traces:_e.unknown().array()})]).optional()}),Fj=_e.object({thoughts:_e.string(),result:_e.boolean(),relevantElements:_e.array(_e.number()).optional(),updatedMemory:ru.optional()}),sx=_e.object({failedResults:nx.array(),nextStepsSerialized:_e.string().array(),currentScreenXml:_e.string(),currentScreenshot:_e.string(),customInstructions:_e.string().optional(),testDescription:_e.string()}),lx=(n=>(n.LEGITIMATE="LEGITIMATE",n.RECOVERABLE="RECOVERABLE",n.INELIGIBLE="INELIGIBLE",n))(lx||{}),Uj=_e.object({thoughts:_e.string(),scenario:_e.nativeEnum(lx),instructions:_e.string().nullish()});var cx=t=>!(!t.org_id||!t.user_id||!t.platform);import{z as os}from"zod";var ux=os.object({id:os.string().uuid(),skipped:os.boolean().optional(),envKey:os.string().optional().describe("key in the environment to save the result of this step to")}),Wy=ux.merge(ka).extend({type:os.literal("REQUEST")}),$y=ux.merge(Up).extend({type:os.literal("JAVASCRIPT")}),qy=os.discriminatedUnion("type",[$y,Wy]);import{z as Bn}from"zod";var dx=Bn.object({id:Bn.string(),name:ui,description:Bn.string().optional().nullish(),baseUrl:Jp.nullish(),schemaVersion:Bn.string(),advanced:Bn.unknown().optional(),retries:Bn.number(),envs:Bn.array(pm).nullish(),parameters:dm.nullish()}),Bj=Bn.object({createdAt:Bn.coerce.date(),updatedAt:Bn.coerce.date(),schedule:Cl.nullish(),notification:Rl.nullish(),createdBy:Bn.string(),organizationId:Bn.string()}),zj=dx.merge(Bj),xhe=zj.extend({steps:qy.array()}),_he=dx.extend({steps:qy.array()});import{z as nn}from"zod";var px=nn.object({startedAt:nn.coerce.date(),finishedAt:nn.coerce.date(),status:nn.nativeEnum(at),message:nn.string().optional(),data:nn.unknown().optional()}),Hj=px.merge($y).extend({type:nn.literal("JAVASCRIPT")}),Gj=px.merge(Wy).extend({type:nn.literal("REQUEST")}),jj=nn.discriminatedUnion("type",[Hj,Gj]),mx=nn.object({startedAt:nn.coerce.date(),finishedAt:nn.coerce.date().nullish(),status:nn.nativeEnum(nt),results:jj.array(),failureReason:nn.string().nullish(),failureDetails:Kp.nullish()});import{z as on}from"zod";var Vj=on.object({id:on.string(),organizationId:on.string(),createdAt:on.coerce.date(),updatedAt:on.coerce.date(),createdBy:on.string(),scheduledAt:on.coerce.date().nullish(),startedAt:on.coerce.date().nullish(),finishedAt:on.coerce.date().nullish(),status:on.nativeEnum(nt),trigger:on.nativeEnum(rn),results:mx.array().nullish(),apiTestName:on.string().nullish(),apiTestPath:on.string().nullish(),apiTestId:on.string().nullish()}),Uhe=Vj.pick({status:!0,startedAt:!0,finishedAt:!0});var Yu=(o=>(o.TestRun="test-run",o.MobileTestRun="mobile-test-run",o.CreditsUsed="credits-used",o.CreditsUsedV2="credits-used-v2",o))(Yu||{}),fx=3;function Wj(t){return t==="MODULE"||t==="CONDITIONAL"||t==="SECTION"||t==="RESOLVED_MODULE"}function Ky(t){if(!Wj(t))switch(t){case"PRESET_ACTION":return 0;case"AI_ACTION":return 3;case"AI_ACTION_DYNAMIC":return 5;default:(r=>{throw"If Typescript complains about the line below, you missed a case or break in the switch above"})(t)}}function Yy(t){switch(t.type){case"AI_EXTRACT":case"AI_ASSERTION":return fx;case"CAPTCHA":return 3;case"CLICK":case"TYPE":case"SELECT_OPTION":case"HOVER":case"ELEMENT_CHECK":case"FOCUS":case"BLUR":case"SCROLL_DOWN":case"SCROLL_LEFT":case"SCROLL_RIGHT":case"SCROLL_UP":case"MOUSE_DRAG":return t.useSelector||!t.target||t.target.type!=="description"?0:1;case"DRAG":return t.useSelector?0:1;case"VISUAL_DIFF":case"TAB":case"JAVASCRIPT":case"NAVIGATE":case"WAIT":case"SUCCESS":case"AUTH_LOAD":case"AUTH_SAVE":case"COOKIE":case"DIALOG":case"FILE_UPLOAD":case"GO_BACK":case"GO_FORWARD":case"LOCAL_STORAGE":case"NEW_TAB":case"PAGE_CHECK":case"PRESS":case"KEY_DOWN":case"KEY_UP":case"COPY":case"PASTE":case"REFRESH":case"REQUEST":case"GRAPHQL_REQUEST":case"WAIT_FOR_URL":case"REGISTER_REQUEST_LISTENER":case"AWAIT_LISTENER":case"RECORD_REQUESTS":case"GET_RECORDED_REQUESTS":case"SET_HEADER":case"MOCK_ROUTE":case"REMOVE_ROUTE_MOCK":case"OFFLINE_MODE":return 0;default:(r=>{throw"If Typescript complains about the line below, you missed a case or break in the switch above"})(t)}}var Dl=class{trackStepExecution(){}async flush(){}};import{parseString as $j,splitCookiesString as qj}from"set-cookie-parser";import{z as Ze}from"zod";var Xy=Ze.object({name:Ze.string(),value:Ze.string(),url:Ze.string().optional(),domain:Ze.string().optional(),path:Ze.string().optional(),expires:Ze.number().default(Date.now()/1e3+60*60*24*365),httpOnly:Ze.boolean().optional(),secure:Ze.boolean().default(!0),sameSite:Ze.union([Ze.literal("Strict"),Ze.literal("Lax"),Ze.literal("None")]).default("None")});function Rm(t,e){let r=[],n=qj(t);for(let o of n){let i=$j(o,{decodeValues:!1});if(!i.name)throw new Error("Name missing from cookie");if(!i.value)continue;let a;if(i.sameSite){let u=i.sameSite.trim().toLowerCase();if(u==="strict")a="Strict";else if(u==="lax")a="Lax";else if(u==="none")a="None";else throw new Error(`Invalid sameSite setting in cookie: ${u}`)}i.httpOnly===void 0&&(i.httpOnly=!1),!i.path&&i.domain&&(i.path="/"),!i.domain&&e&&(i.domain=e);let s=Xy.parse({...i,expires:i.expires?i.expires.getTime()/1e3:void 0,sameSite:a});r.push(s);let c=[s.name,...Object.keys(s)].map(u=>u.toLowerCase()),l=o.match(/\b(\S+)=([^;]*)/g);if(l)for(let u of l){let[d,p]=u.split("=");if(!d||!p)throw new Error(`Invalid key-value pair in cookie: ${u}`);c.includes(d.toLowerCase())||r.push({...s,name:d,value:p})}}return r}var Kj=Ze.object({origin:Ze.string(),localStorage:Ze.array(Ze.object({name:Ze.string(),value:Ze.string()})),sessionStorage:Ze.array(Ze.object({name:Ze.string(),value:Ze.string()})).optional()}),Yj=Ze.object({entries:Ze.record(Ze.string(),Ze.array(Ze.tuple([Ze.unknown(),Ze.unknown()]))),version:Ze.number().optional()}),wm=Ze.object({cookies:Xy.array().optional(),origins:Kj.array().optional(),idb:Ze.record(Ze.string(),Yj).optional().describe("key is db name")});function hx(t,e){let r=[];return t.cloneSync()?.serializeSync()?.cookies.forEach(n=>{let o=Xy.safeParse({name:n.key,...n});if(!o.success)return;let i=o.data;!i.domain&&!i.url&&(i.domain=e),r.push(i)}),r}import{v4 as ige}from"uuid";import Z from"zod";var Xj=["SCREEN","OPEN_APP","OPEN_WEBVIEW","CUSTOM","CUSTOM_COORDINATES"],gx=Z.object({type:Z.enum(Xj).describe("Where to interact. SCREEN = entire device (use for system surfaces like the notification bar or quick settings), OPEN_APP = current foreground app, OPEN_WEBVIEW = active webview (only if a webview is present and there is high confidence that the element is inside it), CUSTOM = explicitly describe the container if and only if NONE of the above fit, CUSTOM_COORDINATES = use explicit pixel coordinates for the scroll start position and distance (fallback if other containers don't work)."),description:Z.string().or(Z.null()).describe("Description of the container to interact with. Only used if the container type is CUSTOM, else set to null."),startX:Z.number().or(Z.null()).describe("Starting X coordinate in pixels. Only used if the container type is CUSTOM_COORDINATES, else set to null."),startY:Z.number().or(Z.null()).describe("Starting Y coordinate in pixels. Only used if the container type is CUSTOM_COORDINATES, else set to null."),deltaPixels:Z.number().or(Z.null()).describe("Number of pixels to scroll in the specified direction. Only used if the container type is CUSTOM_COORDINATES, else set to null.")}),Jj=Z.object({xPercent:Z.number().min(0).max(1).describe("X coordinate as a fraction of the viewport width (0 = left edge, 1 = right edge)."),yPercent:Z.number().min(0).max(1).describe("Y coordinate as a fraction of the viewport height (0 = top edge, 1 = bottom edge).")}),Qj=Z.string().or(Jj).describe("Either a string description of an actual element in the page XML to target, or an object with xPercent/yPercent (0-1) for coordinate-based targeting when no suitable element exists. Prefer element descriptions when possible."),Sx=Z.object({type:Z.literal("TAP"),target:Qj,longPress:Z.boolean().describe("Whether to hold the tap down before releasing. Useful for triggering context menus."),iterations:Z.null().or(Z.number()).describe("Number of times to tap the element, useful for selecting text, selecting a row, or opening a menu. If null, tap once."),relativePosition:Z.null().or(Z.object({x:Z.number(),y:Z.number()})).describe("Specific position to tap within the bounding box of the element, specified in pixels. E.g. 0,0 is the top left corner. Only applicable when target is a string description.")}).describe("Tap on an element on the screen, or tap at specific coordinates."),Zj=Z.object({type:Z.literal("PRESS"),key:Z.nativeEnum(Ml)}).describe("Press a button on the device. Some buttons are physical (volume) while others are virtual (Back/Home/App Switcher)."),yx=Z.object({type:Z.literal("AI_CHECK"),assertion:Z.string().describe("A natural language assertion to validate. On each attempt, Momentic's AI agents will evaluate the assertion by analyzing the current emulator XML and screenshot. Thus, the assertion must be verifiable based on a single point in time. The assertion will be automatically retried until it is true or the timeout is reached."),timeoutSecs:Z.number().describe("Maximum number of seconds to wait for the assertion to be true.")}).describe("Use AI to verify a statement about the state of the emulator. Will retry up until the timeout, so this can be used as a flexible wait that supports visual, numerical, and logical reasoning."),Ex=Z.object({type:Z.literal("WAIT"),timeoutSecs:Z.number().describe("Number of seconds to wait.")}).describe("Wait for a fixed number of seconds. Use this in these scenarios: 1. Short waits that are expected to be less than 5 seconds almost all the time, which shouldn't warrant an AI call (e.g. an app needs to finish loading, or some contents are suspending); 2. Waits with an obvious deterministic duration (e.g. a 60-second countdown is on the page). For other scenarios, prefer AI_CHECK."),mge=Z.object({type:Z.literal("AI_EXTRACT"),goal:Z.string().describe("Natural language description of what to extract from the current emulator state."),schema:Z.string().or(Z.null()).describe("Optional JSON schema string for the expected output shape. Use null to omit.")}).describe("Use AI to extract structured data from the current emulator state."),Tx=Z.object({type:Z.literal("TYPE"),text:Z.string().describe("Exact type to text, which will be passed to appium's driver.keys() method."),keyPressDelayMs:Z.number().or(Z.null()).describe("Milliseconds to wait between each key press. Useful for triggering auto-complete and other event listeners."),clearContent:Z.boolean().or(Z.null()).describe("Clear the content of the input before typing. Do not set to true if the input is already empty.")}),bx=Z.object({type:Z.literal("SWIPE"),direction:Z.enum(["up","down","left","right"]).describe("Direction to swipe. Important: swiping up will scroll down, and vice versa."),container:gx,viewportPercent:Z.number().min(.1).max(1).or(Z.null()).describe("How much of the container height/width to swipe each time as a decimal (0.1 - 1). Set to null for default (0.8)."),durationMs:Z.number().int().positive().or(Z.null()).describe("Optional swipe duration in milliseconds. Set to null for default.")}).describe("Swipe a single time in a specified direction within a container (screen/app/webview/custom container/custom coordinates)."),vx=Z.object({type:Z.literal("SCROLL_TO"),targetDescription:Z.string().describe("Description of the element to scroll to inside the container."),direction:Z.enum(["down","up"]).describe("Direction to search for the target. Important: this is direction the target is in relative to the current position. E.g. 'down' means the desired element is below the current position."),container:gx,scrollStepPercent:Z.number().min(.1).max(1).or(Z.null()).describe("How much of the container height to scroll at each step (0.1 - 1). Set to null for default (0.8)."),maxScrollAttempts:Z.number().int().min(1).max(50).or(Z.null()).describe("Maximum number of scroll attempts before giving up. Set to null for default (5).")}).describe("Scroll within a container until the described target is visible or we can't scroll anymore. There is no need to repeat the same scroll to command in the same direction multiple times in a row. If a scroll fails, we do not restore the position automatically."),fge=Z.discriminatedUnion("type",[Sx,Zj,yx,Ex,Tx,bx,vx]),eV=Z.object({type:Z.literal("PRESS"),key:Z.nativeEnum(es)}).describe("Press a physical button on the device. Only HOME and POWER are available on iOS."),tV=Z.object({type:Z.literal("PRESS_KEYBOARD"),key:Z.nativeEnum(ts)}).describe("Press a key on the keyboard. Available keys: ENTER, BACKSPACE."),hge=Z.discriminatedUnion("type",[Sx,eV,tV,yx,Ex,Tx,bx,vx]);var gge={TAP:"Tap on an element on the screen.",TYPE:"Type the specified text into an element.",PRESS:"Press a physical button on the device.",PRESS_KEYBOARD:"Press a button on the keyboard.",SWIPE:"Swipe on the screen.",SCREEN_CHECK:"Assert on the screen content using pre-built conditions.",SCROLL_TO:"Scroll until an element is visible.",DRAG_AND_DROP:"Drag an element onto another element in the same context.",ELEMENT_CHECK:"Assert on an element's state using pre-built conditions, including content, visibility, attribute value checks.",OPEN_APP:"Open an app on the device.",KILL_APP:"Kill an app on the device.",OPEN_NOTIFICATION_DRAWER:"Open the notification drawer.",JAVASCRIPT:"Execute JavaScript code in the emulator.",REQUEST:"Make an HTTP request to a URL.",WAIT:"Wait for a fixed number of seconds. Prefer this for short, deterministic waits; use AI_CHECK for longer or undefined waits.",ADD_FILE:"Add a file to the device's disk.",INSTALL_APP:"Install an app on the device.",UNINSTALL_APP:"Uninstall an app on the device.",TOGGLE_SETTINGS:"Toggle device settings.",ADB:"Execute an ADB command on the device.",STATE:"Capture and return emulator state details.",ROTATE_ORIENTATION:"Rotate the device orientation.",AI_CHECK:"Use AI to verify a statement about the current state of the emulator or wait until a statement is true.",AI_EXTRACT:"Extract data from the emulator state and optionally store it in an environment variable."};var Sge=["TAP","TYPE","PRESS","PRESS_KEYBOARD","SWIPE","SCREEN_CHECK","SCROLL_TO","DRAG_AND_DROP","KILL_APP","OPEN_NOTIFICATION_DRAWER","WAIT","TOGGLE_SETTINGS","ROTATE_ORIENTATION","AI_CHECK"];import Ax from"zod";var an={type:!0,cache:!0},Cx=[Pl.pick(an),Ou.pick(an),Bu.pick(an),Gu.pick(an),Fu.pick(an),Du.pick(an),Pu.pick(an)],kl=Ax.discriminatedUnion("type",Cx),Rx=[Pl.pick(an),Lu.pick(an),zu.pick(an),ju.pick(an),Uu.pick(an),Mu.pick(an),ku.pick(an)],wx=Ax.discriminatedUnion("type",Rx);var Nge=Object.values(Ge).filter(t=>Cx.some(e=>e.shape.type.safeParse(t).success));var Dge=Object.values(Ge).filter(t=>Rx.some(e=>e.shape.type.safeParse(t).success));function xm(t){switch(t){case"ANDROID":return kl;case"IOS":return wx;default:throw new Error(`Unsupported platform: ${t}`)}}var kge=fl(kl),Fge=fl(wx);var Uge=za(kl);import xx from"zod";var Xu=(n=>(n.US_WEST_1="us-west1",n.EU_NORTH_1="eu-north1",n.AS_SOUTH_1="as-south1",n))(Xu||{}),_x=(e=>(e.LOCAL="local",e))(_x||{}),Ix=xx.nativeEnum(Xu).or(xx.nativeEnum(_x)),Ju=(r=>(r.ANDROID_14="14",r.ANDROID_15="15",r))(Ju||{});var Jy=(e=>(e.IOS_26="26",e))(Jy||{});import{cloneDeep as jge}from"lodash-es";import Wge from"truncate-json";import Jt from"zod";import{z as To}from"zod";import{z as xt}from"zod";var Mr=xt.object({id:xt.string(),name:ui,baseUrl:Jp,description:xt.string().optional().nullish(),schemaVersion:xt.string(),advanced:Qa,retries:xt.number().optional().nullish(),envs:xt.array(pm).nullish(),parameters:dm.nullish(),disabled:xt.boolean().optional(),labels:xt.array(xt.string()).optional().catch([])}),Qge=xt.enum(["INHERIT","ENABLED","DISABLED"]);var rV=Qa.extend({failureRecovery:xt.boolean().or(xt.string()).optional().transform(t=>typeof t=="string"?t:t===void 0?"INHERIT":t?"ENABLED":"DISABLED"),useMemory:xt.boolean().or(xt.string()).optional().transform(t=>typeof t=="string"?t:t===void 0?"INHERIT":t?"ENABLED":"DISABLED")});var Zge=Mr.pick({name:!0,description:!0,baseUrl:!0,retries:!0,disabled:!0,parameters:!0}).extend({advanced:rV}),eSe=Mr.pick({name:!0,description:!0,baseUrl:!0,retries:!0,disabled:!0,advanced:!0,parameters:!0}),nV=xt.object({labels:xt.array(xt.string()).optional(),outputs:cw.nullish()}),zn=Mr.merge(nV),oV=xt.object({createdAt:xt.coerce.date(),updatedAt:xt.coerce.date(),updatedBy:xt.string().nullable(),schedule:Cl,notification:Rl,createdBy:xt.string(),organizationId:xt.string(),folderId:xt.string().nullable().optional()}),iV=Mr.merge(oV),tSe=iV.merge(Wi),_m=Mr.merge(Wi),rSe=Mr.merge(Va);var aV="test",sV="module",lV="mobile-test",cV="mobile-module";var ye=(o=>(o.TEST=`momentic/${aV}`,o.MODULE=`momentic/${sV}`,o.MOBILE_TEST=`momentic/${lV}`,o.MOBILE_MODULE=`momentic/${cV}`,o))(ye||{}),cSe=Mr.merge(Va),Qy=tn.extend({steps:To.array(To.record(To.string(),To.unknown())),schemaVersion:To.string()}),uSe=Qy.extend({fileType:To.literal(ye.MODULE)}),dSe=To.object({test:To.string().describe("YAML for the test, including metadata and steps"),modules:To.record(To.string(),To.string()).describe("Map of module name to YAML for the module")});function Im(t){if(t===void 0)return"__undefined__";if(t===null)return null;if(typeof t!="object")return t;if(Array.isArray(t))return t.map(Im);let e={};for(let[r,n]of Object.entries(t))e[r]=Im(n);return e}var Qu=Jt.object({parameterNames:Jt.string().array(),defaultParameters:Jt.record(Jt.string(),Jt.string()).optional(),parameterEnums:Jt.record(Jt.string(),Jt.string().array()).optional()}),uV=Jt.object({moduleId:Jt.string().uuid(),name:Jt.string(),description:Jt.string().nullish(),parameters:Qu.optional(),enabled:Jt.boolean().nullish(),schemaVersion:Jt.string()}),Pm=uV.omit({name:!0}),Mx=Pm.extend({steps:Jt.array(Jt.record(Jt.string(),Jt.unknown()))}),dV=Jt.object({fileType:Jt.literal(ye.MOBILE_MODULE)}).merge(Mx);import Oe from"zod";import*as Fl from"zod";var ESe=Fl.custom().refine(t=>t&&t.length>0).refine(t=>t&&t[0]instanceof File,{message:"Please upload a valid file."}),Zy=Fl.preprocess(t=>{if(typeof t!="string")return t;let e=t.trim();return e.length===0?void 0:e},Fl.string().optional());import fi from"zod";var hi=(e=>(e.MODULE="RESOLVED_MOBILE_MODULE",e))(hi||{}),Ox=fi.object({description:fi.string().optional(),name:fi.string().describe("name of the module"),parameters:Qu.optional()}),eE=Nl.merge(Ox).extend({steps:fi.lazy(()=>is.array())}),pV=Nl.merge(Ox).extend({steps:fi.lazy(()=>Zu.array())}),mV=Ll.merge(eE).extend({type:fi.literal("RESOLVED_MOBILE_MODULE")}),fV=Ll.merge(pV).extend({type:fi.literal("RESOLVED_MOBILE_MODULE")}),is=fi.discriminatedUnion("type",[mV,Vu,ns]),Zu=fi.discriminatedUnion("type",[fV,jy,ns]);function Lx(t){return Object.values(hi).includes(t)||Object.values(Sn).includes(t)}var hV=Oe.object({disableMomenticAccessibilityTree:Oe.boolean().optional(),autoGrantPermissions:Oe.boolean().optional(),disableXmlSnapshots:Oe.boolean().optional().describe("Skip collecting XML snapshots during test runs. This can speed up test runs, but will cause the run viewer to show less information."),browserSettings:Al.optional()}),tE=hV.extend({region:Ix.optional().describe("Do you want local or Limbar?"),remoteEmulatorSettings:Oe.object({androidVersion:Oe.nativeEnum(Ju).optional()}).optional(),localEmulatorSettings:Oe.object({avdId:Zy}).optional(),geolocation:Oe.object({latitude:Oe.coerce.number().refine(t=>t>=-90&&t<=90,{message:"Latitude must be between -90 and 90 degrees"}),longitude:Oe.coerce.number().refine(t=>t>=-180&&t<=180,{message:"Longitude must be between -180 and 180 degrees"})}).optional(),waitForStability:Oe.boolean().optional().describe("wait for stability before every targeting action")}),Ul=Oe.object({retries:Oe.number().optional().describe("number of retries to run"),defaultChannel:Oe.string().optional().describe("Default app release channel to use when installing from managed mobile artifacts."),defaultTag:Oe.string().optional().describe("Default app artifact tag to use. If not set, the latest available tag is used."),defaultEnv:Oe.string().optional().describe("Default mobile environment name to load variables from at runtime."),defaultApkFilePath:Zy.describe("APK to install when using the emulator in the local region."),emulator:tE.optional().describe("Emulator configuration for local or remote mobile execution, including region and local emulator overrides."),ai:sy.optional().describe("AI behavior overrides for this mobile test, such as memory and failure recovery settings.")}),Nx=Oe.object({id:Oe.string().uuid(),description:Oe.string(),schemaVersion:Oe.string(),settings:Ul.optional(),disabled:Oe.boolean().optional(),labels:Oe.array(Oe.string()).optional()}),Mm=Nx.extend({platform:Oe.literal("ANDROID").optional().default("ANDROID")}),Om=Nx.extend({platform:Oe.literal("IOS")}),rE=Oe.discriminatedUnion("platform",[Mm,Om]),Dx=Oe.object({fileType:Oe.literal(ye.MOBILE_TEST)}),Lm=Dx.merge(Mm),Nm=Dx.merge(Om),BSe=Oe.discriminatedUnion("platform",[Lm,Nm]),kx=Mm.merge(Oe.object({steps:Oe.array($u)})),Fx=Om.merge(Oe.object({steps:Oe.array(Vy)})),zSe=Oe.discriminatedUnion("platform",[kx,Fx]),gV=Lm.merge(kx),SV=Nm.merge(Fx),yV=Oe.discriminatedUnion("platform",[gV,SV]),HSe=Oe.object({name:Oe.string(),steps:Oe.array($u).optional(),settings:Ul.optional()}),Ux=Mm.extend({steps:is.array()}),Bx=Om.extend({steps:Zu.array()}),GSe=Oe.discriminatedUnion("platform",[Ux,Bx]),EV=Ux.extend({name:Oe.string()}),TV=Bx.extend({name:Oe.string()}),bV=Oe.discriminatedUnion("platform",[EV,TV]);import ke from"zod";import re from"zod";var sn=re.object({startTime:re.number(),endTime:re.number().optional(),durationMs:re.number().optional(),error:re.string().optional(),result:re.unknown().optional(),attributes:re.record(re.string(),re.unknown()),subSpans:re.lazy(()=>DV.array())});var nE=sn.extend({type:re.literal("SECTION"),name:re.string()}),vV=sn.extend({type:re.literal("GET_PAGE_STATE")}),AV=sn.extend({type:re.literal("GET_PAGE_SCREENSHOT")}),CV=sn.extend({type:re.literal("SMART_WAITING")}),RV=sn.extend({type:re.literal("SCROLL_ELEMENT_INTO_VIEW")}),wV=sn.extend({type:re.literal("AI_LOCATOR_CALL"),screenshotSnapshotId:re.string().optional(),result:re.object({id:re.number(),thoughts:re.string()}).optional()}),xV=sn.extend({type:re.literal("AI_ASSERTION_CALL"),screenshotSnapshotId:re.string().optional(),elementScreenshotSnapshotId:re.string().optional(),result:re.object({thoughts:re.string(),result:re.boolean()}).optional()}),_V=sn.extend({type:re.literal("ELEMENT_ASSERTION"),name:re.string(),result:re.object({success:re.boolean(),message:re.string().optional()}).optional()}),IV=sn.extend({type:re.literal("BROWSER_INTERACTION"),name:re.string(),coordinates:re.object({x:re.number(),y:re.number()}).optional(),value:re.string().optional(),selector:re.string().optional()}),PV=sn.extend({type:re.literal("CACHE_RESOLUTION"),resolutionMethod:re.string().optional(),cacheMissReason:re.nativeEnum(nl).optional(),targetSource:re.string().optional(),result:re.object({serializedElement:re.string()}).optional()}),MV=sn.extend({type:re.literal("TARGET_RESOLUTION"),elementScreenshotSnapshotId:re.string().optional(),result:re.object({serializedElement:re.string()}).optional()}),OV=sn.extend({type:re.literal("LOCATOR_REDIRECT"),elementScreenshotSnapshotId:re.string().optional(),result:re.object({outcome:re.string(),logs:re.string().array().optional(),serializedElement:re.string().optional(),relativeClickPoint:re.object({x:re.number(),y:re.number()}).optional(),force:re.boolean().optional()}).optional()}),LV=sn.extend({type:re.literal("WAIT_FOR_STABILITY")}),NV=sn.extend({type:re.literal("GENERIC"),name:re.string()}),DV=re.discriminatedUnion("type",[nE,vV,AV,CV,RV,wV,xV,_V,IV,MV,PV,OV,LV,NV]);var Hn=ke.object({startTime:ke.number(),endTime:ke.number().optional(),durationMs:ke.number().optional(),error:ke.string().optional(),result:ke.unknown().optional(),attributes:ke.record(ke.string(),ke.unknown()),subSpans:ke.lazy(()=>KV.array())});var kV=Hn.extend({type:ke.literal("SECTION"),name:ke.string()}),FV=Hn.extend({type:ke.literal("AI_LOCATOR_CALL"),result:ke.object({id:ke.number(),thoughts:ke.string()}).optional()}),UV=Hn.extend({type:ke.literal("AI_ASSERTION_CALL"),result:ke.object({thoughts:ke.string(),result:ke.boolean()}).optional()}),BV=Hn.extend({type:ke.literal("TARGET_RESOLUTION"),result:ke.object({serializedElement:ke.string()}).optional()}),zV=Hn.extend({type:ke.literal("EMULATOR_INTERACTION"),name:ke.string(),withinWebview:ke.boolean().optional()}),HV=Hn.extend({type:ke.literal("EMULATOR_READ_STATE"),name:ke.string()}),GV=Hn.extend({type:ke.literal("ELEMENT_ASSERTION"),name:ke.string(),result:ke.object({success:ke.boolean(),message:ke.string().optional()}).optional()}),jV=Hn.extend({type:ke.literal("CACHE_RESOLUTION")}),VV=Hn.extend({type:ke.literal("WAIT_FOR_SCREENSHOT_STABILITY")}),WV=Hn.extend({type:ke.literal("WAIT_FOR_PAGE_STABILITY")}),$V=Hn.extend({type:ke.literal("WEBVIEW_LOCATOR_CALL"),webTrace:nE}),qV=Hn.extend({type:ke.literal("GENERIC"),name:ke.string()}),KV=ke.discriminatedUnion("type",[kV,FV,UV,BV,zV,HV,GV,jV,VV,WV,$V,qV]);import{parse as QSe}from"date-fns";import{z as Bl}from"zod";var eye=Bl.object({testId:Bl.string(),sessionId:Bl.string()}),zx=Bl.object({uploadUrl:Bl.string(),id:Bl.string()});import YV from"zod";var Hx=(r=>(r.LOCAL="local",r.REMOTE="remote",r))(Hx||{}),nye=YV.nativeEnum(Hx);var Dye=new Set(Object.values(rt));var XV={AI_ACTION:"AI action",AI_ACTION_DYNAMIC:"AI action",CONDITIONAL:"Conditional",RESOLVED_MODULE:"Module",AI_ASSERTION:"AI check",AI_EXTRACT:"AI extract",CLICK:"Click",TYPE:"Type",JAVASCRIPT:"JavaScript",SELECT_OPTION:"Select",PRESS:"Press",KEY_DOWN:"Key down",KEY_UP:"Key up",NAVIGATE:"Navigate",SCROLL_UP:"Scroll up",SCROLL_DOWN:"Scroll down",SCROLL_LEFT:"Scroll left",SCROLL_RIGHT:"Scroll right",HOVER:"Hover",BLUR:"Blur",FILE_UPLOAD:"File upload",FOCUS:"Focus",GO_BACK:"Go back",GO_FORWARD:"Go forward",WAIT:"Wait",REFRESH:"Refresh",TAB:"Switch tab",NEW_TAB:"New tab",COOKIE:"Cookie",LOCAL_STORAGE:"localStorage",REQUEST:"API request",GRAPHQL_REQUEST:"GraphQL request",CAPTCHA:"CAPTCHA",DRAG:"Drag & drop",VISUAL_DIFF:"Visual diff",DIALOG:"Dialog",MOUSE_DRAG:"Mouse drag",AUTH_LOAD:"Load auth state",AUTH_SAVE:"Save auth state",ELEMENT_CHECK:"Element check",PAGE_CHECK:"Page check",WAIT_FOR_URL:"Wait for URL",COPY:"Copy",PASTE:"Paste",REGISTER_REQUEST_LISTENER:"Register request listener",AWAIT_LISTENER:"Await listener",RECORD_REQUESTS:"Record requests",GET_RECORDED_REQUESTS:"Get recorded requests",SET_HEADER:"Set header",MOCK_ROUTE:"Mock route",REMOVE_ROUTE_MOCK:"Remove route mock",OFFLINE_MODE:"Offline mode",SUCCESS:"Done"},kye={AI_ACTION:["ai","action","agent"],AI_ACTION_DYNAMIC:["ai","action","dynamic","agent"],CONDITIONAL:["conditional","if","else","elif","branch"],RESOLVED_MODULE:[],AI_ASSERTION:["ai","check","assert","make sure","ensure"],AI_EXTRACT:["ai","extract","data"],CLICK:["click","press"],TYPE:["type","input","write","press"],JAVASCRIPT:["js","javascript","code","execute"],SELECT_OPTION:["select","option","choose"],PRESS:["keyboard","type","key"],KEY_DOWN:["keyboard","type","key","down","press"],KEY_UP:["keyboard","type","key","up","press"],NAVIGATE:["go to","visit"],SCROLL_UP:[],SCROLL_DOWN:[],SCROLL_LEFT:[],SCROLL_RIGHT:[],HOVER:["scroll into view","go to"],BLUR:[],FILE_UPLOAD:[],FOCUS:[],GO_BACK:[],GO_FORWARD:[],WAIT:[],REFRESH:[],TAB:[],NEW_TAB:[],COOKIE:[],LOCAL_STORAGE:[],REQUEST:[],GRAPHQL_REQUEST:[],CAPTCHA:[],DRAG:[],VISUAL_DIFF:[],DIALOG:[],MOUSE_DRAG:[],AUTH_LOAD:[],AUTH_SAVE:[],ELEMENT_CHECK:[],PAGE_CHECK:[],WAIT_FOR_URL:[],COPY:[],PASTE:[],REGISTER_REQUEST_LISTENER:[],AWAIT_LISTENER:[],RECORD_REQUESTS:[],GET_RECORDED_REQUESTS:[],SET_HEADER:[],MOCK_ROUTE:[],REMOVE_ROUTE_MOCK:[],OFFLINE_MODE:[],SUCCESS:[]},mt={AI_ACTION:"Ask AI achieve a specific goal. Saves the steps for reuse. Please use Dynamic AI action instead.",AI_ACTION_DYNAMIC:"Ask AI achieve a specific goal. Fully dynamic and does not save the steps for reuse. Our most capable AI agent.",CONDITIONAL:"Execute steps based on the outcome of a conditional check",RESOLVED_MODULE:"A list of steps that can be reused in multiple tests.",AI_ASSERTION:"Ask AI to verify whether something is true on the page.",CLICK:"Click on an element on the page.",DIALOG:"Specify how native browser dialogs should be handled.",AI_EXTRACT:"Ask AI to extract data from the page.",HOVER:"Hover over an element on the page.",FILE_UPLOAD:"Automatically upload a file when the native file upload dialog is activated.",FOCUS:"Focus an element on the page.",BLUR:"Remove focus from an element on the page.",SELECT_OPTION:"Select an option from an HTML Select <select> element.",TYPE:"Type the specified text into an element.",PRESS:"Press the specified keys using the keyboard. (e.g. Control+A)",KEY_DOWN:"Hold down the specified keys on the keyboard. (e.g. Control+A)",KEY_UP:"Release the specified keys on the keyboard. (e.g. Control+A)",NAVIGATE:"Navigate to the specified URL.",SCROLL_UP:"Scroll up by a specified height.",SCROLL_DOWN:"Scroll down by a specified height.",SCROLL_LEFT:"Scroll left by a specified width.",SCROLL_RIGHT:"Scroll right by a specified width.",GO_BACK:"Go back in browser history.",GO_FORWARD:"Go forward in browser history.",WAIT:"Wait for the specified number of seconds.",REFRESH:"Refresh the page. This will not clear cookies or session data.",TAB:"Switch to different tab in the browser.",NEW_TAB:"Create and switch to a new tab in the browser.",COOKIE:"Set a cookie that will persist throughout the browser session.",LOCAL_STORAGE:"Set a localStorage value that will persist throughout the browser session",CAPTCHA:"Solve CAPTCHAs on the page. This feature is only available on Momentic Cloud and may take up to 60 seconds. Disabling CAPTCHAs in non-production environments is strongly advised.",REQUEST:"Make an API request to a URL.",GRAPHQL_REQUEST:"Make a GraphQL request to a URL.",JAVASCRIPT:"Run JavaScript code in the browser or a Node.js environment.",DRAG:"Click and drag an element to another location.",VISUAL_DIFF:"Compare a screenshot of the page or a specific element to a baseline image.",MOUSE_DRAG:"Click and drag the mouse by a specified distance.",AUTH_LOAD:"Load or clear session state using a JavaScript object including cookies, localStorage, and IndexDB entries.",AUTH_SAVE:"Save authentication state (cookies, localStorage) into a JavaScript object.",ELEMENT_CHECK:"Assert on an element's state using pre-built conditions, including content, visibility, attribute value checks.",PAGE_CHECK:"Assert on the active page's contents using pre-built conditions.",WAIT_FOR_URL:"Wait for the active page's URL to match a target value or pattern.",COPY:"Copy the specified value to the browser clipboard.",PASTE:"Paste the browser clipboard contents.",REGISTER_REQUEST_LISTENER:"Register a listener for network requests.",AWAIT_LISTENER:"Wait for a listener to fire, and return the response data.",RECORD_REQUESTS:"Record network requests that match a given pattern.",GET_RECORDED_REQUESTS:"Get recorded requests that matched the pattern.",SET_HEADER:"Set a header.",MOCK_ROUTE:"Mock network requests to a specific URL.",REMOVE_ROUTE_MOCK:"Remove a previously set route mock.",OFFLINE_MODE:"Configure offline mode.",SUCCESS:"Indicate the entire AI action has succeeded, optionally based on a condition."},Fye={AI_CHECK:"AI check",AI_EXTRACT:"AI extract",RESOLVED_MOBILE_MODULE:"Module",MOBILE_AI_ACTION_STEP:"AI action",TAP:"Tap",TYPE:"Type",PRESS:"Press button",PRESS_KEYBOARD:"Press keyboard",SWIPE:"Swipe",SCROLL_TO:"Scroll to",DRAG_AND_DROP:"Drag & drop",SCREEN_CHECK:"Screen check",ELEMENT_CHECK:"Element check",OPEN_APP:"Open app",KILL_APP:"Kill app",OPEN_NOTIFICATION_DRAWER:"Open notification drawer",JAVASCRIPT:"JavaScript",REQUEST:"API request",WAIT:"Wait",ADD_FILE:"Add file",INSTALL_APP:"Install app",UNINSTALL_APP:"Uninstall app",TOGGLE_SETTINGS:"Toggle settings",ROTATE_ORIENTATION:"Rotate orientation",ADB:"ADB command",STATE:"Debug state"},Uye={MOBILE_AI_ACTION_STEP:"Ask AI to accomplish a high-level goal by generating other steps.",RESOLVED_MOBILE_MODULE:"A list of steps that can be reused in multiple tests.",TAP:"Tap on an element on the screen.",TYPE:"Type the specified text into an element.",PRESS:"Press a physical button on the device.",PRESS_KEYBOARD:"Press a special key on the keyboard.",SWIPE:"Swipe on the screen.",SCREEN_CHECK:"Assert on the screen content using pre-built conditions.",SCROLL_TO:"Scroll until an element is visible.",DRAG_AND_DROP:"Drag an element onto another element in the same context.",ELEMENT_CHECK:"Assert on an element's state using pre-built conditions, including content, visibility, attribute value checks.",OPEN_APP:"Open an app on the device.",KILL_APP:"Terminate the currently active app and remove it from recents.",OPEN_NOTIFICATION_DRAWER:"Open the notification drawer.",JAVASCRIPT:"Execute JavaScript code in a NodeJS context.",REQUEST:"Make an HTTP request to a URL.",WAIT:"Wait for a specified amount of time.",ADD_FILE:"Add a file to the device's disk.",INSTALL_APP:"Install one or more APKs onto the connected emulator (local emulator only).",UNINSTALL_APP:"Uninstall an APK from the connected emulator (local emulator only).",TOGGLE_SETTINGS:"Toggle device settings.",ROTATE_ORIENTATION:"Rotate the device orientation to portrait or landscape.",ADB:"Execute an ADB command on the device.",STATE:"Capture and return emulator state details.",AI_CHECK:"Ask AI to verify whether something is true on the screen.",AI_EXTRACT:"Ask AI to extract data from the emulator state."};import JV from"semver";import{z as QV}from"zod";var Gye=QV.string().refine(t=>JV.valid(t),{message:"must be a valid semver string"});function zl(t){if(t!==void 0)return t===!0||t==="true"||t==="1"}import{Faker as Wye,en as $ye}from"@faker-js/faker";import{z as $}from"zod";var Hl=55555,Kye=$.object({body:$.string(),to:$.string(),from:$.string()}),Yye=$.object({from:$.string().optional(),to:$.string(),timeout:$.number().optional(),beforeDate:$.string().pipe($.coerce.date()).or($.date()).optional(),afterDate:$.string().pipe($.coerce.date()).or($.date()).optional()}),Xye=$.object({to:$.string().email(),from:$.string(),subject:$.string(),body:$.string(),html:$.string().optional()}),Jye=$.object({inbox:$.string().transform(t=>t.toLowerCase()),afterDate:$.string().pipe($.coerce.date()).or($.date()).optional(),timeout:$.number().optional(),trimWhitespace:$.boolean().optional()}),Qye=$.object({inbox:$.string(),limit:$.number().optional(),afterDate:$.string().pipe($.coerce.date()).or($.date()).optional(),trimWhitespace:$.boolean().optional()});var Dm=(r=>(r.RAW="RAW",r.RESPONSE="RESPONSE",r))(Dm||{}),Gx=$.object({body:$.string().nullish(),status:$.number().optional(),headers:$.array($.tuple([$.string(),$.string()])).optional()}),ZV=$.object({url:$.string(),options:$.object({method:$.string(),body:$.string().nullish(),headers:$.array($.tuple([$.string(),$.string()])).optional()}).optional()}).optional(),eW=$.object({body:$.string().nullish(),options:$.object({status:$.number(),statusText:$.string().optional(),headers:$.array($.tuple([$.string(),$.string()])).optional()}).optional()}).optional(),jx=$.object({result:$.unknown(),variableUpdates:$.record($.string(),$.unknown()).optional(),persistentVariableUpdates:$.record($.string(),$.unknown()).optional(),error:$.string().optional(),success:$.boolean()}),Zye=$.object({id:$.string().optional(),orgId:$.string(),momenticLambdaAuthHash:$.string(),code:$.string(),fragment:$.boolean(),state:$.object({env:$.record($.string(),$.unknown()),request:ZV,response:eW,additionalBindings:$.record($.string(),$.unknown()).optional()}),timeoutMs:$.number().optional(),disallowVariableUpdates:$.boolean().optional(),responseSerialization:$.nativeEnum(Dm).optional()}),Ji=15e3;import*as Or from"zod";import{extendZodWithOpenApi as tW}from"zod-openapi";tW(Or);var rW=Or.object({url:Or.string(),lineNumber:Or.number(),columnNumber:Or.number()}).openapi({ref:"CodeLocation"}),km=Or.object({timestamp:Or.number(),text:Or.string(),type:Or.string(),tabIndex:Or.number(),args:Or.unknown().array().optional(),url:Or.string().optional(),location:rW.optional()}).openapi({ref:"ConsoleLog"}),Vx=km.array(),oE=Vx.array();import*as iE from"zod";import{extendZodWithOpenApi as nW}from"zod-openapi";nW(iE);var oW=iE.object({logsPerPage:km.array().array()}).openapi({ref:"DebugData"});import*as Ot from"zod";import{extendZodWithOpenApi as iW}from"zod-openapi";iW(Ot);var Wx=Ot.object({total:Ot.number(),user:Ot.number(),sys:Ot.number(),intervalMs:Ot.number()}),aW=Ot.object({total:Ot.number(),free:Ot.number(),freePercentage:Ot.number()}),sW=Ot.object({rss:Ot.number(),heapTotal:Ot.number(),heapUsed:Ot.number(),external:Ot.number(),arrayBuffers:Ot.number()}),$x=Ot.object({timestamp:Ot.number(),system:Ot.object({cpu:Wx.nullable(),memory:aW}),process:Ot.object({cpu:Wx.nullable(),memory:sW})}).openapi({ref:"ResourceUsageSample"}),lW=Ot.object({samples:$x.array()}).openapi({ref:"ResourceUsageSeries"});var ed=class{async getConsoleLogsForRunAttempt(e,r,n){}async getNetworkLogsForRunAttempt(e,r,n){}async getHtmlSnapshot(e,r){}async getA11yTreeSnapshot(e,r){}async getScreenshot(e,r){}async storeConsoleLogsForRunAttempt(e,r,n,o){}async storeNetworkLogsForRunAttempt(e,r,n,o){}listVideoAssetPaths(){return[]}close(){}async storeScreenshot(e,r,n){}async storeOnDemandScreenshotById(e,r,n,o){}async storeHtmlSnapshot(e,r,n){}};import{z as k}from"zod";var cW=k.object({name:k.string(),version:k.string(),comment:k.string().optional()}),uW=k.object({name:k.string(),version:k.string(),comment:k.string().optional()}),dW=k.object({onContentLoad:k.number().optional(),onLoad:k.number().optional(),comment:k.string().optional()}),td=k.object({startedDateTime:k.string(),id:k.string(),title:k.string().optional(),pageTimings:dW,comment:k.string().optional()}),pW=k.array(td),mW=k.object({name:k.string(),value:k.string(),path:k.string().optional(),domain:k.string().optional(),expires:k.string().optional(),httpOnly:k.boolean().optional(),secure:k.boolean().optional(),comment:k.string().optional()}),Kx=k.array(mW),fW=k.object({name:k.string(),value:k.string(),comment:k.string().optional()}),Yx=k.array(fW),hW=k.object({name:k.string(),value:k.string(),comment:k.string().optional()}),gW=k.array(hW),SW=k.object({name:k.string(),value:k.string().optional(),fileName:k.string().optional(),contentType:k.string().optional(),comment:k.string().optional()}),yW=k.array(SW),EW=k.object({mimeType:k.string(),params:yW,text:k.string(),comment:k.string().optional(),_redactedReason:k.string().optional()}),TW=k.object({method:k.string(),url:k.string(),httpVersion:k.string().optional(),cookies:Kx,headers:Yx,queryString:gW,postData:EW.optional(),headersSize:k.number().optional(),bodySize:k.number().optional(),comment:k.string().optional()}),bW=k.object({size:k.number().optional(),compression:k.number().optional(),mimeType:k.string().optional(),text:k.string().optional(),encoding:k.string().optional(),comment:k.string().optional(),_redactedReason:k.string().optional()}),vW=k.object({status:k.number(),statusText:k.string(),httpVersion:k.string().optional(),cookies:Kx,headers:Yx,content:bW,redirectURL:k.string().optional(),headersSize:k.number().optional(),bodySize:k.number().optional(),comment:k.string().optional(),_mocked:k.boolean().optional()}),qx=k.object({expires:k.string().optional(),lastAccess:k.string(),eTag:k.string(),hitCount:k.number(),comment:k.string().optional()}),AW=k.object({beforeRequest:qx.optional(),afterRequest:qx.optional(),comment:k.string().optional()}),CW=k.object({blocked:k.number().optional(),dns:k.number().optional(),connect:k.number().optional(),send:k.number(),wait:k.number(),receive:k.number(),ssl:k.number().optional(),comment:k.string().optional()}),rd=k.object({pageref:k.string().optional(),startedDateTime:k.string(),time:k.number().optional(),request:TW,response:vW.optional(),cache:AW.optional(),timings:CW,serverIPAddress:k.string().optional(),connection:k.string().optional(),comment:k.string().optional(),_resourceType:k.string().optional()}),RW=k.array(rd),wW=k.object({version:k.string().default("1.1"),creator:cW.optional(),browser:uW.optional(),pages:pW.optional(),entries:RW,comment:k.string().optional()}),xW=k.object({log:wW}),fEe=k.record(k.string(),td),hEe=k.record(k.string(),rd);function aE(t,e){return{log:{version:"1.2",creator:{name:"Momentic, Inc.",version:"1.0.0"},pages:Object.values(t).sort((r,n)=>new Date(r.startedDateTime).getTime()-new Date(n.startedDateTime).getTime()),entries:Object.values(e).sort((r,n)=>new Date(r.startedDateTime).getTime()-new Date(n.startedDateTime).getTime())}}}var Xx=t=>{throw new Error(`Exhaustive check failed for value: ${t}`)};import{cloneDeep as _W}from"lodash-es";import{z as Uo}from"zod";var sE=(d=>(d.DisableClickhouseCaches="disable_clickhouse_caches",d.ShowZeroOpacityElements="show_zero_opacity_elements",d.VisualActions="visual_actions",d.RagV2="rag_v2",d.DisableSecondaryCacheResolution="disable_secondary_cache_resolution",d.GlobalLocatorRedirect="global_locator_redirect",d.FakerConstantSeed="faker_constant_seed",d.AutoExpandIframes="auto_expand_iframes",d.NewAiActionStepsUseV3="new_ai_action_steps_use_v3",d.PerformanceInsights="performance_insights",d.IosTests="ios_tests",d))(sE||{});var Jx=Uo.union([Uo.string(),Uo.number(),Uo.boolean(),Uo.null(),Uo.record(Uo.string(),Uo.lazy(()=>Jx)),Uo.array(Uo.lazy(()=>Jx))]),nd=class{flags;payloads;constructor(e,r){this.flags=e,this.payloads=r}isBooleanFlagEnabled(e){return process.env&&process.env[`MOMENTIC_FLAG_OVERRIDE_${e.toUpperCase()}`]==="true"?!0:process.env&&process.env[`MOMENTIC_FLAG_OVERRIDE_${e.toUpperCase()}`]==="false"?!1:this.flags[e]===!0}getAllFlags(){let e=_W(this.flags);return Object.entries(e).forEach(([r,n])=>{typeof n=="boolean"&&Object.values(sE).includes(r)&&(e[r]=this.isBooleanFlagEnabled(r))}),e}getFlagPayload(e){let r=this.payloads[e];if(r!==void 0){if(typeof r=="string")try{return JSON.parse(r)}catch{return r}return r}}refresh(){throw new Error("Not implemented")}},xEe=new nd({},{});var od={".123":"application/vnd.lotus-1-2-3",".3dml":"text/vnd.in3d.3dml",".3g2":"video/3gpp2",".3gp":"video/3gpp",".a":"application/octet-stream",".aab":"application/x-authorware-bin",".aac":"audio/x-aac",".aam":"application/x-authorware-map",".aas":"application/x-authorware-seg",".abw":"application/x-abiword",".acc":"application/vnd.americandynamics.acc",".ace":"application/x-ace-compressed",".acu":"application/vnd.acucobol",".acutc":"application/vnd.acucorp",".adp":"audio/adpcm",".aep":"application/vnd.audiograph",".afm":"application/x-font-type1",".afp":"application/vnd.ibm.modcap",".ai":"application/postscript",".aif":"audio/x-aiff",".aifc":"audio/x-aiff",".aiff":"audio/x-aiff",".air":"application/vnd.adobe.air-application-installer-package+zip",".ami":"application/vnd.amiga.ami",".apk":"application/vnd.android.package-archive",".application":"application/x-ms-application",".apr":"application/vnd.lotus-approach",".asc":"application/pgp-signature",".asf":"video/x-ms-asf",".asm":"text/x-asm",".aso":"application/vnd.accpac.simply.aso",".asx":"video/x-ms-asf",".atc":"application/vnd.acucorp",".atom":"application/atom+xml",".atomcat":"application/atomcat+xml",".atomsvc":"application/atomsvc+xml",".atx":"application/vnd.antix.game-component",".au":"audio/basic",".avi":"video/x-msvideo",".aw":"application/applixware",".azf":"application/vnd.airzip.filesecure.azf",".azs":"application/vnd.airzip.filesecure.azs",".azw":"application/vnd.amazon.ebook",".bat":"application/x-msdownload",".bcpio":"application/x-bcpio",".bdf":"application/x-font-bdf",".bdm":"application/vnd.syncml.dm+wbxml",".bh2":"application/vnd.fujitsu.oasysprs",".bin":"application/octet-stream",".bmi":"application/vnd.bmi",".bmp":"image/bmp",".book":"application/vnd.framemaker",".box":"application/vnd.previewsystems.box",".boz":"application/x-bzip2",".bpk":"application/octet-stream",".btif":"image/prs.btif",".bz":"application/x-bzip",".bz2":"application/x-bzip2",".c":"text/x-c",".c4d":"application/vnd.clonk.c4group",".c4f":"application/vnd.clonk.c4group",".c4g":"application/vnd.clonk.c4group",".c4p":"application/vnd.clonk.c4group",".c4u":"application/vnd.clonk.c4group",".cab":"application/vnd.ms-cab-compressed",".car":"application/vnd.curl.car",".cat":"application/vnd.ms-pki.seccat",".cc":"text/x-c",".cct":"application/x-director",".ccxml":"application/ccxml+xml",".cdbcmsg":"application/vnd.contact.cmsg",".cdf":"application/x-netcdf",".cdkey":"application/vnd.mediastation.cdkey",".cdx":"chemical/x-cdx",".cdxml":"application/vnd.chemdraw+xml",".cdy":"application/vnd.cinderella",".cer":"application/pkix-cert",".cgm":"image/cgm",".chat":"application/x-chat",".chm":"application/vnd.ms-htmlhelp",".chrt":"application/vnd.kde.kchart",".cif":"chemical/x-cif",".cii":"application/vnd.anser-web-certificate-issue-initiation",".cil":"application/vnd.ms-artgalry",".cla":"application/vnd.claymore",".class":"application/java-vm",".clkk":"application/vnd.crick.clicker.keyboard",".clkp":"application/vnd.crick.clicker.palette",".clkt":"application/vnd.crick.clicker.template",".clkw":"application/vnd.crick.clicker.wordbank",".clkx":"application/vnd.crick.clicker",".clp":"application/x-msclip",".cmc":"application/vnd.cosmocaller",".cmdf":"chemical/x-cmdf",".cml":"chemical/x-cml",".cmp":"application/vnd.yellowriver-custom-menu",".cmx":"image/x-cmx",".cod":"application/vnd.rim.cod",".com":"application/x-msdownload",".conf":"text/plain",".cpio":"application/x-cpio",".cpp":"text/x-c",".cpt":"application/mac-compactpro",".crd":"application/x-mscardfile",".crl":"application/pkix-crl",".crt":"application/x-x509-ca-cert",".csh":"application/x-csh",".csml":"chemical/x-csml",".csp":"application/vnd.commonspace",".css":"text/css",".cst":"application/x-director",".csv":"text/csv",".cu":"application/cu-seeme",".curl":"text/vnd.curl",".cww":"application/prs.cww",".cxt":"application/x-director",".cxx":"text/x-c",".daf":"application/vnd.mobius.daf",".dataless":"application/vnd.fdsn.seed",".davmount":"application/davmount+xml",".dcr":"application/x-director",".dcurl":"text/vnd.curl.dcurl",".dd2":"application/vnd.oma.dd2+xml",".ddd":"application/vnd.fujixerox.ddd",".deb":"application/x-debian-package",".def":"text/plain",".deploy":"application/octet-stream",".der":"application/x-x509-ca-cert",".dfac":"application/vnd.dreamfactory",".dic":"text/x-c",".diff":"text/plain",".dir":"application/x-director",".dis":"application/vnd.mobius.dis",".dist":"application/octet-stream",".distz":"application/octet-stream",".djv":"image/vnd.djvu",".djvu":"image/vnd.djvu",".dll":"application/x-msdownload",".dmg":"application/octet-stream",".dms":"application/octet-stream",".dna":"application/vnd.dna",".doc":"application/msword",".docm":"application/vnd.ms-word.document.macroenabled.12",".docx":"application/vnd.openxmlformats-officedocument.wordprocessingml.document",".dot":"application/msword",".dotm":"application/vnd.ms-word.template.macroenabled.12",".dotx":"application/vnd.openxmlformats-officedocument.wordprocessingml.template",".dp":"application/vnd.osgi.dp",".dpg":"application/vnd.dpgraph",".dsc":"text/prs.lines.tag",".dtb":"application/x-dtbook+xml",".dtd":"application/xml-dtd",".dts":"audio/vnd.dts",".dtshd":"audio/vnd.dts.hd",".dump":"application/octet-stream",".dvi":"application/x-dvi",".dwf":"model/vnd.dwf",".dwg":"image/vnd.dwg",".dxf":"image/vnd.dxf",".dxp":"application/vnd.spotfire.dxp",".dxr":"application/x-director",".ecelp4800":"audio/vnd.nuera.ecelp4800",".ecelp7470":"audio/vnd.nuera.ecelp7470",".ecelp9600":"audio/vnd.nuera.ecelp9600",".ecma":"application/ecmascript",".edm":"application/vnd.novadigm.edm",".edx":"application/vnd.novadigm.edx",".efif":"application/vnd.picsel",".ei6":"application/vnd.pg.osasli",".elc":"application/octet-stream",".eml":"message/rfc822",".emma":"application/emma+xml",".eol":"audio/vnd.digital-winds",".eot":"application/vnd.ms-fontobject",".eps":"application/postscript",".epub":"application/epub+zip",".es3":"application/vnd.eszigno3+xml",".esf":"application/vnd.epson.esf",".et3":"application/vnd.eszigno3+xml",".etx":"text/x-setext",".exe":"application/x-msdownload",".ext":"application/vnd.novadigm.ext",".ez":"application/andrew-inset",".ez2":"application/vnd.ezpix-album",".ez3":"application/vnd.ezpix-package",".f":"text/x-fortran",".f4v":"video/x-f4v",".f77":"text/x-fortran",".f90":"text/x-fortran",".fbs":"image/vnd.fastbidsheet",".fdf":"application/vnd.fdf",".fe_launch":"application/vnd.denovo.fcselayout-link",".fg5":"application/vnd.fujitsu.oasysgp",".fgd":"application/x-director",".fh":"image/x-freehand",".fh4":"image/x-freehand",".fh5":"image/x-freehand",".fh7":"image/x-freehand",".fhc":"image/x-freehand",".fig":"application/x-xfig",".fli":"video/x-fli",".flo":"application/vnd.micrografx.flo",".flv":"video/x-flv",".flw":"application/vnd.kde.kivio",".flx":"text/vnd.fmi.flexstor",".fly":"text/vnd.fly",".fm":"application/vnd.framemaker",".fnc":"application/vnd.frogans.fnc",".for":"text/x-fortran",".fpx":"image/vnd.fpx",".frame":"application/vnd.framemaker",".fsc":"application/vnd.fsc.weblaunch",".fst":"image/vnd.fst",".ftc":"application/vnd.fluxtime.clip",".fti":"application/vnd.anser-web-funds-transfer-initiation",".fvt":"video/vnd.fvt",".fzs":"application/vnd.fuzzysheet",".g3":"image/g3fax",".gac":"application/vnd.groove-account",".gdl":"model/vnd.gdl",".geo":"application/vnd.dynageo",".gex":"application/vnd.geometry-explorer",".ggb":"application/vnd.geogebra.file",".ggt":"application/vnd.geogebra.tool",".ghf":"application/vnd.groove-help",".gif":"image/gif",".gim":"application/vnd.groove-identity-message",".gmx":"application/vnd.gmx",".gnumeric":"application/x-gnumeric",".gph":"application/vnd.flographit",".gqf":"application/vnd.grafeq",".gqs":"application/vnd.grafeq",".gram":"application/srgs",".gre":"application/vnd.geometry-explorer",".grv":"application/vnd.groove-injector",".grxml":"application/srgs+xml",".gsf":"application/x-font-ghostscript",".gtar":"application/x-gtar",".gtm":"application/vnd.groove-tool-message",".gtw":"model/vnd.gtw",".gv":"text/vnd.graphviz",".gz":"application/x-gzip",".h":"text/x-c",".h261":"video/h261",".h263":"video/h263",".h264":"video/h264",".hbci":"application/vnd.hbci",".hdf":"application/x-hdf",".hh":"text/x-c",".hlp":"application/winhlp",".hpgl":"application/vnd.hp-hpgl",".hpid":"application/vnd.hp-hpid",".hps":"application/vnd.hp-hps",".hqx":"application/mac-binhex40",".htke":"application/vnd.kenameaapp",".htm":"text/html",".html":"text/html",".hvd":"application/vnd.yamaha.hv-dic",".hvp":"application/vnd.yamaha.hv-voice",".hvs":"application/vnd.yamaha.hv-script",".icc":"application/vnd.iccprofile",".ice":"x-conference/x-cooltalk",".icm":"application/vnd.iccprofile",".ico":"image/x-icon",".ics":"text/calendar",".ief":"image/ief",".ifb":"text/calendar",".ifm":"application/vnd.shana.informed.formdata",".iges":"model/iges",".igl":"application/vnd.igloader",".igs":"model/iges",".igx":"application/vnd.micrografx.igx",".iif":"application/vnd.shana.informed.interchange",".imp":"application/vnd.accpac.simply.imp",".ims":"application/vnd.ms-ims",".in":"text/plain",".ipk":"application/vnd.shana.informed.package",".irm":"application/vnd.ibm.rights-management",".irp":"application/vnd.irepository.package+xml",".iso":"application/octet-stream",".itp":"application/vnd.shana.informed.formtemplate",".ivp":"application/vnd.immervision-ivp",".ivu":"application/vnd.immervision-ivu",".jad":"text/vnd.sun.j2me.app-descriptor",".jam":"application/vnd.jam",".jar":"application/java-archive",".java":"text/x-java-source",".jisp":"application/vnd.jisp",".jlt":"application/vnd.hp-jlyt",".jnlp":"application/x-java-jnlp-file",".joda":"application/vnd.joost.joda-archive",".jpe":"image/jpeg",".jpeg":"image/jpeg",".jpg":"image/jpeg",".jpgm":"video/jpm",".jpgv":"video/jpeg",".jpm":"video/jpm",".js":"application/javascript",".json":"application/json",".kar":"audio/midi",".karbon":"application/vnd.kde.karbon",".kfo":"application/vnd.kde.kformula",".kia":"application/vnd.kidspiration",".kil":"application/x-killustrator",".kml":"application/vnd.google-earth.kml+xml",".kmz":"application/vnd.google-earth.kmz",".kne":"application/vnd.kinar",".knp":"application/vnd.kinar",".kon":"application/vnd.kde.kontour",".kpr":"application/vnd.kde.kpresenter",".kpt":"application/vnd.kde.kpresenter",".ksh":"text/plain",".ksp":"application/vnd.kde.kspread",".ktr":"application/vnd.kahootz",".ktz":"application/vnd.kahootz",".kwd":"application/vnd.kde.kword",".kwt":"application/vnd.kde.kword",".latex":"application/x-latex",".lbd":"application/vnd.llamagraphics.life-balance.desktop",".lbe":"application/vnd.llamagraphics.life-balance.exchange+xml",".les":"application/vnd.hhe.lesson-player",".lha":"application/octet-stream",".link66":"application/vnd.route66.link66+xml",".list":"text/plain",".list3820":"application/vnd.ibm.modcap",".listafp":"application/vnd.ibm.modcap",".log":"text/plain",".lostxml":"application/lost+xml",".lrf":"application/octet-stream",".lrm":"application/vnd.ms-lrm",".ltf":"application/vnd.frogans.ltf",".lvp":"audio/vnd.lucent.voice",".lwp":"application/vnd.lotus-wordpro",".lzh":"application/octet-stream",".m13":"application/x-msmediaview",".m14":"application/x-msmediaview",".m1v":"video/mpeg",".m2a":"audio/mpeg",".m2v":"video/mpeg",".m3a":"audio/mpeg",".m3u":"audio/x-mpegurl",".m4u":"video/vnd.mpegurl",".m4v":"video/x-m4v",".ma":"application/mathematica",".mag":"application/vnd.ecowin.chart",".maker":"application/vnd.framemaker",".man":"text/troff",".mathml":"application/mathml+xml",".mb":"application/mathematica",".mbk":"application/vnd.mobius.mbk",".mbox":"application/mbox",".mc1":"application/vnd.medcalcdata",".mcd":"application/vnd.mcd",".mcurl":"text/vnd.curl.mcurl",".mdb":"application/x-msaccess",".mdi":"image/vnd.ms-modi",".me":"text/troff",".mesh":"model/mesh",".mfm":"application/vnd.mfmp",".mgz":"application/vnd.proteus.magazine",".mht":"message/rfc822",".mhtml":"message/rfc822",".mid":"audio/midi",".midi":"audio/midi",".mif":"application/vnd.mif",".mime":"message/rfc822",".mj2":"video/mj2",".mjp2":"video/mj2",".mkv":"video/x-matroska",".mlp":"application/vnd.dolby.mlp",".mmd":"application/vnd.chipnuts.karaoke-mmd",".mmf":"application/vnd.smaf",".mmr":"image/vnd.fujixerox.edmics-mmr",".mny":"application/x-msmoney",".mobi":"application/x-mobipocket-ebook",".mov":"video/quicktime",".movie":"video/x-sgi-movie",".mp2":"audio/mpeg",".mp2a":"audio/mpeg",".mp3":"audio/mpeg",".mp4":"video/mp4",".mp4a":"audio/mp4",".mp4s":"application/mp4",".mp4v":"video/mp4",".mpa":"video/mpeg",".mpc":"application/vnd.mophun.certificate",".mpe":"video/mpeg",".mpeg":"video/mpeg",".mpg":"video/mpeg",".mpg4":"video/mp4",".mpga":"audio/mpeg",".mpkg":"application/vnd.apple.installer+xml",".mpm":"application/vnd.blueice.multipass",".mpn":"application/vnd.mophun.application",".mpp":"application/vnd.ms-project",".mpt":"application/vnd.ms-project",".mpy":"application/vnd.ibm.minipay",".mqy":"application/vnd.mobius.mqy",".mrc":"application/marc",".ms":"text/troff",".mscml":"application/mediaservercontrol+xml",".mseed":"application/vnd.fdsn.mseed",".mseq":"application/vnd.mseq",".msf":"application/vnd.epson.msf",".msh":"model/mesh",".msi":"application/x-msdownload",".msl":"application/vnd.mobius.msl",".msty":"application/vnd.muvee.style",".mts":"model/vnd.mts",".mus":"application/vnd.musician",".musicxml":"application/vnd.recordare.musicxml+xml",".mvb":"application/x-msmediaview",".mwf":"application/vnd.mfer",".mxf":"application/mxf",".mxl":"application/vnd.recordare.musicxml",".mxml":"application/xv+xml",".mxs":"application/vnd.triscape.mxs",".mxu":"video/vnd.mpegurl",".n-gage":"application/vnd.nokia.n-gage.symbian.install",".nb":"application/mathematica",".nc":"application/x-netcdf",".ncx":"application/x-dtbncx+xml",".ngdat":"application/vnd.nokia.n-gage.data",".nlu":"application/vnd.neurolanguage.nlu",".nml":"application/vnd.enliven",".nnd":"application/vnd.noblenet-directory",".nns":"application/vnd.noblenet-sealer",".nnw":"application/vnd.noblenet-web",".npx":"image/vnd.net-fpx",".nsf":"application/vnd.lotus-notes",".nws":"message/rfc822",".o":"application/octet-stream",".oa2":"application/vnd.fujitsu.oasys2",".oa3":"application/vnd.fujitsu.oasys3",".oas":"application/vnd.fujitsu.oasys",".obd":"application/x-msbinder",".obj":"application/octet-stream",".oda":"application/oda",".odb":"application/vnd.oasis.opendocument.database",".odc":"application/vnd.oasis.opendocument.chart",".odf":"application/vnd.oasis.opendocument.formula",".odft":"application/vnd.oasis.opendocument.formula-template",".odg":"application/vnd.oasis.opendocument.graphics",".odi":"application/vnd.oasis.opendocument.image",".odp":"application/vnd.oasis.opendocument.presentation",".ods":"application/vnd.oasis.opendocument.spreadsheet",".odt":"application/vnd.oasis.opendocument.text",".oga":"audio/ogg",".ogg":"audio/ogg",".ogv":"video/ogg",".ogx":"application/ogg",".onepkg":"application/onenote",".onetmp":"application/onenote",".onetoc":"application/onenote",".onetoc2":"application/onenote",".opf":"application/oebps-package+xml",".oprc":"application/vnd.palm",".org":"application/vnd.lotus-organizer",".osf":"application/vnd.yamaha.openscoreformat",".osfpvg":"application/vnd.yamaha.openscoreformat.osfpvg+xml",".otc":"application/vnd.oasis.opendocument.chart-template",".otf":"application/x-font-otf",".otg":"application/vnd.oasis.opendocument.graphics-template",".oth":"application/vnd.oasis.opendocument.text-web",".oti":"application/vnd.oasis.opendocument.image-template",".otm":"application/vnd.oasis.opendocument.text-master",".otp":"application/vnd.oasis.opendocument.presentation-template",".ots":"application/vnd.oasis.opendocument.spreadsheet-template",".ott":"application/vnd.oasis.opendocument.text-template",".oxt":"application/vnd.openofficeorg.extension",".p":"text/x-pascal",".p10":"application/pkcs10",".p12":"application/x-pkcs12",".p7b":"application/x-pkcs7-certificates",".p7c":"application/pkcs7-mime",".p7m":"application/pkcs7-mime",".p7r":"application/x-pkcs7-certreqresp",".p7s":"application/pkcs7-signature",".pas":"text/x-pascal",".pbd":"application/vnd.powerbuilder6",".pbm":"image/x-portable-bitmap",".pcf":"application/x-font-pcf",".pcl":"application/vnd.hp-pcl",".pclxl":"application/vnd.hp-pclxl",".pct":"image/x-pict",".pcurl":"application/vnd.curl.pcurl",".pcx":"image/x-pcx",".pdb":"application/vnd.palm",".pdf":"application/pdf",".pfa":"application/x-font-type1",".pfb":"application/x-font-type1",".pfm":"application/x-font-type1",".pfr":"application/font-tdpfr",".pfx":"application/x-pkcs12",".pgm":"image/x-portable-graymap",".pgn":"application/x-chess-pgn",".pgp":"application/pgp-encrypted",".pic":"image/x-pict",".pkg":"application/octet-stream",".pki":"application/pkixcmp",".pkipath":"application/pkix-pkipath",".pl":"text/plain",".plb":"application/vnd.3gpp.pic-bw-large",".plc":"application/vnd.mobius.plc",".plf":"application/vnd.pocketlearn",".pls":"application/pls+xml",".pml":"application/vnd.ctc-posml",".png":"image/png",".pnm":"image/x-portable-anymap",".portpkg":"application/vnd.macports.portpkg",".pot":"application/vnd.ms-powerpoint",".potm":"application/vnd.ms-powerpoint.template.macroenabled.12",".potx":"application/vnd.openxmlformats-officedocument.presentationml.template",".ppa":"application/vnd.ms-powerpoint",".ppam":"application/vnd.ms-powerpoint.addin.macroenabled.12",".ppd":"application/vnd.cups-ppd",".ppm":"image/x-portable-pixmap",".pps":"application/vnd.ms-powerpoint",".ppsm":"application/vnd.ms-powerpoint.slideshow.macroenabled.12",".ppsx":"application/vnd.openxmlformats-officedocument.presentationml.slideshow",".ppt":"application/vnd.ms-powerpoint",".pptm":"application/vnd.ms-powerpoint.presentation.macroenabled.12",".pptx":"application/vnd.openxmlformats-officedocument.presentationml.presentation",".pqa":"application/vnd.palm",".prc":"application/x-mobipocket-ebook",".pre":"application/vnd.lotus-freelance",".prf":"application/pics-rules",".ps":"application/postscript",".psb":"application/vnd.3gpp.pic-bw-small",".psd":"image/vnd.adobe.photoshop",".psf":"application/x-font-linux-psf",".ptid":"application/vnd.pvi.ptid1",".pub":"application/x-mspublisher",".pvb":"application/vnd.3gpp.pic-bw-var",".pwn":"application/vnd.3m.post-it-notes",".pwz":"application/vnd.ms-powerpoint",".py":"text/x-python",".pya":"audio/vnd.ms-playready.media.pya",".pyc":"application/x-python-code",".pyo":"application/x-python-code",".pyv":"video/vnd.ms-playready.media.pyv",".qam":"application/vnd.epson.quickanime",".qbo":"application/vnd.intu.qbo",".qfx":"application/vnd.intu.qfx",".qps":"application/vnd.publishare-delta-tree",".qt":"video/quicktime",".qwd":"application/vnd.quark.quarkxpress",".qwt":"application/vnd.quark.quarkxpress",".qxb":"application/vnd.quark.quarkxpress",".qxd":"application/vnd.quark.quarkxpress",".qxl":"application/vnd.quark.quarkxpress",".qxt":"application/vnd.quark.quarkxpress",".ra":"audio/x-pn-realaudio",".ram":"audio/x-pn-realaudio",".rar":"application/x-rar-compressed",".ras":"image/x-cmu-raster",".rcprofile":"application/vnd.ipunplugged.rcprofile",".rdf":"application/rdf+xml",".rdz":"application/vnd.data-vision.rdz",".rep":"application/vnd.businessobjects",".res":"application/x-dtbresource+xml",".rgb":"image/x-rgb",".rif":"application/reginfo+xml",".rl":"application/resource-lists+xml",".rlc":"image/vnd.fujixerox.edmics-rlc",".rld":"application/resource-lists-diff+xml",".rm":"application/vnd.rn-realmedia",".rmi":"audio/midi",".rmp":"audio/x-pn-realaudio-plugin",".rms":"application/vnd.jcp.javame.midlet-rms",".rnc":"application/relax-ng-compact-syntax",".roff":"text/troff",".rpm":"application/x-rpm",".rpss":"application/vnd.nokia.radio-presets",".rpst":"application/vnd.nokia.radio-preset",".rq":"application/sparql-query",".rs":"application/rls-services+xml",".rsd":"application/rsd+xml",".rss":"application/rss+xml",".rtf":"application/rtf",".rtx":"text/richtext",".s":"text/x-asm",".saf":"application/vnd.yamaha.smaf-audio",".sbml":"application/sbml+xml",".sc":"application/vnd.ibm.secure-container",".scd":"application/x-msschedule",".scm":"application/vnd.lotus-screencam",".scq":"application/scvp-cv-request",".scs":"application/scvp-cv-response",".scurl":"text/vnd.curl.scurl",".sda":"application/vnd.stardivision.draw",".sdc":"application/vnd.stardivision.calc",".sdd":"application/vnd.stardivision.impress",".sdkd":"application/vnd.solent.sdkm+xml",".sdkm":"application/vnd.solent.sdkm+xml",".sdp":"application/sdp",".sdw":"application/vnd.stardivision.writer",".see":"application/vnd.seemail",".seed":"application/vnd.fdsn.seed",".sema":"application/vnd.sema",".semd":"application/vnd.semd",".semf":"application/vnd.semf",".ser":"application/java-serialized-object",".setpay":"application/set-payment-initiation",".setreg":"application/set-registration-initiation",".sfd-hdstx":"application/vnd.hydrostatix.sof-data",".sfs":"application/vnd.spotfire.sfs",".sgl":"application/vnd.stardivision.writer-global",".sgm":"text/sgml",".sgml":"text/sgml",".sh":"application/x-sh",".shar":"application/x-shar",".shf":"application/shf+xml",".si":"text/vnd.wap.si",".sic":"application/vnd.wap.sic",".sig":"application/pgp-signature",".silo":"model/mesh",".sis":"application/vnd.symbian.install",".sisx":"application/vnd.symbian.install",".sit":"application/x-stuffit",".sitx":"application/x-stuffitx",".skd":"application/vnd.koan",".skm":"application/vnd.koan",".skp":"application/vnd.koan",".skt":"application/vnd.koan",".sl":"text/vnd.wap.sl",".slc":"application/vnd.wap.slc",".sldm":"application/vnd.ms-powerpoint.slide.macroenabled.12",".sldx":"application/vnd.openxmlformats-officedocument.presentationml.slide",".slt":"application/vnd.epson.salt",".smf":"application/vnd.stardivision.math",".smi":"application/smil+xml",".smil":"application/smil+xml",".snd":"audio/basic",".snf":"application/x-font-snf",".so":"application/octet-stream",".spc":"application/x-pkcs7-certificates",".spf":"application/vnd.yamaha.smaf-phrase",".spl":"application/x-futuresplash",".spot":"text/vnd.in3d.spot",".spp":"application/scvp-vp-response",".spq":"application/scvp-vp-request",".spx":"audio/ogg",".src":"application/x-wais-source",".srx":"application/sparql-results+xml",".sse":"application/vnd.kodak-descriptor",".ssf":"application/vnd.epson.ssf",".ssml":"application/ssml+xml",".stc":"application/vnd.sun.xml.calc.template",".std":"application/vnd.sun.xml.draw.template",".stf":"application/vnd.wt.stf",".sti":"application/vnd.sun.xml.impress.template",".stk":"application/hyperstudio",".stl":"application/vnd.ms-pki.stl",".str":"application/vnd.pg.format",".stw":"application/vnd.sun.xml.writer.template",".sus":"application/vnd.sus-calendar",".susp":"application/vnd.sus-calendar",".sv4cpio":"application/x-sv4cpio",".sv4crc":"application/x-sv4crc",".svd":"application/vnd.svd",".svg":"image/svg+xml",".svgz":"image/svg+xml",".swa":"application/x-director",".swf":"application/x-shockwave-flash",".swi":"application/vnd.arastra.swi",".sxc":"application/vnd.sun.xml.calc",".sxd":"application/vnd.sun.xml.draw",".sxg":"application/vnd.sun.xml.writer.global",".sxi":"application/vnd.sun.xml.impress",".sxm":"application/vnd.sun.xml.math",".sxw":"application/vnd.sun.xml.writer",".t":"text/troff",".tao":"application/vnd.tao.intent-module-archive",".tar":"application/x-tar",".tcap":"application/vnd.3gpp2.tcap",".tcl":"application/x-tcl",".teacher":"application/vnd.smart.teacher",".tex":"application/x-tex",".texi":"application/x-texinfo",".texinfo":"application/x-texinfo",".text":"text/plain",".tfm":"application/x-tex-tfm",".tgz":"application/x-gzip",".tif":"image/tiff",".tiff":"image/tiff",".tmo":"application/vnd.tmobile-livetv",".torrent":"application/x-bittorrent",".tpl":"application/vnd.groove-tool-template",".tpt":"application/vnd.trid.tpt",".tr":"text/troff",".tra":"application/vnd.trueapp",".trm":"application/x-msterminal",".tsv":"text/tab-separated-values",".ttc":"application/x-font-ttf",".ttf":"application/x-font-ttf",".twd":"application/vnd.simtech-mindmapper",".twds":"application/vnd.simtech-mindmapper",".txd":"application/vnd.genomatix.tuxedo",".txf":"application/vnd.mobius.txf",".txt":"text/plain",".u32":"application/x-authorware-bin",".udeb":"application/x-debian-package",".ufd":"application/vnd.ufdl",".ufdl":"application/vnd.ufdl",".umj":"application/vnd.umajin",".unityweb":"application/vnd.unity",".uoml":"application/vnd.uoml+xml",".uri":"text/uri-list",".uris":"text/uri-list",".urls":"text/uri-list",".ustar":"application/x-ustar",".utz":"application/vnd.uiq.theme",".uu":"text/x-uuencode",".vcd":"application/x-cdlink",".vcf":"text/x-vcard",".vcg":"application/vnd.groove-vcard",".vcs":"text/x-vcalendar",".vcx":"application/vnd.vcx",".vis":"application/vnd.visionary",".viv":"video/vnd.vivo",".vor":"application/vnd.stardivision.writer",".vox":"application/x-authorware-bin",".vrml":"model/vrml",".vsd":"application/vnd.visio",".vsf":"application/vnd.vsf",".vss":"application/vnd.visio",".vst":"application/vnd.visio",".vsw":"application/vnd.visio",".vtu":"model/vnd.vtu",".vxml":"application/voicexml+xml",".w3d":"application/x-director",".webm":"video/webm",".wad":"application/x-doom",".wav":"audio/x-wav",".wax":"audio/x-ms-wax",".wbmp":"image/vnd.wap.wbmp",".wbs":"application/vnd.criticaltools.wbs+xml",".wbxml":"application/vnd.wap.wbxml",".wcm":"application/vnd.ms-works",".wdb":"application/vnd.ms-works",".wiz":"application/msword",".wks":"application/vnd.ms-works",".wm":"video/x-ms-wm",".wma":"audio/x-ms-wma",".wmd":"application/x-ms-wmd",".wmf":"application/x-msmetafile",".wml":"text/vnd.wap.wml",".wmlc":"application/vnd.wap.wmlc",".wmls":"text/vnd.wap.wmlscript",".wmlsc":"application/vnd.wap.wmlscriptc",".wmv":"video/x-ms-wmv",".wmx":"video/x-ms-wmx",".wmz":"application/x-ms-wmz",".wpd":"application/vnd.wordperfect",".wpl":"application/vnd.ms-wpl",".wps":"application/vnd.ms-works",".wqd":"application/vnd.wqd",".wri":"application/x-mswrite",".wrl":"model/vrml",".wsdl":"application/wsdl+xml",".wspolicy":"application/wspolicy+xml",".wtb":"application/vnd.webturbo",".wvx":"video/x-ms-wvx",".x32":"application/x-authorware-bin",".x3d":"application/vnd.hzn-3d-crossword",".xap":"application/x-silverlight-app",".xar":"application/vnd.xara",".xbap":"application/x-ms-xbap",".xbd":"application/vnd.fujixerox.docuworks.binder",".xbm":"image/x-xbitmap",".xdm":"application/vnd.syncml.dm+xml",".xdp":"application/vnd.adobe.xdp+xml",".xdw":"application/vnd.fujixerox.docuworks",".xenc":"application/xenc+xml",".xer":"application/patch-ops-error+xml",".xfdf":"application/vnd.adobe.xfdf",".xfdl":"application/vnd.xfdl",".xht":"application/xhtml+xml",".xhtml":"application/xhtml+xml",".xhvml":"application/xv+xml",".xif":"image/vnd.xiff",".xla":"application/vnd.ms-excel",".xlam":"application/vnd.ms-excel.addin.macroenabled.12",".xlb":"application/vnd.ms-excel",".xlc":"application/vnd.ms-excel",".xlm":"application/vnd.ms-excel",".xls":"application/vnd.ms-excel",".xlsb":"application/vnd.ms-excel.sheet.binary.macroenabled.12",".xlsm":"application/vnd.ms-excel.sheet.macroenabled.12",".xlsx":"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",".xlt":"application/vnd.ms-excel",".xltm":"application/vnd.ms-excel.template.macroenabled.12",".xltx":"application/vnd.openxmlformats-officedocument.spreadsheetml.template",".xlw":"application/vnd.ms-excel",".xml":"application/xml",".xo":"application/vnd.olpc-sugar",".xop":"application/xop+xml",".xpdl":"application/xml",".xpi":"application/x-xpinstall",".xpm":"image/x-xpixmap",".xpr":"application/vnd.is-xpr",".xps":"application/vnd.ms-xpsdocument",".xpw":"application/vnd.intercon.formnet",".xpx":"application/vnd.intercon.formnet",".xsl":"application/xml",".xslt":"application/xslt+xml",".xsm":"application/vnd.syncml+xml",".xspf":"application/xspf+xml",".xul":"application/vnd.mozilla.xul+xml",".xvm":"application/xv+xml",".xvml":"application/xv+xml",".xwd":"image/x-xwindowdump",".xyz":"chemical/x-xyz",".zaz":"application/vnd.zzazz.deck+xml",".zip":"application/zip",".zir":"application/vnd.zul",".zirz":"application/vnd.zul",".zmm":"application/vnd.handheld-entertainment+xml"},Qx=[".sh",".exe",".app",".bat",".cmd",".msi",".apk",".jar",".py",".js",".cron",".php",".asp"],IEe=Object.keys(od);import{z as Qi}from"zod";var OEe=Qi.object({id:Qi.string(),name:Qi.string(),createdAt:Qi.coerce.date(),createdBy:Qi.string(),updatedAt:Qi.coerce.date(),updatedBy:Qi.string().nullable(),organizationId:Qi.string()});import{z as V}from"zod";import Zi from"zod";var Gl=Zi.object({platformSep:Zi.string(),fullPathSegments:Zi.string().array(),relativePathSegments:Zi.string().array(),relativePath:Zi.string().describe("path relative to the root test directory, i.e. my-folder/my-test.yaml"),fileName:Zi.string().describe("base name of the file including the extension, e.g. my-module.module.yaml"),lastModified:Zi.coerce.date(),createdAt:Zi.coerce.date()});var IW=V.array(Gl.extend({id:V.string(),name:V.string(),description:V.string().optional(),labels:V.string().array().optional()})),PW=Gl.extend({id:V.string(),name:V.string(),description:V.string().optional(),content:YS}),MW=V.array(PW),WEe=V.object({tests:IW,modules:MW,labels:V.string().array()}),$Ee=_m.merge(zn),Zx=V.object({schemaVersion:V.string(),stepLists:Wi}),e_=zn.partial().merge(Mr.pick({id:!0})),ea="1-255 chars; Only letters/numbers/dashes. Cannot start/end with '-'. Not '.yaml', 'none', or UUID.",lE={name:V.string().min(1).max(255).describe(ea),description:V.string().optional(),baseUrl:V.string().url().optional().describe("For LLM: Ask the user for the base URL if they don't provide it."),environment:V.string().optional().describe("For LLM: Do not include the variable unless the user explicitly asks for it and use the environment lookup tool to get the correct one before passing here."),browserType:V.nativeEnum(So).optional().describe("For LLM: Never assign this variable unless the user explicitly asks for it."),viewport:tm.optional().describe("For LLM: Never assign this variable unless the user explicitly asks for it."),pathSegments:V.string().array().optional().describe("For LLM: Only use if explicitly called for by the user. Used to create the test in the correct folder. Paths are relative to the project root.")},t_=V.object(lE),qEe=_m.merge(V.object({relativeFilePath:V.string().describe("relative to project root")})),r_=V.object({name:V.string()}),KEe=V.object({relativeFilePath:V.string()}),n_=V.object({name:V.string()}),YEe=V.object({relativeFilePath:V.string()}),o_=V.object({name:V.string(),description:V.string(),enabled:V.boolean(),steps:V.lazy(()=>Nt.array()),testFilePath:V.string().describe("relative to the project root"),folderPath:V.string().optional().describe("user selected folder path")}),i_=V.object({name:V.string(),description:V.string(),enabled:V.boolean()}).partial();var XEe=V.array(rw),a_=V.object({defaultEnv:V.string().optional().describe("name of the default env, or undefined to unset")}),s_=V.object({configFilePath:V.string().describe("full path on disk")}),JEe=V.string().array(),QEe=V.object({message:V.string(),newRelativeTestPath:V.string().optional()}),cE=V.object({name:V.string(),absolutePath:V.string(),relativePath:V.string(),pathSegments:V.array(V.string()),isDirectory:V.boolean(),size:V.number(),createdAt:V.coerce.date(),modifiedAt:V.coerce.date(),accessedAt:V.coerce.date()}),l_=V.object({pathSegments:V.array(V.string())}),ZEe=V.object({absolutePath:V.string(),pathSegments:V.array(V.string()),contents:V.array(cE)}),c_=V.object({pathSegments:V.array(V.string())}),u_=V.object({pathSegments:V.array(V.string()),newPathSegments:V.array(V.string())}),d_=V.object({pathSegments:V.array(V.string()),recursive:V.boolean().optional()}),eTe=V.object({success:V.boolean(),message:V.string(),pathSegments:V.array(V.string()).optional()}),tTe=V.object({gitBranch:V.string(),fileMtime:V.coerce.date(),gitCommitSha:V.string()});var Fm=["node_modules","dist","bin",".git",".npm",".next","out",".yarn","__pycache__","build",".env",".venv","venv","env","wheels"],Um=Fm.map(t=>`**/${t}/**`),p_=typeof process<"u"&&!0&&!0,Gn=typeof process<"u"&&!1,m_=2e5;var Bm=58889;import Bo from"chalk";import OW from"safe-stable-stringify";import LW from"truncate-json";import NW from"zod";var as=OW.configure({deterministic:!1});function f_(t){let e=as(t),{jsonString:r}=LW(e,5e4);return r}var DW=["app","version","env","namespace","host"];function ot(t){let e=t.bindings()??{},r={};for(let n of Object.keys(e)){let o=e[n];!DW.includes(n)&&typeof o=="string"&&(r[n]=o)}return r}var uE=NW.enum(["debug","info","warn","error"]);var id={debug:20,info:30,warn:40,error:50},h_={20:"debug",30:"info",40:"warn",50:"error"},ss=class t{minLogLevel;logBindings;constructor(e,r){typeof e=="string"?this.minLogLevel=id[e]:this.minLogLevel=e,this.logBindings=r}logWithLevel(e,r,...n){try{this.logWithLevelHelper(e,r,...n)}catch(o){console.error(`Failed to log to console: ${o}`)}}indentMultiline(e,r=" "){return e.split(`
|
|
20
|
+
Parse error: ${e.error.message}`}throw new Yp(n,{cause:e.error})}var _R=t=>{let e=sG(t);switch(e.type){case"CLICK":return{id:ct(),type:"CLICK",doubleClick:e.doubleClick??void 0,rightClick:e.rightClick??void 0,waitForDownload:e.waitForDownload??void 0,downloadTimeoutMs:e.waitForDownload===!0?e.downloadTimeoutMs??void 0:void 0,delayMs:e.delayMs??void 0,target:{type:"description",elementDescriptor:e.description}};case"TYPE":return{id:ct(),type:"TYPE",value:e.text,target:{type:"description",elementDescriptor:e.description},pressEnter:e.pressEnter??void 0,clearContent:e.clearContent??void 0};case"PRESS":return{id:ct(),type:"PRESS",value:e.keys.join("+")};case"SELECT_OPTION":return{id:ct(),type:"SELECT_OPTION",target:{type:"description",elementDescriptor:`<select> element matching description: ${e.description}`},choice:PS.parse(e.option)};case"NAVIGATE":return{id:ct(),type:"NAVIGATE",url:e.url};case"SCROLL":return e.y>0?{id:ct(),type:"SCROLL_DOWN",deltaY:e.y}:{id:ct(),type:"SCROLL_UP",deltaY:-e.y};case"WAIT":return{id:ct(),type:"WAIT",delay:e.timeout};case"AI_ASSERTION":return{id:ct(),type:"AI_ASSERTION",assertion:e.assertion,timeout:e.timeout};case"HOVER":return{id:ct(),type:"HOVER",target:{type:"description",elementDescriptor:e.description}};case"DRAG":return{id:ct(),type:"DRAG",fromTarget:{type:"description",elementDescriptor:e.fromDescription},toTarget:{type:"description",elementDescriptor:e.toDescription},steps:e.steps??void 0,hoverSeconds:e.hoverSeconds??void 0};case"JAVASCRIPT":return{id:ct(),type:"JAVASCRIPT",code:e.code,environment:e.environment??void 0,timeout:e.timeout??void 0};case"AI_EXTRACT":return{id:ct(),type:"AI_EXTRACT",goal:e.goal,schema:e.schema??void 0,iframeUrl:e.iframeUrl??void 0};case"COPY":return{id:ct(),type:"COPY",value:e.value};case"PASTE":return{id:ct(),type:"PASTE"};case"REFRESH":return{id:ct(),type:"REFRESH"};case"GO_FORWARD":return{id:ct(),type:"GO_FORWARD"};case"LOCAL_STORAGE":return{id:ct(),type:"LOCAL_STORAGE",key:e.key,value:e.value};case"MOUSE_DRAG":return{id:ct(),type:"MOUSE_DRAG",target:e.description?{type:"description",elementDescriptor:e.description}:void 0,deltaX:e.deltaX.toString(),deltaY:e.deltaY.toString(),steps:e.steps??void 0};case"ELEMENT_CHECK":{let r;switch(e.assertionType){case"EXISTS":r={type:"ELEMENT_EXISTENCE",condition:"EXISTS",negated:e.negated??void 0};break;case"VISIBLE":r={type:"ELEMENT_EXISTENCE",condition:"VISIBLE",negated:e.negated??void 0};break;case"CONTENT_CONTAINS":r={type:"ELEMENT_CONTENT",operation:"CONTAINS",value:e.value??"",negated:e.negated??void 0};break;case"CONTENT_EQUALS":r={type:"ELEMENT_CONTENT",operation:"EQUALS",value:e.value??"",negated:e.negated??void 0};break;default:return(o=>{throw"If Typescript complains about the line below, you missed a case or break in the switch above"})(e.assertionType)}return{id:ct(),type:"ELEMENT_CHECK",target:{type:"description",elementDescriptor:e.description},assertion:r,timeout:e.timeout??void 0}}case"PAGE_CHECK":return{id:ct(),type:"PAGE_CHECK",assertion:{type:"CONTENT",value:e.value??void 0,negated:e.negated??void 0},timeout:e.timeout??void 0};case"NEW_TAB":return{id:ct(),type:"NEW_TAB",url:e.url};case"WAIT_FOR_URL":return{id:ct(),type:"WAIT_FOR_URL",matcher:e.matcher,caseInsensitive:e.caseInsensitive??void 0,negated:e.negated??void 0,timeout:e.timeout??void 0};case"GO_BACK":return{id:ct(),type:"GO_BACK"};case"REQUEST":return{id:ct(),type:"REQUEST",url:e.url,method:e.method,headers:e.headers??void 0,params:e.params??void 0,body:e.body?{type:"json",content:e.body}:void 0,timeout:e.timeout??void 0};case"GRAPHQL_REQUEST":return{id:ct(),type:"GRAPHQL_REQUEST",url:e.url,headers:e.headers??void 0,query:e.query,variables:e.variables??void 0,timeout:e.timeout??void 0};case"SET_HEADER":return{id:ct(),type:"SET_HEADER",name:e.name,value:e.value,requestMatcher:e.requestMatcher??void 0};case"REGISTER_REQUEST_LISTENER":return{id:ct(),type:"REGISTER_REQUEST_LISTENER",requestMatcher:e.requestMatcher,key:e.key};case"RECORD_REQUESTS":return{id:ct(),type:"RECORD_REQUESTS",requestMatcher:e.requestMatcher,key:e.key};case"MOCK_ROUTE":return{id:ct(),type:"MOCK_ROUTE",requestMatcher:e.requestMatcher,responseGenerator:e.responseGenerator,fetchOriginalResponse:e.fetchOriginalResponse??void 0,key:e.key??void 0};case"SUCCESS":case"FAILURE":return{id:ct(),type:e.type};default:return(n=>{throw"If Typescript complains about the line below, you missed a case or break in the switch above"})(e)}};import{z as GS}from"zod";import{extendZodWithOpenApi as uG}from"zod-openapi";import{z as IR}from"zod";import{extendZodWithOpenApi as lG}from"zod-openapi";import{z as Vi}from"zod";var Dn=Vi.object({index:Vi.number().optional().describe("global index within a test (in-order traversal)"),id:Vi.string(),skipped:Vi.boolean().optional(),comment:Vi.string().optional(),envKey:Vi.string().optional().describe("key in the environment to save the result of this step to"),aiSuggested:Vi.boolean().optional(),retries:Vi.number().optional()});lG(IR);var cG=Dn.extend({type:IR.literal("PRESET_ACTION")}),hn=cG.extend({command:ml}).openapi({ref:"PresetAction"});uG(GS);var Ga=Dn.extend({type:GS.literal("AI_ACTION"),text:GS.string(),steps:hn.array().optional()}).openapi({ref:"AIAction"});import{z as Wr}from"zod";import{z as gu}from"zod";import{extendZodWithOpenApi as dG}from"zod-openapi";dG(gu);var Su=30,jS=(r=>(r.V2="2",r.V3="3",r))(jS||{}),pG=gu.nativeEnum(jS),El=Dn.extend({type:gu.literal("AI_ACTION_DYNAMIC"),text:gu.string(),retries:gu.number().optional(),version:pG.optional()}).openapi({ref:"AIActionDynamic"});import{z as PR}from"zod";var VS=Dn.extend({type:PR.literal("CONDITIONAL"),skipped:PR.boolean().optional()});import{z as Ye}from"zod";var mG=Ye.object({cacheKey:Ye.string(),cacheExpiryMs:Ye.number()}),WS=Dn.extend({id:Ye.string().uuid().describe("ID of the module step itself. Used to 'namespace' step cache entries."),inputs:Ye.record(Ye.string()).optional(),cacheConfig:mG.optional()}),ho=WS.extend({type:Ye.literal("MODULE"),moduleId:Ye.string().uuid()}),fG=Ye.union([ho.pick({type:!0,moduleId:!0}),Ye.record(Ye.unknown())]),hG=Ye.object({type:Ye.literal("URL_REGEX"),regex:Ye.string()}),gG=Ye.object({type:Ye.literal("PAGE_CHECK"),substring:Ye.string()}),$S=Ye.object({cacheInvalidation:Ye.discriminatedUnion("type",[gG,hG]).optional()}),tn=Ye.object({moduleId:Ye.string().uuid(),name:Ye.string(),description:Ye.string().nullish(),enabled:Ye.boolean().nullish(),parameters:Ye.string().array().nullish(),defaultParameters:Ye.record(Ye.string(),Ye.string()).nullish(),parameterEnums:Ye.record(Ye.string(),Ye.string().array()).nullish(),defaultCacheKey:Ye.string().nullish(),defaultCacheTtl:Ye.number().nullish(),defaultCacheAllInvocations:Ye.boolean().nullish(),autoAuth:Ye.boolean().nullish(),advanced:$S.nullish()});var qS=t=>t.type==="RESOLVED_MODULE";import{z as kn}from"zod";var KS=(n=>(n.ALWAYS="ALWAYS",n.ON_FAILURE="ON_FAILURE",n.ON_ACTION_FAILURE="ON_ACTION_FAILURE",n))(KS||{});var SG=kn.discriminatedUnion("type",[kn.object({type:kn.literal("NAVIGATE_URL"),url:kn.string().url()}),kn.object({type:kn.literal("GO_TO_SECTION_START")})]),yG=kn.object({trigger:kn.nativeEnum(KS).optional(),attempts:kn.number().int().optional(),restartBehavior:SG}),yu=Dn.extend({type:kn.literal("SECTION"),description:kn.string().describe("user provided goal of what the section should accomplish"),plan:kn.string().array().optional(),autohealingConfig:yG.optional()});var MR=tn.merge(WS).extend({type:Wr.literal("RESOLVED_MODULE"),steps:Wr.lazy(()=>Nt.array())}),YS=tn.extend({steps:Wr.lazy(()=>Nt.array())}),XS=yu.extend({steps:Wr.lazy(()=>bt.array())}),EG=yu.extend({steps:Wr.lazy(()=>Nt.array())}),ja=VS.extend({blocks:Wr.object({assertion:Wr.lazy(()=>hn),steps:Wr.lazy(()=>bt.array())}).array(),elseSteps:Wr.lazy(()=>bt.array().optional())}),TG=VS.extend({blocks:Wr.object({assertion:Wr.lazy(()=>hn),steps:Wr.lazy(()=>Nt.array())}).array(),elseSteps:Wr.lazy(()=>Nt.array().optional())}),bt=Wr.discriminatedUnion("type",[hn,Ga,El,ho,ja,XS]),Nt=Wr.discriminatedUnion("type",[hn,Ga,El,MR,TG,EG]);import{z as Fn}from"zod";var bG=Fn.object({steps:bt.array(),beforeSteps:bt.array().nullish(),afterSteps:bt.array().nullish()}),Wi=Fn.object({steps:Nt.array(),beforeSteps:Nt.array().nullish(),afterSteps:Nt.array().nullish()}),Va=Fn.object({steps:Fn.record(Fn.string(),Fn.unknown()).array(),beforeSteps:Fn.record(Fn.string(),Fn.unknown()).array().nullish(),afterSteps:Fn.record(Fn.string(),Fn.unknown()).array().nullish()});var De="1.0.22",JS="0.0.3";import{z as Qp}from"zod";import{z as Wa}from"zod";var vG=/^[a-f0-9]{8}-[a-f0-9]{4}-[1-5][a-f0-9]{3}-[89ab][a-f0-9]{3}-[a-f0-9]{12}$/,dt=t=>{let e=t.trim().toLowerCase().replace(/[^a-z0-9]/g,"-");for(;e.includes("--");)e=e.replaceAll("--","-");return e.startsWith("-")&&(e=e.slice(1)),e.endsWith("-")&&(e=e.slice(0,e.length-1)),e};var ui=Wa.string().min(1).max(255).superRefine((t,e)=>{try{go(t)}catch(r){return e.addIssue({code:Wa.ZodIssueCode.custom,message:r.message,fatal:!0}),Wa.NEVER}});function go(t){if(t=t.toLowerCase().trim(),t.length===0||t.length>255)throw new Error("Name must be between 1 and 255 characters long");if(/[<>:"/\\|?*]/.test(t))throw new Error('Name contains one of the following invalid characters: <>:"/\\|?*');if(t.endsWith("-")||t.startsWith("-"))throw new Error("Name cannot start or end with a dash.");if(t.includes("\0"))throw new Error("Name cannot contain null characters");if(/^(con|prn|aux|nul|com[0-9]|lpt[0-9])(\..*)?$/i.test(t))throw new Error(`"${t}" is a reserved name on Windows and cannot be used as a filename.`);if(/^\.+$/.test(t)||/^\s|\s$/.test(t))throw new Error("Name cannot start or end with a space or dot.");if(t.endsWith(".yaml"))throw new Error('Name cannot end with ".yaml".');if(t==="none")throw new Error("Name cannot be 'none'.");if(t.match(vG))throw new Error("Name cannot be a UUID. Please choose a different name.")}var Jp=Wa.preprocess(t=>t===null?"":t,Wa.union([Wa.string().url(),Wa.literal("")])).optional();var OR=["CLICK","TYPE","PRESS","SELECT_OPTION","DRAG","NAVIGATE","SCROLL","WAIT","AI_ASSERTION","HOVER","BLUR","GO_BACK","GO_FORWARD","REFRESH","NEW_TAB","SWITCH_TAB","WAIT_FOR_URL","COPY","PASTE","ELEMENT_CHECK","PAGE_CHECK","AI_EXTRACT","COOKIE","LOCAL_STORAGE","REQUEST","GRAPHQL_REQUEST","JAVASCRIPT","SET_HEADER","MOCK_ROUTE","REMOVE_ROUTE_MOCK","FILE_UPLOAD","DIALOG","MOUSE_DRAG","MODULE","AI_ACTION_DYNAMIC","CONDITIONAL"],$a=Qp.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)"),LR=Qp.object({id:Qp.string().optional().describe("Recommended way of selecting an entity. The id of the entity to resolve."),name:ui.optional().describe("1-255 chars; Only letters/numbers/dashes. Cannot start/end with '-'. Not '.yaml', 'none', or UUID."),path:Qp.string().optional().describe("The path of the entity to resolve.")}).describe("A selector for a single entity. Exactly one of id, name, or path must be provided. Id is recommended.").refine(t=>[t.id,t.name,t.path].filter(Boolean).length===1,"Exactly one of id, name, or path must be provided.");function NR(t,e){let r=e.parameters??[],n=e.defaultParameters??{},o=e.parameterEnums??{},i=t??{},a=new Set([...r,...Object.keys(n)]),s=Object.keys(i).filter(u=>!a.has(u));if(s.length>0){let u=a.size>0?Array.from(a).join(", "):"none";throw new Error(`Module "${e.name}" received unknown parameters: ${s.join(", ")}. Valid parameters are: ${u}`)}let l=r.filter(u=>!(u in n)).filter(u=>!(u in i));if(l.length>0)throw new Error(`Module "${e.name}" is missing required parameters: ${l.join(", ")}. Please call momentic_module_get to inspect the module's parameter requirements.`);for(let[u,d]of Object.entries(i))if(u in o){let p=o[u];if(p&&!p.includes(d))throw new Error(`Module "${e.name}" parameter "${u}" must be one of: ${p.join(", ")}. Received: "${d}"`)}}var DR=D.object({phrase:D.string()}),Zp=D.object({thoughts:D.string().optional(),result:D.union([D.literal("NOT_FOUND"),D.string(),D.number(),D.array(D.unknown()),D.record(D.unknown(),D.unknown()),D.unknown()])}),ule=D.object({text:D.string()}),AG=D.boolean().or(D.nativeEnum(en)).transform(t=>!(!t||t==="irrelevant")),kR=D.object({attributes:D.array(D.string()).nullish(),text:AG.nullish(),position:D.nativeEnum(en).nullish(),shape:D.nativeEnum(en).nullish()}),CG=D.object({id:D.number().int(),requirements:kR}),RG=CG.array(),em=D.object({thoughts:D.string(),review:D.string().optional(),id:D.number().int(),updatedMemory:eu.optional(),requirements:kR.nullish().transform(t=>{if(t!==null)return t}),additionalElements:RG.nullish().transform(t=>{if(t!==null)return t})});var FR=(m=>(m.NO_DESCRIPTION_PROVIDED="NO_DESCRIPTION_PROVIDED",m.FEW_WORDS="FEW_WORDS",m.STYLE_TAG="STYLE_TAG",m.TYPE_IN_DESCRIPTION="TYPE_IN_DESCRIPTION",m.HARDCODED_ATTRIBUTE="HARDCODED_ATTRIBUTE",m.NONE="NONE",m.AMBIGUOUS_DESCRIPTION="AMBIGUOUS_DESCRIPTION",m.AMBIGUOUS_ASSERTION="AMBIGUOUS_ASSERTION",m.PREFER_PAGE_CHECK="PREFER_PAGE_CHECK",m.PREFER_ASSERTION="PREFER_ASSERTION",m.HTML_ELEMENTS="HTML_ELEMENTS",m.MULTIPLE_ELEMENTS_DESCRIPTION="MULTIPLE_ELEMENTS_DESCRIPTION",m.NEEDS_DATE_VARIABLE="NEEDS_DATE_VARIABLE",m))(FR||{}),UR=(o=>(o.NONE="NONE",o.AMBIGUOUS_DESCRIPTION="AMBIGUOUS_DESCRIPTION",o.COPILOT_MISUSE="COPILOT_MISUSE",o.IRRELEVANT_MESSAGE="IRRELEVANT_MESSAGE",o))(UR||{});var BR=D.object({thoughts:D.string(),category:D.nativeEnum(FR)}),zR=D.object({thoughts:D.string(),category:D.nativeEnum(UR)}),HR=D.object({anyUntestedSteps:D.boolean().describe("True if any steps (especially new/edited) were not fully run (preview + add) or if their immediately following step, if any, was not run."),possibleErrors:D.object({error:D.string(),solutionFound:D.object({description:D.string(),passedSuccessfully:D.boolean().describe("Whether the solution passed successfully")})}).array().describe("Information about any errors we encountered and how we solved them"),safeToContinue:D.boolean().describe("Whether it is safe to continue or if we are stuck and need intervention"),finalReport:D.string().describe("A final summary report of the session, are we stuck, can we go forward, do we need help, or are we good to go?")}),GR=D.object({summary:D.string().describe("Single large block of text summary of the full chat thread; high-signal only."),errorsRanInto:D.array(D.object({error:D.string(),workAround:D.string()})).default([]).describe("List of encountered errors and mitigations."),untestedSteps:D.array(D.string()).default([]).describe("Steps added/discussed but not validated.")}),wG=D.discriminatedUnion("op",[D.object({op:D.literal("replace"),path:D.string(),value:D.string()}),D.object({op:D.literal("add"),path:D.string(),value:D.string()}),D.object({op:D.literal("remove"),path:D.string()})]),dle=D.object({thoughts:D.string(),patches:wG.array()}),xG=[D.literal("add"),D.literal("replace"),D.literal("remove")],_G=D.object({op:D.union(xG),path:D.string(),value:Nt.optional()}),jR=D.object({patches:_G.array(),thoughts:D.string()}),QS=(n=>(n.LEGITIMATE="LEGITIMATE",n.RECOVERABLE="RECOVERABLE",n.INELIGIBLE="INELIGIBLE",n))(QS||{}),VR=D.object({thoughts:D.string(),scenario:D.nativeEnum(QS),instructions:D.string().nullish()}),WR=D.object({reasoning:D.string(),scenario:D.string(),patch:D.null().optional()}),ple=D.object({thoughts:D.string(),evaluation:D.number().min(0).max(10)}),mle=D.object({observations:D.string(),reasoning:D.string(),command:Gp});var ZS=D.object({summary:D.string(),reasoning:D.string(),evaluation:D.discriminatedUnion("type",[D.object({type:D.literal("DONE")}),D.object({type:D.literal("RIGHT_TRACK")}),D.object({type:D.literal("WRONG_TRACK"),feedback:D.string()}),D.object({type:D.literal("IMPOSSIBLE")})])}),IG=D.object({startId:D.number().int(),endId:D.number().int()}),$R=(n=>(n.SIMPLE_CONTENT_BASED_LOCATOR="SIMPLE_CONTENT_BASED_LOCATOR",n.SIMPLE_CONTENT_BASED_ASSERTION="SIMPLE_CONTENT_BASED_ASSERTION",n.OTHER="OTHER",n))($R||{}),qR=D.object({categoryThoughts:D.string(),category:D.nativeEnum($R),relevantSections:IG.array()}),di=D.boolean().nullish().transform(t=>t??!1),KR=D.object({thoughts:D.string().optional(),isPageReady:di,descriptionLabels:D.object({usesTextContent:di,usesAppearance:di,usesPosition:di,usesRelativeElements:di,usesSingleQuotes:di,isAmbiguous:di,targetDoesNotExist:di,usesIcon:di}).optional()});import{z as N}from"zod";import*as Ue from"zod";var Tle=Ue.object({thoughts:Ue.string().optional().describe("only provided if a description was provided"),target:li.optional().describe("only provided if a description was provided"),pageState:Ue.string().optional().describe("serialized a11y tree, only provided if a description was provided"),options:Ue.object({label:Ue.string(),value:Ue.string()}).array().optional().describe("list of options, provided for <select> elements only"),screenshot:Ue.object({data:Ue.string().or(Na),height:Ue.number().int(),width:Ue.number().int()}).optional().describe("only provided if returnScreenshot is true")}),YR=Ue.union([Ue.literal("ELEMENT_CHECK"),Ue.literal("NEGATED_CHECK"),Ue.literal("NEGATED_ELEMENT_VISIBLE_CHECK"),Ue.literal("SELECT_OPTION"),Ue.literal("TYPE")]);function qa(t){if(!("useSelector"in t&&t.useSelector)){if(t.type==="SELECT_OPTION")return"SELECT_OPTION";if(t.type==="TYPE")return"TYPE";if(t.type==="ELEMENT_CHECK"&&t.assertion.type==="ELEMENT_EXISTENCE"&&t.assertion.condition==="EXISTS"&&t.assertion.negated)return"NEGATED_CHECK";if(t.type==="ELEMENT_CHECK"&&t.assertion.type==="ELEMENT_EXISTENCE"&&t.assertion.condition==="VISIBLE"&&t.assertion.negated)return"NEGATED_ELEMENT_VISIBLE_CHECK";if(t.type==="ELEMENT_CHECK")return"ELEMENT_CHECK"}}var Eu=(a=>(a.USER_SELECTOR="USER_SELECTOR",a.CSS_SELECTOR="CSS_SELECTOR",a.HYBRID_SELECTOR="HYBRID_SELECTOR",a.HTML_DISTANCE="HTML_DISTANCE",a.TEMPLATE_MATCHING="TEMPLATE_MATCHING",a.AUTO_FRAME="AUTO_FRAME",a))(Eu||{}),Tl=Ue.object({matched:Ue.boolean(),reason:Ue.string().optional().describe("Human understandable description"),logs:Ue.string().array().optional().describe("Logs for debugging")}),PG=Tl.extend({type:Ue.literal("USER_SELECTOR")}),MG=Tl.extend({type:Ue.literal("CSS_SELECTOR"),selectors:Ue.string().array()}),OG=Tl.extend({type:Ue.literal("HYBRID_SELECTOR")}),LG=Tl.extend({type:Ue.literal("HTML_DISTANCE"),distance:Ue.number().optional(),closestElement:Ue.string().optional(),savedElement:Ue.string().optional()}),NG=Tl.extend({type:Ue.literal("TEMPLATE_MATCHING")}),DG=Tl.extend({type:Ue.literal("AUTO_FRAME"),logs:Ue.string().array().optional()}),XR=Ue.discriminatedUnion("type",[PG,MG,OG,LG,NG,DG]);import{z as vu}from"zod";import{z as YG}from"zod";import*as ue from"zod";import{extendZodWithOpenApi as HG}from"zod-openapi";import{cloneDeep as Tu}from"lodash-es";import nw from"truncate-json";import*as Xa from"zod";import{extendZodWithOpenApi as UG}from"zod-openapi";import{z as Pr}from"zod";import{z as Ce}from"zod";import{z as ey}from"zod";var So=(o=>(o.CHROMIUM="Chromium",o.GOOGLE_CHROME="Google Chrome",o.CHROME_FOR_TESTING="Chrome for Testing",o.ORG_DEFAULT="Org Default",o))(So||{});var tm=ey.object({width:ey.number().min(200).max(1e4),height:ey.number().min(200).max(1e4)}),JR={"Desktop Large":{width:1920,height:1080},"Desktop Small":{width:1280,height:800},iPad:{width:768,height:1024},"Pixel 8":{width:448,height:998},"iPhone 15":{width:393,height:852}},Ale=Object.keys(JR);var Ir=JR["Desktop Large"],$i="en-us",qi="America/Los_Angeles",kG="Chromium",Ki={latitude:37.7749,longitude:-122.4194};function rm({configuredBrowserType:t,orgDefaultBrowserType:e,browserTypeOverride:r}){let n=r??t;return n==="Org Default"&&e?e:n??kG}var nm=(a=>(a.ClipboardRead="clipboard-read",a.ClipboardWrite="clipboard-write",a.Microphone="microphone",a.Camera="camera",a.Geolocation="geolocation",a.LocalNetworkAccess="local-network-access",a))(nm||{});var ty=Ce.object({autoFollowNewTabs:Ce.boolean().optional().describe("Deprecated: Auto-follow new tabs that are opened."),showZeroOpacityElements:Ce.union([Ce.boolean(),Ce.literal("inputs-only")]).optional(),ignoreHrefForCaching:Ce.boolean().optional(),disableSecondaryCacheResolution:Ce.boolean().optional(),hybridSelectorMode:Ce.enum(["off","test","prefer"]).optional(),globalLocatorRedirect:Ce.union([Ce.boolean(),Ce.literal("always")]).optional(),enableForceClickForMissingRedirectElement:Ce.boolean().optional(),visualActions:Ce.boolean().optional(),autoExpandIframes:Ce.boolean().optional(),disableHtmlSnapshots:Ce.boolean().optional(),defaultBrowserType:Ce.nativeEnum(So).optional(),importantAttributes:Ce.string().array().optional(),importantClasses:Ce.string().array().optional(),importantStyles:Ce.string().array().optional()});var QR=1e4,ZR=6e4,FG=Ce.object({server:Ce.string(),username:Ce.string().optional(),password:Ce.string().optional()}),Ka=ty.extend({pageLoadTimeoutMs:Ce.number().optional().refine(t=>t===void 0||t<=ZR&&t>=-1,{message:`Page load timeout must be between 0 and ${ZR/1e3} seconds`}).describe("global page load timeout default for all tests in ms, can still be overridden by individual tests"),smartWaitingTimeoutMs:Ce.number().optional().refine(t=>t===void 0||t<=QR&&t>=-1,{message:`Smart waiting timeout must be between 0 and ${QR/1e3} seconds`}),ignorePageLoadTimeouts:Ce.boolean().optional(),localChromeExtensionPaths:Ce.string().array().optional(),extraHeaders:Ce.record(Ce.string(),Ce.string()).optional().describe("HTTP headers to be sent on every request"),initialLocalStorage:Ce.record(Ce.string(),Ce.record(Ce.string(),Ce.string())).optional().describe("Initial local storage key-value pairs to set per domain on browser startup"),userAgent:Ce.string().optional(),disableGpu:Ce.boolean().optional(),disableZygote:Ce.boolean().optional(),disableBrowserMonitoring:Ce.boolean().optional().describe("Disable console logs and network request recording, which power the console and network tab in the run viewer"),disableConsoleLogs:Ce.boolean().optional().describe("Disable console log recording in the run viewer."),disableNetworkLogs:Ce.boolean().optional().describe("Disable network request recording in the run viewer."),bustCacheOnBoundingBoxChange:Ce.boolean().optional().describe("This setting is deprecated. Bust the cache if no elements are matched that have the same bounding box and location as the original element. This will improve accuracy on sites that use many same components, at the expense of stability and speed."),allowPartialAccessibilityTree:Ce.boolean().optional().describe("Allow fetching the partial accessibility tree if fetching the full tree takes too long."),ignoreHttpsErrors:Ce.boolean().optional().describe("Ignore HTTPS errors, such as self-signed certificates and certificate errors. This can be useful for testing sites that use self-signed certificates or certificate errors."),proxy:FG.optional().describe("HTTP proxy server to use for the entire browser. This can dramatically increase network latency."),disableFullStory:Ce.boolean().optional().describe("Disable FullStory, a third-party analytics tool that can significantly impact browser performance. This can be useful for testing sites that use FullStory."),grantedPermissions:Ce.nativeEnum(nm).array().optional().describe("List of permissions to grant to sites. If not provided, all permissions are granted.")});var ir="BASE_URL",om="CURRENT_URL",Ya="ENV_NAME",bl="TEST_NAME",Ole={[ir]:"https://www.google.com"},ew=Pr.string().describe("Name of the fixture (must be available locally in the fixtures directory)."),tw=Pr.object({name:Pr.string(),variables:Pr.record(Pr.string().describe("variable name"),Pr.string().describe("variable value"))}),rw=Pr.object({name:Pr.string(),variables:Pr.record(Pr.string().describe("variable name"),Pr.unknown().describe("variable value")),browser:Ka.optional()});var Lle=Pr.object({name:Pr.string(),variables:Pr.record(Pr.string().describe("variable name"),Pr.unknown().describe("variable value"))});UG(Xa);var ry=Xa.object({env:Xa.record(Xa.unknown())}).openapi({ref:"TestContextSnapshot"}),BG="\u2022\u2022\u2022\u2022\u2022\u2022\u2022\u2022\u2022\u2022\u2022\u2022\u2022\u2022\u2022",zG=[ir,Ya,bl],ow=[om,ir,Ya,bl],$r=class t{env={};varsFromMomenticEnvironment={};constructor(e){this.reset(e)}static dummyContext(e=void 0,r=void 0,n={}){return new t({baseUrl:"about:blank",currentUrl:"about:blank",testName:e,envName:r,variablesFromEnvironment:n})}static fromSnapshot({snapshot:e,environmentVariables:r}){let n=e.env[ir]??"about:blank",o=e.env[om]??"about:blank",i=e.env[Ya],a=e.env[bl],s={};for(let[l,u]of Object.entries(e.env))ow.includes(l)||(r??{})[l]===void 0&&(s[l]=u);return new t({baseUrl:n,currentUrl:o,dynamicVariables:s,envName:i,testName:a,variablesFromEnvironment:r??{}})}setEnvVariables(e){let r=Tu(e);this.env=Object.assign(this.env,r)}setInputs(e){e&&this.setEnvVariables(e)}setMomenticSystemVariable(e,r){this.varsFromMomenticEnvironment[e]=r}getVariable(e){return this.env[e]}setVariable(e,r){zG.includes(e)||(this.env[e]=r)}getEnvName(){return this.env[Ya]}toObjectCopy(){let e={env:Object.assign({},this.env,this.varsFromMomenticEnvironment)};return Tu(e)}toEditorDisplayCopy(){return this.toObjectCopy()}toRedactedDisplayCopy(){let e=this.toObjectCopy();e.env=Object.fromEntries(Object.entries(e.env).map(([n,o])=>ow.includes(n)||this.varsFromMomenticEnvironment[n]===void 0?[n,o]:[n,BG]));for(let[n,o]of Object.entries(e.env)){if(!o){e.env[n]=o;continue}let{jsonString:i}=nw(JSON.stringify(o),5e3);try{e.env[n]=JSON.parse(i)}catch{e.env[n]=void 0}}let{jsonString:r}=nw(JSON.stringify(e.env),25e3);try{e.env=JSON.parse(r)}catch{e.env={}}return e}setCurrentUrl(e){this.env[om]=e}reset(e){this.env={},this.varsFromMomenticEnvironment={},this.setEnvVariables(e.dynamicVariables??{}),this.setCurrentUrl(e.currentUrl),this.varsFromMomenticEnvironment=Tu(e.variablesFromEnvironment),this.setMomenticSystemVariable(ir,e.baseUrl),e.envName&&this.setMomenticSystemVariable(Ya,e.envName),e.testName&&this.setMomenticSystemVariable(bl,e.testName)}getDynamicVariablesCopy(){return Tu(this.env)}getVariablesFromEnvironmentCopy(){return Tu(this.varsFromMomenticEnvironment)}};var at=(i=>(i.SUCCESS="SUCCESS",i.FAILED="FAILED",i.RUNNING="RUNNING",i.IDLE="IDLE",i.CANCELLED="CANCELLED",i))(at||{}),im=(n=>(n.SUCCESS="SUCCESS",n.FAILED="FAILED",n.CANCELLED="CANCELLED",n))(im||{});HG(ue);var ny=ue.object({beforeUrl:ue.string().optional(),afterUrl:ue.string().optional(),message:ue.string().optional(),beforeSnapshot:ue.string().optional(),afterSnapshot:ue.string().optional(),startedAt:ue.coerce.date(),finishedAt:ue.coerce.date()}),GG=ny.extend({viewport:ue.object({height:ue.number(),width:ue.number()}).nullish(),status:ue.nativeEnum(im),message:ue.string().optional(),elementInteracted:ue.string().optional()}),Ja=ny.extend({status:ue.nativeEnum(at),message:ue.string().optional(),data:ue.unknown().optional(),beforeTestContext:ry.optional(),afterTestContext:ry.optional(),failureReason:ue.nativeEnum(Ne).optional(),details:ue.unknown().describe("Parse using StepExecutionLogSchema.array() to get type safety. We don't explicitly type it because it's non-critical information."),trace:ue.unknown().optional().describe("Web interaction trace from step execution (WebSectionSpan)")}).openapi({ref:"StepResultMetadata"}),oy=(r=>(r.NOT_ELIGIBLE="NOT_ELIGIBLE",r.ATTEMPTED="ATTEMPTED",r))(oy||{}),am=Ja.merge(hn).extend({results:GG.array().describe("Command that was executed. Array is just for consistency with other result types. There should only ever be one item."),previousAttempts:ue.lazy(()=>mr.array()).optional(),failureRecoveryStatus:ue.object({type:ue.nativeEnum(oy),message:ue.string()}).optional()}),jG=Ja.merge(Ga).extend({results:ue.lazy(()=>am.array()),previousAttempts:ue.lazy(()=>mr.array()).optional()}),VG=Ja.merge(El).extend({results:ue.lazy(()=>am.array()),previousAttempts:ue.lazy(()=>mr.array()).optional()}),WG=Ja.merge(ho).extend({moduleName:ue.string().optional(),results:ue.lazy(()=>mr.array()),previousAttempts:ue.lazy(()=>mr.array()).optional()}),$G=Ja.merge(ja).extend({assertionResult:am.optional(),results:ue.lazy(()=>mr.array()).describe("results for the block actually executed"),previousAttempts:ue.lazy(()=>mr.array()).optional()}),qG=Ja.merge(yu).extend({results:ue.lazy(()=>mr.array()),healingAttempts:ue.lazy(()=>mr.array().array()).optional(),previousAttempts:ue.lazy(()=>mr.array()).optional()}),mr=ue.discriminatedUnion("type",[jG,VG,am,WG,$G,qG]),sm=Ja.pick({startedAt:!0,finishedAt:!0,status:!0,message:!0,data:!0}),KG=ny.extend({index:ue.number().optional(),userFacingStepReference:ue.string().optional(),description:ue.string(),pageState:ue.string().optional(),elementInteracted:ue.string().optional(),startedAt:ue.coerce.date().or(ue.string()).optional().catch(void 0),finishedAt:ue.coerce.date().or(ue.string()).optional().catch(void 0)}),lm=KG.extend({beforeScreenshot:ue.string().optional(),afterScreenshot:ue.string().optional()});var iy=YG.object({results:mr.array().describe("main results"),beforeResults:mr.array().optional(),afterResults:mr.array().optional()}),bu=iy.partial();import{z as ee}from"zod";import{extendZodWithOpenApi as rj}from"zod-openapi";import{z as Yi}from"zod";import XG from"zod";var gn=(r=>(r.ANDROID="ANDROID",r.IOS="IOS",r))(gn||{});var iw=XG.nativeEnum(gn);var vl=(n=>(n.WEB="WEB",n.ANDROID="ANDROID",n.IOS="IOS",n))(vl||{});var cm=Yi.object({fromStepId:Yi.string(),parentStepIdChain:Yi.array(Yi.string())}),um=Yi.object({toStepId:Yi.string(),parentStepIdChain:Yi.array(Yi.string())});import{z as St}from"zod";import{isValidCron as JG}from"cron-validator";import{z as Be}from"zod";var aw=["Africa/Abidjan","Africa/Accra","Africa/Algiers","Africa/Bissau","Africa/Cairo","Africa/Casablanca","Africa/Ceuta","Africa/El_Aaiun","Africa/Johannesburg","Africa/Juba","Africa/Khartoum","Africa/Lagos","Africa/Maputo","Africa/Monrovia","Africa/Nairobi","Africa/Ndjamena","Africa/Sao_Tome","Africa/Tripoli","Africa/Tunis","Africa/Windhoek","America/Adak","America/Anchorage","America/Argentina/Buenos_Aires","America/Argentina/Catamarca","America/Argentina/Cordoba","America/Argentina/Jujuy","America/Argentina/La_Rioja","America/Argentina/Mendoza","America/Argentina/Rio_Gallegos","America/Argentina/Salta","America/Argentina/San_Juan","America/Argentina/San_Luis","America/Argentina/Tucuman","America/Argentina/Ushuaia","America/Araguaina","America/Asuncion","America/Atikokan","America/Bahia","America/Bahia_Banderas","America/Barbados","America/Belem","America/Belize","America/Blanc-Sablon","America/Boa_Vista","America/Bogota","America/Boise","America/Cambridge_Bay","America/Campo_Grande","America/Cancun","America/Caracas","America/Cayenne","America/Chicago","America/Chihuahua","America/Costa_Rica","America/Creston","America/Cuiaba","America/Curacao","America/Danmarkshavn","America/Dawson","America/Dawson_Creek","America/Denver","America/Detroit","America/Dominica","America/Edmonton","America/Eirunepe","America/El_Salvador","America/Fort_Nelson","America/Fortaleza","America/Glace_Bay","America/Goose_Bay","America/Grand_Turk","America/Grenada","America/Guadeloupe","America/Guatemala","America/Guayaquil","America/Guyana","America/Halifax","America/Havana","America/Hermosillo","America/Indiana/Indianapolis","America/Indiana/Knox","America/Indiana/Marengo","America/Indiana/Petersburg","America/Indiana/Tell_City","America/Indiana/Vevay","America/Indiana/Vincennes","America/Indiana/Winamac","America/Inuvik","America/Iqaluit","America/Jamaica","America/Juneau","America/Kentucky/Louisville","America/Kentucky/Monticello","America/La_Paz","America/Lima","America/Los_Angeles","America/Maceio","America/Managua","America/Manaus","America/Marigot","America/Martinique","America/Matamoros","America/Mazatlan","America/Menominee","America/Merida","America/Metlakatla","America/Mexico_City","America/Miquelon","America/Moncton","America/Monterrey","America/Montevideo","America/Montserrat","America/Nassau","America/New_York","America/Nipigon","America/Nome","America/Noronha","America/North_Dakota/Beulah","America/North_Dakota/Center","America/North_Dakota/New_Salem","America/Ojinaga","America/Panama","America/Pangnirtung","America/Paramaribo","America/Phoenix","America/Port-au-Prince","America/Port_of_Spain","America/Porto_Velho","America/Puerto_Rico","America/Punta_Arenas","America/Rainy_River","America/Rankin_Inlet","America/Recife","America/Regina","America/Resolute","America/Rio_Branco","America/Santarem","America/Santiago","America/Santo_Domingo","America/Sao_Paulo","America/Scoresbysund","America/Sitka","America/St_Barthelemy","America/St_Johns","America/St_Kitts","America/St_Lucia","America/St_Thomas","America/St_Vincent","America/Swift_Current","America/Tegucigalpa","America/Thule","America/Thunder_Bay","America/Tijuana","America/Toronto","America/Tortola","America/Vancouver","America/Whitehorse","America/Winnipeg","America/Yakutat","America/Yellowknife","Antarctica/Casey","Antarctica/Davis","Antarctica/DumontDUrville","Antarctica/Macquarie","Antarctica/Mawson","Antarctica/Palmer","Antarctica/Rothera","Antarctica/Syowa","Antarctica/Troll","Antarctica/Vostok","Arctic/Longyearbyen","Asia/Aden","Asia/Almaty","Asia/Amman","Asia/Anadyr","Asia/Aqtau","Asia/Aqtobe","Asia/Ashgabat","Asia/Atyrau","Asia/Baghdad","Asia/Bahrain","Asia/Baku","Asia/Bangkok","Asia/Barnaul","Asia/Beirut","Asia/Bishkek","Asia/Brunei","Asia/Chita","Asia/Choibalsan","Asia/Colombo","Asia/Damascus","Asia/Dhaka","Asia/Dili","Asia/Dubai","Asia/Dushanbe","Asia/Famagusta","Asia/Gaza","Asia/Hebron","Asia/Ho_Chi_Minh","Asia/Hong_Kong","Asia/Hovd","Asia/Irkutsk","Asia/Jakarta","Asia/Jayapura","Asia/Jerusalem","Asia/Kabul","Asia/Kamchatka","Asia/Karachi","Asia/Kathmandu","Asia/Khandyga","Asia/Kolkata","Asia/Krasnoyarsk","Asia/Kuala_Lumpur","Asia/Kuching","Asia/Kuwait","Asia/Macau","Asia/Magadan","Asia/Makassar","Asia/Manila","Asia/Muscat","Asia/Nicosia","Asia/Novokuznetsk","Asia/Novosibirsk","Asia/Omsk","Asia/Oral","Asia/Phnom_Penh","Asia/Pontianak","Asia/Pyongyang","Asia/Qatar","Asia/Qostanay","Asia/Qyzylorda","Asia/Riyadh","Asia/Sakhalin","Asia/Samarkand","Asia/Seoul","Asia/Shanghai","Asia/Singapore","Asia/Srednekolymsk","Asia/Taipei","Asia/Tashkent","Asia/Tbilisi","Asia/Tehran","Asia/Thimphu","Asia/Tokyo","Asia/Tomsk","Asia/Ulaanbaatar","Asia/Urumqi","Asia/Ust-Nera","Asia/Vientiane","Asia/Vladivostok","Asia/Yakutsk","Asia/Yangon","Asia/Yekaterinburg","Asia/Yerevan","Atlantic/Azores","Atlantic/Bermuda","Atlantic/Canary","Atlantic/Cape_Verde","Atlantic/Faroe","Atlantic/Madeira","Atlantic/Reykjavik","Atlantic/South_Georgia","Atlantic/Stanley","Australia/Adelaide","Australia/Brisbane","Australia/Broken_Hill","Australia/Currie","Australia/Darwin","Australia/Eucla","Australia/Hobart","Australia/Lindeman","Australia/Lord_Howe","Australia/Melbourne","Australia/Perth","Australia/Sydney","Europe/Amsterdam","Europe/Andorra","Europe/Astrakhan","Europe/Athens","Europe/Belgrade","Europe/Berlin","Europe/Bratislava","Europe/Brussels","Europe/Bucharest","Europe/Budapest","Europe/Busingen","Europe/Chisinau","Europe/Copenhagen","Europe/Dublin","Europe/Gibraltar","Europe/Guernsey","Europe/Helsinki","Europe/Isle_of_Man","Europe/Istanbul","Europe/Jersey","Europe/Kaliningrad","Europe/Kiev","Europe/Kirov","Europe/Lisbon","Europe/Ljubljana","Europe/London","Europe/Luxembourg","Europe/Madrid","Europe/Malta","Europe/Mariehamn","Europe/Minsk","Europe/Monaco","Europe/Moscow","Europe/Oslo","Europe/Paris","Europe/Podgorica","Europe/Prague","Europe/Riga","Europe/Rome","Europe/Samara","Europe/San_Marino","Europe/Sarajevo","Europe/Saratov","Europe/Simferopol","Europe/Skopje","Europe/Sofia","Europe/Stockholm","Europe/Tallinn","Europe/Tirane","Europe/Ulyanovsk","Europe/Uzhgorod","Europe/Vaduz","Europe/Vatican","Europe/Vienna","Europe/Vilnius","Europe/Volgograd","Europe/Warsaw","Europe/Zagreb","Europe/Zaporozhye","Europe/Zurich","Indian/Antananarivo","Indian/Chagos","Indian/Christmas","Indian/Cocos","Indian/Comoro","Indian/Kerguelen","Indian/Mahe","Indian/Maldives","Indian/Mauritius","Indian/Mayotte","Indian/Reunion","Pacific/Apia","Pacific/Auckland","Pacific/Bougainville","Pacific/Chatham","Pacific/Chuuk","Pacific/Easter","Pacific/Efate","Pacific/Enderbury","Pacific/Fakaofo","Pacific/Fiji","Pacific/Funafuti","Pacific/Galapagos","Pacific/Gambier","Pacific/Guadalcanal","Pacific/Guam","Pacific/Honolulu","Pacific/Kiritimati","Pacific/Kosrae","Pacific/Kwajalein","Pacific/Majuro","Pacific/Marquesas","Pacific/Midway","Pacific/Nauru","Pacific/Niue","Pacific/Norfolk","Pacific/Noumea","Pacific/Pago_Pago","Pacific/Palau","Pacific/Pitcairn","Pacific/Pohnpei","Pacific/Port_Moresby","Pacific/Rarotonga","Pacific/Saipan","Pacific/Tahiti","Pacific/Tarawa","Pacific/Tongatapu","Pacific/Wake","Pacific/Wallis"];var sw=1e4,Al=Ka.extend({browserType:Be.nativeEnum(So).optional(),slowMoMs:Be.number().optional().refine(t=>t===void 0||t<=sw&&t>=-1,{message:`Slow motion must be between 0 and ${sw} milliseconds`}),basicAuthorization:Be.object({username:Be.string().optional(),password:Be.string().optional()}).optional(),geolocation:Be.object({latitude:Be.coerce.number().refine(t=>t>=-90&&t<=90,{message:"Latitude must be between -90 and 90 degrees"}),longitude:Be.coerce.number().refine(t=>t>=-180&&t<=180,{message:"Longitude must be between -180 and 180 degrees"})}).optional(),disableJavaScript:Be.boolean().optional(),locale:Be.string().optional(),timezone:Be.enum(aw).optional(),colorScheme:Be.enum(["light","dark"]).optional()}),lw=["extraHeaders","basicAuthorization","localChromeExtensionPaths","proxy"],ay=Be.object({useMemory:Be.boolean().optional(),failureRecovery:Be.boolean().optional().describe("undefined means inherit org settings")}),sy=ay.extend({disableAICaching:Be.boolean().optional(),failureRecoveryInstructions:Be.string().optional()}),QG=Be.object({viewport:tm.optional()}),Qa=QG.merge(sy).merge(Al),Cl=Be.object({cron:Be.string().refine(t=>JG(t),{message:"Invalid cron expression."}).default("0 0 */1 * *"),enabled:Be.boolean().default(!1),env:Be.string().optional(),timeZone:Be.string().default("America/Los_Angeles"),jobKey:Be.string().optional()}),Rl=Be.object({onSuccess:Be.boolean().default(!1),failureMessage:Be.string().optional(),onFailure:Be.boolean().default(!0),successMessage:Be.string().optional()}),ZG=Be.object({name:Be.string(),required:Be.boolean().optional(),defaultValue:Be.string().describe("this is not optional because we need a value when the editor is first loaded")}),dm=ZG.array(),ej=Be.object({name:Be.string(),value:Be.string()}),cw=ej.array(),pm=Be.object({name:Be.string(),default:Be.boolean().optional(),fixtures:ew.array().optional()});var pi=ay.extend({agentConfig:St.record(St.string(),St.string()).optional(),aiFailureAnalysis:St.boolean().optional(),aiPageFiltering:St.boolean().optional().describe("rag v2 feature flag")}),tj=St.object({cliOnly:St.boolean().optional(),neverShowUsageBanner:St.boolean().optional(),hideInternalTraceInfo:St.boolean().optional()}),ly=St.object({fakerConstantSeed:St.boolean().optional(),isolateCachesByEnvironment:St.boolean().optional()}),uw=St.object({ai:pi.optional(),githubAppInstallationId:St.number().nullish(),githubAppSummaryMessageEnabled:St.boolean().nullish(),githubReleaseAppInstallationId:St.number().nullish(),gitlabAppAccessToken:St.string().nullish(),gitlabAppBaseUrl:St.string().nullish(),browser:ty.optional(),internal:tj.optional(),advanced:ly.optional()}),yce=St.object({globalOverrides:St.record(St.string()).optional(),agentConfig:St.record(St.string(),St.string()).optional()}),Ece=St.record(St.string(),St.string()).nullish();rj(ee);var rn={WEBHOOK:"WEBHOOK",CRON:"CRON",MANUAL:"MANUAL",CLI:"CLI"},nt=(s=>(s.PENDING="PENDING",s.RUNNING="RUNNING",s.PASSED="PASSED",s.FAILED="FAILED",s.CANCELLED="CANCELLED",s.RETRYING="RETRYING",s.WAITING_FOR_USER="WAITING_FOR_USER",s))(nt||{}),mm=(r=>(r.BEFORE_ALL="BEFORE_ALL",r.AFTER_ALL="AFTER_ALL",r))(mm||{});var nj=ee.object({attempts:ee.number().int().nonnegative()}),Xt=ee.string().pipe(ee.coerce.date()).or(ee.date()),Za=ee.object({id:ee.string(),runKey:ee.string(),organizationId:ee.string(),executionType:ee.nativeEnum(vl).optional().default("WEB"),createdAt:Xt,createdBy:ee.string(),flake:ee.boolean().nullish(),scheduledAt:Xt.or(ee.null()),startedAt:Xt.or(ee.null()),updatedAt:Xt.nullish(),finishedAt:Xt.or(ee.null()),resolvedBaseUrl:ee.string().nullish(),environmentName:ee.string().nullish(),gitBranchName:ee.string().nullish(),githubRepository:ee.string().nullish(),gitlabProjectPath:ee.string().nullish(),labels:ee.array(ee.string()).optional(),gitOriginUrl:ee.string().nullish(),gitCommitSha:ee.string().nullish(),gitCommitShaShort:ee.string().nullish(),gitCommitAuthorName:ee.string().nullish(),cliVersion:ee.string().nullish(),section:ee.nativeEnum(mm).nullish(),status:ee.nativeEnum(nt),trigger:ee.nativeEnum(rn),attempts:ee.number(),runAttempts:ee.array(ee.object({id:ee.string(),status:ee.nativeEnum(nt),startedAt:Xt.or(ee.null()),finishedAt:Xt.or(ee.null())})).optional(),videos:ee.array(ee.string()).optional(),failureReason:ee.nativeEnum(Ne).nullish(),failureDetails:Kp.nullish(),failureRecoveryDetails:nj.nullish(),pipelineId:ee.string().nullish(),resolvedInputs:ee.record(ee.string(),ee.string()).nullish(),quarantined:ee.boolean().nullish().default(!1),quarantinedReason:ee.string().nullish(),localTestId:ee.string().nullish(),testId:ee.string().nullish(),testName:ee.string().nullish(),description:ee.string().nullish(),directory:ee.string().nullish(),test:ee.object({name:ee.string(),id:ee.string()}).nullish().default(null),suiteId:ee.string().nullish(),aiSettings:pi.nullish()}).openapi({ref:"RunMetadata"}),oj={id:!0,status:!0,testName:!0,localTestId:!0,testId:!0,test:{select:{name:!0,id:!0}},finishedAt:!0,failureReason:!0,failureDetails:!0},fm=Za.pick({...oj,test:!0}),dw=Za.omit({failureReason:!0,failureDetails:!0,test:!0}),cy=Za.extend({stepsSnapshot:ee.array(ee.record(ee.unknown())).nullish(),resolvedInputs:ee.record(ee.string(),ee.string()).nullish(),test:ee.object({name:ee.string(),id:ee.string(),description:ee.string().nullish(),baseUrl:ee.string().nullish(),advanced:Qa.nullish()}).nullish()}).merge(iy),pw=t=>t.includes("PASSED")&&t.includes("FAILED");var ij=vu.object({id:vu.string().uuid(),startedAt:Xt.or(vu.null()),finishedAt:Xt.or(vu.null()),status:vu.nativeEnum(nt)}).merge(bu),Nce=ij.array();var hm=(i=>(i.JUNIT="junit",i.ALLURE="allure",i.ALLURE_JSON="allure-json",i.PLAYWRIGHT_JSON="playwright-json",i.BUILDKITE_JSON="buildkite-json",i))(hm||{});import{z as Dt}from"zod";var mw=Dt.object({id:Dt.string(),status:Dt.nativeEnum(nt),trigger:Dt.nativeEnum(rn),createdAt:Xt,startedAt:Xt.nullish(),finishedAt:Xt.nullish(),gitCommitSha:Dt.string().nullish(),gitCommitShaShort:Dt.string().nullish(),gitCommitTimestamp:Xt.nullish(),gitBranchName:Dt.string().nullish(),gitOriginUrl:Dt.string().nullish(),gitCommitMessage:Dt.string().nullish(),gitCommitAuthorName:Dt.string().nullish(),githubRepository:Dt.string().nullish(),gitlabProjectPath:Dt.string().nullish(),pipelineId:Dt.string().nullish(),ciProvider:Dt.string().nullish(),cliVersion:Dt.string().nullish(),labels:Dt.string().array().optional(),localSuiteName:Dt.string().optional(),suite:Dt.object({id:Dt.string(),name:Dt.string()}).nullish(),runs:Dt.object({status:Dt.nativeEnum(nt)}).array()}).openapi({ref:"RunGroup"}),fw=mw.pick({id:!0,createdAt:!0,startedAt:!0,finishedAt:!0,status:!0,trigger:!0,suite:!0,localSuiteName:!0}).extend({runs:fm.array()}),zce=mw.extend({runs:Za.array()});import{z as ar}from"zod";var aj=ar.object({type:ar.literal("TARGETING"),name:ar.string().optional().describe("Target name to disambiguate for steps with multiple targets"),elementLocationDecisions:XR.array(),pageState:ar.string().optional(),targetSource:ar.nativeEnum(Lo).optional(),targetUpdateTime:ar.string().optional()}),sj=ar.object({type:ar.literal("AI_LOCATION"),matched:ar.boolean(),pageState:ar.string().optional(),ragUsed:ar.boolean().optional(),thoughts:ar.string().optional()}),lj=ar.object({type:ar.literal("ASSERTION"),relevantElementsSerialized:ar.string().array().optional(),pageState:ar.string().optional(),ragUsed:ar.boolean().optional()}),hw=ar.discriminatedUnion("type",[aj,sj,lj]);import{z as Ht}from"zod";var cj=Ht.object({id:Ht.string(),name:Ht.string()}),Yce=cj.merge(Ht.object({createdAt:Xt,createdBy:Ht.string(),schedule:Cl,notification:Rl,environment:Ht.object({name:Ht.string()}).nullish(),beforeTests:Ht.object({id:Ht.string()}).array().nullish(),afterTests:Ht.object({id:Ht.string()}).array().nullish()})),gw=Ht.object({id:Ht.string().uuid(),orgId:Ht.string(),createdAt:Xt,startedAt:Xt.or(Ht.null()),finishedAt:Xt.or(Ht.null()),status:Ht.nativeEnum(nt),trigger:Ht.nativeEnum(rn),suite:Ht.object({id:Ht.string(),name:Ht.string()}).nullish(),runs:Za.array()}),Xce=gw.pick({id:!0,createdAt:!0,startedAt:!0,finishedAt:!0,status:!0,trigger:!0,suite:!0}),Sw=gw.extend({runs:fm.array()});import{z as qr}from"zod";var uy=qr.object({content:qr.string(),ids:qr.string().array(),tokenLength:qr.number()}),uj=qr.object({chunks:uy.array()}),pue=qr.object({ids:qr.string().array(),score:qr.number(),tokenLength:qr.number()}),mue=uj.extend({description:qr.string().describe("Input to pass to RAG engine"),tokenLimit:qr.number()}),yw=qr.object({ids:qr.number().array()}),Ew=qr.object({indices:qr.number().array()});var Gt=N.object({disableCache:N.boolean().optional(),useMemory:N.boolean().optional(),clientMode:N.enum(["interactive","runner"]).optional(),loggerTags:N.record(N.string(),N.string()).optional(),langfuseSessionId:N.string().optional(),agentConfigVersion:N.string().optional()}),vue=Gt.extend({chunks:uy.array(),description:N.string().describe("Input to pass to AI"),type:N.union([N.literal("locator"),N.literal("assertion"),N.literal("ai-action")]),softTokenLimit:N.number(),hardTokenLimit:N.number(),callId:N.string().optional()}),dj=N.object({screenshotBase64AfterCommand:N.string(),urlAfterCommand:N.string(),serializedCommand:N.string(),elementInteracted:N.string().optional(),thoughts:N.string().optional()}),Tw=N.object({goal:N.string(),browserState:N.string(),screenshot:N.string(),source:YR.optional().catch(void 0),isTieBreakerCall:N.boolean().optional(),memory:N.discriminatedUnion("type",[lo,N.object({type:N.literal("RESOLVED_TRACES"),traces:N.unknown().array()})]).optional(),firstPassModelResults:em.array().optional()}),bw=N.object({target:N.string().or(N.number()),browserState:N.string().optional(),screenshot:N.string().optional(),boundingBox:N.object({x:N.number(),y:N.number(),height:N.number(),width:N.number()}).optional()}),vw=N.object({goal:N.string(),browserState:N.string(),screenshot:N.string().optional(),returnSchema:N.string().optional()}),Aw=N.object({goal:N.string(),emulatorState:N.string(),screenshot:N.string().optional(),returnSchema:N.string().optional()}),dy=N.union([N.literal("NEGATED_CHECK"),N.literal("CONDITIONAL_CHECK")]),Cw=N.object({goal:N.string(),browserState:N.string(),screenshot:N.string(),url:N.string(),contextChoice:MS.optional(),memory:N.discriminatedUnion("type",[Da,N.object({type:N.literal("RESOLVED_TRACES"),traces:N.unknown().array()})]).optional(),source:dy.optional()}),Rw=N.object({command:ml}),ww=N.object({message:N.string()}),xw=N.object({messagesAndToolCalls:N.array(N.string())}),_w=N.object({messagesAndToolCalls:N.array(N.string()).describe("Chat history to condense for summarization")}),py=N.object({goal:N.string(),browserState:N.string(),startingScreenshot:N.string().optional(),screenshot:N.string(),url:N.string(),history:dj.array(),actionHint:N.string().optional(),lastError:N.string().optional()}),Iw=N.object({results:lm.array(),errorMessage:N.string(),errorStack:N.string().optional()}),Pw=N.object({results:lm.array(),goal:N.string(),errorMessage:N.string()}),Mw=N.object({failedResults:lm.array(),nextStepsSerialized:N.string().array(),currentUrl:N.string(),currentPageState:N.string(),currentScreenshot:N.string(),customInstructions:N.string().optional(),testDescription:N.string().optional()}),Aue=N.object({description:N.string(),type:N.union([N.literal("locator"),N.literal("assertion"),N.literal("ai-action")]),excerpt:N.string()}),Ow=N.object({type:N.string(),browserContext:N.string(),currentStep:N.string(),screenshot:N.string()}),Lw=N.object({description:N.string(),browserState:N.string(),screenshot:N.string()}),pj=N.enum(["locator","assertion"]),Cue=N.object({completionType:pj,currentGoal:N.string(),pastGoal:N.string().optional(),currentScreenshot:N.string(),pastScreenshot:N.string(),pastResult:N.union([N.boolean(),N.number()])});import{z as Au}from"zod";var xue=Au.object({goal:Au.string()}),Nw=Au.object({keywords:Au.array(Au.string())});import{z as wl}from"zod";var Cu=(o=>(o.LOCATOR="locator",o.ASSERTION="assertion",o.VISUAL_ASSERTION="visual-assertion",o.TEXT_EXTRACTION="text-extraction",o))(Cu||{}),Pue=wl.nativeEnum(Cu),Mue=new Set(Object.values(Cu));var mj=wl.enum(["v1","v2","v3","v4"]),fj=wl.string().regex(/^v\d+\.\d+$/).describe("pinned sub-version like v3.1"),Oue=wl.union([mj,fj,wl.string().describe("for people with special configurations")]),xl={locator:"v3",assertion:"v3","visual-assertion":"v3","text-extraction":"v3"};var Dw=(a=>(a.ANDROID_LOCATOR="android-locator",a.IOS_LOCATOR="ios-locator",a.ANDROID_ASSERTION="android-assertion",a.IOS_ASSERTION="ios-assertion",a.ANDROID_TEXT_EXTRACTION="android-text-extraction",a.IOS_TEXT_EXTRACTION="ios-text-extraction",a))(Dw||{}),Lue=wl.nativeEnum(Dw);import{z as _e}from"zod";import Ku from"zod";import fr from"zod";import tr from"zod";import{v4 as Vpe}from"uuid";import Ij from"zod";import*as U from"zod";var gm=U.discriminatedUnion("type",[U.object({type:U.literal("SCREEN")}),U.object({type:U.literal("OPEN_APP")}),U.object({type:U.literal("OPEN_WEBVIEW")})]),mi=U.object({type:U.literal("description"),description:U.string()}),my=U.object({type:U.literal("CUSTOM_COORDINATES"),startX:U.number().describe("Starting X coordinate in pixels"),startY:U.number().describe("Starting Y coordinate in pixels"),deltaPixels:U.number().describe("Number of pixels to scroll in the specified direction")}),Sm=U.discriminatedUnion("type",[...gm.options,U.object({type:U.literal("CUSTOM"),target:mi}),my]);var hj=U.object({type:U.literal("coordinates"),xPercent:U.number(),yPercent:U.number()}),_l=U.discriminatedUnion("type",[mi,hj]);var fy=U.object({requiredText:U.string().optional(),requiredAttributes:U.record(U.string(),U.string()).optional(),requiredBounds:U.boolean().optional(),position:U.object({x1:U.number(),y1:U.number(),x2:U.number(),y2:U.number(),tolerance:U.nativeEnum(en),preciseTolerance:U.boolean().optional()}).optional(),shape:U.object({width:U.number(),height:U.number(),tolerance:U.nativeEnum(en),preciseTolerance:U.boolean().optional()}).optional()}),kw=U.object({xPath:U.string(),requirements:fy.optional()}),gj=U.object({type:U.literal("CUSTOM"),target:mi,cache:U.lazy(()=>Fw).optional()}),Sj=U.object({pixelDelta:U.number().describe("Number of pixels to scroll in the specified direction"),scrollableElement:U.union([gm,gj,my]),direction:U.enum(["up","down"])}),Fw=U.object({type:U.literal("NATIVE"),bounds:U.number().array().optional(),resolvedDescription:U.string().optional(),xPath:U.string().optional(),elementOnlySerializedXml:U.string().optional(),scrollDetails:Sj.optional(),requirements:fy.optional(),requiredRelatedElements:kw.array().optional(),memory:lo.optional()}),yj=U.object({type:U.literal("WEBVIEW"),resolvedDescription:U.string().optional(),xPath:U.string().optional(),browserCache:li.optional(),memory:lo.optional()}),ym=U.union([Fw,yj]);var Ej=U.object({left:U.number(),top:U.number(),right:U.number(),bottom:U.number()}),Fue=U.object({newViewportBounds:Ej}),Tj=U.object({type:U.literal("CUSTOM"),target:mi,cache:U.lazy(()=>Bw).optional()}),Uw=U.object({pixelDelta:U.number().describe("Number of pixels to scroll in the specified direction"),scrollableElement:U.union([gm,Tj,my]),direction:U.enum(["up","down"])}),Bw=U.object({type:U.literal("NATIVE"),bounds:U.tuple([U.number(),U.number(),U.number(),U.number()]).optional(),resolvedDescription:U.string().optional(),xPath:U.string().optional(),elementOnlySerializedXml:U.string().optional(),scrollDetails:Uw.optional(),requirements:fy.optional(),requiredRelatedElements:kw.array().optional(),memory:lo.optional()}),bj=U.object({type:U.literal("WEBVIEW"),resolvedDescription:U.string().optional(),xPath:U.string().optional(),scrollDetails:Uw.optional(),browserCache:li.optional(),memory:lo.optional()}),Em=U.discriminatedUnion("type",[Bw,bj]);import hy from"zod";import Xi from"zod";var Ge=(R=>(R.AI_CHECK="AI_CHECK",R.AI_EXTRACT="AI_EXTRACT",R.TAP="TAP",R.TYPE="TYPE",R.PRESS="PRESS",R.PRESS_KEYBOARD="PRESS_KEYBOARD",R.OPEN_APP="OPEN_APP",R.KILL_APP="KILL_APP",R.OPEN_NOTIFICATION_DRAWER="OPEN_NOTIFICATION_DRAWER",R.SWIPE="SWIPE",R.SCROLL_TO="SCROLL_TO",R.SCREEN_CHECK="SCREEN_CHECK",R.ELEMENT_CHECK="ELEMENT_CHECK",R.DRAG_AND_DROP="DRAG_AND_DROP",R.JAVASCRIPT="JAVASCRIPT",R.REQUEST="REQUEST",R.WAIT="WAIT",R.ADD_FILE="ADD_FILE",R.INSTALL_APP="INSTALL_APP",R.UNINSTALL_APP="UNINSTALL_APP",R.TOGGLE_SETTINGS="TOGGLE_SETTINGS",R.ROTATE_ORIENTATION="ROTATE_ORIENTATION",R.ADB="ADB",R.STATE="STATE",R))(Ge||{}),ge=Xi.object({id:Xi.string().uuid(),disableCache:Xi.boolean().optional()}),Il=Xi.object({updatedAt:Xi.coerce.date().optional(),updatedAtLoggerTags:Xi.record(Xi.string(),Xi.string()).optional()}),Un=Il.extend({target:ym}),Tm=Il.extend({fromTarget:ym,toTarget:ym}),yo=Il.extend({target:Em}),zw=Il.extend({fromTarget:Em,toTarget:Em});var gy=ge.extend({type:hy.literal("ADB"),command:hy.string(),jsonArgs:hy.string().optional()});import Hw from"zod";var vj=Hw.string().trim(),Sy=ge.extend({type:Hw.literal("INSTALL_APP"),uri:vj});import Aj from"zod";var yy=ge.extend({type:Aj.literal("OPEN_NOTIFICATION_DRAWER")});import Gw from"zod";var Ru=(o=>(o.AIRPLANE_MODE="AIRPLANE_MODE",o.DATA="DATA",o.WIFI="WIFI",o.LOCATION="LOCATION",o))(Ru||{}),Ey=ge.extend({type:Gw.literal("TOGGLE_SETTINGS"),settingsType:Gw.nativeEnum(Ru)});import jw from"zod";var Ty=ge.extend({type:jw.literal("UNINSTALL_APP"),packageName:jw.string()});import $w from"zod";import by from"zod";var vy=ge.extend({type:by.literal("ADD_FILE"),file:by.string(),storageLocation:by.string()});import Ay from"zod";var Pl=ge.extend({type:Ay.literal("AI_CHECK"),assertion:Ay.string(),timeoutSecs:Ay.number().optional(),cache:Il.extend({memory:Da.optional()}).optional()});import Cy from"zod";var Ry=ge.extend({type:Cy.literal("AI_EXTRACT"),goal:Cy.string(),schema:Cy.string().optional()});import wy from"zod";var xy=ge.extend({type:wy.literal("JAVASCRIPT"),code:wy.string(),timeout:wy.number().int().max(60).optional().describe("Max seconds for the code to complete")});import Cj from"zod";var _y=ge.extend({type:Cj.literal("KILL_APP")});import wu from"zod";var es=(r=>(r.HOME="HOME",r.POWER="POWER",r))(es||{}),Ml=(a=>(a.BACK="BACK",a.APP_SWITCHER="APP_SWITCHER",a.SEARCH="SEARCH",a.VOLUME_UP="VOLUME_UP",a.VOLUME_DOWN="VOLUME_DOWN",a.VOLUME_MUTE="VOLUME_MUTE",a))(Ml||{}),xu=ge.extend({type:wu.literal("PRESS"),key:wu.nativeEnum(es),longPress:wu.boolean().optional()}),Iy=xu.extend({key:wu.nativeEnum(Ml).or(wu.nativeEnum(es))}),Py=xu;import Rj from"zod";var My=ge.extend({type:Rj.literal("REQUEST")}).merge(ka);import Vw from"zod";var _u=(r=>(r.PORTRAIT="PORTRAIT",r.LANDSCAPE="LANDSCAPE",r))(_u||{}),Oy=ge.extend({type:Vw.literal("ROTATE_ORIENTATION"),orientation:Vw.nativeEnum(_u)});import Ol from"zod";var wj=Ol.object({type:Ol.literal("CONTENT"),negated:Ol.boolean().optional(),value:Ol.string()}),Ly=ge.extend({type:Ol.literal("SCREEN_CHECK"),assertion:wj,timeout:Ol.number().int().min(0).max(Ba).optional().describe("max seconds to wait for the assertion to be true")});import xj from"zod";var Ny=ge.extend({type:xj.literal("STATE")});import Ww from"zod";var Dy=ge.extend({type:Ww.literal("WAIT"),timeoutSecs:Ww.number()});var Iu=$w.discriminatedUnion("type",[Ny,Pl,Ry,xy,Dy,My,Oy,Ly,vy,_y]),_j=$w.discriminatedUnion("type",[...Iu.options,xu]);import ky from"zod";var qw=ge.extend({type:ky.literal("DRAG_AND_DROP"),fromTarget:mi,toTarget:mi,hoverDuration:ky.number().optional(),dragDuration:ky.number().optional()}),Pu=qw.extend({cache:Tm.optional()}),Mu=qw.extend({cache:zw.optional()});import Kw from"zod";var Yw=ge.extend({type:Kw.literal("ELEMENT_CHECK"),target:_l,assertion:Fp,timeout:Kw.number().int().min(0).max(Ba).optional().describe("max seconds to wait for the assertion to be true")}),Ou=Yw.extend({cache:Un.optional()}),Lu=Yw.extend({cache:yo.optional()});import Nu from"zod";var ts=(r=>(r.ENTER="ENTER",r.BACKSPACE="BACKSPACE",r))(ts||{}),bm=(e=>(e.CLOSE_KEYBOARD="CLOSE_KEYBOARD",e))(bm||{}),Fy=ge.extend({type:Nu.literal("PRESS_KEYBOARD"),key:Nu.nativeEnum(ts)}),Uy=ge.extend({type:Nu.literal("PRESS_KEYBOARD"),key:Nu.nativeEnum(bm).or(Nu.nativeEnum(ts))});import rs from"zod";var By=ge.extend({type:rs.literal("OPEN_APP"),packageName:rs.string(),activityName:rs.string().optional(),intentExtras:rs.string().optional()}),zy=ge.extend({type:rs.literal("OPEN_APP"),packageName:rs.string(),intentExtras:rs.string().optional()});import vm from"zod";var Xw=ge.extend({type:vm.literal("SCROLL_TO"),target:mi,direction:vm.enum(["down","up"]),scrollableElement:Sm,scrollStepPercent:vm.number().min(.1).max(1).optional().describe("How much of the container height to scroll at each step (0.1 to 1.0). Default is 0.8 (80%)."),maxScrollAttempts:vm.number().int().min(1).max(50).optional().describe("Maximum number of scroll attempts before giving up. Default is 5.")}),Du=Xw.extend({cache:Un.optional()}),ku=Xw.extend({cache:yo.optional()});import Am from"zod";var Jw=ge.extend({type:Am.literal("SWIPE"),direction:Am.enum(["up","down","left","right"]),scrollableElement:Sm,viewportPercent:Am.number().optional(),durationMs:Am.number().optional()}),Fu=Jw.extend({cache:Un.optional()}),Uu=Jw.extend({cache:yo.optional()});import Fo from"zod";var Qw=ge.extend({type:Fo.literal("TAP"),target:_l,longPress:Fo.boolean().optional(),longPressDurationMs:Fo.number().optional(),iterations:Fo.number().optional(),tapDelayMs:Fo.number().optional(),relativePosition:Fo.object({x:Fo.number(),y:Fo.number()}).optional(),doubleTap:Fo.boolean().optional(),doubleTapDelayMs:Fo.number().optional()}),Bu=Qw.extend({cache:Un.optional()}),zu=Qw.extend({cache:yo.optional()});import Hu from"zod";var Zw=ge.extend({type:Hu.literal("TYPE"),target:_l.optional(),keyPressDelayMs:Hu.number().optional(),text:Hu.string(),clearContent:Hu.boolean().optional(),forceClearContent:Hu.boolean().optional()});var Gu=Zw.extend({cache:Un.optional()}),ju=Zw.extend({cache:yo.optional()});var Hy=Ij.discriminatedUnion("type",[...Iu.options,Bu,Gu,Iy,Uy,Ty,Sy,gy,Pu,yy,Du,Fu,Ey,Ou,By]);import{v4 as Ime}from"uuid";import Pj from"zod";var Gy=Pj.discriminatedUnion("type",[...Iu.options,zu,ju,Py,Fy,zy,Uu,Mu,ku,Lu]);var Sn=(n=>(n.PRESET="MOBILE_PRESET_STEP",n.MODULE="MOBILE_MODULE_STEP",n.AI_ACTION="MOBILE_AI_ACTION_STEP",n))(Sn||{}),Ll=tr.object({id:tr.string().uuid(),envKey:tr.string().optional(),skipped:tr.boolean().optional(),retries:tr.number().optional()}),rx=Ll.extend({type:tr.literal("MOBILE_PRESET_STEP"),keyPressDelayMs:tr.number().optional()}),Vu=rx.extend({command:Hy}),jy=rx.extend({command:Gy}),Nl=tr.object({moduleId:tr.string(),inputs:tr.record(tr.string(),tr.string()).optional()}),Wu=Ll.merge(Nl.extend({type:tr.literal("MOBILE_MODULE_STEP")})),Vfe=Nl.extend({steps:tr.lazy(()=>$u.array())}),Wfe=Nl.extend({steps:tr.lazy(()=>Vy.array())}),ns=Ll.extend({type:tr.literal("MOBILE_AI_ACTION_STEP"),text:tr.string()}),$u=tr.discriminatedUnion("type",[Vu,Wu,ns]),Vy=tr.discriminatedUnion("type",[jy,Wu,ns]);var qu=fr.object({message:fr.string().optional(),startTime:fr.number(),endTime:fr.number(),status:fr.nativeEnum(at),trace:fr.unknown(),beforeSnapshot:fr.string().optional(),afterSnapshot:fr.string().optional(),data:fr.unknown().optional().describe("output data from the step"),aiSuggested:fr.boolean().optional()}),Oj=qu.merge(Vu).extend({previousAttempts:fr.lazy(()=>Eo.array()).optional()}),Lj=qu.merge(Wu).extend({steps:fr.lazy(()=>Eo.array()),name:fr.string().optional(),previousAttempts:fr.lazy(()=>Eo.array()).optional()}),Nj=qu.merge(ns).extend({steps:fr.lazy(()=>Eo.array()),previousAttempts:fr.lazy(()=>Eo.array()).optional()}),Eo=fr.discriminatedUnion("type",[Oj,Lj,Nj]);var Dj=qu.extend({index:Ku.number().optional(),userFacingStepReference:Ku.string().optional(),description:Ku.string()}),nx=Dj.extend({beforeScreenshot:Ku.string().optional(),afterScreenshot:Ku.string().optional()});var ox=_e.object({attributesRequired:_e.array(_e.string()).optional(),textRequired:_e.boolean().optional(),boundsRequired:_e.boolean().optional(),positionSpecificity:_e.nativeEnum(en).optional(),shapeSpecificity:_e.nativeEnum(en).optional()}),kj=_e.object({thoughts:_e.string(),id:_e.number(),updatedMemory:eu.optional(),inWebview:_e.boolean().optional(),requirements:ox.optional(),additionalElements:_e.object({id:_e.number(),requirements:ox}).array().optional()}),ix=_e.object({description:_e.string(),screenXml:_e.string(),screenshot:_e.string(),memory:_e.discriminatedUnion("type",[lo,_e.object({type:_e.literal("RESOLVED_TRACES"),traces:_e.unknown().array()})]).optional()}),ax=_e.object({assertion:_e.string(),screenXml:_e.string(),screenshot:_e.string(),memory:_e.discriminatedUnion("type",[Da,_e.object({type:_e.literal("RESOLVED_TRACES"),traces:_e.unknown().array()})]).optional()}),Fj=_e.object({thoughts:_e.string(),result:_e.boolean(),relevantElements:_e.array(_e.number()).optional(),updatedMemory:ru.optional()}),sx=_e.object({failedResults:nx.array(),nextStepsSerialized:_e.string().array(),currentScreenXml:_e.string(),currentScreenshot:_e.string(),customInstructions:_e.string().optional(),testDescription:_e.string()}),lx=(n=>(n.LEGITIMATE="LEGITIMATE",n.RECOVERABLE="RECOVERABLE",n.INELIGIBLE="INELIGIBLE",n))(lx||{}),Uj=_e.object({thoughts:_e.string(),scenario:_e.nativeEnum(lx),instructions:_e.string().nullish()});var cx=t=>!(!t.org_id||!t.user_id||!t.platform);import{z as os}from"zod";var ux=os.object({id:os.string().uuid(),skipped:os.boolean().optional(),envKey:os.string().optional().describe("key in the environment to save the result of this step to")}),Wy=ux.merge(ka).extend({type:os.literal("REQUEST")}),$y=ux.merge(Up).extend({type:os.literal("JAVASCRIPT")}),qy=os.discriminatedUnion("type",[$y,Wy]);import{z as Bn}from"zod";var dx=Bn.object({id:Bn.string(),name:ui,description:Bn.string().optional().nullish(),baseUrl:Jp.nullish(),schemaVersion:Bn.string(),advanced:Bn.unknown().optional(),retries:Bn.number(),envs:Bn.array(pm).nullish(),parameters:dm.nullish()}),Bj=Bn.object({createdAt:Bn.coerce.date(),updatedAt:Bn.coerce.date(),schedule:Cl.nullish(),notification:Rl.nullish(),createdBy:Bn.string(),organizationId:Bn.string()}),zj=dx.merge(Bj),_he=zj.extend({steps:qy.array()}),Ihe=dx.extend({steps:qy.array()});import{z as nn}from"zod";var px=nn.object({startedAt:nn.coerce.date(),finishedAt:nn.coerce.date(),status:nn.nativeEnum(at),message:nn.string().optional(),data:nn.unknown().optional()}),Hj=px.merge($y).extend({type:nn.literal("JAVASCRIPT")}),Gj=px.merge(Wy).extend({type:nn.literal("REQUEST")}),jj=nn.discriminatedUnion("type",[Hj,Gj]),mx=nn.object({startedAt:nn.coerce.date(),finishedAt:nn.coerce.date().nullish(),status:nn.nativeEnum(nt),results:jj.array(),failureReason:nn.string().nullish(),failureDetails:Kp.nullish()});import{z as on}from"zod";var Vj=on.object({id:on.string(),organizationId:on.string(),createdAt:on.coerce.date(),updatedAt:on.coerce.date(),createdBy:on.string(),scheduledAt:on.coerce.date().nullish(),startedAt:on.coerce.date().nullish(),finishedAt:on.coerce.date().nullish(),status:on.nativeEnum(nt),trigger:on.nativeEnum(rn),results:mx.array().nullish(),apiTestName:on.string().nullish(),apiTestPath:on.string().nullish(),apiTestId:on.string().nullish()}),Bhe=Vj.pick({status:!0,startedAt:!0,finishedAt:!0});var Yu=(o=>(o.TestRun="test-run",o.MobileTestRun="mobile-test-run",o.CreditsUsed="credits-used",o.CreditsUsedV2="credits-used-v2",o))(Yu||{}),fx=3;function Wj(t){return t==="MODULE"||t==="CONDITIONAL"||t==="SECTION"||t==="RESOLVED_MODULE"}function Ky(t){if(!Wj(t))switch(t){case"PRESET_ACTION":return 0;case"AI_ACTION":return 3;case"AI_ACTION_DYNAMIC":return 5;default:(r=>{throw"If Typescript complains about the line below, you missed a case or break in the switch above"})(t)}}function Yy(t){switch(t.type){case"AI_EXTRACT":case"AI_ASSERTION":return fx;case"CAPTCHA":return 3;case"CLICK":case"TYPE":case"SELECT_OPTION":case"HOVER":case"ELEMENT_CHECK":case"FOCUS":case"BLUR":case"SCROLL_DOWN":case"SCROLL_LEFT":case"SCROLL_RIGHT":case"SCROLL_UP":case"MOUSE_DRAG":return t.useSelector||!t.target||t.target.type!=="description"?0:1;case"DRAG":return t.useSelector?0:1;case"VISUAL_DIFF":case"TAB":case"JAVASCRIPT":case"NAVIGATE":case"WAIT":case"SUCCESS":case"AUTH_LOAD":case"AUTH_SAVE":case"COOKIE":case"DIALOG":case"FILE_UPLOAD":case"GO_BACK":case"GO_FORWARD":case"LOCAL_STORAGE":case"NEW_TAB":case"PAGE_CHECK":case"PRESS":case"KEY_DOWN":case"KEY_UP":case"COPY":case"PASTE":case"REFRESH":case"REQUEST":case"GRAPHQL_REQUEST":case"WAIT_FOR_URL":case"REGISTER_REQUEST_LISTENER":case"AWAIT_LISTENER":case"RECORD_REQUESTS":case"GET_RECORDED_REQUESTS":case"SET_HEADER":case"MOCK_ROUTE":case"REMOVE_ROUTE_MOCK":case"OFFLINE_MODE":return 0;default:(r=>{throw"If Typescript complains about the line below, you missed a case or break in the switch above"})(t)}}var Dl=class{trackStepExecution(){}async flush(){}};import{parseString as $j,splitCookiesString as qj}from"set-cookie-parser";import{z as Ze}from"zod";var Xy=Ze.object({name:Ze.string(),value:Ze.string(),url:Ze.string().optional(),domain:Ze.string().optional(),path:Ze.string().optional(),expires:Ze.number().default(Date.now()/1e3+60*60*24*365),httpOnly:Ze.boolean().optional(),secure:Ze.boolean().default(!0),sameSite:Ze.union([Ze.literal("Strict"),Ze.literal("Lax"),Ze.literal("None")]).default("None")});function Rm(t,e){let r=[],n=qj(t);for(let o of n){let i=$j(o,{decodeValues:!1});if(!i.name)throw new Error("Name missing from cookie");if(!i.value)continue;let a;if(i.sameSite){let u=i.sameSite.trim().toLowerCase();if(u==="strict")a="Strict";else if(u==="lax")a="Lax";else if(u==="none")a="None";else throw new Error(`Invalid sameSite setting in cookie: ${u}`)}i.httpOnly===void 0&&(i.httpOnly=!1),!i.path&&i.domain&&(i.path="/"),!i.domain&&e&&(i.domain=e);let s=Xy.parse({...i,expires:i.expires?i.expires.getTime()/1e3:void 0,sameSite:a});r.push(s);let c=[s.name,...Object.keys(s)].map(u=>u.toLowerCase()),l=o.match(/\b(\S+)=([^;]*)/g);if(l)for(let u of l){let[d,p]=u.split("=");if(!d||!p)throw new Error(`Invalid key-value pair in cookie: ${u}`);c.includes(d.toLowerCase())||r.push({...s,name:d,value:p})}}return r}var Kj=Ze.object({origin:Ze.string(),localStorage:Ze.array(Ze.object({name:Ze.string(),value:Ze.string()})),sessionStorage:Ze.array(Ze.object({name:Ze.string(),value:Ze.string()})).optional()}),Yj=Ze.object({entries:Ze.record(Ze.string(),Ze.array(Ze.tuple([Ze.unknown(),Ze.unknown()]))),version:Ze.number().optional()}),wm=Ze.object({cookies:Xy.array().optional(),origins:Kj.array().optional(),idb:Ze.record(Ze.string(),Yj).optional().describe("key is db name")});function hx(t,e){let r=[];return t.cloneSync()?.serializeSync()?.cookies.forEach(n=>{let o=Xy.safeParse({name:n.key,...n});if(!o.success)return;let i=o.data;!i.domain&&!i.url&&(i.domain=e),r.push(i)}),r}import{v4 as age}from"uuid";import Z from"zod";var Xj=["SCREEN","OPEN_APP","OPEN_WEBVIEW","CUSTOM","CUSTOM_COORDINATES"],gx=Z.object({type:Z.enum(Xj).describe("Where to interact. SCREEN = entire device (use for system surfaces like the notification bar or quick settings), OPEN_APP = current foreground app, OPEN_WEBVIEW = active webview (only if a webview is present and there is high confidence that the element is inside it), CUSTOM = explicitly describe the container if and only if NONE of the above fit, CUSTOM_COORDINATES = use explicit pixel coordinates for the scroll start position and distance (fallback if other containers don't work)."),description:Z.string().or(Z.null()).describe("Description of the container to interact with. Only used if the container type is CUSTOM, else set to null."),startX:Z.number().or(Z.null()).describe("Starting X coordinate in pixels. Only used if the container type is CUSTOM_COORDINATES, else set to null."),startY:Z.number().or(Z.null()).describe("Starting Y coordinate in pixels. Only used if the container type is CUSTOM_COORDINATES, else set to null."),deltaPixels:Z.number().or(Z.null()).describe("Number of pixels to scroll in the specified direction. Only used if the container type is CUSTOM_COORDINATES, else set to null.")}),Jj=Z.object({xPercent:Z.number().min(0).max(1).describe("X coordinate as a fraction of the viewport width (0 = left edge, 1 = right edge)."),yPercent:Z.number().min(0).max(1).describe("Y coordinate as a fraction of the viewport height (0 = top edge, 1 = bottom edge).")}),Qj=Z.string().or(Jj).describe("Either a string description of an actual element in the page XML to target, or an object with xPercent/yPercent (0-1) for coordinate-based targeting when no suitable element exists. Prefer element descriptions when possible."),Sx=Z.object({type:Z.literal("TAP"),target:Qj,longPress:Z.boolean().describe("Whether to hold the tap down before releasing. Useful for triggering context menus."),iterations:Z.null().or(Z.number()).describe("Number of times to tap the element, useful for selecting text, selecting a row, or opening a menu. If null, tap once."),relativePosition:Z.null().or(Z.object({x:Z.number(),y:Z.number()})).describe("Specific position to tap within the bounding box of the element, specified in pixels. E.g. 0,0 is the top left corner. Only applicable when target is a string description.")}).describe("Tap on an element on the screen, or tap at specific coordinates."),Zj=Z.object({type:Z.literal("PRESS"),key:Z.nativeEnum(Ml)}).describe("Press a button on the device. Some buttons are physical (volume) while others are virtual (Back/Home/App Switcher)."),yx=Z.object({type:Z.literal("AI_CHECK"),assertion:Z.string().describe("A natural language assertion to validate. On each attempt, Momentic's AI agents will evaluate the assertion by analyzing the current emulator XML and screenshot. Thus, the assertion must be verifiable based on a single point in time. The assertion will be automatically retried until it is true or the timeout is reached."),timeoutSecs:Z.number().describe("Maximum number of seconds to wait for the assertion to be true.")}).describe("Use AI to verify a statement about the state of the emulator. Will retry up until the timeout, so this can be used as a flexible wait that supports visual, numerical, and logical reasoning."),Ex=Z.object({type:Z.literal("WAIT"),timeoutSecs:Z.number().describe("Number of seconds to wait.")}).describe("Wait for a fixed number of seconds. Use this in these scenarios: 1. Short waits that are expected to be less than 5 seconds almost all the time, which shouldn't warrant an AI call (e.g. an app needs to finish loading, or some contents are suspending); 2. Waits with an obvious deterministic duration (e.g. a 60-second countdown is on the page). For other scenarios, prefer AI_CHECK."),fge=Z.object({type:Z.literal("AI_EXTRACT"),goal:Z.string().describe("Natural language description of what to extract from the current emulator state."),schema:Z.string().or(Z.null()).describe("Optional JSON schema string for the expected output shape. Use null to omit.")}).describe("Use AI to extract structured data from the current emulator state."),Tx=Z.object({type:Z.literal("TYPE"),text:Z.string().describe("Exact type to text, which will be passed to appium's driver.keys() method."),keyPressDelayMs:Z.number().or(Z.null()).describe("Milliseconds to wait between each key press. Useful for triggering auto-complete and other event listeners."),clearContent:Z.boolean().or(Z.null()).describe("Clear the content of the input before typing. Do not set to true if the input is already empty.")}),bx=Z.object({type:Z.literal("SWIPE"),direction:Z.enum(["up","down","left","right"]).describe("Direction to swipe. Important: swiping up will scroll down, and vice versa."),container:gx,viewportPercent:Z.number().min(.1).max(1).or(Z.null()).describe("How much of the container height/width to swipe each time as a decimal (0.1 - 1). Set to null for default (0.8)."),durationMs:Z.number().int().positive().or(Z.null()).describe("Optional swipe duration in milliseconds. Set to null for default.")}).describe("Swipe a single time in a specified direction within a container (screen/app/webview/custom container/custom coordinates)."),vx=Z.object({type:Z.literal("SCROLL_TO"),targetDescription:Z.string().describe("Description of the element to scroll to inside the container."),direction:Z.enum(["down","up"]).describe("Direction to search for the target. Important: this is direction the target is in relative to the current position. E.g. 'down' means the desired element is below the current position."),container:gx,scrollStepPercent:Z.number().min(.1).max(1).or(Z.null()).describe("How much of the container height to scroll at each step (0.1 - 1). Set to null for default (0.8)."),maxScrollAttempts:Z.number().int().min(1).max(50).or(Z.null()).describe("Maximum number of scroll attempts before giving up. Set to null for default (5).")}).describe("Scroll within a container until the described target is visible or we can't scroll anymore. There is no need to repeat the same scroll to command in the same direction multiple times in a row. If a scroll fails, we do not restore the position automatically."),hge=Z.discriminatedUnion("type",[Sx,Zj,yx,Ex,Tx,bx,vx]),eV=Z.object({type:Z.literal("PRESS"),key:Z.nativeEnum(es)}).describe("Press a physical button on the device. Only HOME and POWER are available on iOS."),tV=Z.object({type:Z.literal("PRESS_KEYBOARD"),key:Z.nativeEnum(ts)}).describe("Press a key on the keyboard. Available keys: ENTER, BACKSPACE."),gge=Z.discriminatedUnion("type",[Sx,eV,tV,yx,Ex,Tx,bx,vx]);var Sge={TAP:"Tap on an element on the screen.",TYPE:"Type the specified text into an element.",PRESS:"Press a physical button on the device.",PRESS_KEYBOARD:"Press a button on the keyboard.",SWIPE:"Swipe on the screen.",SCREEN_CHECK:"Assert on the screen content using pre-built conditions.",SCROLL_TO:"Scroll until an element is visible.",DRAG_AND_DROP:"Drag an element onto another element in the same context.",ELEMENT_CHECK:"Assert on an element's state using pre-built conditions, including content, visibility, attribute value checks.",OPEN_APP:"Open an app on the device.",KILL_APP:"Kill an app on the device.",OPEN_NOTIFICATION_DRAWER:"Open the notification drawer.",JAVASCRIPT:"Execute JavaScript code in the emulator.",REQUEST:"Make an HTTP request to a URL.",WAIT:"Wait for a fixed number of seconds. Prefer this for short, deterministic waits; use AI_CHECK for longer or undefined waits.",ADD_FILE:"Add a file to the device's disk.",INSTALL_APP:"Install an app on the device.",UNINSTALL_APP:"Uninstall an app on the device.",TOGGLE_SETTINGS:"Toggle device settings.",ADB:"Execute an ADB command on the device.",STATE:"Capture and return emulator state details.",ROTATE_ORIENTATION:"Rotate the device orientation.",AI_CHECK:"Use AI to verify a statement about the current state of the emulator or wait until a statement is true.",AI_EXTRACT:"Extract data from the emulator state and optionally store it in an environment variable."};var yge=["TAP","TYPE","PRESS","PRESS_KEYBOARD","SWIPE","SCREEN_CHECK","SCROLL_TO","DRAG_AND_DROP","KILL_APP","OPEN_NOTIFICATION_DRAWER","WAIT","TOGGLE_SETTINGS","ROTATE_ORIENTATION","AI_CHECK"];import Ax from"zod";var an={type:!0,cache:!0},Cx=[Pl.pick(an),Ou.pick(an),Bu.pick(an),Gu.pick(an),Fu.pick(an),Du.pick(an),Pu.pick(an)],kl=Ax.discriminatedUnion("type",Cx),Rx=[Pl.pick(an),Lu.pick(an),zu.pick(an),ju.pick(an),Uu.pick(an),Mu.pick(an),ku.pick(an)],wx=Ax.discriminatedUnion("type",Rx);var Dge=Object.values(Ge).filter(t=>Cx.some(e=>e.shape.type.safeParse(t).success));var kge=Object.values(Ge).filter(t=>Rx.some(e=>e.shape.type.safeParse(t).success));function xm(t){switch(t){case"ANDROID":return kl;case"IOS":return wx;default:throw new Error(`Unsupported platform: ${t}`)}}var Fge=fl(kl),Uge=fl(wx);var Bge=za(kl);import xx from"zod";var Xu=(n=>(n.US_WEST_1="us-west1",n.EU_NORTH_1="eu-north1",n.AS_SOUTH_1="as-south1",n))(Xu||{}),_x=(e=>(e.LOCAL="local",e))(_x||{}),Ix=xx.nativeEnum(Xu).or(xx.nativeEnum(_x)),Ju=(r=>(r.ANDROID_14="14",r.ANDROID_15="15",r))(Ju||{});var Jy=(e=>(e.IOS_26="26",e))(Jy||{});import{cloneDeep as Vge}from"lodash-es";import $ge from"truncate-json";import Jt from"zod";import{z as To}from"zod";import{z as xt}from"zod";var Mr=xt.object({id:xt.string(),name:ui,baseUrl:Jp,description:xt.string().optional().nullish(),schemaVersion:xt.string(),advanced:Qa,retries:xt.number().optional().nullish(),envs:xt.array(pm).nullish(),parameters:dm.nullish(),disabled:xt.boolean().optional(),labels:xt.array(xt.string()).optional().catch([])}),Zge=xt.enum(["INHERIT","ENABLED","DISABLED"]);var rV=Qa.extend({failureRecovery:xt.boolean().or(xt.string()).optional().transform(t=>typeof t=="string"?t:t===void 0?"INHERIT":t?"ENABLED":"DISABLED"),useMemory:xt.boolean().or(xt.string()).optional().transform(t=>typeof t=="string"?t:t===void 0?"INHERIT":t?"ENABLED":"DISABLED")});var eSe=Mr.pick({name:!0,description:!0,baseUrl:!0,retries:!0,disabled:!0,parameters:!0}).extend({advanced:rV}),tSe=Mr.pick({name:!0,description:!0,baseUrl:!0,retries:!0,disabled:!0,advanced:!0,parameters:!0}),nV=xt.object({labels:xt.array(xt.string()).optional(),outputs:cw.nullish()}),zn=Mr.merge(nV),oV=xt.object({createdAt:xt.coerce.date(),updatedAt:xt.coerce.date(),updatedBy:xt.string().nullable(),schedule:Cl,notification:Rl,createdBy:xt.string(),organizationId:xt.string(),folderId:xt.string().nullable().optional()}),iV=Mr.merge(oV),rSe=iV.merge(Wi),_m=Mr.merge(Wi),nSe=Mr.merge(Va);var aV="test",sV="module",lV="mobile-test",cV="mobile-module";var ye=(o=>(o.TEST=`momentic/${aV}`,o.MODULE=`momentic/${sV}`,o.MOBILE_TEST=`momentic/${lV}`,o.MOBILE_MODULE=`momentic/${cV}`,o))(ye||{}),uSe=Mr.merge(Va),Qy=tn.extend({steps:To.array(To.record(To.string(),To.unknown())),schemaVersion:To.string()}),dSe=Qy.extend({fileType:To.literal(ye.MODULE)}),pSe=To.object({test:To.string().describe("YAML for the test, including metadata and steps"),modules:To.record(To.string(),To.string()).describe("Map of module name to YAML for the module")});function Im(t){if(t===void 0)return"__undefined__";if(t===null)return null;if(typeof t!="object")return t;if(Array.isArray(t))return t.map(Im);let e={};for(let[r,n]of Object.entries(t))e[r]=Im(n);return e}var Qu=Jt.object({parameterNames:Jt.string().array(),defaultParameters:Jt.record(Jt.string(),Jt.string()).optional(),parameterEnums:Jt.record(Jt.string(),Jt.string().array()).optional()}),uV=Jt.object({moduleId:Jt.string().uuid(),name:Jt.string(),description:Jt.string().nullish(),parameters:Qu.optional(),enabled:Jt.boolean().nullish(),schemaVersion:Jt.string()}),Pm=uV.omit({name:!0}),Mx=Pm.extend({steps:Jt.array(Jt.record(Jt.string(),Jt.unknown()))}),dV=Jt.object({fileType:Jt.literal(ye.MOBILE_MODULE)}).merge(Mx);import Oe from"zod";import*as Fl from"zod";var TSe=Fl.custom().refine(t=>t&&t.length>0).refine(t=>t&&t[0]instanceof File,{message:"Please upload a valid file."}),Zy=Fl.preprocess(t=>{if(typeof t!="string")return t;let e=t.trim();return e.length===0?void 0:e},Fl.string().optional());import fi from"zod";var hi=(e=>(e.MODULE="RESOLVED_MOBILE_MODULE",e))(hi||{}),Ox=fi.object({description:fi.string().optional(),name:fi.string().describe("name of the module"),parameters:Qu.optional()}),eE=Nl.merge(Ox).extend({steps:fi.lazy(()=>is.array())}),pV=Nl.merge(Ox).extend({steps:fi.lazy(()=>Zu.array())}),mV=Ll.merge(eE).extend({type:fi.literal("RESOLVED_MOBILE_MODULE")}),fV=Ll.merge(pV).extend({type:fi.literal("RESOLVED_MOBILE_MODULE")}),is=fi.discriminatedUnion("type",[mV,Vu,ns]),Zu=fi.discriminatedUnion("type",[fV,jy,ns]);function Lx(t){return Object.values(hi).includes(t)||Object.values(Sn).includes(t)}var hV=Oe.object({disableMomenticAccessibilityTree:Oe.boolean().optional(),autoGrantPermissions:Oe.boolean().optional(),disableXmlSnapshots:Oe.boolean().optional().describe("Skip collecting XML snapshots during test runs. This can speed up test runs, but will cause the run viewer to show less information."),browserSettings:Al.optional()}),tE=hV.extend({region:Ix.optional().describe("Do you want local or Limbar?"),remoteEmulatorSettings:Oe.object({androidVersion:Oe.nativeEnum(Ju).optional()}).optional(),localEmulatorSettings:Oe.object({avdId:Zy}).optional(),geolocation:Oe.object({latitude:Oe.coerce.number().refine(t=>t>=-90&&t<=90,{message:"Latitude must be between -90 and 90 degrees"}),longitude:Oe.coerce.number().refine(t=>t>=-180&&t<=180,{message:"Longitude must be between -180 and 180 degrees"})}).optional(),waitForStability:Oe.boolean().optional().describe("wait for stability before every targeting action")}),Ul=Oe.object({retries:Oe.number().optional().describe("number of retries to run"),defaultChannel:Oe.string().optional().describe("Default app release channel to use when installing from managed mobile artifacts."),defaultTag:Oe.string().optional().describe("Default app artifact tag to use. If not set, the latest available tag is used."),defaultEnv:Oe.string().optional().describe("Default mobile environment name to load variables from at runtime."),defaultApkFilePath:Zy.describe("APK to install when using the emulator in the local region."),emulator:tE.optional().describe("Emulator configuration for local or remote mobile execution, including region and local emulator overrides."),ai:sy.optional().describe("AI behavior overrides for this mobile test, such as memory and failure recovery settings.")}),Nx=Oe.object({id:Oe.string().uuid(),description:Oe.string(),schemaVersion:Oe.string(),settings:Ul.optional(),disabled:Oe.boolean().optional(),labels:Oe.array(Oe.string()).optional()}),Mm=Nx.extend({platform:Oe.literal("ANDROID").optional().default("ANDROID")}),Om=Nx.extend({platform:Oe.literal("IOS")}),rE=Oe.discriminatedUnion("platform",[Mm,Om]),Dx=Oe.object({fileType:Oe.literal(ye.MOBILE_TEST)}),Lm=Dx.merge(Mm),Nm=Dx.merge(Om),zSe=Oe.discriminatedUnion("platform",[Lm,Nm]),kx=Mm.merge(Oe.object({steps:Oe.array($u)})),Fx=Om.merge(Oe.object({steps:Oe.array(Vy)})),HSe=Oe.discriminatedUnion("platform",[kx,Fx]),gV=Lm.merge(kx),SV=Nm.merge(Fx),yV=Oe.discriminatedUnion("platform",[gV,SV]),GSe=Oe.object({name:Oe.string(),steps:Oe.array($u).optional(),settings:Ul.optional()}),Ux=Mm.extend({steps:is.array()}),Bx=Om.extend({steps:Zu.array()}),jSe=Oe.discriminatedUnion("platform",[Ux,Bx]),EV=Ux.extend({name:Oe.string()}),TV=Bx.extend({name:Oe.string()}),bV=Oe.discriminatedUnion("platform",[EV,TV]);import ke from"zod";import re from"zod";var sn=re.object({startTime:re.number(),endTime:re.number().optional(),durationMs:re.number().optional(),error:re.string().optional(),result:re.unknown().optional(),attributes:re.record(re.string(),re.unknown()),subSpans:re.lazy(()=>DV.array())});var nE=sn.extend({type:re.literal("SECTION"),name:re.string()}),vV=sn.extend({type:re.literal("GET_PAGE_STATE")}),AV=sn.extend({type:re.literal("GET_PAGE_SCREENSHOT")}),CV=sn.extend({type:re.literal("SMART_WAITING")}),RV=sn.extend({type:re.literal("SCROLL_ELEMENT_INTO_VIEW")}),wV=sn.extend({type:re.literal("AI_LOCATOR_CALL"),screenshotSnapshotId:re.string().optional(),result:re.object({id:re.number(),thoughts:re.string()}).optional()}),xV=sn.extend({type:re.literal("AI_ASSERTION_CALL"),screenshotSnapshotId:re.string().optional(),elementScreenshotSnapshotId:re.string().optional(),result:re.object({thoughts:re.string(),result:re.boolean()}).optional()}),_V=sn.extend({type:re.literal("ELEMENT_ASSERTION"),name:re.string(),result:re.object({success:re.boolean(),message:re.string().optional()}).optional()}),IV=sn.extend({type:re.literal("BROWSER_INTERACTION"),name:re.string(),coordinates:re.object({x:re.number(),y:re.number()}).optional(),value:re.string().optional(),selector:re.string().optional()}),PV=sn.extend({type:re.literal("CACHE_RESOLUTION"),resolutionMethod:re.string().optional(),cacheMissReason:re.nativeEnum(nl).optional(),targetSource:re.string().optional(),result:re.object({serializedElement:re.string()}).optional()}),MV=sn.extend({type:re.literal("TARGET_RESOLUTION"),elementScreenshotSnapshotId:re.string().optional(),result:re.object({serializedElement:re.string()}).optional()}),OV=sn.extend({type:re.literal("LOCATOR_REDIRECT"),elementScreenshotSnapshotId:re.string().optional(),result:re.object({outcome:re.string(),logs:re.string().array().optional(),serializedElement:re.string().optional(),relativeClickPoint:re.object({x:re.number(),y:re.number()}).optional(),force:re.boolean().optional()}).optional()}),LV=sn.extend({type:re.literal("WAIT_FOR_STABILITY")}),NV=sn.extend({type:re.literal("GENERIC"),name:re.string()}),DV=re.discriminatedUnion("type",[nE,vV,AV,CV,RV,wV,xV,_V,IV,MV,PV,OV,LV,NV]);var Hn=ke.object({startTime:ke.number(),endTime:ke.number().optional(),durationMs:ke.number().optional(),error:ke.string().optional(),result:ke.unknown().optional(),attributes:ke.record(ke.string(),ke.unknown()),subSpans:ke.lazy(()=>KV.array())});var kV=Hn.extend({type:ke.literal("SECTION"),name:ke.string()}),FV=Hn.extend({type:ke.literal("AI_LOCATOR_CALL"),result:ke.object({id:ke.number(),thoughts:ke.string()}).optional()}),UV=Hn.extend({type:ke.literal("AI_ASSERTION_CALL"),result:ke.object({thoughts:ke.string(),result:ke.boolean()}).optional()}),BV=Hn.extend({type:ke.literal("TARGET_RESOLUTION"),result:ke.object({serializedElement:ke.string()}).optional()}),zV=Hn.extend({type:ke.literal("EMULATOR_INTERACTION"),name:ke.string(),withinWebview:ke.boolean().optional()}),HV=Hn.extend({type:ke.literal("EMULATOR_READ_STATE"),name:ke.string()}),GV=Hn.extend({type:ke.literal("ELEMENT_ASSERTION"),name:ke.string(),result:ke.object({success:ke.boolean(),message:ke.string().optional()}).optional()}),jV=Hn.extend({type:ke.literal("CACHE_RESOLUTION")}),VV=Hn.extend({type:ke.literal("WAIT_FOR_SCREENSHOT_STABILITY")}),WV=Hn.extend({type:ke.literal("WAIT_FOR_PAGE_STABILITY")}),$V=Hn.extend({type:ke.literal("WEBVIEW_LOCATOR_CALL"),webTrace:nE}),qV=Hn.extend({type:ke.literal("GENERIC"),name:ke.string()}),KV=ke.discriminatedUnion("type",[kV,FV,UV,BV,zV,HV,GV,jV,VV,WV,$V,qV]);import{parse as ZSe}from"date-fns";import{z as Bl}from"zod";var tye=Bl.object({testId:Bl.string(),sessionId:Bl.string()}),zx=Bl.object({uploadUrl:Bl.string(),id:Bl.string()});import YV from"zod";var Hx=(r=>(r.LOCAL="local",r.REMOTE="remote",r))(Hx||{}),oye=YV.nativeEnum(Hx);var kye=new Set(Object.values(rt));var XV={AI_ACTION:"AI action",AI_ACTION_DYNAMIC:"AI action",CONDITIONAL:"Conditional",RESOLVED_MODULE:"Module",AI_ASSERTION:"AI check",AI_EXTRACT:"AI extract",CLICK:"Click",TYPE:"Type",JAVASCRIPT:"JavaScript",SELECT_OPTION:"Select",PRESS:"Press",KEY_DOWN:"Key down",KEY_UP:"Key up",NAVIGATE:"Navigate",SCROLL_UP:"Scroll up",SCROLL_DOWN:"Scroll down",SCROLL_LEFT:"Scroll left",SCROLL_RIGHT:"Scroll right",HOVER:"Hover",BLUR:"Blur",FILE_UPLOAD:"File upload",FOCUS:"Focus",GO_BACK:"Go back",GO_FORWARD:"Go forward",WAIT:"Wait",REFRESH:"Refresh",TAB:"Switch tab",NEW_TAB:"New tab",COOKIE:"Cookie",LOCAL_STORAGE:"localStorage",REQUEST:"API request",GRAPHQL_REQUEST:"GraphQL request",CAPTCHA:"CAPTCHA",DRAG:"Drag & drop",VISUAL_DIFF:"Visual diff",DIALOG:"Dialog",MOUSE_DRAG:"Mouse drag",AUTH_LOAD:"Load auth state",AUTH_SAVE:"Save auth state",ELEMENT_CHECK:"Element check",PAGE_CHECK:"Page check",WAIT_FOR_URL:"Wait for URL",COPY:"Copy",PASTE:"Paste",REGISTER_REQUEST_LISTENER:"Register request listener",AWAIT_LISTENER:"Await listener",RECORD_REQUESTS:"Record requests",GET_RECORDED_REQUESTS:"Get recorded requests",SET_HEADER:"Set header",MOCK_ROUTE:"Mock route",REMOVE_ROUTE_MOCK:"Remove route mock",OFFLINE_MODE:"Offline mode",SUCCESS:"Done"},Fye={AI_ACTION:["ai","action","agent"],AI_ACTION_DYNAMIC:["ai","action","dynamic","agent"],CONDITIONAL:["conditional","if","else","elif","branch"],RESOLVED_MODULE:[],AI_ASSERTION:["ai","check","assert","make sure","ensure"],AI_EXTRACT:["ai","extract","data"],CLICK:["click","press"],TYPE:["type","input","write","press"],JAVASCRIPT:["js","javascript","code","execute"],SELECT_OPTION:["select","option","choose"],PRESS:["keyboard","type","key"],KEY_DOWN:["keyboard","type","key","down","press"],KEY_UP:["keyboard","type","key","up","press"],NAVIGATE:["go to","visit"],SCROLL_UP:[],SCROLL_DOWN:[],SCROLL_LEFT:[],SCROLL_RIGHT:[],HOVER:["scroll into view","go to"],BLUR:[],FILE_UPLOAD:[],FOCUS:[],GO_BACK:[],GO_FORWARD:[],WAIT:[],REFRESH:[],TAB:[],NEW_TAB:[],COOKIE:[],LOCAL_STORAGE:[],REQUEST:[],GRAPHQL_REQUEST:[],CAPTCHA:[],DRAG:[],VISUAL_DIFF:[],DIALOG:[],MOUSE_DRAG:[],AUTH_LOAD:[],AUTH_SAVE:[],ELEMENT_CHECK:[],PAGE_CHECK:[],WAIT_FOR_URL:[],COPY:[],PASTE:[],REGISTER_REQUEST_LISTENER:[],AWAIT_LISTENER:[],RECORD_REQUESTS:[],GET_RECORDED_REQUESTS:[],SET_HEADER:[],MOCK_ROUTE:[],REMOVE_ROUTE_MOCK:[],OFFLINE_MODE:[],SUCCESS:[]},mt={AI_ACTION:"Ask AI achieve a specific goal. Saves the steps for reuse. Please use Dynamic AI action instead.",AI_ACTION_DYNAMIC:"Ask AI achieve a specific goal. Fully dynamic and does not save the steps for reuse. Our most capable AI agent.",CONDITIONAL:"Execute steps based on the outcome of a conditional check",RESOLVED_MODULE:"A list of steps that can be reused in multiple tests.",AI_ASSERTION:"Ask AI to verify whether something is true on the page.",CLICK:"Click on an element on the page.",DIALOG:"Specify how native browser dialogs should be handled.",AI_EXTRACT:"Ask AI to extract data from the page.",HOVER:"Hover over an element on the page.",FILE_UPLOAD:"Automatically upload a file when the native file upload dialog is activated.",FOCUS:"Focus an element on the page.",BLUR:"Remove focus from an element on the page.",SELECT_OPTION:"Select an option from an HTML Select <select> element.",TYPE:"Type the specified text into an element.",PRESS:"Press the specified keys using the keyboard. (e.g. Control+A)",KEY_DOWN:"Hold down the specified keys on the keyboard. (e.g. Control+A)",KEY_UP:"Release the specified keys on the keyboard. (e.g. Control+A)",NAVIGATE:"Navigate to the specified URL.",SCROLL_UP:"Scroll up by a specified height.",SCROLL_DOWN:"Scroll down by a specified height.",SCROLL_LEFT:"Scroll left by a specified width.",SCROLL_RIGHT:"Scroll right by a specified width.",GO_BACK:"Go back in browser history.",GO_FORWARD:"Go forward in browser history.",WAIT:"Wait for the specified number of seconds.",REFRESH:"Refresh the page. This will not clear cookies or session data.",TAB:"Switch to different tab in the browser.",NEW_TAB:"Create and switch to a new tab in the browser.",COOKIE:"Set a cookie that will persist throughout the browser session.",LOCAL_STORAGE:"Set a localStorage value that will persist throughout the browser session",CAPTCHA:"Solve CAPTCHAs on the page. This feature is only available on Momentic Cloud and may take up to 60 seconds. Disabling CAPTCHAs in non-production environments is strongly advised.",REQUEST:"Make an API request to a URL.",GRAPHQL_REQUEST:"Make a GraphQL request to a URL.",JAVASCRIPT:"Run JavaScript code in the browser or a Node.js environment.",DRAG:"Click and drag an element to another location.",VISUAL_DIFF:"Compare a screenshot of the page or a specific element to a baseline image.",MOUSE_DRAG:"Click and drag the mouse by a specified distance.",AUTH_LOAD:"Load or clear session state using a JavaScript object including cookies, localStorage, and IndexDB entries.",AUTH_SAVE:"Save authentication state (cookies, localStorage) into a JavaScript object.",ELEMENT_CHECK:"Assert on an element's state using pre-built conditions, including content, visibility, attribute value checks.",PAGE_CHECK:"Assert on the active page's contents using pre-built conditions.",WAIT_FOR_URL:"Wait for the active page's URL to match a target value or pattern.",COPY:"Copy the specified value to the browser clipboard.",PASTE:"Paste the browser clipboard contents.",REGISTER_REQUEST_LISTENER:"Register a listener for network requests.",AWAIT_LISTENER:"Wait for a listener to fire, and return the response data.",RECORD_REQUESTS:"Record network requests that match a given pattern.",GET_RECORDED_REQUESTS:"Get recorded requests that matched the pattern.",SET_HEADER:"Set a header.",MOCK_ROUTE:"Mock network requests to a specific URL.",REMOVE_ROUTE_MOCK:"Remove a previously set route mock.",OFFLINE_MODE:"Configure offline mode.",SUCCESS:"Indicate the entire AI action has succeeded, optionally based on a condition."},Uye={AI_CHECK:"AI check",AI_EXTRACT:"AI extract",RESOLVED_MOBILE_MODULE:"Module",MOBILE_AI_ACTION_STEP:"AI action",TAP:"Tap",TYPE:"Type",PRESS:"Press button",PRESS_KEYBOARD:"Press keyboard",SWIPE:"Swipe",SCROLL_TO:"Scroll to",DRAG_AND_DROP:"Drag & drop",SCREEN_CHECK:"Screen check",ELEMENT_CHECK:"Element check",OPEN_APP:"Open app",KILL_APP:"Kill app",OPEN_NOTIFICATION_DRAWER:"Open notification drawer",JAVASCRIPT:"JavaScript",REQUEST:"API request",WAIT:"Wait",ADD_FILE:"Add file",INSTALL_APP:"Install app",UNINSTALL_APP:"Uninstall app",TOGGLE_SETTINGS:"Toggle settings",ROTATE_ORIENTATION:"Rotate orientation",ADB:"ADB command",STATE:"Debug state"},Bye={MOBILE_AI_ACTION_STEP:"Ask AI to accomplish a high-level goal by generating other steps.",RESOLVED_MOBILE_MODULE:"A list of steps that can be reused in multiple tests.",TAP:"Tap on an element on the screen.",TYPE:"Type the specified text into an element.",PRESS:"Press a physical button on the device.",PRESS_KEYBOARD:"Press a special key on the keyboard.",SWIPE:"Swipe on the screen.",SCREEN_CHECK:"Assert on the screen content using pre-built conditions.",SCROLL_TO:"Scroll until an element is visible.",DRAG_AND_DROP:"Drag an element onto another element in the same context.",ELEMENT_CHECK:"Assert on an element's state using pre-built conditions, including content, visibility, attribute value checks.",OPEN_APP:"Open an app on the device.",KILL_APP:"Terminate the currently active app and remove it from recents.",OPEN_NOTIFICATION_DRAWER:"Open the notification drawer.",JAVASCRIPT:"Execute JavaScript code in a NodeJS context.",REQUEST:"Make an HTTP request to a URL.",WAIT:"Wait for a specified amount of time.",ADD_FILE:"Add a file to the device's disk.",INSTALL_APP:"Install one or more APKs onto the connected emulator (local emulator only).",UNINSTALL_APP:"Uninstall an APK from the connected emulator (local emulator only).",TOGGLE_SETTINGS:"Toggle device settings.",ROTATE_ORIENTATION:"Rotate the device orientation to portrait or landscape.",ADB:"Execute an ADB command on the device.",STATE:"Capture and return emulator state details.",AI_CHECK:"Ask AI to verify whether something is true on the screen.",AI_EXTRACT:"Ask AI to extract data from the emulator state."};import JV from"semver";import{z as QV}from"zod";var jye=QV.string().refine(t=>JV.valid(t),{message:"must be a valid semver string"});function zl(t){if(t!==void 0)return t===!0||t==="true"||t==="1"}import{Faker as $ye,en as qye}from"@faker-js/faker";import{z as $}from"zod";var Hl=55555,Yye=$.object({body:$.string(),to:$.string(),from:$.string()}),Xye=$.object({from:$.string().optional(),to:$.string(),timeout:$.number().optional(),beforeDate:$.string().pipe($.coerce.date()).or($.date()).optional(),afterDate:$.string().pipe($.coerce.date()).or($.date()).optional()}),Jye=$.object({to:$.string().email(),from:$.string(),subject:$.string(),body:$.string(),html:$.string().optional()}),Qye=$.object({inbox:$.string().transform(t=>t.toLowerCase()),afterDate:$.string().pipe($.coerce.date()).or($.date()).optional(),timeout:$.number().optional(),trimWhitespace:$.boolean().optional()}),Zye=$.object({inbox:$.string(),limit:$.number().optional(),afterDate:$.string().pipe($.coerce.date()).or($.date()).optional(),trimWhitespace:$.boolean().optional()});var Dm=(r=>(r.RAW="RAW",r.RESPONSE="RESPONSE",r))(Dm||{}),Gx=$.object({body:$.string().nullish(),status:$.number().optional(),headers:$.array($.tuple([$.string(),$.string()])).optional()}),ZV=$.object({url:$.string(),options:$.object({method:$.string(),body:$.string().nullish(),headers:$.array($.tuple([$.string(),$.string()])).optional()}).optional()}).optional(),eW=$.object({body:$.string().nullish(),options:$.object({status:$.number(),statusText:$.string().optional(),headers:$.array($.tuple([$.string(),$.string()])).optional()}).optional()}).optional(),jx=$.object({result:$.unknown(),variableUpdates:$.record($.string(),$.unknown()).optional(),persistentVariableUpdates:$.record($.string(),$.unknown()).optional(),error:$.string().optional(),success:$.boolean()}),eEe=$.object({id:$.string().optional(),orgId:$.string(),momenticLambdaAuthHash:$.string(),code:$.string(),fragment:$.boolean(),state:$.object({env:$.record($.string(),$.unknown()),request:ZV,response:eW,additionalBindings:$.record($.string(),$.unknown()).optional()}),timeoutMs:$.number().optional(),disallowVariableUpdates:$.boolean().optional(),responseSerialization:$.nativeEnum(Dm).optional()}),Ji=15e3;import*as Or from"zod";import{extendZodWithOpenApi as tW}from"zod-openapi";tW(Or);var rW=Or.object({url:Or.string(),lineNumber:Or.number(),columnNumber:Or.number()}).openapi({ref:"CodeLocation"}),km=Or.object({timestamp:Or.number(),text:Or.string(),type:Or.string(),tabIndex:Or.number(),args:Or.unknown().array().optional(),url:Or.string().optional(),location:rW.optional()}).openapi({ref:"ConsoleLog"}),Vx=km.array(),oE=Vx.array();import*as iE from"zod";import{extendZodWithOpenApi as nW}from"zod-openapi";nW(iE);var oW=iE.object({logsPerPage:km.array().array()}).openapi({ref:"DebugData"});import*as Ot from"zod";import{extendZodWithOpenApi as iW}from"zod-openapi";iW(Ot);var Wx=Ot.object({total:Ot.number(),user:Ot.number(),sys:Ot.number(),intervalMs:Ot.number()}),aW=Ot.object({total:Ot.number(),free:Ot.number(),freePercentage:Ot.number()}),sW=Ot.object({rss:Ot.number(),heapTotal:Ot.number(),heapUsed:Ot.number(),external:Ot.number(),arrayBuffers:Ot.number()}),$x=Ot.object({timestamp:Ot.number(),system:Ot.object({cpu:Wx.nullable(),memory:aW}),process:Ot.object({cpu:Wx.nullable(),memory:sW})}).openapi({ref:"ResourceUsageSample"}),lW=Ot.object({samples:$x.array()}).openapi({ref:"ResourceUsageSeries"});var ed=class{async getConsoleLogsForRunAttempt(e,r,n){}async getNetworkLogsForRunAttempt(e,r,n){}async getHtmlSnapshot(e,r){}async getA11yTreeSnapshot(e,r){}async getScreenshot(e,r){}async storeConsoleLogsForRunAttempt(e,r,n,o){}async storeNetworkLogsForRunAttempt(e,r,n,o){}listVideoAssetPaths(){return[]}close(){}async storeScreenshot(e,r,n){}async storeOnDemandScreenshotById(e,r,n,o){}async storeHtmlSnapshot(e,r,n){}};import{z as k}from"zod";var cW=k.object({name:k.string(),version:k.string(),comment:k.string().optional()}),uW=k.object({name:k.string(),version:k.string(),comment:k.string().optional()}),dW=k.object({onContentLoad:k.number().optional(),onLoad:k.number().optional(),comment:k.string().optional()}),td=k.object({startedDateTime:k.string(),id:k.string(),title:k.string().optional(),pageTimings:dW,comment:k.string().optional()}),pW=k.array(td),mW=k.object({name:k.string(),value:k.string(),path:k.string().optional(),domain:k.string().optional(),expires:k.string().optional(),httpOnly:k.boolean().optional(),secure:k.boolean().optional(),comment:k.string().optional()}),Kx=k.array(mW),fW=k.object({name:k.string(),value:k.string(),comment:k.string().optional()}),Yx=k.array(fW),hW=k.object({name:k.string(),value:k.string(),comment:k.string().optional()}),gW=k.array(hW),SW=k.object({name:k.string(),value:k.string().optional(),fileName:k.string().optional(),contentType:k.string().optional(),comment:k.string().optional()}),yW=k.array(SW),EW=k.object({mimeType:k.string(),params:yW,text:k.string(),comment:k.string().optional(),_redactedReason:k.string().optional()}),TW=k.object({method:k.string(),url:k.string(),httpVersion:k.string().optional(),cookies:Kx,headers:Yx,queryString:gW,postData:EW.optional(),headersSize:k.number().optional(),bodySize:k.number().optional(),comment:k.string().optional()}),bW=k.object({size:k.number().optional(),compression:k.number().optional(),mimeType:k.string().optional(),text:k.string().optional(),encoding:k.string().optional(),comment:k.string().optional(),_redactedReason:k.string().optional()}),vW=k.object({status:k.number(),statusText:k.string(),httpVersion:k.string().optional(),cookies:Kx,headers:Yx,content:bW,redirectURL:k.string().optional(),headersSize:k.number().optional(),bodySize:k.number().optional(),comment:k.string().optional(),_mocked:k.boolean().optional()}),qx=k.object({expires:k.string().optional(),lastAccess:k.string(),eTag:k.string(),hitCount:k.number(),comment:k.string().optional()}),AW=k.object({beforeRequest:qx.optional(),afterRequest:qx.optional(),comment:k.string().optional()}),CW=k.object({blocked:k.number().optional(),dns:k.number().optional(),connect:k.number().optional(),send:k.number(),wait:k.number(),receive:k.number(),ssl:k.number().optional(),comment:k.string().optional()}),rd=k.object({pageref:k.string().optional(),startedDateTime:k.string(),time:k.number().optional(),request:TW,response:vW.optional(),cache:AW.optional(),timings:CW,serverIPAddress:k.string().optional(),connection:k.string().optional(),comment:k.string().optional(),_resourceType:k.string().optional()}),RW=k.array(rd),wW=k.object({version:k.string().default("1.1"),creator:cW.optional(),browser:uW.optional(),pages:pW.optional(),entries:RW,comment:k.string().optional()}),xW=k.object({log:wW}),hEe=k.record(k.string(),td),gEe=k.record(k.string(),rd);function aE(t,e){return{log:{version:"1.2",creator:{name:"Momentic, Inc.",version:"1.0.0"},pages:Object.values(t).sort((r,n)=>new Date(r.startedDateTime).getTime()-new Date(n.startedDateTime).getTime()),entries:Object.values(e).sort((r,n)=>new Date(r.startedDateTime).getTime()-new Date(n.startedDateTime).getTime())}}}var Xx=t=>{throw new Error(`Exhaustive check failed for value: ${t}`)};import{cloneDeep as _W}from"lodash-es";import{z as Uo}from"zod";var sE=(d=>(d.DisableClickhouseCaches="disable_clickhouse_caches",d.ShowZeroOpacityElements="show_zero_opacity_elements",d.VisualActions="visual_actions",d.RagV2="rag_v2",d.DisableSecondaryCacheResolution="disable_secondary_cache_resolution",d.GlobalLocatorRedirect="global_locator_redirect",d.FakerConstantSeed="faker_constant_seed",d.AutoExpandIframes="auto_expand_iframes",d.NewAiActionStepsUseV3="new_ai_action_steps_use_v3",d.PerformanceInsights="performance_insights",d.IosTests="ios_tests",d))(sE||{});var Jx=Uo.union([Uo.string(),Uo.number(),Uo.boolean(),Uo.null(),Uo.record(Uo.string(),Uo.lazy(()=>Jx)),Uo.array(Uo.lazy(()=>Jx))]),nd=class{flags;payloads;constructor(e,r){this.flags=e,this.payloads=r}isBooleanFlagEnabled(e){return process.env&&process.env[`MOMENTIC_FLAG_OVERRIDE_${e.toUpperCase()}`]==="true"?!0:process.env&&process.env[`MOMENTIC_FLAG_OVERRIDE_${e.toUpperCase()}`]==="false"?!1:this.flags[e]===!0}getAllFlags(){let e=_W(this.flags);return Object.entries(e).forEach(([r,n])=>{typeof n=="boolean"&&Object.values(sE).includes(r)&&(e[r]=this.isBooleanFlagEnabled(r))}),e}getFlagPayload(e){let r=this.payloads[e];if(r!==void 0){if(typeof r=="string")try{return JSON.parse(r)}catch{return r}return r}}refresh(){throw new Error("Not implemented")}},_Ee=new nd({},{});var od={".123":"application/vnd.lotus-1-2-3",".3dml":"text/vnd.in3d.3dml",".3g2":"video/3gpp2",".3gp":"video/3gpp",".a":"application/octet-stream",".aab":"application/x-authorware-bin",".aac":"audio/x-aac",".aam":"application/x-authorware-map",".aas":"application/x-authorware-seg",".abw":"application/x-abiword",".acc":"application/vnd.americandynamics.acc",".ace":"application/x-ace-compressed",".acu":"application/vnd.acucobol",".acutc":"application/vnd.acucorp",".adp":"audio/adpcm",".aep":"application/vnd.audiograph",".afm":"application/x-font-type1",".afp":"application/vnd.ibm.modcap",".ai":"application/postscript",".aif":"audio/x-aiff",".aifc":"audio/x-aiff",".aiff":"audio/x-aiff",".air":"application/vnd.adobe.air-application-installer-package+zip",".ami":"application/vnd.amiga.ami",".apk":"application/vnd.android.package-archive",".application":"application/x-ms-application",".apr":"application/vnd.lotus-approach",".asc":"application/pgp-signature",".asf":"video/x-ms-asf",".asm":"text/x-asm",".aso":"application/vnd.accpac.simply.aso",".asx":"video/x-ms-asf",".atc":"application/vnd.acucorp",".atom":"application/atom+xml",".atomcat":"application/atomcat+xml",".atomsvc":"application/atomsvc+xml",".atx":"application/vnd.antix.game-component",".au":"audio/basic",".avi":"video/x-msvideo",".aw":"application/applixware",".azf":"application/vnd.airzip.filesecure.azf",".azs":"application/vnd.airzip.filesecure.azs",".azw":"application/vnd.amazon.ebook",".bat":"application/x-msdownload",".bcpio":"application/x-bcpio",".bdf":"application/x-font-bdf",".bdm":"application/vnd.syncml.dm+wbxml",".bh2":"application/vnd.fujitsu.oasysprs",".bin":"application/octet-stream",".bmi":"application/vnd.bmi",".bmp":"image/bmp",".book":"application/vnd.framemaker",".box":"application/vnd.previewsystems.box",".boz":"application/x-bzip2",".bpk":"application/octet-stream",".btif":"image/prs.btif",".bz":"application/x-bzip",".bz2":"application/x-bzip2",".c":"text/x-c",".c4d":"application/vnd.clonk.c4group",".c4f":"application/vnd.clonk.c4group",".c4g":"application/vnd.clonk.c4group",".c4p":"application/vnd.clonk.c4group",".c4u":"application/vnd.clonk.c4group",".cab":"application/vnd.ms-cab-compressed",".car":"application/vnd.curl.car",".cat":"application/vnd.ms-pki.seccat",".cc":"text/x-c",".cct":"application/x-director",".ccxml":"application/ccxml+xml",".cdbcmsg":"application/vnd.contact.cmsg",".cdf":"application/x-netcdf",".cdkey":"application/vnd.mediastation.cdkey",".cdx":"chemical/x-cdx",".cdxml":"application/vnd.chemdraw+xml",".cdy":"application/vnd.cinderella",".cer":"application/pkix-cert",".cgm":"image/cgm",".chat":"application/x-chat",".chm":"application/vnd.ms-htmlhelp",".chrt":"application/vnd.kde.kchart",".cif":"chemical/x-cif",".cii":"application/vnd.anser-web-certificate-issue-initiation",".cil":"application/vnd.ms-artgalry",".cla":"application/vnd.claymore",".class":"application/java-vm",".clkk":"application/vnd.crick.clicker.keyboard",".clkp":"application/vnd.crick.clicker.palette",".clkt":"application/vnd.crick.clicker.template",".clkw":"application/vnd.crick.clicker.wordbank",".clkx":"application/vnd.crick.clicker",".clp":"application/x-msclip",".cmc":"application/vnd.cosmocaller",".cmdf":"chemical/x-cmdf",".cml":"chemical/x-cml",".cmp":"application/vnd.yellowriver-custom-menu",".cmx":"image/x-cmx",".cod":"application/vnd.rim.cod",".com":"application/x-msdownload",".conf":"text/plain",".cpio":"application/x-cpio",".cpp":"text/x-c",".cpt":"application/mac-compactpro",".crd":"application/x-mscardfile",".crl":"application/pkix-crl",".crt":"application/x-x509-ca-cert",".csh":"application/x-csh",".csml":"chemical/x-csml",".csp":"application/vnd.commonspace",".css":"text/css",".cst":"application/x-director",".csv":"text/csv",".cu":"application/cu-seeme",".curl":"text/vnd.curl",".cww":"application/prs.cww",".cxt":"application/x-director",".cxx":"text/x-c",".daf":"application/vnd.mobius.daf",".dataless":"application/vnd.fdsn.seed",".davmount":"application/davmount+xml",".dcr":"application/x-director",".dcurl":"text/vnd.curl.dcurl",".dd2":"application/vnd.oma.dd2+xml",".ddd":"application/vnd.fujixerox.ddd",".deb":"application/x-debian-package",".def":"text/plain",".deploy":"application/octet-stream",".der":"application/x-x509-ca-cert",".dfac":"application/vnd.dreamfactory",".dic":"text/x-c",".diff":"text/plain",".dir":"application/x-director",".dis":"application/vnd.mobius.dis",".dist":"application/octet-stream",".distz":"application/octet-stream",".djv":"image/vnd.djvu",".djvu":"image/vnd.djvu",".dll":"application/x-msdownload",".dmg":"application/octet-stream",".dms":"application/octet-stream",".dna":"application/vnd.dna",".doc":"application/msword",".docm":"application/vnd.ms-word.document.macroenabled.12",".docx":"application/vnd.openxmlformats-officedocument.wordprocessingml.document",".dot":"application/msword",".dotm":"application/vnd.ms-word.template.macroenabled.12",".dotx":"application/vnd.openxmlformats-officedocument.wordprocessingml.template",".dp":"application/vnd.osgi.dp",".dpg":"application/vnd.dpgraph",".dsc":"text/prs.lines.tag",".dtb":"application/x-dtbook+xml",".dtd":"application/xml-dtd",".dts":"audio/vnd.dts",".dtshd":"audio/vnd.dts.hd",".dump":"application/octet-stream",".dvi":"application/x-dvi",".dwf":"model/vnd.dwf",".dwg":"image/vnd.dwg",".dxf":"image/vnd.dxf",".dxp":"application/vnd.spotfire.dxp",".dxr":"application/x-director",".ecelp4800":"audio/vnd.nuera.ecelp4800",".ecelp7470":"audio/vnd.nuera.ecelp7470",".ecelp9600":"audio/vnd.nuera.ecelp9600",".ecma":"application/ecmascript",".edm":"application/vnd.novadigm.edm",".edx":"application/vnd.novadigm.edx",".efif":"application/vnd.picsel",".ei6":"application/vnd.pg.osasli",".elc":"application/octet-stream",".eml":"message/rfc822",".emma":"application/emma+xml",".eol":"audio/vnd.digital-winds",".eot":"application/vnd.ms-fontobject",".eps":"application/postscript",".epub":"application/epub+zip",".es3":"application/vnd.eszigno3+xml",".esf":"application/vnd.epson.esf",".et3":"application/vnd.eszigno3+xml",".etx":"text/x-setext",".exe":"application/x-msdownload",".ext":"application/vnd.novadigm.ext",".ez":"application/andrew-inset",".ez2":"application/vnd.ezpix-album",".ez3":"application/vnd.ezpix-package",".f":"text/x-fortran",".f4v":"video/x-f4v",".f77":"text/x-fortran",".f90":"text/x-fortran",".fbs":"image/vnd.fastbidsheet",".fdf":"application/vnd.fdf",".fe_launch":"application/vnd.denovo.fcselayout-link",".fg5":"application/vnd.fujitsu.oasysgp",".fgd":"application/x-director",".fh":"image/x-freehand",".fh4":"image/x-freehand",".fh5":"image/x-freehand",".fh7":"image/x-freehand",".fhc":"image/x-freehand",".fig":"application/x-xfig",".fli":"video/x-fli",".flo":"application/vnd.micrografx.flo",".flv":"video/x-flv",".flw":"application/vnd.kde.kivio",".flx":"text/vnd.fmi.flexstor",".fly":"text/vnd.fly",".fm":"application/vnd.framemaker",".fnc":"application/vnd.frogans.fnc",".for":"text/x-fortran",".fpx":"image/vnd.fpx",".frame":"application/vnd.framemaker",".fsc":"application/vnd.fsc.weblaunch",".fst":"image/vnd.fst",".ftc":"application/vnd.fluxtime.clip",".fti":"application/vnd.anser-web-funds-transfer-initiation",".fvt":"video/vnd.fvt",".fzs":"application/vnd.fuzzysheet",".g3":"image/g3fax",".gac":"application/vnd.groove-account",".gdl":"model/vnd.gdl",".geo":"application/vnd.dynageo",".gex":"application/vnd.geometry-explorer",".ggb":"application/vnd.geogebra.file",".ggt":"application/vnd.geogebra.tool",".ghf":"application/vnd.groove-help",".gif":"image/gif",".gim":"application/vnd.groove-identity-message",".gmx":"application/vnd.gmx",".gnumeric":"application/x-gnumeric",".gph":"application/vnd.flographit",".gqf":"application/vnd.grafeq",".gqs":"application/vnd.grafeq",".gram":"application/srgs",".gre":"application/vnd.geometry-explorer",".grv":"application/vnd.groove-injector",".grxml":"application/srgs+xml",".gsf":"application/x-font-ghostscript",".gtar":"application/x-gtar",".gtm":"application/vnd.groove-tool-message",".gtw":"model/vnd.gtw",".gv":"text/vnd.graphviz",".gz":"application/x-gzip",".h":"text/x-c",".h261":"video/h261",".h263":"video/h263",".h264":"video/h264",".hbci":"application/vnd.hbci",".hdf":"application/x-hdf",".hh":"text/x-c",".hlp":"application/winhlp",".hpgl":"application/vnd.hp-hpgl",".hpid":"application/vnd.hp-hpid",".hps":"application/vnd.hp-hps",".hqx":"application/mac-binhex40",".htke":"application/vnd.kenameaapp",".htm":"text/html",".html":"text/html",".hvd":"application/vnd.yamaha.hv-dic",".hvp":"application/vnd.yamaha.hv-voice",".hvs":"application/vnd.yamaha.hv-script",".icc":"application/vnd.iccprofile",".ice":"x-conference/x-cooltalk",".icm":"application/vnd.iccprofile",".ico":"image/x-icon",".ics":"text/calendar",".ief":"image/ief",".ifb":"text/calendar",".ifm":"application/vnd.shana.informed.formdata",".iges":"model/iges",".igl":"application/vnd.igloader",".igs":"model/iges",".igx":"application/vnd.micrografx.igx",".iif":"application/vnd.shana.informed.interchange",".imp":"application/vnd.accpac.simply.imp",".ims":"application/vnd.ms-ims",".in":"text/plain",".ipk":"application/vnd.shana.informed.package",".irm":"application/vnd.ibm.rights-management",".irp":"application/vnd.irepository.package+xml",".iso":"application/octet-stream",".itp":"application/vnd.shana.informed.formtemplate",".ivp":"application/vnd.immervision-ivp",".ivu":"application/vnd.immervision-ivu",".jad":"text/vnd.sun.j2me.app-descriptor",".jam":"application/vnd.jam",".jar":"application/java-archive",".java":"text/x-java-source",".jisp":"application/vnd.jisp",".jlt":"application/vnd.hp-jlyt",".jnlp":"application/x-java-jnlp-file",".joda":"application/vnd.joost.joda-archive",".jpe":"image/jpeg",".jpeg":"image/jpeg",".jpg":"image/jpeg",".jpgm":"video/jpm",".jpgv":"video/jpeg",".jpm":"video/jpm",".js":"application/javascript",".json":"application/json",".kar":"audio/midi",".karbon":"application/vnd.kde.karbon",".kfo":"application/vnd.kde.kformula",".kia":"application/vnd.kidspiration",".kil":"application/x-killustrator",".kml":"application/vnd.google-earth.kml+xml",".kmz":"application/vnd.google-earth.kmz",".kne":"application/vnd.kinar",".knp":"application/vnd.kinar",".kon":"application/vnd.kde.kontour",".kpr":"application/vnd.kde.kpresenter",".kpt":"application/vnd.kde.kpresenter",".ksh":"text/plain",".ksp":"application/vnd.kde.kspread",".ktr":"application/vnd.kahootz",".ktz":"application/vnd.kahootz",".kwd":"application/vnd.kde.kword",".kwt":"application/vnd.kde.kword",".latex":"application/x-latex",".lbd":"application/vnd.llamagraphics.life-balance.desktop",".lbe":"application/vnd.llamagraphics.life-balance.exchange+xml",".les":"application/vnd.hhe.lesson-player",".lha":"application/octet-stream",".link66":"application/vnd.route66.link66+xml",".list":"text/plain",".list3820":"application/vnd.ibm.modcap",".listafp":"application/vnd.ibm.modcap",".log":"text/plain",".lostxml":"application/lost+xml",".lrf":"application/octet-stream",".lrm":"application/vnd.ms-lrm",".ltf":"application/vnd.frogans.ltf",".lvp":"audio/vnd.lucent.voice",".lwp":"application/vnd.lotus-wordpro",".lzh":"application/octet-stream",".m13":"application/x-msmediaview",".m14":"application/x-msmediaview",".m1v":"video/mpeg",".m2a":"audio/mpeg",".m2v":"video/mpeg",".m3a":"audio/mpeg",".m3u":"audio/x-mpegurl",".m4u":"video/vnd.mpegurl",".m4v":"video/x-m4v",".ma":"application/mathematica",".mag":"application/vnd.ecowin.chart",".maker":"application/vnd.framemaker",".man":"text/troff",".mathml":"application/mathml+xml",".mb":"application/mathematica",".mbk":"application/vnd.mobius.mbk",".mbox":"application/mbox",".mc1":"application/vnd.medcalcdata",".mcd":"application/vnd.mcd",".mcurl":"text/vnd.curl.mcurl",".mdb":"application/x-msaccess",".mdi":"image/vnd.ms-modi",".me":"text/troff",".mesh":"model/mesh",".mfm":"application/vnd.mfmp",".mgz":"application/vnd.proteus.magazine",".mht":"message/rfc822",".mhtml":"message/rfc822",".mid":"audio/midi",".midi":"audio/midi",".mif":"application/vnd.mif",".mime":"message/rfc822",".mj2":"video/mj2",".mjp2":"video/mj2",".mkv":"video/x-matroska",".mlp":"application/vnd.dolby.mlp",".mmd":"application/vnd.chipnuts.karaoke-mmd",".mmf":"application/vnd.smaf",".mmr":"image/vnd.fujixerox.edmics-mmr",".mny":"application/x-msmoney",".mobi":"application/x-mobipocket-ebook",".mov":"video/quicktime",".movie":"video/x-sgi-movie",".mp2":"audio/mpeg",".mp2a":"audio/mpeg",".mp3":"audio/mpeg",".mp4":"video/mp4",".mp4a":"audio/mp4",".mp4s":"application/mp4",".mp4v":"video/mp4",".mpa":"video/mpeg",".mpc":"application/vnd.mophun.certificate",".mpe":"video/mpeg",".mpeg":"video/mpeg",".mpg":"video/mpeg",".mpg4":"video/mp4",".mpga":"audio/mpeg",".mpkg":"application/vnd.apple.installer+xml",".mpm":"application/vnd.blueice.multipass",".mpn":"application/vnd.mophun.application",".mpp":"application/vnd.ms-project",".mpt":"application/vnd.ms-project",".mpy":"application/vnd.ibm.minipay",".mqy":"application/vnd.mobius.mqy",".mrc":"application/marc",".ms":"text/troff",".mscml":"application/mediaservercontrol+xml",".mseed":"application/vnd.fdsn.mseed",".mseq":"application/vnd.mseq",".msf":"application/vnd.epson.msf",".msh":"model/mesh",".msi":"application/x-msdownload",".msl":"application/vnd.mobius.msl",".msty":"application/vnd.muvee.style",".mts":"model/vnd.mts",".mus":"application/vnd.musician",".musicxml":"application/vnd.recordare.musicxml+xml",".mvb":"application/x-msmediaview",".mwf":"application/vnd.mfer",".mxf":"application/mxf",".mxl":"application/vnd.recordare.musicxml",".mxml":"application/xv+xml",".mxs":"application/vnd.triscape.mxs",".mxu":"video/vnd.mpegurl",".n-gage":"application/vnd.nokia.n-gage.symbian.install",".nb":"application/mathematica",".nc":"application/x-netcdf",".ncx":"application/x-dtbncx+xml",".ngdat":"application/vnd.nokia.n-gage.data",".nlu":"application/vnd.neurolanguage.nlu",".nml":"application/vnd.enliven",".nnd":"application/vnd.noblenet-directory",".nns":"application/vnd.noblenet-sealer",".nnw":"application/vnd.noblenet-web",".npx":"image/vnd.net-fpx",".nsf":"application/vnd.lotus-notes",".nws":"message/rfc822",".o":"application/octet-stream",".oa2":"application/vnd.fujitsu.oasys2",".oa3":"application/vnd.fujitsu.oasys3",".oas":"application/vnd.fujitsu.oasys",".obd":"application/x-msbinder",".obj":"application/octet-stream",".oda":"application/oda",".odb":"application/vnd.oasis.opendocument.database",".odc":"application/vnd.oasis.opendocument.chart",".odf":"application/vnd.oasis.opendocument.formula",".odft":"application/vnd.oasis.opendocument.formula-template",".odg":"application/vnd.oasis.opendocument.graphics",".odi":"application/vnd.oasis.opendocument.image",".odp":"application/vnd.oasis.opendocument.presentation",".ods":"application/vnd.oasis.opendocument.spreadsheet",".odt":"application/vnd.oasis.opendocument.text",".oga":"audio/ogg",".ogg":"audio/ogg",".ogv":"video/ogg",".ogx":"application/ogg",".onepkg":"application/onenote",".onetmp":"application/onenote",".onetoc":"application/onenote",".onetoc2":"application/onenote",".opf":"application/oebps-package+xml",".oprc":"application/vnd.palm",".org":"application/vnd.lotus-organizer",".osf":"application/vnd.yamaha.openscoreformat",".osfpvg":"application/vnd.yamaha.openscoreformat.osfpvg+xml",".otc":"application/vnd.oasis.opendocument.chart-template",".otf":"application/x-font-otf",".otg":"application/vnd.oasis.opendocument.graphics-template",".oth":"application/vnd.oasis.opendocument.text-web",".oti":"application/vnd.oasis.opendocument.image-template",".otm":"application/vnd.oasis.opendocument.text-master",".otp":"application/vnd.oasis.opendocument.presentation-template",".ots":"application/vnd.oasis.opendocument.spreadsheet-template",".ott":"application/vnd.oasis.opendocument.text-template",".oxt":"application/vnd.openofficeorg.extension",".p":"text/x-pascal",".p10":"application/pkcs10",".p12":"application/x-pkcs12",".p7b":"application/x-pkcs7-certificates",".p7c":"application/pkcs7-mime",".p7m":"application/pkcs7-mime",".p7r":"application/x-pkcs7-certreqresp",".p7s":"application/pkcs7-signature",".pas":"text/x-pascal",".pbd":"application/vnd.powerbuilder6",".pbm":"image/x-portable-bitmap",".pcf":"application/x-font-pcf",".pcl":"application/vnd.hp-pcl",".pclxl":"application/vnd.hp-pclxl",".pct":"image/x-pict",".pcurl":"application/vnd.curl.pcurl",".pcx":"image/x-pcx",".pdb":"application/vnd.palm",".pdf":"application/pdf",".pfa":"application/x-font-type1",".pfb":"application/x-font-type1",".pfm":"application/x-font-type1",".pfr":"application/font-tdpfr",".pfx":"application/x-pkcs12",".pgm":"image/x-portable-graymap",".pgn":"application/x-chess-pgn",".pgp":"application/pgp-encrypted",".pic":"image/x-pict",".pkg":"application/octet-stream",".pki":"application/pkixcmp",".pkipath":"application/pkix-pkipath",".pl":"text/plain",".plb":"application/vnd.3gpp.pic-bw-large",".plc":"application/vnd.mobius.plc",".plf":"application/vnd.pocketlearn",".pls":"application/pls+xml",".pml":"application/vnd.ctc-posml",".png":"image/png",".pnm":"image/x-portable-anymap",".portpkg":"application/vnd.macports.portpkg",".pot":"application/vnd.ms-powerpoint",".potm":"application/vnd.ms-powerpoint.template.macroenabled.12",".potx":"application/vnd.openxmlformats-officedocument.presentationml.template",".ppa":"application/vnd.ms-powerpoint",".ppam":"application/vnd.ms-powerpoint.addin.macroenabled.12",".ppd":"application/vnd.cups-ppd",".ppm":"image/x-portable-pixmap",".pps":"application/vnd.ms-powerpoint",".ppsm":"application/vnd.ms-powerpoint.slideshow.macroenabled.12",".ppsx":"application/vnd.openxmlformats-officedocument.presentationml.slideshow",".ppt":"application/vnd.ms-powerpoint",".pptm":"application/vnd.ms-powerpoint.presentation.macroenabled.12",".pptx":"application/vnd.openxmlformats-officedocument.presentationml.presentation",".pqa":"application/vnd.palm",".prc":"application/x-mobipocket-ebook",".pre":"application/vnd.lotus-freelance",".prf":"application/pics-rules",".ps":"application/postscript",".psb":"application/vnd.3gpp.pic-bw-small",".psd":"image/vnd.adobe.photoshop",".psf":"application/x-font-linux-psf",".ptid":"application/vnd.pvi.ptid1",".pub":"application/x-mspublisher",".pvb":"application/vnd.3gpp.pic-bw-var",".pwn":"application/vnd.3m.post-it-notes",".pwz":"application/vnd.ms-powerpoint",".py":"text/x-python",".pya":"audio/vnd.ms-playready.media.pya",".pyc":"application/x-python-code",".pyo":"application/x-python-code",".pyv":"video/vnd.ms-playready.media.pyv",".qam":"application/vnd.epson.quickanime",".qbo":"application/vnd.intu.qbo",".qfx":"application/vnd.intu.qfx",".qps":"application/vnd.publishare-delta-tree",".qt":"video/quicktime",".qwd":"application/vnd.quark.quarkxpress",".qwt":"application/vnd.quark.quarkxpress",".qxb":"application/vnd.quark.quarkxpress",".qxd":"application/vnd.quark.quarkxpress",".qxl":"application/vnd.quark.quarkxpress",".qxt":"application/vnd.quark.quarkxpress",".ra":"audio/x-pn-realaudio",".ram":"audio/x-pn-realaudio",".rar":"application/x-rar-compressed",".ras":"image/x-cmu-raster",".rcprofile":"application/vnd.ipunplugged.rcprofile",".rdf":"application/rdf+xml",".rdz":"application/vnd.data-vision.rdz",".rep":"application/vnd.businessobjects",".res":"application/x-dtbresource+xml",".rgb":"image/x-rgb",".rif":"application/reginfo+xml",".rl":"application/resource-lists+xml",".rlc":"image/vnd.fujixerox.edmics-rlc",".rld":"application/resource-lists-diff+xml",".rm":"application/vnd.rn-realmedia",".rmi":"audio/midi",".rmp":"audio/x-pn-realaudio-plugin",".rms":"application/vnd.jcp.javame.midlet-rms",".rnc":"application/relax-ng-compact-syntax",".roff":"text/troff",".rpm":"application/x-rpm",".rpss":"application/vnd.nokia.radio-presets",".rpst":"application/vnd.nokia.radio-preset",".rq":"application/sparql-query",".rs":"application/rls-services+xml",".rsd":"application/rsd+xml",".rss":"application/rss+xml",".rtf":"application/rtf",".rtx":"text/richtext",".s":"text/x-asm",".saf":"application/vnd.yamaha.smaf-audio",".sbml":"application/sbml+xml",".sc":"application/vnd.ibm.secure-container",".scd":"application/x-msschedule",".scm":"application/vnd.lotus-screencam",".scq":"application/scvp-cv-request",".scs":"application/scvp-cv-response",".scurl":"text/vnd.curl.scurl",".sda":"application/vnd.stardivision.draw",".sdc":"application/vnd.stardivision.calc",".sdd":"application/vnd.stardivision.impress",".sdkd":"application/vnd.solent.sdkm+xml",".sdkm":"application/vnd.solent.sdkm+xml",".sdp":"application/sdp",".sdw":"application/vnd.stardivision.writer",".see":"application/vnd.seemail",".seed":"application/vnd.fdsn.seed",".sema":"application/vnd.sema",".semd":"application/vnd.semd",".semf":"application/vnd.semf",".ser":"application/java-serialized-object",".setpay":"application/set-payment-initiation",".setreg":"application/set-registration-initiation",".sfd-hdstx":"application/vnd.hydrostatix.sof-data",".sfs":"application/vnd.spotfire.sfs",".sgl":"application/vnd.stardivision.writer-global",".sgm":"text/sgml",".sgml":"text/sgml",".sh":"application/x-sh",".shar":"application/x-shar",".shf":"application/shf+xml",".si":"text/vnd.wap.si",".sic":"application/vnd.wap.sic",".sig":"application/pgp-signature",".silo":"model/mesh",".sis":"application/vnd.symbian.install",".sisx":"application/vnd.symbian.install",".sit":"application/x-stuffit",".sitx":"application/x-stuffitx",".skd":"application/vnd.koan",".skm":"application/vnd.koan",".skp":"application/vnd.koan",".skt":"application/vnd.koan",".sl":"text/vnd.wap.sl",".slc":"application/vnd.wap.slc",".sldm":"application/vnd.ms-powerpoint.slide.macroenabled.12",".sldx":"application/vnd.openxmlformats-officedocument.presentationml.slide",".slt":"application/vnd.epson.salt",".smf":"application/vnd.stardivision.math",".smi":"application/smil+xml",".smil":"application/smil+xml",".snd":"audio/basic",".snf":"application/x-font-snf",".so":"application/octet-stream",".spc":"application/x-pkcs7-certificates",".spf":"application/vnd.yamaha.smaf-phrase",".spl":"application/x-futuresplash",".spot":"text/vnd.in3d.spot",".spp":"application/scvp-vp-response",".spq":"application/scvp-vp-request",".spx":"audio/ogg",".src":"application/x-wais-source",".srx":"application/sparql-results+xml",".sse":"application/vnd.kodak-descriptor",".ssf":"application/vnd.epson.ssf",".ssml":"application/ssml+xml",".stc":"application/vnd.sun.xml.calc.template",".std":"application/vnd.sun.xml.draw.template",".stf":"application/vnd.wt.stf",".sti":"application/vnd.sun.xml.impress.template",".stk":"application/hyperstudio",".stl":"application/vnd.ms-pki.stl",".str":"application/vnd.pg.format",".stw":"application/vnd.sun.xml.writer.template",".sus":"application/vnd.sus-calendar",".susp":"application/vnd.sus-calendar",".sv4cpio":"application/x-sv4cpio",".sv4crc":"application/x-sv4crc",".svd":"application/vnd.svd",".svg":"image/svg+xml",".svgz":"image/svg+xml",".swa":"application/x-director",".swf":"application/x-shockwave-flash",".swi":"application/vnd.arastra.swi",".sxc":"application/vnd.sun.xml.calc",".sxd":"application/vnd.sun.xml.draw",".sxg":"application/vnd.sun.xml.writer.global",".sxi":"application/vnd.sun.xml.impress",".sxm":"application/vnd.sun.xml.math",".sxw":"application/vnd.sun.xml.writer",".t":"text/troff",".tao":"application/vnd.tao.intent-module-archive",".tar":"application/x-tar",".tcap":"application/vnd.3gpp2.tcap",".tcl":"application/x-tcl",".teacher":"application/vnd.smart.teacher",".tex":"application/x-tex",".texi":"application/x-texinfo",".texinfo":"application/x-texinfo",".text":"text/plain",".tfm":"application/x-tex-tfm",".tgz":"application/x-gzip",".tif":"image/tiff",".tiff":"image/tiff",".tmo":"application/vnd.tmobile-livetv",".torrent":"application/x-bittorrent",".tpl":"application/vnd.groove-tool-template",".tpt":"application/vnd.trid.tpt",".tr":"text/troff",".tra":"application/vnd.trueapp",".trm":"application/x-msterminal",".tsv":"text/tab-separated-values",".ttc":"application/x-font-ttf",".ttf":"application/x-font-ttf",".twd":"application/vnd.simtech-mindmapper",".twds":"application/vnd.simtech-mindmapper",".txd":"application/vnd.genomatix.tuxedo",".txf":"application/vnd.mobius.txf",".txt":"text/plain",".u32":"application/x-authorware-bin",".udeb":"application/x-debian-package",".ufd":"application/vnd.ufdl",".ufdl":"application/vnd.ufdl",".umj":"application/vnd.umajin",".unityweb":"application/vnd.unity",".uoml":"application/vnd.uoml+xml",".uri":"text/uri-list",".uris":"text/uri-list",".urls":"text/uri-list",".ustar":"application/x-ustar",".utz":"application/vnd.uiq.theme",".uu":"text/x-uuencode",".vcd":"application/x-cdlink",".vcf":"text/x-vcard",".vcg":"application/vnd.groove-vcard",".vcs":"text/x-vcalendar",".vcx":"application/vnd.vcx",".vis":"application/vnd.visionary",".viv":"video/vnd.vivo",".vor":"application/vnd.stardivision.writer",".vox":"application/x-authorware-bin",".vrml":"model/vrml",".vsd":"application/vnd.visio",".vsf":"application/vnd.vsf",".vss":"application/vnd.visio",".vst":"application/vnd.visio",".vsw":"application/vnd.visio",".vtu":"model/vnd.vtu",".vxml":"application/voicexml+xml",".w3d":"application/x-director",".webm":"video/webm",".wad":"application/x-doom",".wav":"audio/x-wav",".wax":"audio/x-ms-wax",".wbmp":"image/vnd.wap.wbmp",".wbs":"application/vnd.criticaltools.wbs+xml",".wbxml":"application/vnd.wap.wbxml",".wcm":"application/vnd.ms-works",".wdb":"application/vnd.ms-works",".wiz":"application/msword",".wks":"application/vnd.ms-works",".wm":"video/x-ms-wm",".wma":"audio/x-ms-wma",".wmd":"application/x-ms-wmd",".wmf":"application/x-msmetafile",".wml":"text/vnd.wap.wml",".wmlc":"application/vnd.wap.wmlc",".wmls":"text/vnd.wap.wmlscript",".wmlsc":"application/vnd.wap.wmlscriptc",".wmv":"video/x-ms-wmv",".wmx":"video/x-ms-wmx",".wmz":"application/x-ms-wmz",".wpd":"application/vnd.wordperfect",".wpl":"application/vnd.ms-wpl",".wps":"application/vnd.ms-works",".wqd":"application/vnd.wqd",".wri":"application/x-mswrite",".wrl":"model/vrml",".wsdl":"application/wsdl+xml",".wspolicy":"application/wspolicy+xml",".wtb":"application/vnd.webturbo",".wvx":"video/x-ms-wvx",".x32":"application/x-authorware-bin",".x3d":"application/vnd.hzn-3d-crossword",".xap":"application/x-silverlight-app",".xar":"application/vnd.xara",".xbap":"application/x-ms-xbap",".xbd":"application/vnd.fujixerox.docuworks.binder",".xbm":"image/x-xbitmap",".xdm":"application/vnd.syncml.dm+xml",".xdp":"application/vnd.adobe.xdp+xml",".xdw":"application/vnd.fujixerox.docuworks",".xenc":"application/xenc+xml",".xer":"application/patch-ops-error+xml",".xfdf":"application/vnd.adobe.xfdf",".xfdl":"application/vnd.xfdl",".xht":"application/xhtml+xml",".xhtml":"application/xhtml+xml",".xhvml":"application/xv+xml",".xif":"image/vnd.xiff",".xla":"application/vnd.ms-excel",".xlam":"application/vnd.ms-excel.addin.macroenabled.12",".xlb":"application/vnd.ms-excel",".xlc":"application/vnd.ms-excel",".xlm":"application/vnd.ms-excel",".xls":"application/vnd.ms-excel",".xlsb":"application/vnd.ms-excel.sheet.binary.macroenabled.12",".xlsm":"application/vnd.ms-excel.sheet.macroenabled.12",".xlsx":"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",".xlt":"application/vnd.ms-excel",".xltm":"application/vnd.ms-excel.template.macroenabled.12",".xltx":"application/vnd.openxmlformats-officedocument.spreadsheetml.template",".xlw":"application/vnd.ms-excel",".xml":"application/xml",".xo":"application/vnd.olpc-sugar",".xop":"application/xop+xml",".xpdl":"application/xml",".xpi":"application/x-xpinstall",".xpm":"image/x-xpixmap",".xpr":"application/vnd.is-xpr",".xps":"application/vnd.ms-xpsdocument",".xpw":"application/vnd.intercon.formnet",".xpx":"application/vnd.intercon.formnet",".xsl":"application/xml",".xslt":"application/xslt+xml",".xsm":"application/vnd.syncml+xml",".xspf":"application/xspf+xml",".xul":"application/vnd.mozilla.xul+xml",".xvm":"application/xv+xml",".xvml":"application/xv+xml",".xwd":"image/x-xwindowdump",".xyz":"chemical/x-xyz",".zaz":"application/vnd.zzazz.deck+xml",".zip":"application/zip",".zir":"application/vnd.zul",".zirz":"application/vnd.zul",".zmm":"application/vnd.handheld-entertainment+xml"},Qx=[".sh",".exe",".app",".bat",".cmd",".msi",".apk",".jar",".py",".js",".cron",".php",".asp"],PEe=Object.keys(od);import{z as Qi}from"zod";var LEe=Qi.object({id:Qi.string(),name:Qi.string(),createdAt:Qi.coerce.date(),createdBy:Qi.string(),updatedAt:Qi.coerce.date(),updatedBy:Qi.string().nullable(),organizationId:Qi.string()});import{z as V}from"zod";import Zi from"zod";var Gl=Zi.object({platformSep:Zi.string(),fullPathSegments:Zi.string().array(),relativePathSegments:Zi.string().array(),relativePath:Zi.string().describe("path relative to the root test directory, i.e. my-folder/my-test.yaml"),fileName:Zi.string().describe("base name of the file including the extension, e.g. my-module.module.yaml"),lastModified:Zi.coerce.date(),createdAt:Zi.coerce.date()});var IW=V.array(Gl.extend({id:V.string(),name:V.string(),description:V.string().optional(),labels:V.string().array().optional()})),PW=Gl.extend({id:V.string(),name:V.string(),description:V.string().optional(),content:YS}),MW=V.array(PW),$Ee=V.object({tests:IW,modules:MW,labels:V.string().array()}),qEe=_m.merge(zn),Zx=V.object({schemaVersion:V.string(),stepLists:Wi}),e_=zn.partial().merge(Mr.pick({id:!0})),ea="1-255 chars; Only letters/numbers/dashes. Cannot start/end with '-'. Not '.yaml', 'none', or UUID.",lE={name:V.string().min(1).max(255).describe(ea),description:V.string().optional(),baseUrl:V.string().url().optional().describe("For LLM: Ask the user for the base URL if they don't provide it."),environment:V.string().optional().describe("For LLM: Do not include the variable unless the user explicitly asks for it and use the environment lookup tool to get the correct one before passing here."),browserType:V.nativeEnum(So).optional().describe("For LLM: Never assign this variable unless the user explicitly asks for it."),viewport:tm.optional().describe("For LLM: Never assign this variable unless the user explicitly asks for it."),pathSegments:V.string().array().optional().describe("For LLM: Only use if explicitly called for by the user. Used to create the test in the correct folder. Paths are relative to the project root.")},t_=V.object(lE),KEe=_m.merge(V.object({relativeFilePath:V.string().describe("relative to project root")})),r_=V.object({name:V.string()}),YEe=V.object({relativeFilePath:V.string()}),n_=V.object({name:V.string()}),XEe=V.object({relativeFilePath:V.string()}),o_=V.object({name:V.string(),description:V.string(),enabled:V.boolean(),steps:V.lazy(()=>Nt.array()),testFilePath:V.string().describe("relative to the project root"),folderPath:V.string().optional().describe("user selected folder path")}),i_=V.object({name:V.string(),description:V.string(),enabled:V.boolean()}).partial();var JEe=V.array(rw),a_=V.object({defaultEnv:V.string().optional().describe("name of the default env, or undefined to unset")}),s_=V.object({configFilePath:V.string().describe("full path on disk")}),QEe=V.string().array(),ZEe=V.object({message:V.string(),newRelativeTestPath:V.string().optional()}),cE=V.object({name:V.string(),absolutePath:V.string(),relativePath:V.string(),pathSegments:V.array(V.string()),isDirectory:V.boolean(),size:V.number(),createdAt:V.coerce.date(),modifiedAt:V.coerce.date(),accessedAt:V.coerce.date()}),l_=V.object({pathSegments:V.array(V.string())}),eTe=V.object({absolutePath:V.string(),pathSegments:V.array(V.string()),contents:V.array(cE)}),c_=V.object({pathSegments:V.array(V.string())}),u_=V.object({pathSegments:V.array(V.string()),newPathSegments:V.array(V.string())}),d_=V.object({pathSegments:V.array(V.string()),recursive:V.boolean().optional()}),tTe=V.object({success:V.boolean(),message:V.string(),pathSegments:V.array(V.string()).optional()}),rTe=V.object({gitBranch:V.string(),fileMtime:V.coerce.date(),gitCommitSha:V.string()});var Fm=["node_modules","dist","bin",".git",".npm",".next","out",".yarn","__pycache__","build",".env",".venv","venv","env","wheels"],Um=Fm.map(t=>`**/${t}/**`),p_=typeof process<"u"&&!0&&!0,Gn=typeof process<"u"&&!1,m_=2e5;var Bm=58889;import Bo from"chalk";import OW from"safe-stable-stringify";import LW from"truncate-json";import NW from"zod";var as=OW.configure({deterministic:!1});function f_(t){let e=as(t),{jsonString:r}=LW(e,5e4);return r}var DW=["app","version","env","namespace","host"];function ot(t){let e=t.bindings()??{},r={};for(let n of Object.keys(e)){let o=e[n];!DW.includes(n)&&typeof o=="string"&&(r[n]=o)}return r}var uE=NW.enum(["debug","info","warn","error"]);var id={debug:20,info:30,warn:40,error:50},h_={20:"debug",30:"info",40:"warn",50:"error"},ss=class t{minLogLevel;logBindings;constructor(e,r){typeof e=="string"?this.minLogLevel=id[e]:this.minLogLevel=e,this.logBindings=r}logWithLevel(e,r,...n){try{this.logWithLevelHelper(e,r,...n)}catch(o){console.error(`Failed to log to console: ${o}`)}}indentMultiline(e,r=" "){return e.split(`
|
|
21
21
|
`).map((n,o)=>o>0?`${r}${n}`:n).join(`
|
|
22
22
|
`)}logWithLevelHelper(e,r,...n){if(e<this.minLogLevel)return;let o;Array.isArray(n[0])?(o=n[0],n=n.slice(1)):typeof n[0]=="object"&&!(n[0]instanceof Error)&&Object.entries(n[0]).length&&(o={...n[0],...this.logBindings},n=n.slice(1));let i=[];if(i.push(...n),console.log(r(...i)),o&&!Array.isArray(o)){let a=Object.entries(o);for(let[s,c]of a){let l=c;if(c instanceof Error){l=c.message,console.log(r(` ${s}:`,l)),console.log(r(" stack:",c.stack));let d=Object.entries(c).filter(([p])=>p!=="message"&&p!=="stack");for(let[p,m]of d){if(m instanceof Error){console.log(r(` ${s}.${p}:`,m.message)),m.stack&&console.log(r(` ${s}.${p}.stack:`,m.stack));continue}if(typeof m=="object"&&m!==null){let f=this.indentMultiline(as(m,void 0,2)," ");console.log(r(` ${s}.${p}:`,f));continue}console.log(r(` ${s}.${p}:`,m))}}else typeof c=="object"?(l=as(c,void 0,2),l=this.indentMultiline(l),console.log(r(` ${s}:`,l))):console.log(r(` ${s}:`,l))}}else if(o)for(let a of o){let s=a;typeof a=="object"&&(s=as(a,void 0,2),s=s.split(`
|
|
23
23
|
`).map((c,l)=>l>0?` ${c}`:c).join(`
|
|
24
|
-
`)),console.log(" ",r(s))}}setMinLevel(e){typeof e=="string"?this.minLogLevel=id[e]:this.minLogLevel=e}log(...e){this.logWithLevel(30,Bo.reset,...e)}info(...e){this.logWithLevel(30,Bo.white,...e)}debug(...e){this.logWithLevel(20,Bo.dim,...e)}warn(...e){this.logWithLevel(40,Bo.yellow,...e)}error(...e){this.logWithLevel(50,Bo.red,...e)}success(...e){this.logWithLevel(1/0,Bo.green,...e)}dimmed(...e){this.logWithLevel(30,Bo.dim,...e)}underline(...e){this.logWithLevel(40,Bo.underline,...e)}bold(...e){this.logWithLevel(40,Bo.bold,...e)}grey(...e){this.logWithLevel(20,Bo.grey,...e)}child(e){return new t(this.minLogLevel,{...this.logBindings,...e})}async flush(){}bindings(){return this.logBindings}},dE=class{debug(){}info(){}warn(){}error(){}success(){}dimmed(){}underline(){}bold(){}grey(){}child(){return this}async flush(){}bindings(){return{}}},cTe=new dE,kW=typeof window>"u"&&typeof process<"u"&&uE.safeParse(process?.env?.MOMENTIC_DEV_LOG_LEVEL).success?uE.parse(process.env.MOMENTIC_DEV_LOG_LEVEL):30,v=new ss(kW,{}),zo={info:()=>{},error:()=>{},debug:()=>{},warn:()=>{},child:()=>zo,flush:async()=>{},bindings:()=>({})},zm={},Hm=({logger:t,logKey:e,maxCount:r,intervalMs:n},o,i,...a)=>{let s=zm[e];s?clearTimeout(s.timer):(s={count:0,totalCount:0},zm[e]=s),s.totalCount++,s.count<r&&(s.count++,t.debug(o,i,...a)),s.timer=setTimeout(()=>{let c=zm[e];c?.totalCount!==c?.count&&t.debug({logKey:e,totalCount:c?.totalCount,count:c?.count},`Debug logs were rate-limited for ${e}`),delete zm[e]},n)};import{z as K}from"zod";var FW=K.array(Gl.extend({id:K.string(),name:K.string(),description:K.string().optional(),labels:K.string().array().optional()})),UW=K.array(Gl.extend({id:K.string(),name:K.string(),description:K.string().optional(),content:eE})),g_={name:K.string().min(1).max(255).describe(ea),description:K.string().optional(),settings:Ul.optional().describe("Optional mobile test settings to persist on the new test, such as retries, default environment, app selection, emulator configuration, and AI settings."),pathSegments:K.string().array().optional().describe("Path segments for the destination folder. Omit or pass [] to create the test at the project root."),defaultEnv:K.string().optional(),platform:iw.optional().default("ANDROID").describe("For LLM: Never assign this unless the user explicitly asks for iOS. Defaults to Android.")},{defaultEnv:yTe,...ETe}=g_;var TTe=K.object(g_),bTe=K.object({id:K.string(),fileName:K.string(),fullPath:K.string(),relativeFilePath:K.string().describe("relative to project root")});var vTe=K.object({steps:is.array().optional(),settings:Ul.optional(),labels:K.array(K.string()).optional()}),ATe=K.object({message:K.literal("ok")}),CTe=K.object({name:ui.optional(),description:K.string().min(1).optional(),settings:Ul.optional(),disabled:K.boolean().optional(),labels:K.array(K.string()).optional()}),RTe=K.object({message:K.string(),newRelativeTestPath:K.string().optional()}),wTe=K.object({tag:K.string(),channel:K.string(),filePath:K.string()}),xTe=K.object({name:ui}),_Te=K.object({tests:FW,modules:UW,labels:K.string().array()}),ITe=K.object({name:K.string(),description:K.string(),enabled:K.boolean()}).partial(),PTe=K.object({name:K.string(),description:K.string(),enabled:K.boolean(),steps:is.array(),testFilePath:K.string().describe("relative to the project root"),folderPath:K.string().optional().describe("user selected folder path")}),MTe=K.object({name:K.string().describe(ea),description:K.string().optional(),enabled:K.boolean().default(!0),parameters:Qu.optional(),moduleInputs:K.record(K.string(),K.string()).optional(),folderPath:K.string().optional(),testPath:K.string().optional(),startIndex:K.number().optional(),endIndex:K.number().optional()}),OTe=K.object({packages:K.string().array()}),LTe=K.object({name:K.string()}),NTe=K.object({relativeFilePath:K.string()}),S_=K.object({stepId:K.string(),testId:K.string(),environment:K.string().optional(),parentStepIdChain:K.array(K.string()),value:kl}),BW=S_.extend({platform:K.literal("ANDROID"),steps:is.array()}),zW=S_.extend({platform:K.literal("IOS"),steps:Zu.array()}),DTe=K.discriminatedUnion("platform",[BW,zW]),kTe=K.object({platform:K.nativeEnum(gn),completionType:K.string(),traceIds:K.string().array()}),FTe=K.object({completionType:K.string(),traceIds:K.string().array()});import{v4 as HW}from"uuid";var Gm=class{constructor(e){this.params=e}sessions=new Map;registerSession(e){return this.sessions.set(e.sessionId,e),e}getSession(e){return this.sessions.get(e)}listSessionIds(){return Array.from(this.sessions.keys())}touchSession(e){let r=this.sessions.get(e);if(r)return r.lastAccessedAt=Date.now(),this.resetTimeout(r),r}async killSession(e,r){let n=this.sessions.get(e);return n?(n.cleanupPromise||(n.cleanupInProgress=!0,n.cleanupPromise=(async()=>{try{return await this.kill(n,r)?(clearTimeout(n.timeoutHandle),this.sessions.delete(e),!0):(n.cleanupInProgress=!1,n.cleanupPromise=void 0,!1)}catch(o){return n.cleanupInProgress=!1,n.cleanupPromise=void 0,n.logger.error({err:o,sessionId:e,reason:r},`Failed to clean up ${this.params.sessionTypeLabel}`),!1}})()),n.cleanupPromise):!1}async killAllSessions(e){let r=this.listSessionIds(),n=await Promise.all(r.map(async o=>{try{let i=await this.killSession(o,e);return{sessionId:o,didKill:i}}catch{return{sessionId:o,didKill:!1}}}));return{killed:n.filter(o=>o.didKill).map(o=>o.sessionId),failed:n.filter(o=>!o.didKill).map(o=>o.sessionId)}}buildManagedSessionState(e){let r=Date.now(),n=HW();return{sessionId:n,createdAt:r,lastAccessedAt:r,idleTimeoutMs:e.idleTimeoutMs,logger:e.logger,timeoutHandle:setTimeout(()=>{this.killSession(n,"idle timeout").catch(o=>{e.logger.error({err:o,sessionId:n},`Failed to clean up ${this.params.sessionTypeLabel}`)})},e.idleTimeoutMs)}}resetTimeout(e){clearTimeout(e.timeoutHandle),e.timeoutHandle=setTimeout(()=>{this.killSession(e.sessionId,"idle timeout").catch(r=>{e.logger.error({err:r,sessionId:e.sessionId},`Failed to clean up ${this.params.sessionTypeLabel}`)})},e.idleTimeoutMs)}};import{z as jt}from"zod";var y_=jt.object({id:jt.string(),createdAt:jt.coerce.date(),createdBy:jt.string(),organizationId:jt.string(),name:jt.string(),description:jt.string().nullish(),enabled:jt.boolean(),schemaVersion:jt.string().describe("Schema version for steps"),parameters:jt.string().array().nullish().describe("Parameter list"),parameterEnums:jt.record(jt.string(),jt.string().array()).nullish(),defaultParameters:jt.record(jt.string(),jt.string()).nullish(),defaultCacheKey:jt.string().nullish(),defaultCacheTtl:jt.number().nullish(),defaultCacheAllInvocations:jt.boolean().nullish(),autoAuth:jt.boolean().nullish(),advanced:$S.nullish()}),KTe=y_.extend({steps:jt.lazy(()=>bt.array())}),E_=5*60*1e3,pE=tn.merge(y_.omit({id:!0,createdAt:!0,createdBy:!0,organizationId:!0,enabled:!0}));import{formatInTimeZone as JTe}from"date-fns-tz";import*as A from"zod";import{z as kt}from"zod";var mE=(e=>(e.TEST_REVIEW="TEST_REVIEW",e))(mE||{});var GW=kt.object({type:kt.literal("DESCRIPTION_UPDATE"),thoughts:kt.string()}),jm=kt.discriminatedUnion("type",[GW]),jW=kt.object({testId:kt.string(),name:kt.string(),orgId:kt.string(),runId:kt.string(),steps:Nt.array(),purpose:kt.nativeEnum(mE),details:jm.or(jm.array()).optional()});var rbe=jW.pick({name:!0,orgId:!0}),VW=kt.object({id:kt.string(),name:kt.string().nullish(),createdAt:kt.string().pipe(kt.coerce.date()).or(kt.date()),organizationId:kt.string(),schemaVersion:kt.string(),runId:kt.string().nullish(),purpose:kt.nativeEnum(mE),details:jm.or(jm.array()).optional(),applied:kt.boolean().nullish(),appliedAt:kt.coerce.date().nullish()}),T_=VW.extend({steps:Nt.array()});var Vm="x-momentic-cli-version",b_="x-momentic-client-mode",v_="x-momentic-cli-type",A_="x-momentic-logger-tags",WW="x-momentic-main-branch-name",$W="x-momentic-branch-name",qW="x-momentic-commit-timestamp",KW="x-momentic-last-commit-on-main",YW="x-momentic-last-commit-on-main-timestamp",XW="x-momentic-merged-branch-name",C_="x-momentic-session-id",Rbe=A.object({error:A.boolean(),reason:A.string(),message:A.string()}),wbe=Gt.merge(py),R_=Gp,xbe=Gt.merge(py);var _be=Gt.merge(Cw).extend({useConsensus:A.boolean().optional(),attemptNumber:A.number().optional()}),fE=rC,Ibe=Gt.merge(ww),w_=zR,Pbe=Gt.merge(xw),x_=HR,Mbe=Gt.merge(_w),__=GR,Obe=Gt.merge(Rw),I_=BR,Lbe=Gt.merge(Tw),P_=em,Nbe=Gt.merge(bw),M_=DR,Dbe=Gt.merge(vw);var kbe=Gt.merge(Aw),Fbe=Gt.merge(Ow),Ube=Gt.merge(Lw),Bbe=A.object({testPaths:A.string().array().describe("can be either hyphenated, lowercase test names or UUIDs"),env:A.string().optional(),all:A.boolean().optional(),urlOverride:A.string().optional(),customHeaders:A.record(A.string(),A.string()).optional(),testInputMatrix:A.record(A.string(),A.string()).array().optional()}),O_=A.object({queuedTests:A.unknown().array(),runIds:A.string().uuid().array(),runGroupId:A.string().optional()});var zbe=A.string().array(),Hbe=A.union([A.object({paths:A.string().array().describe("run specific test paths (e.g. todo-test)"),all:A.boolean().describe("run all tests").optional()}),A.object({path:A.string().describe("deprecated; present for backcompat")})]),L_=A.object({tests:A.record(A.string().describe("Test name"),A.string().describe("Test YAML")),modules:A.record(A.string().describe("Module name"),A.string().describe("Module YAML"))}),JW=A.object({test:A.string().describe("test YAML"),modules:A.record(A.string().describe("moduleId"),A.string().describe("module YAML"))}),Gbe=JW.array(),jbe=A.object({testId:A.string(),schemaVersion:A.string()}).merge(Va);function hE(t){let{gitMainBranch:e,gitBranchName:r,gitCommitTimestamp:n,lastCommitOnMainSha:o,lastCommitOnMainTimestamp:i}=t,a={};return e&&(a[WW]=encodeURIComponent(e)),r&&(a[$W]=encodeURIComponent(r)),n&&(a[qW]=n.toISOString()),o&&(a[KW]=encodeURIComponent(o)),i&&(a[YW]=i.toISOString()),t.mergedGitBranchName&&(a[XW]=encodeURIComponent(t.mergedGitBranchName)),a}var Vbe=A.object({entries:A.array(NC)});var Wbe=A.object({testId:A.string(),environment:A.string().optional()});function N_(t){return A.record(A.unknown()).transform(e=>{let r={};for(let[n,o]of Object.entries(e)){let i=t.safeParse(o);i.success&&(r[n]=i.data)}return r})}var D_=N_(DC);function k_(t){return N_(za(t))}var QW=A.object({id:A.string(),completionType:A.string(),description:A.string().optional(),thoughts:A.string(),result:A.string(),sessionType:A.string(),timeCreated:A.string().optional()}),ZW=A.object({id:A.string(),assertion:A.string().optional(),result:A.string(),thoughts:A.string(),sessionType:A.string(),timeCreated:A.string().optional()}),$be=A.object({completionType:A.string(),traceIds:A.string().array()}),gE=A.union([QW,ZW]).array(),F_=A.object({trigger:A.nativeEnum(rn),status:A.nativeEnum(nt),startedAt:A.coerce.date().optional(),gitCommitSha:A.string().optional(),gitCommitShaShort:A.string().optional(),gitCommitTimestamp:A.coerce.date().optional(),gitBranchName:A.string().optional(),gitOriginUrl:A.string().optional(),gitCommitMessage:A.string().optional(),gitCommitAuthorName:A.string().optional(),githubRepository:A.string().optional(),gitlabProjectPath:A.string().optional(),pipelineId:A.string().optional(),cliVersion:A.string().optional()}),qbe=A.object({id:A.string()}),U_=A.object({status:A.nativeEnum(nt),updatedAt:A.coerce.date().optional(),finishedAt:A.coerce.date().optional()}),B_=A.object({stepsSnapshot:A.array(A.record(A.unknown())).optional(),runGroupId:A.string().optional(),testId:A.string(),testName:A.string(),resolvedBaseUrl:A.string().optional(),environmentName:A.string().optional(),labels:A.array(A.string()).optional(),cliVersion:A.string().optional(),trigger:A.nativeEnum(rn),schemaVersion:A.string().optional(),section:A.nativeEnum(mm).optional(),resolvedInputs:A.record(A.string(),A.string()).optional(),quarantined:A.boolean().optional().default(!1),quarantinedReason:A.string().optional(),aiSettings:pi.optional()}),Kbe=A.object({id:A.string()}),e$=cy.pick({id:!0,status:!0,testName:!0,testId:!0,test:!0,failureReason:!0,failureDetails:!0}),z_=e$.array(),H_=cy.pick({startedAt:!0,finishedAt:!0,updatedAt:!0,results:!0,beforeResults:!0,afterResults:!0,status:!0,failureDetails:!0,failureReason:!0,failureRecoveryDetails:!0,resolvedBaseUrl:!0,environmentName:!0,labels:!0,cliVersion:!0,resolvedInputs:!0,attempts:!0,flake:!0,aiSettings:!0}).partial(),Ybe=A.object({id:A.string()}),G_=A.object({status:A.nativeEnum(nt),finishedAt:A.coerce.date().optional(),schemaVersion:A.string().optional().default("1.0.19"),results:A.record(A.string(),A.unknown()).array().optional(),beforeResults:A.record(A.string(),A.unknown()).array().optional(),afterResults:A.record(A.string(),A.unknown()).array().optional()}),Xbe=A.object({screenshot:A.string(),contentType:A.enum(["image/jpeg","image/png"]).optional()}),Jbe=A.object({id:A.string(),screenshot:A.string(),contentType:A.enum(["image/jpeg","image/png"])}),j_=A.object({key:A.string()}),V_=A.object({orgId:A.string(),userId:A.string()}),W_=A.array(tw),Qbe=A.record(A.string(),A.union([A.string(),A.boolean()])),Zbe=A.object({paths:A.string().array(),env:A.string().optional(),urlOverride:A.string().optional(),customHeaders:A.record(A.string(),A.string()).optional()}),$_=A.object({suiteRunIds:A.string().array(),runGroupIds:A.string().array()}),eve=A.object({suiteRunIds:A.string().array()}),tve=Sw.array(),rve=A.object({runGroupIds:A.string().array()}),t$=A.object({uploadUrl:A.string()}),nve=Gt.merge(Iw),ove=Gt.merge(Mw),ive=Gt.merge(Pw),r$=A.object({testId:A.string().optional().default(""),testName:A.string().optional().default(""),suiteId:A.string().optional().default(""),suiteName:A.string().optional().default(""),creditsUsed:A.number().optional()}),n$=A.object({transactionId:A.string(),timestamp:A.string(),event:A.nativeEnum(Yu),properties:r$}),ave=n$.array(),q_=T_.omit({steps:!0}).extend({steps:A.array(A.record(A.string(),A.unknown())).describe("unparsed ResolvedStep[]")}),sve=A.object({limit:A.number().max(10).optional(),afterTime:A.number().optional()}),K_=dw.array(),lve=A.object({applied:A.boolean().optional(),appliedAt:A.coerce.date().optional()}),Y_=t$.extend({id:A.string()}),cve=A.object({runGroupId:A.string().uuid().optional()}),X_=A.object({runGroupId:A.string().uuid()}),J_=A.object({quarantined:A.object({testId:A.string().uuid(),quarantinedAt:A.coerce.date(),quarantinedBy:A.string().optional(),quarantinedReason:A.string()}).array()}),uve=A.object({testId:A.string().uuid(),testName:A.string().optional(),reason:A.string(),gitLocalUsername:A.string().optional(),gitLocalEmail:A.string().optional(),gitLocalName:A.string().optional()}),dve=A.object({testName:A.string().optional(),reason:A.string().optional(),gitLocalUsername:A.string().optional(),gitLocalEmail:A.string().optional(),gitLocalName:A.string().optional()}),pve=Gt.merge(ix),mve=Gt.merge(ax),fve=Gt.merge(sx),hve=A.object({apkToInstall:A.object({channel:A.string(),tag:A.string().optional()}).optional(),hostname:A.string().optional(),region:A.nativeEnum(Xu).optional(),osVersion:A.nativeEnum(Ju).optional(),sessionId:A.string().optional()}),Q_=A.object({name:A.string(),webRtcUrl:A.string(),adbUrl:A.string(),token:A.string(),apkDownloadUrl:A.string().optional(),playwrightServerUrl:A.string().optional(),region:A.string().optional()}),gve=A.object({appToInstall:A.object({channel:A.string(),tag:A.string().optional()}).optional(),hostname:A.string().optional(),region:A.nativeEnum(Xu).optional(),osVersion:A.nativeEnum(Jy).optional(),sessionId:A.string().optional()}),Z_=A.object({id:A.string(),apiUrl:A.string(),webRtcUrl:A.string(),wdaUrl:A.string(),token:A.string(),appDownloadUrl:A.string().optional(),region:A.string().optional()}),Sve=A.object({channel:A.string(),tag:A.string(),md5:A.string()}),eI=A.object({id:A.string(),uploadUrl:A.string().optional(),downloadUrl:A.string(),md5:A.string().optional()}),tI=A.object({assets:A.array(A.object({channel:A.string(),tag:A.string(),md5:A.string(),platform:A.nativeEnum(gn).default("ANDROID"),createdAt:A.number().describe("Unix timestamp in milliseconds")}))}),rI=A.object({downloadUrl:A.string()});import{z as Le}from"zod";var oI=7,o$=3,nI=Le.object({quarantinedAt:Le.date(),quarantinedReason:Le.string(),quarantinedBy:Le.string().optional(),quarantinedByGitEmail:Le.string().optional(),quarantinedByGitName:Le.string().optional(),quarantinedByGitUsername:Le.string().optional()}),Tve=Le.object({localTestId:Le.string()}).merge(nI).or(Le.object({cloudTestId:Le.string()}).merge(nI)),iI=(r=>(r.QUARANTINE="QUARANTINE",r.UNQUARANTINE="UNQUARANTINE",r))(iI||{});var SE=Le.object({name:Le.string(),description:Le.string().nullish(),effect:Le.nativeEnum(iI),labels:Le.array(Le.string()).nullish(),githubRepository:Le.string().nullish(),gitlabProjectPath:Le.string().nullish(),gitBranchName:Le.string().nullish(),directory:Le.string().nullish(),slackNotificationChannel:Le.string().nullish()}),i$=Le.object({type:Le.literal("LAST_N_RUNS"),lastN:Le.number().min(o$)}),a$=Le.object({type:Le.literal("LAST_N_HOURS"),lastN:Le.number().min(1).max(oI*24)}),s$=Le.object({type:Le.literal("LAST_N_DAYS"),lastN:Le.number().min(1).max(oI)}),yE=Le.discriminatedUnion("type",[i$,a$,s$]),l$=Le.object({flakeRateThreshold:Le.number().min(1).max(100),evaluationWindow:yE}),c$=SE.extend({type:Le.literal("FLAKE_RATE"),config:l$}),u$=Le.object({passRateThreshold:Le.number().min(1).max(100),evaluationWindow:yE}),d$=SE.extend({type:Le.literal("PASS_RATE"),config:u$}),p$=Le.object({failureCountThreshold:Le.number().min(0),evaluationWindow:yE}),m$=SE.extend({type:Le.literal("FAILURE_COUNT"),config:p$}),bve=Le.discriminatedUnion("type",[c$,d$,m$]);import{z as Vt}from"zod";var Cve=Vt.object({repositoriesIndexed:Vt.boolean(),indexingInProgress:Vt.boolean(),indexesOutdated:Vt.boolean()}),aI=(a=>(a.Queued="queued",a.InProgress="in_progress",a.Completed="completed",a.Waiting="waiting",a.Requested="requested",a.Pending="pending",a))(aI||{}),sI=(s=>(s.Success="success",s.Failure="failure",s.Neutral="neutral",s.Cancelled="cancelled",s.Skipped="skipped",s.TimedOut="timed_out",s.ActionRequired="action_required",s))(sI||{}),Rve=Vt.object({name:Vt.string(),status:Vt.nativeEnum(aI),conclusion:Vt.nativeEnum(sI).nullable()}),ad=Vt.object({sha:Vt.string(),message:Vt.string(),author:Vt.object({name:Vt.string().optional(),email:Vt.string().optional(),date:Vt.coerce.date().optional()}),committer:Vt.object({name:Vt.string().optional(),email:Vt.string().optional(),date:Vt.coerce.date().optional()})}),EE=Vt.object({mergedBranch:Vt.string().optional()});import{z as _t}from"zod";var lI=_t.object({orgId:_t.string(),cacheKeys:_t.string().array()}),_ve=_t.object({keyParams:lI,clientMetadata:_t.string(),lockAcquisitionTimeoutMs:_t.number().optional()}),cI=_t.object({acquired:_t.boolean(),acquiredByMetadata:_t.string(),keyPrefix:_t.string()}),Ive=_t.object({keyPrefix:_t.string(),result:_t.string(),ttlMs:_t.number()}),Pve=_t.union([_t.object({keyPrefix:_t.string()}),lI]),f$=_t.object({remainingTtlMs:_t.number(),value:_t.string().nullish()}),Mve=_t.object({results:_t.record(_t.string(),f$),activeLocks:_t.string().array()}),uI=0,dI=5*60*1e3;var Dve=30*24*60*60*1e3,kve=7*24*60*60*1e3;import{z as pI}from"zod";var Bve=pI.object({quarantineNotifications:pI.string().nullish()});function jl(t){if(t.startsWith("https://api"))return t.replace("https://api","https://app");if(t.startsWith("http://localhost:8000"))return t.replace("http://localhost:8000","http://localhost:3000");throw new Error(`Unknown Momentic app server URL pattern: ${t}`)}import{z as hr}from"zod";var h$=hr.object({version:hr.string(),json:hr.record(hr.unknown()),hash:hr.string()}),mI=hr.record(hr.unknown()),Vve=hr.object({newSvgs:hr.array(h$),metadata:mI.optional()}),g$=hr.object({version:hr.string(),json:hr.record(hr.unknown()).nullish(),hash:hr.string(),description:hr.string().nullish(),metadata:mI.nullish()}),fI=hr.record(hr.string().describe("icon hash"),g$);import{validator as S$}from"@exodus/schemasafe";function hI(t){let e;try{e=JSON.parse(t)}catch(r){return`The schema is not valid JSON. ${r}`}try{S$(e)}catch(r){return`The schema is not a valid JSON schema. ${r}`}}var gI=t=>{t.extraHeaders&&(t.extraHeaders=Object.fromEntries(Object.entries(t.extraHeaders).filter(([e,r])=>e.trim()&&r.trim())))};import{z as sAe}from"zod";var Wm=class{async resolveStepCacheEntries(){}async saveStepCacheEntries(){}};function y$(t){return t.map(e=>({...e,environment:void 0}))}function TE(t,e){return e?t:y$(t)}var yn="get_browser_state",$m="get_environment_variables",qm="reset_session",Ho="run_step",jn="preview_preflight",SI="preview_ensure",sr="preview_step",Km="test_get",lr="test_splice_steps",Ym="module_create",yI="momentic_module_create",Vl="momentic_module_get",Xm="momentic_module_list",ta="momentic_module_recommend",EI="momentic_attributes_list",TI="momentic_test_create",bI="momentic_test_splice_steps",vI="momentic_run_step",AI="momentic_session_start",CI="momentic_session_terminate",RI="momentic_get_session_state",wI="momentic_get_environment_variables",ls="momentic_get_initial_data",xI="momentic_preview_step";var vE="browser-crash-dump.zip",bE=class{loggerBindings;attachBeforeScreenshot(){}attachAfterScreenshot(){}attachBeforeHtmlSnapshot(){}attachAfterHtmlSnapshot(){}recordTargetAutoHeal(){}recordStepDuration(){}storeTraceAsset(){}async finish(){}async startSubSteps(){return new sd}},sd=class{async getScreenshot(){}async getHtmlSnapshot(){}async startStep(){return new bE}};import{z as AE}from"zod";var TAe=AE.object({parentStepIdChain:AE.array(AE.string()),result:Eo});import{z as oe}from"zod";var gr="assets",E$=oe.object({step:Nt,status:oe.nativeEnum(at),startedAt:oe.coerce.date(),finishedAt:oe.coerce.date().optional(),healMetadata:oe.object({healType:oe.nativeEnum(Eu).or(oe.literal("AI")),healedAt:oe.coerce.date()}).optional(),beforeSnapshotId:oe.string().uuid().optional(),afterSnapshotId:oe.string().uuid().optional(),message:oe.string().optional()}),T$=E$.extend({finishedAt:oe.coerce.date().optional().transform(t=>t??new Date)}),PAe=T$.extend({step:oe.unknown()}),CE=oe.object({avdId:oe.string().optional(),channel:oe.string().optional(),tag:oe.string().optional()}),_I="1.0.0",RE=G_.extend({id:oe.string().uuid().optional(),startedAt:oe.coerce.date(),runAttemptSchemaVersion:oe.string().optional(),schemaVersion:oe.string().optional().default("1.0.19"),results:oe.record(oe.string(),oe.unknown()).array().optional(),beforeResults:oe.record(oe.string(),oe.unknown()).array().optional(),afterResults:oe.record(oe.string(),oe.unknown()).array().optional(),assetDetails:CE.optional(),activeVideos:oe.array(oe.object({videoName:oe.string(),timestamp:oe.coerce.date()})).optional()}),II=RE.extend({assetDetails:CE.optional(),finishedAt:oe.coerce.date().optional().transform(t=>t??new Date)}),MAe=RE.merge(bu),OAe=II.merge(bu),PI=oe.object({results:oe.array(Eo),beforeResults:oe.array(Eo).optional(),afterResults:oe.array(Eo).optional()}),LAe=RE.merge(PI),NAe=II.merge(PI),MI=H_.merge(B_).extend({executionType:oe.nativeEnum(vl).optional().default("WEB"),testId:oe.string().uuid(),testDescription:oe.string().optional(),directory:oe.string().optional(),runGroupId:oe.string().uuid(),status:oe.nativeEnum(nt),startedAt:oe.coerce.date(),attempts:oe.number(),failureRecoveryDetails:oe.object({attempts:oe.number()}).optional(),aiSettings:pi.optional(),avgCpuUsage:oe.number().optional(),avgMemoryUsage:oe.number().optional()}),b$=MI.merge(CE),OI=MI.extend({finishedAt:oe.coerce.date().optional().transform(t=>t??new Date)}),DAe=b$.extend({finishedAt:oe.coerce.date().optional().transform(t=>t??new Date)}),v$=F_.merge(U_).extend({id:oe.string().uuid().optional(),startedAt:oe.coerce.date(),cliVersion:oe.string(),labels:oe.string().array().optional().default([]),suiteName:oe.string().optional(),ciProvider:oe.string().optional()}),Wl=v$.extend({updatedAt:oe.coerce.date().optional().transform(t=>t??new Date),finishedAt:oe.coerce.date().optional().transform(t=>t??new Date)});var A$=new Set(["AWAIT_LISTENER","REGISTER_REQUEST_LISTENER","GET_RECORDED_REQUESTS","MOCK_ROUTE","REMOVE_ROUTE_MOCK","SCROLL_DOWN","SCROLL_UP","SCROLL_LEFT","SCROLL_RIGHT","VISUAL_DIFF","WAIT","SET_HEADER","OFFLINE_MODE"]),C$=new Set(["MODULE","RESOLVED_MODULE"]),GAe=new Set(["MOBILE_MODULE_STEP","RESOLVED_MOBILE_MODULE"]);function Jm(t){return t.type!=="PRESET_ACTION"?t.type:t.command.type}function Qm(t){return C$.has(t.type)?!1:t.type!=="PRESET_ACTION"?!0:!A$.has(t.command.type)}var vRe=5*1024,R$="...[truncated]",ARe=Buffer.byteLength(R$,"utf8");import x$ from"fetch-retry";import _$ from"os";import NI,{multistream as I$}from"pino";import P$ from"pino-pretty";import M$ from"pino-std-serializers";var ld;function LI(t){ld=t}var w$=new Set(["InternalWebAgentError","InternalPlatformError","UnknownError"]);function wE(t){return t instanceof Error&&t.name==="AbortError"?!1:t instanceof L?w$.has(t.reason):!0}var $l=new Map,O$=!0,DI="Log throttle exceeded",L$=100,N$=5e3,D$=x$(global.fetch,{retries:2,retryOn:function(t,e,r){return!!(e!==null||r&&r.status>=500)},retryDelay:function(t){return Math.pow(2,t)*500}}),xE=class t{consoleLogger;hostname;captureExceptions;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:r,disableConsoleLogs:n,flushIntervalMs:o,maxBatchSize:i,captureExceptions:a}){this.hostname=r??_$.hostname(),this.disableConsoleLogs=n,this.captureExceptions=a??!1,this.bindingAttributes={...e,env:"production"},this.flushIntervalMs=o??5e3,this.maxBatchSize=i??10;let s={base:this.bindingAttributes,errorKey:"err",level:"debug"};this.consoleLogger=O$?NI(s):NI(s,I$([{stream:P$({colorize:!0})}]))}child(e){return new t({bindings:{...this.bindingAttributes,...e},hostname:this.hostname,disableConsoleLogs:this.disableConsoleLogs,flushIntervalMs:this.flushIntervalMs,maxBatchSize:this.maxBatchSize,captureExceptions:this.captureExceptions})}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 r=await D$(this.site,{method:"POST",headers:{"Content-Type":"application/json","signoz-access-token":"CumAaTMUcwjt05OddAmefKgshbhfRmWxzxih"},body:as(e),signal:AbortSignal.timeout(5e3)});if(!r.ok)throw new Error(`Got error status (${r.statusText}) from SigNoz`)}catch{}}shouldAllowLog(e){if(e===DI)return!0;let r=Date.now();return r-this.lastWindowStart>N$&&(this.logsInCurrentWindow=0,this.droppedLogsInWindow&&this.log("error",void 0,DI),this.droppedLogsInWindow=!1,this.lastWindowStart=r),this.logsInCurrentWindow<L$?(this.logsInCurrentWindow++,!0):(this.droppedLogsInWindow=!0,!1)}log(e,r,n,...o){try{this.logHelper(e,r,n,...o)}catch(i){this.consoleLogger.warn(`Failed to log to Signoz: ${i}`)}}logHelper(e,r,n,...o){if(id[e]<this.minLevelValue||!this.shouldAllowLog(n))return;e==="error"&&this.captureExceptions&&ld&&(r instanceof Error&&wE(r)?ld(r):typeof r=="object"&&r&&"err"in r&&r.err instanceof Error&&wE(r.err)&&ld(r.err)),typeof r=="string"&&!n&&(r={message:r}),typeof r=="object"&&r&&"err"in r&&r.err instanceof Error&&(r.err=M$.err(r.err));let i={...this.bindingAttributes,...r&&typeof r=="object"?r:{},...o.length>0?{args:o}:{}},a={host:this.hostname,env:this.bindingAttributes.env};this.disableConsoleLogs||this.consoleLogger[e](i,n,...o);let s={timestamp:Math.round(Date.now()*1e6),severity_text:e.toUpperCase(),resources:a,attributes:{},body:f_({message:n||"",...i})};this.buffer.push(s),this.buffer.length>=this.maxBatchSize?(this.flushTimer&&(clearTimeout(this.flushTimer),this.flushTimer=void 0),this.flushBuffer()):this.scheduleFlush()}setApp(e){let r=this.bindingAttributes.app;this.bindingAttributes.app=e,$l.set("app",this),$l.delete(r)}debug(e,r,...n){this.log("debug",e,r,...n)}info(e,r,...n){this.log("info",e,r,...n)}warn(e,r,...n){this.log("warn",e,r,...n)}error(e,r,...n){this.log("error",e,r,...n)}bindings(){return this.bindingAttributes}addBinding(e,r){this.bindingAttributes[e]=r}setMinLevel(e){typeof e=="number"?(this.minLevelValue=e,this.consoleLogger.level=h_[e]):(this.minLevelValue=id[e],this.consoleLogger.level=e)}enableConsoleLogs(){this.disableConsoleLogs=!1}},ql=({app:t,hostname:e,disableConsoleLogs:r,captureExceptions:n})=>($l.has(t)||$l.set(t,new xE({bindings:{app:t},hostname:e,disableConsoleLogs:r,captureExceptions:n})),$l.get(t));async function Zm(){await Promise.all([...$l.values()].map(t=>t.flush()))}import{PostHog as k$}from"posthog-node";var ra=class extends Error{constructor(e){super(e),this.name="TimeoutError"}};var FI=t=>{let e=t.reason===void 0?new DOMException("This operation was aborted.","AbortError"):t.reason;return e instanceof Error?e:new DOMException(e,"AbortError")};function J(t,e){let{milliseconds:r,fallback:n,message:o,customTimers:i={setTimeout,clearTimeout}}=e,a;if(typeof r!="number"||Math.sign(r)!==1)throw new TypeError(`Expected \`milliseconds\` to be a positive number, got \`${r}\``);return new Promise((s,c)=>{let l;if(e.signal){let{signal:p}=e;if(p.aborted)return c(FI(p));l=()=>c(FI(p)),p.addEventListener("abort",l,{once:!0})}let u=()=>{if(e.signal&&e.signal.removeEventListener("abort",l),n)try{s(n())}catch(p){c(p)}else{typeof t.cancel=="function"&&Promise.resolve().then(()=>t.cancel()).catch(()=>{});let p=o instanceof Error?o:new ra(o??`Promise timed out after ${r}ms`);c(p)}};r<1/0&&(a=i.setTimeout(u,r));let d=()=>{i.clearTimeout(a),e.signal&&e.signal.removeEventListener("abort",l)};Promise.resolve(t).then(p=>{d(),s(p)}).catch(p=>{d(),c(p)})})}async function UI(t,e){let r,n=0,o=3,i,a;for(;n<o;)try{let s=await J(t.getAllFlagsAndPayloads("unknown",{personProperties:{organizationId:e}}),{milliseconds:5e3});i=s.featureFlags||{},a=s.featureFlagPayloads||{};break}catch(s){r=s,n++,await new Promise(c=>setTimeout(c,100*n))}if(i&&a)return{flags:i,payloads:a};throw r}var ef=class t extends nd{constructor(r,n,o,i){super(o,i);this.client=r;this.orgId=n}static async init(r){let n=new k$("phc_WRWd8LYIv6rolgDsyCdrPpxtZhsu6qXAkEwPicl44bI",{host:"https://us.i.posthog.com"}),{flags:o,payloads:i}=await UI(n,r);return new t(n,r,o,i)}async refresh(){let{flags:r,payloads:n}=await UI(this.client,this.orgId);this.flags=r,this.payloads=n}};import{randomUUID as F$}from"node:crypto";import{PostHog as U$}from"posthog-node";var tf=class t{identity;bindings;client;options;constructor(e,r={},n){this.bindings=e,this.options=r,this.identity=n,this.client=new U$("phc_oy1FexHsc0S3axxOMXCm46yZsW35zROAoV4SOzpDSXH",{host:"https://us.i.posthog.com",...r})}async shutdown(){await this.client.shutdown()}identify(e,r){return this.identity=e,this.bindings={...this.bindings,...r},this}child(e){return new t({...this.bindings,...e},this.options,this.identity)}track(e,r){if(!cx(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:this.identity?.userId??F$(),event:n,timestamp:r?.timestamp,properties:{...this.bindings,...o,organizationId:this.identity?.orgId}}),this}};import{execSync as B$}from"child_process";import{readFileSync as HI}from"fs";import gi from"os";import z$ from"v8";var cs=!!process.env.CI||!!process.env.GITHUB_ACTIONS||!!process.env.GITHUB_RUN_ID||!!process.env.GITLAB_CI||!!process.env.CI_COMMIT_SHA||!!process.env.JENKINS_URL||!!process.env.BUILD_NUMBER||!!process.env.JENKINS_HOME||!!process.env.CIRCLECI||!!process.env.CIRCLE_BUILD_NUM||!!process.env.TRAVIS||!!process.env.TRAVIS_BUILD_NUMBER||!!process.env.BITBUCKET_BUILD_NUMBER||!!process.env.BITBUCKET_COMMIT||!!process.env.CODEBUILD_BUILD_ID||!!process.env.TF_BUILD||!!process.env.BUILD_BUILDID||!!process.env.AGENT_ID||!!process.env.BUILDER_SA_EMAIL||!!process.env.HEROKU_TEST_RUN_ID||!!process.env.CI_NODE_INDEX||!!process.env.TEAMCITY_VERSION||!!process.env.BUILD_VCS_NUMBER||!!process.env.BUILDKITE||!!process.env.BUILDKITE_BUILD_NUMBER||!!process.env.APPVEYOR||!!process.env.APPVEYOR_BUILD_NUMBER||!!process.env.DRONE||!!process.env.DRONE_BUILD_NUMBER||!!process.env.SHIPPABLE||!!process.env.BUILD_URL||!!process.env.SEMAPHORE||!!process.env.SEMAPHORE_EXECUTABLE_UUID||!!process.env.WOODPECKER||!!process.env.CI_BUILD_NUMBER||!!process.env.WERCKER_MAIN_PIPELINE_STARTED||!!process.env.BUDDY_EXECUTION_ID;var H$=2e3,us=t=>Number.parseInt(t,10),PE=t=>HI(t,"utf8").trim(),Kl=t=>us(PE(t)),BI,rf,_E=0,of=gi.platform(),G$=gi.cpus().map(t=>({model:t.model,speed:t.speed})).reduce((t,e)=>(t[e.model]={speed:e.speed},t.totalCores=(t.totalCores??0)+1,t),{});function IE(t=Date.now()){let e=gi.cpus(),r={measurementTime:t,user:0,nice:0,sys:0,idle:0,irq:0,total:0};for(let n of e)r.user+=n.times.user,r.nice+=n.times.nice,r.sys+=n.times.sys,r.idle+=n.times.idle,r.irq+=n.times.irq;return r.total=r.user+r.nice+r.sys+r.idle+r.irq,r}function GI(t,e){let r={user:e.user-t.user,nice:e.nice-t.nice,sys:e.sys-t.sys,idle:e.idle-t.idle,irq:e.irq-t.irq,total:e.total-t.total};return r.total<=0?null:{measurementTime:e.measurementTime,intervalMs:e.measurementTime-t.measurementTime,user:r.user/r.total*100,nice:r.nice/r.total*100,sys:r.sys/r.total*100,idle:r.idle/r.total*100,irq:r.irq/r.total*100,total:100-r.idle/r.total*100}}function j$(){let t=IE();return()=>{let e=IE(),r=GI(t,e);return t=e,r}}function zI(){try{let e=HI("/sys/fs/cgroup/cpu.stat","utf8").match(/^usage_usec\s+(\d+)/m);if(e?.[1])return us(e[1])}catch{}try{let t=Kl("/sys/fs/cgroup/cpuacct/cpuacct.usage");if(!isNaN(t))return t/1e3}catch{}return null}function V$(){try{let e=PE("/sys/fs/cgroup/cpu.max").split(" "),r=e[0],n=e[1];return!r||!n||r==="max"?null:us(r)/us(n)}catch{}try{let t=Kl("/sys/fs/cgroup/cpu/cpu.cfs_quota_us"),e=Kl("/sys/fs/cgroup/cpu/cpu.cfs_period_us");return t===-1||isNaN(e)?null:t/e}catch{return null}}function W$(){if(of!=="linux")return null;let t=zI();if(t===null)return null;let e=V$()??gi.cpus().length,r=t,n=Date.now();return()=>{let o=zI();if(o===null)return null;let i=Date.now(),a=i-n;if(a<=0)return null;let s=o-r,c=a*1e3,l=Math.max(0,Math.min(100,s/c/e*100));return r=o,n=i,{measurementTime:i,intervalMs:a,user:l,nice:0,sys:0,idle:Math.max(0,100-l),irq:0,total:l}}}function $$(){let t=process.cpuUsage(),e=process.hrtime.bigint();return()=>{let r=process.cpuUsage(),n=process.hrtime.bigint(),o=Number(n-e)/1e6,i=r.user-t.user,a=r.system-t.system;if(t=r,e=n,o<=0)return null;let s=Math.max(gi.cpus().length,1),c=l=>Math.max(0,l/1e3/o*100/s);return{total:c(i+a),user:c(i),sys:c(a),intervalMs:o}}}function jI({intervalMs:t=H$,maxSamples:e=1e4,keepSamples:r=!0,onSample:n}={}){let o=[],i=W$()??j$(),a=$$(),s=()=>{let u=Date.now(),d=$I(),p=process.memoryUsage(),m=i(),f=a(),h={timestamp:u,system:{cpu:m,memory:{total:d.totalMemory,free:d.freeMemory,freePercentage:d.freePercentage}},process:{cpu:f,memory:{rss:p.rss,heapTotal:p.heapTotal,heapUsed:p.heapUsed,external:p.external,arrayBuffers:p.arrayBuffers}}};n?.(h),r&&(o.push(h),o.length>e&&o.shift())};s();let c=setInterval(s,t),l=u=>({samples:r?[...o]:[]});return{stop:()=>(clearInterval(c),l(Date.now())),getSeries:()=>l(Date.now())}}var nf=t=>{try{let e={},r=!1,n=$I(),o=K$(),i=`${Math.round(n.freePercentage*100)}%`;n.freePercentage<.05&&(Object.assign(e,process.memoryUsage()),r=!0);let a=`${o?Math.round(o.idle):"unknown"}%`;o&&o?.total>80&&(r=!0);let s=z$.getHeapStatistics(),c=s.used_heap_size,l=s.heap_size_limit;c/l>.9&&(r=!0),r?(_E++,t.warn({memory:n,cpu:o,heapStats:s,...e},"Critical resource usage metrics detected"),cs&&_E>=2&&v.warn(`Low machine resources detected (memory: ${i} free, cpu: ${a} free)`)):(_E=0,t.debug({memory:n,cpu:o},"Got machine resource usage metrics"))}catch{}},VI=t=>{nf(t),setTimeout(()=>nf(t),5e3)};function WI(t){if(!Gn)return nf(t),{interval:setInterval(()=>nf(t),2e4),cpuMetadata:G$,platform:of}}function q$(){if(of!=="linux")return null;try{let t=PE("/sys/fs/cgroup/memory.max"),e=Kl("/sys/fs/cgroup/memory.current");if(t==="max"||isNaN(e))return null;let r=us(t);if(isNaN(r))return null;let n=Math.max(0,r-e);return{totalMemory:r,freeMemory:n,freePercentage:n/r}}catch{}try{let t=Kl("/sys/fs/cgroup/memory/memory.limit_in_bytes"),e=Kl("/sys/fs/cgroup/memory/memory.usage_in_bytes");if(isNaN(t)||isNaN(e))return null;let r=gi.totalmem();if(t>=r)return null;let n=Math.max(0,t-e);return{totalMemory:t,freeMemory:n,freePercentage:n/t}}catch{return null}}function $I(){let t=q$();if(t)return t;let e=gi.totalmem(),r=of==="darwin"?Y$():(()=>{let o=gi.freemem();return{availableMemory:o,rawFreeMemory:o,cachedMemory:0}})(),n=r.availableMemory/e;return{totalMemory:e,freeMemory:r.availableMemory,freePercentage:n}}function K$(){let t=IE();if(!rf)return rf=t,null;let e=GI(rf,t);return rf=t,e?(BI=e,BI):null}function Y$(){try{let t=B$("/usr/bin/vm_stat",{encoding:"utf8",stdio:["pipe","pipe","ignore"]}),r=t.match(/page size of (\d+) bytes/)?.[1],n=r?us(r):4096,o=u=>{let p=t.match(new RegExp(`${u}:\\s+(\\d+)\\.`,"i"))?.[1];return p?us(p):0},i=o("Pages free"),a=o("Pages inactive"),s=o("Pages speculative"),c=i*n,l=(a+s)*n;return{availableMemory:c+l,rawFreeMemory:c,cachedMemory:l}}catch{let t=gi.freemem();return{availableMemory:t,rawFreeMemory:t,cachedMemory:0}}}var af=class{increment(e,r,n){}gauge(e,r){}distribution(e,r,n){}async flush(){}async recordDuration({fn:e}){return await e()}};function X$(t){if(!t||t.length===0)return{};let e={};for(let r of t){let n=r.indexOf(":");if(n>-1){let o=r.slice(0,n).trim(),i=r.slice(n+1).trim();o&&(e[o]=i);continue}e[r]=!0}return e}function sf(t,e){let r=X$(t);return!e||Object.keys(e).length===0?r:{...e,...r}}var EP="=",df=";",GE=",";var TP=8192;var Ql={};O1(Ql,{getKeyPairs:()=>Iq,parseKeyPairsIntoRecord:()=>Pq,parsePairKeyValue:()=>bP,serializeKeyPairs:()=>_q});yt();var xq=function(t,e){var r=typeof Symbol=="function"&&t[Symbol.iterator];if(!r)return t;var n=r.call(t),o,i=[],a;try{for(;(e===void 0||e-- >0)&&!(o=n.next()).done;)i.push(o.value)}catch(s){a={error:s}}finally{try{o&&!o.done&&(r=n.return)&&r.call(n)}finally{if(a)throw a.error}}return i};function _q(t){return t.reduce(function(e,r){var n=""+e+(e!==""?GE:"")+r;return n.length>TP?e:n},"")}function Iq(t){return t.getAllEntries().map(function(e){var r=xq(e,2),n=r[0],o=r[1],i=encodeURIComponent(n)+"="+encodeURIComponent(o.value);return o.metadata!==void 0&&(i+=df+o.metadata.toString()),i})}function bP(t){var e=t.split(df);if(!(e.length<=0)){var r=e.shift();if(r){var n=r.indexOf(EP);if(!(n<=0)){var o=decodeURIComponent(r.substring(0,n).trim()),i=decodeURIComponent(r.substring(n+1).trim()),a;return e.length>0&&(a=OE(e.join(df))),{key:o,value:i,metadata:a}}}}}function Pq(t){return typeof t!="string"||t.length===0?{}:t.split(GE).map(function(e){return bP(e)}).filter(function(e){return e!==void 0&&e.value.length>0}).reduce(function(e,r){return e[r.key]=r.value,e},{})}yt();var pf;(function(t){t.AlwaysOff="always_off",t.AlwaysOn="always_on",t.ParentBasedAlwaysOff="parentbased_always_off",t.ParentBasedAlwaysOn="parentbased_always_on",t.ParentBasedTraceIdRatio="parentbased_traceidratio",t.TraceIdRatio="traceidratio"})(pf||(pf={}));var Mq=",",Oq=["OTEL_SDK_DISABLED"];function Lq(t){return Oq.indexOf(t)>-1}var Nq=["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 Dq(t){return Nq.indexOf(t)>-1}var kq=["OTEL_NO_PATCH_MODULES","OTEL_PROPAGATORS"];function Fq(t){return kq.indexOf(t)>-1}var jE=1/0,VE=128,Uq=128,Bq=128,WE={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:At.INFO,OTEL_NO_PATCH_MODULES:[],OTEL_PROPAGATORS:["tracecontext","baggage"],OTEL_RESOURCE_ATTRIBUTES:"",OTEL_SERVICE_NAME:"",OTEL_ATTRIBUTE_VALUE_LENGTH_LIMIT:jE,OTEL_ATTRIBUTE_COUNT_LIMIT:VE,OTEL_SPAN_ATTRIBUTE_VALUE_LENGTH_LIMIT:jE,OTEL_SPAN_ATTRIBUTE_COUNT_LIMIT:VE,OTEL_LOGRECORD_ATTRIBUTE_VALUE_LENGTH_LIMIT:jE,OTEL_LOGRECORD_ATTRIBUTE_COUNT_LIMIT:VE,OTEL_SPAN_EVENT_COUNT_LIMIT:128,OTEL_SPAN_LINK_COUNT_LIMIT:128,OTEL_SPAN_ATTRIBUTE_PER_EVENT_COUNT_LIMIT:Uq,OTEL_SPAN_ATTRIBUTE_PER_LINK_COUNT_LIMIT:Bq,OTEL_TRACES_EXPORTER:"",OTEL_TRACES_SAMPLER:pf.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 zq(t,e,r){if(!(typeof r[t]>"u")){var n=String(r[t]);e[t]=n.toLowerCase()==="true"}}function Hq(t,e,r,n,o){if(n===void 0&&(n=-1/0),o===void 0&&(o=1/0),typeof r[t]<"u"){var i=Number(r[t]);isNaN(i)||(i<n?e[t]=n:i>o?e[t]=o:e[t]=i)}}function Gq(t,e,r,n){n===void 0&&(n=Mq);var o=r[t];typeof o=="string"&&(e[t]=o.split(n).map(function(i){return i.trim()}))}var jq={ALL:At.ALL,VERBOSE:At.VERBOSE,DEBUG:At.DEBUG,INFO:At.INFO,WARN:At.WARN,ERROR:At.ERROR,NONE:At.NONE};function Vq(t,e,r){var n=r[t];if(typeof n=="string"){var o=jq[n.toUpperCase()];o!=null&&(e[t]=o)}}function vP(t){var e={};for(var r in WE){var n=r;switch(n){case"OTEL_LOG_LEVEL":Vq(n,e,t);break;default:if(Lq(n))zq(n,e,t);else if(Dq(n))Hq(n,e,t);else if(Fq(n))Gq(n,e,t);else{var o=t[n];typeof o<"u"&&o!==null&&(e[n]=String(o))}}}return e}function Sr(){var t=vP(process.env);return Object.assign({},WE,t)}function AP(t){return t>=48&&t<=57?t-48:t>=97&&t<=102?t-87:t-55}function mf(t){for(var e=new Uint8Array(t.length/2),r=0,n=0;n<t.length;n+=2){var o=AP(t.charCodeAt(n)),i=AP(t.charCodeAt(n+1));e[r++]=o<<4|i}return e}var CP="1.25.1";var Wq="deployment.environment";var $q="process.runtime.name";var qq="service.name";var Kq="service.instance.id";var Yq="telemetry.sdk.name",Xq="telemetry.sdk.language",Jq="telemetry.sdk.version";var RP=Wq;var wP=$q;var ff=qq;var xP=Kq;var hd=Yq,gd=Xq,Sd=Jq;var Qq="nodejs";var _P=Qq;var Zl,hf=(Zl={},Zl[hd]="opentelemetry",Zl[wP]="node",Zl[gd]=_P,Zl[Sd]=CP,Zl);var Zq=9,eK=6,tK=Math.pow(10,eK),rK=Math.pow(10,Zq);function IP(t){var e=t/1e3,r=Math.trunc(e),n=Math.round(t%1e3*tK);return[r,n]}function PP(t){return t[0]*rK+t[1]}function yd(t){return t[0]*1e6+t[1]/1e3}var ps;(function(t){t[t.SUCCESS=0]="SUCCESS",t[t.FAILED=1]="FAILED"})(ps||(ps={}));var MP=function(){function t(){var e=this;this._promise=new Promise(function(r,n){e._resolve=r,e._reject=n})}return Object.defineProperty(t.prototype,"promise",{get:function(){return this._promise},enumerable:!1,configurable:!0}),t.prototype.resolve=function(e){this._resolve(e)},t.prototype.reject=function(e){this._reject(e)},t}();var nK=function(t,e){var r=typeof Symbol=="function"&&t[Symbol.iterator];if(!r)return t;var n=r.call(t),o,i=[],a;try{for(;(e===void 0||e-- >0)&&!(o=n.next()).done;)i.push(o.value)}catch(s){a={error:s}}finally{try{o&&!o.done&&(r=n.return)&&r.call(n)}finally{if(a)throw a.error}}return i},oK=function(t,e,r){if(r||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 t.concat(i||Array.prototype.slice.call(e))},OP=function(){function t(e,r){this._callback=e,this._that=r,this._isCalled=!1,this._deferred=new MP}return Object.defineProperty(t.prototype,"isCalled",{get:function(){return this._isCalled},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"promise",{get:function(){return this._deferred.promise},enumerable:!1,configurable:!0}),t.prototype.call=function(){for(var e,r=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,oK([this._that],nK(n),!1))).then(function(i){return r._deferred.resolve(i)},function(i){return r._deferred.reject(i)})}catch(i){this._deferred.reject(i)}}return this._deferred.promise},t}();var Vn;(function(t){t[t.DELTA=0]="DELTA",t[t.CUMULATIVE=1]="CUMULATIVE"})(Vn||(Vn={}));var Lr;(function(t){t[t.HISTOGRAM=0]="HISTOGRAM",t[t.EXPONENTIAL_HISTOGRAM=1]="EXPONENTIAL_HISTOGRAM",t[t.GAUGE=2]="GAUGE",t[t.SUM=3]="SUM"})(Lr||(Lr={}));var iK=function(){var t=function(e,r){return t=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])},t(e,r)};return function(e,r){if(typeof r!="function"&&r!==null)throw new TypeError("Class extends value "+String(r)+" is not a constructor or null");t(e,r);function n(){this.constructor=e}e.prototype=r===null?Object.create(r):(n.prototype=r.prototype,new n)}}();var x_e=function(t){iK(e,t);function e(r){var n=t.call(this,r)||this;return Object.setPrototypeOf(n,e.prototype),n}return e}(Error);function LP(t,e){for(var r=0,n=t.length-1;n-r>1;){var o=Math.trunc((n+r)/2);t[o]<=e?r=o:n=o-1}return t[n]<=e?n:t[r]<=e?r:-1}yt();var Wn;(function(t){t[t.DROP=0]="DROP",t[t.SUM=1]="SUM",t[t.LAST_VALUE=2]="LAST_VALUE",t[t.HISTOGRAM=3]="HISTOGRAM",t[t.EXPONENTIAL_HISTOGRAM=4]="EXPONENTIAL_HISTOGRAM"})(Wn||(Wn={}));var NP=function(){function t(){this.kind=Wn.DROP}return t.prototype.createAccumulation=function(){},t.prototype.merge=function(e,r){},t.prototype.diff=function(e,r){},t.prototype.toMetricData=function(e,r,n,o){},t}();var ze;(function(t){t.COUNTER="COUNTER",t.GAUGE="GAUGE",t.HISTOGRAM="HISTOGRAM",t.UP_DOWN_COUNTER="UP_DOWN_COUNTER",t.OBSERVABLE_COUNTER="OBSERVABLE_COUNTER",t.OBSERVABLE_GAUGE="OBSERVABLE_GAUGE",t.OBSERVABLE_UP_DOWN_COUNTER="OBSERVABLE_UP_DOWN_COUNTER"})(ze||(ze={}));var aK=function(t,e){var r=typeof Symbol=="function"&&t[Symbol.iterator];if(!r)return t;var n=r.call(t),o,i=[],a;try{for(;(e===void 0||e-- >0)&&!(o=n.next()).done;)i.push(o.value)}catch(s){a={error:s}}finally{try{o&&!o.done&&(r=n.return)&&r.call(n)}finally{if(a)throw a.error}}return i};function sK(t){var e=t.map(function(){return 0});return e.push(0),{buckets:{boundaries:t,counts:e},sum:0,count:0,hasMinMax:!1,min:1/0,max:-1/0}}var $E=function(){function t(e,r,n,o){n===void 0&&(n=!0),o===void 0&&(o=sK(r)),this.startTime=e,this._boundaries=r,this._recordMinMax=n,this._current=o}return t.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 r=LP(this._boundaries,e);this._current.buckets.counts[r+1]+=1}},t.prototype.setStartTime=function(e){this.startTime=e},t.prototype.toPointValue=function(){return this._current},t}();var qE=function(){function t(e,r){this._boundaries=e,this._recordMinMax=r,this.kind=Wn.HISTOGRAM}return t.prototype.createAccumulation=function(e){return new $E(e,this._boundaries,this._recordMinMax)},t.prototype.merge=function(e,r){for(var n=e.toPointValue(),o=r.toPointValue(),i=n.buckets.counts,a=o.buckets.counts,s=new Array(i.length),c=0;c<i.length;c++)s[c]=i[c]+a[c];var l=1/0,u=-1/0;return this._recordMinMax&&(n.hasMinMax&&o.hasMinMax?(l=Math.min(n.min,o.min),u=Math.max(n.max,o.max)):n.hasMinMax?(l=n.min,u=n.max):o.hasMinMax&&(l=o.min,u=o.max)),new $E(e.startTime,n.buckets.boundaries,this._recordMinMax,{buckets:{boundaries:n.buckets.boundaries,counts:s},count:n.count+o.count,sum:n.sum+o.sum,hasMinMax:this._recordMinMax&&(n.hasMinMax||o.hasMinMax),min:l,max:u})},t.prototype.diff=function(e,r){for(var n=e.toPointValue(),o=r.toPointValue(),i=n.buckets.counts,a=o.buckets.counts,s=new Array(i.length),c=0;c<i.length;c++)s[c]=a[c]-i[c];return new $E(r.startTime,n.buckets.boundaries,this._recordMinMax,{buckets:{boundaries:n.buckets.boundaries,counts:s},count:o.count-n.count,sum:o.sum-n.sum,hasMinMax:!1,min:1/0,max:-1/0})},t.prototype.toMetricData=function(e,r,n,o){return{descriptor:e,aggregationTemporality:r,dataPointType:Lr.HISTOGRAM,dataPoints:n.map(function(i){var a=aK(i,2),s=a[0],c=a[1],l=c.toPointValue(),u=e.type===ze.GAUGE||e.type===ze.UP_DOWN_COUNTER||e.type===ze.OBSERVABLE_GAUGE||e.type===ze.OBSERVABLE_UP_DOWN_COUNTER;return{attributes:s,startTime:c.startTime,endTime:o,value:{min:l.hasMinMax?l.min:void 0,max:l.hasMinMax?l.max:void 0,sum:u?void 0:l.sum,buckets:l.buckets,count:l.count}}})}},t}();yt();var KE=function(t,e){var r=typeof Symbol=="function"&&t[Symbol.iterator];if(!r)return t;var n=r.call(t),o,i=[],a;try{for(;(e===void 0||e-- >0)&&!(o=n.next()).done;)i.push(o.value)}catch(s){a={error:s}}finally{try{o&&!o.done&&(r=n.return)&&r.call(n)}finally{if(a)throw a.error}}return i},YE=function(t,e,r){if(r||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 t.concat(i||Array.prototype.slice.call(e))},XE=function(){function t(e,r,n,o){e===void 0&&(e=new lK),r===void 0&&(r=0),n===void 0&&(n=0),o===void 0&&(o=0),this.backing=e,this.indexBase=r,this.indexStart=n,this.indexEnd=o}return Object.defineProperty(t.prototype,"offset",{get:function(){return this.indexStart},enumerable:!1,configurable:!0}),Object.defineProperty(t.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}),t.prototype.counts=function(){var e=this;return Array.from({length:this.length},function(r,n){return e.at(n)})},t.prototype.at=function(e){var r=this.indexBase-this.indexStart;return e<r&&(e+=this.backing.length),e-=r,this.backing.countAt(e)},t.prototype.incrementBucket=function(e,r){this.backing.increment(e,r)},t.prototype.decrementBucket=function(e,r){this.backing.decrement(e,r)},t.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()},t.prototype.downscale=function(e){this._rotate();for(var r=1+this.indexEnd-this.indexStart,n=1<<e,o=0,i=0,a=this.indexStart;a<=this.indexEnd;){var s=a%n;s<0&&(s+=n);for(var c=s;c<n&&o<r;c++)this._relocateBucket(i,o),o++,a++;i++}this.indexStart>>=e,this.indexEnd>>=e,this.indexBase=this.indexStart},t.prototype.clone=function(){return new t(this.backing.clone(),this.indexBase,this.indexStart,this.indexEnd)},t.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)},t.prototype._relocateBucket=function(e,r){e!==r&&this.incrementBucket(e,this.backing.emptyBucket(r))},t}();var lK=function(){function t(e){e===void 0&&(e=[0]),this._counts=e}return Object.defineProperty(t.prototype,"length",{get:function(){return this._counts.length},enumerable:!1,configurable:!0}),t.prototype.countAt=function(e){return this._counts[e]},t.prototype.growTo=function(e,r,n){var o=new Array(e).fill(0);o.splice.apply(o,YE([n,this._counts.length-r],KE(this._counts.slice(r)),!1)),o.splice.apply(o,YE([0,r],KE(this._counts.slice(0,r)),!1)),this._counts=o},t.prototype.reverse=function(e,r){for(var n=Math.floor((e+r)/2)-e,o=0;o<n;o++){var i=this._counts[e+o];this._counts[e+o]=this._counts[r-o-1],this._counts[r-o-1]=i}},t.prototype.emptyBucket=function(e){var r=this._counts[e];return this._counts[e]=0,r},t.prototype.increment=function(e,r){this._counts[e]+=r},t.prototype.decrement=function(e,r){this._counts[e]>=r?this._counts[e]-=r:this._counts[e]=0},t.prototype.clone=function(){return new t(YE([],KE(this._counts),!1))},t}();var DP=52,cK=2146435072,uK=1048575,JE=1023,gf=-JE+1,Sf=JE,Ed=Math.pow(2,-1022);function yf(t){var e=new DataView(new ArrayBuffer(8));e.setFloat64(0,t);var r=e.getUint32(0),n=(r&cK)>>20;return n-JE}function Ef(t){var e=new DataView(new ArrayBuffer(8));e.setFloat64(0,t);var r=e.getUint32(0),n=e.getUint32(4),o=(r&uK)*Math.pow(2,32);return o+n}function Td(t,e){return t===0||t===Number.POSITIVE_INFINITY||t===Number.NEGATIVE_INFINITY||Number.isNaN(t)?t:t*Math.pow(2,e)}function FP(t){return t--,t|=t>>1,t|=t>>2,t|=t>>4,t|=t>>8,t|=t>>16,t++,t}var dK=function(){var t=function(e,r){return t=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])},t(e,r)};return function(e,r){if(typeof r!="function"&&r!==null)throw new TypeError("Class extends value "+String(r)+" is not a constructor or null");t(e,r);function n(){this.constructor=e}e.prototype=r===null?Object.create(r):(n.prototype=r.prototype,new n)}}(),na=function(t){dK(e,t);function e(){return t!==null&&t.apply(this,arguments)||this}return e}(Error);var BP=function(){function t(e){this._shift=-e}return t.prototype.mapToIndex=function(e){if(e<Ed)return this._minNormalLowerBoundaryIndex();var r=yf(e),n=this._rightShift(Ef(e)-1,DP);return r+n>>this._shift},t.prototype.lowerBoundary=function(e){var r=this._minNormalLowerBoundaryIndex();if(e<r)throw new na("underflow: "+e+" is < minimum lower boundary: "+r);var n=this._maxNormalLowerBoundaryIndex();if(e>n)throw new na("overflow: "+e+" is > maximum lower boundary: "+n);return Td(1,e<<this._shift)},Object.defineProperty(t.prototype,"scale",{get:function(){return this._shift===0?0:-this._shift},enumerable:!1,configurable:!0}),t.prototype._minNormalLowerBoundaryIndex=function(){var e=gf>>this._shift;return this._shift<2&&e--,e},t.prototype._maxNormalLowerBoundaryIndex=function(){return Sf>>this._shift},t.prototype._rightShift=function(e,r){return Math.floor(e*Math.pow(2,-r))},t}();var zP=function(){function t(e){this._scale=e,this._scaleFactor=Td(Math.LOG2E,e),this._inverseFactor=Td(Math.LN2,-e)}return t.prototype.mapToIndex=function(e){if(e<=Ed)return this._minNormalLowerBoundaryIndex()-1;if(Ef(e)===0){var r=yf(e);return(r<<this._scale)-1}var n=Math.floor(Math.log(e)*this._scaleFactor),o=this._maxNormalLowerBoundaryIndex();return n>=o?o:n},t.prototype.lowerBoundary=function(e){var r=this._maxNormalLowerBoundaryIndex();if(e>=r){if(e===r)return 2*Math.exp((e-(1<<this._scale))/this._scaleFactor);throw new na("overflow: "+e+" is > maximum lower boundary: "+r)}var n=this._minNormalLowerBoundaryIndex();if(e<=n){if(e===n)return Ed;if(e===n-1)return Math.exp((e+(1<<this._scale))/this._scaleFactor)/2;throw new na("overflow: "+e+" is < minimum lower boundary: "+n)}return Math.exp(e*this._inverseFactor)},Object.defineProperty(t.prototype,"scale",{get:function(){return this._scale},enumerable:!1,configurable:!0}),t.prototype._minNormalLowerBoundaryIndex=function(){return gf<<this._scale},t.prototype._maxNormalLowerBoundaryIndex=function(){return(Sf+1<<this._scale)-1},t}();var HP=-10,GP=20,pK=Array.from({length:31},function(t,e){return e>10?new zP(e-10):new BP(e-10)});function QE(t){if(t>GP||t<HP)throw new na("expected scale >= "+HP+" && <= "+GP+", got: "+t);return pK[t+10]}var mK=function(t,e){var r=typeof Symbol=="function"&&t[Symbol.iterator];if(!r)return t;var n=r.call(t),o,i=[],a;try{for(;(e===void 0||e-- >0)&&!(o=n.next()).done;)i.push(o.value)}catch(s){a={error:s}}finally{try{o&&!o.done&&(r=n.return)&&r.call(n)}finally{if(a)throw a.error}}return i},Tf=function(){function t(e,r){this.low=e,this.high=r}return t.combine=function(e,r){return new t(Math.min(e.low,r.low),Math.max(e.high,r.high))},t}(),fK=20,hK=160,ZE=2,gK=function(){function t(e,r,n,o,i,a,s,c,l,u,d){e===void 0&&(e=e),r===void 0&&(r=hK),n===void 0&&(n=!0),o===void 0&&(o=0),i===void 0&&(i=0),a===void 0&&(a=0),s===void 0&&(s=Number.POSITIVE_INFINITY),c===void 0&&(c=Number.NEGATIVE_INFINITY),l===void 0&&(l=new XE),u===void 0&&(u=new XE),d===void 0&&(d=QE(fK)),this.startTime=e,this._maxSize=r,this._recordMinMax=n,this._sum=o,this._count=i,this._zeroCount=a,this._min=s,this._max=c,this._positive=l,this._negative=u,this._mapping=d,this._maxSize<ZE&&(ie.warn("Exponential Histogram Max Size set to "+this._maxSize+", changing to the minimum size of: "+ZE),this._maxSize=ZE)}return t.prototype.record=function(e){this.updateByIncrement(e,1)},t.prototype.setStartTime=function(e){this.startTime=e},t.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(t.prototype,"sum",{get:function(){return this._sum},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"min",{get:function(){return this._min},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"max",{get:function(){return this._max},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"count",{get:function(){return this._count},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"zeroCount",{get:function(){return this._zeroCount},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"scale",{get:function(){return this._count===this._zeroCount?0:this._mapping.scale},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"positive",{get:function(){return this._positive},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"negative",{get:function(){return this._negative},enumerable:!1,configurable:!0}),t.prototype.updateByIncrement=function(e,r){if(!Number.isNaN(e)){if(e>this._max&&(this._max=e),e<this._min&&(this._min=e),this._count+=r,e===0){this._zeroCount+=r;return}this._sum+=e*r,e>0?this._updateBuckets(this._positive,e,r):this._updateBuckets(this._negative,-e,r)}},t.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 r=this._minScale(e);this._downscale(this.scale-r),this._mergeBuckets(this.positive,e,e.positive,r),this._mergeBuckets(this.negative,e,e.negative,r)},t.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 r=this._minScale(e);this._downscale(this.scale-r),this._diffBuckets(this.positive,e,e.positive,r),this._diffBuckets(this.negative,e,e.negative,r)},t.prototype.clone=function(){return new t(this.startTime,this._maxSize,this._recordMinMax,this._sum,this._count,this._zeroCount,this._min,this._max,this.positive.clone(),this.negative.clone(),this._mapping)},t.prototype._updateBuckets=function(e,r,n){var o=this._mapping.mapToIndex(r),i=!1,a=0,s=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,s=o,a=e.indexEnd):o>e.indexEnd&&o-e.indexStart>=this._maxSize&&(i=!0,s=e.indexStart,a=o),i){var c=this._changeScale(a,s);this._downscale(c),o=this._mapping.mapToIndex(r)}this._incrementIndexBy(e,o,n)},t.prototype._incrementIndexBy=function(e,r,n){if(n!==0){if(e.length===0&&(e.indexStart=e.indexEnd=e.indexBase=r),r<e.indexStart){var o=e.indexEnd-r;o>=e.backing.length&&this._grow(e,o+1),e.indexStart=r}else if(r>e.indexEnd){var o=r-e.indexStart;o>=e.backing.length&&this._grow(e,o+1),e.indexEnd=r}var i=r-e.indexBase;i<0&&(i+=e.backing.length),e.incrementBucket(i,n)}},t.prototype._grow=function(e,r){var n=e.backing.length,o=e.indexBase-e.indexStart,i=n-o,a=FP(r);a>this._maxSize&&(a=this._maxSize);var s=a-o;e.backing.growTo(a,i,s)},t.prototype._changeScale=function(e,r){for(var n=0;e-r>=this._maxSize;)e>>=1,r>>=1,n++;return n},t.prototype._downscale=function(e){if(e!==0){if(e<0)throw new Error("impossible change of scale: "+this.scale);var r=this._mapping.scale-e;this._positive.downscale(e),this._negative.downscale(e),this._mapping=QE(r)}},t.prototype._minScale=function(e){var r=Math.min(this.scale,e.scale),n=Tf.combine(this._highLowAtScale(this.positive,this.scale,r),this._highLowAtScale(e.positive,e.scale,r)),o=Tf.combine(this._highLowAtScale(this.negative,this.scale,r),this._highLowAtScale(e.negative,e.scale,r));return Math.min(r-this._changeScale(n.high,n.low),r-this._changeScale(o.high,o.low))},t.prototype._highLowAtScale=function(e,r,n){if(e.length===0)return new Tf(0,-1);var o=r-n;return new Tf(e.indexStart>>o,e.indexEnd>>o)},t.prototype._mergeBuckets=function(e,r,n,o){for(var i=n.offset,a=r.scale-o,s=0;s<n.length;s++)this._incrementIndexBy(e,i+s>>a,n.at(s))},t.prototype._diffBuckets=function(e,r,n,o){for(var i=n.offset,a=r.scale-o,s=0;s<n.length;s++){var c=i+s>>a,l=c-e.indexBase;l<0&&(l+=e.backing.length),e.decrementBucket(l,n.at(s))}e.trim()},t}();var jP=function(){function t(e,r){this._maxSize=e,this._recordMinMax=r,this.kind=Wn.EXPONENTIAL_HISTOGRAM}return t.prototype.createAccumulation=function(e){return new gK(e,this._maxSize,this._recordMinMax)},t.prototype.merge=function(e,r){var n=r.clone();return n.merge(e),n},t.prototype.diff=function(e,r){var n=r.clone();return n.diff(e),n},t.prototype.toMetricData=function(e,r,n,o){return{descriptor:e,aggregationTemporality:r,dataPointType:Lr.EXPONENTIAL_HISTOGRAM,dataPoints:n.map(function(i){var a=mK(i,2),s=a[0],c=a[1],l=c.toPointValue(),u=e.type===ze.GAUGE||e.type===ze.UP_DOWN_COUNTER||e.type===ze.OBSERVABLE_GAUGE||e.type===ze.OBSERVABLE_UP_DOWN_COUNTER;return{attributes:s,startTime:c.startTime,endTime:o,value:{min:l.hasMinMax?l.min:void 0,max:l.hasMinMax?l.max:void 0,sum:u?void 0:l.sum,positive:{offset:l.positive.offset,bucketCounts:l.positive.bucketCounts},negative:{offset:l.negative.offset,bucketCounts:l.negative.bucketCounts},count:l.count,scale:l.scale,zeroCount:l.zeroCount}}})}},t}();var SK=function(t,e){var r=typeof Symbol=="function"&&t[Symbol.iterator];if(!r)return t;var n=r.call(t),o,i=[],a;try{for(;(e===void 0||e-- >0)&&!(o=n.next()).done;)i.push(o.value)}catch(s){a={error:s}}finally{try{o&&!o.done&&(r=n.return)&&r.call(n)}finally{if(a)throw a.error}}return i},eT=function(){function t(e,r,n){r===void 0&&(r=0),n===void 0&&(n=[0,0]),this.startTime=e,this._current=r,this.sampleTime=n}return t.prototype.record=function(e){this._current=e,this.sampleTime=IP(Date.now())},t.prototype.setStartTime=function(e){this.startTime=e},t.prototype.toPointValue=function(){return this._current},t}();var VP=function(){function t(){this.kind=Wn.LAST_VALUE}return t.prototype.createAccumulation=function(e){return new eT(e)},t.prototype.merge=function(e,r){var n=yd(r.sampleTime)>=yd(e.sampleTime)?r:e;return new eT(e.startTime,n.toPointValue(),n.sampleTime)},t.prototype.diff=function(e,r){var n=yd(r.sampleTime)>=yd(e.sampleTime)?r:e;return new eT(r.startTime,n.toPointValue(),n.sampleTime)},t.prototype.toMetricData=function(e,r,n,o){return{descriptor:e,aggregationTemporality:r,dataPointType:Lr.GAUGE,dataPoints:n.map(function(i){var a=SK(i,2),s=a[0],c=a[1];return{attributes:s,startTime:c.startTime,endTime:o,value:c.toPointValue()}})}},t}();var yK=function(t,e){var r=typeof Symbol=="function"&&t[Symbol.iterator];if(!r)return t;var n=r.call(t),o,i=[],a;try{for(;(e===void 0||e-- >0)&&!(o=n.next()).done;)i.push(o.value)}catch(s){a={error:s}}finally{try{o&&!o.done&&(r=n.return)&&r.call(n)}finally{if(a)throw a.error}}return i},bd=function(){function t(e,r,n,o){n===void 0&&(n=0),o===void 0&&(o=!1),this.startTime=e,this.monotonic=r,this._current=n,this.reset=o}return t.prototype.record=function(e){this.monotonic&&e<0||(this._current+=e)},t.prototype.setStartTime=function(e){this.startTime=e},t.prototype.toPointValue=function(){return this._current},t}();var tT=function(){function t(e){this.monotonic=e,this.kind=Wn.SUM}return t.prototype.createAccumulation=function(e){return new bd(e,this.monotonic)},t.prototype.merge=function(e,r){var n=e.toPointValue(),o=r.toPointValue();return r.reset?new bd(r.startTime,this.monotonic,o,r.reset):new bd(e.startTime,this.monotonic,n+o)},t.prototype.diff=function(e,r){var n=e.toPointValue(),o=r.toPointValue();return this.monotonic&&n>o?new bd(r.startTime,this.monotonic,o,!0):new bd(r.startTime,this.monotonic,o-n)},t.prototype.toMetricData=function(e,r,n,o){return{descriptor:e,aggregationTemporality:r,dataPointType:Lr.SUM,dataPoints:n.map(function(i){var a=yK(i,2),s=a[0],c=a[1];return{attributes:s,startTime:c.startTime,endTime:o,value:c.toPointValue()}}),isMonotonic:this.monotonic}},t}();var ms=function(){var t=function(e,r){return t=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])},t(e,r)};return function(e,r){if(typeof r!="function"&&r!==null)throw new TypeError("Class extends value "+String(r)+" is not a constructor or null");t(e,r);function n(){this.constructor=e}e.prototype=r===null?Object.create(r):(n.prototype=r.prototype,new n)}}(),jo=function(){function t(){}return t.Drop=function(){return QP},t.Sum=function(){return ZP},t.LastValue=function(){return eM},t.Histogram=function(){return tM},t.ExponentialHistogram=function(){return EK},t.Default=function(){return TK},t}();var WP=function(t){ms(e,t);function e(){return t!==null&&t.apply(this,arguments)||this}return e.prototype.createAggregator=function(r){return e.DEFAULT_INSTANCE},e.DEFAULT_INSTANCE=new NP,e}(jo);var $P=function(t){ms(e,t);function e(){return t!==null&&t.apply(this,arguments)||this}return e.prototype.createAggregator=function(r){switch(r.type){case ze.COUNTER:case ze.OBSERVABLE_COUNTER:case ze.HISTOGRAM:return e.MONOTONIC_INSTANCE;default:return e.NON_MONOTONIC_INSTANCE}},e.MONOTONIC_INSTANCE=new tT(!0),e.NON_MONOTONIC_INSTANCE=new tT(!1),e}(jo);var qP=function(t){ms(e,t);function e(){return t!==null&&t.apply(this,arguments)||this}return e.prototype.createAggregator=function(r){return e.DEFAULT_INSTANCE},e.DEFAULT_INSTANCE=new VP,e}(jo);var KP=function(t){ms(e,t);function e(){return t!==null&&t.apply(this,arguments)||this}return e.prototype.createAggregator=function(r){return e.DEFAULT_INSTANCE},e.DEFAULT_INSTANCE=new qE([0,5,10,25,50,75,100,250,500,750,1e3,2500,5e3,7500,1e4],!0),e}(jo);var YP=function(t){ms(e,t);function e(r,n){n===void 0&&(n=!0);var o=t.call(this)||this;if(o._recordMinMax=n,r==null)throw new Error("ExplicitBucketHistogramAggregation should be created with explicit boundaries, if a single bucket histogram is required, please pass an empty array");r=r.concat(),r=r.sort(function(s,c){return s-c});var i=r.lastIndexOf(-1/0),a=r.indexOf(1/0);return a===-1&&(a=void 0),o._boundaries=r.slice(i+1,a),o}return e.prototype.createAggregator=function(r){return new qE(this._boundaries,this._recordMinMax)},e}(jo);var XP=function(t){ms(e,t);function e(r,n){r===void 0&&(r=160),n===void 0&&(n=!0);var o=t.call(this)||this;return o._maxSize=r,o._recordMinMax=n,o}return e.prototype.createAggregator=function(r){return new jP(this._maxSize,this._recordMinMax)},e}(jo);var JP=function(t){ms(e,t);function e(){return t!==null&&t.apply(this,arguments)||this}return e.prototype._resolve=function(r){switch(r.type){case ze.COUNTER:case ze.UP_DOWN_COUNTER:case ze.OBSERVABLE_COUNTER:case ze.OBSERVABLE_UP_DOWN_COUNTER:return ZP;case ze.GAUGE:case ze.OBSERVABLE_GAUGE:return eM;case ze.HISTOGRAM:return r.advice.explicitBucketBoundaries?new YP(r.advice.explicitBucketBoundaries):tM}return ie.warn("Unable to recognize instrument type: "+r.type),QP},e.prototype.createAggregator=function(r){return this._resolve(r).createAggregator(r)},e}(jo);var QP=new WP,ZP=new $P,eM=new qP,tM=new KP,EK=new XP,TK=new JP;yt();function bf(){return"unknown_service:"+process.argv0}var oa=function(){return oa=Object.assign||function(t){for(var e,r=1,n=arguments.length;r<n;r++){e=arguments[r];for(var o in e)Object.prototype.hasOwnProperty.call(e,o)&&(t[o]=e[o])}return t},oa.apply(this,arguments)},bK=function(t,e,r,n){function o(i){return i instanceof r?i:new r(function(a){a(i)})}return new(r||(r=Promise))(function(i,a){function s(u){try{l(n.next(u))}catch(d){a(d)}}function c(u){try{l(n.throw(u))}catch(d){a(d)}}function l(u){u.done?i(u.value):o(u.value).then(s,c)}l((n=n.apply(t,e||[])).next())})},vK=function(t,e){var r={label:0,sent:function(){if(i[0]&1)throw i[1];return i[1]},trys:[],ops:[]},n,o,i,a;return a={next:s(0),throw:s(1),return:s(2)},typeof Symbol=="function"&&(a[Symbol.iterator]=function(){return this}),a;function s(l){return function(u){return c([l,u])}}function c(l){if(n)throw new TypeError("Generator is already executing.");for(;r;)try{if(n=1,o&&(i=l[0]&2?o.return:l[0]?o.throw||((i=o.return)&&i.call(o),0):o.next)&&!(i=i.call(o,l[1])).done)return i;switch(o=0,i&&(l=[l[0]&2,i.value]),l[0]){case 0:case 1:i=l;break;case 4:return r.label++,{value:l[1],done:!1};case 5:r.label++,o=l[1],l=[0];continue;case 7:l=r.ops.pop(),r.trys.pop();continue;default:if(i=r.trys,!(i=i.length>0&&i[i.length-1])&&(l[0]===6||l[0]===2)){r=0;continue}if(l[0]===3&&(!i||l[1]>i[0]&&l[1]<i[3])){r.label=l[1];break}if(l[0]===6&&r.label<i[1]){r.label=i[1],i=l;break}if(i&&r.label<i[2]){r.label=i[2],r.ops.push(l);break}i[2]&&r.ops.pop(),r.trys.pop();continue}l=e.call(t,r)}catch(u){l=[6,u],o=0}finally{n=i=0}if(l[0]&5)throw l[1];return{value:l[0]?l[1]:void 0,done:!0}}},AK=function(t,e){var r=typeof Symbol=="function"&&t[Symbol.iterator];if(!r)return t;var n=r.call(t),o,i=[],a;try{for(;(e===void 0||e-- >0)&&!(o=n.next()).done;)i.push(o.value)}catch(s){a={error:s}}finally{try{o&&!o.done&&(r=n.return)&&r.call(n)}finally{if(a)throw a.error}}return i},rT=function(){function t(e,r){var n=this,o;this._attributes=e,this.asyncAttributesPending=r!=null,this._syncAttributes=(o=this._attributes)!==null&&o!==void 0?o:{},this._asyncAttributesPromise=r?.then(function(i){return n._attributes=Object.assign({},n._attributes,i),n.asyncAttributesPending=!1,i},function(i){return ie.debug("a resource's async attributes promise rejected: %s",i),n.asyncAttributesPending=!1,{}})}return t.empty=function(){return t.EMPTY},t.default=function(){var e;return new t((e={},e[ff]=bf(),e[gd]=hf[gd],e[hd]=hf[hd],e[Sd]=hf[Sd],e))},Object.defineProperty(t.prototype,"attributes",{get:function(){var e;return this.asyncAttributesPending&&ie.error("Accessing resource attributes before async attributes settled"),(e=this._attributes)!==null&&e!==void 0?e:{}},enumerable:!1,configurable:!0}),t.prototype.waitForAsyncAttributes=function(){return bK(this,void 0,void 0,function(){return vK(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]}})})},t.prototype.merge=function(e){var r=this,n;if(!e)return this;var o=oa(oa({},this._syncAttributes),(n=e._syncAttributes)!==null&&n!==void 0?n:e.attributes);if(!this._asyncAttributesPromise&&!e._asyncAttributesPromise)return new t(o);var i=Promise.all([this._asyncAttributesPromise,e._asyncAttributesPromise]).then(function(a){var s,c=AK(a,2),l=c[0],u=c[1];return oa(oa(oa(oa({},r._syncAttributes),l),(s=e._syncAttributes)!==null&&s!==void 0?s:e.attributes),u)});return new t(o,i)},t.EMPTY=new t({}),t}();var fs;(function(t){t[t.DELTA=0]="DELTA",t[t.CUMULATIVE=1]="CUMULATIVE",t[t.LOWMEMORY=2]="LOWMEMORY"})(fs||(fs={}));yt();var CK=function(t,e,r,n){function o(i){return i instanceof r?i:new r(function(a){a(i)})}return new(r||(r=Promise))(function(i,a){function s(u){try{l(n.next(u))}catch(d){a(d)}}function c(u){try{l(n.throw(u))}catch(d){a(d)}}function l(u){u.done?i(u.value):o(u.value).then(s,c)}l((n=n.apply(t,e||[])).next())})},RK=function(t,e){var r={label:0,sent:function(){if(i[0]&1)throw i[1];return i[1]},trys:[],ops:[]},n,o,i,a;return a={next:s(0),throw:s(1),return:s(2)},typeof Symbol=="function"&&(a[Symbol.iterator]=function(){return this}),a;function s(l){return function(u){return c([l,u])}}function c(l){if(n)throw new TypeError("Generator is already executing.");for(;r;)try{if(n=1,o&&(i=l[0]&2?o.return:l[0]?o.throw||((i=o.return)&&i.call(o),0):o.next)&&!(i=i.call(o,l[1])).done)return i;switch(o=0,i&&(l=[l[0]&2,i.value]),l[0]){case 0:case 1:i=l;break;case 4:return r.label++,{value:l[1],done:!1};case 5:r.label++,o=l[1],l=[0];continue;case 7:l=r.ops.pop(),r.trys.pop();continue;default:if(i=r.trys,!(i=i.length>0&&i[i.length-1])&&(l[0]===6||l[0]===2)){r=0;continue}if(l[0]===3&&(!i||l[1]>i[0]&&l[1]<i[3])){r.label=l[1];break}if(l[0]===6&&r.label<i[1]){r.label=i[1],i=l;break}if(i&&r.label<i[2]){r.label=i[2],r.ops.push(l);break}i[2]&&r.ops.pop(),r.trys.pop();continue}l=e.call(t,r)}catch(u){l=[6,u],o=0}finally{n=i=0}if(l[0]&5)throw l[1];return{value:l[0]?l[1]:void 0,done:!0}}},nT=function(){return Vn.CUMULATIVE},rM=function(t){switch(t){case ze.COUNTER:case ze.OBSERVABLE_COUNTER:case ze.GAUGE:case ze.HISTOGRAM:case ze.OBSERVABLE_GAUGE:return Vn.DELTA;case ze.UP_DOWN_COUNTER:case ze.OBSERVABLE_UP_DOWN_COUNTER:return Vn.CUMULATIVE}},nM=function(t){switch(t){case ze.COUNTER:case ze.HISTOGRAM:return Vn.DELTA;case ze.GAUGE:case ze.UP_DOWN_COUNTER:case ze.OBSERVABLE_UP_DOWN_COUNTER:case ze.OBSERVABLE_COUNTER:case ze.OBSERVABLE_GAUGE:return Vn.CUMULATIVE}};function wK(){var t=Sr(),e=t.OTEL_EXPORTER_OTLP_METRICS_TEMPORALITY_PREFERENCE.trim().toLowerCase();return e==="cumulative"?nT:e==="delta"?rM:e==="lowmemory"?nM:(ie.warn("OTEL_EXPORTER_OTLP_METRICS_TEMPORALITY_PREFERENCE is set to '"+t.OTEL_EXPORTER_OTLP_METRICS_TEMPORALITY_PREFERENCE+"', but only 'cumulative' and 'delta' are allowed. Using default ('cumulative') instead."),nT)}function xK(t){return t!=null?t===fs.DELTA?rM:t===fs.LOWMEMORY?nM:nT:wK()}function _K(t){return t?.aggregationPreference?t.aggregationPreference:function(e){return jo.Default()}}var oM=function(){function t(e,r){this._otlpExporter=e,this._aggregationSelector=_K(r),this._aggregationTemporalitySelector=xK(r?.temporalityPreference)}return t.prototype.export=function(e,r){this._otlpExporter.export([e],r)},t.prototype.shutdown=function(){return CK(this,void 0,void 0,function(){return RK(this,function(e){switch(e.label){case 0:return[4,this._otlpExporter.shutdown()];case 1:return e.sent(),[2]}})})},t.prototype.forceFlush=function(){return Promise.resolve()},t.prototype.selectAggregation=function(e){return this._aggregationSelector(e)},t.prototype.selectAggregationTemporality=function(e){return this._aggregationTemporalitySelector(e)},t}();yt();yt();var IK=function(t,e){var r=typeof Symbol=="function"&&t[Symbol.iterator];if(!r)return t;var n=r.call(t),o,i=[],a;try{for(;(e===void 0||e-- >0)&&!(o=n.next()).done;)i.push(o.value)}catch(s){a={error:s}}finally{try{o&&!o.done&&(r=n.return)&&r.call(n)}finally{if(a)throw a.error}}return i},iM=1e4,aM=5,sM=1e3,lM=5e3,cM=1.5;function vd(t){t===void 0&&(t={});var e={};return Object.entries(t).forEach(function(r){var n=IK(r,2),o=n[0],i=n[1];typeof i<"u"?e[o]=String(i):ie.warn('Header "'+o+'" has invalid value ('+i+") and will be ignored")}),e}function oT(t,e){return t.endsWith("/")||(t=t+"/"),t+e}function iT(t){try{var e=new URL(t);return e.pathname===""&&(e.pathname=e.pathname+"/"),e.toString()}catch{return ie.warn("Could not parse export URL: '"+t+"'"),t}}function aT(t){return typeof t=="number"?t<=0?sT(t,iM):t:PK()}function PK(){var t,e=Number((t=Sr().OTEL_EXPORTER_OTLP_TRACES_TIMEOUT)!==null&&t!==void 0?t:Sr().OTEL_EXPORTER_OTLP_TIMEOUT);return e<=0?sT(e,iM):e}function sT(t,e){return ie.warn("Timeout must be greater than 0",t),e}function uM(t){var e=[429,502,503,504];return e.includes(t)}function dM(t){if(t==null)return-1;var e=Number.parseInt(t,10);if(Number.isInteger(e))return e>0?e*1e3:-1;var r=new Date(t).getTime()-Date.now();return r>=0?r:0}var pM=function(){function t(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 OP(this._shutdown,this),this._concurrencyLimit=typeof e.concurrencyLimit=="number"?e.concurrencyLimit:30,this.timeoutMillis=aT(e.timeoutMillis),this.onInit(e)}return t.prototype.export=function(e,r){if(this._shutdownOnce.isCalled){r({code:ps.FAILED,error:new Error("Exporter has been shutdown")});return}if(this._sendingPromises.length>=this._concurrencyLimit){r({code:ps.FAILED,error:new Error("Concurrent export limit reached")});return}this._export(e).then(function(){r({code:ps.SUCCESS})}).catch(function(n){r({code:ps.FAILED,error:n})})},t.prototype._export=function(e){var r=this;return new Promise(function(n,o){try{ie.debug("items to be sent",e),r.send(e,n,o)}catch(i){o(i)}})},t.prototype.shutdown=function(){return this._shutdownOnce.call()},t.prototype.forceFlush=function(){return Promise.all(this._sendingPromises).then(function(){})},t.prototype._shutdown=function(){return ie.debug("shutdown started"),this.onShutdown(),this.forceFlush()},t}();yt();import*as lT from"url";import*as Af from"http";import*as Cf from"https";import*as mM from"zlib";import{Readable as OK}from"stream";var ia;(function(t){t.NONE="none",t.GZIP="gzip"})(ia||(ia={}));var MK=function(){var t=function(e,r){return t=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])},t(e,r)};return function(e,r){if(typeof r!="function"&&r!==null)throw new TypeError("Class extends value "+String(r)+" is not a constructor or null");t(e,r);function n(){this.constructor=e}e.prototype=r===null?Object.create(r):(n.prototype=r.prototype,new n)}}(),ec=function(t){MK(e,t);function e(r,n,o){var i=t.call(this,r)||this;return i.name="OTLPExporterError",i.data=o,i.code=n,i}return e}(Error);var vf=function(){return vf=Object.assign||function(t){for(var e,r=1,n=arguments.length;r<n;r++){e=arguments[r];for(var o in e)Object.prototype.hasOwnProperty.call(e,o)&&(t[o]=e[o])}return t},vf.apply(this,arguments)};function cT(t,e,r,n,o){var i=t.timeoutMillis,a=new lT.URL(t.url),s=Number(process.versions.node.split(".")[0]),c,l,u=!1,d=setTimeout(function(){if(clearTimeout(c),u=!0,l.destroyed){var h=new ec("Request Timeout");o(h)}else s>=14?l.destroy():l.abort()},i),p={hostname:a.hostname,port:a.port,path:a.pathname,method:"POST",headers:vf({"Content-Type":r},t.headers),agent:t.agent},m=a.protocol==="http:"?Af.request:Cf.request,f=function(h,S){switch(h===void 0&&(h=aM),S===void 0&&(S=sM),l=m(p,function(E){var y="";E.on("data",function(b){return y+=b}),E.on("aborted",function(){if(u){var b=new ec("Request Timeout");o(b)}}),E.on("end",function(){if(u===!1)if(E.statusCode&&E.statusCode<299)ie.debug("statusCode: "+E.statusCode,y),n(),clearTimeout(d),clearTimeout(c);else if(E.statusCode&&uM(E.statusCode)&&h>0){var b=void 0;S=cM*S,E.headers["retry-after"]?b=dM(E.headers["retry-after"]):b=Math.round(Math.random()*(lM-S)+S),c=setTimeout(function(){f(h-1,S)},b)}else{var C=new ec(E.statusMessage,E.statusCode,y);o(C),clearTimeout(d),clearTimeout(c)}})}),l.on("error",function(E){if(u){var y=new ec("Request Timeout",E.code);o(y)}else o(E);clearTimeout(d),clearTimeout(c)}),l.on("abort",function(){if(u){var E=new ec("Request Timeout");o(E)}clearTimeout(d),clearTimeout(c)}),t.compression){case ia.GZIP:{l.setHeader("Content-Encoding","gzip");var g=LK(e);g.on("error",o).pipe(mM.createGzip()).on("error",o).pipe(l);break}default:l.end(Buffer.from(e));break}};f()}function LK(t){var e=new OK;return e.push(t),e.push(null),e}function uT(t){if(t.httpAgentOptions&&t.keepAlive===!1){ie.warn("httpAgentOptions is used only when keepAlive is true");return}if(!(t.keepAlive===!1||!t.url))try{var e=new lT.URL(t.url),r=e.protocol==="http:"?Af.Agent:Cf.Agent;return new r(vf({keepAlive:!0},t.httpAgentOptions))}catch(n){ie.error("collector exporter failed to create http agent. err: "+n.message);return}}function dT(t){if(t)return t;var e=Sr().OTEL_EXPORTER_OTLP_TRACES_COMPRESSION||Sr().OTEL_EXPORTER_OTLP_COMPRESSION;return e===ia.GZIP?ia.GZIP:ia.NONE}yt();var NK=function(){var t=function(e,r){return t=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])},t(e,r)};return function(e,r){if(typeof r!="function"&&r!==null)throw new TypeError("Class extends value "+String(r)+" is not a constructor or null");t(e,r);function n(){this.constructor=e}e.prototype=r===null?Object.create(r):(n.prototype=r.prototype,new n)}}(),Rf=function(t){NK(e,t);function e(r,n,o){r===void 0&&(r={});var i=t.call(this,r)||this;return i.DEFAULT_HEADERS={},i._contentType=o,r.metadata&&ie.warn("Metadata cannot be set when using http"),i.headers=Object.assign(i.DEFAULT_HEADERS,vd(r.headers),Ql.parseKeyPairsIntoRecord(Sr().OTEL_EXPORTER_OTLP_HEADERS)),i.agent=uT(r),i.compression=dT(r.compression),i._serializer=n,i}return e.prototype.onInit=function(r){},e.prototype.send=function(r,n,o){var i=this;if(this._shutdownOnce.isCalled){ie.debug("Shutdown already started. Cannot send objects");return}var a=new Promise(function(c,l){var u;cT(i,(u=i._serializer.serializeRequest(r))!==null&&u!==void 0?u:new Uint8Array,i._contentType,c,l)}).then(n,o);this._sendingPromises.push(a);var s=function(){var c=i._sendingPromises.indexOf(a);i._sendingPromises.splice(c,1)};a.then(s,s)},e.prototype.onShutdown=function(){},e}(pM);function hM(t){var e=BigInt(1e9);return BigInt(t[0])*e+BigInt(t[1])}function DK(t){var e=Number(BigInt.asUintN(32,t)),r=Number(BigInt.asUintN(32,t>>BigInt(32)));return{low:e,high:r}}function gM(t){var e=hM(t);return DK(e)}function kK(t){var e=hM(t);return e.toString()}var FK=typeof BigInt<"u"?kK:PP;function fM(t){return t}function SM(t){if(t!==void 0)return mf(t)}var UK={encodeHrTime:gM,encodeSpanContext:mf,encodeOptionalSpanContext:SM};function yM(t){var e,r;if(t===void 0)return UK;var n=(e=t.useLongBits)!==null&&e!==void 0?e:!0,o=(r=t.useHex)!==null&&r!==void 0?r:!1;return{encodeHrTime:n?gM:FK,encodeSpanContext:o?fM:mf,encodeOptionalSpanContext:o?fM:SM}}var BK=function(t,e){var r=typeof Symbol=="function"&&t[Symbol.iterator];if(!r)return t;var n=r.call(t),o,i=[],a;try{for(;(e===void 0||e-- >0)&&!(o=n.next()).done;)i.push(o.value)}catch(s){a={error:s}}finally{try{o&&!o.done&&(r=n.return)&&r.call(n)}finally{if(a)throw a.error}}return i};function EM(t){return{name:t.name,version:t.version}}function tc(t){return Object.keys(t).map(function(e){return TM(e,t[e])})}function TM(t,e){return{key:t,value:bM(e)}}function bM(t){var e=typeof t;return e==="string"?{stringValue:t}:e==="number"?Number.isInteger(t)?{intValue:t}:{doubleValue:t}:e==="boolean"?{boolValue:t}:t instanceof Uint8Array?{bytesValue:t}:Array.isArray(t)?{arrayValue:{values:t.map(bM)}}:e==="object"&&t!=null?{kvlistValue:{values:Object.entries(t).map(function(r){var n=BK(r,2),o=n[0],i=n[1];return TM(o,i)})}}:{}}function vM(t){return{attributes:tc(t.attributes),droppedAttributesCount:0}}yt();function CM(t,e){var r=yM(e);return{resource:vM(t.resource),schemaUrl:void 0,scopeMetrics:zK(t.scopeMetrics,r)}}function zK(t,e){return Array.from(t.map(function(r){return{scope:EM(r.scope),metrics:r.metrics.map(function(n){return HK(n,e)}),schemaUrl:r.scope.schemaUrl}}))}function HK(t,e){var r={name:t.descriptor.name,description:t.descriptor.description,unit:t.descriptor.unit},n=WK(t.aggregationTemporality);switch(t.dataPointType){case Lr.SUM:r.sum={aggregationTemporality:n,isMonotonic:t.isMonotonic,dataPoints:AM(t,e)};break;case Lr.GAUGE:r.gauge={dataPoints:AM(t,e)};break;case Lr.HISTOGRAM:r.histogram={aggregationTemporality:n,dataPoints:jK(t,e)};break;case Lr.EXPONENTIAL_HISTOGRAM:r.exponentialHistogram={aggregationTemporality:n,dataPoints:VK(t,e)};break}return r}function GK(t,e,r){var n={attributes:tc(t.attributes),startTimeUnixNano:r.encodeHrTime(t.startTime),timeUnixNano:r.encodeHrTime(t.endTime)};switch(e){case En.INT:n.asInt=t.value;break;case En.DOUBLE:n.asDouble=t.value;break}return n}function AM(t,e){return t.dataPoints.map(function(r){return GK(r,t.descriptor.valueType,e)})}function jK(t,e){return t.dataPoints.map(function(r){var n=r.value;return{attributes:tc(r.attributes),bucketCounts:n.buckets.counts,explicitBounds:n.buckets.boundaries,count:n.count,sum:n.sum,min:n.min,max:n.max,startTimeUnixNano:e.encodeHrTime(r.startTime),timeUnixNano:e.encodeHrTime(r.endTime)}})}function VK(t,e){return t.dataPoints.map(function(r){var n=r.value;return{attributes:tc(r.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(r.startTime),timeUnixNano:e.encodeHrTime(r.endTime)}})}function WK(t){switch(t){case Vn.DELTA:return 1;case Vn.CUMULATIVE:return 2}}function RM(t,e){return{resourceMetrics:t.map(function(r){return CM(r,e)})}}var pT={serializeRequest:function(t){var e=RM(t,{useLongBits:!1}),r=new TextEncoder;return r.encode(JSON.stringify(e))},deserializeResponse:function(t){var e=new TextDecoder;return JSON.parse(e.decode(t))}};var wM="0.52.1";var xM=function(){var t=function(e,r){return t=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])},t(e,r)};return function(e,r){if(typeof r!="function"&&r!==null)throw new TypeError("Class extends value "+String(r)+" is not a constructor or null");t(e,r);function n(){this.constructor=e}e.prototype=r===null?Object.create(r):(n.prototype=r.prototype,new n)}}(),rc=function(){return rc=Object.assign||function(t){for(var e,r=1,n=arguments.length;r<n;r++){e=arguments[r];for(var o in e)Object.prototype.hasOwnProperty.call(e,o)&&(t[o]=e[o])}return t},rc.apply(this,arguments)},_M="v1/metrics",$K="http://localhost:4318/"+_M,qK={"User-Agent":"OTel-OTLP-Exporter-JavaScript/"+wM},KK=function(t){xM(e,t);function e(r){var n=t.call(this,r,pT,"application/json")||this;return n.headers=rc(rc(rc(rc({},n.headers),qK),Ql.parseKeyPairsIntoRecord(Sr().OTEL_EXPORTER_OTLP_METRICS_HEADERS)),vd(r?.headers)),n}return e.prototype.getDefaultUrl=function(r){return typeof r.url=="string"?r.url:Sr().OTEL_EXPORTER_OTLP_METRICS_ENDPOINT.length>0?iT(Sr().OTEL_EXPORTER_OTLP_METRICS_ENDPOINT):Sr().OTEL_EXPORTER_OTLP_ENDPOINT.length>0?oT(Sr().OTEL_EXPORTER_OTLP_ENDPOINT,_M):$K},e}(Rf),IM=function(t){xM(e,t);function e(r){return t.call(this,new KK(r),r)||this}return e}(oM);var nc;(function(t){t[t.DELTA=0]="DELTA",t[t.CUMULATIVE=1]="CUMULATIVE"})(nc||(nc={}));var Vo;(function(t){t[t.HISTOGRAM=0]="HISTOGRAM",t[t.EXPONENTIAL_HISTOGRAM=1]="EXPONENTIAL_HISTOGRAM",t[t.GAUGE=2]="GAUGE",t[t.SUM=3]="SUM"})(Vo||(Vo={}));yt();var YK=function(){var t=function(e,r){return t=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])},t(e,r)};return function(e,r){if(typeof r!="function"&&r!==null)throw new TypeError("Class extends value "+String(r)+" is not a constructor or null");t(e,r);function n(){this.constructor=e}e.prototype=r===null?Object.create(r):(n.prototype=r.prototype,new n)}}(),PM=function(t,e,r,n){function o(i){return i instanceof r?i:new r(function(a){a(i)})}return new(r||(r=Promise))(function(i,a){function s(u){try{l(n.next(u))}catch(d){a(d)}}function c(u){try{l(n.throw(u))}catch(d){a(d)}}function l(u){u.done?i(u.value):o(u.value).then(s,c)}l((n=n.apply(t,e||[])).next())})},MM=function(t,e){var r={label:0,sent:function(){if(i[0]&1)throw i[1];return i[1]},trys:[],ops:[]},n,o,i,a;return a={next:s(0),throw:s(1),return:s(2)},typeof Symbol=="function"&&(a[Symbol.iterator]=function(){return this}),a;function s(l){return function(u){return c([l,u])}}function c(l){if(n)throw new TypeError("Generator is already executing.");for(;r;)try{if(n=1,o&&(i=l[0]&2?o.return:l[0]?o.throw||((i=o.return)&&i.call(o),0):o.next)&&!(i=i.call(o,l[1])).done)return i;switch(o=0,i&&(l=[l[0]&2,i.value]),l[0]){case 0:case 1:i=l;break;case 4:return r.label++,{value:l[1],done:!1};case 5:r.label++,o=l[1],l=[0];continue;case 7:l=r.ops.pop(),r.trys.pop();continue;default:if(i=r.trys,!(i=i.length>0&&i[i.length-1])&&(l[0]===6||l[0]===2)){r=0;continue}if(l[0]===3&&(!i||l[1]>i[0]&&l[1]<i[3])){r.label=l[1];break}if(l[0]===6&&r.label<i[1]){r.label=i[1],i=l;break}if(i&&r.label<i[2]){r.label=i[2],r.ops.push(l);break}i[2]&&r.ops.pop(),r.trys.pop();continue}l=e.call(t,r)}catch(u){l=[6,u],o=0}finally{n=i=0}if(l[0]&5)throw l[1];return{value:l[0]?l[1]:void 0,done:!0}}},XK=function(t,e){var r=typeof Symbol=="function"&&t[Symbol.iterator];if(!r)return t;var n=r.call(t),o,i=[],a;try{for(;(e===void 0||e-- >0)&&!(o=n.next()).done;)i.push(o.value)}catch(s){a={error:s}}finally{try{o&&!o.done&&(r=n.return)&&r.call(n)}finally{if(a)throw a.error}}return i},JK=function(t,e,r){if(r||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 t.concat(i||Array.prototype.slice.call(e))},QK=function(t){var e=typeof Symbol=="function"&&Symbol.iterator,r=e&&t[e],n=0;if(r)return r.call(t);if(t&&typeof t.length=="number")return{next:function(){return t&&n>=t.length&&(t=void 0),{value:t&&t[n++],done:!t}}};throw new TypeError(e?"Object is not iterable.":"Symbol.iterator is not defined.")};function OM(t){return t!=null}function wf(t){var e=Object.keys(t);return e.length===0?"":(e=e.sort(),JSON.stringify(e.map(function(r){return[r,t[r]]})))}function LM(t){var e,r;return t.name+":"+((e=t.version)!==null&&e!==void 0?e:"")+":"+((r=t.schemaUrl)!==null&&r!==void 0?r:"")}var mT=function(t){YK(e,t);function e(r){var n=t.call(this,r)||this;return Object.setPrototypeOf(n,e.prototype),n}return e}(Error);function aa(t,e){var r,n=new Promise(function(i,a){r=setTimeout(function(){a(new mT("Operation timed out."))},e)});return Promise.race([t,n]).then(function(o){return clearTimeout(r),o},function(o){throw clearTimeout(r),o})}function NM(t){return PM(this,void 0,void 0,function(){var e=this;return MM(this,function(r){return[2,Promise.all(t.map(function(n){return PM(e,void 0,void 0,function(){var o,i;return MM(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 DM(t){return t.status==="rejected"}function fT(t,e){var r=[];return t.forEach(function(n){r.push.apply(r,JK([],XK(e(n)),!1))}),r}function kM(t,e){var r,n;if(t.size!==e.size)return!1;try{for(var o=QK(t),i=o.next();!i.done;i=o.next()){var a=i.value;if(!e.has(a))return!1}}catch(s){r={error:s}}finally{try{i&&!i.done&&(n=o.return)&&n.call(o)}finally{if(r)throw r.error}}return!0}function FM(t,e){for(var r=0,n=t.length-1,o=t.length;n>=r;){var i=r+Math.trunc((n-r)/2);t[i]<e?r=i+1:(o=i,n=i-1)}return o}function UM(t,e){return t.toLowerCase()===e.toLowerCase()}yt();var $n;(function(t){t[t.DROP=0]="DROP",t[t.SUM=1]="SUM",t[t.LAST_VALUE=2]="LAST_VALUE",t[t.HISTOGRAM=3]="HISTOGRAM",t[t.EXPONENTIAL_HISTOGRAM=4]="EXPONENTIAL_HISTOGRAM"})($n||($n={}));var hT=function(){function t(){this.kind=$n.DROP}return t.prototype.createAccumulation=function(){},t.prototype.merge=function(e,r){},t.prototype.diff=function(e,r){},t.prototype.toMetricData=function(e,r,n,o){},t}();yt();var Xe;(function(t){t.COUNTER="COUNTER",t.GAUGE="GAUGE",t.HISTOGRAM="HISTOGRAM",t.UP_DOWN_COUNTER="UP_DOWN_COUNTER",t.OBSERVABLE_COUNTER="OBSERVABLE_COUNTER",t.OBSERVABLE_GAUGE="OBSERVABLE_GAUGE",t.OBSERVABLE_UP_DOWN_COUNTER="OBSERVABLE_UP_DOWN_COUNTER"})(Xe||(Xe={}));function Wo(t,e,r){var n,o,i,a;return e2(t)||ie.warn('Invalid metric name: "'+t+'". The metric name should be a ASCII string with a length no greater than 255 characters.'),{name:t,type:e,description:(n=r?.description)!==null&&n!==void 0?n:"",unit:(o=r?.unit)!==null&&o!==void 0?o:"",valueType:(i=r?.valueType)!==null&&i!==void 0?i:En.DOUBLE,advice:(a=r?.advice)!==null&&a!==void 0?a:{}}}function BM(t,e){var r,n;return{name:(r=t.name)!==null&&r!==void 0?r:e.name,description:(n=t.description)!==null&&n!==void 0?n:e.description,type:e.type,unit:e.unit,valueType:e.valueType,advice:e.advice}}function zM(t,e){return UM(t.name,e.name)&&t.unit===e.unit&&t.type===e.type&&t.valueType===e.valueType}var ZK=/^[a-z][a-z0-9_.\-/]{0,254}$/i;function e2(t){return t.match(ZK)!=null}var t2=function(t,e){var r=typeof Symbol=="function"&&t[Symbol.iterator];if(!r)return t;var n=r.call(t),o,i=[],a;try{for(;(e===void 0||e-- >0)&&!(o=n.next()).done;)i.push(o.value)}catch(s){a={error:s}}finally{try{o&&!o.done&&(r=n.return)&&r.call(n)}finally{if(a)throw a.error}}return i};function r2(t){var e=t.map(function(){return 0});return e.push(0),{buckets:{boundaries:t,counts:e},sum:0,count:0,hasMinMax:!1,min:1/0,max:-1/0}}var xf=function(){function t(e,r,n,o){n===void 0&&(n=!0),o===void 0&&(o=r2(r)),this.startTime=e,this._boundaries=r,this._recordMinMax=n,this._current=o}return t.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 r=FM(this._boundaries,e);this._current.buckets.counts[r]+=1}},t.prototype.setStartTime=function(e){this.startTime=e},t.prototype.toPointValue=function(){return this._current},t}();var _f=function(){function t(e,r){this._boundaries=e,this._recordMinMax=r,this.kind=$n.HISTOGRAM}return t.prototype.createAccumulation=function(e){return new xf(e,this._boundaries,this._recordMinMax)},t.prototype.merge=function(e,r){for(var n=e.toPointValue(),o=r.toPointValue(),i=n.buckets.counts,a=o.buckets.counts,s=new Array(i.length),c=0;c<i.length;c++)s[c]=i[c]+a[c];var l=1/0,u=-1/0;return this._recordMinMax&&(n.hasMinMax&&o.hasMinMax?(l=Math.min(n.min,o.min),u=Math.max(n.max,o.max)):n.hasMinMax?(l=n.min,u=n.max):o.hasMinMax&&(l=o.min,u=o.max)),new xf(e.startTime,n.buckets.boundaries,this._recordMinMax,{buckets:{boundaries:n.buckets.boundaries,counts:s},count:n.count+o.count,sum:n.sum+o.sum,hasMinMax:this._recordMinMax&&(n.hasMinMax||o.hasMinMax),min:l,max:u})},t.prototype.diff=function(e,r){for(var n=e.toPointValue(),o=r.toPointValue(),i=n.buckets.counts,a=o.buckets.counts,s=new Array(i.length),c=0;c<i.length;c++)s[c]=a[c]-i[c];return new xf(r.startTime,n.buckets.boundaries,this._recordMinMax,{buckets:{boundaries:n.buckets.boundaries,counts:s},count:o.count-n.count,sum:o.sum-n.sum,hasMinMax:!1,min:1/0,max:-1/0})},t.prototype.toMetricData=function(e,r,n,o){return{descriptor:e,aggregationTemporality:r,dataPointType:Vo.HISTOGRAM,dataPoints:n.map(function(i){var a=t2(i,2),s=a[0],c=a[1],l=c.toPointValue(),u=e.type===Xe.GAUGE||e.type===Xe.UP_DOWN_COUNTER||e.type===Xe.OBSERVABLE_GAUGE||e.type===Xe.OBSERVABLE_UP_DOWN_COUNTER;return{attributes:s,startTime:c.startTime,endTime:o,value:{min:l.hasMinMax?l.min:void 0,max:l.hasMinMax?l.max:void 0,sum:u?void 0:l.sum,buckets:l.buckets,count:l.count}}})}},t}();yt();var gT=function(t,e){var r=typeof Symbol=="function"&&t[Symbol.iterator];if(!r)return t;var n=r.call(t),o,i=[],a;try{for(;(e===void 0||e-- >0)&&!(o=n.next()).done;)i.push(o.value)}catch(s){a={error:s}}finally{try{o&&!o.done&&(r=n.return)&&r.call(n)}finally{if(a)throw a.error}}return i},ST=function(t,e,r){if(r||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 t.concat(i||Array.prototype.slice.call(e))},yT=function(){function t(e,r,n,o){e===void 0&&(e=new n2),r===void 0&&(r=0),n===void 0&&(n=0),o===void 0&&(o=0),this.backing=e,this.indexBase=r,this.indexStart=n,this.indexEnd=o}return Object.defineProperty(t.prototype,"offset",{get:function(){return this.indexStart},enumerable:!1,configurable:!0}),Object.defineProperty(t.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}),t.prototype.counts=function(){var e=this;return Array.from({length:this.length},function(r,n){return e.at(n)})},t.prototype.at=function(e){var r=this.indexBase-this.indexStart;return e<r&&(e+=this.backing.length),e-=r,this.backing.countAt(e)},t.prototype.incrementBucket=function(e,r){this.backing.increment(e,r)},t.prototype.decrementBucket=function(e,r){this.backing.decrement(e,r)},t.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()},t.prototype.downscale=function(e){this._rotate();for(var r=1+this.indexEnd-this.indexStart,n=1<<e,o=0,i=0,a=this.indexStart;a<=this.indexEnd;){var s=a%n;s<0&&(s+=n);for(var c=s;c<n&&o<r;c++)this._relocateBucket(i,o),o++,a++;i++}this.indexStart>>=e,this.indexEnd>>=e,this.indexBase=this.indexStart},t.prototype.clone=function(){return new t(this.backing.clone(),this.indexBase,this.indexStart,this.indexEnd)},t.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)},t.prototype._relocateBucket=function(e,r){e!==r&&this.incrementBucket(e,this.backing.emptyBucket(r))},t}();var n2=function(){function t(e){e===void 0&&(e=[0]),this._counts=e}return Object.defineProperty(t.prototype,"length",{get:function(){return this._counts.length},enumerable:!1,configurable:!0}),t.prototype.countAt=function(e){return this._counts[e]},t.prototype.growTo=function(e,r,n){var o=new Array(e).fill(0);o.splice.apply(o,ST([n,this._counts.length-r],gT(this._counts.slice(r)),!1)),o.splice.apply(o,ST([0,r],gT(this._counts.slice(0,r)),!1)),this._counts=o},t.prototype.reverse=function(e,r){for(var n=Math.floor((e+r)/2)-e,o=0;o<n;o++){var i=this._counts[e+o];this._counts[e+o]=this._counts[r-o-1],this._counts[r-o-1]=i}},t.prototype.emptyBucket=function(e){var r=this._counts[e];return this._counts[e]=0,r},t.prototype.increment=function(e,r){this._counts[e]+=r},t.prototype.decrement=function(e,r){this._counts[e]>=r?this._counts[e]-=r:this._counts[e]=0},t.prototype.clone=function(){return new t(ST([],gT(this._counts),!1))},t}();var HM=52,o2=2146435072,i2=1048575,ET=1023,If=-ET+1,Pf=ET,Ad=Math.pow(2,-1022);function Mf(t){var e=new DataView(new ArrayBuffer(8));e.setFloat64(0,t);var r=e.getUint32(0),n=(r&o2)>>20;return n-ET}function Of(t){var e=new DataView(new ArrayBuffer(8));e.setFloat64(0,t);var r=e.getUint32(0),n=e.getUint32(4),o=(r&i2)*Math.pow(2,32);return o+n}function Cd(t,e){return t===0||t===Number.POSITIVE_INFINITY||t===Number.NEGATIVE_INFINITY||Number.isNaN(t)?t:t*Math.pow(2,e)}function jM(t){return t--,t|=t>>1,t|=t>>2,t|=t>>4,t|=t>>8,t|=t>>16,t++,t}var a2=function(){var t=function(e,r){return t=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])},t(e,r)};return function(e,r){if(typeof r!="function"&&r!==null)throw new TypeError("Class extends value "+String(r)+" is not a constructor or null");t(e,r);function n(){this.constructor=e}e.prototype=r===null?Object.create(r):(n.prototype=r.prototype,new n)}}(),sa=function(t){a2(e,t);function e(){return t!==null&&t.apply(this,arguments)||this}return e}(Error);var WM=function(){function t(e){this._shift=-e}return t.prototype.mapToIndex=function(e){if(e<Ad)return this._minNormalLowerBoundaryIndex();var r=Mf(e),n=this._rightShift(Of(e)-1,HM);return r+n>>this._shift},t.prototype.lowerBoundary=function(e){var r=this._minNormalLowerBoundaryIndex();if(e<r)throw new sa("underflow: "+e+" is < minimum lower boundary: "+r);var n=this._maxNormalLowerBoundaryIndex();if(e>n)throw new sa("overflow: "+e+" is > maximum lower boundary: "+n);return Cd(1,e<<this._shift)},Object.defineProperty(t.prototype,"scale",{get:function(){return this._shift===0?0:-this._shift},enumerable:!1,configurable:!0}),t.prototype._minNormalLowerBoundaryIndex=function(){var e=If>>this._shift;return this._shift<2&&e--,e},t.prototype._maxNormalLowerBoundaryIndex=function(){return Pf>>this._shift},t.prototype._rightShift=function(e,r){return Math.floor(e*Math.pow(2,-r))},t}();var $M=function(){function t(e){this._scale=e,this._scaleFactor=Cd(Math.LOG2E,e),this._inverseFactor=Cd(Math.LN2,-e)}return t.prototype.mapToIndex=function(e){if(e<=Ad)return this._minNormalLowerBoundaryIndex()-1;if(Of(e)===0){var r=Mf(e);return(r<<this._scale)-1}var n=Math.floor(Math.log(e)*this._scaleFactor),o=this._maxNormalLowerBoundaryIndex();return n>=o?o:n},t.prototype.lowerBoundary=function(e){var r=this._maxNormalLowerBoundaryIndex();if(e>=r){if(e===r)return 2*Math.exp((e-(1<<this._scale))/this._scaleFactor);throw new sa("overflow: "+e+" is > maximum lower boundary: "+r)}var n=this._minNormalLowerBoundaryIndex();if(e<=n){if(e===n)return Ad;if(e===n-1)return Math.exp((e+(1<<this._scale))/this._scaleFactor)/2;throw new sa("overflow: "+e+" is < minimum lower boundary: "+n)}return Math.exp(e*this._inverseFactor)},Object.defineProperty(t.prototype,"scale",{get:function(){return this._scale},enumerable:!1,configurable:!0}),t.prototype._minNormalLowerBoundaryIndex=function(){return If<<this._scale},t.prototype._maxNormalLowerBoundaryIndex=function(){return(Pf+1<<this._scale)-1},t}();var qM=-10,KM=20,s2=Array.from({length:31},function(t,e){return e>10?new $M(e-10):new WM(e-10)});function TT(t){if(t>KM||t<qM)throw new sa("expected scale >= "+qM+" && <= "+KM+", got: "+t);return s2[t+10]}var l2=function(t,e){var r=typeof Symbol=="function"&&t[Symbol.iterator];if(!r)return t;var n=r.call(t),o,i=[],a;try{for(;(e===void 0||e-- >0)&&!(o=n.next()).done;)i.push(o.value)}catch(s){a={error:s}}finally{try{o&&!o.done&&(r=n.return)&&r.call(n)}finally{if(a)throw a.error}}return i},Lf=function(){function t(e,r){this.low=e,this.high=r}return t.combine=function(e,r){return new t(Math.min(e.low,r.low),Math.max(e.high,r.high))},t}(),c2=20,u2=160,bT=2,YM=function(){function t(e,r,n,o,i,a,s,c,l,u,d){e===void 0&&(e=e),r===void 0&&(r=u2),n===void 0&&(n=!0),o===void 0&&(o=0),i===void 0&&(i=0),a===void 0&&(a=0),s===void 0&&(s=Number.POSITIVE_INFINITY),c===void 0&&(c=Number.NEGATIVE_INFINITY),l===void 0&&(l=new yT),u===void 0&&(u=new yT),d===void 0&&(d=TT(c2)),this.startTime=e,this._maxSize=r,this._recordMinMax=n,this._sum=o,this._count=i,this._zeroCount=a,this._min=s,this._max=c,this._positive=l,this._negative=u,this._mapping=d,this._maxSize<bT&&(ie.warn("Exponential Histogram Max Size set to "+this._maxSize+", changing to the minimum size of: "+bT),this._maxSize=bT)}return t.prototype.record=function(e){this.updateByIncrement(e,1)},t.prototype.setStartTime=function(e){this.startTime=e},t.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(t.prototype,"sum",{get:function(){return this._sum},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"min",{get:function(){return this._min},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"max",{get:function(){return this._max},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"count",{get:function(){return this._count},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"zeroCount",{get:function(){return this._zeroCount},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"scale",{get:function(){return this._count===this._zeroCount?0:this._mapping.scale},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"positive",{get:function(){return this._positive},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"negative",{get:function(){return this._negative},enumerable:!1,configurable:!0}),t.prototype.updateByIncrement=function(e,r){if(!Number.isNaN(e)){if(e>this._max&&(this._max=e),e<this._min&&(this._min=e),this._count+=r,e===0){this._zeroCount+=r;return}this._sum+=e*r,e>0?this._updateBuckets(this._positive,e,r):this._updateBuckets(this._negative,-e,r)}},t.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 r=this._minScale(e);this._downscale(this.scale-r),this._mergeBuckets(this.positive,e,e.positive,r),this._mergeBuckets(this.negative,e,e.negative,r)},t.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 r=this._minScale(e);this._downscale(this.scale-r),this._diffBuckets(this.positive,e,e.positive,r),this._diffBuckets(this.negative,e,e.negative,r)},t.prototype.clone=function(){return new t(this.startTime,this._maxSize,this._recordMinMax,this._sum,this._count,this._zeroCount,this._min,this._max,this.positive.clone(),this.negative.clone(),this._mapping)},t.prototype._updateBuckets=function(e,r,n){var o=this._mapping.mapToIndex(r),i=!1,a=0,s=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,s=o,a=e.indexEnd):o>e.indexEnd&&o-e.indexStart>=this._maxSize&&(i=!0,s=e.indexStart,a=o),i){var c=this._changeScale(a,s);this._downscale(c),o=this._mapping.mapToIndex(r)}this._incrementIndexBy(e,o,n)},t.prototype._incrementIndexBy=function(e,r,n){if(n!==0){if(e.length===0&&(e.indexStart=e.indexEnd=e.indexBase=r),r<e.indexStart){var o=e.indexEnd-r;o>=e.backing.length&&this._grow(e,o+1),e.indexStart=r}else if(r>e.indexEnd){var o=r-e.indexStart;o>=e.backing.length&&this._grow(e,o+1),e.indexEnd=r}var i=r-e.indexBase;i<0&&(i+=e.backing.length),e.incrementBucket(i,n)}},t.prototype._grow=function(e,r){var n=e.backing.length,o=e.indexBase-e.indexStart,i=n-o,a=jM(r);a>this._maxSize&&(a=this._maxSize);var s=a-o;e.backing.growTo(a,i,s)},t.prototype._changeScale=function(e,r){for(var n=0;e-r>=this._maxSize;)e>>=1,r>>=1,n++;return n},t.prototype._downscale=function(e){if(e!==0){if(e<0)throw new Error("impossible change of scale: "+this.scale);var r=this._mapping.scale-e;this._positive.downscale(e),this._negative.downscale(e),this._mapping=TT(r)}},t.prototype._minScale=function(e){var r=Math.min(this.scale,e.scale),n=Lf.combine(this._highLowAtScale(this.positive,this.scale,r),this._highLowAtScale(e.positive,e.scale,r)),o=Lf.combine(this._highLowAtScale(this.negative,this.scale,r),this._highLowAtScale(e.negative,e.scale,r));return Math.min(r-this._changeScale(n.high,n.low),r-this._changeScale(o.high,o.low))},t.prototype._highLowAtScale=function(e,r,n){if(e.length===0)return new Lf(0,-1);var o=r-n;return new Lf(e.indexStart>>o,e.indexEnd>>o)},t.prototype._mergeBuckets=function(e,r,n,o){for(var i=n.offset,a=r.scale-o,s=0;s<n.length;s++)this._incrementIndexBy(e,i+s>>a,n.at(s))},t.prototype._diffBuckets=function(e,r,n,o){for(var i=n.offset,a=r.scale-o,s=0;s<n.length;s++){var c=i+s>>a,l=c-e.indexBase;l<0&&(l+=e.backing.length),e.decrementBucket(l,n.at(s))}e.trim()},t}();var vT=function(){function t(e,r){this._maxSize=e,this._recordMinMax=r,this.kind=$n.EXPONENTIAL_HISTOGRAM}return t.prototype.createAccumulation=function(e){return new YM(e,this._maxSize,this._recordMinMax)},t.prototype.merge=function(e,r){var n=r.clone();return n.merge(e),n},t.prototype.diff=function(e,r){var n=r.clone();return n.diff(e),n},t.prototype.toMetricData=function(e,r,n,o){return{descriptor:e,aggregationTemporality:r,dataPointType:Vo.EXPONENTIAL_HISTOGRAM,dataPoints:n.map(function(i){var a=l2(i,2),s=a[0],c=a[1],l=c.toPointValue(),u=e.type===Xe.GAUGE||e.type===Xe.UP_DOWN_COUNTER||e.type===Xe.OBSERVABLE_GAUGE||e.type===Xe.OBSERVABLE_UP_DOWN_COUNTER;return{attributes:s,startTime:c.startTime,endTime:o,value:{min:l.hasMinMax?l.min:void 0,max:l.hasMinMax?l.max:void 0,sum:u?void 0:l.sum,positive:{offset:l.positive.offset,bucketCounts:l.positive.bucketCounts},negative:{offset:l.negative.offset,bucketCounts:l.negative.bucketCounts},count:l.count,scale:l.scale,zeroCount:l.zeroCount}}})}},t}();yt();var d2=LE("OpenTelemetry SDK Context Key SUPPRESS_TRACING");function XM(t){return t.setValue(d2,!0)}yt();function JM(){return function(t){ie.error(p2(t))}}function p2(t){return typeof t=="string"?t:JSON.stringify(m2(t))}function m2(t){for(var e={},r=t;r!==null;)Object.getOwnPropertyNames(r).forEach(function(n){if(!e[n]){var o=r[n];o&&(e[n]=String(o))}}),r=Object.getPrototypeOf(r);return e}var f2=JM();function Nf(t){try{f2(t)}catch{}}var QM="1.30.1";var h2="process.runtime.name";var g2="service.name";var S2="telemetry.sdk.name",y2="telemetry.sdk.language",E2="telemetry.sdk.version";var ZM=h2;var eO=g2;var Rd=S2,wd=y2,xd=E2;var T2="nodejs";var tO=T2;var oc,hs=(oc={},oc[Rd]="opentelemetry",oc[ZM]="node",oc[wd]=tO,oc[xd]=QM,oc);function _d(t){t.unref()}var x2=9,_2=6,I2=Math.pow(10,_2),MMe=Math.pow(10,x2);function gs(t){var e=t/1e3,r=Math.trunc(e),n=Math.round(t%1e3*I2);return[r,n]}function ic(t){return t[0]*1e6+t[1]/1e3}var Id;(function(t){t[t.SUCCESS=0]="SUCCESS",t[t.FAILED=1]="FAILED"})(Id||(Id={}));yt();function rO(t,e){return new Promise(function(r){Jl.with(XM(Jl.active()),function(){t.export(e,function(n){r(n)})})})}var nO={_export:rO};var P2=function(t,e){var r=typeof Symbol=="function"&&t[Symbol.iterator];if(!r)return t;var n=r.call(t),o,i=[],a;try{for(;(e===void 0||e-- >0)&&!(o=n.next()).done;)i.push(o.value)}catch(s){a={error:s}}finally{try{o&&!o.done&&(r=n.return)&&r.call(n)}finally{if(a)throw a.error}}return i},Df=function(){function t(e,r,n){r===void 0&&(r=0),n===void 0&&(n=[0,0]),this.startTime=e,this._current=r,this.sampleTime=n}return t.prototype.record=function(e){this._current=e,this.sampleTime=gs(Date.now())},t.prototype.setStartTime=function(e){this.startTime=e},t.prototype.toPointValue=function(){return this._current},t}();var AT=function(){function t(){this.kind=$n.LAST_VALUE}return t.prototype.createAccumulation=function(e){return new Df(e)},t.prototype.merge=function(e,r){var n=ic(r.sampleTime)>=ic(e.sampleTime)?r:e;return new Df(e.startTime,n.toPointValue(),n.sampleTime)},t.prototype.diff=function(e,r){var n=ic(r.sampleTime)>=ic(e.sampleTime)?r:e;return new Df(r.startTime,n.toPointValue(),n.sampleTime)},t.prototype.toMetricData=function(e,r,n,o){return{descriptor:e,aggregationTemporality:r,dataPointType:Vo.GAUGE,dataPoints:n.map(function(i){var a=P2(i,2),s=a[0],c=a[1];return{attributes:s,startTime:c.startTime,endTime:o,value:c.toPointValue()}})}},t}();var M2=function(t,e){var r=typeof Symbol=="function"&&t[Symbol.iterator];if(!r)return t;var n=r.call(t),o,i=[],a;try{for(;(e===void 0||e-- >0)&&!(o=n.next()).done;)i.push(o.value)}catch(s){a={error:s}}finally{try{o&&!o.done&&(r=n.return)&&r.call(n)}finally{if(a)throw a.error}}return i},ac=function(){function t(e,r,n,o){n===void 0&&(n=0),o===void 0&&(o=!1),this.startTime=e,this.monotonic=r,this._current=n,this.reset=o}return t.prototype.record=function(e){this.monotonic&&e<0||(this._current+=e)},t.prototype.setStartTime=function(e){this.startTime=e},t.prototype.toPointValue=function(){return this._current},t}();var kf=function(){function t(e){this.monotonic=e,this.kind=$n.SUM}return t.prototype.createAccumulation=function(e){return new ac(e,this.monotonic)},t.prototype.merge=function(e,r){var n=e.toPointValue(),o=r.toPointValue();return r.reset?new ac(r.startTime,this.monotonic,o,r.reset):new ac(e.startTime,this.monotonic,n+o)},t.prototype.diff=function(e,r){var n=e.toPointValue(),o=r.toPointValue();return this.monotonic&&n>o?new ac(r.startTime,this.monotonic,o,!0):new ac(r.startTime,this.monotonic,o-n)},t.prototype.toMetricData=function(e,r,n,o){return{descriptor:e,aggregationTemporality:r,dataPointType:Vo.SUM,dataPoints:n.map(function(i){var a=M2(i,2),s=a[0],c=a[1];return{attributes:s,startTime:c.startTime,endTime:o,value:c.toPointValue()}}),isMonotonic:this.monotonic}},t}();var Ss=function(){var t=function(e,r){return t=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])},t(e,r)};return function(e,r){if(typeof r!="function"&&r!==null)throw new TypeError("Class extends value "+String(r)+" is not a constructor or null");t(e,r);function n(){this.constructor=e}e.prototype=r===null?Object.create(r):(n.prototype=r.prototype,new n)}}(),qn=function(){function t(){}return t.Drop=function(){return uO},t.Sum=function(){return dO},t.LastValue=function(){return pO},t.Histogram=function(){return mO},t.ExponentialHistogram=function(){return O2},t.Default=function(){return L2},t}();var oO=function(t){Ss(e,t);function e(){return t!==null&&t.apply(this,arguments)||this}return e.prototype.createAggregator=function(r){return e.DEFAULT_INSTANCE},e.DEFAULT_INSTANCE=new hT,e}(qn);var iO=function(t){Ss(e,t);function e(){return t!==null&&t.apply(this,arguments)||this}return e.prototype.createAggregator=function(r){switch(r.type){case Xe.COUNTER:case Xe.OBSERVABLE_COUNTER:case Xe.HISTOGRAM:return e.MONOTONIC_INSTANCE;default:return e.NON_MONOTONIC_INSTANCE}},e.MONOTONIC_INSTANCE=new kf(!0),e.NON_MONOTONIC_INSTANCE=new kf(!1),e}(qn);var aO=function(t){Ss(e,t);function e(){return t!==null&&t.apply(this,arguments)||this}return e.prototype.createAggregator=function(r){return e.DEFAULT_INSTANCE},e.DEFAULT_INSTANCE=new AT,e}(qn);var sO=function(t){Ss(e,t);function e(){return t!==null&&t.apply(this,arguments)||this}return e.prototype.createAggregator=function(r){return e.DEFAULT_INSTANCE},e.DEFAULT_INSTANCE=new _f([0,5,10,25,50,75,100,250,500,750,1e3,2500,5e3,7500,1e4],!0),e}(qn);var Pd=function(t){Ss(e,t);function e(r,n){n===void 0&&(n=!0);var o=t.call(this)||this;if(o._recordMinMax=n,r==null)throw new Error("ExplicitBucketHistogramAggregation should be created with explicit boundaries, if a single bucket histogram is required, please pass an empty array");r=r.concat(),r=r.sort(function(s,c){return s-c});var i=r.lastIndexOf(-1/0),a=r.indexOf(1/0);return a===-1&&(a=void 0),o._boundaries=r.slice(i+1,a),o}return e.prototype.createAggregator=function(r){return new _f(this._boundaries,this._recordMinMax)},e}(qn);var lO=function(t){Ss(e,t);function e(r,n){r===void 0&&(r=160),n===void 0&&(n=!0);var o=t.call(this)||this;return o._maxSize=r,o._recordMinMax=n,o}return e.prototype.createAggregator=function(r){return new vT(this._maxSize,this._recordMinMax)},e}(qn);var cO=function(t){Ss(e,t);function e(){return t!==null&&t.apply(this,arguments)||this}return e.prototype._resolve=function(r){switch(r.type){case Xe.COUNTER:case Xe.UP_DOWN_COUNTER:case Xe.OBSERVABLE_COUNTER:case Xe.OBSERVABLE_UP_DOWN_COUNTER:return dO;case Xe.GAUGE:case Xe.OBSERVABLE_GAUGE:return pO;case Xe.HISTOGRAM:return r.advice.explicitBucketBoundaries?new Pd(r.advice.explicitBucketBoundaries):mO}return ie.warn("Unable to recognize instrument type: "+r.type),uO},e.prototype.createAggregator=function(r){return this._resolve(r).createAggregator(r)},e}(qn);var uO=new oO,dO=new iO,pO=new aO,mO=new sO,O2=new lO,L2=new cO;var fO=function(t){return qn.Default()},hO=function(t){return nc.CUMULATIVE};var CT=function(t,e,r,n){function o(i){return i instanceof r?i:new r(function(a){a(i)})}return new(r||(r=Promise))(function(i,a){function s(u){try{l(n.next(u))}catch(d){a(d)}}function c(u){try{l(n.throw(u))}catch(d){a(d)}}function l(u){u.done?i(u.value):o(u.value).then(s,c)}l((n=n.apply(t,e||[])).next())})},RT=function(t,e){var r={label:0,sent:function(){if(i[0]&1)throw i[1];return i[1]},trys:[],ops:[]},n,o,i,a;return a={next:s(0),throw:s(1),return:s(2)},typeof Symbol=="function"&&(a[Symbol.iterator]=function(){return this}),a;function s(l){return function(u){return c([l,u])}}function c(l){if(n)throw new TypeError("Generator is already executing.");for(;r;)try{if(n=1,o&&(i=l[0]&2?o.return:l[0]?o.throw||((i=o.return)&&i.call(o),0):o.next)&&!(i=i.call(o,l[1])).done)return i;switch(o=0,i&&(l=[l[0]&2,i.value]),l[0]){case 0:case 1:i=l;break;case 4:return r.label++,{value:l[1],done:!1};case 5:r.label++,o=l[1],l=[0];continue;case 7:l=r.ops.pop(),r.trys.pop();continue;default:if(i=r.trys,!(i=i.length>0&&i[i.length-1])&&(l[0]===6||l[0]===2)){r=0;continue}if(l[0]===3&&(!i||l[1]>i[0]&&l[1]<i[3])){r.label=l[1];break}if(l[0]===6&&r.label<i[1]){r.label=i[1],i=l;break}if(i&&r.label<i[2]){r.label=i[2],r.ops.push(l);break}i[2]&&r.ops.pop(),r.trys.pop();continue}l=e.call(t,r)}catch(u){l=[6,u],o=0}finally{n=i=0}if(l[0]&5)throw l[1];return{value:l[0]?l[1]:void 0,done:!0}}},gO=function(t,e){var r=typeof Symbol=="function"&&t[Symbol.iterator];if(!r)return t;var n=r.call(t),o,i=[],a;try{for(;(e===void 0||e-- >0)&&!(o=n.next()).done;)i.push(o.value)}catch(s){a={error:s}}finally{try{o&&!o.done&&(r=n.return)&&r.call(n)}finally{if(a)throw a.error}}return i},N2=function(t,e,r){if(r||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 t.concat(i||Array.prototype.slice.call(e))},SO=function(){function t(e){var r,n,o;this._shutdown=!1,this._aggregationSelector=(r=e?.aggregationSelector)!==null&&r!==void 0?r:fO,this._aggregationTemporalitySelector=(n=e?.aggregationTemporalitySelector)!==null&&n!==void 0?n:hO,this._metricProducers=(o=e?.metricProducers)!==null&&o!==void 0?o:[],this._cardinalitySelector=e?.cardinalitySelector}return t.prototype.setMetricProducer=function(e){if(this._sdkMetricProducer)throw new Error("MetricReader can not be bound to a MeterProvider again.");this._sdkMetricProducer=e,this.onInitialized()},t.prototype.selectAggregation=function(e){return this._aggregationSelector(e)},t.prototype.selectAggregationTemporality=function(e){return this._aggregationTemporalitySelector(e)},t.prototype.selectCardinalityLimit=function(e){return this._cardinalitySelector?this._cardinalitySelector(e):2e3},t.prototype.onInitialized=function(){},t.prototype.collect=function(e){return CT(this,void 0,void 0,function(){var r,n,o,i,a,s;return RT(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(N2([this._sdkMetricProducer.collect({timeoutMillis:e?.timeoutMillis})],gO(this._metricProducers.map(function(l){return l.collect({timeoutMillis:e?.timeoutMillis})})),!1))];case 1:return r=gO.apply(void 0,[c.sent()]),n=r[0],o=r.slice(1),i=n.errors.concat(fT(o,function(l){return l.errors})),a=n.resourceMetrics.resource,s=n.resourceMetrics.scopeMetrics.concat(fT(o,function(l){return l.resourceMetrics.scopeMetrics})),[2,{resourceMetrics:{resource:a,scopeMetrics:s},errors:i}]}})})},t.prototype.shutdown=function(e){return CT(this,void 0,void 0,function(){return RT(this,function(r){switch(r.label){case 0:return this._shutdown?(ie.error("Cannot call shutdown twice."),[2]):e?.timeoutMillis!=null?[3,2]:[4,this.onShutdown()];case 1:return r.sent(),[3,4];case 2:return[4,aa(this.onShutdown(),e.timeoutMillis)];case 3:r.sent(),r.label=4;case 4:return this._shutdown=!0,[2]}})})},t.prototype.forceFlush=function(e){return CT(this,void 0,void 0,function(){return RT(this,function(r){switch(r.label){case 0:return this._shutdown?(ie.warn("Cannot forceFlush on already shutdown MetricReader."),[2]):e?.timeoutMillis!=null?[3,2]:[4,this.onForceFlush()];case 1:return r.sent(),[2];case 2:return[4,aa(this.onForceFlush(),e.timeoutMillis)];case 3:return r.sent(),[2]}})})},t}();yt();var D2=function(){var t=function(e,r){return t=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])},t(e,r)};return function(e,r){if(typeof r!="function"&&r!==null)throw new TypeError("Class extends value "+String(r)+" is not a constructor or null");t(e,r);function n(){this.constructor=e}e.prototype=r===null?Object.create(r):(n.prototype=r.prototype,new n)}}(),Ff=function(t,e,r,n){function o(i){return i instanceof r?i:new r(function(a){a(i)})}return new(r||(r=Promise))(function(i,a){function s(u){try{l(n.next(u))}catch(d){a(d)}}function c(u){try{l(n.throw(u))}catch(d){a(d)}}function l(u){u.done?i(u.value):o(u.value).then(s,c)}l((n=n.apply(t,e||[])).next())})},Uf=function(t,e){var r={label:0,sent:function(){if(i[0]&1)throw i[1];return i[1]},trys:[],ops:[]},n,o,i,a;return a={next:s(0),throw:s(1),return:s(2)},typeof Symbol=="function"&&(a[Symbol.iterator]=function(){return this}),a;function s(l){return function(u){return c([l,u])}}function c(l){if(n)throw new TypeError("Generator is already executing.");for(;r;)try{if(n=1,o&&(i=l[0]&2?o.return:l[0]?o.throw||((i=o.return)&&i.call(o),0):o.next)&&!(i=i.call(o,l[1])).done)return i;switch(o=0,i&&(l=[l[0]&2,i.value]),l[0]){case 0:case 1:i=l;break;case 4:return r.label++,{value:l[1],done:!1};case 5:r.label++,o=l[1],l=[0];continue;case 7:l=r.ops.pop(),r.trys.pop();continue;default:if(i=r.trys,!(i=i.length>0&&i[i.length-1])&&(l[0]===6||l[0]===2)){r=0;continue}if(l[0]===3&&(!i||l[1]>i[0]&&l[1]<i[3])){r.label=l[1];break}if(l[0]===6&&r.label<i[1]){r.label=i[1],i=l;break}if(i&&r.label<i[2]){r.label=i[2],r.ops.push(l);break}i[2]&&r.ops.pop(),r.trys.pop();continue}l=e.call(t,r)}catch(u){l=[6,u],o=0}finally{n=i=0}if(l[0]&5)throw l[1];return{value:l[0]?l[1]:void 0,done:!0}}},k2=function(t,e){var r=typeof Symbol=="function"&&t[Symbol.iterator];if(!r)return t;var n=r.call(t),o,i=[],a;try{for(;(e===void 0||e-- >0)&&!(o=n.next()).done;)i.push(o.value)}catch(s){a={error:s}}finally{try{o&&!o.done&&(r=n.return)&&r.call(n)}finally{if(a)throw a.error}}return i},F2=function(t,e,r){if(r||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 t.concat(i||Array.prototype.slice.call(e))},wT=function(t){D2(e,t);function e(r){var n,o,i,a,s=t.call(this,{aggregationSelector:(n=r.exporter.selectAggregation)===null||n===void 0?void 0:n.bind(r.exporter),aggregationTemporalitySelector:(o=r.exporter.selectAggregationTemporality)===null||o===void 0?void 0:o.bind(r.exporter),metricProducers:r.metricProducers})||this;if(r.exportIntervalMillis!==void 0&&r.exportIntervalMillis<=0)throw Error("exportIntervalMillis must be greater than 0");if(r.exportTimeoutMillis!==void 0&&r.exportTimeoutMillis<=0)throw Error("exportTimeoutMillis must be greater than 0");if(r.exportTimeoutMillis!==void 0&&r.exportIntervalMillis!==void 0&&r.exportIntervalMillis<r.exportTimeoutMillis)throw Error("exportIntervalMillis must be greater than or equal to exportTimeoutMillis");return s._exportInterval=(i=r.exportIntervalMillis)!==null&&i!==void 0?i:6e4,s._exportTimeout=(a=r.exportTimeoutMillis)!==null&&a!==void 0?a:3e4,s._exporter=r.exporter,s}return e.prototype._runOnce=function(){return Ff(this,void 0,void 0,function(){var r;return Uf(this,function(n){switch(n.label){case 0:return n.trys.push([0,2,,3]),[4,aa(this._doRun(),this._exportTimeout)];case 1:return n.sent(),[3,3];case 2:return r=n.sent(),r instanceof mT?(ie.error("Export took longer than %s milliseconds and timed out.",this._exportTimeout),[2]):(Nf(r),[3,3]);case 3:return[2]}})})},e.prototype._doRun=function(){var r,n;return Ff(this,void 0,void 0,function(){var o,i,a,s,c,l;return Uf(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&&(l=ie).error.apply(l,F2(["PeriodicExportingMetricReader: metrics collection errors"],k2(a),!1)),!i.resource.asyncAttributesPending)return[3,5];u.label=2;case 2:return u.trys.push([2,4,,5]),[4,(n=(r=i.resource).waitForAsyncAttributes)===null||n===void 0?void 0:n.call(r)];case 3:return u.sent(),[3,5];case 4:return s=u.sent(),ie.debug("Error while resolving async portion of resource: ",s),Nf(s),[3,5];case 5:return i.scopeMetrics.length===0?[2]:[4,nO._export(this._exporter,i)];case 6:if(c=u.sent(),c.code!==Id.SUCCESS)throw new Error("PeriodicExportingMetricReader: metrics export failed (error "+c.error+")");return[2]}})})},e.prototype.onInitialized=function(){var r=this;this._interval=setInterval(function(){r._runOnce()},this._exportInterval),_d(this._interval)},e.prototype.onForceFlush=function(){return Ff(this,void 0,void 0,function(){return Uf(this,function(r){switch(r.label){case 0:return[4,this._runOnce()];case 1:return r.sent(),[4,this._exporter.forceFlush()];case 2:return r.sent(),[2]}})})},e.prototype.onShutdown=function(){return Ff(this,void 0,void 0,function(){return Uf(this,function(r){switch(r.label){case 0:return this._interval&&clearInterval(this._interval),[4,this.onForceFlush()];case 1:return r.sent(),[4,this._exporter.shutdown()];case 2:return r.sent(),[2]}})})},e}(SO);yt();yt();function Bf(){return"unknown_service:"+process.argv0}var la=function(){return la=Object.assign||function(t){for(var e,r=1,n=arguments.length;r<n;r++){e=arguments[r];for(var o in e)Object.prototype.hasOwnProperty.call(e,o)&&(t[o]=e[o])}return t},la.apply(this,arguments)},U2=function(t,e,r,n){function o(i){return i instanceof r?i:new r(function(a){a(i)})}return new(r||(r=Promise))(function(i,a){function s(u){try{l(n.next(u))}catch(d){a(d)}}function c(u){try{l(n.throw(u))}catch(d){a(d)}}function l(u){u.done?i(u.value):o(u.value).then(s,c)}l((n=n.apply(t,e||[])).next())})},B2=function(t,e){var r={label:0,sent:function(){if(i[0]&1)throw i[1];return i[1]},trys:[],ops:[]},n,o,i,a;return a={next:s(0),throw:s(1),return:s(2)},typeof Symbol=="function"&&(a[Symbol.iterator]=function(){return this}),a;function s(l){return function(u){return c([l,u])}}function c(l){if(n)throw new TypeError("Generator is already executing.");for(;r;)try{if(n=1,o&&(i=l[0]&2?o.return:l[0]?o.throw||((i=o.return)&&i.call(o),0):o.next)&&!(i=i.call(o,l[1])).done)return i;switch(o=0,i&&(l=[l[0]&2,i.value]),l[0]){case 0:case 1:i=l;break;case 4:return r.label++,{value:l[1],done:!1};case 5:r.label++,o=l[1],l=[0];continue;case 7:l=r.ops.pop(),r.trys.pop();continue;default:if(i=r.trys,!(i=i.length>0&&i[i.length-1])&&(l[0]===6||l[0]===2)){r=0;continue}if(l[0]===3&&(!i||l[1]>i[0]&&l[1]<i[3])){r.label=l[1];break}if(l[0]===6&&r.label<i[1]){r.label=i[1],i=l;break}if(i&&r.label<i[2]){r.label=i[2],r.ops.push(l);break}i[2]&&r.ops.pop(),r.trys.pop();continue}l=e.call(t,r)}catch(u){l=[6,u],o=0}finally{n=i=0}if(l[0]&5)throw l[1];return{value:l[0]?l[1]:void 0,done:!0}}},z2=function(t,e){var r=typeof Symbol=="function"&&t[Symbol.iterator];if(!r)return t;var n=r.call(t),o,i=[],a;try{for(;(e===void 0||e-- >0)&&!(o=n.next()).done;)i.push(o.value)}catch(s){a={error:s}}finally{try{o&&!o.done&&(r=n.return)&&r.call(n)}finally{if(a)throw a.error}}return i},zf=function(){function t(e,r){var n=this,o;this._attributes=e,this.asyncAttributesPending=r!=null,this._syncAttributes=(o=this._attributes)!==null&&o!==void 0?o:{},this._asyncAttributesPromise=r?.then(function(i){return n._attributes=Object.assign({},n._attributes,i),n.asyncAttributesPending=!1,i},function(i){return ie.debug("a resource's async attributes promise rejected: %s",i),n.asyncAttributesPending=!1,{}})}return t.empty=function(){return t.EMPTY},t.default=function(){var e;return new t((e={},e[eO]=Bf(),e[wd]=hs[wd],e[Rd]=hs[Rd],e[xd]=hs[xd],e))},Object.defineProperty(t.prototype,"attributes",{get:function(){var e;return this.asyncAttributesPending&&ie.error("Accessing resource attributes before async attributes settled"),(e=this._attributes)!==null&&e!==void 0?e:{}},enumerable:!1,configurable:!0}),t.prototype.waitForAsyncAttributes=function(){return U2(this,void 0,void 0,function(){return B2(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]}})})},t.prototype.merge=function(e){var r=this,n;if(!e)return this;var o=la(la({},this._syncAttributes),(n=e._syncAttributes)!==null&&n!==void 0?n:e.attributes);if(!this._asyncAttributesPromise&&!e._asyncAttributesPromise)return new t(o);var i=Promise.all([this._asyncAttributesPromise,e._asyncAttributesPromise]).then(function(a){var s,c=z2(a,2),l=c[0],u=c[1];return la(la(la(la({},r._syncAttributes),l),(s=e._syncAttributes)!==null&&s!==void 0?s:e.attributes),u)});return new t(o,i)},t.EMPTY=new t({}),t}();var yO=function(){function t(){this._registeredViews=[]}return t.prototype.addView=function(e){this._registeredViews.push(e)},t.prototype.findViews=function(e,r){var n=this,o=this._registeredViews.filter(function(i){return n._matchInstrument(i.instrumentSelector,e)&&n._matchMeter(i.meterSelector,r)});return o},t.prototype._matchInstrument=function(e,r){return(e.getType()===void 0||r.type===e.getType())&&e.getNameFilter().match(r.name)&&e.getUnitFilter().match(r.unit)},t.prototype._matchMeter=function(e,r){return e.getNameFilter().match(r.name)&&(r.version===void 0||e.getVersionFilter().match(r.version))&&(r.schemaUrl===void 0||e.getSchemaUrlFilter().match(r.schemaUrl))},t}();yt();var ys=function(){var t=function(e,r){return t=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])},t(e,r)};return function(e,r){if(typeof r!="function"&&r!==null)throw new TypeError("Class extends value "+String(r)+" is not a constructor or null");t(e,r);function n(){this.constructor=e}e.prototype=r===null?Object.create(r):(n.prototype=r.prototype,new n)}}(),Hf=function(){function t(e,r){this._writableMetricStorage=e,this._descriptor=r}return t.prototype._record=function(e,r,n){if(r===void 0&&(r={}),n===void 0&&(n=Jl.active()),typeof e!="number"){ie.warn("non-number value provided to metric "+this._descriptor.name+": "+e);return}this._descriptor.valueType===En.INT&&!Number.isInteger(e)&&(ie.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,r,n,gs(Date.now()))},t}();var EO=function(t){ys(e,t);function e(){return t!==null&&t.apply(this,arguments)||this}return e.prototype.add=function(r,n,o){this._record(r,n,o)},e}(Hf);var TO=function(t){ys(e,t);function e(){return t!==null&&t.apply(this,arguments)||this}return e.prototype.add=function(r,n,o){if(r<0){ie.warn("negative value provided to counter "+this._descriptor.name+": "+r);return}this._record(r,n,o)},e}(Hf);var bO=function(t){ys(e,t);function e(){return t!==null&&t.apply(this,arguments)||this}return e.prototype.record=function(r,n,o){this._record(r,n,o)},e}(Hf);var vO=function(t){ys(e,t);function e(){return t!==null&&t.apply(this,arguments)||this}return e.prototype.record=function(r,n,o){if(r<0){ie.warn("negative value provided to histogram "+this._descriptor.name+": "+r);return}this._record(r,n,o)},e}(Hf);var Gf=function(){function t(e,r,n){this._observableRegistry=n,this._descriptor=e,this._metricStorages=r}return t.prototype.addCallback=function(e){this._observableRegistry.addCallback(e,this)},t.prototype.removeCallback=function(e){this._observableRegistry.removeCallback(e,this)},t}();var AO=function(t){ys(e,t);function e(){return t!==null&&t.apply(this,arguments)||this}return e}(Gf);var CO=function(t){ys(e,t);function e(){return t!==null&&t.apply(this,arguments)||this}return e}(Gf);var RO=function(t){ys(e,t);function e(){return t!==null&&t.apply(this,arguments)||this}return e}(Gf);function Md(t){return t instanceof Gf}var wO=function(){function t(e){this._meterSharedState=e}return t.prototype.createGauge=function(e,r){var n=Wo(e,Xe.GAUGE,r),o=this._meterSharedState.registerMetricStorage(n);return new bO(o,n)},t.prototype.createHistogram=function(e,r){var n=Wo(e,Xe.HISTOGRAM,r),o=this._meterSharedState.registerMetricStorage(n);return new vO(o,n)},t.prototype.createCounter=function(e,r){var n=Wo(e,Xe.COUNTER,r),o=this._meterSharedState.registerMetricStorage(n);return new TO(o,n)},t.prototype.createUpDownCounter=function(e,r){var n=Wo(e,Xe.UP_DOWN_COUNTER,r),o=this._meterSharedState.registerMetricStorage(n);return new EO(o,n)},t.prototype.createObservableGauge=function(e,r){var n=Wo(e,Xe.OBSERVABLE_GAUGE,r),o=this._meterSharedState.registerAsyncMetricStorage(n);return new CO(n,o,this._meterSharedState.observableRegistry)},t.prototype.createObservableCounter=function(e,r){var n=Wo(e,Xe.OBSERVABLE_COUNTER,r),o=this._meterSharedState.registerAsyncMetricStorage(n);return new AO(n,o,this._meterSharedState.observableRegistry)},t.prototype.createObservableUpDownCounter=function(e,r){var n=Wo(e,Xe.OBSERVABLE_UP_DOWN_COUNTER,r),o=this._meterSharedState.registerAsyncMetricStorage(n);return new RO(n,o,this._meterSharedState.observableRegistry)},t.prototype.addBatchObservableCallback=function(e,r){this._meterSharedState.observableRegistry.addBatchCallback(e,r)},t.prototype.removeBatchObservableCallback=function(e,r){this._meterSharedState.observableRegistry.removeBatchCallback(e,r)},t}();var jf=function(){function t(e){this._instrumentDescriptor=e}return t.prototype.getInstrumentDescriptor=function(){return this._instrumentDescriptor},t.prototype.updateDescription=function(e){this._instrumentDescriptor=Wo(this._instrumentDescriptor.name,this._instrumentDescriptor.type,{description:e,valueType:this._instrumentDescriptor.valueType,unit:this._instrumentDescriptor.unit,advice:this._instrumentDescriptor.advice})},t}();var H2=function(){var t=function(e,r){return t=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])},t(e,r)};return function(e,r){if(typeof r!="function"&&r!==null)throw new TypeError("Class extends value "+String(r)+" is not a constructor or null");t(e,r);function n(){this.constructor=e}e.prototype=r===null?Object.create(r):(n.prototype=r.prototype,new n)}}(),xO=function(t,e){var r={label:0,sent:function(){if(i[0]&1)throw i[1];return i[1]},trys:[],ops:[]},n,o,i,a;return a={next:s(0),throw:s(1),return:s(2)},typeof Symbol=="function"&&(a[Symbol.iterator]=function(){return this}),a;function s(l){return function(u){return c([l,u])}}function c(l){if(n)throw new TypeError("Generator is already executing.");for(;r;)try{if(n=1,o&&(i=l[0]&2?o.return:l[0]?o.throw||((i=o.return)&&i.call(o),0):o.next)&&!(i=i.call(o,l[1])).done)return i;switch(o=0,i&&(l=[l[0]&2,i.value]),l[0]){case 0:case 1:i=l;break;case 4:return r.label++,{value:l[1],done:!1};case 5:r.label++,o=l[1],l=[0];continue;case 7:l=r.ops.pop(),r.trys.pop();continue;default:if(i=r.trys,!(i=i.length>0&&i[i.length-1])&&(l[0]===6||l[0]===2)){r=0;continue}if(l[0]===3&&(!i||l[1]>i[0]&&l[1]<i[3])){r.label=l[1];break}if(l[0]===6&&r.label<i[1]){r.label=i[1],i=l;break}if(i&&r.label<i[2]){r.label=i[2],r.ops.push(l);break}i[2]&&r.ops.pop(),r.trys.pop();continue}l=e.call(t,r)}catch(u){l=[6,u],o=0}finally{n=i=0}if(l[0]&5)throw l[1];return{value:l[0]?l[1]:void 0,done:!0}}},G2=function(){function t(e){this._hash=e,this._valueMap=new Map,this._keyMap=new Map}return t.prototype.get=function(e,r){return r??(r=this._hash(e)),this._valueMap.get(r)},t.prototype.getOrDefault=function(e,r){var n=this._hash(e);if(this._valueMap.has(n))return this._valueMap.get(n);var o=r();return this._keyMap.has(n)||this._keyMap.set(n,e),this._valueMap.set(n,o),o},t.prototype.set=function(e,r,n){n??(n=this._hash(e)),this._keyMap.has(n)||this._keyMap.set(n,e),this._valueMap.set(n,r)},t.prototype.has=function(e,r){return r??(r=this._hash(e)),this._valueMap.has(r)},t.prototype.keys=function(){var e,r;return xO(this,function(n){switch(n.label){case 0:e=this._keyMap.entries(),r=e.next(),n.label=1;case 1:return r.done===!0?[3,3]:[4,[r.value[1],r.value[0]]];case 2:return n.sent(),r=e.next(),[3,1];case 3:return[2]}})},t.prototype.entries=function(){var e,r;return xO(this,function(n){switch(n.label){case 0:e=this._valueMap.entries(),r=e.next(),n.label=1;case 1:return r.done===!0?[3,3]:[4,[this._keyMap.get(r.value[0]),r.value[1],r.value[0]]];case 2:return n.sent(),r=e.next(),[3,1];case 3:return[2]}})},Object.defineProperty(t.prototype,"size",{get:function(){return this._valueMap.size},enumerable:!1,configurable:!0}),t}();var bo=function(t){H2(e,t);function e(){return t.call(this,wf)||this}return e}(G2);var j2=function(t,e){var r=typeof Symbol=="function"&&t[Symbol.iterator];if(!r)return t;var n=r.call(t),o,i=[],a;try{for(;(e===void 0||e-- >0)&&!(o=n.next()).done;)i.push(o.value)}catch(s){a={error:s}}finally{try{o&&!o.done&&(r=n.return)&&r.call(n)}finally{if(a)throw a.error}}return i},Vf=function(){function t(e,r){this._aggregator=e,this._activeCollectionStorage=new bo,this._cumulativeMemoStorage=new bo,this._overflowAttributes={"otel.metric.overflow":!0},this._cardinalityLimit=(r??2e3)-1,this._overflowHashCode=wf(this._overflowAttributes)}return t.prototype.record=function(e,r,n,o){var i=this,a=this._activeCollectionStorage.get(r);if(!a){if(this._activeCollectionStorage.size>=this._cardinalityLimit){var s=this._activeCollectionStorage.getOrDefault(this._overflowAttributes,function(){return i._aggregator.createAccumulation(o)});s?.record(e);return}a=this._aggregator.createAccumulation(o),this._activeCollectionStorage.set(r,a)}a?.record(e)},t.prototype.batchCumulate=function(e,r){var n=this;Array.from(e.entries()).forEach(function(o){var i=j2(o,3),a=i[0],s=i[1],c=i[2],l=n._aggregator.createAccumulation(r);l?.record(s);var u=l;if(n._cumulativeMemoStorage.has(a,c)){var d=n._cumulativeMemoStorage.get(a,c);u=n._aggregator.diff(d,l)}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,l)}if(n._activeCollectionStorage.has(a,c)){var p=n._activeCollectionStorage.get(a,c);u=n._aggregator.merge(p,u)}n._cumulativeMemoStorage.set(a,l,c),n._activeCollectionStorage.set(a,u,c)})},t.prototype.collect=function(){var e=this._activeCollectionStorage;return this._activeCollectionStorage=new bo,e},t}();var xT=function(t){var e=typeof Symbol=="function"&&Symbol.iterator,r=e&&t[e],n=0;if(r)return r.call(t);if(t&&typeof t.length=="number")return{next:function(){return t&&n>=t.length&&(t=void 0),{value:t&&t[n++],done:!t}}};throw new TypeError(e?"Object is not iterable.":"Symbol.iterator is not defined.")},_O=function(t,e){var r=typeof Symbol=="function"&&t[Symbol.iterator];if(!r)return t;var n=r.call(t),o,i=[],a;try{for(;(e===void 0||e-- >0)&&!(o=n.next()).done;)i.push(o.value)}catch(s){a={error:s}}finally{try{o&&!o.done&&(r=n.return)&&r.call(n)}finally{if(a)throw a.error}}return i},Wf=function(){function t(e,r){var n=this;this._aggregator=e,this._unreportedAccumulations=new Map,this._reportHistory=new Map,r.forEach(function(o){n._unreportedAccumulations.set(o,[])})}return t.prototype.buildMetrics=function(e,r,n,o){this._stashAccumulations(n);var i=this._getMergedUnreportedAccumulations(e),a=i,s;if(this._reportHistory.has(e)){var c=this._reportHistory.get(e),l=c.collectionTime;s=c.aggregationTemporality,s===nc.CUMULATIVE?a=t.merge(c.accumulations,i,this._aggregator):a=t.calibrateStartTime(c.accumulations,i,l)}else s=e.selectAggregationTemporality(r.type);this._reportHistory.set(e,{accumulations:a,collectionTime:o,aggregationTemporality:s});var u=V2(a);if(u.length!==0)return this._aggregator.toMetricData(r,s,u,o)},t.prototype._stashAccumulations=function(e){var r,n,o=this._unreportedAccumulations.keys();try{for(var i=xT(o),a=i.next();!a.done;a=i.next()){var s=a.value,c=this._unreportedAccumulations.get(s);c===void 0&&(c=[],this._unreportedAccumulations.set(s,c)),c.push(e)}}catch(l){r={error:l}}finally{try{a&&!a.done&&(n=i.return)&&n.call(i)}finally{if(r)throw r.error}}},t.prototype._getMergedUnreportedAccumulations=function(e){var r,n,o=new bo,i=this._unreportedAccumulations.get(e);if(this._unreportedAccumulations.set(e,[]),i===void 0)return o;try{for(var a=xT(i),s=a.next();!s.done;s=a.next()){var c=s.value;o=t.merge(o,c,this._aggregator)}}catch(l){r={error:l}}finally{try{s&&!s.done&&(n=a.return)&&n.call(a)}finally{if(r)throw r.error}}return o},t.merge=function(e,r,n){for(var o=e,i=r.entries(),a=i.next();a.done!==!0;){var s=_O(a.value,3),c=s[0],l=s[1],u=s[2];if(e.has(c,u)){var d=e.get(c,u),p=n.merge(d,l);o.set(c,p,u)}else o.set(c,l,u);a=i.next()}return o},t.calibrateStartTime=function(e,r,n){var o,i;try{for(var a=xT(e.keys()),s=a.next();!s.done;s=a.next()){var c=_O(s.value,2),l=c[0],u=c[1],d=r.get(l,u);d?.setStartTime(n)}}catch(p){o={error:p}}finally{try{s&&!s.done&&(i=a.return)&&i.call(a)}finally{if(o)throw o.error}}return r},t}();function V2(t){return Array.from(t.entries())}var W2=function(){var t=function(e,r){return t=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])},t(e,r)};return function(e,r){if(typeof r!="function"&&r!==null)throw new TypeError("Class extends value "+String(r)+" is not a constructor or null");t(e,r);function n(){this.constructor=e}e.prototype=r===null?Object.create(r):(n.prototype=r.prototype,new n)}}(),$2=function(t,e){var r=typeof Symbol=="function"&&t[Symbol.iterator];if(!r)return t;var n=r.call(t),o,i=[],a;try{for(;(e===void 0||e-- >0)&&!(o=n.next()).done;)i.push(o.value)}catch(s){a={error:s}}finally{try{o&&!o.done&&(r=n.return)&&r.call(n)}finally{if(a)throw a.error}}return i},IO=function(t){W2(e,t);function e(r,n,o,i,a){var s=t.call(this,r)||this;return s._attributesProcessor=o,s._aggregationCardinalityLimit=a,s._deltaMetricStorage=new Vf(n,s._aggregationCardinalityLimit),s._temporalMetricStorage=new Wf(n,i),s}return e.prototype.record=function(r,n){var o=this,i=new bo;Array.from(r.entries()).forEach(function(a){var s=$2(a,2),c=s[0],l=s[1];i.set(o._attributesProcessor.process(c),l)}),this._deltaMetricStorage.batchCumulate(i,n)},e.prototype.collect=function(r,n){var o=this._deltaMetricStorage.collect();return this._temporalMetricStorage.buildMetrics(r,this._instrumentDescriptor,o,n)},e}(jf);yt();function _T(t,e){var r="";return t.unit!==e.unit&&(r+=" - Unit '"+t.unit+"' does not match '"+e.unit+`'
|
|
24
|
+
`)),console.log(" ",r(s))}}setMinLevel(e){typeof e=="string"?this.minLogLevel=id[e]:this.minLogLevel=e}log(...e){this.logWithLevel(30,Bo.reset,...e)}info(...e){this.logWithLevel(30,Bo.white,...e)}debug(...e){this.logWithLevel(20,Bo.dim,...e)}warn(...e){this.logWithLevel(40,Bo.yellow,...e)}error(...e){this.logWithLevel(50,Bo.red,...e)}success(...e){this.logWithLevel(1/0,Bo.green,...e)}dimmed(...e){this.logWithLevel(30,Bo.dim,...e)}underline(...e){this.logWithLevel(40,Bo.underline,...e)}bold(...e){this.logWithLevel(40,Bo.bold,...e)}grey(...e){this.logWithLevel(20,Bo.grey,...e)}child(e){return new t(this.minLogLevel,{...this.logBindings,...e})}async flush(){}bindings(){return this.logBindings}},dE=class{debug(){}info(){}warn(){}error(){}success(){}dimmed(){}underline(){}bold(){}grey(){}child(){return this}async flush(){}bindings(){return{}}},uTe=new dE,kW=typeof window>"u"&&typeof process<"u"&&uE.safeParse(process?.env?.MOMENTIC_DEV_LOG_LEVEL).success?uE.parse(process.env.MOMENTIC_DEV_LOG_LEVEL):30,v=new ss(kW,{}),zo={info:()=>{},error:()=>{},debug:()=>{},warn:()=>{},child:()=>zo,flush:async()=>{},bindings:()=>({})},zm={},Hm=({logger:t,logKey:e,maxCount:r,intervalMs:n},o,i,...a)=>{let s=zm[e];s?clearTimeout(s.timer):(s={count:0,totalCount:0},zm[e]=s),s.totalCount++,s.count<r&&(s.count++,t.debug(o,i,...a)),s.timer=setTimeout(()=>{let c=zm[e];c?.totalCount!==c?.count&&t.debug({logKey:e,totalCount:c?.totalCount,count:c?.count},`Debug logs were rate-limited for ${e}`),delete zm[e]},n)};import{z as K}from"zod";var FW=K.array(Gl.extend({id:K.string(),name:K.string(),description:K.string().optional(),labels:K.string().array().optional()})),UW=K.array(Gl.extend({id:K.string(),name:K.string(),description:K.string().optional(),content:eE})),g_={name:K.string().min(1).max(255).describe(ea),description:K.string().optional(),settings:Ul.optional().describe("Optional mobile test settings to persist on the new test, such as retries, default environment, app selection, emulator configuration, and AI settings."),pathSegments:K.string().array().optional().describe("Path segments for the destination folder. Omit or pass [] to create the test at the project root."),defaultEnv:K.string().optional(),platform:iw.optional().default("ANDROID").describe("For LLM: Never assign this unless the user explicitly asks for iOS. Defaults to Android.")},{defaultEnv:ETe,...TTe}=g_;var bTe=K.object(g_),vTe=K.object({id:K.string(),fileName:K.string(),fullPath:K.string(),relativeFilePath:K.string().describe("relative to project root")});var ATe=K.object({steps:is.array().optional(),settings:Ul.optional(),labels:K.array(K.string()).optional()}),CTe=K.object({message:K.literal("ok")}),RTe=K.object({name:ui.optional(),description:K.string().min(1).optional(),settings:Ul.optional(),disabled:K.boolean().optional(),labels:K.array(K.string()).optional()}),wTe=K.object({message:K.string(),newRelativeTestPath:K.string().optional()}),xTe=K.object({tag:K.string(),channel:K.string(),filePath:K.string()}),_Te=K.object({name:ui}),ITe=K.object({tests:FW,modules:UW,labels:K.string().array()}),PTe=K.object({name:K.string(),description:K.string(),enabled:K.boolean()}).partial(),MTe=K.object({name:K.string(),description:K.string(),enabled:K.boolean(),steps:is.array(),testFilePath:K.string().describe("relative to the project root"),folderPath:K.string().optional().describe("user selected folder path")}),OTe=K.object({name:K.string().describe(ea),description:K.string().optional(),enabled:K.boolean().default(!0),parameters:Qu.optional(),moduleInputs:K.record(K.string(),K.string()).optional(),folderPath:K.string().optional(),testPath:K.string().optional(),startIndex:K.number().optional(),endIndex:K.number().optional()}),LTe=K.object({packages:K.string().array()}),NTe=K.object({name:K.string()}),DTe=K.object({relativeFilePath:K.string()}),S_=K.object({stepId:K.string(),testId:K.string(),environment:K.string().optional(),parentStepIdChain:K.array(K.string()),value:kl}),BW=S_.extend({platform:K.literal("ANDROID"),steps:is.array()}),zW=S_.extend({platform:K.literal("IOS"),steps:Zu.array()}),kTe=K.discriminatedUnion("platform",[BW,zW]),FTe=K.object({platform:K.nativeEnum(gn),completionType:K.string(),traceIds:K.string().array()}),UTe=K.object({completionType:K.string(),traceIds:K.string().array()});import{v4 as HW}from"uuid";var Gm=class{constructor(e){this.params=e}sessions=new Map;registerSession(e){return this.sessions.set(e.sessionId,e),e}getSession(e){return this.sessions.get(e)}listSessionIds(){return Array.from(this.sessions.keys())}touchSession(e){let r=this.sessions.get(e);if(r)return r.lastAccessedAt=Date.now(),this.resetTimeout(r),r}async killSession(e,r){let n=this.sessions.get(e);return n?(n.cleanupPromise||(n.cleanupInProgress=!0,n.cleanupPromise=(async()=>{try{return await this.kill(n,r)?(clearTimeout(n.timeoutHandle),this.sessions.delete(e),!0):(n.cleanupInProgress=!1,n.cleanupPromise=void 0,!1)}catch(o){return n.cleanupInProgress=!1,n.cleanupPromise=void 0,n.logger.error({err:o,sessionId:e,reason:r},`Failed to clean up ${this.params.sessionTypeLabel}`),!1}})()),n.cleanupPromise):!1}async killAllSessions(e){let r=this.listSessionIds(),n=await Promise.all(r.map(async o=>{try{let i=await this.killSession(o,e);return{sessionId:o,didKill:i}}catch{return{sessionId:o,didKill:!1}}}));return{killed:n.filter(o=>o.didKill).map(o=>o.sessionId),failed:n.filter(o=>!o.didKill).map(o=>o.sessionId)}}buildManagedSessionState(e){let r=Date.now(),n=HW();return{sessionId:n,createdAt:r,lastAccessedAt:r,idleTimeoutMs:e.idleTimeoutMs,logger:e.logger,timeoutHandle:setTimeout(()=>{this.killSession(n,"idle timeout").catch(o=>{e.logger.error({err:o,sessionId:n},`Failed to clean up ${this.params.sessionTypeLabel}`)})},e.idleTimeoutMs)}}resetTimeout(e){clearTimeout(e.timeoutHandle),e.timeoutHandle=setTimeout(()=>{this.killSession(e.sessionId,"idle timeout").catch(r=>{e.logger.error({err:r,sessionId:e.sessionId},`Failed to clean up ${this.params.sessionTypeLabel}`)})},e.idleTimeoutMs)}};import{z as jt}from"zod";var y_=jt.object({id:jt.string(),createdAt:jt.coerce.date(),createdBy:jt.string(),organizationId:jt.string(),name:jt.string(),description:jt.string().nullish(),enabled:jt.boolean(),schemaVersion:jt.string().describe("Schema version for steps"),parameters:jt.string().array().nullish().describe("Parameter list"),parameterEnums:jt.record(jt.string(),jt.string().array()).nullish(),defaultParameters:jt.record(jt.string(),jt.string()).nullish(),defaultCacheKey:jt.string().nullish(),defaultCacheTtl:jt.number().nullish(),defaultCacheAllInvocations:jt.boolean().nullish(),autoAuth:jt.boolean().nullish(),advanced:$S.nullish()}),YTe=y_.extend({steps:jt.lazy(()=>bt.array())}),E_=5*60*1e3,pE=tn.merge(y_.omit({id:!0,createdAt:!0,createdBy:!0,organizationId:!0,enabled:!0}));import{formatInTimeZone as QTe}from"date-fns-tz";import*as A from"zod";import{z as kt}from"zod";var mE=(e=>(e.TEST_REVIEW="TEST_REVIEW",e))(mE||{});var GW=kt.object({type:kt.literal("DESCRIPTION_UPDATE"),thoughts:kt.string()}),jm=kt.discriminatedUnion("type",[GW]),jW=kt.object({testId:kt.string(),name:kt.string(),orgId:kt.string(),runId:kt.string(),steps:Nt.array(),purpose:kt.nativeEnum(mE),details:jm.or(jm.array()).optional()});var nbe=jW.pick({name:!0,orgId:!0}),VW=kt.object({id:kt.string(),name:kt.string().nullish(),createdAt:kt.string().pipe(kt.coerce.date()).or(kt.date()),organizationId:kt.string(),schemaVersion:kt.string(),runId:kt.string().nullish(),purpose:kt.nativeEnum(mE),details:jm.or(jm.array()).optional(),applied:kt.boolean().nullish(),appliedAt:kt.coerce.date().nullish()}),T_=VW.extend({steps:Nt.array()});var Vm="x-momentic-cli-version",b_="x-momentic-client-mode",v_="x-momentic-cli-type",A_="x-momentic-logger-tags",WW="x-momentic-main-branch-name",$W="x-momentic-branch-name",qW="x-momentic-commit-timestamp",KW="x-momentic-last-commit-on-main",YW="x-momentic-last-commit-on-main-timestamp",XW="x-momentic-merged-branch-name",C_="x-momentic-session-id",wbe=A.object({error:A.boolean(),reason:A.string(),message:A.string()}),xbe=Gt.merge(py),R_=Gp,_be=Gt.merge(py);var Ibe=Gt.merge(Cw).extend({useConsensus:A.boolean().optional(),attemptNumber:A.number().optional()}),fE=rC,Pbe=Gt.merge(ww),w_=zR,Mbe=Gt.merge(xw),x_=HR,Obe=Gt.merge(_w),__=GR,Lbe=Gt.merge(Rw),I_=BR,Nbe=Gt.merge(Tw),P_=em,Dbe=Gt.merge(bw),M_=DR,kbe=Gt.merge(vw);var Fbe=Gt.merge(Aw),Ube=Gt.merge(Ow),Bbe=Gt.merge(Lw),zbe=A.object({testPaths:A.string().array().describe("can be either hyphenated, lowercase test names or UUIDs"),env:A.string().optional(),all:A.boolean().optional(),urlOverride:A.string().optional(),customHeaders:A.record(A.string(),A.string()).optional(),testInputMatrix:A.record(A.string(),A.string()).array().optional()}),O_=A.object({queuedTests:A.unknown().array(),runIds:A.string().uuid().array(),runGroupId:A.string().optional()});var Hbe=A.string().array(),Gbe=A.union([A.object({paths:A.string().array().describe("run specific test paths (e.g. todo-test)"),all:A.boolean().describe("run all tests").optional()}),A.object({path:A.string().describe("deprecated; present for backcompat")})]),L_=A.object({tests:A.record(A.string().describe("Test name"),A.string().describe("Test YAML")),modules:A.record(A.string().describe("Module name"),A.string().describe("Module YAML"))}),JW=A.object({test:A.string().describe("test YAML"),modules:A.record(A.string().describe("moduleId"),A.string().describe("module YAML"))}),jbe=JW.array(),Vbe=A.object({testId:A.string(),schemaVersion:A.string()}).merge(Va);function hE(t){let{gitMainBranch:e,gitBranchName:r,gitCommitTimestamp:n,lastCommitOnMainSha:o,lastCommitOnMainTimestamp:i}=t,a={};return e&&(a[WW]=encodeURIComponent(e)),r&&(a[$W]=encodeURIComponent(r)),n&&(a[qW]=n.toISOString()),o&&(a[KW]=encodeURIComponent(o)),i&&(a[YW]=i.toISOString()),t.mergedGitBranchName&&(a[XW]=encodeURIComponent(t.mergedGitBranchName)),a}var Wbe=A.object({entries:A.array(NC)});var $be=A.object({testId:A.string(),environment:A.string().optional()});function N_(t){return A.record(A.unknown()).transform(e=>{let r={};for(let[n,o]of Object.entries(e)){let i=t.safeParse(o);i.success&&(r[n]=i.data)}return r})}var D_=N_(DC);function k_(t){return N_(za(t))}var QW=A.object({id:A.string(),completionType:A.string(),description:A.string().optional(),thoughts:A.string(),result:A.string(),sessionType:A.string(),timeCreated:A.string().optional()}),ZW=A.object({id:A.string(),assertion:A.string().optional(),result:A.string(),thoughts:A.string(),sessionType:A.string(),timeCreated:A.string().optional()}),qbe=A.object({completionType:A.string(),traceIds:A.string().array()}),gE=A.union([QW,ZW]).array(),F_=A.object({trigger:A.nativeEnum(rn),status:A.nativeEnum(nt),startedAt:A.coerce.date().optional(),gitCommitSha:A.string().optional(),gitCommitShaShort:A.string().optional(),gitCommitTimestamp:A.coerce.date().optional(),gitBranchName:A.string().optional(),gitOriginUrl:A.string().optional(),gitCommitMessage:A.string().optional(),gitCommitAuthorName:A.string().optional(),githubRepository:A.string().optional(),gitlabProjectPath:A.string().optional(),pipelineId:A.string().optional(),cliVersion:A.string().optional()}),Kbe=A.object({id:A.string()}),U_=A.object({status:A.nativeEnum(nt),updatedAt:A.coerce.date().optional(),finishedAt:A.coerce.date().optional()}),B_=A.object({stepsSnapshot:A.array(A.record(A.unknown())).optional(),runGroupId:A.string().optional(),testId:A.string(),testName:A.string(),resolvedBaseUrl:A.string().optional(),environmentName:A.string().optional(),labels:A.array(A.string()).optional(),cliVersion:A.string().optional(),trigger:A.nativeEnum(rn),schemaVersion:A.string().optional(),section:A.nativeEnum(mm).optional(),resolvedInputs:A.record(A.string(),A.string()).optional(),quarantined:A.boolean().optional().default(!1),quarantinedReason:A.string().optional(),aiSettings:pi.optional()}),Ybe=A.object({id:A.string()}),e$=cy.pick({id:!0,status:!0,testName:!0,testId:!0,test:!0,failureReason:!0,failureDetails:!0}),z_=e$.array(),H_=cy.pick({startedAt:!0,finishedAt:!0,updatedAt:!0,results:!0,beforeResults:!0,afterResults:!0,status:!0,failureDetails:!0,failureReason:!0,failureRecoveryDetails:!0,resolvedBaseUrl:!0,environmentName:!0,labels:!0,cliVersion:!0,resolvedInputs:!0,attempts:!0,flake:!0,aiSettings:!0}).partial(),Xbe=A.object({id:A.string()}),G_=A.object({status:A.nativeEnum(nt),finishedAt:A.coerce.date().optional(),schemaVersion:A.string().optional().default("1.0.19"),results:A.record(A.string(),A.unknown()).array().optional(),beforeResults:A.record(A.string(),A.unknown()).array().optional(),afterResults:A.record(A.string(),A.unknown()).array().optional()}),Jbe=A.object({screenshot:A.string(),contentType:A.enum(["image/jpeg","image/png"]).optional()}),Qbe=A.object({id:A.string(),screenshot:A.string(),contentType:A.enum(["image/jpeg","image/png"])}),j_=A.object({key:A.string()}),V_=A.object({orgId:A.string(),userId:A.string()}),W_=A.array(tw),Zbe=A.record(A.string(),A.union([A.string(),A.boolean()])),eve=A.object({paths:A.string().array(),env:A.string().optional(),urlOverride:A.string().optional(),customHeaders:A.record(A.string(),A.string()).optional()}),$_=A.object({suiteRunIds:A.string().array(),runGroupIds:A.string().array()}),tve=A.object({suiteRunIds:A.string().array()}),rve=Sw.array(),nve=A.object({runGroupIds:A.string().array()}),t$=A.object({uploadUrl:A.string()}),ove=Gt.merge(Iw),ive=Gt.merge(Mw),ave=Gt.merge(Pw),r$=A.object({testId:A.string().optional().default(""),testName:A.string().optional().default(""),suiteId:A.string().optional().default(""),suiteName:A.string().optional().default(""),creditsUsed:A.number().optional()}),n$=A.object({transactionId:A.string(),timestamp:A.string(),event:A.nativeEnum(Yu),properties:r$}),sve=n$.array(),q_=T_.omit({steps:!0}).extend({steps:A.array(A.record(A.string(),A.unknown())).describe("unparsed ResolvedStep[]")}),lve=A.object({limit:A.number().max(10).optional(),afterTime:A.number().optional()}),K_=dw.array(),cve=A.object({applied:A.boolean().optional(),appliedAt:A.coerce.date().optional()}),Y_=t$.extend({id:A.string()}),uve=A.object({runGroupId:A.string().uuid().optional()}),X_=A.object({runGroupId:A.string().uuid()}),J_=A.object({quarantined:A.object({testId:A.string().uuid(),quarantinedAt:A.coerce.date(),quarantinedBy:A.string().optional(),quarantinedReason:A.string()}).array()}),dve=A.object({testId:A.string().uuid(),testName:A.string().optional(),reason:A.string(),gitLocalUsername:A.string().optional(),gitLocalEmail:A.string().optional(),gitLocalName:A.string().optional()}),pve=A.object({testName:A.string().optional(),reason:A.string().optional(),gitLocalUsername:A.string().optional(),gitLocalEmail:A.string().optional(),gitLocalName:A.string().optional()}),mve=Gt.merge(ix),fve=Gt.merge(ax),hve=Gt.merge(sx),gve=A.object({apkToInstall:A.object({channel:A.string(),tag:A.string().optional()}).optional(),hostname:A.string().optional(),region:A.nativeEnum(Xu).optional(),osVersion:A.nativeEnum(Ju).optional(),sessionId:A.string().optional()}),Q_=A.object({name:A.string(),webRtcUrl:A.string(),adbUrl:A.string(),token:A.string(),apkDownloadUrl:A.string().optional(),playwrightServerUrl:A.string().optional(),region:A.string().optional()}),Sve=A.object({appToInstall:A.object({channel:A.string(),tag:A.string().optional()}).optional(),hostname:A.string().optional(),region:A.nativeEnum(Xu).optional(),osVersion:A.nativeEnum(Jy).optional(),sessionId:A.string().optional()}),Z_=A.object({id:A.string(),apiUrl:A.string(),webRtcUrl:A.string(),wdaUrl:A.string(),token:A.string(),appDownloadUrl:A.string().optional(),region:A.string().optional()}),yve=A.object({channel:A.string(),tag:A.string(),md5:A.string()}),eI=A.object({id:A.string(),uploadUrl:A.string().optional(),downloadUrl:A.string(),md5:A.string().optional()}),tI=A.object({assets:A.array(A.object({channel:A.string(),tag:A.string(),md5:A.string(),platform:A.nativeEnum(gn).default("ANDROID"),createdAt:A.number().describe("Unix timestamp in milliseconds")}))}),rI=A.object({downloadUrl:A.string()});import{z as Le}from"zod";var oI=7,o$=3,nI=Le.object({quarantinedAt:Le.date(),quarantinedReason:Le.string(),quarantinedBy:Le.string().optional(),quarantinedByGitEmail:Le.string().optional(),quarantinedByGitName:Le.string().optional(),quarantinedByGitUsername:Le.string().optional()}),bve=Le.object({localTestId:Le.string()}).merge(nI).or(Le.object({cloudTestId:Le.string()}).merge(nI)),iI=(r=>(r.QUARANTINE="QUARANTINE",r.UNQUARANTINE="UNQUARANTINE",r))(iI||{});var SE=Le.object({name:Le.string(),description:Le.string().nullish(),effect:Le.nativeEnum(iI),labels:Le.array(Le.string()).nullish(),githubRepository:Le.string().nullish(),gitlabProjectPath:Le.string().nullish(),gitBranchName:Le.string().nullish(),directory:Le.string().nullish(),slackNotificationChannel:Le.string().nullish()}),i$=Le.object({type:Le.literal("LAST_N_RUNS"),lastN:Le.number().min(o$)}),a$=Le.object({type:Le.literal("LAST_N_HOURS"),lastN:Le.number().min(1).max(oI*24)}),s$=Le.object({type:Le.literal("LAST_N_DAYS"),lastN:Le.number().min(1).max(oI)}),yE=Le.discriminatedUnion("type",[i$,a$,s$]),l$=Le.object({flakeRateThreshold:Le.number().min(1).max(100),evaluationWindow:yE}),c$=SE.extend({type:Le.literal("FLAKE_RATE"),config:l$}),u$=Le.object({passRateThreshold:Le.number().min(1).max(100),evaluationWindow:yE}),d$=SE.extend({type:Le.literal("PASS_RATE"),config:u$}),p$=Le.object({failureCountThreshold:Le.number().min(0),evaluationWindow:yE}),m$=SE.extend({type:Le.literal("FAILURE_COUNT"),config:p$}),vve=Le.discriminatedUnion("type",[c$,d$,m$]);import{z as Vt}from"zod";var Rve=Vt.object({repositoriesIndexed:Vt.boolean(),indexingInProgress:Vt.boolean(),indexesOutdated:Vt.boolean()}),aI=(a=>(a.Queued="queued",a.InProgress="in_progress",a.Completed="completed",a.Waiting="waiting",a.Requested="requested",a.Pending="pending",a))(aI||{}),sI=(s=>(s.Success="success",s.Failure="failure",s.Neutral="neutral",s.Cancelled="cancelled",s.Skipped="skipped",s.TimedOut="timed_out",s.ActionRequired="action_required",s))(sI||{}),wve=Vt.object({name:Vt.string(),status:Vt.nativeEnum(aI),conclusion:Vt.nativeEnum(sI).nullable()}),ad=Vt.object({sha:Vt.string(),message:Vt.string(),author:Vt.object({name:Vt.string().optional(),email:Vt.string().optional(),date:Vt.coerce.date().optional()}),committer:Vt.object({name:Vt.string().optional(),email:Vt.string().optional(),date:Vt.coerce.date().optional()})}),EE=Vt.object({mergedBranch:Vt.string().optional()});import{z as _t}from"zod";var lI=_t.object({orgId:_t.string(),cacheKeys:_t.string().array()}),Ive=_t.object({keyParams:lI,clientMetadata:_t.string(),lockAcquisitionTimeoutMs:_t.number().optional()}),cI=_t.object({acquired:_t.boolean(),acquiredByMetadata:_t.string(),keyPrefix:_t.string()}),Pve=_t.object({keyPrefix:_t.string(),result:_t.string(),ttlMs:_t.number()}),Mve=_t.union([_t.object({keyPrefix:_t.string()}),lI]),f$=_t.object({remainingTtlMs:_t.number(),value:_t.string().nullish()}),Ove=_t.object({results:_t.record(_t.string(),f$),activeLocks:_t.string().array()}),uI=0,dI=5*60*1e3;var kve=30*24*60*60*1e3,Fve=7*24*60*60*1e3;import{z as pI}from"zod";var zve=pI.object({quarantineNotifications:pI.string().nullish()});function jl(t){if(t.startsWith("https://api"))return t.replace("https://api","https://app");if(t.startsWith("http://localhost:8000"))return t.replace("http://localhost:8000","http://localhost:3000");throw new Error(`Unknown Momentic app server URL pattern: ${t}`)}import{z as hr}from"zod";var h$=hr.object({version:hr.string(),json:hr.record(hr.unknown()),hash:hr.string()}),mI=hr.record(hr.unknown()),Wve=hr.object({newSvgs:hr.array(h$),metadata:mI.optional()}),g$=hr.object({version:hr.string(),json:hr.record(hr.unknown()).nullish(),hash:hr.string(),description:hr.string().nullish(),metadata:mI.nullish()}),fI=hr.record(hr.string().describe("icon hash"),g$);import{validator as S$}from"@exodus/schemasafe";function hI(t){let e;try{e=JSON.parse(t)}catch(r){return`The schema is not valid JSON. ${r}`}try{S$(e)}catch(r){return`The schema is not a valid JSON schema. ${r}`}}var gI=t=>{t.extraHeaders&&(t.extraHeaders=Object.fromEntries(Object.entries(t.extraHeaders).filter(([e,r])=>e.trim()&&r.trim())))};import{z as lAe}from"zod";var Wm=class{async resolveStepCacheEntries(){}async saveStepCacheEntries(){}};function y$(t){return t.map(e=>({...e,environment:void 0}))}function TE(t,e){return e?t:y$(t)}var yn="get_browser_state",$m="get_environment_variables",qm="reset_session",Ho="run_step",jn="preview_preflight",SI="preview_ensure",sr="preview_step",Km="test_get",lr="test_splice_steps",Ym="module_create",yI="momentic_module_create",Vl="momentic_module_get",Xm="momentic_module_list",ta="momentic_module_recommend",EI="momentic_attributes_list",TI="momentic_test_create",bI="momentic_test_splice_steps",vI="momentic_run_step",AI="momentic_session_start",CI="momentic_session_terminate",RI="momentic_get_session_state",wI="momentic_get_environment_variables",ls="momentic_get_initial_data",xI="momentic_preview_step";var vE="browser-crash-dump.zip",bE=class{loggerBindings;attachBeforeScreenshot(){}attachAfterScreenshot(){}attachBeforeHtmlSnapshot(){}attachAfterHtmlSnapshot(){}recordTargetAutoHeal(){}recordStepDuration(){}storeTraceAsset(){}async finish(){}async startSubSteps(){return new sd}},sd=class{async getScreenshot(){}async getHtmlSnapshot(){}async startStep(){return new bE}};import{z as AE}from"zod";var bAe=AE.object({parentStepIdChain:AE.array(AE.string()),result:Eo});import{z as oe}from"zod";var gr="assets",E$=oe.object({step:Nt,status:oe.nativeEnum(at),startedAt:oe.coerce.date(),finishedAt:oe.coerce.date().optional(),healMetadata:oe.object({healType:oe.nativeEnum(Eu).or(oe.literal("AI")),healedAt:oe.coerce.date()}).optional(),beforeSnapshotId:oe.string().uuid().optional(),afterSnapshotId:oe.string().uuid().optional(),message:oe.string().optional()}),T$=E$.extend({finishedAt:oe.coerce.date().optional().transform(t=>t??new Date)}),MAe=T$.extend({step:oe.unknown()}),CE=oe.object({avdId:oe.string().optional(),channel:oe.string().optional(),tag:oe.string().optional()}),_I="1.0.0",RE=G_.extend({id:oe.string().uuid().optional(),startedAt:oe.coerce.date(),runAttemptSchemaVersion:oe.string().optional(),schemaVersion:oe.string().optional().default("1.0.19"),results:oe.record(oe.string(),oe.unknown()).array().optional(),beforeResults:oe.record(oe.string(),oe.unknown()).array().optional(),afterResults:oe.record(oe.string(),oe.unknown()).array().optional(),assetDetails:CE.optional(),activeVideos:oe.array(oe.object({videoName:oe.string(),timestamp:oe.coerce.date()})).optional()}),II=RE.extend({assetDetails:CE.optional(),finishedAt:oe.coerce.date().optional().transform(t=>t??new Date)}),OAe=RE.merge(bu),LAe=II.merge(bu),PI=oe.object({results:oe.array(Eo),beforeResults:oe.array(Eo).optional(),afterResults:oe.array(Eo).optional()}),NAe=RE.merge(PI),DAe=II.merge(PI),MI=H_.merge(B_).extend({executionType:oe.nativeEnum(vl).optional().default("WEB"),testId:oe.string().uuid(),testDescription:oe.string().optional(),directory:oe.string().optional(),runGroupId:oe.string().uuid(),status:oe.nativeEnum(nt),startedAt:oe.coerce.date(),attempts:oe.number(),failureRecoveryDetails:oe.object({attempts:oe.number()}).optional(),aiSettings:pi.optional(),avgCpuUsage:oe.number().optional(),avgMemoryUsage:oe.number().optional()}),b$=MI.merge(CE),OI=MI.extend({finishedAt:oe.coerce.date().optional().transform(t=>t??new Date)}),kAe=b$.extend({finishedAt:oe.coerce.date().optional().transform(t=>t??new Date)}),v$=F_.merge(U_).extend({id:oe.string().uuid().optional(),startedAt:oe.coerce.date(),cliVersion:oe.string(),labels:oe.string().array().optional().default([]),suiteName:oe.string().optional(),ciProvider:oe.string().optional()}),Wl=v$.extend({updatedAt:oe.coerce.date().optional().transform(t=>t??new Date),finishedAt:oe.coerce.date().optional().transform(t=>t??new Date)});var A$=new Set(["AWAIT_LISTENER","REGISTER_REQUEST_LISTENER","GET_RECORDED_REQUESTS","MOCK_ROUTE","REMOVE_ROUTE_MOCK","SCROLL_DOWN","SCROLL_UP","SCROLL_LEFT","SCROLL_RIGHT","VISUAL_DIFF","WAIT","SET_HEADER","OFFLINE_MODE"]),C$=new Set(["MODULE","RESOLVED_MODULE"]),jAe=new Set(["MOBILE_MODULE_STEP","RESOLVED_MOBILE_MODULE"]);function Jm(t){return t.type!=="PRESET_ACTION"?t.type:t.command.type}function Qm(t){return C$.has(t.type)?!1:t.type!=="PRESET_ACTION"?!0:!A$.has(t.command.type)}var ARe=5*1024,R$="...[truncated]",CRe=Buffer.byteLength(R$,"utf8");import x$ from"fetch-retry";import _$ from"os";import NI,{multistream as I$}from"pino";import P$ from"pino-pretty";import M$ from"pino-std-serializers";var ld;function LI(t){ld=t}var w$=new Set(["InternalWebAgentError","InternalPlatformError","UnknownError"]);function wE(t){return t instanceof Error&&t.name==="AbortError"?!1:t instanceof L?w$.has(t.reason):!0}var $l=new Map,O$=!0,DI="Log throttle exceeded",L$=100,N$=5e3,D$=x$(global.fetch,{retries:2,retryOn:function(t,e,r){return!!(e!==null||r&&r.status>=500)},retryDelay:function(t){return Math.pow(2,t)*500}}),xE=class t{consoleLogger;hostname;captureExceptions;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:r,disableConsoleLogs:n,flushIntervalMs:o,maxBatchSize:i,captureExceptions:a}){this.hostname=r??_$.hostname(),this.disableConsoleLogs=n,this.captureExceptions=a??!1,this.bindingAttributes={...e,env:"production"},this.flushIntervalMs=o??5e3,this.maxBatchSize=i??10;let s={base:this.bindingAttributes,errorKey:"err",level:"debug"};this.consoleLogger=O$?NI(s):NI(s,I$([{stream:P$({colorize:!0})}]))}child(e){return new t({bindings:{...this.bindingAttributes,...e},hostname:this.hostname,disableConsoleLogs:this.disableConsoleLogs,flushIntervalMs:this.flushIntervalMs,maxBatchSize:this.maxBatchSize,captureExceptions:this.captureExceptions})}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 r=await D$(this.site,{method:"POST",headers:{"Content-Type":"application/json","signoz-access-token":"CumAaTMUcwjt05OddAmefKgshbhfRmWxzxih"},body:as(e),signal:AbortSignal.timeout(5e3)});if(!r.ok)throw new Error(`Got error status (${r.statusText}) from SigNoz`)}catch{}}shouldAllowLog(e){if(e===DI)return!0;let r=Date.now();return r-this.lastWindowStart>N$&&(this.logsInCurrentWindow=0,this.droppedLogsInWindow&&this.log("error",void 0,DI),this.droppedLogsInWindow=!1,this.lastWindowStart=r),this.logsInCurrentWindow<L$?(this.logsInCurrentWindow++,!0):(this.droppedLogsInWindow=!0,!1)}log(e,r,n,...o){try{this.logHelper(e,r,n,...o)}catch(i){this.consoleLogger.warn(`Failed to log to Signoz: ${i}`)}}logHelper(e,r,n,...o){if(id[e]<this.minLevelValue||!this.shouldAllowLog(n))return;e==="error"&&this.captureExceptions&&ld&&(r instanceof Error&&wE(r)?ld(r):typeof r=="object"&&r&&"err"in r&&r.err instanceof Error&&wE(r.err)&&ld(r.err)),typeof r=="string"&&!n&&(r={message:r}),typeof r=="object"&&r&&"err"in r&&r.err instanceof Error&&(r.err=M$.err(r.err));let i={...this.bindingAttributes,...r&&typeof r=="object"?r:{},...o.length>0?{args:o}:{}},a={host:this.hostname,env:this.bindingAttributes.env};this.disableConsoleLogs||this.consoleLogger[e](i,n,...o);let s={timestamp:Math.round(Date.now()*1e6),severity_text:e.toUpperCase(),resources:a,attributes:{},body:f_({message:n||"",...i})};this.buffer.push(s),this.buffer.length>=this.maxBatchSize?(this.flushTimer&&(clearTimeout(this.flushTimer),this.flushTimer=void 0),this.flushBuffer()):this.scheduleFlush()}setApp(e){let r=this.bindingAttributes.app;this.bindingAttributes.app=e,$l.set("app",this),$l.delete(r)}debug(e,r,...n){this.log("debug",e,r,...n)}info(e,r,...n){this.log("info",e,r,...n)}warn(e,r,...n){this.log("warn",e,r,...n)}error(e,r,...n){this.log("error",e,r,...n)}bindings(){return this.bindingAttributes}addBinding(e,r){this.bindingAttributes[e]=r}setMinLevel(e){typeof e=="number"?(this.minLevelValue=e,this.consoleLogger.level=h_[e]):(this.minLevelValue=id[e],this.consoleLogger.level=e)}enableConsoleLogs(){this.disableConsoleLogs=!1}},ql=({app:t,hostname:e,disableConsoleLogs:r,captureExceptions:n})=>($l.has(t)||$l.set(t,new xE({bindings:{app:t},hostname:e,disableConsoleLogs:r,captureExceptions:n})),$l.get(t));async function Zm(){await Promise.all([...$l.values()].map(t=>t.flush()))}import{PostHog as k$}from"posthog-node";var ra=class extends Error{constructor(e){super(e),this.name="TimeoutError"}};var FI=t=>{let e=t.reason===void 0?new DOMException("This operation was aborted.","AbortError"):t.reason;return e instanceof Error?e:new DOMException(e,"AbortError")};function J(t,e){let{milliseconds:r,fallback:n,message:o,customTimers:i={setTimeout,clearTimeout}}=e,a;if(typeof r!="number"||Math.sign(r)!==1)throw new TypeError(`Expected \`milliseconds\` to be a positive number, got \`${r}\``);return new Promise((s,c)=>{let l;if(e.signal){let{signal:p}=e;if(p.aborted)return c(FI(p));l=()=>c(FI(p)),p.addEventListener("abort",l,{once:!0})}let u=()=>{if(e.signal&&e.signal.removeEventListener("abort",l),n)try{s(n())}catch(p){c(p)}else{typeof t.cancel=="function"&&Promise.resolve().then(()=>t.cancel()).catch(()=>{});let p=o instanceof Error?o:new ra(o??`Promise timed out after ${r}ms`);c(p)}};r<1/0&&(a=i.setTimeout(u,r));let d=()=>{i.clearTimeout(a),e.signal&&e.signal.removeEventListener("abort",l)};Promise.resolve(t).then(p=>{d(),s(p)}).catch(p=>{d(),c(p)})})}async function UI(t,e){let r,n=0,o=3,i,a;for(;n<o;)try{let s=await J(t.getAllFlagsAndPayloads("unknown",{personProperties:{organizationId:e}}),{milliseconds:5e3});i=s.featureFlags||{},a=s.featureFlagPayloads||{};break}catch(s){r=s,n++,await new Promise(c=>setTimeout(c,100*n))}if(i&&a)return{flags:i,payloads:a};throw r}var ef=class t extends nd{constructor(r,n,o,i){super(o,i);this.client=r;this.orgId=n}static async init(r){let n=new k$("phc_WRWd8LYIv6rolgDsyCdrPpxtZhsu6qXAkEwPicl44bI",{host:"https://us.i.posthog.com"}),{flags:o,payloads:i}=await UI(n,r);return new t(n,r,o,i)}async refresh(){let{flags:r,payloads:n}=await UI(this.client,this.orgId);this.flags=r,this.payloads=n}};import{randomUUID as F$}from"node:crypto";import{PostHog as U$}from"posthog-node";var tf=class t{identity;bindings;client;options;constructor(e,r={},n){this.bindings=e,this.options=r,this.identity=n,this.client=new U$("phc_oy1FexHsc0S3axxOMXCm46yZsW35zROAoV4SOzpDSXH",{host:"https://us.i.posthog.com",...r})}async shutdown(){await this.client.shutdown()}identify(e,r){return this.identity=e,this.bindings={...this.bindings,...r},this}child(e){return new t({...this.bindings,...e},this.options,this.identity)}track(e,r){if(!cx(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:this.identity?.userId??F$(),event:n,timestamp:r?.timestamp,properties:{...this.bindings,...o,organizationId:this.identity?.orgId}}),this}};import{execSync as B$}from"child_process";import{readFileSync as HI}from"fs";import gi from"os";import z$ from"v8";var cs=!!process.env.CI||!!process.env.GITHUB_ACTIONS||!!process.env.GITHUB_RUN_ID||!!process.env.GITLAB_CI||!!process.env.CI_COMMIT_SHA||!!process.env.JENKINS_URL||!!process.env.BUILD_NUMBER||!!process.env.JENKINS_HOME||!!process.env.CIRCLECI||!!process.env.CIRCLE_BUILD_NUM||!!process.env.TRAVIS||!!process.env.TRAVIS_BUILD_NUMBER||!!process.env.BITBUCKET_BUILD_NUMBER||!!process.env.BITBUCKET_COMMIT||!!process.env.CODEBUILD_BUILD_ID||!!process.env.TF_BUILD||!!process.env.BUILD_BUILDID||!!process.env.AGENT_ID||!!process.env.BUILDER_SA_EMAIL||!!process.env.HEROKU_TEST_RUN_ID||!!process.env.CI_NODE_INDEX||!!process.env.TEAMCITY_VERSION||!!process.env.BUILD_VCS_NUMBER||!!process.env.BUILDKITE||!!process.env.BUILDKITE_BUILD_NUMBER||!!process.env.APPVEYOR||!!process.env.APPVEYOR_BUILD_NUMBER||!!process.env.DRONE||!!process.env.DRONE_BUILD_NUMBER||!!process.env.SHIPPABLE||!!process.env.BUILD_URL||!!process.env.SEMAPHORE||!!process.env.SEMAPHORE_EXECUTABLE_UUID||!!process.env.WOODPECKER||!!process.env.CI_BUILD_NUMBER||!!process.env.WERCKER_MAIN_PIPELINE_STARTED||!!process.env.BUDDY_EXECUTION_ID;var H$=2e3,us=t=>Number.parseInt(t,10),PE=t=>HI(t,"utf8").trim(),Kl=t=>us(PE(t)),BI,rf,_E=0,of=gi.platform(),G$=gi.cpus().map(t=>({model:t.model,speed:t.speed})).reduce((t,e)=>(t[e.model]={speed:e.speed},t.totalCores=(t.totalCores??0)+1,t),{});function IE(t=Date.now()){let e=gi.cpus(),r={measurementTime:t,user:0,nice:0,sys:0,idle:0,irq:0,total:0};for(let n of e)r.user+=n.times.user,r.nice+=n.times.nice,r.sys+=n.times.sys,r.idle+=n.times.idle,r.irq+=n.times.irq;return r.total=r.user+r.nice+r.sys+r.idle+r.irq,r}function GI(t,e){let r={user:e.user-t.user,nice:e.nice-t.nice,sys:e.sys-t.sys,idle:e.idle-t.idle,irq:e.irq-t.irq,total:e.total-t.total};return r.total<=0?null:{measurementTime:e.measurementTime,intervalMs:e.measurementTime-t.measurementTime,user:r.user/r.total*100,nice:r.nice/r.total*100,sys:r.sys/r.total*100,idle:r.idle/r.total*100,irq:r.irq/r.total*100,total:100-r.idle/r.total*100}}function j$(){let t=IE();return()=>{let e=IE(),r=GI(t,e);return t=e,r}}function zI(){try{let e=HI("/sys/fs/cgroup/cpu.stat","utf8").match(/^usage_usec\s+(\d+)/m);if(e?.[1])return us(e[1])}catch{}try{let t=Kl("/sys/fs/cgroup/cpuacct/cpuacct.usage");if(!isNaN(t))return t/1e3}catch{}return null}function V$(){try{let e=PE("/sys/fs/cgroup/cpu.max").split(" "),r=e[0],n=e[1];return!r||!n||r==="max"?null:us(r)/us(n)}catch{}try{let t=Kl("/sys/fs/cgroup/cpu/cpu.cfs_quota_us"),e=Kl("/sys/fs/cgroup/cpu/cpu.cfs_period_us");return t===-1||isNaN(e)?null:t/e}catch{return null}}function W$(){if(of!=="linux")return null;let t=zI();if(t===null)return null;let e=V$()??gi.cpus().length,r=t,n=Date.now();return()=>{let o=zI();if(o===null)return null;let i=Date.now(),a=i-n;if(a<=0)return null;let s=o-r,c=a*1e3,l=Math.max(0,Math.min(100,s/c/e*100));return r=o,n=i,{measurementTime:i,intervalMs:a,user:l,nice:0,sys:0,idle:Math.max(0,100-l),irq:0,total:l}}}function $$(){let t=process.cpuUsage(),e=process.hrtime.bigint();return()=>{let r=process.cpuUsage(),n=process.hrtime.bigint(),o=Number(n-e)/1e6,i=r.user-t.user,a=r.system-t.system;if(t=r,e=n,o<=0)return null;let s=Math.max(gi.cpus().length,1),c=l=>Math.max(0,l/1e3/o*100/s);return{total:c(i+a),user:c(i),sys:c(a),intervalMs:o}}}function jI({intervalMs:t=H$,maxSamples:e=1e4,keepSamples:r=!0,onSample:n}={}){let o=[],i=W$()??j$(),a=$$(),s=()=>{let u=Date.now(),d=$I(),p=process.memoryUsage(),m=i(),f=a(),h={timestamp:u,system:{cpu:m,memory:{total:d.totalMemory,free:d.freeMemory,freePercentage:d.freePercentage}},process:{cpu:f,memory:{rss:p.rss,heapTotal:p.heapTotal,heapUsed:p.heapUsed,external:p.external,arrayBuffers:p.arrayBuffers}}};n?.(h),r&&(o.push(h),o.length>e&&o.shift())};s();let c=setInterval(s,t),l=u=>({samples:r?[...o]:[]});return{stop:()=>(clearInterval(c),l(Date.now())),getSeries:()=>l(Date.now())}}var nf=t=>{try{let e={},r=!1,n=$I(),o=K$(),i=`${Math.round(n.freePercentage*100)}%`;n.freePercentage<.05&&(Object.assign(e,process.memoryUsage()),r=!0);let a=`${o?Math.round(o.idle):"unknown"}%`;o&&o?.total>80&&(r=!0);let s=z$.getHeapStatistics(),c=s.used_heap_size,l=s.heap_size_limit;c/l>.9&&(r=!0),r?(_E++,t.warn({memory:n,cpu:o,heapStats:s,...e},"Critical resource usage metrics detected"),cs&&_E>=2&&v.warn(`Low machine resources detected (memory: ${i} free, cpu: ${a} free)`)):(_E=0,t.debug({memory:n,cpu:o},"Got machine resource usage metrics"))}catch{}},VI=t=>{nf(t),setTimeout(()=>nf(t),5e3)};function WI(t){if(!Gn)return nf(t),{interval:setInterval(()=>nf(t),2e4),cpuMetadata:G$,platform:of}}function q$(){if(of!=="linux")return null;try{let t=PE("/sys/fs/cgroup/memory.max"),e=Kl("/sys/fs/cgroup/memory.current");if(t==="max"||isNaN(e))return null;let r=us(t);if(isNaN(r))return null;let n=Math.max(0,r-e);return{totalMemory:r,freeMemory:n,freePercentage:n/r}}catch{}try{let t=Kl("/sys/fs/cgroup/memory/memory.limit_in_bytes"),e=Kl("/sys/fs/cgroup/memory/memory.usage_in_bytes");if(isNaN(t)||isNaN(e))return null;let r=gi.totalmem();if(t>=r)return null;let n=Math.max(0,t-e);return{totalMemory:t,freeMemory:n,freePercentage:n/t}}catch{return null}}function $I(){let t=q$();if(t)return t;let e=gi.totalmem(),r=of==="darwin"?Y$():(()=>{let o=gi.freemem();return{availableMemory:o,rawFreeMemory:o,cachedMemory:0}})(),n=r.availableMemory/e;return{totalMemory:e,freeMemory:r.availableMemory,freePercentage:n}}function K$(){let t=IE();if(!rf)return rf=t,null;let e=GI(rf,t);return rf=t,e?(BI=e,BI):null}function Y$(){try{let t=B$("/usr/bin/vm_stat",{encoding:"utf8",stdio:["pipe","pipe","ignore"]}),r=t.match(/page size of (\d+) bytes/)?.[1],n=r?us(r):4096,o=u=>{let p=t.match(new RegExp(`${u}:\\s+(\\d+)\\.`,"i"))?.[1];return p?us(p):0},i=o("Pages free"),a=o("Pages inactive"),s=o("Pages speculative"),c=i*n,l=(a+s)*n;return{availableMemory:c+l,rawFreeMemory:c,cachedMemory:l}}catch{let t=gi.freemem();return{availableMemory:t,rawFreeMemory:t,cachedMemory:0}}}var af=class{increment(e,r,n){}gauge(e,r){}distribution(e,r,n){}async flush(){}async recordDuration({fn:e}){return await e()}};function X$(t){if(!t||t.length===0)return{};let e={};for(let r of t){let n=r.indexOf(":");if(n>-1){let o=r.slice(0,n).trim(),i=r.slice(n+1).trim();o&&(e[o]=i);continue}e[r]=!0}return e}function sf(t,e){let r=X$(t);return!e||Object.keys(e).length===0?r:{...e,...r}}var EP="=",df=";",GE=",";var TP=8192;var Ql={};O1(Ql,{getKeyPairs:()=>Iq,parseKeyPairsIntoRecord:()=>Pq,parsePairKeyValue:()=>bP,serializeKeyPairs:()=>_q});yt();var xq=function(t,e){var r=typeof Symbol=="function"&&t[Symbol.iterator];if(!r)return t;var n=r.call(t),o,i=[],a;try{for(;(e===void 0||e-- >0)&&!(o=n.next()).done;)i.push(o.value)}catch(s){a={error:s}}finally{try{o&&!o.done&&(r=n.return)&&r.call(n)}finally{if(a)throw a.error}}return i};function _q(t){return t.reduce(function(e,r){var n=""+e+(e!==""?GE:"")+r;return n.length>TP?e:n},"")}function Iq(t){return t.getAllEntries().map(function(e){var r=xq(e,2),n=r[0],o=r[1],i=encodeURIComponent(n)+"="+encodeURIComponent(o.value);return o.metadata!==void 0&&(i+=df+o.metadata.toString()),i})}function bP(t){var e=t.split(df);if(!(e.length<=0)){var r=e.shift();if(r){var n=r.indexOf(EP);if(!(n<=0)){var o=decodeURIComponent(r.substring(0,n).trim()),i=decodeURIComponent(r.substring(n+1).trim()),a;return e.length>0&&(a=OE(e.join(df))),{key:o,value:i,metadata:a}}}}}function Pq(t){return typeof t!="string"||t.length===0?{}:t.split(GE).map(function(e){return bP(e)}).filter(function(e){return e!==void 0&&e.value.length>0}).reduce(function(e,r){return e[r.key]=r.value,e},{})}yt();var pf;(function(t){t.AlwaysOff="always_off",t.AlwaysOn="always_on",t.ParentBasedAlwaysOff="parentbased_always_off",t.ParentBasedAlwaysOn="parentbased_always_on",t.ParentBasedTraceIdRatio="parentbased_traceidratio",t.TraceIdRatio="traceidratio"})(pf||(pf={}));var Mq=",",Oq=["OTEL_SDK_DISABLED"];function Lq(t){return Oq.indexOf(t)>-1}var Nq=["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 Dq(t){return Nq.indexOf(t)>-1}var kq=["OTEL_NO_PATCH_MODULES","OTEL_PROPAGATORS"];function Fq(t){return kq.indexOf(t)>-1}var jE=1/0,VE=128,Uq=128,Bq=128,WE={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:At.INFO,OTEL_NO_PATCH_MODULES:[],OTEL_PROPAGATORS:["tracecontext","baggage"],OTEL_RESOURCE_ATTRIBUTES:"",OTEL_SERVICE_NAME:"",OTEL_ATTRIBUTE_VALUE_LENGTH_LIMIT:jE,OTEL_ATTRIBUTE_COUNT_LIMIT:VE,OTEL_SPAN_ATTRIBUTE_VALUE_LENGTH_LIMIT:jE,OTEL_SPAN_ATTRIBUTE_COUNT_LIMIT:VE,OTEL_LOGRECORD_ATTRIBUTE_VALUE_LENGTH_LIMIT:jE,OTEL_LOGRECORD_ATTRIBUTE_COUNT_LIMIT:VE,OTEL_SPAN_EVENT_COUNT_LIMIT:128,OTEL_SPAN_LINK_COUNT_LIMIT:128,OTEL_SPAN_ATTRIBUTE_PER_EVENT_COUNT_LIMIT:Uq,OTEL_SPAN_ATTRIBUTE_PER_LINK_COUNT_LIMIT:Bq,OTEL_TRACES_EXPORTER:"",OTEL_TRACES_SAMPLER:pf.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 zq(t,e,r){if(!(typeof r[t]>"u")){var n=String(r[t]);e[t]=n.toLowerCase()==="true"}}function Hq(t,e,r,n,o){if(n===void 0&&(n=-1/0),o===void 0&&(o=1/0),typeof r[t]<"u"){var i=Number(r[t]);isNaN(i)||(i<n?e[t]=n:i>o?e[t]=o:e[t]=i)}}function Gq(t,e,r,n){n===void 0&&(n=Mq);var o=r[t];typeof o=="string"&&(e[t]=o.split(n).map(function(i){return i.trim()}))}var jq={ALL:At.ALL,VERBOSE:At.VERBOSE,DEBUG:At.DEBUG,INFO:At.INFO,WARN:At.WARN,ERROR:At.ERROR,NONE:At.NONE};function Vq(t,e,r){var n=r[t];if(typeof n=="string"){var o=jq[n.toUpperCase()];o!=null&&(e[t]=o)}}function vP(t){var e={};for(var r in WE){var n=r;switch(n){case"OTEL_LOG_LEVEL":Vq(n,e,t);break;default:if(Lq(n))zq(n,e,t);else if(Dq(n))Hq(n,e,t);else if(Fq(n))Gq(n,e,t);else{var o=t[n];typeof o<"u"&&o!==null&&(e[n]=String(o))}}}return e}function Sr(){var t=vP(process.env);return Object.assign({},WE,t)}function AP(t){return t>=48&&t<=57?t-48:t>=97&&t<=102?t-87:t-55}function mf(t){for(var e=new Uint8Array(t.length/2),r=0,n=0;n<t.length;n+=2){var o=AP(t.charCodeAt(n)),i=AP(t.charCodeAt(n+1));e[r++]=o<<4|i}return e}var CP="1.25.1";var Wq="deployment.environment";var $q="process.runtime.name";var qq="service.name";var Kq="service.instance.id";var Yq="telemetry.sdk.name",Xq="telemetry.sdk.language",Jq="telemetry.sdk.version";var RP=Wq;var wP=$q;var ff=qq;var xP=Kq;var hd=Yq,gd=Xq,Sd=Jq;var Qq="nodejs";var _P=Qq;var Zl,hf=(Zl={},Zl[hd]="opentelemetry",Zl[wP]="node",Zl[gd]=_P,Zl[Sd]=CP,Zl);var Zq=9,eK=6,tK=Math.pow(10,eK),rK=Math.pow(10,Zq);function IP(t){var e=t/1e3,r=Math.trunc(e),n=Math.round(t%1e3*tK);return[r,n]}function PP(t){return t[0]*rK+t[1]}function yd(t){return t[0]*1e6+t[1]/1e3}var ps;(function(t){t[t.SUCCESS=0]="SUCCESS",t[t.FAILED=1]="FAILED"})(ps||(ps={}));var MP=function(){function t(){var e=this;this._promise=new Promise(function(r,n){e._resolve=r,e._reject=n})}return Object.defineProperty(t.prototype,"promise",{get:function(){return this._promise},enumerable:!1,configurable:!0}),t.prototype.resolve=function(e){this._resolve(e)},t.prototype.reject=function(e){this._reject(e)},t}();var nK=function(t,e){var r=typeof Symbol=="function"&&t[Symbol.iterator];if(!r)return t;var n=r.call(t),o,i=[],a;try{for(;(e===void 0||e-- >0)&&!(o=n.next()).done;)i.push(o.value)}catch(s){a={error:s}}finally{try{o&&!o.done&&(r=n.return)&&r.call(n)}finally{if(a)throw a.error}}return i},oK=function(t,e,r){if(r||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 t.concat(i||Array.prototype.slice.call(e))},OP=function(){function t(e,r){this._callback=e,this._that=r,this._isCalled=!1,this._deferred=new MP}return Object.defineProperty(t.prototype,"isCalled",{get:function(){return this._isCalled},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"promise",{get:function(){return this._deferred.promise},enumerable:!1,configurable:!0}),t.prototype.call=function(){for(var e,r=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,oK([this._that],nK(n),!1))).then(function(i){return r._deferred.resolve(i)},function(i){return r._deferred.reject(i)})}catch(i){this._deferred.reject(i)}}return this._deferred.promise},t}();var Vn;(function(t){t[t.DELTA=0]="DELTA",t[t.CUMULATIVE=1]="CUMULATIVE"})(Vn||(Vn={}));var Lr;(function(t){t[t.HISTOGRAM=0]="HISTOGRAM",t[t.EXPONENTIAL_HISTOGRAM=1]="EXPONENTIAL_HISTOGRAM",t[t.GAUGE=2]="GAUGE",t[t.SUM=3]="SUM"})(Lr||(Lr={}));var iK=function(){var t=function(e,r){return t=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])},t(e,r)};return function(e,r){if(typeof r!="function"&&r!==null)throw new TypeError("Class extends value "+String(r)+" is not a constructor or null");t(e,r);function n(){this.constructor=e}e.prototype=r===null?Object.create(r):(n.prototype=r.prototype,new n)}}();var __e=function(t){iK(e,t);function e(r){var n=t.call(this,r)||this;return Object.setPrototypeOf(n,e.prototype),n}return e}(Error);function LP(t,e){for(var r=0,n=t.length-1;n-r>1;){var o=Math.trunc((n+r)/2);t[o]<=e?r=o:n=o-1}return t[n]<=e?n:t[r]<=e?r:-1}yt();var Wn;(function(t){t[t.DROP=0]="DROP",t[t.SUM=1]="SUM",t[t.LAST_VALUE=2]="LAST_VALUE",t[t.HISTOGRAM=3]="HISTOGRAM",t[t.EXPONENTIAL_HISTOGRAM=4]="EXPONENTIAL_HISTOGRAM"})(Wn||(Wn={}));var NP=function(){function t(){this.kind=Wn.DROP}return t.prototype.createAccumulation=function(){},t.prototype.merge=function(e,r){},t.prototype.diff=function(e,r){},t.prototype.toMetricData=function(e,r,n,o){},t}();var ze;(function(t){t.COUNTER="COUNTER",t.GAUGE="GAUGE",t.HISTOGRAM="HISTOGRAM",t.UP_DOWN_COUNTER="UP_DOWN_COUNTER",t.OBSERVABLE_COUNTER="OBSERVABLE_COUNTER",t.OBSERVABLE_GAUGE="OBSERVABLE_GAUGE",t.OBSERVABLE_UP_DOWN_COUNTER="OBSERVABLE_UP_DOWN_COUNTER"})(ze||(ze={}));var aK=function(t,e){var r=typeof Symbol=="function"&&t[Symbol.iterator];if(!r)return t;var n=r.call(t),o,i=[],a;try{for(;(e===void 0||e-- >0)&&!(o=n.next()).done;)i.push(o.value)}catch(s){a={error:s}}finally{try{o&&!o.done&&(r=n.return)&&r.call(n)}finally{if(a)throw a.error}}return i};function sK(t){var e=t.map(function(){return 0});return e.push(0),{buckets:{boundaries:t,counts:e},sum:0,count:0,hasMinMax:!1,min:1/0,max:-1/0}}var $E=function(){function t(e,r,n,o){n===void 0&&(n=!0),o===void 0&&(o=sK(r)),this.startTime=e,this._boundaries=r,this._recordMinMax=n,this._current=o}return t.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 r=LP(this._boundaries,e);this._current.buckets.counts[r+1]+=1}},t.prototype.setStartTime=function(e){this.startTime=e},t.prototype.toPointValue=function(){return this._current},t}();var qE=function(){function t(e,r){this._boundaries=e,this._recordMinMax=r,this.kind=Wn.HISTOGRAM}return t.prototype.createAccumulation=function(e){return new $E(e,this._boundaries,this._recordMinMax)},t.prototype.merge=function(e,r){for(var n=e.toPointValue(),o=r.toPointValue(),i=n.buckets.counts,a=o.buckets.counts,s=new Array(i.length),c=0;c<i.length;c++)s[c]=i[c]+a[c];var l=1/0,u=-1/0;return this._recordMinMax&&(n.hasMinMax&&o.hasMinMax?(l=Math.min(n.min,o.min),u=Math.max(n.max,o.max)):n.hasMinMax?(l=n.min,u=n.max):o.hasMinMax&&(l=o.min,u=o.max)),new $E(e.startTime,n.buckets.boundaries,this._recordMinMax,{buckets:{boundaries:n.buckets.boundaries,counts:s},count:n.count+o.count,sum:n.sum+o.sum,hasMinMax:this._recordMinMax&&(n.hasMinMax||o.hasMinMax),min:l,max:u})},t.prototype.diff=function(e,r){for(var n=e.toPointValue(),o=r.toPointValue(),i=n.buckets.counts,a=o.buckets.counts,s=new Array(i.length),c=0;c<i.length;c++)s[c]=a[c]-i[c];return new $E(r.startTime,n.buckets.boundaries,this._recordMinMax,{buckets:{boundaries:n.buckets.boundaries,counts:s},count:o.count-n.count,sum:o.sum-n.sum,hasMinMax:!1,min:1/0,max:-1/0})},t.prototype.toMetricData=function(e,r,n,o){return{descriptor:e,aggregationTemporality:r,dataPointType:Lr.HISTOGRAM,dataPoints:n.map(function(i){var a=aK(i,2),s=a[0],c=a[1],l=c.toPointValue(),u=e.type===ze.GAUGE||e.type===ze.UP_DOWN_COUNTER||e.type===ze.OBSERVABLE_GAUGE||e.type===ze.OBSERVABLE_UP_DOWN_COUNTER;return{attributes:s,startTime:c.startTime,endTime:o,value:{min:l.hasMinMax?l.min:void 0,max:l.hasMinMax?l.max:void 0,sum:u?void 0:l.sum,buckets:l.buckets,count:l.count}}})}},t}();yt();var KE=function(t,e){var r=typeof Symbol=="function"&&t[Symbol.iterator];if(!r)return t;var n=r.call(t),o,i=[],a;try{for(;(e===void 0||e-- >0)&&!(o=n.next()).done;)i.push(o.value)}catch(s){a={error:s}}finally{try{o&&!o.done&&(r=n.return)&&r.call(n)}finally{if(a)throw a.error}}return i},YE=function(t,e,r){if(r||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 t.concat(i||Array.prototype.slice.call(e))},XE=function(){function t(e,r,n,o){e===void 0&&(e=new lK),r===void 0&&(r=0),n===void 0&&(n=0),o===void 0&&(o=0),this.backing=e,this.indexBase=r,this.indexStart=n,this.indexEnd=o}return Object.defineProperty(t.prototype,"offset",{get:function(){return this.indexStart},enumerable:!1,configurable:!0}),Object.defineProperty(t.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}),t.prototype.counts=function(){var e=this;return Array.from({length:this.length},function(r,n){return e.at(n)})},t.prototype.at=function(e){var r=this.indexBase-this.indexStart;return e<r&&(e+=this.backing.length),e-=r,this.backing.countAt(e)},t.prototype.incrementBucket=function(e,r){this.backing.increment(e,r)},t.prototype.decrementBucket=function(e,r){this.backing.decrement(e,r)},t.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()},t.prototype.downscale=function(e){this._rotate();for(var r=1+this.indexEnd-this.indexStart,n=1<<e,o=0,i=0,a=this.indexStart;a<=this.indexEnd;){var s=a%n;s<0&&(s+=n);for(var c=s;c<n&&o<r;c++)this._relocateBucket(i,o),o++,a++;i++}this.indexStart>>=e,this.indexEnd>>=e,this.indexBase=this.indexStart},t.prototype.clone=function(){return new t(this.backing.clone(),this.indexBase,this.indexStart,this.indexEnd)},t.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)},t.prototype._relocateBucket=function(e,r){e!==r&&this.incrementBucket(e,this.backing.emptyBucket(r))},t}();var lK=function(){function t(e){e===void 0&&(e=[0]),this._counts=e}return Object.defineProperty(t.prototype,"length",{get:function(){return this._counts.length},enumerable:!1,configurable:!0}),t.prototype.countAt=function(e){return this._counts[e]},t.prototype.growTo=function(e,r,n){var o=new Array(e).fill(0);o.splice.apply(o,YE([n,this._counts.length-r],KE(this._counts.slice(r)),!1)),o.splice.apply(o,YE([0,r],KE(this._counts.slice(0,r)),!1)),this._counts=o},t.prototype.reverse=function(e,r){for(var n=Math.floor((e+r)/2)-e,o=0;o<n;o++){var i=this._counts[e+o];this._counts[e+o]=this._counts[r-o-1],this._counts[r-o-1]=i}},t.prototype.emptyBucket=function(e){var r=this._counts[e];return this._counts[e]=0,r},t.prototype.increment=function(e,r){this._counts[e]+=r},t.prototype.decrement=function(e,r){this._counts[e]>=r?this._counts[e]-=r:this._counts[e]=0},t.prototype.clone=function(){return new t(YE([],KE(this._counts),!1))},t}();var DP=52,cK=2146435072,uK=1048575,JE=1023,gf=-JE+1,Sf=JE,Ed=Math.pow(2,-1022);function yf(t){var e=new DataView(new ArrayBuffer(8));e.setFloat64(0,t);var r=e.getUint32(0),n=(r&cK)>>20;return n-JE}function Ef(t){var e=new DataView(new ArrayBuffer(8));e.setFloat64(0,t);var r=e.getUint32(0),n=e.getUint32(4),o=(r&uK)*Math.pow(2,32);return o+n}function Td(t,e){return t===0||t===Number.POSITIVE_INFINITY||t===Number.NEGATIVE_INFINITY||Number.isNaN(t)?t:t*Math.pow(2,e)}function FP(t){return t--,t|=t>>1,t|=t>>2,t|=t>>4,t|=t>>8,t|=t>>16,t++,t}var dK=function(){var t=function(e,r){return t=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])},t(e,r)};return function(e,r){if(typeof r!="function"&&r!==null)throw new TypeError("Class extends value "+String(r)+" is not a constructor or null");t(e,r);function n(){this.constructor=e}e.prototype=r===null?Object.create(r):(n.prototype=r.prototype,new n)}}(),na=function(t){dK(e,t);function e(){return t!==null&&t.apply(this,arguments)||this}return e}(Error);var BP=function(){function t(e){this._shift=-e}return t.prototype.mapToIndex=function(e){if(e<Ed)return this._minNormalLowerBoundaryIndex();var r=yf(e),n=this._rightShift(Ef(e)-1,DP);return r+n>>this._shift},t.prototype.lowerBoundary=function(e){var r=this._minNormalLowerBoundaryIndex();if(e<r)throw new na("underflow: "+e+" is < minimum lower boundary: "+r);var n=this._maxNormalLowerBoundaryIndex();if(e>n)throw new na("overflow: "+e+" is > maximum lower boundary: "+n);return Td(1,e<<this._shift)},Object.defineProperty(t.prototype,"scale",{get:function(){return this._shift===0?0:-this._shift},enumerable:!1,configurable:!0}),t.prototype._minNormalLowerBoundaryIndex=function(){var e=gf>>this._shift;return this._shift<2&&e--,e},t.prototype._maxNormalLowerBoundaryIndex=function(){return Sf>>this._shift},t.prototype._rightShift=function(e,r){return Math.floor(e*Math.pow(2,-r))},t}();var zP=function(){function t(e){this._scale=e,this._scaleFactor=Td(Math.LOG2E,e),this._inverseFactor=Td(Math.LN2,-e)}return t.prototype.mapToIndex=function(e){if(e<=Ed)return this._minNormalLowerBoundaryIndex()-1;if(Ef(e)===0){var r=yf(e);return(r<<this._scale)-1}var n=Math.floor(Math.log(e)*this._scaleFactor),o=this._maxNormalLowerBoundaryIndex();return n>=o?o:n},t.prototype.lowerBoundary=function(e){var r=this._maxNormalLowerBoundaryIndex();if(e>=r){if(e===r)return 2*Math.exp((e-(1<<this._scale))/this._scaleFactor);throw new na("overflow: "+e+" is > maximum lower boundary: "+r)}var n=this._minNormalLowerBoundaryIndex();if(e<=n){if(e===n)return Ed;if(e===n-1)return Math.exp((e+(1<<this._scale))/this._scaleFactor)/2;throw new na("overflow: "+e+" is < minimum lower boundary: "+n)}return Math.exp(e*this._inverseFactor)},Object.defineProperty(t.prototype,"scale",{get:function(){return this._scale},enumerable:!1,configurable:!0}),t.prototype._minNormalLowerBoundaryIndex=function(){return gf<<this._scale},t.prototype._maxNormalLowerBoundaryIndex=function(){return(Sf+1<<this._scale)-1},t}();var HP=-10,GP=20,pK=Array.from({length:31},function(t,e){return e>10?new zP(e-10):new BP(e-10)});function QE(t){if(t>GP||t<HP)throw new na("expected scale >= "+HP+" && <= "+GP+", got: "+t);return pK[t+10]}var mK=function(t,e){var r=typeof Symbol=="function"&&t[Symbol.iterator];if(!r)return t;var n=r.call(t),o,i=[],a;try{for(;(e===void 0||e-- >0)&&!(o=n.next()).done;)i.push(o.value)}catch(s){a={error:s}}finally{try{o&&!o.done&&(r=n.return)&&r.call(n)}finally{if(a)throw a.error}}return i},Tf=function(){function t(e,r){this.low=e,this.high=r}return t.combine=function(e,r){return new t(Math.min(e.low,r.low),Math.max(e.high,r.high))},t}(),fK=20,hK=160,ZE=2,gK=function(){function t(e,r,n,o,i,a,s,c,l,u,d){e===void 0&&(e=e),r===void 0&&(r=hK),n===void 0&&(n=!0),o===void 0&&(o=0),i===void 0&&(i=0),a===void 0&&(a=0),s===void 0&&(s=Number.POSITIVE_INFINITY),c===void 0&&(c=Number.NEGATIVE_INFINITY),l===void 0&&(l=new XE),u===void 0&&(u=new XE),d===void 0&&(d=QE(fK)),this.startTime=e,this._maxSize=r,this._recordMinMax=n,this._sum=o,this._count=i,this._zeroCount=a,this._min=s,this._max=c,this._positive=l,this._negative=u,this._mapping=d,this._maxSize<ZE&&(ie.warn("Exponential Histogram Max Size set to "+this._maxSize+", changing to the minimum size of: "+ZE),this._maxSize=ZE)}return t.prototype.record=function(e){this.updateByIncrement(e,1)},t.prototype.setStartTime=function(e){this.startTime=e},t.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(t.prototype,"sum",{get:function(){return this._sum},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"min",{get:function(){return this._min},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"max",{get:function(){return this._max},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"count",{get:function(){return this._count},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"zeroCount",{get:function(){return this._zeroCount},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"scale",{get:function(){return this._count===this._zeroCount?0:this._mapping.scale},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"positive",{get:function(){return this._positive},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"negative",{get:function(){return this._negative},enumerable:!1,configurable:!0}),t.prototype.updateByIncrement=function(e,r){if(!Number.isNaN(e)){if(e>this._max&&(this._max=e),e<this._min&&(this._min=e),this._count+=r,e===0){this._zeroCount+=r;return}this._sum+=e*r,e>0?this._updateBuckets(this._positive,e,r):this._updateBuckets(this._negative,-e,r)}},t.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 r=this._minScale(e);this._downscale(this.scale-r),this._mergeBuckets(this.positive,e,e.positive,r),this._mergeBuckets(this.negative,e,e.negative,r)},t.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 r=this._minScale(e);this._downscale(this.scale-r),this._diffBuckets(this.positive,e,e.positive,r),this._diffBuckets(this.negative,e,e.negative,r)},t.prototype.clone=function(){return new t(this.startTime,this._maxSize,this._recordMinMax,this._sum,this._count,this._zeroCount,this._min,this._max,this.positive.clone(),this.negative.clone(),this._mapping)},t.prototype._updateBuckets=function(e,r,n){var o=this._mapping.mapToIndex(r),i=!1,a=0,s=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,s=o,a=e.indexEnd):o>e.indexEnd&&o-e.indexStart>=this._maxSize&&(i=!0,s=e.indexStart,a=o),i){var c=this._changeScale(a,s);this._downscale(c),o=this._mapping.mapToIndex(r)}this._incrementIndexBy(e,o,n)},t.prototype._incrementIndexBy=function(e,r,n){if(n!==0){if(e.length===0&&(e.indexStart=e.indexEnd=e.indexBase=r),r<e.indexStart){var o=e.indexEnd-r;o>=e.backing.length&&this._grow(e,o+1),e.indexStart=r}else if(r>e.indexEnd){var o=r-e.indexStart;o>=e.backing.length&&this._grow(e,o+1),e.indexEnd=r}var i=r-e.indexBase;i<0&&(i+=e.backing.length),e.incrementBucket(i,n)}},t.prototype._grow=function(e,r){var n=e.backing.length,o=e.indexBase-e.indexStart,i=n-o,a=FP(r);a>this._maxSize&&(a=this._maxSize);var s=a-o;e.backing.growTo(a,i,s)},t.prototype._changeScale=function(e,r){for(var n=0;e-r>=this._maxSize;)e>>=1,r>>=1,n++;return n},t.prototype._downscale=function(e){if(e!==0){if(e<0)throw new Error("impossible change of scale: "+this.scale);var r=this._mapping.scale-e;this._positive.downscale(e),this._negative.downscale(e),this._mapping=QE(r)}},t.prototype._minScale=function(e){var r=Math.min(this.scale,e.scale),n=Tf.combine(this._highLowAtScale(this.positive,this.scale,r),this._highLowAtScale(e.positive,e.scale,r)),o=Tf.combine(this._highLowAtScale(this.negative,this.scale,r),this._highLowAtScale(e.negative,e.scale,r));return Math.min(r-this._changeScale(n.high,n.low),r-this._changeScale(o.high,o.low))},t.prototype._highLowAtScale=function(e,r,n){if(e.length===0)return new Tf(0,-1);var o=r-n;return new Tf(e.indexStart>>o,e.indexEnd>>o)},t.prototype._mergeBuckets=function(e,r,n,o){for(var i=n.offset,a=r.scale-o,s=0;s<n.length;s++)this._incrementIndexBy(e,i+s>>a,n.at(s))},t.prototype._diffBuckets=function(e,r,n,o){for(var i=n.offset,a=r.scale-o,s=0;s<n.length;s++){var c=i+s>>a,l=c-e.indexBase;l<0&&(l+=e.backing.length),e.decrementBucket(l,n.at(s))}e.trim()},t}();var jP=function(){function t(e,r){this._maxSize=e,this._recordMinMax=r,this.kind=Wn.EXPONENTIAL_HISTOGRAM}return t.prototype.createAccumulation=function(e){return new gK(e,this._maxSize,this._recordMinMax)},t.prototype.merge=function(e,r){var n=r.clone();return n.merge(e),n},t.prototype.diff=function(e,r){var n=r.clone();return n.diff(e),n},t.prototype.toMetricData=function(e,r,n,o){return{descriptor:e,aggregationTemporality:r,dataPointType:Lr.EXPONENTIAL_HISTOGRAM,dataPoints:n.map(function(i){var a=mK(i,2),s=a[0],c=a[1],l=c.toPointValue(),u=e.type===ze.GAUGE||e.type===ze.UP_DOWN_COUNTER||e.type===ze.OBSERVABLE_GAUGE||e.type===ze.OBSERVABLE_UP_DOWN_COUNTER;return{attributes:s,startTime:c.startTime,endTime:o,value:{min:l.hasMinMax?l.min:void 0,max:l.hasMinMax?l.max:void 0,sum:u?void 0:l.sum,positive:{offset:l.positive.offset,bucketCounts:l.positive.bucketCounts},negative:{offset:l.negative.offset,bucketCounts:l.negative.bucketCounts},count:l.count,scale:l.scale,zeroCount:l.zeroCount}}})}},t}();var SK=function(t,e){var r=typeof Symbol=="function"&&t[Symbol.iterator];if(!r)return t;var n=r.call(t),o,i=[],a;try{for(;(e===void 0||e-- >0)&&!(o=n.next()).done;)i.push(o.value)}catch(s){a={error:s}}finally{try{o&&!o.done&&(r=n.return)&&r.call(n)}finally{if(a)throw a.error}}return i},eT=function(){function t(e,r,n){r===void 0&&(r=0),n===void 0&&(n=[0,0]),this.startTime=e,this._current=r,this.sampleTime=n}return t.prototype.record=function(e){this._current=e,this.sampleTime=IP(Date.now())},t.prototype.setStartTime=function(e){this.startTime=e},t.prototype.toPointValue=function(){return this._current},t}();var VP=function(){function t(){this.kind=Wn.LAST_VALUE}return t.prototype.createAccumulation=function(e){return new eT(e)},t.prototype.merge=function(e,r){var n=yd(r.sampleTime)>=yd(e.sampleTime)?r:e;return new eT(e.startTime,n.toPointValue(),n.sampleTime)},t.prototype.diff=function(e,r){var n=yd(r.sampleTime)>=yd(e.sampleTime)?r:e;return new eT(r.startTime,n.toPointValue(),n.sampleTime)},t.prototype.toMetricData=function(e,r,n,o){return{descriptor:e,aggregationTemporality:r,dataPointType:Lr.GAUGE,dataPoints:n.map(function(i){var a=SK(i,2),s=a[0],c=a[1];return{attributes:s,startTime:c.startTime,endTime:o,value:c.toPointValue()}})}},t}();var yK=function(t,e){var r=typeof Symbol=="function"&&t[Symbol.iterator];if(!r)return t;var n=r.call(t),o,i=[],a;try{for(;(e===void 0||e-- >0)&&!(o=n.next()).done;)i.push(o.value)}catch(s){a={error:s}}finally{try{o&&!o.done&&(r=n.return)&&r.call(n)}finally{if(a)throw a.error}}return i},bd=function(){function t(e,r,n,o){n===void 0&&(n=0),o===void 0&&(o=!1),this.startTime=e,this.monotonic=r,this._current=n,this.reset=o}return t.prototype.record=function(e){this.monotonic&&e<0||(this._current+=e)},t.prototype.setStartTime=function(e){this.startTime=e},t.prototype.toPointValue=function(){return this._current},t}();var tT=function(){function t(e){this.monotonic=e,this.kind=Wn.SUM}return t.prototype.createAccumulation=function(e){return new bd(e,this.monotonic)},t.prototype.merge=function(e,r){var n=e.toPointValue(),o=r.toPointValue();return r.reset?new bd(r.startTime,this.monotonic,o,r.reset):new bd(e.startTime,this.monotonic,n+o)},t.prototype.diff=function(e,r){var n=e.toPointValue(),o=r.toPointValue();return this.monotonic&&n>o?new bd(r.startTime,this.monotonic,o,!0):new bd(r.startTime,this.monotonic,o-n)},t.prototype.toMetricData=function(e,r,n,o){return{descriptor:e,aggregationTemporality:r,dataPointType:Lr.SUM,dataPoints:n.map(function(i){var a=yK(i,2),s=a[0],c=a[1];return{attributes:s,startTime:c.startTime,endTime:o,value:c.toPointValue()}}),isMonotonic:this.monotonic}},t}();var ms=function(){var t=function(e,r){return t=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])},t(e,r)};return function(e,r){if(typeof r!="function"&&r!==null)throw new TypeError("Class extends value "+String(r)+" is not a constructor or null");t(e,r);function n(){this.constructor=e}e.prototype=r===null?Object.create(r):(n.prototype=r.prototype,new n)}}(),jo=function(){function t(){}return t.Drop=function(){return QP},t.Sum=function(){return ZP},t.LastValue=function(){return eM},t.Histogram=function(){return tM},t.ExponentialHistogram=function(){return EK},t.Default=function(){return TK},t}();var WP=function(t){ms(e,t);function e(){return t!==null&&t.apply(this,arguments)||this}return e.prototype.createAggregator=function(r){return e.DEFAULT_INSTANCE},e.DEFAULT_INSTANCE=new NP,e}(jo);var $P=function(t){ms(e,t);function e(){return t!==null&&t.apply(this,arguments)||this}return e.prototype.createAggregator=function(r){switch(r.type){case ze.COUNTER:case ze.OBSERVABLE_COUNTER:case ze.HISTOGRAM:return e.MONOTONIC_INSTANCE;default:return e.NON_MONOTONIC_INSTANCE}},e.MONOTONIC_INSTANCE=new tT(!0),e.NON_MONOTONIC_INSTANCE=new tT(!1),e}(jo);var qP=function(t){ms(e,t);function e(){return t!==null&&t.apply(this,arguments)||this}return e.prototype.createAggregator=function(r){return e.DEFAULT_INSTANCE},e.DEFAULT_INSTANCE=new VP,e}(jo);var KP=function(t){ms(e,t);function e(){return t!==null&&t.apply(this,arguments)||this}return e.prototype.createAggregator=function(r){return e.DEFAULT_INSTANCE},e.DEFAULT_INSTANCE=new qE([0,5,10,25,50,75,100,250,500,750,1e3,2500,5e3,7500,1e4],!0),e}(jo);var YP=function(t){ms(e,t);function e(r,n){n===void 0&&(n=!0);var o=t.call(this)||this;if(o._recordMinMax=n,r==null)throw new Error("ExplicitBucketHistogramAggregation should be created with explicit boundaries, if a single bucket histogram is required, please pass an empty array");r=r.concat(),r=r.sort(function(s,c){return s-c});var i=r.lastIndexOf(-1/0),a=r.indexOf(1/0);return a===-1&&(a=void 0),o._boundaries=r.slice(i+1,a),o}return e.prototype.createAggregator=function(r){return new qE(this._boundaries,this._recordMinMax)},e}(jo);var XP=function(t){ms(e,t);function e(r,n){r===void 0&&(r=160),n===void 0&&(n=!0);var o=t.call(this)||this;return o._maxSize=r,o._recordMinMax=n,o}return e.prototype.createAggregator=function(r){return new jP(this._maxSize,this._recordMinMax)},e}(jo);var JP=function(t){ms(e,t);function e(){return t!==null&&t.apply(this,arguments)||this}return e.prototype._resolve=function(r){switch(r.type){case ze.COUNTER:case ze.UP_DOWN_COUNTER:case ze.OBSERVABLE_COUNTER:case ze.OBSERVABLE_UP_DOWN_COUNTER:return ZP;case ze.GAUGE:case ze.OBSERVABLE_GAUGE:return eM;case ze.HISTOGRAM:return r.advice.explicitBucketBoundaries?new YP(r.advice.explicitBucketBoundaries):tM}return ie.warn("Unable to recognize instrument type: "+r.type),QP},e.prototype.createAggregator=function(r){return this._resolve(r).createAggregator(r)},e}(jo);var QP=new WP,ZP=new $P,eM=new qP,tM=new KP,EK=new XP,TK=new JP;yt();function bf(){return"unknown_service:"+process.argv0}var oa=function(){return oa=Object.assign||function(t){for(var e,r=1,n=arguments.length;r<n;r++){e=arguments[r];for(var o in e)Object.prototype.hasOwnProperty.call(e,o)&&(t[o]=e[o])}return t},oa.apply(this,arguments)},bK=function(t,e,r,n){function o(i){return i instanceof r?i:new r(function(a){a(i)})}return new(r||(r=Promise))(function(i,a){function s(u){try{l(n.next(u))}catch(d){a(d)}}function c(u){try{l(n.throw(u))}catch(d){a(d)}}function l(u){u.done?i(u.value):o(u.value).then(s,c)}l((n=n.apply(t,e||[])).next())})},vK=function(t,e){var r={label:0,sent:function(){if(i[0]&1)throw i[1];return i[1]},trys:[],ops:[]},n,o,i,a;return a={next:s(0),throw:s(1),return:s(2)},typeof Symbol=="function"&&(a[Symbol.iterator]=function(){return this}),a;function s(l){return function(u){return c([l,u])}}function c(l){if(n)throw new TypeError("Generator is already executing.");for(;r;)try{if(n=1,o&&(i=l[0]&2?o.return:l[0]?o.throw||((i=o.return)&&i.call(o),0):o.next)&&!(i=i.call(o,l[1])).done)return i;switch(o=0,i&&(l=[l[0]&2,i.value]),l[0]){case 0:case 1:i=l;break;case 4:return r.label++,{value:l[1],done:!1};case 5:r.label++,o=l[1],l=[0];continue;case 7:l=r.ops.pop(),r.trys.pop();continue;default:if(i=r.trys,!(i=i.length>0&&i[i.length-1])&&(l[0]===6||l[0]===2)){r=0;continue}if(l[0]===3&&(!i||l[1]>i[0]&&l[1]<i[3])){r.label=l[1];break}if(l[0]===6&&r.label<i[1]){r.label=i[1],i=l;break}if(i&&r.label<i[2]){r.label=i[2],r.ops.push(l);break}i[2]&&r.ops.pop(),r.trys.pop();continue}l=e.call(t,r)}catch(u){l=[6,u],o=0}finally{n=i=0}if(l[0]&5)throw l[1];return{value:l[0]?l[1]:void 0,done:!0}}},AK=function(t,e){var r=typeof Symbol=="function"&&t[Symbol.iterator];if(!r)return t;var n=r.call(t),o,i=[],a;try{for(;(e===void 0||e-- >0)&&!(o=n.next()).done;)i.push(o.value)}catch(s){a={error:s}}finally{try{o&&!o.done&&(r=n.return)&&r.call(n)}finally{if(a)throw a.error}}return i},rT=function(){function t(e,r){var n=this,o;this._attributes=e,this.asyncAttributesPending=r!=null,this._syncAttributes=(o=this._attributes)!==null&&o!==void 0?o:{},this._asyncAttributesPromise=r?.then(function(i){return n._attributes=Object.assign({},n._attributes,i),n.asyncAttributesPending=!1,i},function(i){return ie.debug("a resource's async attributes promise rejected: %s",i),n.asyncAttributesPending=!1,{}})}return t.empty=function(){return t.EMPTY},t.default=function(){var e;return new t((e={},e[ff]=bf(),e[gd]=hf[gd],e[hd]=hf[hd],e[Sd]=hf[Sd],e))},Object.defineProperty(t.prototype,"attributes",{get:function(){var e;return this.asyncAttributesPending&&ie.error("Accessing resource attributes before async attributes settled"),(e=this._attributes)!==null&&e!==void 0?e:{}},enumerable:!1,configurable:!0}),t.prototype.waitForAsyncAttributes=function(){return bK(this,void 0,void 0,function(){return vK(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]}})})},t.prototype.merge=function(e){var r=this,n;if(!e)return this;var o=oa(oa({},this._syncAttributes),(n=e._syncAttributes)!==null&&n!==void 0?n:e.attributes);if(!this._asyncAttributesPromise&&!e._asyncAttributesPromise)return new t(o);var i=Promise.all([this._asyncAttributesPromise,e._asyncAttributesPromise]).then(function(a){var s,c=AK(a,2),l=c[0],u=c[1];return oa(oa(oa(oa({},r._syncAttributes),l),(s=e._syncAttributes)!==null&&s!==void 0?s:e.attributes),u)});return new t(o,i)},t.EMPTY=new t({}),t}();var fs;(function(t){t[t.DELTA=0]="DELTA",t[t.CUMULATIVE=1]="CUMULATIVE",t[t.LOWMEMORY=2]="LOWMEMORY"})(fs||(fs={}));yt();var CK=function(t,e,r,n){function o(i){return i instanceof r?i:new r(function(a){a(i)})}return new(r||(r=Promise))(function(i,a){function s(u){try{l(n.next(u))}catch(d){a(d)}}function c(u){try{l(n.throw(u))}catch(d){a(d)}}function l(u){u.done?i(u.value):o(u.value).then(s,c)}l((n=n.apply(t,e||[])).next())})},RK=function(t,e){var r={label:0,sent:function(){if(i[0]&1)throw i[1];return i[1]},trys:[],ops:[]},n,o,i,a;return a={next:s(0),throw:s(1),return:s(2)},typeof Symbol=="function"&&(a[Symbol.iterator]=function(){return this}),a;function s(l){return function(u){return c([l,u])}}function c(l){if(n)throw new TypeError("Generator is already executing.");for(;r;)try{if(n=1,o&&(i=l[0]&2?o.return:l[0]?o.throw||((i=o.return)&&i.call(o),0):o.next)&&!(i=i.call(o,l[1])).done)return i;switch(o=0,i&&(l=[l[0]&2,i.value]),l[0]){case 0:case 1:i=l;break;case 4:return r.label++,{value:l[1],done:!1};case 5:r.label++,o=l[1],l=[0];continue;case 7:l=r.ops.pop(),r.trys.pop();continue;default:if(i=r.trys,!(i=i.length>0&&i[i.length-1])&&(l[0]===6||l[0]===2)){r=0;continue}if(l[0]===3&&(!i||l[1]>i[0]&&l[1]<i[3])){r.label=l[1];break}if(l[0]===6&&r.label<i[1]){r.label=i[1],i=l;break}if(i&&r.label<i[2]){r.label=i[2],r.ops.push(l);break}i[2]&&r.ops.pop(),r.trys.pop();continue}l=e.call(t,r)}catch(u){l=[6,u],o=0}finally{n=i=0}if(l[0]&5)throw l[1];return{value:l[0]?l[1]:void 0,done:!0}}},nT=function(){return Vn.CUMULATIVE},rM=function(t){switch(t){case ze.COUNTER:case ze.OBSERVABLE_COUNTER:case ze.GAUGE:case ze.HISTOGRAM:case ze.OBSERVABLE_GAUGE:return Vn.DELTA;case ze.UP_DOWN_COUNTER:case ze.OBSERVABLE_UP_DOWN_COUNTER:return Vn.CUMULATIVE}},nM=function(t){switch(t){case ze.COUNTER:case ze.HISTOGRAM:return Vn.DELTA;case ze.GAUGE:case ze.UP_DOWN_COUNTER:case ze.OBSERVABLE_UP_DOWN_COUNTER:case ze.OBSERVABLE_COUNTER:case ze.OBSERVABLE_GAUGE:return Vn.CUMULATIVE}};function wK(){var t=Sr(),e=t.OTEL_EXPORTER_OTLP_METRICS_TEMPORALITY_PREFERENCE.trim().toLowerCase();return e==="cumulative"?nT:e==="delta"?rM:e==="lowmemory"?nM:(ie.warn("OTEL_EXPORTER_OTLP_METRICS_TEMPORALITY_PREFERENCE is set to '"+t.OTEL_EXPORTER_OTLP_METRICS_TEMPORALITY_PREFERENCE+"', but only 'cumulative' and 'delta' are allowed. Using default ('cumulative') instead."),nT)}function xK(t){return t!=null?t===fs.DELTA?rM:t===fs.LOWMEMORY?nM:nT:wK()}function _K(t){return t?.aggregationPreference?t.aggregationPreference:function(e){return jo.Default()}}var oM=function(){function t(e,r){this._otlpExporter=e,this._aggregationSelector=_K(r),this._aggregationTemporalitySelector=xK(r?.temporalityPreference)}return t.prototype.export=function(e,r){this._otlpExporter.export([e],r)},t.prototype.shutdown=function(){return CK(this,void 0,void 0,function(){return RK(this,function(e){switch(e.label){case 0:return[4,this._otlpExporter.shutdown()];case 1:return e.sent(),[2]}})})},t.prototype.forceFlush=function(){return Promise.resolve()},t.prototype.selectAggregation=function(e){return this._aggregationSelector(e)},t.prototype.selectAggregationTemporality=function(e){return this._aggregationTemporalitySelector(e)},t}();yt();yt();var IK=function(t,e){var r=typeof Symbol=="function"&&t[Symbol.iterator];if(!r)return t;var n=r.call(t),o,i=[],a;try{for(;(e===void 0||e-- >0)&&!(o=n.next()).done;)i.push(o.value)}catch(s){a={error:s}}finally{try{o&&!o.done&&(r=n.return)&&r.call(n)}finally{if(a)throw a.error}}return i},iM=1e4,aM=5,sM=1e3,lM=5e3,cM=1.5;function vd(t){t===void 0&&(t={});var e={};return Object.entries(t).forEach(function(r){var n=IK(r,2),o=n[0],i=n[1];typeof i<"u"?e[o]=String(i):ie.warn('Header "'+o+'" has invalid value ('+i+") and will be ignored")}),e}function oT(t,e){return t.endsWith("/")||(t=t+"/"),t+e}function iT(t){try{var e=new URL(t);return e.pathname===""&&(e.pathname=e.pathname+"/"),e.toString()}catch{return ie.warn("Could not parse export URL: '"+t+"'"),t}}function aT(t){return typeof t=="number"?t<=0?sT(t,iM):t:PK()}function PK(){var t,e=Number((t=Sr().OTEL_EXPORTER_OTLP_TRACES_TIMEOUT)!==null&&t!==void 0?t:Sr().OTEL_EXPORTER_OTLP_TIMEOUT);return e<=0?sT(e,iM):e}function sT(t,e){return ie.warn("Timeout must be greater than 0",t),e}function uM(t){var e=[429,502,503,504];return e.includes(t)}function dM(t){if(t==null)return-1;var e=Number.parseInt(t,10);if(Number.isInteger(e))return e>0?e*1e3:-1;var r=new Date(t).getTime()-Date.now();return r>=0?r:0}var pM=function(){function t(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 OP(this._shutdown,this),this._concurrencyLimit=typeof e.concurrencyLimit=="number"?e.concurrencyLimit:30,this.timeoutMillis=aT(e.timeoutMillis),this.onInit(e)}return t.prototype.export=function(e,r){if(this._shutdownOnce.isCalled){r({code:ps.FAILED,error:new Error("Exporter has been shutdown")});return}if(this._sendingPromises.length>=this._concurrencyLimit){r({code:ps.FAILED,error:new Error("Concurrent export limit reached")});return}this._export(e).then(function(){r({code:ps.SUCCESS})}).catch(function(n){r({code:ps.FAILED,error:n})})},t.prototype._export=function(e){var r=this;return new Promise(function(n,o){try{ie.debug("items to be sent",e),r.send(e,n,o)}catch(i){o(i)}})},t.prototype.shutdown=function(){return this._shutdownOnce.call()},t.prototype.forceFlush=function(){return Promise.all(this._sendingPromises).then(function(){})},t.prototype._shutdown=function(){return ie.debug("shutdown started"),this.onShutdown(),this.forceFlush()},t}();yt();import*as lT from"url";import*as Af from"http";import*as Cf from"https";import*as mM from"zlib";import{Readable as OK}from"stream";var ia;(function(t){t.NONE="none",t.GZIP="gzip"})(ia||(ia={}));var MK=function(){var t=function(e,r){return t=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])},t(e,r)};return function(e,r){if(typeof r!="function"&&r!==null)throw new TypeError("Class extends value "+String(r)+" is not a constructor or null");t(e,r);function n(){this.constructor=e}e.prototype=r===null?Object.create(r):(n.prototype=r.prototype,new n)}}(),ec=function(t){MK(e,t);function e(r,n,o){var i=t.call(this,r)||this;return i.name="OTLPExporterError",i.data=o,i.code=n,i}return e}(Error);var vf=function(){return vf=Object.assign||function(t){for(var e,r=1,n=arguments.length;r<n;r++){e=arguments[r];for(var o in e)Object.prototype.hasOwnProperty.call(e,o)&&(t[o]=e[o])}return t},vf.apply(this,arguments)};function cT(t,e,r,n,o){var i=t.timeoutMillis,a=new lT.URL(t.url),s=Number(process.versions.node.split(".")[0]),c,l,u=!1,d=setTimeout(function(){if(clearTimeout(c),u=!0,l.destroyed){var h=new ec("Request Timeout");o(h)}else s>=14?l.destroy():l.abort()},i),p={hostname:a.hostname,port:a.port,path:a.pathname,method:"POST",headers:vf({"Content-Type":r},t.headers),agent:t.agent},m=a.protocol==="http:"?Af.request:Cf.request,f=function(h,S){switch(h===void 0&&(h=aM),S===void 0&&(S=sM),l=m(p,function(E){var y="";E.on("data",function(b){return y+=b}),E.on("aborted",function(){if(u){var b=new ec("Request Timeout");o(b)}}),E.on("end",function(){if(u===!1)if(E.statusCode&&E.statusCode<299)ie.debug("statusCode: "+E.statusCode,y),n(),clearTimeout(d),clearTimeout(c);else if(E.statusCode&&uM(E.statusCode)&&h>0){var b=void 0;S=cM*S,E.headers["retry-after"]?b=dM(E.headers["retry-after"]):b=Math.round(Math.random()*(lM-S)+S),c=setTimeout(function(){f(h-1,S)},b)}else{var C=new ec(E.statusMessage,E.statusCode,y);o(C),clearTimeout(d),clearTimeout(c)}})}),l.on("error",function(E){if(u){var y=new ec("Request Timeout",E.code);o(y)}else o(E);clearTimeout(d),clearTimeout(c)}),l.on("abort",function(){if(u){var E=new ec("Request Timeout");o(E)}clearTimeout(d),clearTimeout(c)}),t.compression){case ia.GZIP:{l.setHeader("Content-Encoding","gzip");var g=LK(e);g.on("error",o).pipe(mM.createGzip()).on("error",o).pipe(l);break}default:l.end(Buffer.from(e));break}};f()}function LK(t){var e=new OK;return e.push(t),e.push(null),e}function uT(t){if(t.httpAgentOptions&&t.keepAlive===!1){ie.warn("httpAgentOptions is used only when keepAlive is true");return}if(!(t.keepAlive===!1||!t.url))try{var e=new lT.URL(t.url),r=e.protocol==="http:"?Af.Agent:Cf.Agent;return new r(vf({keepAlive:!0},t.httpAgentOptions))}catch(n){ie.error("collector exporter failed to create http agent. err: "+n.message);return}}function dT(t){if(t)return t;var e=Sr().OTEL_EXPORTER_OTLP_TRACES_COMPRESSION||Sr().OTEL_EXPORTER_OTLP_COMPRESSION;return e===ia.GZIP?ia.GZIP:ia.NONE}yt();var NK=function(){var t=function(e,r){return t=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])},t(e,r)};return function(e,r){if(typeof r!="function"&&r!==null)throw new TypeError("Class extends value "+String(r)+" is not a constructor or null");t(e,r);function n(){this.constructor=e}e.prototype=r===null?Object.create(r):(n.prototype=r.prototype,new n)}}(),Rf=function(t){NK(e,t);function e(r,n,o){r===void 0&&(r={});var i=t.call(this,r)||this;return i.DEFAULT_HEADERS={},i._contentType=o,r.metadata&&ie.warn("Metadata cannot be set when using http"),i.headers=Object.assign(i.DEFAULT_HEADERS,vd(r.headers),Ql.parseKeyPairsIntoRecord(Sr().OTEL_EXPORTER_OTLP_HEADERS)),i.agent=uT(r),i.compression=dT(r.compression),i._serializer=n,i}return e.prototype.onInit=function(r){},e.prototype.send=function(r,n,o){var i=this;if(this._shutdownOnce.isCalled){ie.debug("Shutdown already started. Cannot send objects");return}var a=new Promise(function(c,l){var u;cT(i,(u=i._serializer.serializeRequest(r))!==null&&u!==void 0?u:new Uint8Array,i._contentType,c,l)}).then(n,o);this._sendingPromises.push(a);var s=function(){var c=i._sendingPromises.indexOf(a);i._sendingPromises.splice(c,1)};a.then(s,s)},e.prototype.onShutdown=function(){},e}(pM);function hM(t){var e=BigInt(1e9);return BigInt(t[0])*e+BigInt(t[1])}function DK(t){var e=Number(BigInt.asUintN(32,t)),r=Number(BigInt.asUintN(32,t>>BigInt(32)));return{low:e,high:r}}function gM(t){var e=hM(t);return DK(e)}function kK(t){var e=hM(t);return e.toString()}var FK=typeof BigInt<"u"?kK:PP;function fM(t){return t}function SM(t){if(t!==void 0)return mf(t)}var UK={encodeHrTime:gM,encodeSpanContext:mf,encodeOptionalSpanContext:SM};function yM(t){var e,r;if(t===void 0)return UK;var n=(e=t.useLongBits)!==null&&e!==void 0?e:!0,o=(r=t.useHex)!==null&&r!==void 0?r:!1;return{encodeHrTime:n?gM:FK,encodeSpanContext:o?fM:mf,encodeOptionalSpanContext:o?fM:SM}}var BK=function(t,e){var r=typeof Symbol=="function"&&t[Symbol.iterator];if(!r)return t;var n=r.call(t),o,i=[],a;try{for(;(e===void 0||e-- >0)&&!(o=n.next()).done;)i.push(o.value)}catch(s){a={error:s}}finally{try{o&&!o.done&&(r=n.return)&&r.call(n)}finally{if(a)throw a.error}}return i};function EM(t){return{name:t.name,version:t.version}}function tc(t){return Object.keys(t).map(function(e){return TM(e,t[e])})}function TM(t,e){return{key:t,value:bM(e)}}function bM(t){var e=typeof t;return e==="string"?{stringValue:t}:e==="number"?Number.isInteger(t)?{intValue:t}:{doubleValue:t}:e==="boolean"?{boolValue:t}:t instanceof Uint8Array?{bytesValue:t}:Array.isArray(t)?{arrayValue:{values:t.map(bM)}}:e==="object"&&t!=null?{kvlistValue:{values:Object.entries(t).map(function(r){var n=BK(r,2),o=n[0],i=n[1];return TM(o,i)})}}:{}}function vM(t){return{attributes:tc(t.attributes),droppedAttributesCount:0}}yt();function CM(t,e){var r=yM(e);return{resource:vM(t.resource),schemaUrl:void 0,scopeMetrics:zK(t.scopeMetrics,r)}}function zK(t,e){return Array.from(t.map(function(r){return{scope:EM(r.scope),metrics:r.metrics.map(function(n){return HK(n,e)}),schemaUrl:r.scope.schemaUrl}}))}function HK(t,e){var r={name:t.descriptor.name,description:t.descriptor.description,unit:t.descriptor.unit},n=WK(t.aggregationTemporality);switch(t.dataPointType){case Lr.SUM:r.sum={aggregationTemporality:n,isMonotonic:t.isMonotonic,dataPoints:AM(t,e)};break;case Lr.GAUGE:r.gauge={dataPoints:AM(t,e)};break;case Lr.HISTOGRAM:r.histogram={aggregationTemporality:n,dataPoints:jK(t,e)};break;case Lr.EXPONENTIAL_HISTOGRAM:r.exponentialHistogram={aggregationTemporality:n,dataPoints:VK(t,e)};break}return r}function GK(t,e,r){var n={attributes:tc(t.attributes),startTimeUnixNano:r.encodeHrTime(t.startTime),timeUnixNano:r.encodeHrTime(t.endTime)};switch(e){case En.INT:n.asInt=t.value;break;case En.DOUBLE:n.asDouble=t.value;break}return n}function AM(t,e){return t.dataPoints.map(function(r){return GK(r,t.descriptor.valueType,e)})}function jK(t,e){return t.dataPoints.map(function(r){var n=r.value;return{attributes:tc(r.attributes),bucketCounts:n.buckets.counts,explicitBounds:n.buckets.boundaries,count:n.count,sum:n.sum,min:n.min,max:n.max,startTimeUnixNano:e.encodeHrTime(r.startTime),timeUnixNano:e.encodeHrTime(r.endTime)}})}function VK(t,e){return t.dataPoints.map(function(r){var n=r.value;return{attributes:tc(r.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(r.startTime),timeUnixNano:e.encodeHrTime(r.endTime)}})}function WK(t){switch(t){case Vn.DELTA:return 1;case Vn.CUMULATIVE:return 2}}function RM(t,e){return{resourceMetrics:t.map(function(r){return CM(r,e)})}}var pT={serializeRequest:function(t){var e=RM(t,{useLongBits:!1}),r=new TextEncoder;return r.encode(JSON.stringify(e))},deserializeResponse:function(t){var e=new TextDecoder;return JSON.parse(e.decode(t))}};var wM="0.52.1";var xM=function(){var t=function(e,r){return t=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])},t(e,r)};return function(e,r){if(typeof r!="function"&&r!==null)throw new TypeError("Class extends value "+String(r)+" is not a constructor or null");t(e,r);function n(){this.constructor=e}e.prototype=r===null?Object.create(r):(n.prototype=r.prototype,new n)}}(),rc=function(){return rc=Object.assign||function(t){for(var e,r=1,n=arguments.length;r<n;r++){e=arguments[r];for(var o in e)Object.prototype.hasOwnProperty.call(e,o)&&(t[o]=e[o])}return t},rc.apply(this,arguments)},_M="v1/metrics",$K="http://localhost:4318/"+_M,qK={"User-Agent":"OTel-OTLP-Exporter-JavaScript/"+wM},KK=function(t){xM(e,t);function e(r){var n=t.call(this,r,pT,"application/json")||this;return n.headers=rc(rc(rc(rc({},n.headers),qK),Ql.parseKeyPairsIntoRecord(Sr().OTEL_EXPORTER_OTLP_METRICS_HEADERS)),vd(r?.headers)),n}return e.prototype.getDefaultUrl=function(r){return typeof r.url=="string"?r.url:Sr().OTEL_EXPORTER_OTLP_METRICS_ENDPOINT.length>0?iT(Sr().OTEL_EXPORTER_OTLP_METRICS_ENDPOINT):Sr().OTEL_EXPORTER_OTLP_ENDPOINT.length>0?oT(Sr().OTEL_EXPORTER_OTLP_ENDPOINT,_M):$K},e}(Rf),IM=function(t){xM(e,t);function e(r){return t.call(this,new KK(r),r)||this}return e}(oM);var nc;(function(t){t[t.DELTA=0]="DELTA",t[t.CUMULATIVE=1]="CUMULATIVE"})(nc||(nc={}));var Vo;(function(t){t[t.HISTOGRAM=0]="HISTOGRAM",t[t.EXPONENTIAL_HISTOGRAM=1]="EXPONENTIAL_HISTOGRAM",t[t.GAUGE=2]="GAUGE",t[t.SUM=3]="SUM"})(Vo||(Vo={}));yt();var YK=function(){var t=function(e,r){return t=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])},t(e,r)};return function(e,r){if(typeof r!="function"&&r!==null)throw new TypeError("Class extends value "+String(r)+" is not a constructor or null");t(e,r);function n(){this.constructor=e}e.prototype=r===null?Object.create(r):(n.prototype=r.prototype,new n)}}(),PM=function(t,e,r,n){function o(i){return i instanceof r?i:new r(function(a){a(i)})}return new(r||(r=Promise))(function(i,a){function s(u){try{l(n.next(u))}catch(d){a(d)}}function c(u){try{l(n.throw(u))}catch(d){a(d)}}function l(u){u.done?i(u.value):o(u.value).then(s,c)}l((n=n.apply(t,e||[])).next())})},MM=function(t,e){var r={label:0,sent:function(){if(i[0]&1)throw i[1];return i[1]},trys:[],ops:[]},n,o,i,a;return a={next:s(0),throw:s(1),return:s(2)},typeof Symbol=="function"&&(a[Symbol.iterator]=function(){return this}),a;function s(l){return function(u){return c([l,u])}}function c(l){if(n)throw new TypeError("Generator is already executing.");for(;r;)try{if(n=1,o&&(i=l[0]&2?o.return:l[0]?o.throw||((i=o.return)&&i.call(o),0):o.next)&&!(i=i.call(o,l[1])).done)return i;switch(o=0,i&&(l=[l[0]&2,i.value]),l[0]){case 0:case 1:i=l;break;case 4:return r.label++,{value:l[1],done:!1};case 5:r.label++,o=l[1],l=[0];continue;case 7:l=r.ops.pop(),r.trys.pop();continue;default:if(i=r.trys,!(i=i.length>0&&i[i.length-1])&&(l[0]===6||l[0]===2)){r=0;continue}if(l[0]===3&&(!i||l[1]>i[0]&&l[1]<i[3])){r.label=l[1];break}if(l[0]===6&&r.label<i[1]){r.label=i[1],i=l;break}if(i&&r.label<i[2]){r.label=i[2],r.ops.push(l);break}i[2]&&r.ops.pop(),r.trys.pop();continue}l=e.call(t,r)}catch(u){l=[6,u],o=0}finally{n=i=0}if(l[0]&5)throw l[1];return{value:l[0]?l[1]:void 0,done:!0}}},XK=function(t,e){var r=typeof Symbol=="function"&&t[Symbol.iterator];if(!r)return t;var n=r.call(t),o,i=[],a;try{for(;(e===void 0||e-- >0)&&!(o=n.next()).done;)i.push(o.value)}catch(s){a={error:s}}finally{try{o&&!o.done&&(r=n.return)&&r.call(n)}finally{if(a)throw a.error}}return i},JK=function(t,e,r){if(r||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 t.concat(i||Array.prototype.slice.call(e))},QK=function(t){var e=typeof Symbol=="function"&&Symbol.iterator,r=e&&t[e],n=0;if(r)return r.call(t);if(t&&typeof t.length=="number")return{next:function(){return t&&n>=t.length&&(t=void 0),{value:t&&t[n++],done:!t}}};throw new TypeError(e?"Object is not iterable.":"Symbol.iterator is not defined.")};function OM(t){return t!=null}function wf(t){var e=Object.keys(t);return e.length===0?"":(e=e.sort(),JSON.stringify(e.map(function(r){return[r,t[r]]})))}function LM(t){var e,r;return t.name+":"+((e=t.version)!==null&&e!==void 0?e:"")+":"+((r=t.schemaUrl)!==null&&r!==void 0?r:"")}var mT=function(t){YK(e,t);function e(r){var n=t.call(this,r)||this;return Object.setPrototypeOf(n,e.prototype),n}return e}(Error);function aa(t,e){var r,n=new Promise(function(i,a){r=setTimeout(function(){a(new mT("Operation timed out."))},e)});return Promise.race([t,n]).then(function(o){return clearTimeout(r),o},function(o){throw clearTimeout(r),o})}function NM(t){return PM(this,void 0,void 0,function(){var e=this;return MM(this,function(r){return[2,Promise.all(t.map(function(n){return PM(e,void 0,void 0,function(){var o,i;return MM(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 DM(t){return t.status==="rejected"}function fT(t,e){var r=[];return t.forEach(function(n){r.push.apply(r,JK([],XK(e(n)),!1))}),r}function kM(t,e){var r,n;if(t.size!==e.size)return!1;try{for(var o=QK(t),i=o.next();!i.done;i=o.next()){var a=i.value;if(!e.has(a))return!1}}catch(s){r={error:s}}finally{try{i&&!i.done&&(n=o.return)&&n.call(o)}finally{if(r)throw r.error}}return!0}function FM(t,e){for(var r=0,n=t.length-1,o=t.length;n>=r;){var i=r+Math.trunc((n-r)/2);t[i]<e?r=i+1:(o=i,n=i-1)}return o}function UM(t,e){return t.toLowerCase()===e.toLowerCase()}yt();var $n;(function(t){t[t.DROP=0]="DROP",t[t.SUM=1]="SUM",t[t.LAST_VALUE=2]="LAST_VALUE",t[t.HISTOGRAM=3]="HISTOGRAM",t[t.EXPONENTIAL_HISTOGRAM=4]="EXPONENTIAL_HISTOGRAM"})($n||($n={}));var hT=function(){function t(){this.kind=$n.DROP}return t.prototype.createAccumulation=function(){},t.prototype.merge=function(e,r){},t.prototype.diff=function(e,r){},t.prototype.toMetricData=function(e,r,n,o){},t}();yt();var Xe;(function(t){t.COUNTER="COUNTER",t.GAUGE="GAUGE",t.HISTOGRAM="HISTOGRAM",t.UP_DOWN_COUNTER="UP_DOWN_COUNTER",t.OBSERVABLE_COUNTER="OBSERVABLE_COUNTER",t.OBSERVABLE_GAUGE="OBSERVABLE_GAUGE",t.OBSERVABLE_UP_DOWN_COUNTER="OBSERVABLE_UP_DOWN_COUNTER"})(Xe||(Xe={}));function Wo(t,e,r){var n,o,i,a;return e2(t)||ie.warn('Invalid metric name: "'+t+'". The metric name should be a ASCII string with a length no greater than 255 characters.'),{name:t,type:e,description:(n=r?.description)!==null&&n!==void 0?n:"",unit:(o=r?.unit)!==null&&o!==void 0?o:"",valueType:(i=r?.valueType)!==null&&i!==void 0?i:En.DOUBLE,advice:(a=r?.advice)!==null&&a!==void 0?a:{}}}function BM(t,e){var r,n;return{name:(r=t.name)!==null&&r!==void 0?r:e.name,description:(n=t.description)!==null&&n!==void 0?n:e.description,type:e.type,unit:e.unit,valueType:e.valueType,advice:e.advice}}function zM(t,e){return UM(t.name,e.name)&&t.unit===e.unit&&t.type===e.type&&t.valueType===e.valueType}var ZK=/^[a-z][a-z0-9_.\-/]{0,254}$/i;function e2(t){return t.match(ZK)!=null}var t2=function(t,e){var r=typeof Symbol=="function"&&t[Symbol.iterator];if(!r)return t;var n=r.call(t),o,i=[],a;try{for(;(e===void 0||e-- >0)&&!(o=n.next()).done;)i.push(o.value)}catch(s){a={error:s}}finally{try{o&&!o.done&&(r=n.return)&&r.call(n)}finally{if(a)throw a.error}}return i};function r2(t){var e=t.map(function(){return 0});return e.push(0),{buckets:{boundaries:t,counts:e},sum:0,count:0,hasMinMax:!1,min:1/0,max:-1/0}}var xf=function(){function t(e,r,n,o){n===void 0&&(n=!0),o===void 0&&(o=r2(r)),this.startTime=e,this._boundaries=r,this._recordMinMax=n,this._current=o}return t.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 r=FM(this._boundaries,e);this._current.buckets.counts[r]+=1}},t.prototype.setStartTime=function(e){this.startTime=e},t.prototype.toPointValue=function(){return this._current},t}();var _f=function(){function t(e,r){this._boundaries=e,this._recordMinMax=r,this.kind=$n.HISTOGRAM}return t.prototype.createAccumulation=function(e){return new xf(e,this._boundaries,this._recordMinMax)},t.prototype.merge=function(e,r){for(var n=e.toPointValue(),o=r.toPointValue(),i=n.buckets.counts,a=o.buckets.counts,s=new Array(i.length),c=0;c<i.length;c++)s[c]=i[c]+a[c];var l=1/0,u=-1/0;return this._recordMinMax&&(n.hasMinMax&&o.hasMinMax?(l=Math.min(n.min,o.min),u=Math.max(n.max,o.max)):n.hasMinMax?(l=n.min,u=n.max):o.hasMinMax&&(l=o.min,u=o.max)),new xf(e.startTime,n.buckets.boundaries,this._recordMinMax,{buckets:{boundaries:n.buckets.boundaries,counts:s},count:n.count+o.count,sum:n.sum+o.sum,hasMinMax:this._recordMinMax&&(n.hasMinMax||o.hasMinMax),min:l,max:u})},t.prototype.diff=function(e,r){for(var n=e.toPointValue(),o=r.toPointValue(),i=n.buckets.counts,a=o.buckets.counts,s=new Array(i.length),c=0;c<i.length;c++)s[c]=a[c]-i[c];return new xf(r.startTime,n.buckets.boundaries,this._recordMinMax,{buckets:{boundaries:n.buckets.boundaries,counts:s},count:o.count-n.count,sum:o.sum-n.sum,hasMinMax:!1,min:1/0,max:-1/0})},t.prototype.toMetricData=function(e,r,n,o){return{descriptor:e,aggregationTemporality:r,dataPointType:Vo.HISTOGRAM,dataPoints:n.map(function(i){var a=t2(i,2),s=a[0],c=a[1],l=c.toPointValue(),u=e.type===Xe.GAUGE||e.type===Xe.UP_DOWN_COUNTER||e.type===Xe.OBSERVABLE_GAUGE||e.type===Xe.OBSERVABLE_UP_DOWN_COUNTER;return{attributes:s,startTime:c.startTime,endTime:o,value:{min:l.hasMinMax?l.min:void 0,max:l.hasMinMax?l.max:void 0,sum:u?void 0:l.sum,buckets:l.buckets,count:l.count}}})}},t}();yt();var gT=function(t,e){var r=typeof Symbol=="function"&&t[Symbol.iterator];if(!r)return t;var n=r.call(t),o,i=[],a;try{for(;(e===void 0||e-- >0)&&!(o=n.next()).done;)i.push(o.value)}catch(s){a={error:s}}finally{try{o&&!o.done&&(r=n.return)&&r.call(n)}finally{if(a)throw a.error}}return i},ST=function(t,e,r){if(r||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 t.concat(i||Array.prototype.slice.call(e))},yT=function(){function t(e,r,n,o){e===void 0&&(e=new n2),r===void 0&&(r=0),n===void 0&&(n=0),o===void 0&&(o=0),this.backing=e,this.indexBase=r,this.indexStart=n,this.indexEnd=o}return Object.defineProperty(t.prototype,"offset",{get:function(){return this.indexStart},enumerable:!1,configurable:!0}),Object.defineProperty(t.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}),t.prototype.counts=function(){var e=this;return Array.from({length:this.length},function(r,n){return e.at(n)})},t.prototype.at=function(e){var r=this.indexBase-this.indexStart;return e<r&&(e+=this.backing.length),e-=r,this.backing.countAt(e)},t.prototype.incrementBucket=function(e,r){this.backing.increment(e,r)},t.prototype.decrementBucket=function(e,r){this.backing.decrement(e,r)},t.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()},t.prototype.downscale=function(e){this._rotate();for(var r=1+this.indexEnd-this.indexStart,n=1<<e,o=0,i=0,a=this.indexStart;a<=this.indexEnd;){var s=a%n;s<0&&(s+=n);for(var c=s;c<n&&o<r;c++)this._relocateBucket(i,o),o++,a++;i++}this.indexStart>>=e,this.indexEnd>>=e,this.indexBase=this.indexStart},t.prototype.clone=function(){return new t(this.backing.clone(),this.indexBase,this.indexStart,this.indexEnd)},t.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)},t.prototype._relocateBucket=function(e,r){e!==r&&this.incrementBucket(e,this.backing.emptyBucket(r))},t}();var n2=function(){function t(e){e===void 0&&(e=[0]),this._counts=e}return Object.defineProperty(t.prototype,"length",{get:function(){return this._counts.length},enumerable:!1,configurable:!0}),t.prototype.countAt=function(e){return this._counts[e]},t.prototype.growTo=function(e,r,n){var o=new Array(e).fill(0);o.splice.apply(o,ST([n,this._counts.length-r],gT(this._counts.slice(r)),!1)),o.splice.apply(o,ST([0,r],gT(this._counts.slice(0,r)),!1)),this._counts=o},t.prototype.reverse=function(e,r){for(var n=Math.floor((e+r)/2)-e,o=0;o<n;o++){var i=this._counts[e+o];this._counts[e+o]=this._counts[r-o-1],this._counts[r-o-1]=i}},t.prototype.emptyBucket=function(e){var r=this._counts[e];return this._counts[e]=0,r},t.prototype.increment=function(e,r){this._counts[e]+=r},t.prototype.decrement=function(e,r){this._counts[e]>=r?this._counts[e]-=r:this._counts[e]=0},t.prototype.clone=function(){return new t(ST([],gT(this._counts),!1))},t}();var HM=52,o2=2146435072,i2=1048575,ET=1023,If=-ET+1,Pf=ET,Ad=Math.pow(2,-1022);function Mf(t){var e=new DataView(new ArrayBuffer(8));e.setFloat64(0,t);var r=e.getUint32(0),n=(r&o2)>>20;return n-ET}function Of(t){var e=new DataView(new ArrayBuffer(8));e.setFloat64(0,t);var r=e.getUint32(0),n=e.getUint32(4),o=(r&i2)*Math.pow(2,32);return o+n}function Cd(t,e){return t===0||t===Number.POSITIVE_INFINITY||t===Number.NEGATIVE_INFINITY||Number.isNaN(t)?t:t*Math.pow(2,e)}function jM(t){return t--,t|=t>>1,t|=t>>2,t|=t>>4,t|=t>>8,t|=t>>16,t++,t}var a2=function(){var t=function(e,r){return t=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])},t(e,r)};return function(e,r){if(typeof r!="function"&&r!==null)throw new TypeError("Class extends value "+String(r)+" is not a constructor or null");t(e,r);function n(){this.constructor=e}e.prototype=r===null?Object.create(r):(n.prototype=r.prototype,new n)}}(),sa=function(t){a2(e,t);function e(){return t!==null&&t.apply(this,arguments)||this}return e}(Error);var WM=function(){function t(e){this._shift=-e}return t.prototype.mapToIndex=function(e){if(e<Ad)return this._minNormalLowerBoundaryIndex();var r=Mf(e),n=this._rightShift(Of(e)-1,HM);return r+n>>this._shift},t.prototype.lowerBoundary=function(e){var r=this._minNormalLowerBoundaryIndex();if(e<r)throw new sa("underflow: "+e+" is < minimum lower boundary: "+r);var n=this._maxNormalLowerBoundaryIndex();if(e>n)throw new sa("overflow: "+e+" is > maximum lower boundary: "+n);return Cd(1,e<<this._shift)},Object.defineProperty(t.prototype,"scale",{get:function(){return this._shift===0?0:-this._shift},enumerable:!1,configurable:!0}),t.prototype._minNormalLowerBoundaryIndex=function(){var e=If>>this._shift;return this._shift<2&&e--,e},t.prototype._maxNormalLowerBoundaryIndex=function(){return Pf>>this._shift},t.prototype._rightShift=function(e,r){return Math.floor(e*Math.pow(2,-r))},t}();var $M=function(){function t(e){this._scale=e,this._scaleFactor=Cd(Math.LOG2E,e),this._inverseFactor=Cd(Math.LN2,-e)}return t.prototype.mapToIndex=function(e){if(e<=Ad)return this._minNormalLowerBoundaryIndex()-1;if(Of(e)===0){var r=Mf(e);return(r<<this._scale)-1}var n=Math.floor(Math.log(e)*this._scaleFactor),o=this._maxNormalLowerBoundaryIndex();return n>=o?o:n},t.prototype.lowerBoundary=function(e){var r=this._maxNormalLowerBoundaryIndex();if(e>=r){if(e===r)return 2*Math.exp((e-(1<<this._scale))/this._scaleFactor);throw new sa("overflow: "+e+" is > maximum lower boundary: "+r)}var n=this._minNormalLowerBoundaryIndex();if(e<=n){if(e===n)return Ad;if(e===n-1)return Math.exp((e+(1<<this._scale))/this._scaleFactor)/2;throw new sa("overflow: "+e+" is < minimum lower boundary: "+n)}return Math.exp(e*this._inverseFactor)},Object.defineProperty(t.prototype,"scale",{get:function(){return this._scale},enumerable:!1,configurable:!0}),t.prototype._minNormalLowerBoundaryIndex=function(){return If<<this._scale},t.prototype._maxNormalLowerBoundaryIndex=function(){return(Pf+1<<this._scale)-1},t}();var qM=-10,KM=20,s2=Array.from({length:31},function(t,e){return e>10?new $M(e-10):new WM(e-10)});function TT(t){if(t>KM||t<qM)throw new sa("expected scale >= "+qM+" && <= "+KM+", got: "+t);return s2[t+10]}var l2=function(t,e){var r=typeof Symbol=="function"&&t[Symbol.iterator];if(!r)return t;var n=r.call(t),o,i=[],a;try{for(;(e===void 0||e-- >0)&&!(o=n.next()).done;)i.push(o.value)}catch(s){a={error:s}}finally{try{o&&!o.done&&(r=n.return)&&r.call(n)}finally{if(a)throw a.error}}return i},Lf=function(){function t(e,r){this.low=e,this.high=r}return t.combine=function(e,r){return new t(Math.min(e.low,r.low),Math.max(e.high,r.high))},t}(),c2=20,u2=160,bT=2,YM=function(){function t(e,r,n,o,i,a,s,c,l,u,d){e===void 0&&(e=e),r===void 0&&(r=u2),n===void 0&&(n=!0),o===void 0&&(o=0),i===void 0&&(i=0),a===void 0&&(a=0),s===void 0&&(s=Number.POSITIVE_INFINITY),c===void 0&&(c=Number.NEGATIVE_INFINITY),l===void 0&&(l=new yT),u===void 0&&(u=new yT),d===void 0&&(d=TT(c2)),this.startTime=e,this._maxSize=r,this._recordMinMax=n,this._sum=o,this._count=i,this._zeroCount=a,this._min=s,this._max=c,this._positive=l,this._negative=u,this._mapping=d,this._maxSize<bT&&(ie.warn("Exponential Histogram Max Size set to "+this._maxSize+", changing to the minimum size of: "+bT),this._maxSize=bT)}return t.prototype.record=function(e){this.updateByIncrement(e,1)},t.prototype.setStartTime=function(e){this.startTime=e},t.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(t.prototype,"sum",{get:function(){return this._sum},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"min",{get:function(){return this._min},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"max",{get:function(){return this._max},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"count",{get:function(){return this._count},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"zeroCount",{get:function(){return this._zeroCount},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"scale",{get:function(){return this._count===this._zeroCount?0:this._mapping.scale},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"positive",{get:function(){return this._positive},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"negative",{get:function(){return this._negative},enumerable:!1,configurable:!0}),t.prototype.updateByIncrement=function(e,r){if(!Number.isNaN(e)){if(e>this._max&&(this._max=e),e<this._min&&(this._min=e),this._count+=r,e===0){this._zeroCount+=r;return}this._sum+=e*r,e>0?this._updateBuckets(this._positive,e,r):this._updateBuckets(this._negative,-e,r)}},t.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 r=this._minScale(e);this._downscale(this.scale-r),this._mergeBuckets(this.positive,e,e.positive,r),this._mergeBuckets(this.negative,e,e.negative,r)},t.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 r=this._minScale(e);this._downscale(this.scale-r),this._diffBuckets(this.positive,e,e.positive,r),this._diffBuckets(this.negative,e,e.negative,r)},t.prototype.clone=function(){return new t(this.startTime,this._maxSize,this._recordMinMax,this._sum,this._count,this._zeroCount,this._min,this._max,this.positive.clone(),this.negative.clone(),this._mapping)},t.prototype._updateBuckets=function(e,r,n){var o=this._mapping.mapToIndex(r),i=!1,a=0,s=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,s=o,a=e.indexEnd):o>e.indexEnd&&o-e.indexStart>=this._maxSize&&(i=!0,s=e.indexStart,a=o),i){var c=this._changeScale(a,s);this._downscale(c),o=this._mapping.mapToIndex(r)}this._incrementIndexBy(e,o,n)},t.prototype._incrementIndexBy=function(e,r,n){if(n!==0){if(e.length===0&&(e.indexStart=e.indexEnd=e.indexBase=r),r<e.indexStart){var o=e.indexEnd-r;o>=e.backing.length&&this._grow(e,o+1),e.indexStart=r}else if(r>e.indexEnd){var o=r-e.indexStart;o>=e.backing.length&&this._grow(e,o+1),e.indexEnd=r}var i=r-e.indexBase;i<0&&(i+=e.backing.length),e.incrementBucket(i,n)}},t.prototype._grow=function(e,r){var n=e.backing.length,o=e.indexBase-e.indexStart,i=n-o,a=jM(r);a>this._maxSize&&(a=this._maxSize);var s=a-o;e.backing.growTo(a,i,s)},t.prototype._changeScale=function(e,r){for(var n=0;e-r>=this._maxSize;)e>>=1,r>>=1,n++;return n},t.prototype._downscale=function(e){if(e!==0){if(e<0)throw new Error("impossible change of scale: "+this.scale);var r=this._mapping.scale-e;this._positive.downscale(e),this._negative.downscale(e),this._mapping=TT(r)}},t.prototype._minScale=function(e){var r=Math.min(this.scale,e.scale),n=Lf.combine(this._highLowAtScale(this.positive,this.scale,r),this._highLowAtScale(e.positive,e.scale,r)),o=Lf.combine(this._highLowAtScale(this.negative,this.scale,r),this._highLowAtScale(e.negative,e.scale,r));return Math.min(r-this._changeScale(n.high,n.low),r-this._changeScale(o.high,o.low))},t.prototype._highLowAtScale=function(e,r,n){if(e.length===0)return new Lf(0,-1);var o=r-n;return new Lf(e.indexStart>>o,e.indexEnd>>o)},t.prototype._mergeBuckets=function(e,r,n,o){for(var i=n.offset,a=r.scale-o,s=0;s<n.length;s++)this._incrementIndexBy(e,i+s>>a,n.at(s))},t.prototype._diffBuckets=function(e,r,n,o){for(var i=n.offset,a=r.scale-o,s=0;s<n.length;s++){var c=i+s>>a,l=c-e.indexBase;l<0&&(l+=e.backing.length),e.decrementBucket(l,n.at(s))}e.trim()},t}();var vT=function(){function t(e,r){this._maxSize=e,this._recordMinMax=r,this.kind=$n.EXPONENTIAL_HISTOGRAM}return t.prototype.createAccumulation=function(e){return new YM(e,this._maxSize,this._recordMinMax)},t.prototype.merge=function(e,r){var n=r.clone();return n.merge(e),n},t.prototype.diff=function(e,r){var n=r.clone();return n.diff(e),n},t.prototype.toMetricData=function(e,r,n,o){return{descriptor:e,aggregationTemporality:r,dataPointType:Vo.EXPONENTIAL_HISTOGRAM,dataPoints:n.map(function(i){var a=l2(i,2),s=a[0],c=a[1],l=c.toPointValue(),u=e.type===Xe.GAUGE||e.type===Xe.UP_DOWN_COUNTER||e.type===Xe.OBSERVABLE_GAUGE||e.type===Xe.OBSERVABLE_UP_DOWN_COUNTER;return{attributes:s,startTime:c.startTime,endTime:o,value:{min:l.hasMinMax?l.min:void 0,max:l.hasMinMax?l.max:void 0,sum:u?void 0:l.sum,positive:{offset:l.positive.offset,bucketCounts:l.positive.bucketCounts},negative:{offset:l.negative.offset,bucketCounts:l.negative.bucketCounts},count:l.count,scale:l.scale,zeroCount:l.zeroCount}}})}},t}();yt();var d2=LE("OpenTelemetry SDK Context Key SUPPRESS_TRACING");function XM(t){return t.setValue(d2,!0)}yt();function JM(){return function(t){ie.error(p2(t))}}function p2(t){return typeof t=="string"?t:JSON.stringify(m2(t))}function m2(t){for(var e={},r=t;r!==null;)Object.getOwnPropertyNames(r).forEach(function(n){if(!e[n]){var o=r[n];o&&(e[n]=String(o))}}),r=Object.getPrototypeOf(r);return e}var f2=JM();function Nf(t){try{f2(t)}catch{}}var QM="1.30.1";var h2="process.runtime.name";var g2="service.name";var S2="telemetry.sdk.name",y2="telemetry.sdk.language",E2="telemetry.sdk.version";var ZM=h2;var eO=g2;var Rd=S2,wd=y2,xd=E2;var T2="nodejs";var tO=T2;var oc,hs=(oc={},oc[Rd]="opentelemetry",oc[ZM]="node",oc[wd]=tO,oc[xd]=QM,oc);function _d(t){t.unref()}var x2=9,_2=6,I2=Math.pow(10,_2),OMe=Math.pow(10,x2);function gs(t){var e=t/1e3,r=Math.trunc(e),n=Math.round(t%1e3*I2);return[r,n]}function ic(t){return t[0]*1e6+t[1]/1e3}var Id;(function(t){t[t.SUCCESS=0]="SUCCESS",t[t.FAILED=1]="FAILED"})(Id||(Id={}));yt();function rO(t,e){return new Promise(function(r){Jl.with(XM(Jl.active()),function(){t.export(e,function(n){r(n)})})})}var nO={_export:rO};var P2=function(t,e){var r=typeof Symbol=="function"&&t[Symbol.iterator];if(!r)return t;var n=r.call(t),o,i=[],a;try{for(;(e===void 0||e-- >0)&&!(o=n.next()).done;)i.push(o.value)}catch(s){a={error:s}}finally{try{o&&!o.done&&(r=n.return)&&r.call(n)}finally{if(a)throw a.error}}return i},Df=function(){function t(e,r,n){r===void 0&&(r=0),n===void 0&&(n=[0,0]),this.startTime=e,this._current=r,this.sampleTime=n}return t.prototype.record=function(e){this._current=e,this.sampleTime=gs(Date.now())},t.prototype.setStartTime=function(e){this.startTime=e},t.prototype.toPointValue=function(){return this._current},t}();var AT=function(){function t(){this.kind=$n.LAST_VALUE}return t.prototype.createAccumulation=function(e){return new Df(e)},t.prototype.merge=function(e,r){var n=ic(r.sampleTime)>=ic(e.sampleTime)?r:e;return new Df(e.startTime,n.toPointValue(),n.sampleTime)},t.prototype.diff=function(e,r){var n=ic(r.sampleTime)>=ic(e.sampleTime)?r:e;return new Df(r.startTime,n.toPointValue(),n.sampleTime)},t.prototype.toMetricData=function(e,r,n,o){return{descriptor:e,aggregationTemporality:r,dataPointType:Vo.GAUGE,dataPoints:n.map(function(i){var a=P2(i,2),s=a[0],c=a[1];return{attributes:s,startTime:c.startTime,endTime:o,value:c.toPointValue()}})}},t}();var M2=function(t,e){var r=typeof Symbol=="function"&&t[Symbol.iterator];if(!r)return t;var n=r.call(t),o,i=[],a;try{for(;(e===void 0||e-- >0)&&!(o=n.next()).done;)i.push(o.value)}catch(s){a={error:s}}finally{try{o&&!o.done&&(r=n.return)&&r.call(n)}finally{if(a)throw a.error}}return i},ac=function(){function t(e,r,n,o){n===void 0&&(n=0),o===void 0&&(o=!1),this.startTime=e,this.monotonic=r,this._current=n,this.reset=o}return t.prototype.record=function(e){this.monotonic&&e<0||(this._current+=e)},t.prototype.setStartTime=function(e){this.startTime=e},t.prototype.toPointValue=function(){return this._current},t}();var kf=function(){function t(e){this.monotonic=e,this.kind=$n.SUM}return t.prototype.createAccumulation=function(e){return new ac(e,this.monotonic)},t.prototype.merge=function(e,r){var n=e.toPointValue(),o=r.toPointValue();return r.reset?new ac(r.startTime,this.monotonic,o,r.reset):new ac(e.startTime,this.monotonic,n+o)},t.prototype.diff=function(e,r){var n=e.toPointValue(),o=r.toPointValue();return this.monotonic&&n>o?new ac(r.startTime,this.monotonic,o,!0):new ac(r.startTime,this.monotonic,o-n)},t.prototype.toMetricData=function(e,r,n,o){return{descriptor:e,aggregationTemporality:r,dataPointType:Vo.SUM,dataPoints:n.map(function(i){var a=M2(i,2),s=a[0],c=a[1];return{attributes:s,startTime:c.startTime,endTime:o,value:c.toPointValue()}}),isMonotonic:this.monotonic}},t}();var Ss=function(){var t=function(e,r){return t=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])},t(e,r)};return function(e,r){if(typeof r!="function"&&r!==null)throw new TypeError("Class extends value "+String(r)+" is not a constructor or null");t(e,r);function n(){this.constructor=e}e.prototype=r===null?Object.create(r):(n.prototype=r.prototype,new n)}}(),qn=function(){function t(){}return t.Drop=function(){return uO},t.Sum=function(){return dO},t.LastValue=function(){return pO},t.Histogram=function(){return mO},t.ExponentialHistogram=function(){return O2},t.Default=function(){return L2},t}();var oO=function(t){Ss(e,t);function e(){return t!==null&&t.apply(this,arguments)||this}return e.prototype.createAggregator=function(r){return e.DEFAULT_INSTANCE},e.DEFAULT_INSTANCE=new hT,e}(qn);var iO=function(t){Ss(e,t);function e(){return t!==null&&t.apply(this,arguments)||this}return e.prototype.createAggregator=function(r){switch(r.type){case Xe.COUNTER:case Xe.OBSERVABLE_COUNTER:case Xe.HISTOGRAM:return e.MONOTONIC_INSTANCE;default:return e.NON_MONOTONIC_INSTANCE}},e.MONOTONIC_INSTANCE=new kf(!0),e.NON_MONOTONIC_INSTANCE=new kf(!1),e}(qn);var aO=function(t){Ss(e,t);function e(){return t!==null&&t.apply(this,arguments)||this}return e.prototype.createAggregator=function(r){return e.DEFAULT_INSTANCE},e.DEFAULT_INSTANCE=new AT,e}(qn);var sO=function(t){Ss(e,t);function e(){return t!==null&&t.apply(this,arguments)||this}return e.prototype.createAggregator=function(r){return e.DEFAULT_INSTANCE},e.DEFAULT_INSTANCE=new _f([0,5,10,25,50,75,100,250,500,750,1e3,2500,5e3,7500,1e4],!0),e}(qn);var Pd=function(t){Ss(e,t);function e(r,n){n===void 0&&(n=!0);var o=t.call(this)||this;if(o._recordMinMax=n,r==null)throw new Error("ExplicitBucketHistogramAggregation should be created with explicit boundaries, if a single bucket histogram is required, please pass an empty array");r=r.concat(),r=r.sort(function(s,c){return s-c});var i=r.lastIndexOf(-1/0),a=r.indexOf(1/0);return a===-1&&(a=void 0),o._boundaries=r.slice(i+1,a),o}return e.prototype.createAggregator=function(r){return new _f(this._boundaries,this._recordMinMax)},e}(qn);var lO=function(t){Ss(e,t);function e(r,n){r===void 0&&(r=160),n===void 0&&(n=!0);var o=t.call(this)||this;return o._maxSize=r,o._recordMinMax=n,o}return e.prototype.createAggregator=function(r){return new vT(this._maxSize,this._recordMinMax)},e}(qn);var cO=function(t){Ss(e,t);function e(){return t!==null&&t.apply(this,arguments)||this}return e.prototype._resolve=function(r){switch(r.type){case Xe.COUNTER:case Xe.UP_DOWN_COUNTER:case Xe.OBSERVABLE_COUNTER:case Xe.OBSERVABLE_UP_DOWN_COUNTER:return dO;case Xe.GAUGE:case Xe.OBSERVABLE_GAUGE:return pO;case Xe.HISTOGRAM:return r.advice.explicitBucketBoundaries?new Pd(r.advice.explicitBucketBoundaries):mO}return ie.warn("Unable to recognize instrument type: "+r.type),uO},e.prototype.createAggregator=function(r){return this._resolve(r).createAggregator(r)},e}(qn);var uO=new oO,dO=new iO,pO=new aO,mO=new sO,O2=new lO,L2=new cO;var fO=function(t){return qn.Default()},hO=function(t){return nc.CUMULATIVE};var CT=function(t,e,r,n){function o(i){return i instanceof r?i:new r(function(a){a(i)})}return new(r||(r=Promise))(function(i,a){function s(u){try{l(n.next(u))}catch(d){a(d)}}function c(u){try{l(n.throw(u))}catch(d){a(d)}}function l(u){u.done?i(u.value):o(u.value).then(s,c)}l((n=n.apply(t,e||[])).next())})},RT=function(t,e){var r={label:0,sent:function(){if(i[0]&1)throw i[1];return i[1]},trys:[],ops:[]},n,o,i,a;return a={next:s(0),throw:s(1),return:s(2)},typeof Symbol=="function"&&(a[Symbol.iterator]=function(){return this}),a;function s(l){return function(u){return c([l,u])}}function c(l){if(n)throw new TypeError("Generator is already executing.");for(;r;)try{if(n=1,o&&(i=l[0]&2?o.return:l[0]?o.throw||((i=o.return)&&i.call(o),0):o.next)&&!(i=i.call(o,l[1])).done)return i;switch(o=0,i&&(l=[l[0]&2,i.value]),l[0]){case 0:case 1:i=l;break;case 4:return r.label++,{value:l[1],done:!1};case 5:r.label++,o=l[1],l=[0];continue;case 7:l=r.ops.pop(),r.trys.pop();continue;default:if(i=r.trys,!(i=i.length>0&&i[i.length-1])&&(l[0]===6||l[0]===2)){r=0;continue}if(l[0]===3&&(!i||l[1]>i[0]&&l[1]<i[3])){r.label=l[1];break}if(l[0]===6&&r.label<i[1]){r.label=i[1],i=l;break}if(i&&r.label<i[2]){r.label=i[2],r.ops.push(l);break}i[2]&&r.ops.pop(),r.trys.pop();continue}l=e.call(t,r)}catch(u){l=[6,u],o=0}finally{n=i=0}if(l[0]&5)throw l[1];return{value:l[0]?l[1]:void 0,done:!0}}},gO=function(t,e){var r=typeof Symbol=="function"&&t[Symbol.iterator];if(!r)return t;var n=r.call(t),o,i=[],a;try{for(;(e===void 0||e-- >0)&&!(o=n.next()).done;)i.push(o.value)}catch(s){a={error:s}}finally{try{o&&!o.done&&(r=n.return)&&r.call(n)}finally{if(a)throw a.error}}return i},N2=function(t,e,r){if(r||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 t.concat(i||Array.prototype.slice.call(e))},SO=function(){function t(e){var r,n,o;this._shutdown=!1,this._aggregationSelector=(r=e?.aggregationSelector)!==null&&r!==void 0?r:fO,this._aggregationTemporalitySelector=(n=e?.aggregationTemporalitySelector)!==null&&n!==void 0?n:hO,this._metricProducers=(o=e?.metricProducers)!==null&&o!==void 0?o:[],this._cardinalitySelector=e?.cardinalitySelector}return t.prototype.setMetricProducer=function(e){if(this._sdkMetricProducer)throw new Error("MetricReader can not be bound to a MeterProvider again.");this._sdkMetricProducer=e,this.onInitialized()},t.prototype.selectAggregation=function(e){return this._aggregationSelector(e)},t.prototype.selectAggregationTemporality=function(e){return this._aggregationTemporalitySelector(e)},t.prototype.selectCardinalityLimit=function(e){return this._cardinalitySelector?this._cardinalitySelector(e):2e3},t.prototype.onInitialized=function(){},t.prototype.collect=function(e){return CT(this,void 0,void 0,function(){var r,n,o,i,a,s;return RT(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(N2([this._sdkMetricProducer.collect({timeoutMillis:e?.timeoutMillis})],gO(this._metricProducers.map(function(l){return l.collect({timeoutMillis:e?.timeoutMillis})})),!1))];case 1:return r=gO.apply(void 0,[c.sent()]),n=r[0],o=r.slice(1),i=n.errors.concat(fT(o,function(l){return l.errors})),a=n.resourceMetrics.resource,s=n.resourceMetrics.scopeMetrics.concat(fT(o,function(l){return l.resourceMetrics.scopeMetrics})),[2,{resourceMetrics:{resource:a,scopeMetrics:s},errors:i}]}})})},t.prototype.shutdown=function(e){return CT(this,void 0,void 0,function(){return RT(this,function(r){switch(r.label){case 0:return this._shutdown?(ie.error("Cannot call shutdown twice."),[2]):e?.timeoutMillis!=null?[3,2]:[4,this.onShutdown()];case 1:return r.sent(),[3,4];case 2:return[4,aa(this.onShutdown(),e.timeoutMillis)];case 3:r.sent(),r.label=4;case 4:return this._shutdown=!0,[2]}})})},t.prototype.forceFlush=function(e){return CT(this,void 0,void 0,function(){return RT(this,function(r){switch(r.label){case 0:return this._shutdown?(ie.warn("Cannot forceFlush on already shutdown MetricReader."),[2]):e?.timeoutMillis!=null?[3,2]:[4,this.onForceFlush()];case 1:return r.sent(),[2];case 2:return[4,aa(this.onForceFlush(),e.timeoutMillis)];case 3:return r.sent(),[2]}})})},t}();yt();var D2=function(){var t=function(e,r){return t=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])},t(e,r)};return function(e,r){if(typeof r!="function"&&r!==null)throw new TypeError("Class extends value "+String(r)+" is not a constructor or null");t(e,r);function n(){this.constructor=e}e.prototype=r===null?Object.create(r):(n.prototype=r.prototype,new n)}}(),Ff=function(t,e,r,n){function o(i){return i instanceof r?i:new r(function(a){a(i)})}return new(r||(r=Promise))(function(i,a){function s(u){try{l(n.next(u))}catch(d){a(d)}}function c(u){try{l(n.throw(u))}catch(d){a(d)}}function l(u){u.done?i(u.value):o(u.value).then(s,c)}l((n=n.apply(t,e||[])).next())})},Uf=function(t,e){var r={label:0,sent:function(){if(i[0]&1)throw i[1];return i[1]},trys:[],ops:[]},n,o,i,a;return a={next:s(0),throw:s(1),return:s(2)},typeof Symbol=="function"&&(a[Symbol.iterator]=function(){return this}),a;function s(l){return function(u){return c([l,u])}}function c(l){if(n)throw new TypeError("Generator is already executing.");for(;r;)try{if(n=1,o&&(i=l[0]&2?o.return:l[0]?o.throw||((i=o.return)&&i.call(o),0):o.next)&&!(i=i.call(o,l[1])).done)return i;switch(o=0,i&&(l=[l[0]&2,i.value]),l[0]){case 0:case 1:i=l;break;case 4:return r.label++,{value:l[1],done:!1};case 5:r.label++,o=l[1],l=[0];continue;case 7:l=r.ops.pop(),r.trys.pop();continue;default:if(i=r.trys,!(i=i.length>0&&i[i.length-1])&&(l[0]===6||l[0]===2)){r=0;continue}if(l[0]===3&&(!i||l[1]>i[0]&&l[1]<i[3])){r.label=l[1];break}if(l[0]===6&&r.label<i[1]){r.label=i[1],i=l;break}if(i&&r.label<i[2]){r.label=i[2],r.ops.push(l);break}i[2]&&r.ops.pop(),r.trys.pop();continue}l=e.call(t,r)}catch(u){l=[6,u],o=0}finally{n=i=0}if(l[0]&5)throw l[1];return{value:l[0]?l[1]:void 0,done:!0}}},k2=function(t,e){var r=typeof Symbol=="function"&&t[Symbol.iterator];if(!r)return t;var n=r.call(t),o,i=[],a;try{for(;(e===void 0||e-- >0)&&!(o=n.next()).done;)i.push(o.value)}catch(s){a={error:s}}finally{try{o&&!o.done&&(r=n.return)&&r.call(n)}finally{if(a)throw a.error}}return i},F2=function(t,e,r){if(r||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 t.concat(i||Array.prototype.slice.call(e))},wT=function(t){D2(e,t);function e(r){var n,o,i,a,s=t.call(this,{aggregationSelector:(n=r.exporter.selectAggregation)===null||n===void 0?void 0:n.bind(r.exporter),aggregationTemporalitySelector:(o=r.exporter.selectAggregationTemporality)===null||o===void 0?void 0:o.bind(r.exporter),metricProducers:r.metricProducers})||this;if(r.exportIntervalMillis!==void 0&&r.exportIntervalMillis<=0)throw Error("exportIntervalMillis must be greater than 0");if(r.exportTimeoutMillis!==void 0&&r.exportTimeoutMillis<=0)throw Error("exportTimeoutMillis must be greater than 0");if(r.exportTimeoutMillis!==void 0&&r.exportIntervalMillis!==void 0&&r.exportIntervalMillis<r.exportTimeoutMillis)throw Error("exportIntervalMillis must be greater than or equal to exportTimeoutMillis");return s._exportInterval=(i=r.exportIntervalMillis)!==null&&i!==void 0?i:6e4,s._exportTimeout=(a=r.exportTimeoutMillis)!==null&&a!==void 0?a:3e4,s._exporter=r.exporter,s}return e.prototype._runOnce=function(){return Ff(this,void 0,void 0,function(){var r;return Uf(this,function(n){switch(n.label){case 0:return n.trys.push([0,2,,3]),[4,aa(this._doRun(),this._exportTimeout)];case 1:return n.sent(),[3,3];case 2:return r=n.sent(),r instanceof mT?(ie.error("Export took longer than %s milliseconds and timed out.",this._exportTimeout),[2]):(Nf(r),[3,3]);case 3:return[2]}})})},e.prototype._doRun=function(){var r,n;return Ff(this,void 0,void 0,function(){var o,i,a,s,c,l;return Uf(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&&(l=ie).error.apply(l,F2(["PeriodicExportingMetricReader: metrics collection errors"],k2(a),!1)),!i.resource.asyncAttributesPending)return[3,5];u.label=2;case 2:return u.trys.push([2,4,,5]),[4,(n=(r=i.resource).waitForAsyncAttributes)===null||n===void 0?void 0:n.call(r)];case 3:return u.sent(),[3,5];case 4:return s=u.sent(),ie.debug("Error while resolving async portion of resource: ",s),Nf(s),[3,5];case 5:return i.scopeMetrics.length===0?[2]:[4,nO._export(this._exporter,i)];case 6:if(c=u.sent(),c.code!==Id.SUCCESS)throw new Error("PeriodicExportingMetricReader: metrics export failed (error "+c.error+")");return[2]}})})},e.prototype.onInitialized=function(){var r=this;this._interval=setInterval(function(){r._runOnce()},this._exportInterval),_d(this._interval)},e.prototype.onForceFlush=function(){return Ff(this,void 0,void 0,function(){return Uf(this,function(r){switch(r.label){case 0:return[4,this._runOnce()];case 1:return r.sent(),[4,this._exporter.forceFlush()];case 2:return r.sent(),[2]}})})},e.prototype.onShutdown=function(){return Ff(this,void 0,void 0,function(){return Uf(this,function(r){switch(r.label){case 0:return this._interval&&clearInterval(this._interval),[4,this.onForceFlush()];case 1:return r.sent(),[4,this._exporter.shutdown()];case 2:return r.sent(),[2]}})})},e}(SO);yt();yt();function Bf(){return"unknown_service:"+process.argv0}var la=function(){return la=Object.assign||function(t){for(var e,r=1,n=arguments.length;r<n;r++){e=arguments[r];for(var o in e)Object.prototype.hasOwnProperty.call(e,o)&&(t[o]=e[o])}return t},la.apply(this,arguments)},U2=function(t,e,r,n){function o(i){return i instanceof r?i:new r(function(a){a(i)})}return new(r||(r=Promise))(function(i,a){function s(u){try{l(n.next(u))}catch(d){a(d)}}function c(u){try{l(n.throw(u))}catch(d){a(d)}}function l(u){u.done?i(u.value):o(u.value).then(s,c)}l((n=n.apply(t,e||[])).next())})},B2=function(t,e){var r={label:0,sent:function(){if(i[0]&1)throw i[1];return i[1]},trys:[],ops:[]},n,o,i,a;return a={next:s(0),throw:s(1),return:s(2)},typeof Symbol=="function"&&(a[Symbol.iterator]=function(){return this}),a;function s(l){return function(u){return c([l,u])}}function c(l){if(n)throw new TypeError("Generator is already executing.");for(;r;)try{if(n=1,o&&(i=l[0]&2?o.return:l[0]?o.throw||((i=o.return)&&i.call(o),0):o.next)&&!(i=i.call(o,l[1])).done)return i;switch(o=0,i&&(l=[l[0]&2,i.value]),l[0]){case 0:case 1:i=l;break;case 4:return r.label++,{value:l[1],done:!1};case 5:r.label++,o=l[1],l=[0];continue;case 7:l=r.ops.pop(),r.trys.pop();continue;default:if(i=r.trys,!(i=i.length>0&&i[i.length-1])&&(l[0]===6||l[0]===2)){r=0;continue}if(l[0]===3&&(!i||l[1]>i[0]&&l[1]<i[3])){r.label=l[1];break}if(l[0]===6&&r.label<i[1]){r.label=i[1],i=l;break}if(i&&r.label<i[2]){r.label=i[2],r.ops.push(l);break}i[2]&&r.ops.pop(),r.trys.pop();continue}l=e.call(t,r)}catch(u){l=[6,u],o=0}finally{n=i=0}if(l[0]&5)throw l[1];return{value:l[0]?l[1]:void 0,done:!0}}},z2=function(t,e){var r=typeof Symbol=="function"&&t[Symbol.iterator];if(!r)return t;var n=r.call(t),o,i=[],a;try{for(;(e===void 0||e-- >0)&&!(o=n.next()).done;)i.push(o.value)}catch(s){a={error:s}}finally{try{o&&!o.done&&(r=n.return)&&r.call(n)}finally{if(a)throw a.error}}return i},zf=function(){function t(e,r){var n=this,o;this._attributes=e,this.asyncAttributesPending=r!=null,this._syncAttributes=(o=this._attributes)!==null&&o!==void 0?o:{},this._asyncAttributesPromise=r?.then(function(i){return n._attributes=Object.assign({},n._attributes,i),n.asyncAttributesPending=!1,i},function(i){return ie.debug("a resource's async attributes promise rejected: %s",i),n.asyncAttributesPending=!1,{}})}return t.empty=function(){return t.EMPTY},t.default=function(){var e;return new t((e={},e[eO]=Bf(),e[wd]=hs[wd],e[Rd]=hs[Rd],e[xd]=hs[xd],e))},Object.defineProperty(t.prototype,"attributes",{get:function(){var e;return this.asyncAttributesPending&&ie.error("Accessing resource attributes before async attributes settled"),(e=this._attributes)!==null&&e!==void 0?e:{}},enumerable:!1,configurable:!0}),t.prototype.waitForAsyncAttributes=function(){return U2(this,void 0,void 0,function(){return B2(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]}})})},t.prototype.merge=function(e){var r=this,n;if(!e)return this;var o=la(la({},this._syncAttributes),(n=e._syncAttributes)!==null&&n!==void 0?n:e.attributes);if(!this._asyncAttributesPromise&&!e._asyncAttributesPromise)return new t(o);var i=Promise.all([this._asyncAttributesPromise,e._asyncAttributesPromise]).then(function(a){var s,c=z2(a,2),l=c[0],u=c[1];return la(la(la(la({},r._syncAttributes),l),(s=e._syncAttributes)!==null&&s!==void 0?s:e.attributes),u)});return new t(o,i)},t.EMPTY=new t({}),t}();var yO=function(){function t(){this._registeredViews=[]}return t.prototype.addView=function(e){this._registeredViews.push(e)},t.prototype.findViews=function(e,r){var n=this,o=this._registeredViews.filter(function(i){return n._matchInstrument(i.instrumentSelector,e)&&n._matchMeter(i.meterSelector,r)});return o},t.prototype._matchInstrument=function(e,r){return(e.getType()===void 0||r.type===e.getType())&&e.getNameFilter().match(r.name)&&e.getUnitFilter().match(r.unit)},t.prototype._matchMeter=function(e,r){return e.getNameFilter().match(r.name)&&(r.version===void 0||e.getVersionFilter().match(r.version))&&(r.schemaUrl===void 0||e.getSchemaUrlFilter().match(r.schemaUrl))},t}();yt();var ys=function(){var t=function(e,r){return t=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])},t(e,r)};return function(e,r){if(typeof r!="function"&&r!==null)throw new TypeError("Class extends value "+String(r)+" is not a constructor or null");t(e,r);function n(){this.constructor=e}e.prototype=r===null?Object.create(r):(n.prototype=r.prototype,new n)}}(),Hf=function(){function t(e,r){this._writableMetricStorage=e,this._descriptor=r}return t.prototype._record=function(e,r,n){if(r===void 0&&(r={}),n===void 0&&(n=Jl.active()),typeof e!="number"){ie.warn("non-number value provided to metric "+this._descriptor.name+": "+e);return}this._descriptor.valueType===En.INT&&!Number.isInteger(e)&&(ie.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,r,n,gs(Date.now()))},t}();var EO=function(t){ys(e,t);function e(){return t!==null&&t.apply(this,arguments)||this}return e.prototype.add=function(r,n,o){this._record(r,n,o)},e}(Hf);var TO=function(t){ys(e,t);function e(){return t!==null&&t.apply(this,arguments)||this}return e.prototype.add=function(r,n,o){if(r<0){ie.warn("negative value provided to counter "+this._descriptor.name+": "+r);return}this._record(r,n,o)},e}(Hf);var bO=function(t){ys(e,t);function e(){return t!==null&&t.apply(this,arguments)||this}return e.prototype.record=function(r,n,o){this._record(r,n,o)},e}(Hf);var vO=function(t){ys(e,t);function e(){return t!==null&&t.apply(this,arguments)||this}return e.prototype.record=function(r,n,o){if(r<0){ie.warn("negative value provided to histogram "+this._descriptor.name+": "+r);return}this._record(r,n,o)},e}(Hf);var Gf=function(){function t(e,r,n){this._observableRegistry=n,this._descriptor=e,this._metricStorages=r}return t.prototype.addCallback=function(e){this._observableRegistry.addCallback(e,this)},t.prototype.removeCallback=function(e){this._observableRegistry.removeCallback(e,this)},t}();var AO=function(t){ys(e,t);function e(){return t!==null&&t.apply(this,arguments)||this}return e}(Gf);var CO=function(t){ys(e,t);function e(){return t!==null&&t.apply(this,arguments)||this}return e}(Gf);var RO=function(t){ys(e,t);function e(){return t!==null&&t.apply(this,arguments)||this}return e}(Gf);function Md(t){return t instanceof Gf}var wO=function(){function t(e){this._meterSharedState=e}return t.prototype.createGauge=function(e,r){var n=Wo(e,Xe.GAUGE,r),o=this._meterSharedState.registerMetricStorage(n);return new bO(o,n)},t.prototype.createHistogram=function(e,r){var n=Wo(e,Xe.HISTOGRAM,r),o=this._meterSharedState.registerMetricStorage(n);return new vO(o,n)},t.prototype.createCounter=function(e,r){var n=Wo(e,Xe.COUNTER,r),o=this._meterSharedState.registerMetricStorage(n);return new TO(o,n)},t.prototype.createUpDownCounter=function(e,r){var n=Wo(e,Xe.UP_DOWN_COUNTER,r),o=this._meterSharedState.registerMetricStorage(n);return new EO(o,n)},t.prototype.createObservableGauge=function(e,r){var n=Wo(e,Xe.OBSERVABLE_GAUGE,r),o=this._meterSharedState.registerAsyncMetricStorage(n);return new CO(n,o,this._meterSharedState.observableRegistry)},t.prototype.createObservableCounter=function(e,r){var n=Wo(e,Xe.OBSERVABLE_COUNTER,r),o=this._meterSharedState.registerAsyncMetricStorage(n);return new AO(n,o,this._meterSharedState.observableRegistry)},t.prototype.createObservableUpDownCounter=function(e,r){var n=Wo(e,Xe.OBSERVABLE_UP_DOWN_COUNTER,r),o=this._meterSharedState.registerAsyncMetricStorage(n);return new RO(n,o,this._meterSharedState.observableRegistry)},t.prototype.addBatchObservableCallback=function(e,r){this._meterSharedState.observableRegistry.addBatchCallback(e,r)},t.prototype.removeBatchObservableCallback=function(e,r){this._meterSharedState.observableRegistry.removeBatchCallback(e,r)},t}();var jf=function(){function t(e){this._instrumentDescriptor=e}return t.prototype.getInstrumentDescriptor=function(){return this._instrumentDescriptor},t.prototype.updateDescription=function(e){this._instrumentDescriptor=Wo(this._instrumentDescriptor.name,this._instrumentDescriptor.type,{description:e,valueType:this._instrumentDescriptor.valueType,unit:this._instrumentDescriptor.unit,advice:this._instrumentDescriptor.advice})},t}();var H2=function(){var t=function(e,r){return t=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])},t(e,r)};return function(e,r){if(typeof r!="function"&&r!==null)throw new TypeError("Class extends value "+String(r)+" is not a constructor or null");t(e,r);function n(){this.constructor=e}e.prototype=r===null?Object.create(r):(n.prototype=r.prototype,new n)}}(),xO=function(t,e){var r={label:0,sent:function(){if(i[0]&1)throw i[1];return i[1]},trys:[],ops:[]},n,o,i,a;return a={next:s(0),throw:s(1),return:s(2)},typeof Symbol=="function"&&(a[Symbol.iterator]=function(){return this}),a;function s(l){return function(u){return c([l,u])}}function c(l){if(n)throw new TypeError("Generator is already executing.");for(;r;)try{if(n=1,o&&(i=l[0]&2?o.return:l[0]?o.throw||((i=o.return)&&i.call(o),0):o.next)&&!(i=i.call(o,l[1])).done)return i;switch(o=0,i&&(l=[l[0]&2,i.value]),l[0]){case 0:case 1:i=l;break;case 4:return r.label++,{value:l[1],done:!1};case 5:r.label++,o=l[1],l=[0];continue;case 7:l=r.ops.pop(),r.trys.pop();continue;default:if(i=r.trys,!(i=i.length>0&&i[i.length-1])&&(l[0]===6||l[0]===2)){r=0;continue}if(l[0]===3&&(!i||l[1]>i[0]&&l[1]<i[3])){r.label=l[1];break}if(l[0]===6&&r.label<i[1]){r.label=i[1],i=l;break}if(i&&r.label<i[2]){r.label=i[2],r.ops.push(l);break}i[2]&&r.ops.pop(),r.trys.pop();continue}l=e.call(t,r)}catch(u){l=[6,u],o=0}finally{n=i=0}if(l[0]&5)throw l[1];return{value:l[0]?l[1]:void 0,done:!0}}},G2=function(){function t(e){this._hash=e,this._valueMap=new Map,this._keyMap=new Map}return t.prototype.get=function(e,r){return r??(r=this._hash(e)),this._valueMap.get(r)},t.prototype.getOrDefault=function(e,r){var n=this._hash(e);if(this._valueMap.has(n))return this._valueMap.get(n);var o=r();return this._keyMap.has(n)||this._keyMap.set(n,e),this._valueMap.set(n,o),o},t.prototype.set=function(e,r,n){n??(n=this._hash(e)),this._keyMap.has(n)||this._keyMap.set(n,e),this._valueMap.set(n,r)},t.prototype.has=function(e,r){return r??(r=this._hash(e)),this._valueMap.has(r)},t.prototype.keys=function(){var e,r;return xO(this,function(n){switch(n.label){case 0:e=this._keyMap.entries(),r=e.next(),n.label=1;case 1:return r.done===!0?[3,3]:[4,[r.value[1],r.value[0]]];case 2:return n.sent(),r=e.next(),[3,1];case 3:return[2]}})},t.prototype.entries=function(){var e,r;return xO(this,function(n){switch(n.label){case 0:e=this._valueMap.entries(),r=e.next(),n.label=1;case 1:return r.done===!0?[3,3]:[4,[this._keyMap.get(r.value[0]),r.value[1],r.value[0]]];case 2:return n.sent(),r=e.next(),[3,1];case 3:return[2]}})},Object.defineProperty(t.prototype,"size",{get:function(){return this._valueMap.size},enumerable:!1,configurable:!0}),t}();var bo=function(t){H2(e,t);function e(){return t.call(this,wf)||this}return e}(G2);var j2=function(t,e){var r=typeof Symbol=="function"&&t[Symbol.iterator];if(!r)return t;var n=r.call(t),o,i=[],a;try{for(;(e===void 0||e-- >0)&&!(o=n.next()).done;)i.push(o.value)}catch(s){a={error:s}}finally{try{o&&!o.done&&(r=n.return)&&r.call(n)}finally{if(a)throw a.error}}return i},Vf=function(){function t(e,r){this._aggregator=e,this._activeCollectionStorage=new bo,this._cumulativeMemoStorage=new bo,this._overflowAttributes={"otel.metric.overflow":!0},this._cardinalityLimit=(r??2e3)-1,this._overflowHashCode=wf(this._overflowAttributes)}return t.prototype.record=function(e,r,n,o){var i=this,a=this._activeCollectionStorage.get(r);if(!a){if(this._activeCollectionStorage.size>=this._cardinalityLimit){var s=this._activeCollectionStorage.getOrDefault(this._overflowAttributes,function(){return i._aggregator.createAccumulation(o)});s?.record(e);return}a=this._aggregator.createAccumulation(o),this._activeCollectionStorage.set(r,a)}a?.record(e)},t.prototype.batchCumulate=function(e,r){var n=this;Array.from(e.entries()).forEach(function(o){var i=j2(o,3),a=i[0],s=i[1],c=i[2],l=n._aggregator.createAccumulation(r);l?.record(s);var u=l;if(n._cumulativeMemoStorage.has(a,c)){var d=n._cumulativeMemoStorage.get(a,c);u=n._aggregator.diff(d,l)}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,l)}if(n._activeCollectionStorage.has(a,c)){var p=n._activeCollectionStorage.get(a,c);u=n._aggregator.merge(p,u)}n._cumulativeMemoStorage.set(a,l,c),n._activeCollectionStorage.set(a,u,c)})},t.prototype.collect=function(){var e=this._activeCollectionStorage;return this._activeCollectionStorage=new bo,e},t}();var xT=function(t){var e=typeof Symbol=="function"&&Symbol.iterator,r=e&&t[e],n=0;if(r)return r.call(t);if(t&&typeof t.length=="number")return{next:function(){return t&&n>=t.length&&(t=void 0),{value:t&&t[n++],done:!t}}};throw new TypeError(e?"Object is not iterable.":"Symbol.iterator is not defined.")},_O=function(t,e){var r=typeof Symbol=="function"&&t[Symbol.iterator];if(!r)return t;var n=r.call(t),o,i=[],a;try{for(;(e===void 0||e-- >0)&&!(o=n.next()).done;)i.push(o.value)}catch(s){a={error:s}}finally{try{o&&!o.done&&(r=n.return)&&r.call(n)}finally{if(a)throw a.error}}return i},Wf=function(){function t(e,r){var n=this;this._aggregator=e,this._unreportedAccumulations=new Map,this._reportHistory=new Map,r.forEach(function(o){n._unreportedAccumulations.set(o,[])})}return t.prototype.buildMetrics=function(e,r,n,o){this._stashAccumulations(n);var i=this._getMergedUnreportedAccumulations(e),a=i,s;if(this._reportHistory.has(e)){var c=this._reportHistory.get(e),l=c.collectionTime;s=c.aggregationTemporality,s===nc.CUMULATIVE?a=t.merge(c.accumulations,i,this._aggregator):a=t.calibrateStartTime(c.accumulations,i,l)}else s=e.selectAggregationTemporality(r.type);this._reportHistory.set(e,{accumulations:a,collectionTime:o,aggregationTemporality:s});var u=V2(a);if(u.length!==0)return this._aggregator.toMetricData(r,s,u,o)},t.prototype._stashAccumulations=function(e){var r,n,o=this._unreportedAccumulations.keys();try{for(var i=xT(o),a=i.next();!a.done;a=i.next()){var s=a.value,c=this._unreportedAccumulations.get(s);c===void 0&&(c=[],this._unreportedAccumulations.set(s,c)),c.push(e)}}catch(l){r={error:l}}finally{try{a&&!a.done&&(n=i.return)&&n.call(i)}finally{if(r)throw r.error}}},t.prototype._getMergedUnreportedAccumulations=function(e){var r,n,o=new bo,i=this._unreportedAccumulations.get(e);if(this._unreportedAccumulations.set(e,[]),i===void 0)return o;try{for(var a=xT(i),s=a.next();!s.done;s=a.next()){var c=s.value;o=t.merge(o,c,this._aggregator)}}catch(l){r={error:l}}finally{try{s&&!s.done&&(n=a.return)&&n.call(a)}finally{if(r)throw r.error}}return o},t.merge=function(e,r,n){for(var o=e,i=r.entries(),a=i.next();a.done!==!0;){var s=_O(a.value,3),c=s[0],l=s[1],u=s[2];if(e.has(c,u)){var d=e.get(c,u),p=n.merge(d,l);o.set(c,p,u)}else o.set(c,l,u);a=i.next()}return o},t.calibrateStartTime=function(e,r,n){var o,i;try{for(var a=xT(e.keys()),s=a.next();!s.done;s=a.next()){var c=_O(s.value,2),l=c[0],u=c[1],d=r.get(l,u);d?.setStartTime(n)}}catch(p){o={error:p}}finally{try{s&&!s.done&&(i=a.return)&&i.call(a)}finally{if(o)throw o.error}}return r},t}();function V2(t){return Array.from(t.entries())}var W2=function(){var t=function(e,r){return t=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])},t(e,r)};return function(e,r){if(typeof r!="function"&&r!==null)throw new TypeError("Class extends value "+String(r)+" is not a constructor or null");t(e,r);function n(){this.constructor=e}e.prototype=r===null?Object.create(r):(n.prototype=r.prototype,new n)}}(),$2=function(t,e){var r=typeof Symbol=="function"&&t[Symbol.iterator];if(!r)return t;var n=r.call(t),o,i=[],a;try{for(;(e===void 0||e-- >0)&&!(o=n.next()).done;)i.push(o.value)}catch(s){a={error:s}}finally{try{o&&!o.done&&(r=n.return)&&r.call(n)}finally{if(a)throw a.error}}return i},IO=function(t){W2(e,t);function e(r,n,o,i,a){var s=t.call(this,r)||this;return s._attributesProcessor=o,s._aggregationCardinalityLimit=a,s._deltaMetricStorage=new Vf(n,s._aggregationCardinalityLimit),s._temporalMetricStorage=new Wf(n,i),s}return e.prototype.record=function(r,n){var o=this,i=new bo;Array.from(r.entries()).forEach(function(a){var s=$2(a,2),c=s[0],l=s[1];i.set(o._attributesProcessor.process(c),l)}),this._deltaMetricStorage.batchCumulate(i,n)},e.prototype.collect=function(r,n){var o=this._deltaMetricStorage.collect();return this._temporalMetricStorage.buildMetrics(r,this._instrumentDescriptor,o,n)},e}(jf);yt();function _T(t,e){var r="";return t.unit!==e.unit&&(r+=" - Unit '"+t.unit+"' does not match '"+e.unit+`'
|
|
25
25
|
`),t.type!==e.type&&(r+=" - Type '"+t.type+"' does not match '"+e.type+`'
|
|
26
26
|
`),t.valueType!==e.valueType&&(r+=" - Value Type '"+t.valueType+"' does not match '"+e.valueType+`'
|
|
27
27
|
`),t.description!==e.description&&(r+=" - Description '"+t.description+"' does not match '"+e.description+`'
|
|
@@ -33,21 +33,21 @@ Parse error: ${e.error.message}`}throw new Yp(n,{cause:e.error})}var _R=t=>{let
|
|
|
33
33
|
To resolve the conflict:`,IT(l,e))),i=c):ie.warn("A view or instrument with the name ",e.name,` has already been registered and is incompatible with another registered view.
|
|
34
34
|
`,`Details:
|
|
35
35
|
`,_T(l,e),`To resolve the conflict:
|
|
36
|
-
`,IT(l,e))}}catch(u){n={error:u}}finally{try{s&&!s.done&&(o=a.return)&&o.call(a)}finally{if(n)throw n.error}}return i},t}();var MO=function(){function t(e){this._backingStorages=e}return t.prototype.record=function(e,r,n,o){this._backingStorages.forEach(function(i){i.record(e,r,n,o)})},t}();yt();yt();var OO=function(){function t(e,r){this._instrumentName=e,this._valueType=r,this._buffer=new bo}return t.prototype.observe=function(e,r){if(r===void 0&&(r={}),typeof e!="number"){ie.warn("non-number value provided to metric "+this._instrumentName+": "+e);return}this._valueType===En.INT&&!Number.isInteger(e)&&(ie.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(r,e)},t}();var LO=function(){function t(){this._buffer=new Map}return t.prototype.observe=function(e,r,n){if(n===void 0&&(n={}),!!Md(e)){var o=this._buffer.get(e);if(o==null&&(o=new bo,this._buffer.set(e,o)),typeof r!="number"){ie.warn("non-number value provided to metric "+e._descriptor.name+": "+r);return}e._descriptor.valueType===En.INT&&!Number.isInteger(r)&&(ie.warn("INT value type cannot accept a floating-point value for "+e._descriptor.name+", ignoring the fractional digits."),r=Math.trunc(r),!Number.isInteger(r))||o.set(n,r)}},t}();var MT=function(t,e,r,n){function o(i){return i instanceof r?i:new r(function(a){a(i)})}return new(r||(r=Promise))(function(i,a){function s(u){try{l(n.next(u))}catch(d){a(d)}}function c(u){try{l(n.throw(u))}catch(d){a(d)}}function l(u){u.done?i(u.value):o(u.value).then(s,c)}l((n=n.apply(t,e||[])).next())})},OT=function(t,e){var r={label:0,sent:function(){if(i[0]&1)throw i[1];return i[1]},trys:[],ops:[]},n,o,i,a;return a={next:s(0),throw:s(1),return:s(2)},typeof Symbol=="function"&&(a[Symbol.iterator]=function(){return this}),a;function s(l){return function(u){return c([l,u])}}function c(l){if(n)throw new TypeError("Generator is already executing.");for(;r;)try{if(n=1,o&&(i=l[0]&2?o.return:l[0]?o.throw||((i=o.return)&&i.call(o),0):o.next)&&!(i=i.call(o,l[1])).done)return i;switch(o=0,i&&(l=[l[0]&2,i.value]),l[0]){case 0:case 1:i=l;break;case 4:return r.label++,{value:l[1],done:!1};case 5:r.label++,o=l[1],l=[0];continue;case 7:l=r.ops.pop(),r.trys.pop();continue;default:if(i=r.trys,!(i=i.length>0&&i[i.length-1])&&(l[0]===6||l[0]===2)){r=0;continue}if(l[0]===3&&(!i||l[1]>i[0]&&l[1]<i[3])){r.label=l[1];break}if(l[0]===6&&r.label<i[1]){r.label=i[1],i=l;break}if(i&&r.label<i[2]){r.label=i[2],r.ops.push(l);break}i[2]&&r.ops.pop(),r.trys.pop();continue}l=e.call(t,r)}catch(u){l=[6,u],o=0}finally{n=i=0}if(l[0]&5)throw l[1];return{value:l[0]?l[1]:void 0,done:!0}}},NO=function(t,e){var r=typeof Symbol=="function"&&t[Symbol.iterator];if(!r)return t;var n=r.call(t),o,i=[],a;try{for(;(e===void 0||e-- >0)&&!(o=n.next()).done;)i.push(o.value)}catch(s){a={error:s}}finally{try{o&&!o.done&&(r=n.return)&&r.call(n)}finally{if(a)throw a.error}}return i},DO=function(t,e,r){if(r||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 t.concat(i||Array.prototype.slice.call(e))},kO=function(){function t(){this._callbacks=[],this._batchCallbacks=[]}return t.prototype.addCallback=function(e,r){var n=this._findCallback(e,r);n>=0||this._callbacks.push({callback:e,instrument:r})},t.prototype.removeCallback=function(e,r){var n=this._findCallback(e,r);n<0||this._callbacks.splice(n,1)},t.prototype.addBatchCallback=function(e,r){var n=new Set(r.filter(Md));if(n.size===0){ie.error("BatchObservableCallback is not associated with valid instruments",r);return}var o=this._findBatchCallback(e,n);o>=0||this._batchCallbacks.push({callback:e,instruments:n})},t.prototype.removeBatchCallback=function(e,r){var n=new Set(r.filter(Md)),o=this._findBatchCallback(e,n);o<0||this._batchCallbacks.splice(o,1)},t.prototype.observe=function(e,r){return MT(this,void 0,void 0,function(){var n,o,i,a;return OT(this,function(s){switch(s.label){case 0:return n=this._observeCallbacks(e,r),o=this._observeBatchCallbacks(e,r),[4,NM(DO(DO([],NO(n),!1),NO(o),!1))];case 1:return i=s.sent(),a=i.filter(DM).map(function(c){return c.reason}),[2,a]}})})},t.prototype._observeCallbacks=function(e,r){var n=this;return this._callbacks.map(function(o){var i=o.callback,a=o.instrument;return MT(n,void 0,void 0,function(){var s,c;return OT(this,function(l){switch(l.label){case 0:return s=new OO(a._descriptor.name,a._descriptor.valueType),c=Promise.resolve(i(s)),r!=null&&(c=aa(c,r)),[4,c];case 1:return l.sent(),a._metricStorages.forEach(function(u){u.record(s._buffer,e)}),[2]}})})})},t.prototype._observeBatchCallbacks=function(e,r){var n=this;return this._batchCallbacks.map(function(o){var i=o.callback,a=o.instruments;return MT(n,void 0,void 0,function(){var s,c;return OT(this,function(l){switch(l.label){case 0:return s=new LO,c=Promise.resolve(i(s)),r!=null&&(c=aa(c,r)),[4,c];case 1:return l.sent(),a.forEach(function(u){var d=s._buffer.get(u);d!=null&&u._metricStorages.forEach(function(p){p.record(d,e)})}),[2]}})})})},t.prototype._findCallback=function(e,r){return this._callbacks.findIndex(function(n){return n.callback===e&&n.instrument===r})},t.prototype._findBatchCallback=function(e,r){return this._batchCallbacks.findIndex(function(n){return n.callback===e&&kM(n.instruments,r)})},t}();var J2=function(){var t=function(e,r){return t=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])},t(e,r)};return function(e,r){if(typeof r!="function"&&r!==null)throw new TypeError("Class extends value "+String(r)+" is not a constructor or null");t(e,r);function n(){this.constructor=e}e.prototype=r===null?Object.create(r):(n.prototype=r.prototype,new n)}}(),FO=function(t){J2(e,t);function e(r,n,o,i,a){var s=t.call(this,r)||this;return s._attributesProcessor=o,s._aggregationCardinalityLimit=a,s._deltaMetricStorage=new Vf(n,s._aggregationCardinalityLimit),s._temporalMetricStorage=new Wf(n,i),s}return e.prototype.record=function(r,n,o,i){n=this._attributesProcessor.process(n,o),this._deltaMetricStorage.record(r,n,o,i)},e.prototype.collect=function(r,n){var o=this._deltaMetricStorage.collect();return this._temporalMetricStorage.buildMetrics(r,this._instrumentDescriptor,o,n)},e}(jf);var UO=function(){var t=function(e,r){return t=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])},t(e,r)};return function(e,r){if(typeof r!="function"&&r!==null)throw new TypeError("Class extends value "+String(r)+" is not a constructor or null");t(e,r);function n(){this.constructor=e}e.prototype=r===null?Object.create(r):(n.prototype=r.prototype,new n)}}(),sc=function(){function t(){}return t.Noop=function(){return Z2},t}();var Q2=function(t){UO(e,t);function e(){return t!==null&&t.apply(this,arguments)||this}return e.prototype.process=function(r,n){return r},e}(sc);var BO=function(t){UO(e,t);function e(r){var n=t.call(this)||this;return n._allowedAttributeNames=r,n}return e.prototype.process=function(r,n){var o=this,i={};return Object.keys(r).filter(function(a){return o._allowedAttributeNames.includes(a)}).forEach(function(a){return i[a]=r[a]}),i},e}(sc);var Z2=new Q2;var eY=function(t,e,r,n){function o(i){return i instanceof r?i:new r(function(a){a(i)})}return new(r||(r=Promise))(function(i,a){function s(u){try{l(n.next(u))}catch(d){a(d)}}function c(u){try{l(n.throw(u))}catch(d){a(d)}}function l(u){u.done?i(u.value):o(u.value).then(s,c)}l((n=n.apply(t,e||[])).next())})},tY=function(t,e){var r={label:0,sent:function(){if(i[0]&1)throw i[1];return i[1]},trys:[],ops:[]},n,o,i,a;return a={next:s(0),throw:s(1),return:s(2)},typeof Symbol=="function"&&(a[Symbol.iterator]=function(){return this}),a;function s(l){return function(u){return c([l,u])}}function c(l){if(n)throw new TypeError("Generator is already executing.");for(;r;)try{if(n=1,o&&(i=l[0]&2?o.return:l[0]?o.throw||((i=o.return)&&i.call(o),0):o.next)&&!(i=i.call(o,l[1])).done)return i;switch(o=0,i&&(l=[l[0]&2,i.value]),l[0]){case 0:case 1:i=l;break;case 4:return r.label++,{value:l[1],done:!1};case 5:r.label++,o=l[1],l=[0];continue;case 7:l=r.ops.pop(),r.trys.pop();continue;default:if(i=r.trys,!(i=i.length>0&&i[i.length-1])&&(l[0]===6||l[0]===2)){r=0;continue}if(l[0]===3&&(!i||l[1]>i[0]&&l[1]<i[3])){r.label=l[1];break}if(l[0]===6&&r.label<i[1]){r.label=i[1],i=l;break}if(i&&r.label<i[2]){r.label=i[2],r.ops.push(l);break}i[2]&&r.ops.pop(),r.trys.pop();continue}l=e.call(t,r)}catch(u){l=[6,u],o=0}finally{n=i=0}if(l[0]&5)throw l[1];return{value:l[0]?l[1]:void 0,done:!0}}},rY=function(t,e){var r=typeof Symbol=="function"&&t[Symbol.iterator];if(!r)return t;var n=r.call(t),o,i=[],a;try{for(;(e===void 0||e-- >0)&&!(o=n.next()).done;)i.push(o.value)}catch(s){a={error:s}}finally{try{o&&!o.done&&(r=n.return)&&r.call(n)}finally{if(a)throw a.error}}return i},zO=function(){function t(e,r){this._meterProviderSharedState=e,this._instrumentationScope=r,this.metricStorageRegistry=new PO,this.observableRegistry=new kO,this.meter=new wO(this)}return t.prototype.registerMetricStorage=function(e){var r=this._registerMetricStorage(e,FO);return r.length===1?r[0]:new MO(r)},t.prototype.registerAsyncMetricStorage=function(e){var r=this._registerMetricStorage(e,IO);return r},t.prototype.collect=function(e,r,n){return eY(this,void 0,void 0,function(){var o,i,a;return tY(this,function(s){switch(s.label){case 0:return[4,this.observableRegistry.observe(r,n?.timeoutMillis)];case 1:return o=s.sent(),i=this.metricStorageRegistry.getStorages(e),i.length===0?[2,null]:(a=i.map(function(c){return c.collect(e,r)}).filter(OM),a.length===0?[2,{errors:o}]:[2,{scopeMetrics:{scope:this._instrumentationScope,metrics:a},errors:o}])}})})},t.prototype._registerMetricStorage=function(e,r){var n=this,o=this._meterProviderSharedState.viewRegistry.findViews(e,this._instrumentationScope),i=o.map(function(c){var l=BM(c,e),u=n.metricStorageRegistry.findOrUpdateCompatibleStorage(l);if(u!=null)return u;var d=c.aggregation.createAggregator(l),p=new r(l,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),s=a.map(function(c){var l=rY(c,2),u=l[0],d=l[1],p=n.metricStorageRegistry.findOrUpdateCompatibleCollectorStorage(u,e);if(p!=null)return p;var m=d.createAggregator(e),f=u.selectCardinalityLimit(e.type),h=new r(e,m,sc.Noop(),[u],f);return n.metricStorageRegistry.registerForCollector(u,h),h});i=i.concat(s)}return i},t}();var nY=function(t){var e=typeof Symbol=="function"&&Symbol.iterator,r=e&&t[e],n=0;if(r)return r.call(t);if(t&&typeof t.length=="number")return{next:function(){return t&&n>=t.length&&(t=void 0),{value:t&&t[n++],done:!t}}};throw new TypeError(e?"Object is not iterable.":"Symbol.iterator is not defined.")},HO=function(){function t(e){this.resource=e,this.viewRegistry=new yO,this.metricCollectors=[],this.meterSharedStates=new Map}return t.prototype.getMeterSharedState=function(e){var r=LM(e),n=this.meterSharedStates.get(r);return n==null&&(n=new zO(this,e),this.meterSharedStates.set(r,n)),n},t.prototype.selectAggregations=function(e){var r,n,o=[];try{for(var i=nY(this.metricCollectors),a=i.next();!a.done;a=i.next()){var s=a.value;o.push([s,s.selectAggregation(e)])}}catch(c){r={error:c}}finally{try{a&&!a.done&&(n=i.return)&&n.call(i)}finally{if(r)throw r.error}}return o},t}();var $f=function(t,e,r,n){function o(i){return i instanceof r?i:new r(function(a){a(i)})}return new(r||(r=Promise))(function(i,a){function s(u){try{l(n.next(u))}catch(d){a(d)}}function c(u){try{l(n.throw(u))}catch(d){a(d)}}function l(u){u.done?i(u.value):o(u.value).then(s,c)}l((n=n.apply(t,e||[])).next())})},qf=function(t,e){var r={label:0,sent:function(){if(i[0]&1)throw i[1];return i[1]},trys:[],ops:[]},n,o,i,a;return a={next:s(0),throw:s(1),return:s(2)},typeof Symbol=="function"&&(a[Symbol.iterator]=function(){return this}),a;function s(l){return function(u){return c([l,u])}}function c(l){if(n)throw new TypeError("Generator is already executing.");for(;r;)try{if(n=1,o&&(i=l[0]&2?o.return:l[0]?o.throw||((i=o.return)&&i.call(o),0):o.next)&&!(i=i.call(o,l[1])).done)return i;switch(o=0,i&&(l=[l[0]&2,i.value]),l[0]){case 0:case 1:i=l;break;case 4:return r.label++,{value:l[1],done:!1};case 5:r.label++,o=l[1],l=[0];continue;case 7:l=r.ops.pop(),r.trys.pop();continue;default:if(i=r.trys,!(i=i.length>0&&i[i.length-1])&&(l[0]===6||l[0]===2)){r=0;continue}if(l[0]===3&&(!i||l[1]>i[0]&&l[1]<i[3])){r.label=l[1];break}if(l[0]===6&&r.label<i[1]){r.label=i[1],i=l;break}if(i&&r.label<i[2]){r.label=i[2],r.ops.push(l);break}i[2]&&r.ops.pop(),r.trys.pop();continue}l=e.call(t,r)}catch(u){l=[6,u],o=0}finally{n=i=0}if(l[0]&5)throw l[1];return{value:l[0]?l[1]:void 0,done:!0}}},oY=function(t,e){var r=typeof Symbol=="function"&&t[Symbol.iterator];if(!r)return t;var n=r.call(t),o,i=[],a;try{for(;(e===void 0||e-- >0)&&!(o=n.next()).done;)i.push(o.value)}catch(s){a={error:s}}finally{try{o&&!o.done&&(r=n.return)&&r.call(n)}finally{if(a)throw a.error}}return i},iY=function(t,e,r){if(r||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 t.concat(i||Array.prototype.slice.call(e))},GO=function(){function t(e,r){this._sharedState=e,this._metricReader=r}return t.prototype.collect=function(e){return $f(this,void 0,void 0,function(){var r,n,o,i,a=this;return qf(this,function(s){switch(s.label){case 0:return r=gs(Date.now()),n=[],o=[],i=Array.from(this._sharedState.meterSharedStates.values()).map(function(c){return $f(a,void 0,void 0,function(){var l;return qf(this,function(u){switch(u.label){case 0:return[4,c.collect(this,r,e)];case 1:return l=u.sent(),l?.scopeMetrics!=null&&n.push(l.scopeMetrics),l?.errors!=null&&o.push.apply(o,iY([],oY(l.errors),!1)),[2]}})})}),[4,Promise.all(i)];case 1:return s.sent(),[2,{resourceMetrics:{resource:this._sharedState.resource,scopeMetrics:n},errors:o}]}})})},t.prototype.forceFlush=function(e){return $f(this,void 0,void 0,function(){return qf(this,function(r){switch(r.label){case 0:return[4,this._metricReader.forceFlush(e)];case 1:return r.sent(),[2]}})})},t.prototype.shutdown=function(e){return $f(this,void 0,void 0,function(){return qf(this,function(r){switch(r.label){case 0:return[4,this._metricReader.shutdown(e)];case 1:return r.sent(),[2]}})})},t.prototype.selectAggregationTemporality=function(e){return this._metricReader.selectAggregationTemporality(e)},t.prototype.selectAggregation=function(e){return this._metricReader.selectAggregation(e)},t.prototype.selectCardinalityLimit=function(e){var r,n,o;return(o=(n=(r=this._metricReader).selectCardinalityLimit)===null||n===void 0?void 0:n.call(r,e))!==null&&o!==void 0?o:2e3},t}();var jO=function(t,e,r,n){function o(i){return i instanceof r?i:new r(function(a){a(i)})}return new(r||(r=Promise))(function(i,a){function s(u){try{l(n.next(u))}catch(d){a(d)}}function c(u){try{l(n.throw(u))}catch(d){a(d)}}function l(u){u.done?i(u.value):o(u.value).then(s,c)}l((n=n.apply(t,e||[])).next())})},VO=function(t,e){var r={label:0,sent:function(){if(i[0]&1)throw i[1];return i[1]},trys:[],ops:[]},n,o,i,a;return a={next:s(0),throw:s(1),return:s(2)},typeof Symbol=="function"&&(a[Symbol.iterator]=function(){return this}),a;function s(l){return function(u){return c([l,u])}}function c(l){if(n)throw new TypeError("Generator is already executing.");for(;r;)try{if(n=1,o&&(i=l[0]&2?o.return:l[0]?o.throw||((i=o.return)&&i.call(o),0):o.next)&&!(i=i.call(o,l[1])).done)return i;switch(o=0,i&&(l=[l[0]&2,i.value]),l[0]){case 0:case 1:i=l;break;case 4:return r.label++,{value:l[1],done:!1};case 5:r.label++,o=l[1],l=[0];continue;case 7:l=r.ops.pop(),r.trys.pop();continue;default:if(i=r.trys,!(i=i.length>0&&i[i.length-1])&&(l[0]===6||l[0]===2)){r=0;continue}if(l[0]===3&&(!i||l[1]>i[0]&&l[1]<i[3])){r.label=l[1];break}if(l[0]===6&&r.label<i[1]){r.label=i[1],i=l;break}if(i&&r.label<i[2]){r.label=i[2],r.ops.push(l);break}i[2]&&r.ops.pop(),r.trys.pop();continue}l=e.call(t,r)}catch(u){l=[6,u],o=0}finally{n=i=0}if(l[0]&5)throw l[1];return{value:l[0]?l[1]:void 0,done:!0}}},WO=function(t){var e=typeof Symbol=="function"&&Symbol.iterator,r=e&&t[e],n=0;if(r)return r.call(t);if(t&&typeof t.length=="number")return{next:function(){return t&&n>=t.length&&(t=void 0),{value:t&&t[n++],done:!t}}};throw new TypeError(e?"Object is not iterable.":"Symbol.iterator is not defined.")};function aY(t,e){var r=e??zf.empty();return t?zf.default().merge(r):r}var LT=function(){function t(e){var r,n,o,i,a;if(this._shutdown=!1,this._sharedState=new HO(aY((a=e?.mergeResourceWithDefaults)!==null&&a!==void 0?a:!0,e?.resource)),e?.views!=null&&e.views.length>0)try{for(var s=WO(e.views),c=s.next();!c.done;c=s.next()){var l=c.value;this._sharedState.viewRegistry.addView(l)}}catch(m){r={error:m}}finally{try{c&&!c.done&&(n=s.return)&&n.call(s)}finally{if(r)throw r.error}}if(e?.readers!=null&&e.readers.length>0)try{for(var u=WO(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 t.prototype.getMeter=function(e,r,n){return r===void 0&&(r=""),n===void 0&&(n={}),this._shutdown?(ie.warn("A shutdown MeterProvider cannot provide a Meter"),UE()):this._sharedState.getMeterSharedState({name:e,version:r,schemaUrl:n.schemaUrl}).meter},t.prototype.addMetricReader=function(e){var r=new GO(this._sharedState,e);e.setMetricProducer(r),this._sharedState.metricCollectors.push(r)},t.prototype.shutdown=function(e){return jO(this,void 0,void 0,function(){return VO(this,function(r){switch(r.label){case 0:return this._shutdown?(ie.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 r.sent(),[2]}})})},t.prototype.forceFlush=function(e){return jO(this,void 0,void 0,function(){return VO(this,function(r){switch(r.label){case 0:return this._shutdown?(ie.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 r.sent(),[2]}})})},t}();var sY=/[\^$\\.+?()[\]{}|]/g,Kf=function(){function t(e){e==="*"?(this._matchAll=!0,this._regexp=/.*/):(this._matchAll=!1,this._regexp=new RegExp(t.escapePattern(e)))}return t.prototype.match=function(e){return this._matchAll?!0:this._regexp.test(e)},t.escapePattern=function(e){return"^"+e.replace(sY,"\\$&").replace("*",".*")+"$"},t.hasWildcard=function(e){return e.includes("*")},t}();var lc=function(){function t(e){this._matchAll=e===void 0,this._pattern=e}return t.prototype.match=function(e){return!!(this._matchAll||e===this._pattern)},t}();var $O=function(){function t(e){var r;this._nameFilter=new Kf((r=e?.name)!==null&&r!==void 0?r:"*"),this._type=e?.type,this._unitFilter=new lc(e?.unit)}return t.prototype.getType=function(){return this._type},t.prototype.getNameFilter=function(){return this._nameFilter},t.prototype.getUnitFilter=function(){return this._unitFilter},t}();var qO=function(){function t(e){this._nameFilter=new lc(e?.name),this._versionFilter=new lc(e?.version),this._schemaUrlFilter=new lc(e?.schemaUrl)}return t.prototype.getNameFilter=function(){return this._nameFilter},t.prototype.getVersionFilter=function(){return this._versionFilter},t.prototype.getSchemaUrlFilter=function(){return this._schemaUrlFilter},t}();function lY(t){return t.instrumentName==null&&t.instrumentType==null&&t.instrumentUnit==null&&t.meterName==null&&t.meterVersion==null&&t.meterSchemaUrl==null}var Yf=function(){function t(e){var r;if(lY(e))throw new Error("Cannot create view with no selector arguments supplied");if(e.name!=null&&(e?.instrumentName==null||Kf.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 BO(e.attributeKeys):this.attributesProcessor=sc.Noop(),this.name=e.name,this.description=e.description,this.aggregation=(r=e.aggregation)!==null&&r!==void 0?r:qn.Default(),this.instrumentSelector=new $O({name:e.instrumentName,type:e.instrumentType,unit:e.instrumentUnit}),this.meterSelector=new qO({name:e.meterName,version:e.meterVersion,schemaUrl:e.meterSchemaUrl}),this.aggregationCardinalityLimit=e.aggregationCardinalityLimit}return t}();var dNe=process.env.APP||"unknown";yt();import{v4 as uY}from"uuid";function dY(){return new IM({url:"https://us-west.metrics.momentic.ai/v1/metrics",headers:{"x-momentic-metrics-api-key":"c60c6a0f-60da-41a7-a61b-07969a0aa303"},temporalityPreference:fs.DELTA})}var pY=[new Yf({instrumentName:"test_event_duration",instrumentType:Xe.HISTOGRAM,aggregation:new Pd([100,500,1e3,2e3,3e3,4e3,5e3,7500,1e4,15e3,2e4],!1)}),new Yf({instrumentName:"test_step_duration",instrumentType:Xe.HISTOGRAM,aggregation:new Pd([100,500,1e3,2e3,3e3,4e3,5e3,7500,1e4,15e3,2e4],!1)})],Xf=class{globalAttributes;provider;meter;counterCache=new Map;histogramCache=new Map;observableGaugeCache=new Map;gaugeValues=new Map;getCounter(e){let r=this.counterCache.get(e);if(r)return r;let n=this.meter.createCounter(e);return this.counterCache.set(e,n),n}getHistogram(e){let r=this.histogramCache.get(e);if(r)return r;let n=this.meter.createHistogram(e);return this.histogramCache.set(e,n),n}ensureObservableGauge(e){let r=this.observableGaugeCache.get(e);if(r)return r;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 r=typeof process<"u"?"production":"unknown",n=new rT({[ff]:e.serviceName,[RP]:r,[xP]:typeof process<"u"&&process.env.SERVICE_INSTANCE_ID?process.env.SERVICE_INSTANCE_ID:uY()}),o=dY(),i=new wT({exporter:o,exportIntervalMillis:e.exportIntervalMs??6e4});this.provider=new LT({resource:n,readers:[i],views:pY}),uf.setGlobalMeterProvider(this.provider),this.meter=uf.getMeter("momentic-serverless")}increment(e,r,n){try{let o=sf(n,this.globalAttributes);this.getCounter(e).add(typeof r=="number"?r:1,o)}catch{}}gauge(e,r){try{this.ensureObservableGauge(e),this.gaugeValues.set(e,r)}catch{}}distribution(e,r,n){try{let o=sf(n,this.globalAttributes);this.getHistogram(e).record(r,o)}catch{}}async flush(){try{await this.provider.forceFlush()}catch{}}async recordDuration({fn:e,name:r,tags:n}){let o=Date.now();try{return await Promise.resolve(e())}finally{this.distribution(r,Date.now()-o,n)}}};var Wt=new af;function KO(t){t.disabled||(Wt=new Xf(t))}var NT=!1;try{let t=await import("@sentry/node");t.init({dsn:"https://89e980855f7b9c6e56fc6c7e7143888b@o4506426201800704.ingest.us.sentry.io/4508343221354497",environment:"production",dist:"production",release:"cli-2.71.1",tracesSampleRate:0,sendDefaultPii:!0}),LI(t.captureException),NT=!0}catch{}import{Argument as zte,Command as Hte,Option as zr}from"@commander-js/extra-typings";import{execSync as Gte}from"child_process";import{existsSync as mY,statSync as fY}from"fs";function YO(t){try{return mY(t)&&fY(t).isDirectory()}catch(e){return v.error({err:e},`Error reading path ${t} during directory existence check`),!1}}import{confirm as hY,input as gY}from"@inquirer/prompts";import{existsSync as SY,mkdirSync as yY,statSync as EY}from"fs";import{dirname as TY}from"path";var bY=!1,JO=(()=>{try{return EY("/.dockerenv"),!0}catch{return!1}})();async function yr(t){return cs||bY||JO?!0:(await v.flush(),await new Promise(r=>setTimeout(r,100)),await hY({message:t}))}async function DT(t){let e=TY(t);return YO(e)?SY(t)?yr(`File '${XO(t)}' already exists. Overwrite existing content?`):!0:await yr(`Directory '${XO(e)}' doesn't exist. Create it now?`)?(yY(e,{recursive:!0}),!0):!1}function XO(t){return t.replace(/(\s+)/g,"\\$1")}async function QO(t,e){return cs||JO?e:(await gY({message:t,default:e})).trim()||e}import $o,{supportsColor as AY}from"chalk";import{Console as ZO}from"console";import{format as Ld}from"util";var kT=class extends Error{constructor(e,r,n){let o=Error.stackTraceLimit;n&&(Error.stackTraceLimit=Math.max(n,o||10)),super(e),Error.captureStackTrace&&Error.captureStackTrace(this,r),Error.stackTraceLimit=o}},Jf=class t extends ZO{_buffer=[];_groupDepth=0;Console=ZO;constructor(){super({write:e=>(t.write(this._buffer,"log",e),!0)})}static write(e,r,n,o=2){let i=new kT(void 0,t.write).stack;if(!i)return e;let a=i.split(`
|
|
36
|
+
`,IT(l,e))}}catch(u){n={error:u}}finally{try{s&&!s.done&&(o=a.return)&&o.call(a)}finally{if(n)throw n.error}}return i},t}();var MO=function(){function t(e){this._backingStorages=e}return t.prototype.record=function(e,r,n,o){this._backingStorages.forEach(function(i){i.record(e,r,n,o)})},t}();yt();yt();var OO=function(){function t(e,r){this._instrumentName=e,this._valueType=r,this._buffer=new bo}return t.prototype.observe=function(e,r){if(r===void 0&&(r={}),typeof e!="number"){ie.warn("non-number value provided to metric "+this._instrumentName+": "+e);return}this._valueType===En.INT&&!Number.isInteger(e)&&(ie.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(r,e)},t}();var LO=function(){function t(){this._buffer=new Map}return t.prototype.observe=function(e,r,n){if(n===void 0&&(n={}),!!Md(e)){var o=this._buffer.get(e);if(o==null&&(o=new bo,this._buffer.set(e,o)),typeof r!="number"){ie.warn("non-number value provided to metric "+e._descriptor.name+": "+r);return}e._descriptor.valueType===En.INT&&!Number.isInteger(r)&&(ie.warn("INT value type cannot accept a floating-point value for "+e._descriptor.name+", ignoring the fractional digits."),r=Math.trunc(r),!Number.isInteger(r))||o.set(n,r)}},t}();var MT=function(t,e,r,n){function o(i){return i instanceof r?i:new r(function(a){a(i)})}return new(r||(r=Promise))(function(i,a){function s(u){try{l(n.next(u))}catch(d){a(d)}}function c(u){try{l(n.throw(u))}catch(d){a(d)}}function l(u){u.done?i(u.value):o(u.value).then(s,c)}l((n=n.apply(t,e||[])).next())})},OT=function(t,e){var r={label:0,sent:function(){if(i[0]&1)throw i[1];return i[1]},trys:[],ops:[]},n,o,i,a;return a={next:s(0),throw:s(1),return:s(2)},typeof Symbol=="function"&&(a[Symbol.iterator]=function(){return this}),a;function s(l){return function(u){return c([l,u])}}function c(l){if(n)throw new TypeError("Generator is already executing.");for(;r;)try{if(n=1,o&&(i=l[0]&2?o.return:l[0]?o.throw||((i=o.return)&&i.call(o),0):o.next)&&!(i=i.call(o,l[1])).done)return i;switch(o=0,i&&(l=[l[0]&2,i.value]),l[0]){case 0:case 1:i=l;break;case 4:return r.label++,{value:l[1],done:!1};case 5:r.label++,o=l[1],l=[0];continue;case 7:l=r.ops.pop(),r.trys.pop();continue;default:if(i=r.trys,!(i=i.length>0&&i[i.length-1])&&(l[0]===6||l[0]===2)){r=0;continue}if(l[0]===3&&(!i||l[1]>i[0]&&l[1]<i[3])){r.label=l[1];break}if(l[0]===6&&r.label<i[1]){r.label=i[1],i=l;break}if(i&&r.label<i[2]){r.label=i[2],r.ops.push(l);break}i[2]&&r.ops.pop(),r.trys.pop();continue}l=e.call(t,r)}catch(u){l=[6,u],o=0}finally{n=i=0}if(l[0]&5)throw l[1];return{value:l[0]?l[1]:void 0,done:!0}}},NO=function(t,e){var r=typeof Symbol=="function"&&t[Symbol.iterator];if(!r)return t;var n=r.call(t),o,i=[],a;try{for(;(e===void 0||e-- >0)&&!(o=n.next()).done;)i.push(o.value)}catch(s){a={error:s}}finally{try{o&&!o.done&&(r=n.return)&&r.call(n)}finally{if(a)throw a.error}}return i},DO=function(t,e,r){if(r||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 t.concat(i||Array.prototype.slice.call(e))},kO=function(){function t(){this._callbacks=[],this._batchCallbacks=[]}return t.prototype.addCallback=function(e,r){var n=this._findCallback(e,r);n>=0||this._callbacks.push({callback:e,instrument:r})},t.prototype.removeCallback=function(e,r){var n=this._findCallback(e,r);n<0||this._callbacks.splice(n,1)},t.prototype.addBatchCallback=function(e,r){var n=new Set(r.filter(Md));if(n.size===0){ie.error("BatchObservableCallback is not associated with valid instruments",r);return}var o=this._findBatchCallback(e,n);o>=0||this._batchCallbacks.push({callback:e,instruments:n})},t.prototype.removeBatchCallback=function(e,r){var n=new Set(r.filter(Md)),o=this._findBatchCallback(e,n);o<0||this._batchCallbacks.splice(o,1)},t.prototype.observe=function(e,r){return MT(this,void 0,void 0,function(){var n,o,i,a;return OT(this,function(s){switch(s.label){case 0:return n=this._observeCallbacks(e,r),o=this._observeBatchCallbacks(e,r),[4,NM(DO(DO([],NO(n),!1),NO(o),!1))];case 1:return i=s.sent(),a=i.filter(DM).map(function(c){return c.reason}),[2,a]}})})},t.prototype._observeCallbacks=function(e,r){var n=this;return this._callbacks.map(function(o){var i=o.callback,a=o.instrument;return MT(n,void 0,void 0,function(){var s,c;return OT(this,function(l){switch(l.label){case 0:return s=new OO(a._descriptor.name,a._descriptor.valueType),c=Promise.resolve(i(s)),r!=null&&(c=aa(c,r)),[4,c];case 1:return l.sent(),a._metricStorages.forEach(function(u){u.record(s._buffer,e)}),[2]}})})})},t.prototype._observeBatchCallbacks=function(e,r){var n=this;return this._batchCallbacks.map(function(o){var i=o.callback,a=o.instruments;return MT(n,void 0,void 0,function(){var s,c;return OT(this,function(l){switch(l.label){case 0:return s=new LO,c=Promise.resolve(i(s)),r!=null&&(c=aa(c,r)),[4,c];case 1:return l.sent(),a.forEach(function(u){var d=s._buffer.get(u);d!=null&&u._metricStorages.forEach(function(p){p.record(d,e)})}),[2]}})})})},t.prototype._findCallback=function(e,r){return this._callbacks.findIndex(function(n){return n.callback===e&&n.instrument===r})},t.prototype._findBatchCallback=function(e,r){return this._batchCallbacks.findIndex(function(n){return n.callback===e&&kM(n.instruments,r)})},t}();var J2=function(){var t=function(e,r){return t=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])},t(e,r)};return function(e,r){if(typeof r!="function"&&r!==null)throw new TypeError("Class extends value "+String(r)+" is not a constructor or null");t(e,r);function n(){this.constructor=e}e.prototype=r===null?Object.create(r):(n.prototype=r.prototype,new n)}}(),FO=function(t){J2(e,t);function e(r,n,o,i,a){var s=t.call(this,r)||this;return s._attributesProcessor=o,s._aggregationCardinalityLimit=a,s._deltaMetricStorage=new Vf(n,s._aggregationCardinalityLimit),s._temporalMetricStorage=new Wf(n,i),s}return e.prototype.record=function(r,n,o,i){n=this._attributesProcessor.process(n,o),this._deltaMetricStorage.record(r,n,o,i)},e.prototype.collect=function(r,n){var o=this._deltaMetricStorage.collect();return this._temporalMetricStorage.buildMetrics(r,this._instrumentDescriptor,o,n)},e}(jf);var UO=function(){var t=function(e,r){return t=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])},t(e,r)};return function(e,r){if(typeof r!="function"&&r!==null)throw new TypeError("Class extends value "+String(r)+" is not a constructor or null");t(e,r);function n(){this.constructor=e}e.prototype=r===null?Object.create(r):(n.prototype=r.prototype,new n)}}(),sc=function(){function t(){}return t.Noop=function(){return Z2},t}();var Q2=function(t){UO(e,t);function e(){return t!==null&&t.apply(this,arguments)||this}return e.prototype.process=function(r,n){return r},e}(sc);var BO=function(t){UO(e,t);function e(r){var n=t.call(this)||this;return n._allowedAttributeNames=r,n}return e.prototype.process=function(r,n){var o=this,i={};return Object.keys(r).filter(function(a){return o._allowedAttributeNames.includes(a)}).forEach(function(a){return i[a]=r[a]}),i},e}(sc);var Z2=new Q2;var eY=function(t,e,r,n){function o(i){return i instanceof r?i:new r(function(a){a(i)})}return new(r||(r=Promise))(function(i,a){function s(u){try{l(n.next(u))}catch(d){a(d)}}function c(u){try{l(n.throw(u))}catch(d){a(d)}}function l(u){u.done?i(u.value):o(u.value).then(s,c)}l((n=n.apply(t,e||[])).next())})},tY=function(t,e){var r={label:0,sent:function(){if(i[0]&1)throw i[1];return i[1]},trys:[],ops:[]},n,o,i,a;return a={next:s(0),throw:s(1),return:s(2)},typeof Symbol=="function"&&(a[Symbol.iterator]=function(){return this}),a;function s(l){return function(u){return c([l,u])}}function c(l){if(n)throw new TypeError("Generator is already executing.");for(;r;)try{if(n=1,o&&(i=l[0]&2?o.return:l[0]?o.throw||((i=o.return)&&i.call(o),0):o.next)&&!(i=i.call(o,l[1])).done)return i;switch(o=0,i&&(l=[l[0]&2,i.value]),l[0]){case 0:case 1:i=l;break;case 4:return r.label++,{value:l[1],done:!1};case 5:r.label++,o=l[1],l=[0];continue;case 7:l=r.ops.pop(),r.trys.pop();continue;default:if(i=r.trys,!(i=i.length>0&&i[i.length-1])&&(l[0]===6||l[0]===2)){r=0;continue}if(l[0]===3&&(!i||l[1]>i[0]&&l[1]<i[3])){r.label=l[1];break}if(l[0]===6&&r.label<i[1]){r.label=i[1],i=l;break}if(i&&r.label<i[2]){r.label=i[2],r.ops.push(l);break}i[2]&&r.ops.pop(),r.trys.pop();continue}l=e.call(t,r)}catch(u){l=[6,u],o=0}finally{n=i=0}if(l[0]&5)throw l[1];return{value:l[0]?l[1]:void 0,done:!0}}},rY=function(t,e){var r=typeof Symbol=="function"&&t[Symbol.iterator];if(!r)return t;var n=r.call(t),o,i=[],a;try{for(;(e===void 0||e-- >0)&&!(o=n.next()).done;)i.push(o.value)}catch(s){a={error:s}}finally{try{o&&!o.done&&(r=n.return)&&r.call(n)}finally{if(a)throw a.error}}return i},zO=function(){function t(e,r){this._meterProviderSharedState=e,this._instrumentationScope=r,this.metricStorageRegistry=new PO,this.observableRegistry=new kO,this.meter=new wO(this)}return t.prototype.registerMetricStorage=function(e){var r=this._registerMetricStorage(e,FO);return r.length===1?r[0]:new MO(r)},t.prototype.registerAsyncMetricStorage=function(e){var r=this._registerMetricStorage(e,IO);return r},t.prototype.collect=function(e,r,n){return eY(this,void 0,void 0,function(){var o,i,a;return tY(this,function(s){switch(s.label){case 0:return[4,this.observableRegistry.observe(r,n?.timeoutMillis)];case 1:return o=s.sent(),i=this.metricStorageRegistry.getStorages(e),i.length===0?[2,null]:(a=i.map(function(c){return c.collect(e,r)}).filter(OM),a.length===0?[2,{errors:o}]:[2,{scopeMetrics:{scope:this._instrumentationScope,metrics:a},errors:o}])}})})},t.prototype._registerMetricStorage=function(e,r){var n=this,o=this._meterProviderSharedState.viewRegistry.findViews(e,this._instrumentationScope),i=o.map(function(c){var l=BM(c,e),u=n.metricStorageRegistry.findOrUpdateCompatibleStorage(l);if(u!=null)return u;var d=c.aggregation.createAggregator(l),p=new r(l,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),s=a.map(function(c){var l=rY(c,2),u=l[0],d=l[1],p=n.metricStorageRegistry.findOrUpdateCompatibleCollectorStorage(u,e);if(p!=null)return p;var m=d.createAggregator(e),f=u.selectCardinalityLimit(e.type),h=new r(e,m,sc.Noop(),[u],f);return n.metricStorageRegistry.registerForCollector(u,h),h});i=i.concat(s)}return i},t}();var nY=function(t){var e=typeof Symbol=="function"&&Symbol.iterator,r=e&&t[e],n=0;if(r)return r.call(t);if(t&&typeof t.length=="number")return{next:function(){return t&&n>=t.length&&(t=void 0),{value:t&&t[n++],done:!t}}};throw new TypeError(e?"Object is not iterable.":"Symbol.iterator is not defined.")},HO=function(){function t(e){this.resource=e,this.viewRegistry=new yO,this.metricCollectors=[],this.meterSharedStates=new Map}return t.prototype.getMeterSharedState=function(e){var r=LM(e),n=this.meterSharedStates.get(r);return n==null&&(n=new zO(this,e),this.meterSharedStates.set(r,n)),n},t.prototype.selectAggregations=function(e){var r,n,o=[];try{for(var i=nY(this.metricCollectors),a=i.next();!a.done;a=i.next()){var s=a.value;o.push([s,s.selectAggregation(e)])}}catch(c){r={error:c}}finally{try{a&&!a.done&&(n=i.return)&&n.call(i)}finally{if(r)throw r.error}}return o},t}();var $f=function(t,e,r,n){function o(i){return i instanceof r?i:new r(function(a){a(i)})}return new(r||(r=Promise))(function(i,a){function s(u){try{l(n.next(u))}catch(d){a(d)}}function c(u){try{l(n.throw(u))}catch(d){a(d)}}function l(u){u.done?i(u.value):o(u.value).then(s,c)}l((n=n.apply(t,e||[])).next())})},qf=function(t,e){var r={label:0,sent:function(){if(i[0]&1)throw i[1];return i[1]},trys:[],ops:[]},n,o,i,a;return a={next:s(0),throw:s(1),return:s(2)},typeof Symbol=="function"&&(a[Symbol.iterator]=function(){return this}),a;function s(l){return function(u){return c([l,u])}}function c(l){if(n)throw new TypeError("Generator is already executing.");for(;r;)try{if(n=1,o&&(i=l[0]&2?o.return:l[0]?o.throw||((i=o.return)&&i.call(o),0):o.next)&&!(i=i.call(o,l[1])).done)return i;switch(o=0,i&&(l=[l[0]&2,i.value]),l[0]){case 0:case 1:i=l;break;case 4:return r.label++,{value:l[1],done:!1};case 5:r.label++,o=l[1],l=[0];continue;case 7:l=r.ops.pop(),r.trys.pop();continue;default:if(i=r.trys,!(i=i.length>0&&i[i.length-1])&&(l[0]===6||l[0]===2)){r=0;continue}if(l[0]===3&&(!i||l[1]>i[0]&&l[1]<i[3])){r.label=l[1];break}if(l[0]===6&&r.label<i[1]){r.label=i[1],i=l;break}if(i&&r.label<i[2]){r.label=i[2],r.ops.push(l);break}i[2]&&r.ops.pop(),r.trys.pop();continue}l=e.call(t,r)}catch(u){l=[6,u],o=0}finally{n=i=0}if(l[0]&5)throw l[1];return{value:l[0]?l[1]:void 0,done:!0}}},oY=function(t,e){var r=typeof Symbol=="function"&&t[Symbol.iterator];if(!r)return t;var n=r.call(t),o,i=[],a;try{for(;(e===void 0||e-- >0)&&!(o=n.next()).done;)i.push(o.value)}catch(s){a={error:s}}finally{try{o&&!o.done&&(r=n.return)&&r.call(n)}finally{if(a)throw a.error}}return i},iY=function(t,e,r){if(r||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 t.concat(i||Array.prototype.slice.call(e))},GO=function(){function t(e,r){this._sharedState=e,this._metricReader=r}return t.prototype.collect=function(e){return $f(this,void 0,void 0,function(){var r,n,o,i,a=this;return qf(this,function(s){switch(s.label){case 0:return r=gs(Date.now()),n=[],o=[],i=Array.from(this._sharedState.meterSharedStates.values()).map(function(c){return $f(a,void 0,void 0,function(){var l;return qf(this,function(u){switch(u.label){case 0:return[4,c.collect(this,r,e)];case 1:return l=u.sent(),l?.scopeMetrics!=null&&n.push(l.scopeMetrics),l?.errors!=null&&o.push.apply(o,iY([],oY(l.errors),!1)),[2]}})})}),[4,Promise.all(i)];case 1:return s.sent(),[2,{resourceMetrics:{resource:this._sharedState.resource,scopeMetrics:n},errors:o}]}})})},t.prototype.forceFlush=function(e){return $f(this,void 0,void 0,function(){return qf(this,function(r){switch(r.label){case 0:return[4,this._metricReader.forceFlush(e)];case 1:return r.sent(),[2]}})})},t.prototype.shutdown=function(e){return $f(this,void 0,void 0,function(){return qf(this,function(r){switch(r.label){case 0:return[4,this._metricReader.shutdown(e)];case 1:return r.sent(),[2]}})})},t.prototype.selectAggregationTemporality=function(e){return this._metricReader.selectAggregationTemporality(e)},t.prototype.selectAggregation=function(e){return this._metricReader.selectAggregation(e)},t.prototype.selectCardinalityLimit=function(e){var r,n,o;return(o=(n=(r=this._metricReader).selectCardinalityLimit)===null||n===void 0?void 0:n.call(r,e))!==null&&o!==void 0?o:2e3},t}();var jO=function(t,e,r,n){function o(i){return i instanceof r?i:new r(function(a){a(i)})}return new(r||(r=Promise))(function(i,a){function s(u){try{l(n.next(u))}catch(d){a(d)}}function c(u){try{l(n.throw(u))}catch(d){a(d)}}function l(u){u.done?i(u.value):o(u.value).then(s,c)}l((n=n.apply(t,e||[])).next())})},VO=function(t,e){var r={label:0,sent:function(){if(i[0]&1)throw i[1];return i[1]},trys:[],ops:[]},n,o,i,a;return a={next:s(0),throw:s(1),return:s(2)},typeof Symbol=="function"&&(a[Symbol.iterator]=function(){return this}),a;function s(l){return function(u){return c([l,u])}}function c(l){if(n)throw new TypeError("Generator is already executing.");for(;r;)try{if(n=1,o&&(i=l[0]&2?o.return:l[0]?o.throw||((i=o.return)&&i.call(o),0):o.next)&&!(i=i.call(o,l[1])).done)return i;switch(o=0,i&&(l=[l[0]&2,i.value]),l[0]){case 0:case 1:i=l;break;case 4:return r.label++,{value:l[1],done:!1};case 5:r.label++,o=l[1],l=[0];continue;case 7:l=r.ops.pop(),r.trys.pop();continue;default:if(i=r.trys,!(i=i.length>0&&i[i.length-1])&&(l[0]===6||l[0]===2)){r=0;continue}if(l[0]===3&&(!i||l[1]>i[0]&&l[1]<i[3])){r.label=l[1];break}if(l[0]===6&&r.label<i[1]){r.label=i[1],i=l;break}if(i&&r.label<i[2]){r.label=i[2],r.ops.push(l);break}i[2]&&r.ops.pop(),r.trys.pop();continue}l=e.call(t,r)}catch(u){l=[6,u],o=0}finally{n=i=0}if(l[0]&5)throw l[1];return{value:l[0]?l[1]:void 0,done:!0}}},WO=function(t){var e=typeof Symbol=="function"&&Symbol.iterator,r=e&&t[e],n=0;if(r)return r.call(t);if(t&&typeof t.length=="number")return{next:function(){return t&&n>=t.length&&(t=void 0),{value:t&&t[n++],done:!t}}};throw new TypeError(e?"Object is not iterable.":"Symbol.iterator is not defined.")};function aY(t,e){var r=e??zf.empty();return t?zf.default().merge(r):r}var LT=function(){function t(e){var r,n,o,i,a;if(this._shutdown=!1,this._sharedState=new HO(aY((a=e?.mergeResourceWithDefaults)!==null&&a!==void 0?a:!0,e?.resource)),e?.views!=null&&e.views.length>0)try{for(var s=WO(e.views),c=s.next();!c.done;c=s.next()){var l=c.value;this._sharedState.viewRegistry.addView(l)}}catch(m){r={error:m}}finally{try{c&&!c.done&&(n=s.return)&&n.call(s)}finally{if(r)throw r.error}}if(e?.readers!=null&&e.readers.length>0)try{for(var u=WO(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 t.prototype.getMeter=function(e,r,n){return r===void 0&&(r=""),n===void 0&&(n={}),this._shutdown?(ie.warn("A shutdown MeterProvider cannot provide a Meter"),UE()):this._sharedState.getMeterSharedState({name:e,version:r,schemaUrl:n.schemaUrl}).meter},t.prototype.addMetricReader=function(e){var r=new GO(this._sharedState,e);e.setMetricProducer(r),this._sharedState.metricCollectors.push(r)},t.prototype.shutdown=function(e){return jO(this,void 0,void 0,function(){return VO(this,function(r){switch(r.label){case 0:return this._shutdown?(ie.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 r.sent(),[2]}})})},t.prototype.forceFlush=function(e){return jO(this,void 0,void 0,function(){return VO(this,function(r){switch(r.label){case 0:return this._shutdown?(ie.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 r.sent(),[2]}})})},t}();var sY=/[\^$\\.+?()[\]{}|]/g,Kf=function(){function t(e){e==="*"?(this._matchAll=!0,this._regexp=/.*/):(this._matchAll=!1,this._regexp=new RegExp(t.escapePattern(e)))}return t.prototype.match=function(e){return this._matchAll?!0:this._regexp.test(e)},t.escapePattern=function(e){return"^"+e.replace(sY,"\\$&").replace("*",".*")+"$"},t.hasWildcard=function(e){return e.includes("*")},t}();var lc=function(){function t(e){this._matchAll=e===void 0,this._pattern=e}return t.prototype.match=function(e){return!!(this._matchAll||e===this._pattern)},t}();var $O=function(){function t(e){var r;this._nameFilter=new Kf((r=e?.name)!==null&&r!==void 0?r:"*"),this._type=e?.type,this._unitFilter=new lc(e?.unit)}return t.prototype.getType=function(){return this._type},t.prototype.getNameFilter=function(){return this._nameFilter},t.prototype.getUnitFilter=function(){return this._unitFilter},t}();var qO=function(){function t(e){this._nameFilter=new lc(e?.name),this._versionFilter=new lc(e?.version),this._schemaUrlFilter=new lc(e?.schemaUrl)}return t.prototype.getNameFilter=function(){return this._nameFilter},t.prototype.getVersionFilter=function(){return this._versionFilter},t.prototype.getSchemaUrlFilter=function(){return this._schemaUrlFilter},t}();function lY(t){return t.instrumentName==null&&t.instrumentType==null&&t.instrumentUnit==null&&t.meterName==null&&t.meterVersion==null&&t.meterSchemaUrl==null}var Yf=function(){function t(e){var r;if(lY(e))throw new Error("Cannot create view with no selector arguments supplied");if(e.name!=null&&(e?.instrumentName==null||Kf.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 BO(e.attributeKeys):this.attributesProcessor=sc.Noop(),this.name=e.name,this.description=e.description,this.aggregation=(r=e.aggregation)!==null&&r!==void 0?r:qn.Default(),this.instrumentSelector=new $O({name:e.instrumentName,type:e.instrumentType,unit:e.instrumentUnit}),this.meterSelector=new qO({name:e.meterName,version:e.meterVersion,schemaUrl:e.meterSchemaUrl}),this.aggregationCardinalityLimit=e.aggregationCardinalityLimit}return t}();var pNe=process.env.APP||"unknown";yt();import{v4 as uY}from"uuid";function dY(){return new IM({url:"https://us-west.metrics.momentic.ai/v1/metrics",headers:{"x-momentic-metrics-api-key":"c60c6a0f-60da-41a7-a61b-07969a0aa303"},temporalityPreference:fs.DELTA})}var pY=[new Yf({instrumentName:"test_event_duration",instrumentType:Xe.HISTOGRAM,aggregation:new Pd([100,500,1e3,2e3,3e3,4e3,5e3,7500,1e4,15e3,2e4],!1)}),new Yf({instrumentName:"test_step_duration",instrumentType:Xe.HISTOGRAM,aggregation:new Pd([100,500,1e3,2e3,3e3,4e3,5e3,7500,1e4,15e3,2e4],!1)})],Xf=class{globalAttributes;provider;meter;counterCache=new Map;histogramCache=new Map;observableGaugeCache=new Map;gaugeValues=new Map;getCounter(e){let r=this.counterCache.get(e);if(r)return r;let n=this.meter.createCounter(e);return this.counterCache.set(e,n),n}getHistogram(e){let r=this.histogramCache.get(e);if(r)return r;let n=this.meter.createHistogram(e);return this.histogramCache.set(e,n),n}ensureObservableGauge(e){let r=this.observableGaugeCache.get(e);if(r)return r;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 r=typeof process<"u"?"production":"unknown",n=new rT({[ff]:e.serviceName,[RP]:r,[xP]:typeof process<"u"&&process.env.SERVICE_INSTANCE_ID?process.env.SERVICE_INSTANCE_ID:uY()}),o=dY(),i=new wT({exporter:o,exportIntervalMillis:e.exportIntervalMs??6e4});this.provider=new LT({resource:n,readers:[i],views:pY}),uf.setGlobalMeterProvider(this.provider),this.meter=uf.getMeter("momentic-serverless")}increment(e,r,n){try{let o=sf(n,this.globalAttributes);this.getCounter(e).add(typeof r=="number"?r:1,o)}catch{}}gauge(e,r){try{this.ensureObservableGauge(e),this.gaugeValues.set(e,r)}catch{}}distribution(e,r,n){try{let o=sf(n,this.globalAttributes);this.getHistogram(e).record(r,o)}catch{}}async flush(){try{await this.provider.forceFlush()}catch{}}async recordDuration({fn:e,name:r,tags:n}){let o=Date.now();try{return await Promise.resolve(e())}finally{this.distribution(r,Date.now()-o,n)}}};var Wt=new af;function KO(t){t.disabled||(Wt=new Xf(t))}var NT=!1;try{let t=await import("@sentry/node");t.init({dsn:"https://89e980855f7b9c6e56fc6c7e7143888b@o4506426201800704.ingest.us.sentry.io/4508343221354497",environment:"production",dist:"production",release:"cli-2.71.2",tracesSampleRate:0,sendDefaultPii:!0}),LI(t.captureException),NT=!0}catch{}import{Argument as zte,Command as Hte,Option as zr}from"@commander-js/extra-typings";import{execSync as Gte}from"child_process";import{existsSync as mY,statSync as fY}from"fs";function YO(t){try{return mY(t)&&fY(t).isDirectory()}catch(e){return v.error({err:e},`Error reading path ${t} during directory existence check`),!1}}import{confirm as hY,input as gY}from"@inquirer/prompts";import{existsSync as SY,mkdirSync as yY,statSync as EY}from"fs";import{dirname as TY}from"path";var bY=!1,JO=(()=>{try{return EY("/.dockerenv"),!0}catch{return!1}})();async function yr(t){return cs||bY||JO?!0:(await v.flush(),await new Promise(r=>setTimeout(r,100)),await hY({message:t}))}async function DT(t){let e=TY(t);return YO(e)?SY(t)?yr(`File '${XO(t)}' already exists. Overwrite existing content?`):!0:await yr(`Directory '${XO(e)}' doesn't exist. Create it now?`)?(yY(e,{recursive:!0}),!0):!1}function XO(t){return t.replace(/(\s+)/g,"\\$1")}async function QO(t,e){return cs||JO?e:(await gY({message:t,default:e})).trim()||e}import $o,{supportsColor as AY}from"chalk";import{Console as ZO}from"console";import{format as Ld}from"util";var kT=class extends Error{constructor(e,r,n){let o=Error.stackTraceLimit;n&&(Error.stackTraceLimit=Math.max(n,o||10)),super(e),Error.captureStackTrace&&Error.captureStackTrace(this,r),Error.stackTraceLimit=o}},Jf=class t extends ZO{_buffer=[];_groupDepth=0;Console=ZO;constructor(){super({write:e=>(t.write(this._buffer,"log",e),!0)})}static write(e,r,n,o=2){let i=new kT(void 0,t.write).stack;if(!i)return e;let a=i.split(`
|
|
37
37
|
`).slice(o).filter(Boolean).join(`
|
|
38
38
|
`);return e.push({message:n,origin:a,type:r}),e}_log(e,r){t.write(this._buffer,e," ".repeat(this._groupDepth)+r,3)}debug(e,...r){this._log("debug",Ld(e,...r))}error(e,...r){this._log("error",Ld(e,...r))}info(e,...r){this._log("info",Ld(e,...r))}log(e,...r){this._log("log",Ld(e,...r))}warn(e,...r){this._log("warn",Ld(e,...r))}getBuffer(){return this._buffer.length>0?this._buffer:void 0}};function eL(t){let e=globalThis.console,r=new Jf;globalThis.console=r;try{t()}finally{let o=r.getBuffer()?.map(i=>i.message).join(`
|
|
39
39
|
`);process.stderr.write(`${o}
|
|
40
40
|
`),globalThis.console=e}}var It=" ".repeat(6);function tL(t,e="",r=!1){let n=process.stdout?.columns||process.stderr?.columns||80,o=Math.max(n-e.length,20),i=t.split(`
|
|
41
41
|
`),a=[];for(let s of i)if(r){let c=s;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=s.split(" "),l="";for(let u of c){if(!l.length){l=u;continue}let d=`${l} ${u}`;d.length<=o?l=d:(a.push(e+l),l=u)}a.push(e+l)}return a.join(`
|
|
42
|
-
`)}import{hostname as vY}from"os";var le=ql({app:"cli",hostname:vY(),disableConsoleLogs:!0,captureExceptions:!0}).child({cliVersion:"2.71.
|
|
42
|
+
`)}import{hostname as vY}from"os";var le=ql({app:"cli",hostname:vY(),disableConsoleLogs:!0,captureExceptions:!0}).child({cliVersion:"2.71.2"});var CY=5;async function Zf({getResults:t,checkDone:e,name:r,timeoutMs:n=18e5}){let o=Date.now(),i=0;for(;Date.now()-o<n;){let a;i>CY&&(v.error(`Failed to fetch ${r} status too many times.`),process.exit(1));try{a=await t(),i=0}catch(l){i++,le.warn({err:l},"Failed to fetch run status, retrying..."),v.warn({err:l},"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(l=>setTimeout(l,c))}v.error(`Timeout elapsed waiting for ${r} to complete (${Math.floor(n/1e3)}s).`),process.exit(1)}function cc({results:t,startTime:e,entity:r,getDisplayLine:n,onFailed:o}){let i=t.filter(u=>u.status==="PASSED"&&u.quarantined),a=t.filter(u=>u.status==="PASSED"&&!u.quarantined),s=t.filter(u=>u.status==="FAILED"&&u.quarantined),c=t.filter(u=>u.status==="FAILED"&&!u.quarantined),l=t.filter(u=>u.status==="CANCELLED");return eL(()=>{if(c.forEach(u=>{v.log(""),o(u)}),c.length){v.log("");let u=c.length===1?"":"s";v.error(`${c.length} ${r}${u} failed:`),c.forEach(d=>{v.dimmed(n(d))})}if(l.length){v.log("");let u=l.length===1?"":"s";v.warn(`${l.length} ${r}${u} cancelled:`),l.forEach(d=>{v.dimmed(n(d))})}if(a.length){v.log("");let u=a.length===1?"":"s";v.success(`${a.length} ${r}${u} passed:`),a.forEach(d=>{v.dimmed(n(d))})}if(s.length){v.log("");let u=s.length===1?"":"s";v.warn(`${s.length} quarantined ${r}${u} failed:`),s.forEach(d=>{v.dimmed(n(d))})}if(i.length){v.log("");let u=i.length===1?"":"s";v.warn(`${i.length} quarantined ${r}${u} passed:`),i.forEach(d=>{v.dimmed(n(d))})}v.log(""),v.dimmed(`Total time: ${Math.round((Date.now()-e)/1e3)}s`)}),{quarantinedPassed:i.length,passed:a.length,quarantinedFailed:s.length,failed:c.length,cancelled:l.length}}var eh=(t,e)=>{if(!t.failureDetails||!t.failureReason)return;let r=gl[t.failureDetails?.classification?.reason||t.failureReason],n=t.failureDetails?.classification?.summary||Gi[t.failureReason],o=t.failureDetails.classification?.rootCause;if(v.error(e),o){v.log(`${It}- Error type: ${$o.dim(r)}`);let i="- Root cause analysis:",a=tL(`${i} ${o}`,`${It} `,!1),s=a.indexOf(":");v.log(`${It}${i} ${$o.dim(a.slice(s+1))}`)}else v.log(`${It}Reason: ${$o.red(r)}`),v.log(`${It}Description: ${$o.red(n)}`)},Nd=({status:t,testLogRef:e,getRunningTestsCount:r,getTotalTestsCount:n,additionalText:o})=>{t=t.toUpperCase();let i=t,a;t.includes("FAIL")?(i=$o.bgRed.white("FAIL"),a=3):t.includes("PASS")?(i=$o.bgGreen.white("PASS"),a=3):t.includes("START")?(i=$o.bgBlue.white("START"),a=2):t.includes("CANCEL")?(i=$o.bgRgb(191,68,11).white("CANCEL"),a=1):t.includes("RETRY")?(i=$o.bgRgb(191,68,11).white("RETRY"),a=2):t.includes("RUN")||t.includes("PROG")?(i=$o.bgMagenta.white("RUNNING"),a=0):(v.warn(`Unknown status tried to be logged in run test locally: ${t}`),a=0),AY||(i=`${i}`),v.log(`${i}${" ".repeat(a)} ${e} ${o?`${o} `:""}(${r()}/${n()})`)};import RY from"fs";import{platform as wY,tmpdir as xY}from"os";import _Y from"path";import{program as IY}from"playwright-core/lib/cli/program";import{registry as Dd}from"playwright-core/lib/server";import rL from"proper-lockfile";var nL=_Y.join(xY(),"momenticBrowserInstallation");var th=["chrome","chromium","chrome-for-testing","ffmpeg"],FT=[...th.filter(t=>t!=="ffmpeg")],PY={Chromium:"chromium","Google Chrome":"chrome","Chrome for Testing":"chrome-for-testing"};function oL(t){switch(t){case"chromium":return"Chromium";case"chrome":return"Google Chrome";case"chrome-for-testing":return"Chrome for Testing";case"ffmpeg":throw new Error(`Unknown browser: ${t}`);default:return(r=>{throw new Error("Unknown browser")})(t)}}var iL={chrome:"chrome",chromium:"chromium","chrome-for-testing":"chromium-headless-shell",ffmpeg:"ffmpeg"};function aL(t){if(t==="Org Default")return!1;let e=iL[PY[t]??""]??"",r=Dd.findExecutable(e);return!r||r.installType==="none"?!1:UT(r)}function UT(t){let e=t.executablePath();return RY.existsSync(e)}function MY(t,e){let r=iL[t];if(!r)throw new Error(`Requested install of unknown browser type ${t}`);let n=Dd.findExecutable(r);if(!n||n.installType==="none")throw new Error(`Requested install of unknown browser type ${t}`);if(!(!e&&UT(n)))return n}async function OY({browser:t,force:e}){let r=MY(t,e);if(!r){v.info(`Browser '${t}' is already installed, skipping...`);return}v.info(`Installing browser '${t}'...`);try{await Dd.installDeps([r],!1),await Dd.install([r],!1)}catch(n){if(n.message.includes("Lock file is already being held")){v.warn("Another process is installing Playwright browsers. Waiting for completion before proceeding..");let o=Dd.findExecutable(t),i=5*60*1e3,a=Date.now();for(;Date.now()-a<i&&!UT(o);)v.info("Waiting for browser to finish installing..."),await new Promise(s=>setTimeout(s,5e3))}else throw n}}async function LY(){if(wY()==="win32"){v.info("Installing Windows dependencies for Playwright...");try{await IY.parseAsync(["","","install","winldd"])}catch(t){v.warn(`Failed to install Windows dependencies: ${t}. Continuing with browser installation...`)}}}async function sL({rawBrowsers:t,force:e=!1,all:r=!1}){await LY();let n=r?th:Array.from(new Set(t));try{await rL.lock(nL,{stale:1e3*60*5,update:1e3*60,realpath:!1,retries:{retries:30,factor:2,maxTimeout:15e3,minTimeout:500}})}catch(i){v.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 OY({browser:i,force:e})}catch(a){o=a,v.error(`Failed to install the ${i} browser: ${a}`)}}finally{await rL.unlock(nL,{realpath:!1})}if(o)throw o}import{createServer as NY}from"http";async function lL(t,e,r=30){for(let n=0;n<r;n+=1){let o=t+n;if(await DY(o))return o}v.error(`Could not find an available port for ${e} starting from ${t} after ${r} attempts`),process.exit(1)}async function DY(t){return new Promise((e,r)=>{let n=NY();n.once("error",o=>{o.code==="EADDRINUSE"?e(!1):(v.warn({err:o},"Unexpected error checking for open ports, continuing..."),n.close(),e(!0))}),n.once("listening",()=>{n.close(()=>{e(!0)})}),n.listen(t)})}import kY from"blocked-at";import FY from"why-is-node-running";function cL(t){UY(t),BY()}function UY(t){kY((e,r)=>{console.warn(`Detected the NodeJS event loop was blocked for ${e.toFixed(0)}ms. This can cause the CLI to hang.`);let n=r.join(`
|
|
43
43
|
`);console.warn(n),t.warn({stack:n,time:e},"NodeJS event loop blocked")},{threshold:1e3,trimFalsePositives:!0})}function BY(){process.on("SIGINT",()=>{if("_getActiveHandles"in process){let t=process._getActiveHandles();console.log("Active handles:",t.map(e=>e.constructor?.name))}FY(),setImmediate(()=>{setTimeout(()=>{process.exit(1)},2e3).unref()})})}function uL(t){let e=t?.shardIndex??1,r=t?.shardCount??1;if(e<1)throw new Error("Shard index must be greater than 0.");if(r<1)throw new Error("Shard count must be greater than 0.");if(e>r)throw new Error("Shard index cannot be greater than shard count")}function zY(t,e,r,n){if(r>t.length&&(v.warn(`Shard count ${r} is greater than the number of tests ${t.length}! Some workers won't have any tests to run.`),r=Math.max(r,t.length),e>r))return[];let o=Math.floor((e-1)*(t.length/r)),i=Math.floor(e*(t.length/r));return(n?[...t].sort((s,c)=>n(s).localeCompare(n(c))):[...t].sort()).filter((s,c)=>c>=o&&c<i)}function dL(t){let{items:e,shardIndex:r,shardCount:n,sortKey:o}=t;return n>1?zY(e,r,n,o):e}function rh({regenerateCache:t,saveCache:e,disableCache:r}){if(r){if(t)throw new Error("--disable-cache and --regenerate-cache cannot be used together.");if(e)throw new Error("--disable-cache and --save-cache cannot be used together.")}}function BT(t,e,r){return t instanceof Ha?(t.zodIssues.forEach(n=>{r.push({file:e,stepIndex:typeof n.path[0]=="number"?n.path[0]:void 0,field:n.path.slice(1).join(".")||n.path.join("."),issue:n.message})}),!0):!1}function uc({parsingErrors:t,parsingErrorDetails:e,failedTestFilePaths:r,failedModuleFilePaths:n}){if(v.error(`
|
|
44
44
|
Found ${t} file(s) with validation errors that must be fixed manually:
|
|
45
45
|
`),e.length>0){let o=new Map;e.forEach(i=>{let a=o.get(i.file)||[];a.push(i),o.set(i.file,a)}),o.forEach((i,a)=>{v.error(` ${a}`),i.forEach(({stepIndex:s,field:c,issue:l})=>{let u=s!==void 0?`Step ${s}`:"File",d=c?`, field "${c}"`:"";v.error(` ${u}${d}:`),v.error(` \u2192 ${l}`)})})}else r.size>0&&v.error(`Failed test files:
|
|
46
46
|
${[...r].map(o=>`${It}- ${o}`).join(`
|
|
47
47
|
`)}`),n&&n.size>0&&v.error(`Failed module files:
|
|
48
48
|
${[...n].map(o=>`${It}- ${o}`).join(`
|
|
49
|
-
`)}`);v.warn("Please fix these errors in your test files and try again.")}import{once as pL}from"lodash-es";var mL=[],nh=pL(async({reason:t,logger:e,exitCode:r})=>{for(let n of mL.toReversed())try{await n(t,e)}catch(o){e.error({err:o,reason:t},"Error running shutdown handler")}e.info({reason:t,exitCode:r},"Exiting process");try{await J(Promise.all([Zm(),Wt.flush()]),{milliseconds:5e3})}catch{}r!=null?process.exit(r):process.exit()}),dc=pL((t,e)=>{process.once("SIGINT",()=>nh({reason:"SIGINT",logger:t,exitCode:0})),process.once("SIGTERM",()=>nh({reason:"SIGTERM",logger:t,exitCode:0})),e&&(process.once("uncaughtException",r=>(t.error({err:r},"Uncaught exception, shutting down"),nh({reason:"uncaughtException",logger:t,exitCode:1}))),process.once("unhandledRejection",r=>(t.error({reason:r},"Unhandled rejection, shutting down"),nh({reason:"unhandledRejection",logger:t,exitCode:1}))))});function Es(t){mL.push(t)}import{randomUUID as jte}from"crypto";import zB from"body-parser";import fee from"cors";import hee from"dedent";import{Router as IJ}from"express";import{diff as w4}from"deep-object-diff";import Xn from"fs";import Rs from"path";function vt(t,e,r=!1){return t.length<e?t:t.slice(0,e-3)+(r?"...TRUNCATED...":"[...]")}var Ei={EQUALS:"equals",CONTAINS:"contains",STARTS_WITH:"starts with",EXISTS:"exists"},Ti={EQUALS:"does not equal",CONTAINS:"does not contain",STARTS_WITH:"does not start with",EXISTS:"does not exist"},zT={EXISTS:"exists",VISIBLE:"is visible",ENABLED:"is enabled",EDITABLE:"is editable",FOCUSED:"is focused"},HT={EXISTS:"does not exist",VISIBLE:"is not visible",ENABLED:"is disabled",EDITABLE:"is not editable",FOCUSED:"is not focused"};function fL(t){switch(t.type){case"ELEMENT_CONTENT":return`content ${t.negated?Ti[t.operation]:Ei[t.operation]} '${t.value}'`;case"ELEMENT_ATTRIBUTE":{let r=t.negated?Ti[t.operation]:Ei[t.operation];return t.operation==="EXISTS"?`attribute '${t.attr}' ${r}`:`attribute '${t.attr}' ${r} '${t.value}'`}case"ELEMENT_NAME":{let r=t.negated?Ti[t.operation]:Ei[t.operation];return t.operation==="EXISTS"?`tag name ${r}`:`tag name ${r} '${t.value}'`}case"ELEMENT_STYLE":{let r=t.negated?Ti[t.operation]:Ei[t.operation];return t.operation==="EXISTS"?`style property '${t.property}' ${r}`:`style property '${t.property}' ${r} '${t.value}'`}case"ELEMENT_EXISTENCE":return t.negated?HT[t.condition]:zT[t.condition];default:return(r=>{throw"If Typescript complains about the line below, you missed a case or break in the switch above"})(t)}}var Pke={CONTENT:"The page"};function HY(t){switch(t.type){case"VALUE":return`the option with value ${t.value}`;case"LABEL":return`the option with label ${t.label}`;case"INDEX":return`the option at index ${t.index}`;default:return(r=>{throw"If Typescript complains about the line below, you missed a case or break in the switch above"})(t)}}function ih(t){switch(t.type){case"SUBSTRING":return`match substring '${t.url}'`;case"REGEX":return`match regex '${t.regex}'`;case"GLOB":return`match glob '${t.glob}'`;case"DOMAIN":return`match domain '${t.domain}'`;default:return(r=>{throw"If Typescript complains about the line below, you missed a case or break in the switch above"})(t)}}function oh(t){let e="";return t.method&&(e=` with method ${t.method}`),`${ih(t.urlMatcher)}${e}`}function GY(t){return`${t.negated?Ti.CONTAINS:Ei.CONTAINS} '${t.value}'`}function jY(t){switch(t.type){case"CONTENT":return GY(t);default:return t.type,""}}function bi(t,e=!0){switch(t.type){case"SUCCESS":return t.condition?.assertion?`Check success condition: ${t.condition.assertion}`:"All commands completed";case"AI_EXTRACT":return`Extract data from page: ${t.goal}`;case"NAVIGATE":return`Go to URL: ${e?vt(t.url,30):t.url}`;case"DIALOG":return`Automatically ${t.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 ${t.deltaY?`${t.deltaY}px`:"1 page height"}${t.target?` in the container of: ${_r(t.target)}`:""}`;case"SCROLL_UP":return`Scroll up ${t.deltaY?`${t.deltaY}px`:"1 page height"}${t.target?` in the container of: ${_r(t.target)}`:""}`;case"SCROLL_LEFT":return`Scroll left ${t.deltaX?`${t.deltaX}px`:"1 page width"}${t.target?` in the container of: ${_r(t.target)}`:""}`;case"SCROLL_RIGHT":return`Scroll right ${t.deltaX?`${t.deltaX}px`:"1 page width"}${t.target?` in the container of: ${_r(t.target)}`:""}`;case"WAIT":return`Wait for ${t.delay} seconds`;case"REFRESH":return"Refresh the page";case"CLICK":{if(t.target?.type==="coordinates")return`Click at coordinates: ${_r(t.target)}`;let n="";return t.target?.elementDescriptor.length?n=` on element: '${t.target.elementDescriptor}'`:t.cache?.target.nodeOnlySerializedHtml&&(n=` on element: '${t.cache?.target.nodeOnlySerializedHtml}'`),`Click${n}`}case"FOCUS":return`Focus ${_r(t.target)}`;case"BLUR":return`Focus ${_r(t.target)}`;case"DRAG":return`Drag ${_r(t.fromTarget)} onto ${_r(t.toTarget)}`;case"MOUSE_DRAG":return t.target?.type==="description"&&t.target.elementDescriptor?`Click and drag ${_r(t.target)} by ${t.deltaX}px horizontally, ${t.deltaY}px vertically`:`Click and drag mouse by ${t.deltaX}px horizontally, ${t.deltaY}px vertically`;case"TYPE":{let n="";return t.target?.type==="coordinates"?n=` in element at coordinates: ${_r(t.target)}`:t.target?.elementDescriptor.length?n=` in element: '${t.target.elementDescriptor}'`:t.cache?.target.nodeOnlySerializedHtml&&(n=` in element: '${t.cache?.target.nodeOnlySerializedHtml}'`),`Type '${t.value}'${n||""}`}case"HOVER":{let n="";return t.target.type==="coordinates"?n=` over coordinates: ${_r(t.target)}`:t.target.elementDescriptor.length>0?n=` over element: '${t.target.elementDescriptor}'`:t.cache?.target.nodeOnlySerializedHtml&&(n=` over element: '${t.cache?.target.nodeOnlySerializedHtml}'`),`Hover${n}`}case"PRESS":return`Press ${t.value}`;case"KEY_DOWN":return`Hold down ${t.value} on the keyboard`;case"KEY_UP":return`Release ${t.value} on the keyboard`;case"SELECT_OPTION":{let n="",o=HY(t.choice);return t.target.type==="coordinates"?n=` from element at coordinates: ${_r(t.target)}`:t.target.elementDescriptor.length>0?n=` from: '${t.target.elementDescriptor}'`:t.cache?.target.nodeOnlySerializedHtml&&(n=` from: '${t.cache?.target.nodeOnlySerializedHtml}'`),`Select option '${o}'${n}`}case"TAB":switch(t.action.type){case"SUBSTRING":return`Switch to tab with substring: ${t.action.substring}`;case"REGEX":return`Switch to tab matching regex: ${t.action.pattern}`;case"INDEX":return`Switch to tab at index: ${t.action.index}`;default:return(o=>{throw"If Typescript complains about the line below, you missed a case or break in the switch above"})(t.action)}return"Switch to unknown tab";case"NEW_TAB":return`Open new tab to: ${t.url}`;case"REQUEST":return`Send ${t.method} request to ${t.url}`;case"GRAPHQL_REQUEST":return`Send GraphQL request to ${t.url}`;case"COOKIE":return`Set cookie: ${t.value}`;case"LOCAL_STORAGE":return`Set local storage: ${t.key}: ${t.value}`;case"JAVASCRIPT":return`Run JavaScript: ${e?vt(t.code,30):t.code}`;case"AI_ASSERTION":return`Assertion: '${t.assertion}'`;case"VISUAL_DIFF":return`Visual diff against baseline ${t.target?`for element: ${_r(t.target)}`:"for entire page"}`;case"FILE_UPLOAD":return t.fileSource.type==="URL"?`Upload file: ${t.fileSource.url}`:`Upload file: ${t.fileSource.name}`;case"AUTH_LOAD":return"Load auth state";case"AUTH_SAVE":return"Save auth state";case"ELEMENT_CHECK":return`Check the element ${_r(t.target)} ${fL(t.assertion)}`;case"PAGE_CHECK":return`Check the page ${jY(t.assertion)}`;case"WAIT_FOR_URL":return`Wait for page URL to ${ih(t.matcher)}`;case"COPY":return"Copy to clipboard";case"PASTE":return"Paste clipboard contents";case"REGISTER_REQUEST_LISTENER":return t.requestMatcher?`Register a listener for network requests that ${oh(t.requestMatcher)}`:"Register a listener for network requests";case"AWAIT_LISTENER":return t.key?`Wait for the listener ${t.key} to resolve`:"Wait for a listener to resolve";case"RECORD_REQUESTS":return t.requestMatcher?`Start recording requests that match ${oh(t.requestMatcher)}`:"Start recording network requests";case"GET_RECORDED_REQUESTS":return t.key?`Get the requests that were recorded for ${t.key}`:"Get the requests that were recorded";case"SET_HEADER":return t.name?t.requestMatcher?`Set a ${t.name} header for requests that match ${oh(t.requestMatcher)}`:`Set a ${t.name} header for all requests`:"Set a header";case"MOCK_ROUTE":return t.requestMatcher?`Mock requests that ${oh(t.requestMatcher)}`:"Mock a network route";case"REMOVE_ROUTE_MOCK":return t.key?`Remove the mock with key ${t.key}`:"Remove all route mocks";case"OFFLINE_MODE":return t.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"})(t)}}function VY(t){return typeof t=="object"&&t!==null}function vo(t){if(t instanceof Date)return t;if(Array.isArray(t))return t.map(vo);if(VY(t)){let e={};return Object.entries(t).forEach(([r,n])=>{n!==void 0&&(e[r]=vo(n))}),e}return t}function kd(t,e,r,n){let{negated:o,ignoreCase:i}=n,a=t===null?null:t.trim(),s=e.trim();i&&(a=a?.toLowerCase()??null,s=s.toLowerCase());let c;switch(r){case"CONTAINS":{if(a===null){c=!1;break}c=a.includes(s);break}case"EQUALS":{c=a===s;break}case"STARTS_WITH":{if(a===null){c=!1;break}c=a.startsWith(s);break}case"EXISTS":{c=a!==null;break}default:throw new Error(`Unrecognized content assertion type: ${r}`)}return o?!c:c}function hL(t){return t.type==="ELEMENT_EXISTENCE"&&t.negated&&(t.condition==="EXISTS"||t.condition==="VISIBLE")}function pc(t){return t.type==="ELEMENT_EXISTENCE"?t.negated?zT[t.condition]:HT[t.condition]:t.negated?Ei[t.operation]:Ti[t.operation]}import{diff as qY}from"deep-object-diff";import{cloneDeep as ch}from"lodash-es";function ln(t){let e={parentChain:[]};return ah(t,e),e}function ah(t,e){let{onPresetAction:r,onSimpleStepContainer:n,onConditional:o,earlyStop:i}=t;for(let a of t.steps)switch(a.type){case"PRESET_ACTION":if(r(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(r(c.assertion,e)&&i||ah({...t,steps:c.steps},e)&&i)return!0;if(ah({...t,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),ah({...t,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 gL(t,e,r,n){let o=Array.from(e),i=Array.from(n);for(let s=0;s<o.length;s++){if(o[s]!==n[s])return!1;i.shift()}return!!Ts([t],r,i).result}function SL(t){if(t.type==="RESOLVED_MODULE")return!0;let e=!1;return ln({steps:[t],earlyStop:!0,onPresetAction:()=>!1,onConditional:()=>!1,onSimpleStepContainer:(r,n)=>n.parentChain.length===0?!1:r.type==="RESOLVED_MODULE"?(e=!0,!0):!1}),e}function WY(t){if(t.type==="CONDITIONAL"){let e=[];for(let r of t.blocks)e.push(...r.steps??[]);return e.push(...t.elseSteps??[]),e}return t.type==="RESOLVED_MODULE"||t.type==="SECTION"||t.type==="AI_ACTION"?t.steps??[]:[]}function $Y(t){if(t.type==="CONDITIONAL"){let e=t.blocks[0];return e?e.steps:null}return t.type==="RESOLVED_MODULE"||t.type==="SECTION"||t.type==="AI_ACTION"?t.steps??null:null}function yL(t,e){let r=e[e.length-1];if(!r)return null;let n=e.slice(0,-1),{result:o}=Ts(t,r,n);return o?$Y(o):null}function EL(t,e,r){let n=[],o=t,i=r?` in ${r} section`:"";for(let a=0;a<e.length;a++){let s=e[a];if(s===void 0)throw new Error(`Invalid parentStepIdChain: missing id at index ${a} in [${e.join(", ")}]`);let c=o.find(l=>l.id===s);if(!c)throw new Error(`Step ${s} not found at chain index ${a}${i} (parent chain: [${e.join(", ")}])`);n.push(c),o=WY(c)}return n}function Ts(t,e,r=[]){let n,o=[],i=(a,s)=>{let c=JSON.stringify(s.parentChain.map(u=>u.id)),l=r.length===0?!0:JSON.stringify(r)===c;return a.id===e&&l?(n=a,o=s.parentChain,!0):!1};return ln({steps:t,earlyStop:!0,onPresetAction:i,onConditional:i,onSimpleStepContainer:i}),{result:n,parentChain:o}}function TL(t,e){e(t);for(let r in t){let n=t[r];n&&(Array.isArray(n)?lh(n,e):typeof n=="object"&&TL(n,e))}}function lh(t,e){for(let r of t)r&&(Array.isArray(r)?lh(r,e):typeof r=="object"&&TL(r,e))}function Fd(t,e){if(t.length>e.length)return!1;for(let r=0;r<t.length;r++)if(t[r]!==e[r])return!1;return!0}function sh(t){for(let e of t.results)switch(e.type){case"PRESET_ACTION":t.onPresetAction(e);break;case"AI_ACTION":case"AI_ACTION_DYNAMIC":case"MODULE":t.onSimpleStepContainer?.(e),sh({...t,results:e.results});break;case"CONDITIONAL":t.onConditional?.(e),e.assertionResult&&t.onPresetAction(e.assertionResult),sh({...t,results:e.results});break;default:throw new Error(`Unsupported result type: ${e.type}`)}}function vi(t,e){return!t&&!e?!1:!t||!e?!0:Object.keys(qY(t,e)).length>0}function mc({steps:t,topLevel:e=!0,...r}){let{stepCacheEntries:n,logger:o,keyPrefix:i}=r,a=[],s=[],c=[],l=0,u=(p,m)=>{try{let f=po.parse(m.value);if(f.type!==p.type){o.warn({parsedCacheEntry:f,command:p},"Not using step cache due to type mismatch"),s.push(m.key);return}p.cache=f.cache,a.push(m.key),c.push(m.uniqueKey)}catch(f){s.push(m.key),o.error({err:f,cacheEntry:m},"Not using step cache due to parsing error")}},d=(p,m)=>{let f=KY(p.id,m),h=f.find(S=>!!n[S]);if(h)u(p,n[h]);else{if(p.type==="AI_ASSERTION")return;s.push(f[0])}};for(let p of t)switch(p.type){case"RESOLVED_MODULE":{l+=p.steps.length;let{cacheKeysHit:m,cacheKeysMissed:f,uniqueKeysHit:h}=mc({...r,steps:p.steps,keyPrefix:i?`${i}:${p.id}`:p.id,topLevel:!1});a.push(...m),s.push(...f),c.push(...h);break}case"SECTION":case"AI_ACTION":{if(l+=p.steps?.length??0,!p.steps?.length)break;let{cacheKeysHit:m,cacheKeysMissed:f,uniqueKeysHit:h}=mc({...r,steps:p.steps,topLevel:!1});a.push(...m),s.push(...f),c.push(...h);break}case"AI_ACTION_DYNAMIC":continue;case"PRESET_ACTION":{if(!jp.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;l++,d(p.command,i);break}case"CONDITIONAL":{for(let m of p.blocks){l++,d(m.assertion.command,i),l+=m.steps.length;let{cacheKeysHit:f,cacheKeysMissed:h,uniqueKeysHit:S}=mc({...r,steps:m.steps,topLevel:!1});a.push(...f),s.push(...h),c.push(...S)}if(p.elseSteps){l+=p.elseSteps.length;let{cacheKeysHit:m,cacheKeysMissed:f,uniqueKeysHit:h}=mc({...r,steps:p.elseSteps,topLevel:!1});a.push(...m),s.push(...f),c.push(...h)}break}default:return(f=>{throw"If Typescript complains about the line below, you missed a case or break in the switch above"})(p)}return e&&l&&s.length>0&&o.warn({totalSteps:l,cacheKeysMissed:s,cacheKeysHit:a,uniqueKeysHit:c,cacheEntriesKeys:Object.values(n).map(p=>p.uniqueKey)},"Step cache did not fully resolve"),{cacheKeysHit:a,cacheKeysMissed:s,uniqueKeysHit:c}}function AL(t,e){return e?`${e}:${t}`:t}function KY(t,e){let r=[],n=e?.split(":")??[];for(let o=n.length;o>=0;o--){let i=[...n.slice(o),t];r.push(i.join(":"))}return r.reverse(),r}function GT(t){let{moduleStepParents:e=[],moduleIdParents:r=[]}=t;if(e.length!==r.length)throw new Error(`Invalid cache entry parent length: ${JSON.stringify(e)}
|
|
50
|
-
${JSON.stringify(r)}`);return{key:AL(t.id,e.join(":")),organizationId:t.orgId,value:t.value,testId:t.testId,environment:t.environment}}function CL(t){let e=new Set;return lh(t,r=>{if("type"in r&&r.type==="RESOLVED_MODULE"&&"moduleId"in r){let n=r.moduleId;typeof n=="string"&&!e.has(n)&&e.add(n)}}),e}function uh({cmd:t,newTarget:e,key:r,logger:n,updatedWithAI:o}){if(t.type==="DRAG")if(r!=="fromTarget"&&r!=="toTarget")n.error({cmd:t,newTarget:e,key:r},"Attempted to apply invalid cache to DRAG command");else{let i=t.cache?.updatedAt;t.cache={...t.cache,[r]:e,updatedAt:i&&!o?i:new Date}}else if(r==="target"&&Hi(t)){let i=t.cache?.updatedAt;t.cache={...t.cache,target:e,updatedAt:i&&!o?i:new Date}}else n.error({cmd:t,newTarget:e,key:r},"Invalid target cache application")}function Bd(t,e,r){let n=t.cache&&"memory"in t.cache?t.cache.memory?.traces:void 0;vi(n,e)&&(r.info({updatedTraces:e,oldCmd:t},"Wrote new memory to assertion command"),t.cache={...t.cache,memory:{type:"GCS_TRACES",traces:e},updatedAt:new Date})}function RL({logger:t,steps:e}){let r={};return ln({steps:e,onPresetAction:(n,o)=>{let i=n.command;if(!("cache"in i)||!i.cache)return;let a=o.parentChain.filter(l=>l.type==="RESOLVED_MODULE").map(l=>l.id).join(":"),s=AL(i.id,a),c=po.safeParse(i);c.success?r[s]=c.data:t.warn({err:c.error},"Attempted to save invalid command cache")},onSimpleStepContainer:(n,o)=>{},onConditional:(n,o)=>{}}),r}function Ud(t){return{...t,serializedHtml:void 0,nodeOnlySerializedHtml:void 0,screenshotUrl:void 0,boundingBox:void 0,selector:void 0,hybridSelector:void 0,generatedSelectors:void 0,id:-1}}function YY(t,e){return t&&!vi(t.memory,e.memory)?t:{...t,memory:e.memory,updatedAt:e.updatedAt}}function jT(t,e){return t?vi(t.target.memory,e.target.memory)?{target:{...t.target,memory:e.target.memory},updatedAt:e.updatedAt}:t:{target:Ud(e.target),updatedAt:e.updatedAt}}function XY(t,e){let r=ch(t);return r.fromTarget?vi(t.fromTarget?.memory,e.fromTarget?.memory)&&(r.fromTarget={...r.fromTarget,memory:e.fromTarget?.memory},r.updatedAt=e.updatedAt):(r.fromTarget=e.fromTarget,r.fromTarget&&(r.fromTarget=Ud(r.fromTarget),r.updatedAt=e.updatedAt)),r.toTarget?vi(t.toTarget?.memory,e.toTarget?.memory)&&(r.toTarget={...r.toTarget,memory:e.toTarget?.memory},r.updatedAt=e.updatedAt):(r.toTarget=e.toTarget,r.toTarget&&(r.toTarget=Ud(r.toTarget),r.updatedAt=e.updatedAt)),r}function wL({newEntries:t,originalCachesMap:e}){let r=[];for(let n of t){let o=e[n.key],i=n.value.cache;if(i){if(o?n.value={...o}:n.value={type:n.value.type,cache:void 0},"memory"in i&&i.memory){let a=o&&o.cache&&"memory"in o.cache?o.cache.memory:void 0;vi(a,i.memory)&&(n.value.cache=YY(o?.cache,i),r.push(n))}else if("target"in i&&i.target.memory){let a=o&&o.cache&&"memory"in o.cache?o.cache.memory:void 0;if(vi(a,i.target.memory)){let s=mn.safeParse(n.value.cache);n.value.cache=jT(s.data,i),r.push(n)}}else if("fromTarget"in i||"toTarget"in i){let a=IS.optional().parse(n.value.cache);if(!a)continue;let s={from:a.fromTarget?.memory,to:a.toTarget?.memory},c={from:o&&o.cache&&"fromTarget"in o.cache?o.cache.fromTarget?.memory:void 0,to:o&&o.cache&&"toTarget"in o.cache?o.cache.toTarget?.memory:void 0};vi(c,s)&&(n.value.cache=XY(a,i),r.push(n))}}}return r}async function dh({cacheStorage:t,logger:e,schemaVersion:r,stepLists:n,testId:o,environment:i}){let a=ch(n.steps),s=ch(n.beforeSteps)??void 0,c=ch(n.afterSteps)??void 0,l={steps:a,beforeSteps:s,afterSteps:c};try{await t.resolveStepCacheEntries({testId:o,environment:i,stepLists:l,schemaVersion:r,logger:e})}catch(u){throw e.error({err:u},"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: ${u}`,{cause:u})}return l}function xL(t){let e=[];for(let r of t){r.sort((a,s)=>a.timestamp-s.timestamp);let n=[],o,i=1;for(let a of r)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
|
|
49
|
+
`)}`);v.warn("Please fix these errors in your test files and try again.")}import{once as pL}from"lodash-es";var mL=[],nh=pL(async({reason:t,logger:e,exitCode:r})=>{for(let n of mL.toReversed())try{await n(t,e)}catch(o){e.error({err:o,reason:t},"Error running shutdown handler")}e.info({reason:t,exitCode:r},"Exiting process");try{await J(Promise.all([Zm(),Wt.flush()]),{milliseconds:5e3})}catch{}r!=null?process.exit(r):process.exit()}),dc=pL((t,e)=>{process.once("SIGINT",()=>nh({reason:"SIGINT",logger:t,exitCode:0})),process.once("SIGTERM",()=>nh({reason:"SIGTERM",logger:t,exitCode:0})),e&&(process.once("uncaughtException",r=>(t.error({err:r},"Uncaught exception, shutting down"),nh({reason:"uncaughtException",logger:t,exitCode:1}))),process.once("unhandledRejection",r=>(t.error({reason:r},"Unhandled rejection, shutting down"),nh({reason:"unhandledRejection",logger:t,exitCode:1}))))});function Es(t){mL.push(t)}import{randomUUID as jte}from"crypto";import zB from"body-parser";import fee from"cors";import hee from"dedent";import{Router as IJ}from"express";import{diff as w4}from"deep-object-diff";import Xn from"fs";import Rs from"path";function vt(t,e,r=!1){return t.length<e?t:t.slice(0,e-3)+(r?"...TRUNCATED...":"[...]")}var Ei={EQUALS:"equals",CONTAINS:"contains",STARTS_WITH:"starts with",EXISTS:"exists"},Ti={EQUALS:"does not equal",CONTAINS:"does not contain",STARTS_WITH:"does not start with",EXISTS:"does not exist"},zT={EXISTS:"exists",VISIBLE:"is visible",ENABLED:"is enabled",EDITABLE:"is editable",FOCUSED:"is focused"},HT={EXISTS:"does not exist",VISIBLE:"is not visible",ENABLED:"is disabled",EDITABLE:"is not editable",FOCUSED:"is not focused"};function fL(t){switch(t.type){case"ELEMENT_CONTENT":return`content ${t.negated?Ti[t.operation]:Ei[t.operation]} '${t.value}'`;case"ELEMENT_ATTRIBUTE":{let r=t.negated?Ti[t.operation]:Ei[t.operation];return t.operation==="EXISTS"?`attribute '${t.attr}' ${r}`:`attribute '${t.attr}' ${r} '${t.value}'`}case"ELEMENT_NAME":{let r=t.negated?Ti[t.operation]:Ei[t.operation];return t.operation==="EXISTS"?`tag name ${r}`:`tag name ${r} '${t.value}'`}case"ELEMENT_STYLE":{let r=t.negated?Ti[t.operation]:Ei[t.operation];return t.operation==="EXISTS"?`style property '${t.property}' ${r}`:`style property '${t.property}' ${r} '${t.value}'`}case"ELEMENT_EXISTENCE":return t.negated?HT[t.condition]:zT[t.condition];default:return(r=>{throw"If Typescript complains about the line below, you missed a case or break in the switch above"})(t)}}var Mke={CONTENT:"The page"};function HY(t){switch(t.type){case"VALUE":return`the option with value ${t.value}`;case"LABEL":return`the option with label ${t.label}`;case"INDEX":return`the option at index ${t.index}`;default:return(r=>{throw"If Typescript complains about the line below, you missed a case or break in the switch above"})(t)}}function ih(t){switch(t.type){case"SUBSTRING":return`match substring '${t.url}'`;case"REGEX":return`match regex '${t.regex}'`;case"GLOB":return`match glob '${t.glob}'`;case"DOMAIN":return`match domain '${t.domain}'`;default:return(r=>{throw"If Typescript complains about the line below, you missed a case or break in the switch above"})(t)}}function oh(t){let e="";return t.method&&(e=` with method ${t.method}`),`${ih(t.urlMatcher)}${e}`}function GY(t){return`${t.negated?Ti.CONTAINS:Ei.CONTAINS} '${t.value}'`}function jY(t){switch(t.type){case"CONTENT":return GY(t);default:return t.type,""}}function bi(t,e=!0){switch(t.type){case"SUCCESS":return t.condition?.assertion?`Check success condition: ${t.condition.assertion}`:"All commands completed";case"AI_EXTRACT":return`Extract data from page: ${t.goal}`;case"NAVIGATE":return`Go to URL: ${e?vt(t.url,30):t.url}`;case"DIALOG":return`Automatically ${t.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 ${t.deltaY?`${t.deltaY}px`:"1 page height"}${t.target?` in the container of: ${_r(t.target)}`:""}`;case"SCROLL_UP":return`Scroll up ${t.deltaY?`${t.deltaY}px`:"1 page height"}${t.target?` in the container of: ${_r(t.target)}`:""}`;case"SCROLL_LEFT":return`Scroll left ${t.deltaX?`${t.deltaX}px`:"1 page width"}${t.target?` in the container of: ${_r(t.target)}`:""}`;case"SCROLL_RIGHT":return`Scroll right ${t.deltaX?`${t.deltaX}px`:"1 page width"}${t.target?` in the container of: ${_r(t.target)}`:""}`;case"WAIT":return`Wait for ${t.delay} seconds`;case"REFRESH":return"Refresh the page";case"CLICK":{if(t.target?.type==="coordinates")return`Click at coordinates: ${_r(t.target)}`;let n="";return t.target?.elementDescriptor.length?n=` on element: '${t.target.elementDescriptor}'`:t.cache?.target.nodeOnlySerializedHtml&&(n=` on element: '${t.cache?.target.nodeOnlySerializedHtml}'`),`Click${n}`}case"FOCUS":return`Focus ${_r(t.target)}`;case"BLUR":return`Focus ${_r(t.target)}`;case"DRAG":return`Drag ${_r(t.fromTarget)} onto ${_r(t.toTarget)}`;case"MOUSE_DRAG":return t.target?.type==="description"&&t.target.elementDescriptor?`Click and drag ${_r(t.target)} by ${t.deltaX}px horizontally, ${t.deltaY}px vertically`:`Click and drag mouse by ${t.deltaX}px horizontally, ${t.deltaY}px vertically`;case"TYPE":{let n="";return t.target?.type==="coordinates"?n=` in element at coordinates: ${_r(t.target)}`:t.target?.elementDescriptor.length?n=` in element: '${t.target.elementDescriptor}'`:t.cache?.target.nodeOnlySerializedHtml&&(n=` in element: '${t.cache?.target.nodeOnlySerializedHtml}'`),`Type '${t.value}'${n||""}`}case"HOVER":{let n="";return t.target.type==="coordinates"?n=` over coordinates: ${_r(t.target)}`:t.target.elementDescriptor.length>0?n=` over element: '${t.target.elementDescriptor}'`:t.cache?.target.nodeOnlySerializedHtml&&(n=` over element: '${t.cache?.target.nodeOnlySerializedHtml}'`),`Hover${n}`}case"PRESS":return`Press ${t.value}`;case"KEY_DOWN":return`Hold down ${t.value} on the keyboard`;case"KEY_UP":return`Release ${t.value} on the keyboard`;case"SELECT_OPTION":{let n="",o=HY(t.choice);return t.target.type==="coordinates"?n=` from element at coordinates: ${_r(t.target)}`:t.target.elementDescriptor.length>0?n=` from: '${t.target.elementDescriptor}'`:t.cache?.target.nodeOnlySerializedHtml&&(n=` from: '${t.cache?.target.nodeOnlySerializedHtml}'`),`Select option '${o}'${n}`}case"TAB":switch(t.action.type){case"SUBSTRING":return`Switch to tab with substring: ${t.action.substring}`;case"REGEX":return`Switch to tab matching regex: ${t.action.pattern}`;case"INDEX":return`Switch to tab at index: ${t.action.index}`;default:return(o=>{throw"If Typescript complains about the line below, you missed a case or break in the switch above"})(t.action)}return"Switch to unknown tab";case"NEW_TAB":return`Open new tab to: ${t.url}`;case"REQUEST":return`Send ${t.method} request to ${t.url}`;case"GRAPHQL_REQUEST":return`Send GraphQL request to ${t.url}`;case"COOKIE":return`Set cookie: ${t.value}`;case"LOCAL_STORAGE":return`Set local storage: ${t.key}: ${t.value}`;case"JAVASCRIPT":return`Run JavaScript: ${e?vt(t.code,30):t.code}`;case"AI_ASSERTION":return`Assertion: '${t.assertion}'`;case"VISUAL_DIFF":return`Visual diff against baseline ${t.target?`for element: ${_r(t.target)}`:"for entire page"}`;case"FILE_UPLOAD":return t.fileSource.type==="URL"?`Upload file: ${t.fileSource.url}`:`Upload file: ${t.fileSource.name}`;case"AUTH_LOAD":return"Load auth state";case"AUTH_SAVE":return"Save auth state";case"ELEMENT_CHECK":return`Check the element ${_r(t.target)} ${fL(t.assertion)}`;case"PAGE_CHECK":return`Check the page ${jY(t.assertion)}`;case"WAIT_FOR_URL":return`Wait for page URL to ${ih(t.matcher)}`;case"COPY":return"Copy to clipboard";case"PASTE":return"Paste clipboard contents";case"REGISTER_REQUEST_LISTENER":return t.requestMatcher?`Register a listener for network requests that ${oh(t.requestMatcher)}`:"Register a listener for network requests";case"AWAIT_LISTENER":return t.key?`Wait for the listener ${t.key} to resolve`:"Wait for a listener to resolve";case"RECORD_REQUESTS":return t.requestMatcher?`Start recording requests that match ${oh(t.requestMatcher)}`:"Start recording network requests";case"GET_RECORDED_REQUESTS":return t.key?`Get the requests that were recorded for ${t.key}`:"Get the requests that were recorded";case"SET_HEADER":return t.name?t.requestMatcher?`Set a ${t.name} header for requests that match ${oh(t.requestMatcher)}`:`Set a ${t.name} header for all requests`:"Set a header";case"MOCK_ROUTE":return t.requestMatcher?`Mock requests that ${oh(t.requestMatcher)}`:"Mock a network route";case"REMOVE_ROUTE_MOCK":return t.key?`Remove the mock with key ${t.key}`:"Remove all route mocks";case"OFFLINE_MODE":return t.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"})(t)}}function VY(t){return typeof t=="object"&&t!==null}function vo(t){if(t instanceof Date)return t;if(Array.isArray(t))return t.map(vo);if(VY(t)){let e={};return Object.entries(t).forEach(([r,n])=>{n!==void 0&&(e[r]=vo(n))}),e}return t}function kd(t,e,r,n){let{negated:o,ignoreCase:i}=n,a=t===null?null:t.trim(),s=e.trim();i&&(a=a?.toLowerCase()??null,s=s.toLowerCase());let c;switch(r){case"CONTAINS":{if(a===null){c=!1;break}c=a.includes(s);break}case"EQUALS":{c=a===s;break}case"STARTS_WITH":{if(a===null){c=!1;break}c=a.startsWith(s);break}case"EXISTS":{c=a!==null;break}default:throw new Error(`Unrecognized content assertion type: ${r}`)}return o?!c:c}function hL(t){return t.type==="ELEMENT_EXISTENCE"&&t.negated&&(t.condition==="EXISTS"||t.condition==="VISIBLE")}function pc(t){return t.type==="ELEMENT_EXISTENCE"?t.negated?zT[t.condition]:HT[t.condition]:t.negated?Ei[t.operation]:Ti[t.operation]}import{diff as qY}from"deep-object-diff";import{cloneDeep as ch}from"lodash-es";function ln(t){let e={parentChain:[]};return ah(t,e),e}function ah(t,e){let{onPresetAction:r,onSimpleStepContainer:n,onConditional:o,earlyStop:i}=t;for(let a of t.steps)switch(a.type){case"PRESET_ACTION":if(r(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(r(c.assertion,e)&&i||ah({...t,steps:c.steps},e)&&i)return!0;if(ah({...t,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),ah({...t,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 gL(t,e,r,n){let o=Array.from(e),i=Array.from(n);for(let s=0;s<o.length;s++){if(o[s]!==n[s])return!1;i.shift()}return!!Ts([t],r,i).result}function SL(t){if(t.type==="RESOLVED_MODULE")return!0;let e=!1;return ln({steps:[t],earlyStop:!0,onPresetAction:()=>!1,onConditional:()=>!1,onSimpleStepContainer:(r,n)=>n.parentChain.length===0?!1:r.type==="RESOLVED_MODULE"?(e=!0,!0):!1}),e}function WY(t){if(t.type==="CONDITIONAL"){let e=[];for(let r of t.blocks)e.push(...r.steps??[]);return e.push(...t.elseSteps??[]),e}return t.type==="RESOLVED_MODULE"||t.type==="SECTION"||t.type==="AI_ACTION"?t.steps??[]:[]}function $Y(t){if(t.type==="CONDITIONAL"){let e=t.blocks[0];return e?e.steps:null}return t.type==="RESOLVED_MODULE"||t.type==="SECTION"||t.type==="AI_ACTION"?t.steps??null:null}function yL(t,e){let r=e[e.length-1];if(!r)return null;let n=e.slice(0,-1),{result:o}=Ts(t,r,n);return o?$Y(o):null}function EL(t,e,r){let n=[],o=t,i=r?` in ${r} section`:"";for(let a=0;a<e.length;a++){let s=e[a];if(s===void 0)throw new Error(`Invalid parentStepIdChain: missing id at index ${a} in [${e.join(", ")}]`);let c=o.find(l=>l.id===s);if(!c)throw new Error(`Step ${s} not found at chain index ${a}${i} (parent chain: [${e.join(", ")}])`);n.push(c),o=WY(c)}return n}function Ts(t,e,r=[]){let n,o=[],i=(a,s)=>{let c=JSON.stringify(s.parentChain.map(u=>u.id)),l=r.length===0?!0:JSON.stringify(r)===c;return a.id===e&&l?(n=a,o=s.parentChain,!0):!1};return ln({steps:t,earlyStop:!0,onPresetAction:i,onConditional:i,onSimpleStepContainer:i}),{result:n,parentChain:o}}function TL(t,e){e(t);for(let r in t){let n=t[r];n&&(Array.isArray(n)?lh(n,e):typeof n=="object"&&TL(n,e))}}function lh(t,e){for(let r of t)r&&(Array.isArray(r)?lh(r,e):typeof r=="object"&&TL(r,e))}function Fd(t,e){if(t.length>e.length)return!1;for(let r=0;r<t.length;r++)if(t[r]!==e[r])return!1;return!0}function sh(t){for(let e of t.results)switch(e.type){case"PRESET_ACTION":t.onPresetAction(e);break;case"AI_ACTION":case"AI_ACTION_DYNAMIC":case"MODULE":t.onSimpleStepContainer?.(e),sh({...t,results:e.results});break;case"CONDITIONAL":t.onConditional?.(e),e.assertionResult&&t.onPresetAction(e.assertionResult),sh({...t,results:e.results});break;default:throw new Error(`Unsupported result type: ${e.type}`)}}function vi(t,e){return!t&&!e?!1:!t||!e?!0:Object.keys(qY(t,e)).length>0}function mc({steps:t,topLevel:e=!0,...r}){let{stepCacheEntries:n,logger:o,keyPrefix:i}=r,a=[],s=[],c=[],l=0,u=(p,m)=>{try{let f=po.parse(m.value);if(f.type!==p.type){o.warn({parsedCacheEntry:f,command:p},"Not using step cache due to type mismatch"),s.push(m.key);return}p.cache=f.cache,a.push(m.key),c.push(m.uniqueKey)}catch(f){s.push(m.key),o.error({err:f,cacheEntry:m},"Not using step cache due to parsing error")}},d=(p,m)=>{let f=KY(p.id,m),h=f.find(S=>!!n[S]);if(h)u(p,n[h]);else{if(p.type==="AI_ASSERTION")return;s.push(f[0])}};for(let p of t)switch(p.type){case"RESOLVED_MODULE":{l+=p.steps.length;let{cacheKeysHit:m,cacheKeysMissed:f,uniqueKeysHit:h}=mc({...r,steps:p.steps,keyPrefix:i?`${i}:${p.id}`:p.id,topLevel:!1});a.push(...m),s.push(...f),c.push(...h);break}case"SECTION":case"AI_ACTION":{if(l+=p.steps?.length??0,!p.steps?.length)break;let{cacheKeysHit:m,cacheKeysMissed:f,uniqueKeysHit:h}=mc({...r,steps:p.steps,topLevel:!1});a.push(...m),s.push(...f),c.push(...h);break}case"AI_ACTION_DYNAMIC":continue;case"PRESET_ACTION":{if(!jp.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;l++,d(p.command,i);break}case"CONDITIONAL":{for(let m of p.blocks){l++,d(m.assertion.command,i),l+=m.steps.length;let{cacheKeysHit:f,cacheKeysMissed:h,uniqueKeysHit:S}=mc({...r,steps:m.steps,topLevel:!1});a.push(...f),s.push(...h),c.push(...S)}if(p.elseSteps){l+=p.elseSteps.length;let{cacheKeysHit:m,cacheKeysMissed:f,uniqueKeysHit:h}=mc({...r,steps:p.elseSteps,topLevel:!1});a.push(...m),s.push(...f),c.push(...h)}break}default:return(f=>{throw"If Typescript complains about the line below, you missed a case or break in the switch above"})(p)}return e&&l&&s.length>0&&o.warn({totalSteps:l,cacheKeysMissed:s,cacheKeysHit:a,uniqueKeysHit:c,cacheEntriesKeys:Object.values(n).map(p=>p.uniqueKey)},"Step cache did not fully resolve"),{cacheKeysHit:a,cacheKeysMissed:s,uniqueKeysHit:c}}function AL(t,e){return e?`${e}:${t}`:t}function KY(t,e){let r=[],n=e?.split(":")??[];for(let o=n.length;o>=0;o--){let i=[...n.slice(o),t];r.push(i.join(":"))}return r.reverse(),r}function GT(t){let{moduleStepParents:e=[],moduleIdParents:r=[]}=t;if(e.length!==r.length)throw new Error(`Invalid cache entry parent length: ${JSON.stringify(e)}
|
|
50
|
+
${JSON.stringify(r)}`);return{key:AL(t.id,e.join(":")),organizationId:t.orgId,value:t.value,testId:t.testId,environment:t.environment}}function CL(t){let e=new Set;return lh(t,r=>{if("type"in r&&r.type==="RESOLVED_MODULE"&&"moduleId"in r){let n=r.moduleId;typeof n=="string"&&!e.has(n)&&e.add(n)}}),e}function uh({cmd:t,newTarget:e,key:r,logger:n,updatedWithAI:o}){if(t.type==="DRAG")if(r!=="fromTarget"&&r!=="toTarget")n.error({cmd:t,newTarget:e,key:r},"Attempted to apply invalid cache to DRAG command");else{let i=t.cache?.updatedAt;t.cache={...t.cache,[r]:e,updatedAt:i&&!o?i:new Date}}else if(r==="target"&&Hi(t)){let i=t.cache?.updatedAt;t.cache={...t.cache,target:e,updatedAt:i&&!o?i:new Date}}else n.error({cmd:t,newTarget:e,key:r},"Invalid target cache application")}function Bd(t,e,r){let n=t.cache&&"memory"in t.cache?t.cache.memory?.traces:void 0;vi(n,e)&&(r.info({updatedTraces:e,oldCmd:t},"Wrote new memory to assertion command"),t.cache={...t.cache,memory:{type:"GCS_TRACES",traces:e},updatedAt:new Date})}function RL({logger:t,steps:e}){let r={};return ln({steps:e,onPresetAction:(n,o)=>{let i=n.command;if(!("cache"in i)||!i.cache)return;let a=o.parentChain.filter(l=>l.type==="RESOLVED_MODULE").map(l=>l.id).join(":"),s=AL(i.id,a),c=po.safeParse(i);c.success?r[s]=c.data:t.warn({err:c.error},"Attempted to save invalid command cache")},onSimpleStepContainer:(n,o)=>{},onConditional:(n,o)=>{}}),r}function Ud(t){return{...t,serializedHtml:void 0,nodeOnlySerializedHtml:void 0,screenshotUrl:void 0,boundingBox:void 0,selector:void 0,hybridSelector:void 0,generatedSelectors:void 0,id:-1}}function YY(t,e){return t&&!vi(t.memory,e.memory)?t:{...t,memory:e.memory,updatedAt:e.updatedAt}}function jT(t,e){return t?vi(t.target.memory,e.target.memory)?{target:{...t.target,memory:e.target.memory},updatedAt:e.updatedAt}:t:{target:Ud(e.target),updatedAt:e.updatedAt}}function XY(t,e){let r=ch(t);return r.fromTarget?vi(t.fromTarget?.memory,e.fromTarget?.memory)&&(r.fromTarget={...r.fromTarget,memory:e.fromTarget?.memory},r.updatedAt=e.updatedAt):(r.fromTarget=e.fromTarget,r.fromTarget&&(r.fromTarget=Ud(r.fromTarget),r.updatedAt=e.updatedAt)),r.toTarget?vi(t.toTarget?.memory,e.toTarget?.memory)&&(r.toTarget={...r.toTarget,memory:e.toTarget?.memory},r.updatedAt=e.updatedAt):(r.toTarget=e.toTarget,r.toTarget&&(r.toTarget=Ud(r.toTarget),r.updatedAt=e.updatedAt)),r}function wL({newEntries:t,originalCachesMap:e}){let r=[];for(let n of t){let o=e[n.key],i=n.value.cache;if(i){if(o?n.value={...o}:n.value={type:n.value.type,cache:void 0},"memory"in i&&i.memory){let a=o&&o.cache&&"memory"in o.cache?o.cache.memory:void 0;vi(a,i.memory)&&(n.value.cache=YY(o?.cache,i),r.push(n))}else if("target"in i&&i.target.memory){let a=o&&o.cache&&"memory"in o.cache?o.cache.memory:void 0;if(vi(a,i.target.memory)){let s=mn.safeParse(n.value.cache);n.value.cache=jT(s.data,i),r.push(n)}}else if("fromTarget"in i||"toTarget"in i){let a=IS.optional().parse(n.value.cache);if(!a)continue;let s={from:a.fromTarget?.memory,to:a.toTarget?.memory},c={from:o&&o.cache&&"fromTarget"in o.cache?o.cache.fromTarget?.memory:void 0,to:o&&o.cache&&"toTarget"in o.cache?o.cache.toTarget?.memory:void 0};vi(c,s)&&(n.value.cache=XY(a,i),r.push(n))}}}return r}async function dh({cacheStorage:t,logger:e,schemaVersion:r,stepLists:n,testId:o,environment:i}){let a=ch(n.steps),s=ch(n.beforeSteps)??void 0,c=ch(n.afterSteps)??void 0,l={steps:a,beforeSteps:s,afterSteps:c};try{await t.resolveStepCacheEntries({testId:o,environment:i,stepLists:l,schemaVersion:r,logger:e})}catch(u){throw e.error({err:u},"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: ${u}`,{cause:u})}return l}function xL(t){let e=[];for(let r of t){r.sort((a,s)=>a.timestamp-s.timestamp);let n=[],o,i=1;for(let a of r)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 KUe}from"lodash-es";import VT from"semver";function ph(t,e){if(t!=="0.0.1"&&t!==e[e.length-1].toVersion)throw new Error("Please bump latestSchemaVersion in types package after adding a migration");e.forEach((r,n)=>{if(!VT.valid(r.toVersion)||!VT.valid(r.fromVersion))throw new Error(`Migration '${r.name}' has invalid version`);if(!VT.gt(r.toVersion,r.fromVersion))throw new Error(`Migration '${r.name}' has toVersion <= fromVersion`);if(n===0)return;if(e[n-1].toVersion!==r.fromVersion)throw new Error(`Migration '${r.name}' at index ${n} is not contiguous with previous migration`)})}import ZY,{gte as e4}from"semver";var ca=3.1783027;function JY(t){let e=0;for(let r=0;r<t.length;r++){let n=t.charCodeAt(r);!(n>=48&&n<=57)&&!(n>=65&&n<=90)&&!(n>=97&&n<=122)&&e++}return e}function et(t){return Math.ceil(WT(t)/ca)}function WT(t){let e=0;if(typeof t=="string"){let r=t;r=r.replaceAll(`
|
|
51
51
|
`,""),r=r.replaceAll(" ","");let n=JY(r);return r.length-n+ca*n}if(typeof t>"u"||t===null)return 0;if(typeof t=="number")return String(t).length;if(Array.isArray(t))return t.forEach(r=>{e+=WT(r)}),e;if(typeof t=="object"){let r=t;return r.type==="image"||r.type==="media"&&"data"in r&&"mediaType"in r&&typeof r.mediaType=="string"&&r.mediaType.includes("jpeg")?1600:(Object.keys(r).forEach(n=>{e+=String(n).length,n==="image_url"?(r[n]??{}).detail==="high"?e+=1105*ca:e+=85*ca:n==="source"&&typeof r[n]=="object"&&r[n]?.type==="base64"?e+=1600*ca:e+=WT(r[n])}),e)}if(typeof t=="boolean")return t?4:5;throw new Error(`Unsupported type passed to token length calculator '${typeof t}': ${t}`)}var zd=class{diff(e,r,n={}){let o;typeof n=="function"?(o=n,n={}):"callback"in n&&(o=n.callback);let i=this.castInput(e,n),a=this.castInput(r,n),s=this.removeEmpty(this.tokenize(i,n)),c=this.removeEmpty(this.tokenize(a,n));return this.diffWithOptionsObj(s,c,n,o)}diffWithOptionsObj(e,r,n,o){var i;let a=E=>{if(E=this.postProcess(E,n),o){setTimeout(function(){o(E)},0);return}else return E},s=r.length,c=e.length,l=1,u=s+c;n.maxEditLength!=null&&(u=Math.min(u,n.maxEditLength));let d=(i=n.timeout)!==null&&i!==void 0?i:1/0,p=Date.now()+d,m=[{oldPos:-1,lastComponent:void 0}],f=this.extractCommon(m[0],r,e,0,n);if(m[0].oldPos+1>=c&&f+1>=s)return a(this.buildValues(m[0].lastComponent,r,e));let h=-1/0,S=1/0,g=()=>{for(let E=Math.max(h,-l);E<=Math.min(S,l);E+=2){let y,b=m[E-1],C=m[E+1];b&&(m[E-1]=void 0);let I=!1;if(C){let R=C.oldPos-E;I=C&&0<=R&&R<s}let _=b&&b.oldPos+1<c;if(!I&&!_){m[E]=void 0;continue}if(!_||I&&b.oldPos<C.oldPos?y=this.addToPath(C,!0,!1,0,n):y=this.addToPath(b,!1,!0,1,n),f=this.extractCommon(y,r,e,E,n),y.oldPos+1>=c&&f+1>=s)return a(this.buildValues(y.lastComponent,r,e))||!0;m[E]=y,y.oldPos+1>=c&&(S=Math.min(S,E-1)),f+1>=s&&(h=Math.max(h,E+1))}l++};if(o)(function E(){setTimeout(function(){if(l>u||Date.now()>p)return o(void 0);g()||E()},0)})();else for(;l<=u&&Date.now()<=p;){let E=g();if(E)return E}}addToPath(e,r,n,o,i){let a=e.lastComponent;return a&&!i.oneChangePerToken&&a.added===r&&a.removed===n?{oldPos:e.oldPos+o,lastComponent:{count:a.count+1,added:r,removed:n,previousComponent:a.previousComponent}}:{oldPos:e.oldPos+o,lastComponent:{count:1,added:r,removed:n,previousComponent:a}}}extractCommon(e,r,n,o,i){let a=r.length,s=n.length,c=e.oldPos,l=c-o,u=0;for(;l+1<a&&c+1<s&&this.equals(n[c+1],r[l+1],i);)l++,c++,u++,i.oneChangePerToken&&(e.lastComponent={count:1,previousComponent:e.lastComponent,added:!1,removed:!1});return u&&!i.oneChangePerToken&&(e.lastComponent={count:u,previousComponent:e.lastComponent,added:!1,removed:!1}),e.oldPos=c,l}equals(e,r,n){return n.comparator?n.comparator(e,r):e===r||!!n.ignoreCase&&e.toLowerCase()===r.toLowerCase()}removeEmpty(e){let r=[];for(let n=0;n<e.length;n++)e[n]&&r.push(e[n]);return r}castInput(e,r){return e}tokenize(e,r){return Array.from(e)}join(e){return e.join("")}postProcess(e,r){return e}get useLongestToken(){return!1}buildValues(e,r,n){let o=[],i;for(;e;)o.push(e),i=e.previousComponent,delete e.previousComponent,e=i;o.reverse();let a=o.length,s=0,c=0,l=0;for(;s<a;s++){let u=o[s];if(u.removed)u.value=this.join(n.slice(l,l+u.count)),l+=u.count;else{if(!u.added&&this.useLongestToken){let d=r.slice(c,c+u.count);d=d.map(function(p,m){let f=n[l+m];return f.length>p.length?f:p}),u.value=this.join(d)}else u.value=this.join(r.slice(c,c+u.count));c+=u.count,u.added||(l+=u.count)}}return o}};var $T=class extends zd{constructor(){super(...arguments),this.tokenize=QY}equals(e,r,n){return n.ignoreWhitespace?((!n.newlineIsToken||!e.includes(`
|
|
52
52
|
`))&&(e=e.trim()),(!n.newlineIsToken||!r.includes(`
|
|
53
53
|
`))&&(r=r.trim())):n.ignoreNewlineAtEof&&!n.newlineIsToken&&(e.endsWith(`
|
|
@@ -55,19 +55,19 @@ ${JSON.stringify(r)}`);return{key:AL(t.id,e.join(":")),organizationId:t.orgId,va
|
|
|
55
55
|
`)&&(r=r.slice(0,-1))),super.equals(e,r,n)}},_L=new $T;function qT(t,e,r){return _L.diff(t,e,r)}function QY(t,e){e.stripTrailingCr&&(t=t.replace(/\r\n/g,`
|
|
56
56
|
`));let r=[],n=t.split(/(\n|\r\n)/);n[n.length-1]||n.pop();for(let o=0;o<n.length;o++){let i=n[o];o%2&&!e.newlineIsToken?r[r.length-1]+=i:r.push(i)}return r}function Hd(t,e,r){r=r||{};let n=r.n_surrounding??-1;n=n>=0?n:-1;let o=qT(t,e,{ignoreWhitespace:!1}),i=[],a=[];if(o.forEach(function(s){let c=s.removed&&s.added?"!":s.removed?"-":s.added?"+":" ",l=s.value.split(`
|
|
57
57
|
`);l.length>0&&l[l.length-1]===""&&(l=l.slice(0,l.length-1)),l.forEach(function(u){c!==" "&&n>=0&&a.push(i.length),i.push(c+u)})}),n>=0){let s={};a.forEach(function(u){let d,p;for(d=-n;d<n+1;d++)p=u+d,p>=0&&p<i.length&&(s[p]=i[p])}),i=[];let c,l;for(l in s)Object.hasOwn(s,l)&&(c!==void 0&&parseInt(l,10)!==parseInt(c,10)+1&&i.push("@@"),i.push(s[l]),c=l)}return i.join(`
|
|
58
|
-
`)}var mh=class{limit;windowMs;userActions;constructor(e,r){this.limit=e,this.windowMs=r,this.userActions=new Map}_cleanup(e,r="DEFAULT_USER"){let n=Date.now(),o=`${r}:${e}`;if(this.userActions.has(o)){let a=this.userActions.get(o)?.filter(s=>n-s<=this.windowMs)??[];a.length>0?this.userActions.set(o,a):this.userActions.delete(o)}}increment(e,r="DEFAULT_USER"){let n=Date.now(),o=`${r}:${e}`;this._cleanup(r,e),this.userActions.has(o)||this.userActions.set(o,[]);let i=this.userActions.get(o);return i.length>=this.limit?!0:(i.push(n),!1)}};async function xe(t,e){if(!(t<=0))return new Promise((r,n)=>{if(e?.aborted){n(e.reason);return}e?.addEventListener("abort",i,{once:!0});let o=setTimeout(()=>{e?.removeEventListener("abort",i),r()},t);function i(){clearTimeout(o),e?.removeEventListener("abort",i),n(e?.reason)}})}function t4(t){return t.every(e=>e&&typeof e=="object"&&!Array.isArray(e))}async function KT({metadata:t,steps:e,logger:r,toVersion:n,migrations:o}){let i=e,{schemaVersion:a,id:s}=t,c=o.findIndex(d=>ZY.gt(d.toVersion,a));if(c===-1)return{steps:i,newVersion:a};let l=a;for(let d=c;d<o.length;d++){if(n&&e4(l,n)){r.debug("Stopping migration early because toVersion was reached");break}let p=o[d],m={id:s,migration:p.name,toVersion:p.toVersion};try{i=await IL(i,p),l=p.toVersion}catch(f){throw r.warn({err:f,...m},"Migration failed"),new Error(`Step migration ${p.name} failed: ${f}`)}}let u=Hd(JSON.stringify(e,void 0,2),JSON.stringify(i,void 0,2),{n_surrounding:1});return u.trim()&&r.debug({diffs:u,id:s},"Migration diffs"),{newVersion:l,steps:i}}async function IL(t,e){let r=await e.execute(t);for(let n of r)for(let o of Object.keys(n)){if(!e.recursiveKeys.has(o))continue;let i=n[o];!i||!Array.isArray(i)||t4(i)&&(n[o]=await IL(i,e))}return r}var PL={name:"Migrate API request body types",fromVersion:"0.0.1",toVersion:"0.0.2",recursiveKeys:new Set(["results","steps","blocks","elseSteps"]),stopOnFailure:!1,execute:async t=>t.map(e=>{if(e.type!=="MOBILE_PRESET_STEP")return e;let r=e.command;if(!r||r.type!=="REQUEST")return e;let n=typeof r.body=="string"&&r.body.length>0?{type:"json",content:r.body}:void 0;return r.body=n,e})};var ML={name:"Migrate double tap to iterations",fromVersion:"0.0.2",toVersion:"0.0.3",recursiveKeys:new Set(["results","steps","blocks","elseSteps"]),stopOnFailure:!1,execute:async t=>t.map(e=>{if(e.type!=="MOBILE_PRESET_STEP")return e;let r=e.command;return!r||r.type!=="TAP"||!r.doubleTap||(r.iterations=2,delete r.doubleTap,r.tapDelayMs=r.doubleTapDelayMs,delete r.doubleTapDelayMs),e})};var r4=[PL,ML];ph(JS,r4);var OL={name:"Migrate to ai step v2",fromVersion:"1.0.4",toVersion:"1.0.5",recursiveKeys:new Set(["results","commands"]),stopOnFailure:!0,execute:async t=>(t=t.filter(e=>!(e.status!==void 0&&e.type==="AI_ACTION")),t=t.map(e=>(e.status===void 0||e.type==="PRESET_ACTION"&&(e.results=e.commands??e.results??[]),e)),t)};var LL={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 t=>t.map(e=>{if(e.type!=="AI_ACTION"||e.status!==void 0||!e.commands||!e.commands.length)return e;let r=e.commands,n=r[r.length-1];return n&&n.type!=="SUCCESS"&&r.push({type:"SUCCESS"}),e})};var n4=["target","fromTarget","toTarget"];function NL(t){for(let e of n4){if(t[e]===void 0)continue;let r=t[e];r.elementDescriptor!==void 0?r.type="description":t[e]={type:"description",elementDescriptor:""}}}var DL={name:"Migrate element target to discriminated union",fromVersion:"1.0.6",toVersion:"1.0.7",recursiveKeys:new Set(["results","steps"]),stopOnFailure:!0,execute:async t=>t.map(e=>{switch(e.type){case"PRESET_ACTION":return NL(e.command),e;case"AI_ACTION":{let r=e.commands;for(let n of r??[])NL(n);return e}default:return e}})};import{v4 as o4}from"uuid";var kL={name:"Ensure module steps have ids",fromVersion:"1.0.7",toVersion:"1.0.8",recursiveKeys:new Set(["results","steps"]),stopOnFailure:!0,execute:async t=>t.map(e=>{switch(e.type){case"MODULE":return e.id||(e.id=o4()),e;default:return e}})};import{v4 as FL}from"uuid";var UL={name:"Ensure module steps have ids",fromVersion:"1.0.8",toVersion:"1.0.9",recursiveKeys:new Set(["results","steps"]),stopOnFailure:!0,execute:async t=>t.map(e=>{switch(e.type){case"PRESET_ACTION":{if(!e.command)return e;let r=e.command;return r.id=r.id??FL(),e}case"AI_ACTION":return e.commands&&(e.steps=e.commands.map(r=>({type:"PRESET_ACTION",command:{...r,id:r.id??FL()}})),delete e.commands),e;default:return e}})};var BL={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 t=>t.map(e=>{switch(e.type){case"PRESET_ACTION":{if(!e.command)return e;let r=e.command;return typeof r.type!="string"||r.type!=="AI_WAIT"||(r.type="AI_ASSERTION",r.timeout||(r.timeout=10)),e}default:return e}})};import{v4 as i4}from"uuid";var zL={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 t=>t.map(e=>("id"in e&&typeof e.id=="string"||(e.id=i4()),e))};import{v4 as HL}from"uuid";var GL={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 t=>t.map(e=>{if("id"in e&&typeof e.id=="string")return e;if("condition"in e&&typeof e.condition=="object"&&e.condition){let r=e.condition;r.id||(r.id=HL())}return e.id=HL(),e})};var jL={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 t=>t.map(e=>{if(e.type!=="PRESET_ACTION")return e;let r=e.command;return!r||typeof r.envKey!="string"||(e.envKey=r.envKey,delete r.envKey),e})};import{v4 as a4}from"uuid";var VL={name:"Redo last two migrations",fromVersion:"1.0.13",toVersion:"1.0.14",recursiveKeys:new Set(["results","steps","blocks","elseSteps"]),stopOnFailure:!0,execute:async t=>t.map(e=>{if((!("id"in e)||typeof e.id!="string")&&(e.id=a4()),e.type!=="PRESET_ACTION")return e;let r=e.command;return!r||typeof r.envKey!="string"||(e.envKey=r.envKey,delete r.envKey),e})};var WL={name:"Migrate select choice",fromVersion:"1.0.14",toVersion:"1.0.15",recursiveKeys:new Set(["results","steps","blocks","elseSteps"]),stopOnFailure:!0,execute:async t=>t.map(e=>{if(e.type!=="PRESET_ACTION")return e;let r=e.command;return!r||r.type!=="SELECT_OPTION"||e.option===void 0||(e.choice={type:"VALUE",value:r.option},e.option=void 0),e})};var $L={name:"Migrate select choice",fromVersion:"1.0.15",toVersion:"1.0.16",recursiveKeys:new Set(["results","steps","blocks","elseSteps"]),stopOnFailure:!0,execute:async t=>t.map(e=>{if(e.type!=="PRESET_ACTION")return e;let r=e.command;return r&&qL(r),e})};function qL(t){t&&Object.keys(t).forEach(e=>{if(typeof t[e]=="object"&&t[e]){qL(t[e]);return}if(typeof t[e]!="string")return;let r=t[e];e==="code"?t[e]=r.replace(/inputs\./g,"env."):r.includes("{{")&&r.includes("}}")&&(t[e]=r.replace(/inputs\./g,"env."))})}var KL={name:"Migrate switch tab choice",fromVersion:"1.0.16",toVersion:"1.0.17",recursiveKeys:new Set(["results","steps","blocks","elseSteps"]),stopOnFailure:!0,execute:async t=>t.map(e=>{if(e.type!=="PRESET_ACTION")return e;let r=e.command;return!r||r.type!=="TAB"||r.url===void 0||(r.action={type:"SUBSTRING",substring:r.url},r.url=void 0),e})};var YL={name:"Remove press keys sequentially",fromVersion:"1.0.17",toVersion:"1.0.18",recursiveKeys:new Set(["results","steps","blocks","elseSteps"]),stopOnFailure:!1,execute:async t=>t.map(e=>{if(e.type!=="PRESET_ACTION")return e;let r=e.command;return!r||r.type!=="TYPE"?e:r.pressKeysSequentially===void 0?(r.delay=0,e):(r.pressKeysSequentially&&(r.pressKeysSequentially=void 0,r.delay=50),e)})};var XL={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 t=>t.map(e=>{if(e.type!=="PRESET_ACTION")return e;let r=e.command;return!r||r.type!=="WAIT_FOR_URL"||r.url===void 0||(r.matcher={type:"GLOB",glob:r.url},r.url=void 0),e})};var JL={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 t=>t.map(e=>{if(e.type!=="PRESET_ACTION")return e;let r=e.command;if(!r)return e;if(r.type==="SELECT_OPTION"){if(r.option===void 0)return e;r.choice={type:"VALUE",value:r.option},r.option=void 0}else if(r.type==="TAB"){if(r.url===void 0)return e;r.action={type:"SUBSTRING",substring:r.url},r.url=void 0}else if(r.type==="WAIT_FOR_URL"){if(r.url===void 0)return e;r.matcher={type:"GLOB",glob:r.url},r.url=void 0}else r.type==="AI_WAIT"&&(r.type="AI_ASSERTION",r.timeout||(r.timeout=10));return e})};var QL={name:"Migrate ",fromVersion:"1.0.20",toVersion:"1.0.21",recursiveKeys:new Set(["results","steps","blocks","elseSteps"]),stopOnFailure:!1,execute:async t=>t.map(e=>{if(e.type!=="PRESET_ACTION")return e;let r=e.command;return!r||r.type!=="MOCK_ROUTE"&&r.type!=="SET_HEADER"&&r.type!=="RECORD_REQUESTS"&&r.type!=="REGISTER_REQUEST_LISTENER"||(r.type==="REGISTER_REQUEST_LISTENER"||r.type==="RECORD_REQUESTS"?r.requestMatcher={urlMatcher:{type:"REGEX",regex:r.pattern}}:(r.type==="SET_HEADER"||r.type==="MOCK_ROUTE")&&r.urlPattern&&(r.requestMatcher={urlMatcher:{type:"REGEX",regex:r.urlPattern}})),e})};var ZL={name:"Migrate API request body types",fromVersion:"1.0.21",toVersion:"1.0.22",recursiveKeys:new Set(["results","steps","blocks","elseSteps"]),stopOnFailure:!1,execute:async t=>t.map(e=>{if(e.type!=="PRESET_ACTION")return e;let r=e.command;if(!r||r.type!=="REQUEST")return e;let n=typeof r.body=="string"&&r.body.length>0?{type:"json",content:r.body}:void 0;return r.body=n,e})};var eN={name:"Migrate AI checks to preset actions",fromVersion:"1.0.0",toVersion:"1.0.1",recursiveKeys:new Set,execute:async t=>t.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 fh=new Set(["CLICK","TYPE","SELECT_OPTION"]),tN={name:"Migrate element descriptor to live in a target object",fromVersion:"1.0.3",toVersion:"1.0.4",recursiveKeys:new Set,execute:async t=>t.map(e=>{let r=e.command,n=r?.type,o=r?.elementDescriptor;return(o!==void 0||fh.has(n))&&(r.target={elementDescriptor:o??""}),e.commands&&Array.isArray(e.commands)&&e.commands.forEach(a=>{let s=a?.elementDescriptor,c=a?.type;(s!==void 0||fh.has(c))&&(a.target={elementDescriptor:s??""})}),e.results&&Array.isArray(e.results)&&e.results.forEach(a=>{let s=a.command,c=s?.elementDescriptor,l=s?.type;(c!==void 0||fh.has(l))&&(s.target={elementDescriptor:c??""}),a.commands&&Array.isArray(a.commands)&&a.commands.forEach(d=>{let p=d?.elementDescriptor,m=d?.type;(p!==void 0||fh.has(m))&&(d.target={elementDescriptor:p??""})})}),e}),stopOnFailure:!0};var rN={name:"Migrate FAILURE status to FAILED",fromVersion:"1.0.1",toVersion:"1.0.2",recursiveKeys:new Set,execute:async t=>t.map(e=>{let r=e;return r.status==="FAILURE"&&(r.status="FAILED"),typeof r.commands=="object"&&Array.isArray(r.commands)&&r.commands.forEach(n=>{if(n&&typeof n=="object"){let o=n;o?.status==="FAILURE"&&(o.status="FAILED")}}),r}),stopOnFailure:!0};var nN={name:"Migrate preset step types to use the same",fromVersion:"1.0.2",toVersion:"1.0.3",recursiveKeys:new Set,execute:async t=>t.map(e=>{let r=e.command,n=r?.type;return n?.startsWith("PRESET_")&&(r.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,s=a?.type;s?.startsWith("PRESET_")&&(a.type=s.slice(7)),i.commands&&Array.isArray(i.commands)&&i.commands.forEach(l=>{let u=l.type;u?.startsWith("PRESET_")&&(l.type=u.slice(7))})}),e}),stopOnFailure:!0};var oN=[eN,rN,nN,tN,OL,LL,DL,kL,UL,BL,zL,GL,jL,VL,WL,$L,KL,YL,XL,JL,QL,ZL];ph(De,oN);async function fc({metadata:t,steps:e,logger:r,toVersion:n}){return await KT({metadata:t,steps:e,logger:r,toVersion:n,migrations:oN})}import aBe from"zod";import{diff as dBe}from"deep-object-diff";import{cloneDeep as mBe}from"lodash-es";import{v4 as LBe}from"uuid";import{cloneDeep as c4}from"lodash-es";import pN from"truncate-json";import{v4 as sN}from"uuid";import{cloneDeep as cze,unset as uze}from"lodash-es";function iN(t){switch(t.type){case"AI_ACTION":return`AI action: ${vt(t.text,100)}`;case"AI_ACTION_DYNAMIC":return`AI action: ${vt(t.text,100)}`;case"PRESET_ACTION":return bi(t.command);case"MODULE":return`Module ${t.moduleName??t.id}`;case"CONDITIONAL":return"Conditional step";case"SECTION":return`Section ${t.description?`with goal: ${vt(t.description,100)}`:""}`;default:return(r=>{throw new Error("You missed a case in the switch above")})(t)}}function Kn(t){switch(t.type){case"AI_ACTION":return`AI action: ${vt(t.text,100)}`;case"AI_ACTION_DYNAMIC":return`AI action: ${vt(t.text,100)}`;case"PRESET_ACTION":return bi(t.command);case"MODULE":return`Module: ${t.id}`;case"RESOLVED_MODULE":return`Module: ${t.name}`;case"CONDITIONAL":return"Conditional step";case"SECTION":return`Section${t.description?`with goal: ${vt(t.description,100)}`:""}`;default:return(r=>{throw new Error("You missed a case in the switch above")})(t)}}function hc(t,e){return t.split(`
|
|
58
|
+
`)}var mh=class{limit;windowMs;userActions;constructor(e,r){this.limit=e,this.windowMs=r,this.userActions=new Map}_cleanup(e,r="DEFAULT_USER"){let n=Date.now(),o=`${r}:${e}`;if(this.userActions.has(o)){let a=this.userActions.get(o)?.filter(s=>n-s<=this.windowMs)??[];a.length>0?this.userActions.set(o,a):this.userActions.delete(o)}}increment(e,r="DEFAULT_USER"){let n=Date.now(),o=`${r}:${e}`;this._cleanup(r,e),this.userActions.has(o)||this.userActions.set(o,[]);let i=this.userActions.get(o);return i.length>=this.limit?!0:(i.push(n),!1)}};async function xe(t,e){if(!(t<=0))return new Promise((r,n)=>{if(e?.aborted){n(e.reason);return}e?.addEventListener("abort",i,{once:!0});let o=setTimeout(()=>{e?.removeEventListener("abort",i),r()},t);function i(){clearTimeout(o),e?.removeEventListener("abort",i),n(e?.reason)}})}function t4(t){return t.every(e=>e&&typeof e=="object"&&!Array.isArray(e))}async function KT({metadata:t,steps:e,logger:r,toVersion:n,migrations:o}){let i=e,{schemaVersion:a,id:s}=t,c=o.findIndex(d=>ZY.gt(d.toVersion,a));if(c===-1)return{steps:i,newVersion:a};let l=a;for(let d=c;d<o.length;d++){if(n&&e4(l,n)){r.debug("Stopping migration early because toVersion was reached");break}let p=o[d],m={id:s,migration:p.name,toVersion:p.toVersion};try{i=await IL(i,p),l=p.toVersion}catch(f){throw r.warn({err:f,...m},"Migration failed"),new Error(`Step migration ${p.name} failed: ${f}`)}}let u=Hd(JSON.stringify(e,void 0,2),JSON.stringify(i,void 0,2),{n_surrounding:1});return u.trim()&&r.debug({diffs:u,id:s},"Migration diffs"),{newVersion:l,steps:i}}async function IL(t,e){let r=await e.execute(t);for(let n of r)for(let o of Object.keys(n)){if(!e.recursiveKeys.has(o))continue;let i=n[o];!i||!Array.isArray(i)||t4(i)&&(n[o]=await IL(i,e))}return r}var PL={name:"Migrate API request body types",fromVersion:"0.0.1",toVersion:"0.0.2",recursiveKeys:new Set(["results","steps","blocks","elseSteps"]),stopOnFailure:!1,execute:async t=>t.map(e=>{if(e.type!=="MOBILE_PRESET_STEP")return e;let r=e.command;if(!r||r.type!=="REQUEST")return e;let n=typeof r.body=="string"&&r.body.length>0?{type:"json",content:r.body}:void 0;return r.body=n,e})};var ML={name:"Migrate double tap to iterations",fromVersion:"0.0.2",toVersion:"0.0.3",recursiveKeys:new Set(["results","steps","blocks","elseSteps"]),stopOnFailure:!1,execute:async t=>t.map(e=>{if(e.type!=="MOBILE_PRESET_STEP")return e;let r=e.command;return!r||r.type!=="TAP"||!r.doubleTap||(r.iterations=2,delete r.doubleTap,r.tapDelayMs=r.doubleTapDelayMs,delete r.doubleTapDelayMs),e})};var r4=[PL,ML];ph(JS,r4);var OL={name:"Migrate to ai step v2",fromVersion:"1.0.4",toVersion:"1.0.5",recursiveKeys:new Set(["results","commands"]),stopOnFailure:!0,execute:async t=>(t=t.filter(e=>!(e.status!==void 0&&e.type==="AI_ACTION")),t=t.map(e=>(e.status===void 0||e.type==="PRESET_ACTION"&&(e.results=e.commands??e.results??[]),e)),t)};var LL={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 t=>t.map(e=>{if(e.type!=="AI_ACTION"||e.status!==void 0||!e.commands||!e.commands.length)return e;let r=e.commands,n=r[r.length-1];return n&&n.type!=="SUCCESS"&&r.push({type:"SUCCESS"}),e})};var n4=["target","fromTarget","toTarget"];function NL(t){for(let e of n4){if(t[e]===void 0)continue;let r=t[e];r.elementDescriptor!==void 0?r.type="description":t[e]={type:"description",elementDescriptor:""}}}var DL={name:"Migrate element target to discriminated union",fromVersion:"1.0.6",toVersion:"1.0.7",recursiveKeys:new Set(["results","steps"]),stopOnFailure:!0,execute:async t=>t.map(e=>{switch(e.type){case"PRESET_ACTION":return NL(e.command),e;case"AI_ACTION":{let r=e.commands;for(let n of r??[])NL(n);return e}default:return e}})};import{v4 as o4}from"uuid";var kL={name:"Ensure module steps have ids",fromVersion:"1.0.7",toVersion:"1.0.8",recursiveKeys:new Set(["results","steps"]),stopOnFailure:!0,execute:async t=>t.map(e=>{switch(e.type){case"MODULE":return e.id||(e.id=o4()),e;default:return e}})};import{v4 as FL}from"uuid";var UL={name:"Ensure module steps have ids",fromVersion:"1.0.8",toVersion:"1.0.9",recursiveKeys:new Set(["results","steps"]),stopOnFailure:!0,execute:async t=>t.map(e=>{switch(e.type){case"PRESET_ACTION":{if(!e.command)return e;let r=e.command;return r.id=r.id??FL(),e}case"AI_ACTION":return e.commands&&(e.steps=e.commands.map(r=>({type:"PRESET_ACTION",command:{...r,id:r.id??FL()}})),delete e.commands),e;default:return e}})};var BL={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 t=>t.map(e=>{switch(e.type){case"PRESET_ACTION":{if(!e.command)return e;let r=e.command;return typeof r.type!="string"||r.type!=="AI_WAIT"||(r.type="AI_ASSERTION",r.timeout||(r.timeout=10)),e}default:return e}})};import{v4 as i4}from"uuid";var zL={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 t=>t.map(e=>("id"in e&&typeof e.id=="string"||(e.id=i4()),e))};import{v4 as HL}from"uuid";var GL={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 t=>t.map(e=>{if("id"in e&&typeof e.id=="string")return e;if("condition"in e&&typeof e.condition=="object"&&e.condition){let r=e.condition;r.id||(r.id=HL())}return e.id=HL(),e})};var jL={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 t=>t.map(e=>{if(e.type!=="PRESET_ACTION")return e;let r=e.command;return!r||typeof r.envKey!="string"||(e.envKey=r.envKey,delete r.envKey),e})};import{v4 as a4}from"uuid";var VL={name:"Redo last two migrations",fromVersion:"1.0.13",toVersion:"1.0.14",recursiveKeys:new Set(["results","steps","blocks","elseSteps"]),stopOnFailure:!0,execute:async t=>t.map(e=>{if((!("id"in e)||typeof e.id!="string")&&(e.id=a4()),e.type!=="PRESET_ACTION")return e;let r=e.command;return!r||typeof r.envKey!="string"||(e.envKey=r.envKey,delete r.envKey),e})};var WL={name:"Migrate select choice",fromVersion:"1.0.14",toVersion:"1.0.15",recursiveKeys:new Set(["results","steps","blocks","elseSteps"]),stopOnFailure:!0,execute:async t=>t.map(e=>{if(e.type!=="PRESET_ACTION")return e;let r=e.command;return!r||r.type!=="SELECT_OPTION"||e.option===void 0||(e.choice={type:"VALUE",value:r.option},e.option=void 0),e})};var $L={name:"Migrate select choice",fromVersion:"1.0.15",toVersion:"1.0.16",recursiveKeys:new Set(["results","steps","blocks","elseSteps"]),stopOnFailure:!0,execute:async t=>t.map(e=>{if(e.type!=="PRESET_ACTION")return e;let r=e.command;return r&&qL(r),e})};function qL(t){t&&Object.keys(t).forEach(e=>{if(typeof t[e]=="object"&&t[e]){qL(t[e]);return}if(typeof t[e]!="string")return;let r=t[e];e==="code"?t[e]=r.replace(/inputs\./g,"env."):r.includes("{{")&&r.includes("}}")&&(t[e]=r.replace(/inputs\./g,"env."))})}var KL={name:"Migrate switch tab choice",fromVersion:"1.0.16",toVersion:"1.0.17",recursiveKeys:new Set(["results","steps","blocks","elseSteps"]),stopOnFailure:!0,execute:async t=>t.map(e=>{if(e.type!=="PRESET_ACTION")return e;let r=e.command;return!r||r.type!=="TAB"||r.url===void 0||(r.action={type:"SUBSTRING",substring:r.url},r.url=void 0),e})};var YL={name:"Remove press keys sequentially",fromVersion:"1.0.17",toVersion:"1.0.18",recursiveKeys:new Set(["results","steps","blocks","elseSteps"]),stopOnFailure:!1,execute:async t=>t.map(e=>{if(e.type!=="PRESET_ACTION")return e;let r=e.command;return!r||r.type!=="TYPE"?e:r.pressKeysSequentially===void 0?(r.delay=0,e):(r.pressKeysSequentially&&(r.pressKeysSequentially=void 0,r.delay=50),e)})};var XL={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 t=>t.map(e=>{if(e.type!=="PRESET_ACTION")return e;let r=e.command;return!r||r.type!=="WAIT_FOR_URL"||r.url===void 0||(r.matcher={type:"GLOB",glob:r.url},r.url=void 0),e})};var JL={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 t=>t.map(e=>{if(e.type!=="PRESET_ACTION")return e;let r=e.command;if(!r)return e;if(r.type==="SELECT_OPTION"){if(r.option===void 0)return e;r.choice={type:"VALUE",value:r.option},r.option=void 0}else if(r.type==="TAB"){if(r.url===void 0)return e;r.action={type:"SUBSTRING",substring:r.url},r.url=void 0}else if(r.type==="WAIT_FOR_URL"){if(r.url===void 0)return e;r.matcher={type:"GLOB",glob:r.url},r.url=void 0}else r.type==="AI_WAIT"&&(r.type="AI_ASSERTION",r.timeout||(r.timeout=10));return e})};var QL={name:"Migrate ",fromVersion:"1.0.20",toVersion:"1.0.21",recursiveKeys:new Set(["results","steps","blocks","elseSteps"]),stopOnFailure:!1,execute:async t=>t.map(e=>{if(e.type!=="PRESET_ACTION")return e;let r=e.command;return!r||r.type!=="MOCK_ROUTE"&&r.type!=="SET_HEADER"&&r.type!=="RECORD_REQUESTS"&&r.type!=="REGISTER_REQUEST_LISTENER"||(r.type==="REGISTER_REQUEST_LISTENER"||r.type==="RECORD_REQUESTS"?r.requestMatcher={urlMatcher:{type:"REGEX",regex:r.pattern}}:(r.type==="SET_HEADER"||r.type==="MOCK_ROUTE")&&r.urlPattern&&(r.requestMatcher={urlMatcher:{type:"REGEX",regex:r.urlPattern}})),e})};var ZL={name:"Migrate API request body types",fromVersion:"1.0.21",toVersion:"1.0.22",recursiveKeys:new Set(["results","steps","blocks","elseSteps"]),stopOnFailure:!1,execute:async t=>t.map(e=>{if(e.type!=="PRESET_ACTION")return e;let r=e.command;if(!r||r.type!=="REQUEST")return e;let n=typeof r.body=="string"&&r.body.length>0?{type:"json",content:r.body}:void 0;return r.body=n,e})};var eN={name:"Migrate AI checks to preset actions",fromVersion:"1.0.0",toVersion:"1.0.1",recursiveKeys:new Set,execute:async t=>t.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 fh=new Set(["CLICK","TYPE","SELECT_OPTION"]),tN={name:"Migrate element descriptor to live in a target object",fromVersion:"1.0.3",toVersion:"1.0.4",recursiveKeys:new Set,execute:async t=>t.map(e=>{let r=e.command,n=r?.type,o=r?.elementDescriptor;return(o!==void 0||fh.has(n))&&(r.target={elementDescriptor:o??""}),e.commands&&Array.isArray(e.commands)&&e.commands.forEach(a=>{let s=a?.elementDescriptor,c=a?.type;(s!==void 0||fh.has(c))&&(a.target={elementDescriptor:s??""})}),e.results&&Array.isArray(e.results)&&e.results.forEach(a=>{let s=a.command,c=s?.elementDescriptor,l=s?.type;(c!==void 0||fh.has(l))&&(s.target={elementDescriptor:c??""}),a.commands&&Array.isArray(a.commands)&&a.commands.forEach(d=>{let p=d?.elementDescriptor,m=d?.type;(p!==void 0||fh.has(m))&&(d.target={elementDescriptor:p??""})})}),e}),stopOnFailure:!0};var rN={name:"Migrate FAILURE status to FAILED",fromVersion:"1.0.1",toVersion:"1.0.2",recursiveKeys:new Set,execute:async t=>t.map(e=>{let r=e;return r.status==="FAILURE"&&(r.status="FAILED"),typeof r.commands=="object"&&Array.isArray(r.commands)&&r.commands.forEach(n=>{if(n&&typeof n=="object"){let o=n;o?.status==="FAILURE"&&(o.status="FAILED")}}),r}),stopOnFailure:!0};var nN={name:"Migrate preset step types to use the same",fromVersion:"1.0.2",toVersion:"1.0.3",recursiveKeys:new Set,execute:async t=>t.map(e=>{let r=e.command,n=r?.type;return n?.startsWith("PRESET_")&&(r.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,s=a?.type;s?.startsWith("PRESET_")&&(a.type=s.slice(7)),i.commands&&Array.isArray(i.commands)&&i.commands.forEach(l=>{let u=l.type;u?.startsWith("PRESET_")&&(l.type=u.slice(7))})}),e}),stopOnFailure:!0};var oN=[eN,rN,nN,tN,OL,LL,DL,kL,UL,BL,zL,GL,jL,VL,WL,$L,KL,YL,XL,JL,QL,ZL];ph(De,oN);async function fc({metadata:t,steps:e,logger:r,toVersion:n}){return await KT({metadata:t,steps:e,logger:r,toVersion:n,migrations:oN})}import sBe from"zod";import{diff as pBe}from"deep-object-diff";import{cloneDeep as fBe}from"lodash-es";import{v4 as NBe}from"uuid";import{cloneDeep as c4}from"lodash-es";import pN from"truncate-json";import{v4 as sN}from"uuid";import{cloneDeep as uze,unset as dze}from"lodash-es";function iN(t){switch(t.type){case"AI_ACTION":return`AI action: ${vt(t.text,100)}`;case"AI_ACTION_DYNAMIC":return`AI action: ${vt(t.text,100)}`;case"PRESET_ACTION":return bi(t.command);case"MODULE":return`Module ${t.moduleName??t.id}`;case"CONDITIONAL":return"Conditional step";case"SECTION":return`Section ${t.description?`with goal: ${vt(t.description,100)}`:""}`;default:return(r=>{throw new Error("You missed a case in the switch above")})(t)}}function Kn(t){switch(t.type){case"AI_ACTION":return`AI action: ${vt(t.text,100)}`;case"AI_ACTION_DYNAMIC":return`AI action: ${vt(t.text,100)}`;case"PRESET_ACTION":return bi(t.command);case"MODULE":return`Module: ${t.id}`;case"RESOLVED_MODULE":return`Module: ${t.name}`;case"CONDITIONAL":return"Conditional step";case"SECTION":return`Section${t.description?`with goal: ${vt(t.description,100)}`:""}`;default:return(r=>{throw new Error("You missed a case in the switch above")})(t)}}function hc(t,e){return t.split(`
|
|
59
59
|
`).map(r=>" ".repeat(e)+r).join(`
|
|
60
60
|
`)}function YT(t){switch(t.type){case"AI_ACTION":case"AI_ACTION_DYNAMIC":{let e="results"in t&&Array.isArray(t.results)?t.results.length:0;return`AI action: ${t.text}
|
|
61
61
|
${hc(`Number of sub-steps: ${e}`,2)}`}case"PRESET_ACTION":return bi(t.command,!1);case"MODULE":{let e="results"in t&&Array.isArray(t.results)?t.results.length:0,r=[`Module: ${t.id}`];if("moduleName"in t){let n=t.moduleName;r.push(`Module Name: ${n}`)}return r.push(hc(`Number of sub-steps: ${e}`,2)),r.join(`
|
|
62
62
|
`)}case"RESOLVED_MODULE":return`Module: ${t.name}`;case"CONDITIONAL":{let e=["Conditional step"];if("assertionResult"in t&&t.assertionResult&&(e.push(hc("Conditional check:",2)),e.push(hc(YT(t.assertionResult),2))),"results"in t&&Array.isArray(t.results)){let r=t.results.length,n="assertionResult"in t&&t.assertionResult?"Branch steps":"Else branch steps";e.push(hc(`${n}: ${r}`,2))}return e.join(`
|
|
63
63
|
`)}case"SECTION":{let e="results"in t&&Array.isArray(t.results)?t.results.length:0;return`Section${t.description?`with goal: ${t.description}`:""}
|
|
64
64
|
${hc(`Number of sub-steps: ${e}`,2)}`}default:return(r=>{throw new Error("You missed a case in the switch above")})(t)}}function aN(t){switch(t.type){case"AI_ACTION":return t;case"AI_ACTION_DYNAMIC":return t;case"PRESET_ACTION":return t;case"MODULE":return t;case"RESOLVED_MODULE":return{...t,steps:void 0};case"CONDITIONAL":return{...t,blocks:t.blocks.map(e=>({...e,steps:void 0})),elseSteps:void 0};case"SECTION":return{...t,steps:void 0};default:return(r=>{throw new Error("You missed a case in the switch above")})(t)}}var lN=1e3,cN=5e7,u4="[FAILED]";async function uN(t,e,r,n="image/jpeg"){if(r){let o=await e.getScreenshot(t,r);if(o)return`data:${n};base64,${Buffer.from(o).toString("base64")}`}}function d4(t,e){let r=(()=>{switch(t.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")})(t)}})();return mN(t)?t.message||"Section start placeholder":(o=>e?`${e==="start"?"Start":"End"} of ${r}
|
|
65
|
-
${o}`:o)(YT(t))}function p4(t,{unflattenedIndex:e,parentStep:r}){if(!(e===void 0||mN(t))){if(r){let n=`sub-step ${e}`;switch(r.type){case"MODULE":return`${n} within module '${r.moduleName??r.id}'`;case"AI_ACTION":case"AI_ACTION_DYNAMIC":return`${n} within AI action`;case"CONDITIONAL":return`${n} within conditional step`;default:return n}}return`step ${e}`}}function mN(t){return t.type==="PRESET_ACTION"&&t.command?.type==="SUCCESS"&&!!t.message?.match(/^Starting the [\w- ]+ section$/)}function gh(t,e={}){let r=e.followingStepStart??e.precedingStepEnd??new Date;return{type:"PRESET_ACTION",id:sN(),message:`Starting the ${t.replace(/-/g," ")} section`,startedAt:r,finishedAt:r,status:"SUCCESS",command:{id:sN(),type:"SUCCESS"},results:[]}}function hh(t,e={}){let{index:r,includeDomState:n=!1,header:o,unflattenedIndex:i,parentStep:a,includeUserFacingStepReference:s}=e,c=d4(t,o),l;t.type==="PRESET_ACTION"&&(l=t.results?.[0]?.elementInteracted);let u=t.message!=="Successfully executed preset action."?t.message:void 0,d=c;t.status==="FAILED"&&(d=`${u4} ${d}`);let p={description:d,startedAt:t.startedAt.toISOString(),finishedAt:t.finishedAt.toISOString(),beforeUrl:t.beforeUrl,afterUrl:t.afterUrl,beforeSnapshot:t.beforeSnapshot,afterSnapshot:t.afterSnapshot,elementInteracted:l,message:u,index:r};if(s&&(p.userFacingStepReference=p4(t,{parentStep:a,unflattenedIndex:i})),t.status==="FAILED"&&n)try{let m=hw.array().parse(t.details);for(let f of m)"pageState"in f&&(p.pageState=f.pageState)}catch{}return p}async function fN(t,e,r,{addIndices:n=!0,includeDomState:o=!1,flatten:i=!0,maxItemsFromEnd:a=15,indexOffset:s=0,isTopLevelResultList:c=!0,includeUserFacingStepReference:l,parentStep:u}){let d,p=[];for(let m=0;m<r.length;m++){let f=r[m],h=n?m+s:void 0,S=c?m-1:m;switch(f.type){case"PRESET_ACTION":{p.push(hh(f,{index:h,includeDomState:o,includeUserFacingStepReference:l,header:void 0,unflattenedIndex:S,parentStep:u})),f.status==="FAILED"&&(d=h);break}case"CONDITIONAL":case"AI_ACTION":case"AI_ACTION_DYNAMIC":case"MODULE":case"SECTION":{if(i){p.push(hh(f,{index:n?h:void 0,includeDomState:o,includeUserFacingStepReference:l,header:"start",unflattenedIndex:S,parentStep:u})),s+=1;let{failureIndex:g,results:E}=await fN(t,e,f.results,{addIndices:n,includeDomState:o,includeUserFacingStepReference:l,flatten:i,maxItemsFromEnd:a,indexOffset:s+m,isTopLevelResultList:!1,parentStep:f});p.push(...E),g!==void 0?d=g:f.status==="FAILED"&&(d=h),s+=E.length,p.push(hh(f,{index:n?s+m:void 0,includeDomState:o,includeUserFacingStepReference:l,parentStep:u,header:"end"}))}else p.push(hh(f,{index:n?s+m:void 0,includeDomState:o,includeUserFacingStepReference:l,parentStep:u,header:void 0}));break}default:return(E=>{throw new Error("You missed a case in the switch above")})(f)}}return{results:p,failureIndex:d}}async function gc(t,e,r,{numStepsWithScreenshots:n=5,addIndices:o=!0,includeBeforeScreenshots:i=!1,screenshotMediaType:a="image/jpeg",includeDomState:s=!1,includeUserFacingStepReference:c,flatten:l=!0,maxItemsFromEnd:u=20}){let d=await fN(t,e,r,{addIndices:o,includeUserFacingStepReference:c,includeDomState:s,flatten:l,maxItemsFromEnd:u,indexOffset:0}),{results:p}=d,{failureIndex:m}=d;m!==void 0&&p.length>0&&(p=p.slice(0,m+1));let f=[],h=0;if(u!==void 0&&p.length>u&&(h=p.length-u),m!==void 0&&m<p.length-1&&t.warn({failureIndex:m,flattenedResultsLength:p.length,lastIndex:p.length-1,isLastIndex:m===p.length-1,offset:h},"PROCESS_RESULTS_FOR_LLM: Failure index check - should not be possible"),m!==void 0&&h>m)throw new Error("Failure index is out of bounds");for(let S=h;S<p.length;S++){let g=p[S],E={description:g.description,startedAt:g.startedAt,finishedAt:g.finishedAt,beforeUrl:g.beforeUrl,afterUrl:g.afterUrl,elementInteracted:g.elementInteracted,userFacingStepReference:g.userFacingStepReference,message:g.message,pageState:g.pageState,index:g.index},y,b;(n===void 0||n>0&&S>=p.length-n)&&(g.afterSnapshot&&(b=await uN(t,e,g.afterSnapshot,a)),i&&g.beforeSnapshot&&(y=await uN(t,e,g.beforeSnapshot,a))),E.beforeScreenshot=y,E.afterScreenshot=b,f.push(E)}return{results:f,failureIndex:m!==void 0?m-h:void 0}}function Gd({json:t,keysToRedact:e,maxJsonStringSize:r}){try{if(!t)return t;if(typeof t=="string")return vt(t,r??2e4);if(typeof t=="object"){let{jsonString:n}=pN(JSON.stringify(t,(o,i)=>e?.includes(o)||typeof i=="string"&&i.length>3e4?"REDACTED":i),r??2e4);return JSON.parse(n)}return t}catch{return t}}function XT(t,e){for(let r=0;r<t.length;r++){let n=t[r];try{if(n.data){let{jsonString:o}=pN(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":dN(n);break;case"CONDITIONAL":n.assertionResult&&dN(n.assertionResult),XT(n.results,e);break;case"AI_ACTION_DYNAMIC":case"AI_ACTION":case"MODULE":case"SECTION":{XT(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 dN(t){let e=t.command;"cache"in e&&e.cache&&(e.cache=void 0)}function Sh(t,e){let r=c4(t);if(XT(r,e),r.length>lN)return e.warn("Results too long, truncating before insertion"),r.slice(r.length-lN,r.length);let n=JSON.stringify(r);if(n.length>cN)for(e.warn({serializedLength:n.length,resultsArrayLength:r.length},"Database content violation: results too large, truncating before insertion");n.length>cN;)r.splice(0,1),n=JSON.stringify(r);try{return mr.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 Mze}from"lodash-es";import{diff as m1e}from"deep-object-diff";import{diff as SN}from"deep-object-diff";import{cloneDeep as hN}from"lodash-es";import{v4 as JT}from"uuid";async function Ft(t){let e=new Map,r=new Set,n=Wi.parse({steps:t.stepLists.steps??[],beforeSteps:t.stepLists.beforeSteps??void 0,afterSteps:t.stepLists.afterSteps??void 0}),o=hN(n.steps),i=await bs({...t,steps:o,moduleStepParents:[],moduleIdParents:[],moduleIdReplacements:e,seenModules:r}),a={stepsToSave:{steps:i.stepsToSave,beforeSteps:void 0,afterSteps:void 0},cachesToSave:i.cachesToSave,moduleUpdates:i.moduleUpdates};for(let s of["beforeSteps","afterSteps"]){let c=hN(n[s]);if(!c)continue;let l=await bs({...t,steps:c,moduleStepParents:[],moduleIdParents:[],moduleIdReplacements:e,seenModules:r});a.cachesToSave.push(...l.cachesToSave),a.moduleUpdates.push(...l.moduleUpdates),a.stepsToSave[s]=l.stepsToSave}return a}async function bs({steps:t,...e}){let{seenModules:r,cacheCreationParams:n,moduleIdParents:o,moduleStepParents:i,moduleIdReplacements:a,shouldCreateNewModuleId:s,createNewCacheIds:c}=e,l={cachesToSave:[],stepsToSave:[],moduleUpdates:[]};for(let u of t)switch(delete u.index,delete u.aiSuggested,u.id=c?JT():u.id,u.type){case"PRESET_ACTION":{let p=u.command;l.cachesToSave=l.cachesToSave.concat(gN({...e,command:p})),l.stepsToSave.push({...u,command:p});break}case"RESOLVED_MODULE":{let p=c?JT():u.id,m=u.moduleId;a.has(m)?m=a.get(m):s!==void 0&&(m=await s(u),a.set(u.moduleId,m));let{cachesToSave:f,stepsToSave:h,moduleUpdates:S}=await bs({...e,steps:u.steps,cacheCreationParams:n?{...n}:void 0,createNewCacheIds:!1,moduleStepParents:[...i,p],moduleIdParents:[...o,m],skipCacheIntermediateEntries:c});l.moduleUpdates=l.moduleUpdates.concat(S),l.cachesToSave=l.cachesToSave.concat(f),r.has(m)||(r.add(m),l.moduleUpdates.push({...tn.parse(u),steps:bt.array().parse(h),moduleId:m}));let g=ho.parse({...u,type:"MODULE",moduleId:m,inputs:u.inputs,id:p,skipped:u.skipped,cacheConfig:u.cacheConfig,envKey:u.envKey});l.stepsToSave.push(g);break}case"AI_ACTION":{if(!u.steps){l.stepsToSave.push(u);break}let{stepsToSave:p,cachesToSave:m}=await bs({...e,steps:u.steps});try{u.steps=hn.array().parse(p)}catch(f){throw new Error(`Only preset actions are allowed in AI actions at the moment: ${f}`)}l.stepsToSave.push(u),l.cachesToSave=l.cachesToSave.concat(m);break}case"AI_ACTION_DYNAMIC":{l.stepsToSave.push(u);break}case"CONDITIONAL":{let p=[];for(let f of u.blocks){l.cachesToSave=l.cachesToSave.concat(gN({...e,command:f.assertion.command}));let{stepsToSave:h,cachesToSave:S,moduleUpdates:g}=await bs({...e,steps:f.steps});p.push({...f,steps:h}),l.cachesToSave=l.cachesToSave.concat(S),l.moduleUpdates=l.moduleUpdates.concat(g)}let m={...u,elseSteps:void 0,blocks:p};if(u.elseSteps){let{stepsToSave:f,cachesToSave:h,moduleUpdates:S}=await bs({...e,steps:u.elseSteps});m.elseSteps=f,l.cachesToSave=l.cachesToSave.concat(h),l.moduleUpdates=l.moduleUpdates.concat(S)}l.stepsToSave.push(m);break}case"SECTION":{let{stepsToSave:p,cachesToSave:m,moduleUpdates:f}=await bs({...e,steps:u.steps}),h={...u,steps:p};l.moduleUpdates=l.moduleUpdates.concat(f),l.stepsToSave.push(h),l.cachesToSave=l.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 l}function gN({command:t,cacheCreationParams:e,createNewCacheIds:r,moduleIdParents:n,moduleStepParents:o}){let i=[];if(t.id=r?JT():t.id,"cache"in t&&t.cache){if(e){let a=GT({id:t.id,orgId:e.orgId,testId:e.testId,environment:e.environment,value:po.parse(t),moduleIdParents:n,moduleStepParents:o});a&&i.push(a)}delete t.cache}return t.thoughts&&delete t.thoughts,i}async function vs({logger:t,cacheStorage:e,orgId:r,testId:n,environment:o,originalStepsWithCaches:i,updatedStepsWithCaches:a}){let s=SN(i,a);if(Object.keys(s).length!==0){t.debug("Updating step caches post-success");try{let{cachesToSave:c}=await Ft({stepLists:a,cacheCreationParams:{testId:n,orgId:r,environment:o}});await e.saveStepCacheEntries({logger:t,entries:c})}catch(c){t.error({err:c},"Failed to save step caches after successful execution. This is not critical, but can impact future performance.")}}}async function Sc({logger:t,cacheStorage:e,orgId:r,testId:n,environment:o,originalStepsWithCaches:i,updatedStepsWithCaches:a}){let s=SN(i,a);if(Object.keys(s).length===0)return;t.debug("Updating memory post-run failure");let c={};for(let d of["steps","beforeSteps","afterSteps"]){let p=i[d];if(!p||!p.length)continue;let m=RL({logger:t,steps:p});for(let[f,h]of Object.entries(m))c[f]=h}let{cachesToSave:l}=await Ft({stepLists:a,cacheCreationParams:{testId:n,orgId:r,environment:o}});t.debug({newEntries:l.length,originalCaches:Object.keys(c).length},"Comparing caches for memory pruning");let u=wL({newEntries:l,originalCachesMap:c});if(u.length){t.debug({prunedCaches:u.map(d=>({key:d.key,value:d.value.type}))},"Saving pruned memory post-failure");try{await e.saveStepCacheEntries({logger:t,entries:u})}catch(d){t.error({err:d},"Failed to save memory after failed execution. This is not critical, but can impact future performance.")}}}function yN(t,e){if(!(!t.envs||!t.envs.length)){for(let r of t.envs){let n=r;e in r&&(n[e]&&(r.default=!0),delete n.defaultOnCloud,delete n.defaultOnLocal)}t.envs.some(r=>r.default)||(t.envs[0].default=!0)}}import{cloneDeep as EN}from"lodash-es";import{z as m4}from"zod";async function TN({rawSteps:t,metadata:e,logger:r,callbacks:n}){yN(e,"defaultOnCloud");let o={},{resolvedSteps:i,newSchemaVersion:a}=await yh({rawSteps:t.steps,migrationMetadata:e,logger:r,callbacks:n,resolvedModuleCache:o}),s={...e,steps:i,schemaVersion:a};for(let c of["beforeSteps","afterSteps"]){let l=t[c];if(!l)continue;let{resolvedSteps:u}=await yh({rawSteps:l,migrationMetadata:e,logger:r,callbacks:n,resolvedModuleCache:o});s[c]=u}return{resolvedTest:s,moduleIds:Array.from(Object.keys(o))}}async function As(t,e,r){let{newVersion:n,steps:o}=await fc({metadata:t,steps:e,logger:r});try{return{steps:bt.array().parse(o),newVersion:n}}catch(i){throw i instanceof m4.ZodError?(r.warn({type:"zod",zodIssues:i.issues,newVersion:n,id:t.id},"Failed to parse test steps while migrating test"),new Ha("Failed to parse test steps while migrating test",t.id,"entity",i.issues,{cause:i})):(r.warn({err:i,newVersion:n,id:t.id},"Failed to parse test steps while migrating test"),new du(`Failed to parse test steps while migrating test: ${i}`,t.id,"entity",{cause:i}))}}async function yh({rawSteps:t,migrationMetadata:e,logger:r,callbacks:n,resolvedModuleCache:o={}}){let{newVersion:i,steps:a}=await As(e,t,r),s=[];for(let c of a)s.push(await jd({step:c,callbacks:n,logger:r,resolvedModuleCache:o}));return{resolvedSteps:s,newSchemaVersion:i}}async function jd({step:t,callbacks:e,logger:r,resolvedModuleCache:n}){switch(t.type){case"AI_ACTION":return t;case"AI_ACTION_DYNAMIC":return t;case"PRESET_ACTION":return t;case"MODULE":{let c=t.moduleId,l=n[c];if(l)return{...EN(l),...t,type:"RESOLVED_MODULE"};let u=await e.onFetchModule({id:c,logger:r});if(!u)throw new Error(`Could not find module with id ${c}`);let{newVersion:d,steps:p}=await fc({metadata:{id:c,schemaVersion:u.schemaVersion},steps:u.steps,logger:r}),m;try{m=bt.array().parse(p)}catch(S){throw r.warn({type:"zod",err:S,steps:p,newVersion:d,id:c},"Module failed to parse"),S}let f;try{f=await Promise.all(m.map(S=>jd({step:S,callbacks:e,logger:r,resolvedModuleCache:n})))}catch(S){throw r.warn({err:S,...t},`Failed to recursively resolve module '${u.name}': ${S}`),S}let h={...u,steps:f};return n[c]=EN(h),{...h,...t,type:"RESOLVED_MODULE"}}case"CONDITIONAL":let o=[];for(let c of t.blocks){let l=[];for(let u of c.steps)l.push(await jd({step:u,callbacks:e,logger:r,resolvedModuleCache:n}));o.push({...c,steps:l})}let i;if(t.elseSteps){i=[];for(let c of t.elseSteps)i.push(await jd({step:c,callbacks:e,logger:r,resolvedModuleCache:n}))}return{...t,blocks:o,elseSteps:i};case"SECTION":let a=[];for(let c of t.steps)a.push(await jd({step:c,callbacks:e,logger:r,resolvedModuleCache:n}));return{...t,steps:a};default:return(c=>{throw"If Typescript complains about the line below, you missed a case or break in the switch above"})(t)}}import{cloneDeep as f4}from"lodash-es";import{stringify as bN}from"yaml";async function vN({test:t,processedModuleNames:e=new Set,createNewCacheIds:r=!1}){let n={id:t.id,name:t.name,description:t.description,baseUrl:t.baseUrl,schemaVersion:t.schemaVersion,advanced:t.advanced,retries:t.retries,envs:t.envs,disabled:t.disabled,labels:t.labels},o={},i=await h4({originalStepLists:{steps:t.steps,beforeSteps:t.beforeSteps,afterSteps:t.afterSteps},modules:o,processedModuleNames:e,createNewCacheIds:r}),a={fileType:ye.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:bN(a),modules:o}}async function h4({originalStepLists:t,modules:e,processedModuleNames:r,createNewCacheIds:n}){let o=f4(t);Object.values(o).forEach(s=>{g4(s??[])});let{stepsToSave:i,moduleUpdates:a}=await Ft({stepLists:o,createNewCacheIds:n});for(let s of a)r.has(s.name)||(e[s.name]=S4(s),r.add(s.name));return i}function g4(t){ln({steps:t,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 S4(t){let e=tn.parse(t),r={fileType:ye.MODULE,...e,schemaVersion:De,steps:t.steps};return bN(r)}async function Vd({promiseGenerator:t,signal:e,codePath:r,logger:n}){let i=Date.now(),a=setInterval(()=>{if(e?.aborted){clearInterval(a);return}n?.warn({codePath:r,startTime:i,elapsedMilliseconds:Date.now()-i},`Asynchronous operation is taking a long time (${r})`)},5e3);return new Promise((s,c)=>{function l(){clearInterval(a),e?.removeEventListener("abort",l),c(e?.reason)}if(e?.aborted){c(e?.reason),clearInterval(a);return}e?.addEventListener("abort",l,{once:!0}),(async()=>{try{s(await t())}catch(u){c(u)}finally{clearInterval(a),e?.removeEventListener("abort",l)}})()})}async function Wd({promiseGenerator:t,timeoutMs:e,codePath:r,logger:n,signal:o}){let i=!1,a=new AbortController,s=()=>{a.abort()},c=setTimeout(()=>{o?.removeEventListener("abort",s),!i&&a.abort()},e);o?.addEventListener("abort",s,{once:!0});try{return await Vd({promiseGenerator:t,signal:a.signal,codePath:r,logger:n})}finally{i=!0,o?.removeEventListener("abort",s),clearTimeout(c)}}function AN(t,e){let r=Math.max(1,e),n=t/r;return Math.max(n,1e3)}function Eh(t){let e=[];for(let r of t)switch(r.type){case"PRESET_ACTION":case"AI_ACTION":case"AI_ACTION_DYNAMIC":e.push(r);break;case"RESOLVED_MODULE":{let n={...r,type:"MODULE"};e.push(ho.parse(n));break}case"SECTION":{let n={...r,steps:Eh(r.steps)};e.push(bt.parse(n));break}case"CONDITIONAL":{let n={...r,blocks:r.blocks.map(o=>({assertion:o.assertion,steps:Eh(o.steps)})),elseSteps:r.elseSteps?Eh(r.elseSteps):void 0};e.push(ja.parse(n));break}default:return(o=>{throw"If Typescript complains about the line below, you missed a case or break in the switch above"})(r)}return e}function Th(t){return Eh([t])[0]}import y4 from"picomatch";var bh=(t,e,r)=>{r?.caseInsensitive&&(t=t.toLowerCase());let n;switch(e.type){case"SUBSTRING":{let o=r?.caseInsensitive?e.url.toLowerCase():e.url;n=t.includes(o);break}case"GLOB":{let o=r?.caseInsensitive?e.glob.toLowerCase():e.glob;n=t===e.glob||y4(o)(t);break}case"REGEX":{n=new RegExp(e.regex).test(t);break}case"DOMAIN":{let o=r?.caseInsensitive?e.domain.toLowerCase():e.domain;n=new URL(t).hostname===o;break}}return r?.negated?!n:n},vh=(t,e)=>{try{let{hostname:r,pathname:n}=new URL(t),{hostname:o,pathname:i}=new URL(e);return r!==o||n!==i}catch{return!1}},yc=t=>{try{return new URL(t),!0}catch{return!1}},CN=t=>!t.toLowerCase().startsWith("http"),Ec=(t,e)=>{try{return new URL(t,e),!0}catch{return!1}};function Cs(t,e){try{return!!new URL(t).origin.trim()}catch(r){return e?.warn({url:t,err:r},"Invalid URL in check"),!1}}async function E4(t){let{logger:e,browserStateStorage:r,generator:n,results:o,error:i,maxItemsFromEnd:a,numStepsWithScreenshots:s,disableCache:c}=t,l=[];if(o.length>0){let{results:d}=await gc(e,r,o,{numStepsWithScreenshots:s,addIndices:!1,includeUserFacingStepReference:!0,maxItemsFromEnd:a,includeBeforeScreenshots:!0,includeContainerTagsInDescription:!0});l=d}return await n.getTestResultClassification({results:l,errorMessage:i.message,errorStack:i.stack},{disableCache:c??!1,loggerTags:ot(e)})}async function RN(t){let{logger:e,browserStateStorage:r,generator:n,fullResults:o,failureReason:i,error:a,maxItemsFromEnd:s,numStepsWithScreenshots:c,disableCache:l}=t,u=o?.results??[];if(i==="SetupFailureError"){let d=(o?.beforeResults??[]).at(0);u=[gh("setup",{followingStepStart:d?.startedAt}),...o?.beforeResults??[]]}else if(i==="TeardownFailureError"){let d=u.at(-1),p=(o?.afterResults??[])[0],m=gh("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=gh("main-test-body",{precedingStepEnd:d?.finishedAt,followingStepStart:p?.startedAt});u=[...o?.beforeResults??[],m,...u]}if(!r||!u||u.length===0)return{};try{let d=await E4({logger:e,browserStateStorage:r,generator:n,results:u,error:a,maxItemsFromEnd:s,numStepsWithScreenshots:c,disableCache:l});return{classification:d,aiFailureReason:d.reason}}catch(d){return e.error({err:d},"Failed to classify test result"),{}}}function wN(t,e,r){let{organizationId:n="local",runKey:o=e,createdBy:i="local-user",runGroupMetadata:a,runAttempts:s=[]}=r??{},c=t.trigger===rn.CLI;return{id:e,runKey:o,organizationId:n,executionType:t.executionType,createdAt:t.startedAt??new Date,createdBy:i,flake:t.flake??null,scheduledAt:null,startedAt:t.startedAt??null,updatedAt:t.finishedAt??null,finishedAt:t.finishedAt??null,resolvedBaseUrl:t.resolvedBaseUrl??null,environmentName:t.environmentName??null,gitBranchName:a?.gitBranchName??null,githubRepository:a?.githubRepository??null,gitlabProjectPath:a?.gitlabProjectPath??null,labels:t.labels??[],gitOriginUrl:a?.gitOriginUrl??null,gitCommitSha:a?.gitCommitSha??null,gitCommitShaShort:a?.gitCommitShaShort??null,gitCommitAuthorName:a?.gitCommitAuthorName??null,cliVersion:t.cliVersion??a?.cliVersion??null,status:t.status,trigger:t.trigger,attempts:t.attempts,runAttempts:s,videos:[],failureReason:t.failureReason??null,failureDetails:t.failureDetails??null,failureRecoveryDetails:t.failureRecoveryDetails??null,pipelineId:a?.pipelineId??null,resolvedInputs:t.resolvedInputs??null,quarantined:t.quarantined??!1,quarantinedReason:t.quarantinedReason??null,...c?{localTestId:t.testId??null,testName:t.testName??t.testDescription??null,test:null}:{testId:t.testId??null,test:t.testId?{id:t.testId,name:t.testName??t.testDescription??"Unknown Test"}:null},description:t.testDescription??null,suiteId:void 0,aiSettings:t.aiSettings??void 0}}import{v4 as xN}from"uuid";function QT(t,e){return{...t,testId:e?.testId??"",testName:e?.testName??"",suiteId:e?.suiteId??"",suiteName:e?.suiteName??""}}var Ah=class{reporter;asyncWork;metadata;creditsUsedV1=0;creditsUsedV2=0;constructor({logger:e,reporter:r,runType:n,runId:o,testMetadata:i,suiteMetadata:a}){this.reporter=r,this.metadata={testId:i.id,testName:i.name,suiteId:a?.id,suiteName:a?.name},this.asyncWork=[r.reportBillableEvents(e,[{event:n,timestamp:new Date().toISOString(),transactionId:o,properties:QT({},this.metadata)}]).catch(s=>e.error({err:s},"Failed to report billable event"))]}trackStepExecution(e){if(Lx(e.type)){this.creditsUsedV2+=1;return}let r=Ky(e.type);if(this.creditsUsedV1+=r??0,e.type==="PRESET_ACTION"){this.creditsUsedV2+=1;let n=Yy(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:xN(),properties:QT({creditsUsed:this.creditsUsedV1},this.metadata)}]).catch(r=>e.error({err:r},"Failed to report credits used"))),this.creditsUsedV2>0&&this.asyncWork.push(this.reporter.reportBillableEvents(e,[{event:"credits-used-v2",timestamp:new Date().toISOString(),transactionId:xN(),properties:QT({creditsUsed:this.creditsUsedV2},this.metadata)}]).catch(r=>e.error({err:r},"Failed to report credits used"))),await Promise.allSettled(this.asyncWork)}};import{cloneDeep as T4}from"lodash-es";function Ch(t,e){if(t.length===0)return`${e}: (no steps)`;let r=tb(t,{includeCache:!0});r.forEach((o,i)=>{let a=o;a.index=i});let n=["```json",JSON.stringify(r,null,2),"```"].join(`
|
|
65
|
+
${o}`:o)(YT(t))}function p4(t,{unflattenedIndex:e,parentStep:r}){if(!(e===void 0||mN(t))){if(r){let n=`sub-step ${e}`;switch(r.type){case"MODULE":return`${n} within module '${r.moduleName??r.id}'`;case"AI_ACTION":case"AI_ACTION_DYNAMIC":return`${n} within AI action`;case"CONDITIONAL":return`${n} within conditional step`;default:return n}}return`step ${e}`}}function mN(t){return t.type==="PRESET_ACTION"&&t.command?.type==="SUCCESS"&&!!t.message?.match(/^Starting the [\w- ]+ section$/)}function gh(t,e={}){let r=e.followingStepStart??e.precedingStepEnd??new Date;return{type:"PRESET_ACTION",id:sN(),message:`Starting the ${t.replace(/-/g," ")} section`,startedAt:r,finishedAt:r,status:"SUCCESS",command:{id:sN(),type:"SUCCESS"},results:[]}}function hh(t,e={}){let{index:r,includeDomState:n=!1,header:o,unflattenedIndex:i,parentStep:a,includeUserFacingStepReference:s}=e,c=d4(t,o),l;t.type==="PRESET_ACTION"&&(l=t.results?.[0]?.elementInteracted);let u=t.message!=="Successfully executed preset action."?t.message:void 0,d=c;t.status==="FAILED"&&(d=`${u4} ${d}`);let p={description:d,startedAt:t.startedAt.toISOString(),finishedAt:t.finishedAt.toISOString(),beforeUrl:t.beforeUrl,afterUrl:t.afterUrl,beforeSnapshot:t.beforeSnapshot,afterSnapshot:t.afterSnapshot,elementInteracted:l,message:u,index:r};if(s&&(p.userFacingStepReference=p4(t,{parentStep:a,unflattenedIndex:i})),t.status==="FAILED"&&n)try{let m=hw.array().parse(t.details);for(let f of m)"pageState"in f&&(p.pageState=f.pageState)}catch{}return p}async function fN(t,e,r,{addIndices:n=!0,includeDomState:o=!1,flatten:i=!0,maxItemsFromEnd:a=15,indexOffset:s=0,isTopLevelResultList:c=!0,includeUserFacingStepReference:l,parentStep:u}){let d,p=[];for(let m=0;m<r.length;m++){let f=r[m],h=n?m+s:void 0,S=c?m-1:m;switch(f.type){case"PRESET_ACTION":{p.push(hh(f,{index:h,includeDomState:o,includeUserFacingStepReference:l,header:void 0,unflattenedIndex:S,parentStep:u})),f.status==="FAILED"&&(d=h);break}case"CONDITIONAL":case"AI_ACTION":case"AI_ACTION_DYNAMIC":case"MODULE":case"SECTION":{if(i){p.push(hh(f,{index:n?h:void 0,includeDomState:o,includeUserFacingStepReference:l,header:"start",unflattenedIndex:S,parentStep:u})),s+=1;let{failureIndex:g,results:E}=await fN(t,e,f.results,{addIndices:n,includeDomState:o,includeUserFacingStepReference:l,flatten:i,maxItemsFromEnd:a,indexOffset:s+m,isTopLevelResultList:!1,parentStep:f});p.push(...E),g!==void 0?d=g:f.status==="FAILED"&&(d=h),s+=E.length,p.push(hh(f,{index:n?s+m:void 0,includeDomState:o,includeUserFacingStepReference:l,parentStep:u,header:"end"}))}else p.push(hh(f,{index:n?s+m:void 0,includeDomState:o,includeUserFacingStepReference:l,parentStep:u,header:void 0}));break}default:return(E=>{throw new Error("You missed a case in the switch above")})(f)}}return{results:p,failureIndex:d}}async function gc(t,e,r,{numStepsWithScreenshots:n=5,addIndices:o=!0,includeBeforeScreenshots:i=!1,screenshotMediaType:a="image/jpeg",includeDomState:s=!1,includeUserFacingStepReference:c,flatten:l=!0,maxItemsFromEnd:u=20}){let d=await fN(t,e,r,{addIndices:o,includeUserFacingStepReference:c,includeDomState:s,flatten:l,maxItemsFromEnd:u,indexOffset:0}),{results:p}=d,{failureIndex:m}=d;m!==void 0&&p.length>0&&(p=p.slice(0,m+1));let f=[],h=0;if(u!==void 0&&p.length>u&&(h=p.length-u),m!==void 0&&m<p.length-1&&t.warn({failureIndex:m,flattenedResultsLength:p.length,lastIndex:p.length-1,isLastIndex:m===p.length-1,offset:h},"PROCESS_RESULTS_FOR_LLM: Failure index check - should not be possible"),m!==void 0&&h>m)throw new Error("Failure index is out of bounds");for(let S=h;S<p.length;S++){let g=p[S],E={description:g.description,startedAt:g.startedAt,finishedAt:g.finishedAt,beforeUrl:g.beforeUrl,afterUrl:g.afterUrl,elementInteracted:g.elementInteracted,userFacingStepReference:g.userFacingStepReference,message:g.message,pageState:g.pageState,index:g.index},y,b;(n===void 0||n>0&&S>=p.length-n)&&(g.afterSnapshot&&(b=await uN(t,e,g.afterSnapshot,a)),i&&g.beforeSnapshot&&(y=await uN(t,e,g.beforeSnapshot,a))),E.beforeScreenshot=y,E.afterScreenshot=b,f.push(E)}return{results:f,failureIndex:m!==void 0?m-h:void 0}}function Gd({json:t,keysToRedact:e,maxJsonStringSize:r}){try{if(!t)return t;if(typeof t=="string")return vt(t,r??2e4);if(typeof t=="object"){let{jsonString:n}=pN(JSON.stringify(t,(o,i)=>e?.includes(o)||typeof i=="string"&&i.length>3e4?"REDACTED":i),r??2e4);return JSON.parse(n)}return t}catch{return t}}function XT(t,e){for(let r=0;r<t.length;r++){let n=t[r];try{if(n.data){let{jsonString:o}=pN(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":dN(n);break;case"CONDITIONAL":n.assertionResult&&dN(n.assertionResult),XT(n.results,e);break;case"AI_ACTION_DYNAMIC":case"AI_ACTION":case"MODULE":case"SECTION":{XT(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 dN(t){let e=t.command;"cache"in e&&e.cache&&(e.cache=void 0)}function Sh(t,e){let r=c4(t);if(XT(r,e),r.length>lN)return e.warn("Results too long, truncating before insertion"),r.slice(r.length-lN,r.length);let n=JSON.stringify(r);if(n.length>cN)for(e.warn({serializedLength:n.length,resultsArrayLength:r.length},"Database content violation: results too large, truncating before insertion");n.length>cN;)r.splice(0,1),n=JSON.stringify(r);try{return mr.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 Oze}from"lodash-es";import{diff as f1e}from"deep-object-diff";import{diff as SN}from"deep-object-diff";import{cloneDeep as hN}from"lodash-es";import{v4 as JT}from"uuid";async function Ft(t){let e=new Map,r=new Set,n=Wi.parse({steps:t.stepLists.steps??[],beforeSteps:t.stepLists.beforeSteps??void 0,afterSteps:t.stepLists.afterSteps??void 0}),o=hN(n.steps),i=await bs({...t,steps:o,moduleStepParents:[],moduleIdParents:[],moduleIdReplacements:e,seenModules:r}),a={stepsToSave:{steps:i.stepsToSave,beforeSteps:void 0,afterSteps:void 0},cachesToSave:i.cachesToSave,moduleUpdates:i.moduleUpdates};for(let s of["beforeSteps","afterSteps"]){let c=hN(n[s]);if(!c)continue;let l=await bs({...t,steps:c,moduleStepParents:[],moduleIdParents:[],moduleIdReplacements:e,seenModules:r});a.cachesToSave.push(...l.cachesToSave),a.moduleUpdates.push(...l.moduleUpdates),a.stepsToSave[s]=l.stepsToSave}return a}async function bs({steps:t,...e}){let{seenModules:r,cacheCreationParams:n,moduleIdParents:o,moduleStepParents:i,moduleIdReplacements:a,shouldCreateNewModuleId:s,createNewCacheIds:c}=e,l={cachesToSave:[],stepsToSave:[],moduleUpdates:[]};for(let u of t)switch(delete u.index,delete u.aiSuggested,u.id=c?JT():u.id,u.type){case"PRESET_ACTION":{let p=u.command;l.cachesToSave=l.cachesToSave.concat(gN({...e,command:p})),l.stepsToSave.push({...u,command:p});break}case"RESOLVED_MODULE":{let p=c?JT():u.id,m=u.moduleId;a.has(m)?m=a.get(m):s!==void 0&&(m=await s(u),a.set(u.moduleId,m));let{cachesToSave:f,stepsToSave:h,moduleUpdates:S}=await bs({...e,steps:u.steps,cacheCreationParams:n?{...n}:void 0,createNewCacheIds:!1,moduleStepParents:[...i,p],moduleIdParents:[...o,m],skipCacheIntermediateEntries:c});l.moduleUpdates=l.moduleUpdates.concat(S),l.cachesToSave=l.cachesToSave.concat(f),r.has(m)||(r.add(m),l.moduleUpdates.push({...tn.parse(u),steps:bt.array().parse(h),moduleId:m}));let g=ho.parse({...u,type:"MODULE",moduleId:m,inputs:u.inputs,id:p,skipped:u.skipped,cacheConfig:u.cacheConfig,envKey:u.envKey});l.stepsToSave.push(g);break}case"AI_ACTION":{if(!u.steps){l.stepsToSave.push(u);break}let{stepsToSave:p,cachesToSave:m}=await bs({...e,steps:u.steps});try{u.steps=hn.array().parse(p)}catch(f){throw new Error(`Only preset actions are allowed in AI actions at the moment: ${f}`)}l.stepsToSave.push(u),l.cachesToSave=l.cachesToSave.concat(m);break}case"AI_ACTION_DYNAMIC":{l.stepsToSave.push(u);break}case"CONDITIONAL":{let p=[];for(let f of u.blocks){l.cachesToSave=l.cachesToSave.concat(gN({...e,command:f.assertion.command}));let{stepsToSave:h,cachesToSave:S,moduleUpdates:g}=await bs({...e,steps:f.steps});p.push({...f,steps:h}),l.cachesToSave=l.cachesToSave.concat(S),l.moduleUpdates=l.moduleUpdates.concat(g)}let m={...u,elseSteps:void 0,blocks:p};if(u.elseSteps){let{stepsToSave:f,cachesToSave:h,moduleUpdates:S}=await bs({...e,steps:u.elseSteps});m.elseSteps=f,l.cachesToSave=l.cachesToSave.concat(h),l.moduleUpdates=l.moduleUpdates.concat(S)}l.stepsToSave.push(m);break}case"SECTION":{let{stepsToSave:p,cachesToSave:m,moduleUpdates:f}=await bs({...e,steps:u.steps}),h={...u,steps:p};l.moduleUpdates=l.moduleUpdates.concat(f),l.stepsToSave.push(h),l.cachesToSave=l.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 l}function gN({command:t,cacheCreationParams:e,createNewCacheIds:r,moduleIdParents:n,moduleStepParents:o}){let i=[];if(t.id=r?JT():t.id,"cache"in t&&t.cache){if(e){let a=GT({id:t.id,orgId:e.orgId,testId:e.testId,environment:e.environment,value:po.parse(t),moduleIdParents:n,moduleStepParents:o});a&&i.push(a)}delete t.cache}return t.thoughts&&delete t.thoughts,i}async function vs({logger:t,cacheStorage:e,orgId:r,testId:n,environment:o,originalStepsWithCaches:i,updatedStepsWithCaches:a}){let s=SN(i,a);if(Object.keys(s).length!==0){t.debug("Updating step caches post-success");try{let{cachesToSave:c}=await Ft({stepLists:a,cacheCreationParams:{testId:n,orgId:r,environment:o}});await e.saveStepCacheEntries({logger:t,entries:c})}catch(c){t.error({err:c},"Failed to save step caches after successful execution. This is not critical, but can impact future performance.")}}}async function Sc({logger:t,cacheStorage:e,orgId:r,testId:n,environment:o,originalStepsWithCaches:i,updatedStepsWithCaches:a}){let s=SN(i,a);if(Object.keys(s).length===0)return;t.debug("Updating memory post-run failure");let c={};for(let d of["steps","beforeSteps","afterSteps"]){let p=i[d];if(!p||!p.length)continue;let m=RL({logger:t,steps:p});for(let[f,h]of Object.entries(m))c[f]=h}let{cachesToSave:l}=await Ft({stepLists:a,cacheCreationParams:{testId:n,orgId:r,environment:o}});t.debug({newEntries:l.length,originalCaches:Object.keys(c).length},"Comparing caches for memory pruning");let u=wL({newEntries:l,originalCachesMap:c});if(u.length){t.debug({prunedCaches:u.map(d=>({key:d.key,value:d.value.type}))},"Saving pruned memory post-failure");try{await e.saveStepCacheEntries({logger:t,entries:u})}catch(d){t.error({err:d},"Failed to save memory after failed execution. This is not critical, but can impact future performance.")}}}function yN(t,e){if(!(!t.envs||!t.envs.length)){for(let r of t.envs){let n=r;e in r&&(n[e]&&(r.default=!0),delete n.defaultOnCloud,delete n.defaultOnLocal)}t.envs.some(r=>r.default)||(t.envs[0].default=!0)}}import{cloneDeep as EN}from"lodash-es";import{z as m4}from"zod";async function TN({rawSteps:t,metadata:e,logger:r,callbacks:n}){yN(e,"defaultOnCloud");let o={},{resolvedSteps:i,newSchemaVersion:a}=await yh({rawSteps:t.steps,migrationMetadata:e,logger:r,callbacks:n,resolvedModuleCache:o}),s={...e,steps:i,schemaVersion:a};for(let c of["beforeSteps","afterSteps"]){let l=t[c];if(!l)continue;let{resolvedSteps:u}=await yh({rawSteps:l,migrationMetadata:e,logger:r,callbacks:n,resolvedModuleCache:o});s[c]=u}return{resolvedTest:s,moduleIds:Array.from(Object.keys(o))}}async function As(t,e,r){let{newVersion:n,steps:o}=await fc({metadata:t,steps:e,logger:r});try{return{steps:bt.array().parse(o),newVersion:n}}catch(i){throw i instanceof m4.ZodError?(r.warn({type:"zod",zodIssues:i.issues,newVersion:n,id:t.id},"Failed to parse test steps while migrating test"),new Ha("Failed to parse test steps while migrating test",t.id,"entity",i.issues,{cause:i})):(r.warn({err:i,newVersion:n,id:t.id},"Failed to parse test steps while migrating test"),new du(`Failed to parse test steps while migrating test: ${i}`,t.id,"entity",{cause:i}))}}async function yh({rawSteps:t,migrationMetadata:e,logger:r,callbacks:n,resolvedModuleCache:o={}}){let{newVersion:i,steps:a}=await As(e,t,r),s=[];for(let c of a)s.push(await jd({step:c,callbacks:n,logger:r,resolvedModuleCache:o}));return{resolvedSteps:s,newSchemaVersion:i}}async function jd({step:t,callbacks:e,logger:r,resolvedModuleCache:n}){switch(t.type){case"AI_ACTION":return t;case"AI_ACTION_DYNAMIC":return t;case"PRESET_ACTION":return t;case"MODULE":{let c=t.moduleId,l=n[c];if(l)return{...EN(l),...t,type:"RESOLVED_MODULE"};let u=await e.onFetchModule({id:c,logger:r});if(!u)throw new Error(`Could not find module with id ${c}`);let{newVersion:d,steps:p}=await fc({metadata:{id:c,schemaVersion:u.schemaVersion},steps:u.steps,logger:r}),m;try{m=bt.array().parse(p)}catch(S){throw r.warn({type:"zod",err:S,steps:p,newVersion:d,id:c},"Module failed to parse"),S}let f;try{f=await Promise.all(m.map(S=>jd({step:S,callbacks:e,logger:r,resolvedModuleCache:n})))}catch(S){throw r.warn({err:S,...t},`Failed to recursively resolve module '${u.name}': ${S}`),S}let h={...u,steps:f};return n[c]=EN(h),{...h,...t,type:"RESOLVED_MODULE"}}case"CONDITIONAL":let o=[];for(let c of t.blocks){let l=[];for(let u of c.steps)l.push(await jd({step:u,callbacks:e,logger:r,resolvedModuleCache:n}));o.push({...c,steps:l})}let i;if(t.elseSteps){i=[];for(let c of t.elseSteps)i.push(await jd({step:c,callbacks:e,logger:r,resolvedModuleCache:n}))}return{...t,blocks:o,elseSteps:i};case"SECTION":let a=[];for(let c of t.steps)a.push(await jd({step:c,callbacks:e,logger:r,resolvedModuleCache:n}));return{...t,steps:a};default:return(c=>{throw"If Typescript complains about the line below, you missed a case or break in the switch above"})(t)}}import{cloneDeep as f4}from"lodash-es";import{stringify as bN}from"yaml";async function vN({test:t,processedModuleNames:e=new Set,createNewCacheIds:r=!1}){let n={id:t.id,name:t.name,description:t.description,baseUrl:t.baseUrl,schemaVersion:t.schemaVersion,advanced:t.advanced,retries:t.retries,envs:t.envs,disabled:t.disabled,labels:t.labels},o={},i=await h4({originalStepLists:{steps:t.steps,beforeSteps:t.beforeSteps,afterSteps:t.afterSteps},modules:o,processedModuleNames:e,createNewCacheIds:r}),a={fileType:ye.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:bN(a),modules:o}}async function h4({originalStepLists:t,modules:e,processedModuleNames:r,createNewCacheIds:n}){let o=f4(t);Object.values(o).forEach(s=>{g4(s??[])});let{stepsToSave:i,moduleUpdates:a}=await Ft({stepLists:o,createNewCacheIds:n});for(let s of a)r.has(s.name)||(e[s.name]=S4(s),r.add(s.name));return i}function g4(t){ln({steps:t,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 S4(t){let e=tn.parse(t),r={fileType:ye.MODULE,...e,schemaVersion:De,steps:t.steps};return bN(r)}async function Vd({promiseGenerator:t,signal:e,codePath:r,logger:n}){let i=Date.now(),a=setInterval(()=>{if(e?.aborted){clearInterval(a);return}n?.warn({codePath:r,startTime:i,elapsedMilliseconds:Date.now()-i},`Asynchronous operation is taking a long time (${r})`)},5e3);return new Promise((s,c)=>{function l(){clearInterval(a),e?.removeEventListener("abort",l),c(e?.reason)}if(e?.aborted){c(e?.reason),clearInterval(a);return}e?.addEventListener("abort",l,{once:!0}),(async()=>{try{s(await t())}catch(u){c(u)}finally{clearInterval(a),e?.removeEventListener("abort",l)}})()})}async function Wd({promiseGenerator:t,timeoutMs:e,codePath:r,logger:n,signal:o}){let i=!1,a=new AbortController,s=()=>{a.abort()},c=setTimeout(()=>{o?.removeEventListener("abort",s),!i&&a.abort()},e);o?.addEventListener("abort",s,{once:!0});try{return await Vd({promiseGenerator:t,signal:a.signal,codePath:r,logger:n})}finally{i=!0,o?.removeEventListener("abort",s),clearTimeout(c)}}function AN(t,e){let r=Math.max(1,e),n=t/r;return Math.max(n,1e3)}function Eh(t){let e=[];for(let r of t)switch(r.type){case"PRESET_ACTION":case"AI_ACTION":case"AI_ACTION_DYNAMIC":e.push(r);break;case"RESOLVED_MODULE":{let n={...r,type:"MODULE"};e.push(ho.parse(n));break}case"SECTION":{let n={...r,steps:Eh(r.steps)};e.push(bt.parse(n));break}case"CONDITIONAL":{let n={...r,blocks:r.blocks.map(o=>({assertion:o.assertion,steps:Eh(o.steps)})),elseSteps:r.elseSteps?Eh(r.elseSteps):void 0};e.push(ja.parse(n));break}default:return(o=>{throw"If Typescript complains about the line below, you missed a case or break in the switch above"})(r)}return e}function Th(t){return Eh([t])[0]}import y4 from"picomatch";var bh=(t,e,r)=>{r?.caseInsensitive&&(t=t.toLowerCase());let n;switch(e.type){case"SUBSTRING":{let o=r?.caseInsensitive?e.url.toLowerCase():e.url;n=t.includes(o);break}case"GLOB":{let o=r?.caseInsensitive?e.glob.toLowerCase():e.glob;n=t===e.glob||y4(o)(t);break}case"REGEX":{n=new RegExp(e.regex).test(t);break}case"DOMAIN":{let o=r?.caseInsensitive?e.domain.toLowerCase():e.domain;n=new URL(t).hostname===o;break}}return r?.negated?!n:n},vh=(t,e)=>{try{let{hostname:r,pathname:n}=new URL(t),{hostname:o,pathname:i}=new URL(e);return r!==o||n!==i}catch{return!1}},yc=t=>{try{return new URL(t),!0}catch{return!1}},CN=t=>!t.toLowerCase().startsWith("http"),Ec=(t,e)=>{try{return new URL(t,e),!0}catch{return!1}};function Cs(t,e){try{return!!new URL(t).origin.trim()}catch(r){return e?.warn({url:t,err:r},"Invalid URL in check"),!1}}async function E4(t){let{logger:e,browserStateStorage:r,generator:n,results:o,error:i,maxItemsFromEnd:a,numStepsWithScreenshots:s,disableCache:c}=t,l=[];if(o.length>0){let{results:d}=await gc(e,r,o,{numStepsWithScreenshots:s,addIndices:!1,includeUserFacingStepReference:!0,maxItemsFromEnd:a,includeBeforeScreenshots:!0,includeContainerTagsInDescription:!0});l=d}return await n.getTestResultClassification({results:l,errorMessage:i.message,errorStack:i.stack},{disableCache:c??!1,loggerTags:ot(e)})}async function RN(t){let{logger:e,browserStateStorage:r,generator:n,fullResults:o,failureReason:i,error:a,maxItemsFromEnd:s,numStepsWithScreenshots:c,disableCache:l}=t,u=o?.results??[];if(i==="SetupFailureError"){let d=(o?.beforeResults??[]).at(0);u=[gh("setup",{followingStepStart:d?.startedAt}),...o?.beforeResults??[]]}else if(i==="TeardownFailureError"){let d=u.at(-1),p=(o?.afterResults??[])[0],m=gh("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=gh("main-test-body",{precedingStepEnd:d?.finishedAt,followingStepStart:p?.startedAt});u=[...o?.beforeResults??[],m,...u]}if(!r||!u||u.length===0)return{};try{let d=await E4({logger:e,browserStateStorage:r,generator:n,results:u,error:a,maxItemsFromEnd:s,numStepsWithScreenshots:c,disableCache:l});return{classification:d,aiFailureReason:d.reason}}catch(d){return e.error({err:d},"Failed to classify test result"),{}}}function wN(t,e,r){let{organizationId:n="local",runKey:o=e,createdBy:i="local-user",runGroupMetadata:a,runAttempts:s=[]}=r??{},c=t.trigger===rn.CLI;return{id:e,runKey:o,organizationId:n,executionType:t.executionType,createdAt:t.startedAt??new Date,createdBy:i,flake:t.flake??null,scheduledAt:null,startedAt:t.startedAt??null,updatedAt:t.finishedAt??null,finishedAt:t.finishedAt??null,resolvedBaseUrl:t.resolvedBaseUrl??null,environmentName:t.environmentName??null,gitBranchName:a?.gitBranchName??null,githubRepository:a?.githubRepository??null,gitlabProjectPath:a?.gitlabProjectPath??null,labels:t.labels??[],gitOriginUrl:a?.gitOriginUrl??null,gitCommitSha:a?.gitCommitSha??null,gitCommitShaShort:a?.gitCommitShaShort??null,gitCommitAuthorName:a?.gitCommitAuthorName??null,cliVersion:t.cliVersion??a?.cliVersion??null,status:t.status,trigger:t.trigger,attempts:t.attempts,runAttempts:s,videos:[],failureReason:t.failureReason??null,failureDetails:t.failureDetails??null,failureRecoveryDetails:t.failureRecoveryDetails??null,pipelineId:a?.pipelineId??null,resolvedInputs:t.resolvedInputs??null,quarantined:t.quarantined??!1,quarantinedReason:t.quarantinedReason??null,...c?{localTestId:t.testId??null,testName:t.testName??t.testDescription??null,test:null}:{testId:t.testId??null,test:t.testId?{id:t.testId,name:t.testName??t.testDescription??"Unknown Test"}:null},description:t.testDescription??null,suiteId:void 0,aiSettings:t.aiSettings??void 0}}import{v4 as xN}from"uuid";function QT(t,e){return{...t,testId:e?.testId??"",testName:e?.testName??"",suiteId:e?.suiteId??"",suiteName:e?.suiteName??""}}var Ah=class{reporter;asyncWork;metadata;creditsUsedV1=0;creditsUsedV2=0;constructor({logger:e,reporter:r,runType:n,runId:o,testMetadata:i,suiteMetadata:a}){this.reporter=r,this.metadata={testId:i.id,testName:i.name,suiteId:a?.id,suiteName:a?.name},this.asyncWork=[r.reportBillableEvents(e,[{event:n,timestamp:new Date().toISOString(),transactionId:o,properties:QT({},this.metadata)}]).catch(s=>e.error({err:s},"Failed to report billable event"))]}trackStepExecution(e){if(Lx(e.type)){this.creditsUsedV2+=1;return}let r=Ky(e.type);if(this.creditsUsedV1+=r??0,e.type==="PRESET_ACTION"){this.creditsUsedV2+=1;let n=Yy(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:xN(),properties:QT({creditsUsed:this.creditsUsedV1},this.metadata)}]).catch(r=>e.error({err:r},"Failed to report credits used"))),this.creditsUsedV2>0&&this.asyncWork.push(this.reporter.reportBillableEvents(e,[{event:"credits-used-v2",timestamp:new Date().toISOString(),transactionId:xN(),properties:QT({creditsUsed:this.creditsUsedV2},this.metadata)}]).catch(r=>e.error({err:r},"Failed to report credits used"))),await Promise.allSettled(this.asyncWork)}};import{cloneDeep as T4}from"lodash-es";function Ch(t,e){if(t.length===0)return`${e}: (no steps)`;let r=tb(t,{includeCache:!0});r.forEach((o,i)=>{let a=o;a.index=i});let n=["```json",JSON.stringify(r,null,2),"```"].join(`
|
|
66
66
|
`);return`${e}:
|
|
67
67
|
${n}`}function tb(t,e={}){let{includeCache:r=!0}=e,n=T4(t);return ln({steps:n,earlyStop:!1,onPresetAction:(o,i)=>{let a=o;a.parentStepIdChain=i.parentChain.map(l=>l.id),ZT(o);let s;if(r&&Hi(o.command)&&o.command.cache!==void 0){let l=v4(o.command.cache);l&&"target"in l&&(s=l.target)}let c=o.command;return s!==void 0?c.cache=s:delete c.cache,c.thoughts&&delete c.thoughts,delete c.id,"index"in o&&delete o.index,!1},onConditional:(o,i)=>{let a=o;return a.parentStepIdChain=i.parentChain.map(s=>s.id),ZT(o),!1},onSimpleStepContainer:(o,i)=>{let a=i.parentChain.map(c=>c.id);if(o.type==="AI_ACTION"){let c=o,l=o.text,u=o.id;return Object.keys(c).forEach(d=>{delete c[d]}),c.type="AI_ACTION_DYNAMIC",c.text=l,c.id=u,c.parentStepIdChain=a,!1}let s=o;if(s.parentStepIdChain=a,ZT(o),o.type==="RESOLVED_MODULE"){let c=o;delete c.cacheConfig,delete c.enabled,delete c.defaultCacheKey,delete c.defaultCacheTtl,delete c.defaultCacheAllInvocations,delete c.autoAuth,delete c.advanced}return!1}}),n}function ZT(t){let e=t;delete e.aiSuggested,delete e.retries,delete e.skipped}function b4(t){return t.selector?t.selector:t.generatedSelectors?.[0]}function eb(t){let e=b4(t),r=t.nodeOnlySerializedHtml,n={};return e&&(n.selector=e),r&&(n.nodeOnlySerializedHtml=r),Object.keys(n).length?n:void 0}function v4(t){if(!t)return;let e={};if("target"in t)return{target:eb(t.target)};if("fromTarget"in t||"toTarget"in t){let r=t.fromTarget?eb(t.fromTarget):void 0,n=t.toTarget?eb(t.toTarget):void 0;return r&&(e.fromTarget=r),n&&(e.toTarget=n),Object.keys(e).length?e:void 0}}import ws from"yaml";import{z as MN}from"zod";import{execSync as A4}from"child_process";function Ai(t,e){let r=e.hooks?.postSave;if(!r)return;let n;r.includes("$1")?n=r.replaceAll("$1",t):n=`${r} ${t}`,v.debug({postSaveCommand:n},"Executing post-save hook command");try{A4(n,{encoding:"utf-8"})}catch(o){v.warn({err:o,postSaveCommand:n},"Failed to execute post-save hook command, continuing...")}}import{diff as _N}from"deep-object-diff";import Ao from"fs";import{cloneDeep as C4}from"lodash-es";import $d from"path";import{v4 as R4}from"uuid";import Tc from"yaml";function IN(t,e){let r=Tc.stringify(t);Ao.writeFileSync(e,r,"utf-8")}function Yn({content:t,schemaVersion:e,momenticFiles:r,project:n,forceSaveOnNoDiffs:o}){let i=r.modules[t.moduleId]?.fullFilePath;if(!i||!Ao.existsSync(i))throw new Error(`Tried to update module ${t.moduleId} that could not be found on disk`);let a=Ao.readFileSync(i,"utf-8"),s=Tc.parse(a),c;if(t.name&&t.name!==s.name){let m=`${dt(t.name)}.module.yaml`;if(c=$d.join($d.dirname(i),m),Ao.existsSync(c))throw new Error(`A conflicting file '${t.name}' already exists at path '${c}'`)}let l={...t,schemaVersion:e},u=vo({fileType:ye.MODULE,...pE.parse(l),steps:bt.array().parse(t.steps)}),d=_N(u,s);if(d&&Object.keys(d).length===0&&!o){v.debug(`Skipping save for module ${t.moduleId} since there are no changes`);return}let p=Tc.stringify(u);Ao.writeFileSync(i,p,"utf-8"),c&&Ao.renameSync(i,c),Ai(c||i,n.config)}function PN({moduleId:t,content:e,momenticFiles:r,project:n,logger:o}){let i=r.modules[t]?.fullFilePath;if(!i)throw new Error(`Tried to update module ${t} that could not be found on disk`);let a=Ci(i,o),s={...a,...e},c=vo({fileType:ye.MODULE,...pE.parse(s),steps:a.steps}),l=_N(c,a);if(l&&Object.keys(l).length===0){v.debug(`Skipping save for module ${t} since there are no changes`);return}let u=Tc.stringify(c);Ao.writeFileSync(i,u,"utf-8");let d;if(e.name){let p=`${dt(e.name)}.module.yaml`;if(d=$d.join($d.dirname(i),p),Ao.existsSync(d))throw new Error(`Module with name '${e.name}' already exists at path '${d}'`);Ao.renameSync(i,d)}Ai(d||i,n.config)}async function Rh({name:t,description:e,enabled:r,steps:n,folder:o,project:i}){let a=dt(t),s=$d.join(o,`${a}.module.yaml`),c=R4(),{stepsToSave:l}=await Ft({stepLists:{steps:n}}),u={fileType:ye.MODULE,schemaVersion:De,moduleId:c,name:t,description:e,enabled:r,steps:l.steps},d=Tc.stringify(u);return Ao.writeFileSync(s,d,"utf-8"),Ai(s,i.config),{moduleId:c,name:t,description:e,enabled:r,steps:n}}function Ci(t,e){let r=Ao.readFileSync(t,"utf-8"),n=Tc.parse(r);try{return Qy.parse(n)}catch(o){throw e.error({err:o,moduleFilePath:t,moduleContents:r},`${t} does not parse as a valid Momentic module`),o}}async function wi(t,e,r,n){let o=Ci(t.fullFilePath,r),{resolvedSteps:i}=await yh({rawSteps:o.steps,migrationMetadata:{id:o.moduleId,schemaVersion:o.schemaVersion},resolvedModuleCache:n,logger:r,callbacks:{onFetchModule:async({id:s})=>{let c=e.modules[s]?.fullFilePath;if(c)return Ci(c,r)}}}),a={...o,steps:i};return n&&(n[t.id]=C4(a)),a}async function wh(t,e){let r={};return await Promise.all(Object.values(t.modules).map(async n=>{await wi(n,t,e,r)})),Array.from(Object.values(r))}function ON(t,e){let r=ws.stringify(t);Xn.writeFileSync(e,r,"utf-8")}async function LN({test:t,name:e,folder:r}){let n=await vN({test:t});if(Object.keys(n.modules).length)throw new Error("A brand new test should not contain any modules in it");let i=`${dt(e)}.test.yaml`,a=Rs.join(r,i);return Xn.writeFileSync(a,n.test,"utf-8"),a}function rb(t,e,r){let n=Rs.join(r.rootDir,t);if(!Xn.existsSync(n))throw new Error(`Test not found at path '${t}' in project '${r.rootDir}'`);let o=Xn.readFileSync(n,"utf-8"),i=ws.parse(o),a,s;if(e.name&&e.name!==i.name){let p=`${dt(e.name)}.test.yaml`;if(a=Rs.join(Rs.dirname(t),p),s=Rs.join(r.rootDir,a),Xn.existsSync(s))throw new Error(`Test with name '${e.name}' already exists at path '${s}'`)}let c={...i,...e},l=zn.parse(c),u=vo({fileType:ye.TEST,...zn.parse(l),beforeSteps:i.beforeSteps??void 0,steps:i.steps,afterSteps:i.afterSteps??void 0,retries:l.retries??void 0}),d=ws.stringify(u);return Xn.writeFileSync(n,d,"utf-8"),s&&Xn.renameSync(n,s),Ai(n,r.config),{newRelativeTestPath:a}}function Tn({relativeTestPath:t,steps:e,schemaVersion:r,project:n,forceSaveOnNoDiffs:o}){let i=Rs.join(n.rootDir,t);if(!Xn.existsSync(i))throw new Error(`Test not found at path '${t}' in project '${n.rootDir}'`);let a=Xn.readFileSync(i,"utf-8"),s=ws.parse(a),c=zn.parse({...s,schemaVersion:r}),l=bt.array().or(MN.undefined()).parse(e.beforeSteps),u=bt.array().parse(e.steps),d=bt.array().or(MN.undefined()).parse(e.afterSteps),p=vo({fileType:ye.TEST,...c,beforeSteps:l&&l.length>0?l:void 0,steps:u,afterSteps:d&&d.length>0?d:void 0}),m=w4(p,s);if(m&&Object.keys(m).length===0&&!o){v.debug(`Skipping save for test ${c.name} since there are no changes`);return}let f=ws.stringify(p);Xn.writeFileSync(i,f,"utf-8"),v.debug(`Saving test ${c.name} to ${i}`),Ai(i,n.config)}function qd(t,e){let r=Rs.join(e.rootDir,t);if(!r)throw new Error(`Could not find test with path ${t} in Momentic project (${e.rootDir})`);let n;try{n=Xn.readFileSync(r,"utf8"),n=n.replace(/\r\n|\r/g,`
|
|
68
68
|
`)}catch(i){throw new Error(`Could not read test file ${r}: ${i}`)}let o;try{o=ws.parse(n)}catch(i){throw new Error(`Could not parse test file ${r} as YAML: ${i}`)}return Mr.parse(o)}function xs(t,e,r){let n=r.project.rootDir,o;try{o=Xn.readFileSync(t,"utf-8")}catch(a){throw e.error({err:a,projectRoot:n},a.message),new Error(a.message)}let i=ws.parse(o);if(!i.steps||!Array.isArray(i.steps))throw new Error(`Test ${t} is missing steps`);return i}async function Ut(t,e,r){let n=xs(t,e,r),o;try{o=zn.parse(n)}catch(a){throw new Error(`Test ${t} is missing metadata or has invalid metadata: ${a}`)}let{resolvedTest:i}=await TN({rawSteps:{steps:n.steps,beforeSteps:n.beforeSteps,afterSteps:n.afterSteps},metadata:o,logger:e,callbacks:{onFetchModule:async({id:a,logger:s})=>{let c=r.modules[a]?.fullFilePath;if(c)return Ci(c,s)}}});return i}import x4 from"@dotenvx/dotenvx";import _4 from"fs";import NN from"path";function xh(t,e){return(t.config.environments??[]).map(r=>_s(r.name,t,e))}function DN(t){return t.includes("${")?t.replace(/\$\{([^}]+)\}/g,(e,r)=>{let n=r.match(/^([A-Za-z_][A-Za-z0-9_]*)(?:(:-|-)([\s\S]*))?$/);if(!n)return process.env[r]||"";let o=n[1];if(!o)return"";let i=n[2],a=n[3],s=process.env[o];return i===":-"?s&&s!==""?s:a||"":i==="-"?s!==void 0?s:a||"":s||""}):t}function I4(t){let{envVariables:e,project:r}=t;if(!e)return{};let n={};for(let[o,i]of Object.entries(e)){if(typeof i=="string"){let s=DN(i);s&&(n[o]=s);continue}let a;try{a=_4.readFileSync(NN.resolve(r.rootDir,i.fromFile),"utf-8")}catch(s){throw new Error(`Failed to read environment variable '${o}' from file '${i.fromFile}': ${s}`)}if(i.json)try{n[o]=JSON.parse(a)}catch(s){throw new Error(`Failed to parse environment variable '${o}' from file '${i.fromFile}' as JSON: ${s}`)}else n[o]=a}return Object.keys(n).length>0&&v.debug(n,"Set environment variables with interpolation from project configuration"),n}function P4(t){let{project:e,envFile:r,logger:n}=t,o={};if(!r)return o;let i=x4.config({path:NN.resolve(e.rootDir,r),processEnv:o,logLevel:"error",quiet:!0});if(i.error)throw new Error(`Failed to load .env file: ${i.error.message}`);return n.debug("Set environment variables from .env file"),o}function _s(t,e,r){let n=(e.config.environments??[]).find(c=>c.name===t);if(!n)throw new Error(`Environment ${t} not found in local project configuration file`);if(!n.baseUrl)throw new Error(`Browser environment ${t} does not have a baseUrl configured`);let o={[ir]:DN(n.baseUrl)},i=I4({envVariables:n.envVariables,project:e});Object.assign(o,i);let a=P4({project:e,envFile:n.envFile,logger:r});return Object.assign(o,a),n.inheritFromShell&&(r.debug(process.env,"Inheriting environment variables from shell"),Object.assign(o,process.env)),{name:t,variables:o,browser:n.browser}}import{existsSync as O4,readFileSync as L4,readdirSync as N4,writeFileSync as D4}from"fs";import{glob as k4}from"glob";import Is,{dirname as kN}from"path";import{cwd as ob}from"process";import FN from"yaml";import{z as gt}from"zod";import M4 from"zod";var _h=["**/*.test.yaml","**/*.module.yaml"],nb=M4.string().refine(t=>/^[a-zA-Z0-9-]+$/.test(t)),Ih=15;var ua="momentic.config.yaml",ib="momentic.workspace.yaml",F4=gt.object({projects:gt.string().array().describe("list of glob patterns to find project (momentic.config.yaml) files")}),U4=gt.union([gt.string(),gt.object({fromFile:gt.string(),json:gt.boolean().optional()})]),B4=gt.object({name:nb,baseUrl:gt.string().optional().describe("Optional for mobile tests"),envFile:gt.string().optional().describe("path to a file on disk to read environment variables from. can be relative to project root or absolute."),envVariables:gt.record(gt.string(),U4).optional(),inheritFromShell:gt.boolean().optional().describe("inherit all environment variables from the shell - might be noisy"),browser:Ka.optional().describe("NB: most things should use project-level configuration only")}),z4=gt.object({postSave:gt.string().optional()}),H4=gt.object({name:nb,include:gt.string().array().optional().describe("list of glob patterns that match momentic files (optional)"),exclude:gt.string().array().optional().describe("opposite of include, takes precedence over include"),goldenFileDir:gt.string().optional(),reporterDir:gt.string().optional(),outputDir:gt.string().optional(),recordVideo:gt.boolean().optional(),retries:gt.number().optional().describe("number of retries per test"),parallel:gt.number().optional().describe("degree of parallelism"),environments:gt.array(B4).optional(),gitMainBranch:gt.string().optional().readonly(),gitProtectedBranches:gt.string().array().optional().readonly(),ai:pi.optional(),browser:Ka.optional(),emulator:tE.optional(),advanced:ly.optional(),displayRoot:gt.string().optional().describe("relative path from project root to use as the Repository root"),hooks:z4.optional()});function UN(t,e){let r;try{r=L4(t,"utf-8")}catch(o){v.warn(`Could not read possible Momentic ${e} file at ${t}: ${o}`);return}let n;try{if(n=FN.parse(r),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){v.warn(`Possible Momentic ${e} file at ${t} does not parse as valid YAML: ${o}`);return}return n}function ab(t){let e=UN(t,"project configuration");if(e!==void 0)try{return H4.parse(e)}catch(r){v.warn(`Possible Momentic project configuration file at ${t} does not adhere to the required schema: ${r}`);return}}function G4(t){let e=UN(t,"workspace configuration");if(e!==void 0)try{return F4.parse(e)}catch(r){v.warn(`Possible Momentic workspace configuration file at ${t} does not adhere to the required schema: ${r}`);return}}function j4(){let t=[],e=ob(),r=Is.parse(e).root,n=15,o=0;for(;o<n;){o++;let i=Is.basename(e);if(Fm.includes(i))return v.warn(`Stopping search for Momentic projects since the current directory name (${i}) is likely a system artifact folder.`),t;for(let a of N4(e))if(a.endsWith(ua)){let s=Is.join(e,a),c=ab(s);c&&t.push({configFilePath:s,config:c,rootDir:kN(s)})}if(t.length)return t;if(e=Is.dirname(e),e===r)break}return t}async function Ct(t={}){let{configFilePath:e,nameFilter:r,skipExitOnError:n}=t,o=await sb(e,n);if(r&&(o=o.filter(i=>i.config.name===r)),o.length>1)throw new Error(`Multiple valid projects were found in the same directory. Please use the '-c / --config' flag to disambiguate:
|
|
69
69
|
${o.map(i=>i.configFilePath)}`);if(o.length===0)throw new Error("No valid Momentic project file available.");return v.debug(`Found valid project configuration at ${o[0].configFilePath}`),o[0]}async function V4(t){let e=G4(t);if(!e||!e.projects||!e.projects.length)return;let r=e.projects.map(a=>(a.endsWith("/")||(a+="/"),`${a}*${ua}`)),n=AbortSignal.timeout(2e3),o;try{o=await k4(r,{absolute:!1,cwd:ob(),dotRelative:!1,maxDepth:Ih,nodir:!0,signal:n})}catch(a){throw v.error({err:a},`Failed to list the available Momentic projects in the current directory. This usually indicates the 'include' or 'exclude' option in your ${ib} is misconfigured.`),a}let i=[];for(let a of o){let s=Is.join(ob(),a),c=ab(s);c&&i.push({configFilePath:s,config:c,rootDir:kN(s)})}return i}async function sb(t,e){if(t){t=Is.resolve(t);let n=ab(t);return n?[{config:n,configFilePath:t,rootDir:Is.dirname(t)}]:(console.error(`No valid Momentic project file found at ${t}.`),e||process.exit(1),[])}if(O4(ib)){let n=await V4(ib);if(n)return n}return j4()}function da(t,e){let r=FN.stringify(t);D4(e,r)}import zN from"fs";import{glob as W4}from"glob";import Kd from"path";import $4 from"yaml";import{z as BN}from"zod";var HN=!1,q4=BN.object({fileType:BN.nativeEnum(ye)});async function fe(t,e=!1){let r={project:t,tests:{},modules:{},mobileTests:{},mobileModules:{},duplicateEntities:{}},n=t.config.include??_h,o=Array.from(t.config.exclude??[]).concat(Um),i=AbortSignal.timeout(5e3),a;try{a=await W4(n,{absolute:!1,cwd:t.rootDir,ignore:o,dotRelative:!1,maxDepth:Ih,nodir:!0,signal:i})}catch(s){throw v.error({err:s},"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:s})}for(let s of a){let c=K4(t.rootDir,s,r,e?zo:v);c&&(r.duplicateEntities[c.id]=c.paths)}return HN=!0,r}function K4(t,e,r,n){let o=Kd.join(t,e),i=Y4(o,n);if(!i)return;let a=X4(i,o,n);if(!a)return;let s=q4.safeParse(a);if(s.success===!1){n.warn(`Possible Momentic file at ${o} does not have a 'fileType', skipping: ${s.error}`);return}let c=s.data.fileType,l=J4(o,n);if(!l)return;let u=Q4(e,o,l);switch(c){case ye.TEST:try{return Z4(a,r,u,o,n)}catch(d){n.warn(`Skipping file '${o}' because it is missing Momentic test metadata: ${d}`);return}case ye.MODULE:try{return e5(a,r,u,o,n)}catch(d){n.warn(`Skipping file '${o}' because it is missing Momentic module metadata: ${d}`);return}case ye.MOBILE_TEST:try{return r5(a,r,u,o,n)}catch(d){n.warn(`Skipping file '${o}' because it is missing Momentic mobile test metadata: ${d}`);return}case ye.MOBILE_MODULE:try{return t5(a,r,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 Y4(t,e){try{return zN.readFileSync(t,"utf-8")}catch(r){e.warn(`Could not read possible Momentic file at ${t}, skipping: ${r}`);return}}function X4(t,e,r){try{let n=$4.parse(t);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){r.warn(`Could not parse possible Momentic file at ${e}, skipping: ${n}`);return}}function J4(t,e){try{return zN.statSync(t)}catch(r){e.warn(`Skipping path '${t}' because it could not be stat, skipping: ${r}`);return}}function Q4(t,e,r){return{relativePath:t,fullFilePath:e,platformSep:Kd.sep,fullPathSegments:e.split(Kd.sep),relativePathSegments:t.split(Kd.sep),fileName:Kd.basename(e),lastModified:r.mtime,createdAt:r.birthtime}}function Z4(t,e,r,n,o){let i=zn.parse(t),a;if(e.tests[i.id]){let s=e.tests[i.id].fullFilePath;a={id:i.id,paths:[s,n]}}return e.tests[i.id]={type:ye.TEST,name:i.name,id:i.id,description:i.description??void 0,labels:i.labels,...r},a}function e5(t,e,r,n,o){let i=tn.parse(t),a;if(e.modules[i.moduleId]){let c=e.modules[i.moduleId].fullFilePath;a={id:i.moduleId,paths:[c,n]}}e.modules[i.moduleId]={type:ye.MODULE,name:i.name,id:i.moduleId,description:i.description??void 0,...r};let s=r.fileName.replace(".module.yaml","");return!HN&&dt(i.name)!==s&&o.warn(`The module with ID ${i.moduleId} has a name (${i.name}) that does not match its file name (${s}). We recommend renaming the module or the file to be consistent to avoid confusion and issues with module resolution.`),a}function t5(t,e,r,n,o){let i=Pm.parse(t),a;if(e.mobileModules[i.moduleId]){let c=e.mobileModules[i.moduleId].fullFilePath;a={id:i.moduleId,paths:[c,n]}}let s=r.fileName.replace(".module.yaml","");return e.mobileModules[i.moduleId]={type:ye.MOBILE_MODULE,name:s,id:i.moduleId,description:i.description??void 0,...r},a}function r5(t,e,r,n,o){let i=rE.parse(t),a;if(e.mobileTests[i.id]){let c=e.mobileTests[i.id].fullFilePath;a={id:i.id,paths:[c,n]}}let s=r.fileName.replace(".test.yaml","");return e.mobileTests[i.id]={type:ye.MOBILE_TEST,name:s,id:i.id,description:i.description??void 0,labels:i.labels,...r},a}import bc from"fs";import lb from"path";import{z as cb}from"zod";var GN="golden/visual-diff",jN="reports",VN="test-results";var n5=cb.object({width:cb.number(),height:cb.number()}),vc=class{defaultGoldenScreenshotDir;regenerateGoldenFiles;apiClient;constructor(e,r,n){let o=lb.join(e.rootDir,e.config.goldenFileDir??GN);this.defaultGoldenScreenshotDir=o,this.regenerateGoldenFiles=n,this.apiClient=r}async prepareGoldenScreenshotForComparison(e,r,n){if(wC(r.screenshot?.data))return{buffer:(await this.apiClient.fetchOnDemandScreenshot(r.screenshot.data.id)).data,width:r.screenshot.width,height:r.screenshot.height};if(r.screenshot?.data?.startsWith("https://")){let a=await fetch(r.screenshot.data);return{buffer:Buffer.from(await a.arrayBuffer()),width:r.screenshot.width,height:r.screenshot.height}}let o=r.screenshot?.data;o||(o=lb.join(this.defaultGoldenScreenshotDir,`${r.id}.jpg`));let i=`${o}.metadata.json`;if(this.regenerateGoldenFiles)return bc.mkdirSync(lb.dirname(o),{recursive:!0}),bc.writeFileSync(o,n.buffer),bc.writeFileSync(i,JSON.stringify({width:n.width,height:n.height})),{buffer:Buffer.from(n.buffer),width:n.width,height:n.height};if(bc.existsSync(o)){let a=bc.readFileSync(o),s=n5.parse(JSON.parse(bc.readFileSync(i,"utf-8")));return{buffer:a,width:s.width,height:s.height}}else throw new L("UserConfigurationError",`Cannot execute visual diff without a saved baseline screenshot at ${o}`)}};import{execFile as o5}from"node:child_process";import{promisify as i5}from"node:util";import a5 from"simple-git";var WN=3e3,ft=a5(),s5=i5(o5);async function Jn(t){let{logger:e,operation:r,fn:n,context:o}=t,i=Date.now();try{return await n()}finally{let a=Date.now()-i;a>WN&&e.warn({operation:r,durationMs:a,thresholdMs:WN,...o??{}},"[timing] slow git metadata operation")}}function xi(t){if(t)try{let e=new Date(t);return isNaN(e.getTime())?void 0:e}catch{return}}async function l5(t){let e=await Et(t,ft.raw(["config","--list"])),r={};if(!e)return r;for(let n of e.split(`
|
|
70
|
-
`)){let o=n.indexOf("=");if(o===-1)continue;let i=n.slice(0,o),a=n.slice(o+1).trim();r[i]=a}return r}async function c5(t,e,r){try{let o=r["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&&e?.startsWith("git@")&&n.includes("github"))try{let{stdout:o,stderr:i}=await s5("ssh",["-T","-o","BatchMode=yes",`git@${n}`],{timeout:5e3}),s=`${o??""}${i??""}`.trim().match(/Hi\s+([A-Za-z0-9_-]+)!/);if(s?.[1])return s[1]}catch{return}}async function u5(t,e,r){let n=e?.includes("github.com"),o=e?.includes("gitlab.com");try{if(n)return c5(t,e,r);if(o)return}catch{}}function Ph(t){if(t.startsWith("git@")){let e=t.split(":");if(e.length===2){let r=e[1].replace(".git","").split("/");if(r.length===2){let n=r[0],o=r[1];return`${n}/${o}`}}}else if(t.startsWith("http")||t.startsWith("https")){let r=new URL(t).pathname.split("/").filter(Boolean);if(r.length>=2){let n=r[0],o=r[1].replace(".git","");return`${n}/${o}`}}}function d5(t){if(!(t instanceof Error))return!1;let e=t.message;return e.includes("not a git repository")||e.includes("ENOENT")}async function Et(t,e){try{return(await e).trim()}catch(r){if(d5(r))return;t.error({err:r},"Failed to run git command");return}}function p5(){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";if(process.env.MOMENTIC_GIT_OVERRIDE)return"Custom"}async function m5(t){let[e,r,n]=await Promise.all([Et(t,ft.show(["--no-patch","--format=%ci"])),Et(t,ft.show(["-s","--pretty=%B"])),Et(t,ft.show(["-s","--pretty=%an"]))]),o=process.env.GITHUB_SERVER_URL&&process.env.GITHUB_REPOSITORY?`${process.env.GITHUB_SERVER_URL}/${process.env.GITHUB_REPOSITORY}`:void 0;return{ciProvider:"GithubActions",gitCommitSha:process.env.GITHUB_SHA,gitCommitShaShort:process.env.GITHUB_SHA?.slice(0,6),gitCommitTimestamp:e?xi(e):void 0,gitBranchName:process.env.GITHUB_HEAD_REF||process.env.GITHUB_REF_NAME,gitOriginUrl:o,gitCommitMessage:r,gitCommitAuthorName:n,githubRepository:process.env.GITHUB_REPOSITORY,pipelineId:process.env.GITHUB_RUN_ID}}async function f5(t){let[e,r,n]=await Promise.all([Et(t,ft.listRemote(["--get-url","origin"])),Et(t,ft.show(["-s","--pretty=%B"])),Et(t,ft.show(["-s","--pretty=%an"]))]);return{ciProvider:"GitlabCI",gitCommitSha:process.env.CI_COMMIT_SHA,gitCommitShaShort:process.env.CI_COMMIT_SHORT_SHA,gitCommitTimestamp:process.env.CI_COMMIT_TIMESTAMP?xi(process.env.CI_COMMIT_TIMESTAMP):void 0,gitBranchName:process.env.CI_COMMIT_BRANCH||process.env.CI_COMMIT_REF_NAME,gitOriginUrl:e,gitCommitMessage:r,gitCommitAuthorName:n,gitlabProjectPath:process.env.CI_PROJECT_PATH,pipelineId:`${process.env.CI_PIPELINE_ID}:${process.env.CI_JOB_ID}`}}async function h5(t){let[e,r,n,o]=await Promise.all([Et(t,ft.show(["--no-patch","--format=%ci"])),Et(t,ft.listRemote(["--get-url","origin"])),Et(t,ft.show(["-s","--pretty=%B"])),Et(t,ft.show(["-s","--pretty=%an"]))]),i=process.env.CIRCLE_REPOSITORY_URL??r,a=i?.includes("github.com"),s=i?.includes("gitlab.com"),c=i?Ph(i):void 0;return{ciProvider:"CircleCI",gitCommitSha:process.env.CIRCLE_SHA1,gitCommitShaShort:process.env.CIRCLE_SHA1?.slice(0,6),gitCommitTimestamp:e?xi(e):void 0,gitBranchName:process.env.CIRCLE_BRANCH,gitOriginUrl:i,gitCommitMessage:n,gitCommitAuthorName:o,githubRepository:a?c:void 0,gitlabProjectPath:s?c:void 0,pipelineId:process.env.CIRCLE_PIPELINE_ID}}async function g5(t){let[e,r,n]=await Promise.all([Et(t,ft.show(["--no-patch","--format=%ci"])),Et(t,ft.show(["-s","--pretty=%B"])),Et(t,ft.show(["-s","--pretty=%an"]))]),o=process.env.BUILDKITE_REPO,i=o?.includes("github.com"),a=o?.includes("gitlab.com"),s=o?Ph(o):void 0;return{ciProvider:"Buildkite",gitCommitSha:process.env.BUILDKITE_COMMIT,gitCommitShaShort:process.env.BUILDKITE_COMMIT?.slice(0,6),gitCommitTimestamp:e?xi(e):void 0,gitBranchName:process.env.BUILDKITE_BRANCH,gitOriginUrl:o,gitCommitMessage:r,gitCommitAuthorName:n,githubRepository:i?s:void 0,gitlabProjectPath:a?s:void 0,pipelineId:`${process.env.BUILDKITE_PIPELINE_ID}:${process.env.BUILDKITE_BUILD_ID}:${process.env.BUILDKITE_JOB_ID}`}}async function S5(t){let[e,r,n]=await Promise.all([Et(t,ft.show(["--no-patch","--format=%ci"])),Et(t,ft.show(["-s","--pretty=%B"])),Et(t,ft.show(["-s","--pretty=%an"]))]),o=process.env["Build.Repository.Uri"],i=o?.includes("github.com"),a=o?.includes("gitlab.com"),s=o?Ph(o):void 0;return{ciProvider:"AzureDevOps",gitCommitSha:process.env["Build.SourceVersion"],gitCommitShaShort:process.env["Build.SourceVersion"]?.slice(0,6),gitCommitTimestamp:e?xi(e):void 0,gitBranchName:process.env["System.PullRequest.SourceBranch"]??process.env["Build.SourceBranchName"],gitOriginUrl:o,gitCommitMessage:r,gitCommitAuthorName:n,githubRepository:i?s:void 0,gitlabProjectPath:a?s:void 0,pipelineId:`${process.env["System.JobId"]}:${process.env["System.JobAttempt"]}`}}async function y5(t,e,r){let[n,o,i,a,s,c,l,u,d]=await Promise.all([Et(t,ft.revparse(["HEAD"])),Et(t,ft.revparse(["--short","HEAD"])),Et(t,ft.revparse(["--abbrev-ref","HEAD"])),Et(t,ft.listRemote(["--get-url","origin"])),Et(t,ft.show(["--no-patch","--format=%ci"])),Et(t,ft.show(["-s","--pretty=%B"])),Et(t,ft.show(["-s","--pretty=%an"])),e?Et(t,ft.raw(["merge-base","--fork-point",e])):Promise.resolve(void 0),l5(t)]),p=u||(e?await Et(t,ft.raw(["merge-base",e,"HEAD"])):void 0),m=p?await Et(t,ft.show(["--no-patch","--format=%ci",p])):void 0,f=a?.includes("github.com"),h=a?.includes("gitlab.com"),S=a?Ph(a):void 0,g=d["user.email"]||void 0,E=d["user.name"]||void 0,y=d["user.username"]||void 0,b=d["github.user"]||void 0,_=(r?.includeHostingUsername??!0?await u5(t,a,d):void 0)??y??b??void 0;return{ciProvider:"none",gitCommitSha:n,gitCommitShaShort:o,gitBranchName:i,gitOriginUrl:a,gitCommitTimestamp:s?xi(s):void 0,gitCommitMessage:c,gitCommitAuthorName:l,gitLocalUsername:_,gitLocalEmail:g,gitLocalName:E,lastCommitOnMainSha:p,lastCommitOnMainTimestamp:m?xi(m):void 0,githubRepository:f?S:void 0,gitlabProjectPath:h?S:void 0,pipelineId:void 0}}async function E5(){let t=process.env._HEAD_REPO_URL;return{ciProvider:"GCPCloudBuild",gitCommitSha:process.env.COMMIT_SHA,gitCommitShaShort:process.env.COMMIT_SHA?.slice(0,6),gitBranchName:process.env.BRANCH_NAME,gitOriginUrl:t?process.env._HEAD_REPO_URL:void 0,gitCommitTimestamp:void 0,gitCommitMessage:void 0,gitCommitAuthorName:void 0,githubRepository:t?process.env.REPO_FULL_NAME:void 0,pipelineId:`${process.env.PROJECT_ID}:${process.env.BUILD_ID}`}}function T5(){return{ciProvider:"Custom",gitCommitSha:process.env.GIT_COMMIT_SHA,gitCommitShaShort:process.env.GIT_COMMIT_SHA_SHORT??process.env.GIT_COMMIT_SHA?.slice(0,6),gitCommitTimestamp:xi(process.env.GIT_COMMIT_TIMESTAMP),gitBranchName:process.env.GIT_BRANCH_NAME,gitOriginUrl:process.env.GIT_ORIGIN_URL,gitCommitAuthorName:process.env.GIT_COMMIT_AUTHOR_NAME,gitCommitMessage:process.env.GIT_COMMIT_MESSAGE,lastCommitOnMainSha:process.env.LAST_COMMIT_ON_MAIN_SHA,lastCommitOnMainTimestamp:xi(process.env.LAST_COMMIT_ON_MAIN_TIMESTAMP),mergedGitBranchName:process.env.MERGED_GIT_BRANCH_NAME,githubRepository:process.env.GITHUB_REPOSITORY,gitlabProjectPath:process.env.GITLAB_PROJECT_PATH,gitLocalUsername:process.env.GIT_USERNAME,gitLocalEmail:process.env.GIT_EMAIL,gitLocalName:process.env.GIT_NAME}}async function b5(t){let e=[...t.config.gitProtectedBranches??[]];return t.config.gitMainBranch&&e.push(t.config.gitMainBranch),{gitMainBranch:t.config.gitMainBranch,gitProtectedBranches:e}}async function _i(t,e,r){let n=p5();if(!n)return y5(t,e,r);switch(n){case"GithubActions":return m5(t);case"GitlabCI":return f5(t);case"CircleCI":return h5(t);case"Buildkite":return g5(t);case"AzureDevOps":return S5(t);case"GCPCloudBuild":return E5();case"Custom":return T5()}}async function v5(t,e,r,n){let o=n,i=n.gitCommitSha;if(!i)return o;let a=n.gitMainBranch;if(a&&(!o.lastCommitOnMainSha||!o.lastCommitOnMainTimestamp))try{let s=await Jn({logger:t,operation:"getRemoteMetadataFromGitlab.getMergeBaseCommitFromGitlab",fn:()=>e.getMergeBaseCommitFromGitlab(r,a,i),context:{projectPath:r,mainBranch:a}});o={...o,lastCommitOnMainSha:s.sha,lastCommitOnMainTimestamp:s.committer.date}}catch(s){t.warn({err:s},"Failed to get merge base commit from Gitlab")}if(!o.gitCommitTimestamp||!o.gitCommitAuthorName||!o.gitCommitMessage||!o.gitCommitAuthorName)try{let s=await Jn({logger:t,operation:"getRemoteMetadataFromGitlab.getCommitFromGitlab",fn:()=>e.getCommitFromGitlab(r,i),context:{projectPath:r,gitCommitSha:i}});s&&(o={...o,gitCommitTimestamp:o.gitCommitTimestamp??s.committer.date,gitCommitAuthorName:o.gitCommitAuthorName??s.author.name,gitCommitMessage:o.gitCommitMessage??s.message})}catch(s){t.warn({err:s},"Failed to get commit from Gitlab")}if(n.gitBranchName&&n.gitBranchName===n.gitMainBranch&&!o.mergedGitBranchName){let s=n.gitBranchName;try{let c=await Jn({logger:t,operation:"getRemoteMetadataFromGitlab.getMergedBranchFromGitlab",fn:()=>e.getMergedBranchFromGitlab(r,s,i),context:{projectPath:r,branchName:s,gitCommitSha:i}});c.mergedBranch&&(o={...o,mergedGitBranchName:c.mergedBranch})}catch(c){t.warn({err:c},"Failed to get merged branch from Gitlab")}}return o}async function A5(t,e,r,n,o){let i=o,a=o.gitCommitSha;if(!a)return i;let s=o.gitMainBranch;if(s&&(!i.lastCommitOnMainSha||!i.lastCommitOnMainTimestamp))try{let c=await Jn({logger:t,operation:"getRemoteMetadataFromGitHub.getMergeBaseCommitFromGithub",fn:()=>e.getMergeBaseCommitFromGithub(r,n,s,a),context:{owner:r,repo:n,mainBranch:s}});i={...i,lastCommitOnMainSha:c.sha,lastCommitOnMainTimestamp:c.committer.date}}catch(c){t.warn({err:c},"Failed to get merge base commit from GitHub")}if(!i.gitCommitTimestamp||!i.gitCommitAuthorName||!i.gitCommitMessage||!i.gitCommitAuthorName)try{let c=await Jn({logger:t,operation:"getRemoteMetadataFromGitHub.getCommitFromGithub",fn:()=>e.getCommitFromGithub(r,n,a),context:{owner:r,repo:n,gitCommitSha:a}});c&&(i={...i,gitCommitTimestamp:i.gitCommitTimestamp??c.committer.date,gitCommitAuthorName:i.gitCommitAuthorName??c.author.name,gitCommitMessage:i.gitCommitMessage??c.message})}catch(c){t.warn({err:c},"Failed to get commit from GitHub")}if(o.gitBranchName&&o.gitBranchName===o.gitMainBranch&&!i.mergedGitBranchName){let c=o.gitBranchName;try{let l=await Jn({logger:t,operation:"getRemoteMetadataFromGitHub.getMergedBranchFromGithub",fn:()=>e.getMergedBranchFromGithub(r,n,c,a),context:{owner:r,repo:n,branchName:c,gitCommitSha:a}});l.mergedBranch&&(i={...i,mergedGitBranchName:l.mergedBranch})}catch(l){t.warn({err:l},"Failed to get merged branch from GitHub")}}return i}async function C5(t,e,r){try{if(r.githubRepository){let[n,o]=r.githubRepository.split("/");return await Jn({logger:t,operation:"getRemoteMetadataIfNeeded.getRemoteMetadataFromGitHub",fn:()=>A5(t,e,n,o,r),context:{githubRepository:r.githubRepository}})}else if(r.gitlabProjectPath){let n=r.gitlabProjectPath;return await Jn({logger:t,operation:"getRemoteMetadataIfNeeded.getRemoteMetadataFromGitlab",fn:()=>v5(t,e,n,r),context:{gitlabProjectPath:n}})}}catch(n){t.warn({err:n},"Failed to get remote git metadata")}return r}async function Er(t,e,r,n){let o={},i={gitMainBranch:r.config.gitMainBranch};return Jn({logger:t,operation:"getGitMetadata.total",fn:async()=>{let[a,s]=await Promise.all([Jn({logger:t,operation:"getGitMetadata.getConfiguredGitMetadata",fn:()=>b5(r),context:{projectConfigPath:r.configFilePath}}),Jn({logger:t,operation:"getGitMetadata.getEnvironmentGitMetadata",fn:async()=>{let u=await _i(t,r.config.gitMainBranch,n);return i.ciProvider=u.ciProvider,u},context:i})]),c={...a,...s};o.gitBranchName=c.gitBranchName,o.githubRepository=c.githubRepository,o.gitlabProjectPath=c.gitlabProjectPath,(!c.lastCommitOnMainSha||!c.lastCommitOnMainTimestamp)&&c.gitBranchName===a.gitMainBranch&&(c.lastCommitOnMainSha=c.gitCommitSha,c.lastCommitOnMainTimestamp=c.gitCommitTimestamp);let l=await Jn({logger:t,operation:"getGitMetadata.getRemoteMetadataIfNeeded",fn:()=>C5(t,e,c),context:{githubRepository:c.githubRepository,gitlabProjectPath:c.gitlabProjectPath,gitBranchName:c.gitBranchName}});return{...a,...s,...l}},context:o})}async function $N(){try{let t=await ft.remote(["show","origin"]);return t?t.match(/HEAD branch: (.*)$/m)?.[1]?.trim():void 0}catch{return}}async function qN(){try{return!!(await ft.show(["--no-patch","--format=%ci"])).trim()}catch{return null}}import{diff as Nje}from"deep-object-diff";import{cloneDeep as kje}from"lodash-es";import{v4 as Kje}from"uuid";import Xje from"yaml";import dVe from"yaml";import Ps from"zod";var hVe=Ps.discriminatedUnion("platform",[Lm.extend({steps:Ps.record(Ps.string(),Ps.unknown()).array()}),Nm.extend({steps:Ps.record(Ps.string(),Ps.unknown()).array()})]);import{randomUUID as R5}from"crypto";import pa from"fs";import Ac from"path";var YN=new Set([".DS_Store","__MACOSX"]),XN={status:(t,e)=>{if(t.status===e.status)return t.status;if(t.status==="FAILED"||e.status==="FAILED")return"FAILED";if(t.status==="CANCELLED"||e.status==="CANCELLED")return"CANCELLED";if(t.status==="RETRYING"||e.status==="RETRYING")return"RETRYING";if(t.status==="RUNNING"||e.status==="RUNNING")return"RUNNING";if(t.status==="PENDING"||e.status==="PENDING")return"PENDING";throw new Error(`Invalid run status merge: ${t.status} and ${e.status}`)},startedAt:(t,e)=>t.startedAt<e.startedAt?t.startedAt:e.startedAt,updatedAt:(t,e)=>t.updatedAt>e.updatedAt?t.updatedAt:e.updatedAt,finishedAt:(t,e)=>!t.finishedAt||!e.finishedAt?new Date:t.finishedAt>e.finishedAt?t.finishedAt:e.finishedAt,gitCommitTimestamp:(t,e)=>{if(!(!t&&!e)){if(!t.gitCommitTimestamp||!e.gitCommitTimestamp||t.gitCommitTimestamp.getTime()!==e.gitCommitTimestamp.getTime())throw new Error(`Git commit timestamps must match to be merged: ${t.gitCommitTimestamp} and ${e.gitCommitTimestamp}`);return t.gitCommitTimestamp}},pipelineId:(t,e)=>t.pipelineId===e.pipelineId?t.pipelineId:!t.pipelineId&&e.pipelineId?e.pipelineId:!e.pipelineId&&t.pipelineId?t.pipelineId:t.startedAt<e.startedAt?e.pipelineId:t.pipelineId,labels:(t,e)=>{let r=new Set([...t.labels??[],...e.labels??[]]);return Array.from(r)}};function w5(t,e,r){if(XN[r]){let i=XN[r];return i(t,e)}let n=t[r],o=e[r];if(n!==o)throw new Error(`Metadata values for key "${r}" do not match: "${n}" vs "${o}"`);return n}var ub=class extends Error{constructor(e,r){let n=`${e} contains invalid Momentic results: ${r}. 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 JN(t,e){try{let r=Ac.join(e,"metadata.json");return Wl.parse(JSON.parse(pa.readFileSync(r,"utf-8")))}catch{throw new ub(t,e)}}function QN(t,e,r){let n=R5(),o=t.child({runGroupId:n});pa.rmSync(e,{recursive:!0,force:!0});let i=pa.readdirSync(r).filter(c=>!YN.has(c)).map(c=>Ac.join(r,c));if(i.length===0)throw new Error(`No run groups found in results path: ${r}`);pa.mkdirSync(e,{recursive:!0});let a={...JN(r,i[0]),id:n};for(let c of i){let l=Ac.join(c,"runs");if(!pa.existsSync(l))continue;let u=JN(r,c);o.info({oldRunGroupId:u.id},"Merging run groups");for(let p in u){if(p==="id")continue;let m=p;a[m]=w5(a,u,m)}let d=pa.readdirSync(l);for(let p of d){if(YN.has(p))continue;let m=Ac.join(l,p),f=Ac.join(e,"runs",p);pa.cpSync(m,f,{recursive:!0})}}let s=Ac.join(e,"metadata.json");pa.writeFileSync(s,JSON.stringify(a,null,2))}import kD from"adm-zip";import Lb from"fs";import{z as mJ}from"zod";var Y="v1",db="cli",Ms="2.71.1";var x5=9e4,_5=3,I5=1500,P5=15e3,Co=class extends Error{status;rawError;constructor(e,r,n,o={}){super(n,o),this.status=e,this.rawError=r}};async function M5(t){return t.text().then(e=>{try{return JSON.parse(e).error}catch{return e}})}var pb=class{baseUrl;logger;constructor(e){this.baseUrl=e.baseUrl,this.logger=e.logger}getHeaders(){let e={"Content-Type":"application/json"};return Ms&&(e[Vm]=Ms),db&&(e[v_]=db),e}async sendRequest(e,r){let{retries:n=_5,requestTimeoutMs:o=x5,initialRetryDelayMs:i=I5,maxRetryDelayMs:a=P5,onFailedRequest:s}=r,c=n,l=n,u,d={path:e,baseUrl:this.baseUrl,method:r.method};for(;c>0;)try{return c--,await this.sendSingleRequestHelper(e,r,o)}catch(p){u=p;try{s?.(u)}catch{}if(p instanceof Co&&p.status>=400&&p.status<500)throw p;if(p instanceof Error&&p.name==="AbortError"&&(u=new ra),c===0)throw u;let m=l-c,f=Math.min(i*Math.pow(2,m-1),a);await new Promise(h=>setTimeout(h,f))}throw this.logger.warn({...d,err:u},"Got fatal error response from Momentic server"),u}async sendSingleRequestHelper(e,r,n){let o={path:e,baseUrl:this.baseUrl,method:r.method},i=new AbortController,a=setTimeout(()=>i.abort(),n),s=()=>i.abort();r.signal&&r.signal.addEventListener("abort",s,{once:!0});let c=Date.now(),l={...this.getHeaders(),...r.extraHeaders};try{let u=await fetch(`${this.baseUrl}${e}`,{method:r.method,body:r.body?JSON.stringify(r.body):void 0,headers:l,signal:i.signal});if(!u.ok){let m=await M5(u);throw new Co(u.status,m,`Request to ${r.method} ${e} failed with status ${u.status}: ${m}`)}let d;if(u.status===204)d={};else if(r.responseType==="buffer"){let m=await u.arrayBuffer();d=Buffer.from(m)}else{let m=await u.text();try{d=JSON.parse(m)}catch{d=m}}this.logger&&r.logResponse===!0&&d&&this.logger.debug({result:d,status:u.status,durationMs:Date.now()-c,...o},"Got response from Momentic server");let p=r.responseHeadersObject;return p&&u.headers.forEach((m,f)=>{p[f.toLowerCase()]=m}),d}finally{clearTimeout(a),r.signal&&r.signal.removeEventListener("abort",s)}}},Tr=class extends pb{apiKey;mode;constructor(e){super(e),this.apiKey=e.apiKey,this.mode=e.mode}getHeaders(){return{...super.getHeaders(),Authorization:`Bearer ${this.apiKey}`,[b_]:this.mode??""}}};import{createAnthropic as pJ}from"@ai-sdk/anthropic";import{InvalidArgumentError as L5}from"@ai-sdk/provider";import{APICallError as UVe}from"@ai-sdk/provider";import{APICallError as D5}from"@ai-sdk/provider";import{LoadAPIKeyError as Lh}from"@ai-sdk/provider";import{LoadSettingError as GVe}from"@ai-sdk/provider";import{JSONParseError as Fh,TypeValidationError as H5}from"@ai-sdk/provider";import{TypeValidationError as Sb}from"@ai-sdk/provider";import{TypeValidationError as W5}from"@ai-sdk/provider";var Mh=class extends Error{constructor(e,r){super(e),this.name="ParseError",this.type=r.type,this.field=r.field,this.value=r.value,this.line=r.line}};function mb(t){}function ZN(t){if(typeof t=="function")throw new TypeError("`callbacks` must be an object, got a function instead. Did you mean `{onEvent: fn}`?");let{onEvent:e=mb,onError:r=mb,onRetry:n=mb,onComment:o}=t,i="",a=!0,s,c="",l="";function u(h){let S=a?h.replace(/^\xEF\xBB\xBF/,""):h,[g,E]=O5(`${i}${S}`);for(let y of g)d(y);i=E,a=!1}function d(h){if(h===""){m();return}if(h.startsWith(":")){o&&o(h.slice(h.startsWith(": ")?2:1));return}let S=h.indexOf(":");if(S!==-1){let g=h.slice(0,S),E=h[S+1]===" "?2:1,y=h.slice(S+E);p(g,y,h);return}p(h,"",h)}function p(h,S,g){switch(h){case"event":l=S;break;case"data":c=`${c}${S}
|
|
70
|
+
`)){let o=n.indexOf("=");if(o===-1)continue;let i=n.slice(0,o),a=n.slice(o+1).trim();r[i]=a}return r}async function c5(t,e,r){try{let o=r["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&&e?.startsWith("git@")&&n.includes("github"))try{let{stdout:o,stderr:i}=await s5("ssh",["-T","-o","BatchMode=yes",`git@${n}`],{timeout:5e3}),s=`${o??""}${i??""}`.trim().match(/Hi\s+([A-Za-z0-9_-]+)!/);if(s?.[1])return s[1]}catch{return}}async function u5(t,e,r){let n=e?.includes("github.com"),o=e?.includes("gitlab.com");try{if(n)return c5(t,e,r);if(o)return}catch{}}function Ph(t){if(t.startsWith("git@")){let e=t.split(":");if(e.length===2){let r=e[1].replace(".git","").split("/");if(r.length===2){let n=r[0],o=r[1];return`${n}/${o}`}}}else if(t.startsWith("http")||t.startsWith("https")){let r=new URL(t).pathname.split("/").filter(Boolean);if(r.length>=2){let n=r[0],o=r[1].replace(".git","");return`${n}/${o}`}}}function d5(t){if(!(t instanceof Error))return!1;let e=t.message;return e.includes("not a git repository")||e.includes("ENOENT")}async function Et(t,e){try{return(await e).trim()}catch(r){if(d5(r))return;t.error({err:r},"Failed to run git command");return}}function p5(){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";if(process.env.MOMENTIC_GIT_OVERRIDE)return"Custom"}async function m5(t){let[e,r,n]=await Promise.all([Et(t,ft.show(["--no-patch","--format=%ci"])),Et(t,ft.show(["-s","--pretty=%B"])),Et(t,ft.show(["-s","--pretty=%an"]))]),o=process.env.GITHUB_SERVER_URL&&process.env.GITHUB_REPOSITORY?`${process.env.GITHUB_SERVER_URL}/${process.env.GITHUB_REPOSITORY}`:void 0;return{ciProvider:"GithubActions",gitCommitSha:process.env.GITHUB_SHA,gitCommitShaShort:process.env.GITHUB_SHA?.slice(0,6),gitCommitTimestamp:e?xi(e):void 0,gitBranchName:process.env.GITHUB_HEAD_REF||process.env.GITHUB_REF_NAME,gitOriginUrl:o,gitCommitMessage:r,gitCommitAuthorName:n,githubRepository:process.env.GITHUB_REPOSITORY,pipelineId:process.env.GITHUB_RUN_ID}}async function f5(t){let[e,r,n]=await Promise.all([Et(t,ft.listRemote(["--get-url","origin"])),Et(t,ft.show(["-s","--pretty=%B"])),Et(t,ft.show(["-s","--pretty=%an"]))]);return{ciProvider:"GitlabCI",gitCommitSha:process.env.CI_COMMIT_SHA,gitCommitShaShort:process.env.CI_COMMIT_SHORT_SHA,gitCommitTimestamp:process.env.CI_COMMIT_TIMESTAMP?xi(process.env.CI_COMMIT_TIMESTAMP):void 0,gitBranchName:process.env.CI_COMMIT_BRANCH||process.env.CI_COMMIT_REF_NAME,gitOriginUrl:e,gitCommitMessage:r,gitCommitAuthorName:n,gitlabProjectPath:process.env.CI_PROJECT_PATH,pipelineId:`${process.env.CI_PIPELINE_ID}:${process.env.CI_JOB_ID}`}}async function h5(t){let[e,r,n,o]=await Promise.all([Et(t,ft.show(["--no-patch","--format=%ci"])),Et(t,ft.listRemote(["--get-url","origin"])),Et(t,ft.show(["-s","--pretty=%B"])),Et(t,ft.show(["-s","--pretty=%an"]))]),i=process.env.CIRCLE_REPOSITORY_URL??r,a=i?.includes("github.com"),s=i?.includes("gitlab.com"),c=i?Ph(i):void 0;return{ciProvider:"CircleCI",gitCommitSha:process.env.CIRCLE_SHA1,gitCommitShaShort:process.env.CIRCLE_SHA1?.slice(0,6),gitCommitTimestamp:e?xi(e):void 0,gitBranchName:process.env.CIRCLE_BRANCH,gitOriginUrl:i,gitCommitMessage:n,gitCommitAuthorName:o,githubRepository:a?c:void 0,gitlabProjectPath:s?c:void 0,pipelineId:process.env.CIRCLE_PIPELINE_ID}}async function g5(t){let[e,r,n]=await Promise.all([Et(t,ft.show(["--no-patch","--format=%ci"])),Et(t,ft.show(["-s","--pretty=%B"])),Et(t,ft.show(["-s","--pretty=%an"]))]),o=process.env.BUILDKITE_REPO,i=o?.includes("github.com"),a=o?.includes("gitlab.com"),s=o?Ph(o):void 0;return{ciProvider:"Buildkite",gitCommitSha:process.env.BUILDKITE_COMMIT,gitCommitShaShort:process.env.BUILDKITE_COMMIT?.slice(0,6),gitCommitTimestamp:e?xi(e):void 0,gitBranchName:process.env.BUILDKITE_BRANCH,gitOriginUrl:o,gitCommitMessage:r,gitCommitAuthorName:n,githubRepository:i?s:void 0,gitlabProjectPath:a?s:void 0,pipelineId:`${process.env.BUILDKITE_PIPELINE_ID}:${process.env.BUILDKITE_BUILD_ID}:${process.env.BUILDKITE_JOB_ID}`}}async function S5(t){let[e,r,n]=await Promise.all([Et(t,ft.show(["--no-patch","--format=%ci"])),Et(t,ft.show(["-s","--pretty=%B"])),Et(t,ft.show(["-s","--pretty=%an"]))]),o=process.env["Build.Repository.Uri"],i=o?.includes("github.com"),a=o?.includes("gitlab.com"),s=o?Ph(o):void 0;return{ciProvider:"AzureDevOps",gitCommitSha:process.env["Build.SourceVersion"],gitCommitShaShort:process.env["Build.SourceVersion"]?.slice(0,6),gitCommitTimestamp:e?xi(e):void 0,gitBranchName:process.env["System.PullRequest.SourceBranch"]??process.env["Build.SourceBranchName"],gitOriginUrl:o,gitCommitMessage:r,gitCommitAuthorName:n,githubRepository:i?s:void 0,gitlabProjectPath:a?s:void 0,pipelineId:`${process.env["System.JobId"]}:${process.env["System.JobAttempt"]}`}}async function y5(t,e,r){let[n,o,i,a,s,c,l,u,d]=await Promise.all([Et(t,ft.revparse(["HEAD"])),Et(t,ft.revparse(["--short","HEAD"])),Et(t,ft.revparse(["--abbrev-ref","HEAD"])),Et(t,ft.listRemote(["--get-url","origin"])),Et(t,ft.show(["--no-patch","--format=%ci"])),Et(t,ft.show(["-s","--pretty=%B"])),Et(t,ft.show(["-s","--pretty=%an"])),e?Et(t,ft.raw(["merge-base","--fork-point",e])):Promise.resolve(void 0),l5(t)]),p=u||(e?await Et(t,ft.raw(["merge-base",e,"HEAD"])):void 0),m=p?await Et(t,ft.show(["--no-patch","--format=%ci",p])):void 0,f=a?.includes("github.com"),h=a?.includes("gitlab.com"),S=a?Ph(a):void 0,g=d["user.email"]||void 0,E=d["user.name"]||void 0,y=d["user.username"]||void 0,b=d["github.user"]||void 0,_=(r?.includeHostingUsername??!0?await u5(t,a,d):void 0)??y??b??void 0;return{ciProvider:"none",gitCommitSha:n,gitCommitShaShort:o,gitBranchName:i,gitOriginUrl:a,gitCommitTimestamp:s?xi(s):void 0,gitCommitMessage:c,gitCommitAuthorName:l,gitLocalUsername:_,gitLocalEmail:g,gitLocalName:E,lastCommitOnMainSha:p,lastCommitOnMainTimestamp:m?xi(m):void 0,githubRepository:f?S:void 0,gitlabProjectPath:h?S:void 0,pipelineId:void 0}}async function E5(){let t=process.env._HEAD_REPO_URL;return{ciProvider:"GCPCloudBuild",gitCommitSha:process.env.COMMIT_SHA,gitCommitShaShort:process.env.COMMIT_SHA?.slice(0,6),gitBranchName:process.env.BRANCH_NAME,gitOriginUrl:t?process.env._HEAD_REPO_URL:void 0,gitCommitTimestamp:void 0,gitCommitMessage:void 0,gitCommitAuthorName:void 0,githubRepository:t?process.env.REPO_FULL_NAME:void 0,pipelineId:`${process.env.PROJECT_ID}:${process.env.BUILD_ID}`}}function T5(){return{ciProvider:"Custom",gitCommitSha:process.env.GIT_COMMIT_SHA,gitCommitShaShort:process.env.GIT_COMMIT_SHA_SHORT??process.env.GIT_COMMIT_SHA?.slice(0,6),gitCommitTimestamp:xi(process.env.GIT_COMMIT_TIMESTAMP),gitBranchName:process.env.GIT_BRANCH_NAME,gitOriginUrl:process.env.GIT_ORIGIN_URL,gitCommitAuthorName:process.env.GIT_COMMIT_AUTHOR_NAME,gitCommitMessage:process.env.GIT_COMMIT_MESSAGE,lastCommitOnMainSha:process.env.LAST_COMMIT_ON_MAIN_SHA,lastCommitOnMainTimestamp:xi(process.env.LAST_COMMIT_ON_MAIN_TIMESTAMP),mergedGitBranchName:process.env.MERGED_GIT_BRANCH_NAME,githubRepository:process.env.GITHUB_REPOSITORY,gitlabProjectPath:process.env.GITLAB_PROJECT_PATH,gitLocalUsername:process.env.GIT_USERNAME,gitLocalEmail:process.env.GIT_EMAIL,gitLocalName:process.env.GIT_NAME}}async function b5(t){let e=[...t.config.gitProtectedBranches??[]];return t.config.gitMainBranch&&e.push(t.config.gitMainBranch),{gitMainBranch:t.config.gitMainBranch,gitProtectedBranches:e}}async function _i(t,e,r){let n=p5();if(!n)return y5(t,e,r);switch(n){case"GithubActions":return m5(t);case"GitlabCI":return f5(t);case"CircleCI":return h5(t);case"Buildkite":return g5(t);case"AzureDevOps":return S5(t);case"GCPCloudBuild":return E5();case"Custom":return T5()}}async function v5(t,e,r,n){let o=n,i=n.gitCommitSha;if(!i)return o;let a=n.gitMainBranch;if(a&&(!o.lastCommitOnMainSha||!o.lastCommitOnMainTimestamp))try{let s=await Jn({logger:t,operation:"getRemoteMetadataFromGitlab.getMergeBaseCommitFromGitlab",fn:()=>e.getMergeBaseCommitFromGitlab(r,a,i),context:{projectPath:r,mainBranch:a}});o={...o,lastCommitOnMainSha:s.sha,lastCommitOnMainTimestamp:s.committer.date}}catch(s){t.warn({err:s},"Failed to get merge base commit from Gitlab")}if(!o.gitCommitTimestamp||!o.gitCommitAuthorName||!o.gitCommitMessage||!o.gitCommitAuthorName)try{let s=await Jn({logger:t,operation:"getRemoteMetadataFromGitlab.getCommitFromGitlab",fn:()=>e.getCommitFromGitlab(r,i),context:{projectPath:r,gitCommitSha:i}});s&&(o={...o,gitCommitTimestamp:o.gitCommitTimestamp??s.committer.date,gitCommitAuthorName:o.gitCommitAuthorName??s.author.name,gitCommitMessage:o.gitCommitMessage??s.message})}catch(s){t.warn({err:s},"Failed to get commit from Gitlab")}if(n.gitBranchName&&n.gitBranchName===n.gitMainBranch&&!o.mergedGitBranchName){let s=n.gitBranchName;try{let c=await Jn({logger:t,operation:"getRemoteMetadataFromGitlab.getMergedBranchFromGitlab",fn:()=>e.getMergedBranchFromGitlab(r,s,i),context:{projectPath:r,branchName:s,gitCommitSha:i}});c.mergedBranch&&(o={...o,mergedGitBranchName:c.mergedBranch})}catch(c){t.warn({err:c},"Failed to get merged branch from Gitlab")}}return o}async function A5(t,e,r,n,o){let i=o,a=o.gitCommitSha;if(!a)return i;let s=o.gitMainBranch;if(s&&(!i.lastCommitOnMainSha||!i.lastCommitOnMainTimestamp))try{let c=await Jn({logger:t,operation:"getRemoteMetadataFromGitHub.getMergeBaseCommitFromGithub",fn:()=>e.getMergeBaseCommitFromGithub(r,n,s,a),context:{owner:r,repo:n,mainBranch:s}});i={...i,lastCommitOnMainSha:c.sha,lastCommitOnMainTimestamp:c.committer.date}}catch(c){t.warn({err:c},"Failed to get merge base commit from GitHub")}if(!i.gitCommitTimestamp||!i.gitCommitAuthorName||!i.gitCommitMessage||!i.gitCommitAuthorName)try{let c=await Jn({logger:t,operation:"getRemoteMetadataFromGitHub.getCommitFromGithub",fn:()=>e.getCommitFromGithub(r,n,a),context:{owner:r,repo:n,gitCommitSha:a}});c&&(i={...i,gitCommitTimestamp:i.gitCommitTimestamp??c.committer.date,gitCommitAuthorName:i.gitCommitAuthorName??c.author.name,gitCommitMessage:i.gitCommitMessage??c.message})}catch(c){t.warn({err:c},"Failed to get commit from GitHub")}if(o.gitBranchName&&o.gitBranchName===o.gitMainBranch&&!i.mergedGitBranchName){let c=o.gitBranchName;try{let l=await Jn({logger:t,operation:"getRemoteMetadataFromGitHub.getMergedBranchFromGithub",fn:()=>e.getMergedBranchFromGithub(r,n,c,a),context:{owner:r,repo:n,branchName:c,gitCommitSha:a}});l.mergedBranch&&(i={...i,mergedGitBranchName:l.mergedBranch})}catch(l){t.warn({err:l},"Failed to get merged branch from GitHub")}}return i}async function C5(t,e,r){try{if(r.githubRepository){let[n,o]=r.githubRepository.split("/");return await Jn({logger:t,operation:"getRemoteMetadataIfNeeded.getRemoteMetadataFromGitHub",fn:()=>A5(t,e,n,o,r),context:{githubRepository:r.githubRepository}})}else if(r.gitlabProjectPath){let n=r.gitlabProjectPath;return await Jn({logger:t,operation:"getRemoteMetadataIfNeeded.getRemoteMetadataFromGitlab",fn:()=>v5(t,e,n,r),context:{gitlabProjectPath:n}})}}catch(n){t.warn({err:n},"Failed to get remote git metadata")}return r}async function Er(t,e,r,n){let o={},i={gitMainBranch:r.config.gitMainBranch};return Jn({logger:t,operation:"getGitMetadata.total",fn:async()=>{let[a,s]=await Promise.all([Jn({logger:t,operation:"getGitMetadata.getConfiguredGitMetadata",fn:()=>b5(r),context:{projectConfigPath:r.configFilePath}}),Jn({logger:t,operation:"getGitMetadata.getEnvironmentGitMetadata",fn:async()=>{let u=await _i(t,r.config.gitMainBranch,n);return i.ciProvider=u.ciProvider,u},context:i})]),c={...a,...s};o.gitBranchName=c.gitBranchName,o.githubRepository=c.githubRepository,o.gitlabProjectPath=c.gitlabProjectPath,(!c.lastCommitOnMainSha||!c.lastCommitOnMainTimestamp)&&c.gitBranchName===a.gitMainBranch&&(c.lastCommitOnMainSha=c.gitCommitSha,c.lastCommitOnMainTimestamp=c.gitCommitTimestamp);let l=await Jn({logger:t,operation:"getGitMetadata.getRemoteMetadataIfNeeded",fn:()=>C5(t,e,c),context:{githubRepository:c.githubRepository,gitlabProjectPath:c.gitlabProjectPath,gitBranchName:c.gitBranchName}});return{...a,...s,...l}},context:o})}async function $N(){try{let t=await ft.remote(["show","origin"]);return t?t.match(/HEAD branch: (.*)$/m)?.[1]?.trim():void 0}catch{return}}async function qN(){try{return!!(await ft.show(["--no-patch","--format=%ci"])).trim()}catch{return null}}import{diff as Dje}from"deep-object-diff";import{cloneDeep as Fje}from"lodash-es";import{v4 as Yje}from"uuid";import Jje from"yaml";import pVe from"yaml";import Ps from"zod";var gVe=Ps.discriminatedUnion("platform",[Lm.extend({steps:Ps.record(Ps.string(),Ps.unknown()).array()}),Nm.extend({steps:Ps.record(Ps.string(),Ps.unknown()).array()})]);import{randomUUID as R5}from"crypto";import pa from"fs";import Ac from"path";var YN=new Set([".DS_Store","__MACOSX"]),XN={status:(t,e)=>{if(t.status===e.status)return t.status;if(t.status==="FAILED"||e.status==="FAILED")return"FAILED";if(t.status==="CANCELLED"||e.status==="CANCELLED")return"CANCELLED";if(t.status==="RETRYING"||e.status==="RETRYING")return"RETRYING";if(t.status==="RUNNING"||e.status==="RUNNING")return"RUNNING";if(t.status==="PENDING"||e.status==="PENDING")return"PENDING";throw new Error(`Invalid run status merge: ${t.status} and ${e.status}`)},startedAt:(t,e)=>t.startedAt<e.startedAt?t.startedAt:e.startedAt,updatedAt:(t,e)=>t.updatedAt>e.updatedAt?t.updatedAt:e.updatedAt,finishedAt:(t,e)=>!t.finishedAt||!e.finishedAt?new Date:t.finishedAt>e.finishedAt?t.finishedAt:e.finishedAt,gitCommitTimestamp:(t,e)=>{if(!(!t&&!e)){if(!t.gitCommitTimestamp||!e.gitCommitTimestamp||t.gitCommitTimestamp.getTime()!==e.gitCommitTimestamp.getTime())throw new Error(`Git commit timestamps must match to be merged: ${t.gitCommitTimestamp} and ${e.gitCommitTimestamp}`);return t.gitCommitTimestamp}},pipelineId:(t,e)=>t.pipelineId===e.pipelineId?t.pipelineId:!t.pipelineId&&e.pipelineId?e.pipelineId:!e.pipelineId&&t.pipelineId?t.pipelineId:t.startedAt<e.startedAt?e.pipelineId:t.pipelineId,labels:(t,e)=>{let r=new Set([...t.labels??[],...e.labels??[]]);return Array.from(r)}};function w5(t,e,r){if(XN[r]){let i=XN[r];return i(t,e)}let n=t[r],o=e[r];if(n!==o)throw new Error(`Metadata values for key "${r}" do not match: "${n}" vs "${o}"`);return n}var ub=class extends Error{constructor(e,r){let n=`${e} contains invalid Momentic results: ${r}. 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 JN(t,e){try{let r=Ac.join(e,"metadata.json");return Wl.parse(JSON.parse(pa.readFileSync(r,"utf-8")))}catch{throw new ub(t,e)}}function QN(t,e,r){let n=R5(),o=t.child({runGroupId:n});pa.rmSync(e,{recursive:!0,force:!0});let i=pa.readdirSync(r).filter(c=>!YN.has(c)).map(c=>Ac.join(r,c));if(i.length===0)throw new Error(`No run groups found in results path: ${r}`);pa.mkdirSync(e,{recursive:!0});let a={...JN(r,i[0]),id:n};for(let c of i){let l=Ac.join(c,"runs");if(!pa.existsSync(l))continue;let u=JN(r,c);o.info({oldRunGroupId:u.id},"Merging run groups");for(let p in u){if(p==="id")continue;let m=p;a[m]=w5(a,u,m)}let d=pa.readdirSync(l);for(let p of d){if(YN.has(p))continue;let m=Ac.join(l,p),f=Ac.join(e,"runs",p);pa.cpSync(m,f,{recursive:!0})}}let s=Ac.join(e,"metadata.json");pa.writeFileSync(s,JSON.stringify(a,null,2))}import kD from"adm-zip";import Lb from"fs";import{z as mJ}from"zod";var Y="v1",db="cli",Ms="2.71.2";var x5=9e4,_5=3,I5=1500,P5=15e3,Co=class extends Error{status;rawError;constructor(e,r,n,o={}){super(n,o),this.status=e,this.rawError=r}};async function M5(t){return t.text().then(e=>{try{return JSON.parse(e).error}catch{return e}})}var pb=class{baseUrl;logger;constructor(e){this.baseUrl=e.baseUrl,this.logger=e.logger}getHeaders(){let e={"Content-Type":"application/json"};return Ms&&(e[Vm]=Ms),db&&(e[v_]=db),e}async sendRequest(e,r){let{retries:n=_5,requestTimeoutMs:o=x5,initialRetryDelayMs:i=I5,maxRetryDelayMs:a=P5,onFailedRequest:s}=r,c=n,l=n,u,d={path:e,baseUrl:this.baseUrl,method:r.method};for(;c>0;)try{return c--,await this.sendSingleRequestHelper(e,r,o)}catch(p){u=p;try{s?.(u)}catch{}if(p instanceof Co&&p.status>=400&&p.status<500)throw p;if(p instanceof Error&&p.name==="AbortError"&&(u=new ra),c===0)throw u;let m=l-c,f=Math.min(i*Math.pow(2,m-1),a);await new Promise(h=>setTimeout(h,f))}throw this.logger.warn({...d,err:u},"Got fatal error response from Momentic server"),u}async sendSingleRequestHelper(e,r,n){let o={path:e,baseUrl:this.baseUrl,method:r.method},i=new AbortController,a=setTimeout(()=>i.abort(),n),s=()=>i.abort();r.signal&&r.signal.addEventListener("abort",s,{once:!0});let c=Date.now(),l={...this.getHeaders(),...r.extraHeaders};try{let u=await fetch(`${this.baseUrl}${e}`,{method:r.method,body:r.body?JSON.stringify(r.body):void 0,headers:l,signal:i.signal});if(!u.ok){let m=await M5(u);throw new Co(u.status,m,`Request to ${r.method} ${e} failed with status ${u.status}: ${m}`)}let d;if(u.status===204)d={};else if(r.responseType==="buffer"){let m=await u.arrayBuffer();d=Buffer.from(m)}else{let m=await u.text();try{d=JSON.parse(m)}catch{d=m}}this.logger&&r.logResponse===!0&&d&&this.logger.debug({result:d,status:u.status,durationMs:Date.now()-c,...o},"Got response from Momentic server");let p=r.responseHeadersObject;return p&&u.headers.forEach((m,f)=>{p[f.toLowerCase()]=m}),d}finally{clearTimeout(a),r.signal&&r.signal.removeEventListener("abort",s)}}},Tr=class extends pb{apiKey;mode;constructor(e){super(e),this.apiKey=e.apiKey,this.mode=e.mode}getHeaders(){return{...super.getHeaders(),Authorization:`Bearer ${this.apiKey}`,[b_]:this.mode??""}}};import{createAnthropic as pJ}from"@ai-sdk/anthropic";import{InvalidArgumentError as L5}from"@ai-sdk/provider";import{APICallError as BVe}from"@ai-sdk/provider";import{APICallError as D5}from"@ai-sdk/provider";import{LoadAPIKeyError as Lh}from"@ai-sdk/provider";import{LoadSettingError as jVe}from"@ai-sdk/provider";import{JSONParseError as Fh,TypeValidationError as H5}from"@ai-sdk/provider";import{TypeValidationError as Sb}from"@ai-sdk/provider";import{TypeValidationError as W5}from"@ai-sdk/provider";var Mh=class extends Error{constructor(e,r){super(e),this.name="ParseError",this.type=r.type,this.field=r.field,this.value=r.value,this.line=r.line}};function mb(t){}function ZN(t){if(typeof t=="function")throw new TypeError("`callbacks` must be an object, got a function instead. Did you mean `{onEvent: fn}`?");let{onEvent:e=mb,onError:r=mb,onRetry:n=mb,onComment:o}=t,i="",a=!0,s,c="",l="";function u(h){let S=a?h.replace(/^\xEF\xBB\xBF/,""):h,[g,E]=O5(`${i}${S}`);for(let y of g)d(y);i=E,a=!1}function d(h){if(h===""){m();return}if(h.startsWith(":")){o&&o(h.slice(h.startsWith(": ")?2:1));return}let S=h.indexOf(":");if(S!==-1){let g=h.slice(0,S),E=h[S+1]===" "?2:1,y=h.slice(S+E);p(g,y,h);return}p(h,"",h)}function p(h,S,g){switch(h){case"event":l=S;break;case"data":c=`${c}${S}
|
|
71
71
|
`;break;case"id":s=S.includes("\0")?void 0:S;break;case"retry":/^\d+$/.test(S)?n(parseInt(S,10)):r(new Mh(`Invalid \`retry\` value: "${S}"`,{type:"invalid-retry",value:S,line:g}));break;default:r(new Mh(`Unknown field "${h.length>20?`${h.slice(0,20)}\u2026`:h}"`,{type:"unknown-field",field:h,value:S,line:g}));break}}function m(){c.length>0&&e({id:s,event:l||void 0,data:c.endsWith(`
|
|
72
72
|
`)?c.slice(0,-1):c}),s=void 0,c="",l=""}function f(h={}){i&&h.consume&&d(i),a=!0,s=void 0,c="",l="",i=""}return{feed:u,reset:f}}function O5(t){let e=[],r="",n=0;for(;n<t.length;){let o=t.indexOf("\r",n),i=t.indexOf(`
|
|
73
73
|
`,n),a=-1;if(o!==-1&&i!==-1?a=Math.min(o,i):o!==-1?a=o:i!==-1&&(a=i),a===-1){r=t.slice(n);break}else{let s=t.slice(n,a);e.push(s),n=a+1,t[n-1]==="\r"&&t[n]===`
|
|
@@ -85,13 +85,13 @@ ${a}
|
|
|
85
85
|
|
|
86
86
|
`;break}case"tool":throw new ED({functionality:"tool messages"});default:{let a=o;throw new Error(`Unsupported role: ${a}`)}}return n+=`${r}:
|
|
87
87
|
`,{prompt:n,stopSequences:[`
|
|
88
|
-
${e}:`]}}function TD({id:t,model:e,created:r}){return{id:t??void 0,modelId:e??void 0,timestamp:r!=null?new Date(r*1e3):void 0}}function bD(t){switch(t){case"stop":return"stop";case"length":return"length";case"content_filter":return"content-filter";case"function_call":case"tool_calls":return"tool-calls";default:return"unknown"}}var i3=Tt(()=>Ee(Ie.object({id:Ie.string().nullish(),created:Ie.number().nullish(),model:Ie.string().nullish(),choices:Ie.array(Ie.object({text:Ie.string(),finish_reason:Ie.string(),logprobs:Ie.object({tokens:Ie.array(Ie.string()),token_logprobs:Ie.array(Ie.number()),top_logprobs:Ie.array(Ie.record(Ie.string(),Ie.number())).nullish()}).nullish()})),usage:Ie.object({prompt_tokens:Ie.number(),completion_tokens:Ie.number(),total_tokens:Ie.number()}).nullish()}))),a3=Tt(()=>Ee(Ie.union([Ie.object({id:Ie.string().nullish(),created:Ie.number().nullish(),model:Ie.string().nullish(),choices:Ie.array(Ie.object({text:Ie.string(),finish_reason:Ie.string().nullish(),index:Ie.number(),logprobs:Ie.object({tokens:Ie.array(Ie.string()),token_logprobs:Ie.array(Ie.number()),top_logprobs:Ie.array(Ie.record(Ie.string(),Ie.number())).nullish()}).nullish()})),usage:Ie.object({prompt_tokens:Ie.number(),completion_tokens:Ie.number(),total_tokens:Ie.number()}).nullish()}),_b]))),vD=Tt(()=>Ee(Ko.object({echo:Ko.boolean().optional(),logitBias:Ko.record(Ko.string(),Ko.number()).optional(),suffix:Ko.string().optional(),user:Ko.string().optional(),logprobs:Ko.union([Ko.boolean(),Ko.number()]).optional()}))),s3=class{constructor(t,e){this.specificationVersion="v2",this.supportedUrls={},this.modelId=t,this.config=e}get providerOptionsName(){return this.config.provider.split(".")[0].trim()}get provider(){return this.config.provider}async getArgs({prompt:t,maxOutputTokens:e,temperature:r,topP:n,topK:o,frequencyPenalty:i,presencePenalty:a,stopSequences:s,responseFormat:c,tools:l,toolChoice:u,seed:d,providerOptions:p}){let m=[],f={...await Yr({provider:"openai",providerOptions:p,schema:vD}),...await Yr({provider:this.providerOptionsName,providerOptions:p,schema:vD})};o!=null&&m.push({type:"unsupported-setting",setting:"topK"}),l?.length&&m.push({type:"unsupported-setting",setting:"tools"}),u!=null&&m.push({type:"unsupported-setting",setting:"toolChoice"}),c!=null&&c.type!=="text"&&m.push({type:"unsupported-setting",setting:"responseFormat",details:"JSON response format is not supported."});let{prompt:h,stopSequences:S}=o3({prompt:t}),g=[...S??[],...s??[]];return{args:{model:this.modelId,echo:f.echo,logit_bias:f.logitBias,logprobs:f?.logprobs===!0?0:f?.logprobs===!1?void 0:f?.logprobs,suffix:f.suffix,user:f.user,max_tokens:e,temperature:r,top_p:n,frequency_penalty:i,presence_penalty:a,seed:d,prompt:h,stop:g.length>0?g:void 0},warnings:m}}async doGenerate(t){var e,r,n;let{args:o,warnings:i}=await this.getArgs(t),{responseHeaders:a,value:s,rawValue:c}=await Xr({url:this.config.url({path:"/completions",modelId:this.modelId}),headers:br(this.config.headers(),t.headers),body:o,failedResponseHandler:Yo,successfulResponseHandler:Zn(i3),abortSignal:t.abortSignal,fetch:this.config.fetch}),l=s.choices[0],u={openai:{}};return l.logprobs!=null&&(u.openai.logprobs=l.logprobs),{content:[{type:"text",text:l.text}],usage:{inputTokens:(e=s.usage)==null?void 0:e.prompt_tokens,outputTokens:(r=s.usage)==null?void 0:r.completion_tokens,totalTokens:(n=s.usage)==null?void 0:n.total_tokens},finishReason:bD(l.finish_reason),request:{body:o},response:{...TD(s),headers:a,body:c},providerMetadata:u,warnings:i}}async doStream(t){let{args:e,warnings:r}=await this.getArgs(t),n={...e,stream:!0,stream_options:{include_usage:!0}},{responseHeaders:o,value:i}=await Xr({url:this.config.url({path:"/completions",modelId:this.modelId}),headers:br(this.config.headers(),t.headers),body:n,failedResponseHandler:Yo,successfulResponseHandler:Rc(a3),abortSignal:t.abortSignal,fetch:this.config.fetch}),a="unknown",s={openai:{}},c={inputTokens:void 0,outputTokens:void 0,totalTokens:void 0},l=!0;return{stream:i.pipeThrough(new TransformStream({start(u){u.enqueue({type:"stream-start",warnings:r})},transform(u,d){if(t.includeRawChunks&&d.enqueue({type:"raw",rawValue:u.rawValue}),!u.success){a="error",d.enqueue({type:"error",error:u.error});return}let p=u.value;if("error"in p){a="error",d.enqueue({type:"error",error:p.error});return}l&&(l=!1,d.enqueue({type:"response-metadata",...TD(p)}),d.enqueue({type:"text-start",id:"0"})),p.usage!=null&&(c.inputTokens=p.usage.prompt_tokens,c.outputTokens=p.usage.completion_tokens,c.totalTokens=p.usage.total_tokens);let m=p.choices[0];m?.finish_reason!=null&&(a=bD(m.finish_reason)),m?.logprobs!=null&&(s.openai.logprobs=m.logprobs),m?.text!=null&&m.text.length>0&&d.enqueue({type:"text-delta",id:"0",delta:m.text})},flush(u){l||u.enqueue({type:"text-end",id:"0"}),u.enqueue({type:"finish",finishReason:a,providerMetadata:s,usage:c})}})),request:{body:n},response:{headers:o}}}},c3=Tt(()=>Ee(Rb.object({dimensions:Rb.number().optional(),user:Rb.string().optional()}))),u3=Tt(()=>Ee(Os.object({data:Os.array(Os.object({embedding:Os.array(Os.number())})),usage:Os.object({prompt_tokens:Os.number()}).nullish()}))),d3=class{constructor(t,e){this.specificationVersion="v2",this.maxEmbeddingsPerCall=2048,this.supportsParallelCalls=!0,this.modelId=t,this.config=e}get provider(){return this.config.provider}async doEmbed({values:t,headers:e,abortSignal:r,providerOptions:n}){var o;if(t.length>this.maxEmbeddingsPerCall)throw new l3({provider:this.provider,modelId:this.modelId,maxEmbeddingsPerCall:this.maxEmbeddingsPerCall,values:t});let i=(o=await Yr({provider:"openai",providerOptions:n,schema:c3}))!=null?o:{},{responseHeaders:a,value:s,rawValue:c}=await Xr({url:this.config.url({path:"/embeddings",modelId:this.modelId}),headers:br(this.config.headers(),e),body:{model:this.modelId,input:t,encoding_format:"float",dimensions:i.dimensions,user:i.user},failedResponseHandler:Yo,successfulResponseHandler:Zn(u3),abortSignal:r,fetch:this.config.fetch});return{embeddings:s.data.map(l=>l.embedding),usage:s.usage?{tokens:s.usage.prompt_tokens}:void 0,response:{headers:a,body:c}}}},p3=Tt(()=>Ee(vr.object({created:vr.number().nullish(),data:vr.array(vr.object({b64_json:vr.string(),revised_prompt:vr.string().nullish()})),background:vr.string().nullish(),output_format:vr.string().nullish(),size:vr.string().nullish(),quality:vr.string().nullish(),usage:vr.object({input_tokens:vr.number().nullish(),output_tokens:vr.number().nullish(),total_tokens:vr.number().nullish(),input_tokens_details:vr.object({image_tokens:vr.number().nullish(),text_tokens:vr.number().nullish()}).nullish()}).nullish()}))),m3={"dall-e-3":1,"dall-e-2":10,"gpt-image-1":10,"gpt-image-1-mini":10,"gpt-image-1.5":10},f3=new Set(["gpt-image-1","gpt-image-1-mini","gpt-image-1.5"]),h3=class{constructor(t,e){this.modelId=t,this.config=e,this.specificationVersion="v2"}get maxImagesPerCall(){var t;return(t=m3[this.modelId])!=null?t:1}get provider(){return this.config.provider}async doGenerate({prompt:t,n:e,size:r,aspectRatio:n,seed:o,providerOptions:i,headers:a,abortSignal:s}){var c,l,u,d;let p=[];n!=null&&p.push({type:"unsupported-setting",setting:"aspectRatio",details:"This model does not support aspect ratio. Use `size` instead."}),o!=null&&p.push({type:"unsupported-setting",setting:"seed"});let m=(u=(l=(c=this.config._internal)==null?void 0:c.currentDate)==null?void 0:l.call(c))!=null?u:new Date,{value:f,responseHeaders:h}=await Xr({url:this.config.url({path:"/images/generations",modelId:this.modelId}),headers:br(this.config.headers(),a),body:{model:this.modelId,prompt:t,n:e,size:r,...(d=i.openai)!=null?d:{},...f3.has(this.modelId)?{}:{response_format:"b64_json"}},failedResponseHandler:Yo,successfulResponseHandler:Zn(p3),abortSignal:s,fetch:this.config.fetch});return{images:f.data.map(S=>S.b64_json),warnings:p,response:{timestamp:m,modelId:this.modelId,headers:h},providerMetadata:{openai:{images:f.data.map(S=>({...S.revised_prompt?{revisedPrompt:S.revised_prompt}:{},...f.created!=null?{created:f.created}:{},...f.size!=null?{size:f.size}:{},...f.quality!=null?{quality:f.quality}:{},...f.background!=null?{background:f.background}:{},...f.output_format!=null?{outputFormat:f.output_format}:{}}))}}}}},g3=Bt(()=>Ee(cr.object({code:cr.string().nullish(),containerId:cr.string()}))),S3=Bt(()=>Ee(cr.object({outputs:cr.array(cr.discriminatedUnion("type",[cr.object({type:cr.literal("logs"),logs:cr.string()}),cr.object({type:cr.literal("image"),url:cr.string()})])).nullish()}))),y3=Bt(()=>Ee(cr.object({container:cr.union([cr.string(),cr.object({fileIds:cr.array(cr.string()).optional()})]).optional()}))),E3=Qn({id:"openai.code_interpreter",name:"code_interpreter",inputSchema:g3,outputSchema:S3}),T3=(t={})=>E3(t),ID=Je.object({key:Je.string(),type:Je.enum(["eq","ne","gt","gte","lt","lte","in","nin"]),value:Je.union([Je.string(),Je.number(),Je.boolean(),Je.array(Je.string())])}),PD=Je.object({type:Je.enum(["and","or"]),filters:Je.array(Je.union([ID,Je.lazy(()=>PD)]))}),b3=Bt(()=>Ee(Je.object({vectorStoreIds:Je.array(Je.string()),maxNumResults:Je.number().optional(),ranking:Je.object({ranker:Je.string().optional(),scoreThreshold:Je.number().optional()}).optional(),filters:Je.union([ID,PD]).optional()}))),v3=Bt(()=>Ee(Je.object({queries:Je.array(Je.string()),results:Je.array(Je.object({attributes:Je.record(Je.string(),Je.unknown()),fileId:Je.string(),filename:Je.string(),score:Je.number(),text:Je.string()})).nullable()}))),A3=Qn({id:"openai.file_search",name:"file_search",inputSchema:Je.object({}),outputSchema:v3}),C3=Bt(()=>Ee(Nr.object({background:Nr.enum(["auto","opaque","transparent"]).optional(),inputFidelity:Nr.enum(["low","high"]).optional(),inputImageMask:Nr.object({fileId:Nr.string().optional(),imageUrl:Nr.string().optional()}).optional(),model:Nr.string().optional(),moderation:Nr.enum(["auto"]).optional(),outputCompression:Nr.number().int().min(0).max(100).optional(),outputFormat:Nr.enum(["png","jpeg","webp"]).optional(),partialImages:Nr.number().int().min(0).max(3).optional(),quality:Nr.enum(["auto","low","medium","high"]).optional(),size:Nr.enum(["1024x1024","1024x1536","1536x1024","auto"]).optional()}).strict())),R3=Bt(()=>Ee(Nr.object({}))),w3=Bt(()=>Ee(Nr.object({result:Nr.string()}))),x3=Qn({id:"openai.image_generation",name:"image_generation",inputSchema:R3,outputSchema:w3}),_3=(t={})=>x3(t),MD=Bt(()=>Ee(An.object({action:An.object({type:An.literal("exec"),command:An.array(An.string()),timeoutMs:An.number().optional(),user:An.string().optional(),workingDirectory:An.string().optional(),env:An.record(An.string(),An.string()).optional()})}))),OD=Bt(()=>Ee(An.object({output:An.string()}))),I3=Qn({id:"openai.local_shell",name:"local_shell",inputSchema:MD,outputSchema:OD}),P3=Bt(()=>Ee(it.object({externalWebAccess:it.boolean().optional(),filters:it.object({allowedDomains:it.array(it.string()).optional()}).optional(),searchContextSize:it.enum(["low","medium","high"]).optional(),userLocation:it.object({type:it.literal("approximate"),country:it.string().optional(),city:it.string().optional(),region:it.string().optional(),timezone:it.string().optional()}).optional()}))),M3=Bt(()=>Ee(it.object({}))),O3=Bt(()=>Ee(it.object({action:it.discriminatedUnion("type",[it.object({type:it.literal("search"),query:it.string().optional()}),it.object({type:it.literal("openPage"),url:it.string().nullish()}),it.object({type:it.literal("findInPage"),url:it.string().nullish(),pattern:it.string().nullish()})]),sources:it.array(it.discriminatedUnion("type",[it.object({type:it.literal("url"),url:it.string()}),it.object({type:it.literal("api"),name:it.string()})])).optional()}))),L3=Qn({id:"openai.web_search",name:"web_search",inputSchema:M3,outputSchema:O3}),N3=(t={})=>L3(t),D3=Bt(()=>Ee($t.object({searchContextSize:$t.enum(["low","medium","high"]).optional(),userLocation:$t.object({type:$t.literal("approximate"),country:$t.string().optional(),city:$t.string().optional(),region:$t.string().optional(),timezone:$t.string().optional()}).optional()}))),k3=Bt(()=>Ee($t.object({}))),F3=Bt(()=>Ee($t.object({action:$t.discriminatedUnion("type",[$t.object({type:$t.literal("search"),query:$t.string().optional()}),$t.object({type:$t.literal("openPage"),url:$t.string().nullish()}),$t.object({type:$t.literal("findInPage"),url:$t.string().nullish(),pattern:$t.string().nullish()})])}))),U3=Qn({id:"openai.web_search_preview",name:"web_search_preview",inputSchema:k3,outputSchema:F3}),B3={codeInterpreter:T3,fileSearch:A3,imageGeneration:_3,localShell:I3,webSearchPreview:U3,webSearch:N3};function AD(t,e){return e?e.some(r=>t.startsWith(r)):!1}async function G3({prompt:t,systemMessageMode:e,fileIdPrefixes:r,store:n,hasLocalShellTool:o=!1}){var i,a,s,c;let l=[],u=[];for(let{role:d,content:p}of t)switch(d){case"system":{switch(e){case"system":{l.push({role:"system",content:p});break}case"developer":{l.push({role:"developer",content:p});break}case"remove":{u.push({type:"other",message:"system messages are removed for this model"});break}default:{let m=e;throw new Error(`Unsupported system message mode: ${m}`)}}break}case"user":{l.push({role:"user",content:p.map((m,f)=>{var h,S,g;switch(m.type){case"text":return{type:"input_text",text:m.text};case"file":if(m.mediaType.startsWith("image/")){let E=m.mediaType==="image/*"?"image/jpeg":m.mediaType;return{type:"input_image",...m.data instanceof URL?{image_url:m.data.toString()}:typeof m.data=="string"&&AD(m.data,r)?{file_id:m.data}:{image_url:`data:${E};base64,${ma(m.data)}`},detail:(S=(h=m.providerOptions)==null?void 0:h.openai)==null?void 0:S.imageDetail}}else{if(m.mediaType==="application/pdf")return m.data instanceof URL?{type:"input_file",file_url:m.data.toString()}:{type:"input_file",...typeof m.data=="string"&&AD(m.data,r)?{file_id:m.data}:{filename:(g=m.filename)!=null?g:`part-${f}.pdf`,file_data:`data:application/pdf;base64,${ma(m.data)}`}};throw new H3({functionality:`file part media type ${m.mediaType}`})}}})});break}case"assistant":{let m={},f={};for(let h of p)switch(h.type){case"text":{let S=(a=(i=h.providerOptions)==null?void 0:i.openai)==null?void 0:a.itemId;if(n&&S!=null){l.push({type:"item_reference",id:S});break}l.push({role:"assistant",content:[{type:"output_text",text:h.text}],id:S});break}case"tool-call":{if(f[h.toolCallId]=h,h.providerExecuted)break;let S=(c=(s=h.providerOptions)==null?void 0:s.openai)==null?void 0:c.itemId;if(n&&S!=null){l.push({type:"item_reference",id:S});break}if(o&&h.toolName==="local_shell"){let g=await qo({value:h.input,schema:MD});l.push({type:"local_shell_call",call_id:h.toolCallId,id:S,action:{type:"exec",command:g.action.command,timeout_ms:g.action.timeoutMs,user:g.action.user,working_directory:g.action.workingDirectory,env:g.action.env}});break}l.push({type:"function_call",call_id:h.toolCallId,name:h.toolName,arguments:JSON.stringify(h.input),id:S});break}case"tool-result":{n?l.push({type:"item_reference",id:h.toolCallId}):u.push({type:"other",message:`Results for OpenAI tool ${h.toolName} are not sent to the API when store is false`});break}case"reasoning":{let S=await Yr({provider:"openai",providerOptions:h.providerOptions,schema:j3}),g=S?.itemId;if(g!=null){let E=m[g];if(n)E===void 0&&(l.push({type:"item_reference",id:g}),m[g]={type:"reasoning",id:g,summary:[]});else{let y=[];h.text.length>0?y.push({type:"summary_text",text:h.text}):E!==void 0&&u.push({type:"other",message:`Cannot append empty reasoning part to existing reasoning sequence. Skipping reasoning part: ${JSON.stringify(h)}.`}),E===void 0?(m[g]={type:"reasoning",id:g,encrypted_content:S?.reasoningEncryptedContent,summary:y},l.push(m[g])):(E.summary.push(...y),S?.reasoningEncryptedContent!=null&&(E.encrypted_content=S.reasoningEncryptedContent))}}else u.push({type:"other",message:`Non-OpenAI reasoning parts are not supported. Skipping reasoning part: ${JSON.stringify(h)}.`});break}}break}case"tool":{for(let m of p){let f=m.output;if(o&&m.toolName==="local_shell"&&f.type==="json"){let S=await qo({value:f.value,schema:OD});l.push({type:"local_shell_call_output",call_id:m.toolCallId,output:S.output});break}let h;switch(f.type){case"text":case"error-text":h=f.value;break;case"json":case"error-json":h=JSON.stringify(f.value);break;case"content":h=f.value.map(S=>{switch(S.type){case"text":return{type:"input_text",text:S.text};case"media":return S.mediaType.startsWith("image/")?{type:"input_image",image_url:`data:${S.mediaType};base64,${S.data}`}:{type:"input_file",filename:"data",file_data:`data:${S.mediaType};base64,${S.data}`}}});break}l.push({type:"function_call_output",call_id:m.toolCallId,output:h})}break}default:{let m=d;throw new Error(`Unsupported role: ${m}`)}}return{input:l,warnings:u}}var j3=wb.object({itemId:wb.string().nullish(),reasoningEncryptedContent:wb.string().nullish()});function CD({finishReason:t,hasFunctionCall:e}){switch(t){case void 0:case null:return e?"tool-calls":"stop";case"max_output_tokens":return"length";case"content_filter":return"content-filter";default:return e?"tool-calls":"unknown"}}var V3=Tt(()=>Ee(T.union([T.object({type:T.literal("response.output_text.delta"),item_id:T.string(),delta:T.string(),logprobs:T.array(T.object({token:T.string(),logprob:T.number(),top_logprobs:T.array(T.object({token:T.string(),logprob:T.number()}))})).nullish()}),T.object({type:T.enum(["response.completed","response.incomplete"]),response:T.object({incomplete_details:T.object({reason:T.string()}).nullish(),usage:T.object({input_tokens:T.number(),input_tokens_details:T.object({cached_tokens:T.number().nullish()}).nullish(),output_tokens:T.number(),output_tokens_details:T.object({reasoning_tokens:T.number().nullish()}).nullish()}),service_tier:T.string().nullish()})}),T.object({type:T.literal("response.created"),response:T.object({id:T.string(),created_at:T.number(),model:T.string(),service_tier:T.string().nullish()})}),T.object({type:T.literal("response.output_item.added"),output_index:T.number(),item:T.discriminatedUnion("type",[T.object({type:T.literal("message"),id:T.string()}),T.object({type:T.literal("reasoning"),id:T.string(),encrypted_content:T.string().nullish()}),T.object({type:T.literal("function_call"),id:T.string(),call_id:T.string(),name:T.string(),arguments:T.string()}),T.object({type:T.literal("web_search_call"),id:T.string(),status:T.string()}),T.object({type:T.literal("computer_call"),id:T.string(),status:T.string()}),T.object({type:T.literal("file_search_call"),id:T.string()}),T.object({type:T.literal("image_generation_call"),id:T.string()}),T.object({type:T.literal("code_interpreter_call"),id:T.string(),container_id:T.string(),code:T.string().nullable(),outputs:T.array(T.discriminatedUnion("type",[T.object({type:T.literal("logs"),logs:T.string()}),T.object({type:T.literal("image"),url:T.string()})])).nullable(),status:T.string()})])}),T.object({type:T.literal("response.output_item.done"),output_index:T.number(),item:T.discriminatedUnion("type",[T.object({type:T.literal("message"),id:T.string()}),T.object({type:T.literal("reasoning"),id:T.string(),encrypted_content:T.string().nullish()}),T.object({type:T.literal("function_call"),id:T.string(),call_id:T.string(),name:T.string(),arguments:T.string(),status:T.literal("completed")}),T.object({type:T.literal("code_interpreter_call"),id:T.string(),code:T.string().nullable(),container_id:T.string(),outputs:T.array(T.discriminatedUnion("type",[T.object({type:T.literal("logs"),logs:T.string()}),T.object({type:T.literal("image"),url:T.string()})])).nullable()}),T.object({type:T.literal("image_generation_call"),id:T.string(),result:T.string()}),T.object({type:T.literal("web_search_call"),id:T.string(),status:T.string(),action:T.discriminatedUnion("type",[T.object({type:T.literal("search"),query:T.string().nullish(),sources:T.array(T.discriminatedUnion("type",[T.object({type:T.literal("url"),url:T.string()}),T.object({type:T.literal("api"),name:T.string()})])).nullish()}),T.object({type:T.literal("open_page"),url:T.string().nullish()}),T.object({type:T.literal("find_in_page"),url:T.string().nullish(),pattern:T.string().nullish()})])}),T.object({type:T.literal("file_search_call"),id:T.string(),queries:T.array(T.string()),results:T.array(T.object({attributes:T.record(T.string(),T.unknown()),file_id:T.string(),filename:T.string(),score:T.number(),text:T.string()})).nullish()}),T.object({type:T.literal("local_shell_call"),id:T.string(),call_id:T.string(),action:T.object({type:T.literal("exec"),command:T.array(T.string()),timeout_ms:T.number().optional(),user:T.string().optional(),working_directory:T.string().optional(),env:T.record(T.string(),T.string()).optional()})}),T.object({type:T.literal("computer_call"),id:T.string(),status:T.literal("completed")})])}),T.object({type:T.literal("response.function_call_arguments.delta"),item_id:T.string(),output_index:T.number(),delta:T.string()}),T.object({type:T.literal("response.image_generation_call.partial_image"),item_id:T.string(),output_index:T.number(),partial_image_b64:T.string()}),T.object({type:T.literal("response.code_interpreter_call_code.delta"),item_id:T.string(),output_index:T.number(),delta:T.string()}),T.object({type:T.literal("response.code_interpreter_call_code.done"),item_id:T.string(),output_index:T.number(),code:T.string()}),T.object({type:T.literal("response.output_text.annotation.added"),annotation:T.discriminatedUnion("type",[T.object({type:T.literal("url_citation"),start_index:T.number(),end_index:T.number(),url:T.string(),title:T.string()}),T.object({type:T.literal("file_citation"),file_id:T.string(),filename:T.string().nullish(),index:T.number().nullish(),start_index:T.number().nullish(),end_index:T.number().nullish(),quote:T.string().nullish()})])}),T.object({type:T.literal("response.reasoning_summary_part.added"),item_id:T.string(),summary_index:T.number()}),T.object({type:T.literal("response.reasoning_summary_text.delta"),item_id:T.string(),summary_index:T.number(),delta:T.string()}),T.object({type:T.literal("response.reasoning_summary_part.done"),item_id:T.string(),summary_index:T.number()}),T.object({type:T.literal("error"),sequence_number:T.number(),error:T.object({type:T.string(),code:T.string(),message:T.string(),param:T.string().nullish()})}),T.object({type:T.string()}).loose().transform(t=>({type:"unknown_chunk",message:t.type}))]))),W3=Tt(()=>Ee(T.object({id:T.string().optional(),created_at:T.number().optional(),error:T.object({message:T.string(),type:T.string(),param:T.string().nullish(),code:T.string()}).nullish(),model:T.string().optional(),output:T.array(T.discriminatedUnion("type",[T.object({type:T.literal("message"),role:T.literal("assistant"),id:T.string(),content:T.array(T.object({type:T.literal("output_text"),text:T.string(),logprobs:T.array(T.object({token:T.string(),logprob:T.number(),top_logprobs:T.array(T.object({token:T.string(),logprob:T.number()}))})).nullish(),annotations:T.array(T.discriminatedUnion("type",[T.object({type:T.literal("url_citation"),start_index:T.number(),end_index:T.number(),url:T.string(),title:T.string()}),T.object({type:T.literal("file_citation"),file_id:T.string(),filename:T.string().nullish(),index:T.number().nullish(),start_index:T.number().nullish(),end_index:T.number().nullish(),quote:T.string().nullish()}),T.object({type:T.literal("container_file_citation"),container_id:T.string(),file_id:T.string(),filename:T.string().nullish(),start_index:T.number().nullish(),end_index:T.number().nullish(),index:T.number().nullish()}),T.object({type:T.literal("file_path"),file_id:T.string(),index:T.number().nullish()})]))}))}),T.object({type:T.literal("web_search_call"),id:T.string(),status:T.string(),action:T.discriminatedUnion("type",[T.object({type:T.literal("search"),query:T.string().nullish(),sources:T.array(T.discriminatedUnion("type",[T.object({type:T.literal("url"),url:T.string()}),T.object({type:T.literal("api"),name:T.string()})])).nullish()}),T.object({type:T.literal("open_page"),url:T.string().nullish()}),T.object({type:T.literal("find_in_page"),url:T.string().nullish(),pattern:T.string().nullish()})])}),T.object({type:T.literal("file_search_call"),id:T.string(),queries:T.array(T.string()),results:T.array(T.object({attributes:T.record(T.string(),T.union([T.string(),T.number(),T.boolean()])),file_id:T.string(),filename:T.string(),score:T.number(),text:T.string()})).nullish()}),T.object({type:T.literal("code_interpreter_call"),id:T.string(),code:T.string().nullable(),container_id:T.string(),outputs:T.array(T.discriminatedUnion("type",[T.object({type:T.literal("logs"),logs:T.string()}),T.object({type:T.literal("image"),url:T.string()})])).nullable()}),T.object({type:T.literal("image_generation_call"),id:T.string(),result:T.string()}),T.object({type:T.literal("local_shell_call"),id:T.string(),call_id:T.string(),action:T.object({type:T.literal("exec"),command:T.array(T.string()),timeout_ms:T.number().optional(),user:T.string().optional(),working_directory:T.string().optional(),env:T.record(T.string(),T.string()).optional()})}),T.object({type:T.literal("function_call"),call_id:T.string(),name:T.string(),arguments:T.string(),id:T.string()}),T.object({type:T.literal("computer_call"),id:T.string(),status:T.string().optional()}),T.object({type:T.literal("reasoning"),id:T.string(),encrypted_content:T.string().nullish(),summary:T.array(T.object({type:T.literal("summary_text"),text:T.string()}))})])).optional(),service_tier:T.string().nullish(),incomplete_details:T.object({reason:T.string()}).nullish(),usage:T.object({input_tokens:T.number(),input_tokens_details:T.object({cached_tokens:T.number().nullish()}).nullish(),output_tokens:T.number(),output_tokens_details:T.object({reasoning_tokens:T.number().nullish()}).nullish()}).optional()}))),LD=20,$3=["o1","o1-2024-12-17","o3","o3-2025-04-16","o3-deep-research","o3-deep-research-2025-06-26","o3-mini","o3-mini-2025-01-31","o4-mini","o4-mini-2025-04-16","o4-mini-deep-research","o4-mini-deep-research-2025-06-26","codex-mini-latest","computer-use-preview","gpt-5","gpt-5-2025-08-07","gpt-5-codex","gpt-5-mini","gpt-5-mini-2025-08-07","gpt-5-nano","gpt-5-nano-2025-08-07","gpt-5-pro","gpt-5-pro-2025-10-06","gpt-5.1","gpt-5.1-chat-latest","gpt-5.1-codex-mini","gpt-5.1-codex","gpt-5.1-codex-max","gpt-5.2","gpt-5.2-chat-latest","gpt-5.2-pro"],YWe=["gpt-4.1","gpt-4.1-2025-04-14","gpt-4.1-mini","gpt-4.1-mini-2025-04-14","gpt-4.1-nano","gpt-4.1-nano-2025-04-14","gpt-4o","gpt-4o-2024-05-13","gpt-4o-2024-08-06","gpt-4o-2024-11-20","gpt-4o-audio-preview","gpt-4o-audio-preview-2024-10-01","gpt-4o-audio-preview-2024-12-17","gpt-4o-search-preview","gpt-4o-search-preview-2025-03-11","gpt-4o-mini-search-preview","gpt-4o-mini-search-preview-2025-03-11","gpt-4o-mini","gpt-4o-mini-2024-07-18","gpt-4-turbo","gpt-4-turbo-2024-04-09","gpt-4-turbo-preview","gpt-4-0125-preview","gpt-4-1106-preview","gpt-4","gpt-4-0613","gpt-4.5-preview","gpt-4.5-preview-2025-02-27","gpt-3.5-turbo-0125","gpt-3.5-turbo","gpt-3.5-turbo-1106","chatgpt-4o-latest","gpt-5-chat-latest",...$3],q3=Tt(()=>Ee(Lt.object({conversation:Lt.string().nullish(),include:Lt.array(Lt.enum(["reasoning.encrypted_content","file_search_call.results","message.output_text.logprobs"])).nullish(),instructions:Lt.string().nullish(),logprobs:Lt.union([Lt.boolean(),Lt.number().min(1).max(LD)]).optional(),maxToolCalls:Lt.number().nullish(),metadata:Lt.any().nullish(),parallelToolCalls:Lt.boolean().nullish(),previousResponseId:Lt.string().nullish(),promptCacheKey:Lt.string().nullish(),promptCacheRetention:Lt.enum(["in_memory","24h"]).nullish(),reasoningEffort:Lt.string().nullish(),reasoningSummary:Lt.string().nullish(),safetyIdentifier:Lt.string().nullish(),serviceTier:Lt.enum(["auto","flex","priority","default"]).nullish(),store:Lt.boolean().nullish(),strictJsonSchema:Lt.boolean().nullish(),textVerbosity:Lt.enum(["low","medium","high"]).nullish(),truncation:Lt.enum(["auto","disabled"]).nullish(),user:Lt.string().nullish()})));async function Y3({tools:t,toolChoice:e,strictJsonSchema:r}){t=t?.length?t:void 0;let n=[];if(t==null)return{tools:void 0,toolChoice:void 0,toolWarnings:n};let o=[];for(let a of t)switch(a.type){case"function":o.push({type:"function",name:a.name,description:a.description,parameters:a.inputSchema,strict:r});break;case"provider-defined":{switch(a.id){case"openai.file_search":{let s=await qo({value:a.args,schema:b3});o.push({type:"file_search",vector_store_ids:s.vectorStoreIds,max_num_results:s.maxNumResults,ranking_options:s.ranking?{ranker:s.ranking.ranker,score_threshold:s.ranking.scoreThreshold}:void 0,filters:s.filters});break}case"openai.local_shell":{o.push({type:"local_shell"});break}case"openai.web_search_preview":{let s=await qo({value:a.args,schema:D3});o.push({type:"web_search_preview",search_context_size:s.searchContextSize,user_location:s.userLocation});break}case"openai.web_search":{let s=await qo({value:a.args,schema:P3});o.push({type:"web_search",filters:s.filters!=null?{allowed_domains:s.filters.allowedDomains}:void 0,external_web_access:s.externalWebAccess,search_context_size:s.searchContextSize,user_location:s.userLocation});break}case"openai.code_interpreter":{let s=await qo({value:a.args,schema:y3});o.push({type:"code_interpreter",container:s.container==null?{type:"auto",file_ids:void 0}:typeof s.container=="string"?s.container:{type:"auto",file_ids:s.container.fileIds}});break}case"openai.image_generation":{let s=await qo({value:a.args,schema:C3});o.push({type:"image_generation",background:s.background,input_fidelity:s.inputFidelity,input_image_mask:s.inputImageMask?{file_id:s.inputImageMask.fileId,image_url:s.inputImageMask.imageUrl}:void 0,model:s.model,size:s.size,quality:s.quality,moderation:s.moderation,output_format:s.outputFormat,output_compression:s.outputCompression});break}}break}default:n.push({type:"unsupported-tool",tool:a});break}if(e==null)return{tools:o,toolChoice:void 0,toolWarnings:n};let i=e.type;switch(i){case"auto":case"none":case"required":return{tools:o,toolChoice:i,toolWarnings:n};case"tool":return{tools:o,toolChoice:e.toolName==="code_interpreter"||e.toolName==="file_search"||e.toolName==="image_generation"||e.toolName==="web_search_preview"||e.toolName==="web_search"?{type:e.toolName}:{type:"function",name:e.toolName},toolWarnings:n};default:{let a=i;throw new K3({functionality:`tool choice type: ${a}`})}}}var X3=class{constructor(t,e){this.specificationVersion="v2",this.supportedUrls={"image/*":[/^https?:\/\/.*$/],"application/pdf":[/^https?:\/\/.*$/]},this.modelId=t,this.config=e}get provider(){return this.config.provider}async getArgs({maxOutputTokens:t,temperature:e,stopSequences:r,topP:n,topK:o,presencePenalty:i,frequencyPenalty:a,seed:s,prompt:c,providerOptions:l,tools:u,toolChoice:d,responseFormat:p}){var m,f,h,S;let g=[],E=_D(this.modelId);o!=null&&g.push({type:"unsupported-setting",setting:"topK"}),s!=null&&g.push({type:"unsupported-setting",setting:"seed"}),i!=null&&g.push({type:"unsupported-setting",setting:"presencePenalty"}),a!=null&&g.push({type:"unsupported-setting",setting:"frequencyPenalty"}),r!=null&&g.push({type:"unsupported-setting",setting:"stopSequences"});let y=await Yr({provider:"openai",providerOptions:l,schema:q3});y?.conversation&&y?.previousResponseId&&g.push({type:"unsupported-setting",setting:"conversation",details:"conversation and previousResponseId cannot be used together"});let{input:b,warnings:C}=await G3({prompt:c,systemMessageMode:E.systemMessageMode,fileIdPrefixes:this.config.fileIdPrefixes,store:(m=y?.store)!=null?m:!0,hasLocalShellTool:M("openai.local_shell")});g.push(...C);let I=(f=y?.strictJsonSchema)!=null?f:!1,_=y?.include;function R(q){_==null?_=[q]:_.includes(q)||(_=[..._,q])}function M(q){return u?.find(X=>X.type==="provider-defined"&&X.id===q)!=null}let P=typeof y?.logprobs=="number"?y?.logprobs:y?.logprobs===!0?LD:void 0;P&&R("message.output_text.logprobs");let B=(h=u?.find(q=>q.type==="provider-defined"&&(q.id==="openai.web_search"||q.id==="openai.web_search_preview")))==null?void 0:h.name;B&&R("web_search_call.action.sources"),M("openai.code_interpreter")&&R("code_interpreter_call.outputs");let F=y?.store;F===!1&&E.isReasoningModel&&R("reasoning.encrypted_content");let G={model:this.modelId,input:b,temperature:e,top_p:n,max_output_tokens:t,...(p?.type==="json"||y?.textVerbosity)&&{text:{...p?.type==="json"&&{format:p.schema!=null?{type:"json_schema",strict:I,name:(S=p.name)!=null?S:"response",description:p.description,schema:p.schema}:{type:"json_object"}},...y?.textVerbosity&&{verbosity:y.textVerbosity}}},conversation:y?.conversation,max_tool_calls:y?.maxToolCalls,metadata:y?.metadata,parallel_tool_calls:y?.parallelToolCalls,previous_response_id:y?.previousResponseId,store:F,user:y?.user,instructions:y?.instructions,service_tier:y?.serviceTier,include:_,prompt_cache_key:y?.promptCacheKey,prompt_cache_retention:y?.promptCacheRetention,safety_identifier:y?.safetyIdentifier,top_logprobs:P,truncation:y?.truncation,...E.isReasoningModel&&(y?.reasoningEffort!=null||y?.reasoningSummary!=null)&&{reasoning:{...y?.reasoningEffort!=null&&{effort:y.reasoningEffort},...y?.reasoningSummary!=null&&{summary:y.reasoningSummary}}}};E.isReasoningModel?y?.reasoningEffort==="none"&&E.supportsNonReasoningParameters||(G.temperature!=null&&(G.temperature=void 0,g.push({type:"unsupported-setting",setting:"temperature",details:"temperature is not supported for reasoning models"})),G.top_p!=null&&(G.top_p=void 0,g.push({type:"unsupported-setting",setting:"topP",details:"topP is not supported for reasoning models"}))):(y?.reasoningEffort!=null&&g.push({type:"unsupported-setting",setting:"reasoningEffort",details:"reasoningEffort is not supported for non-reasoning models"}),y?.reasoningSummary!=null&&g.push({type:"unsupported-setting",setting:"reasoningSummary",details:"reasoningSummary is not supported for non-reasoning models"})),y?.serviceTier==="flex"&&!E.supportsFlexProcessing&&(g.push({type:"unsupported-setting",setting:"serviceTier",details:"flex processing is only available for o3, o4-mini, and gpt-5 models"}),delete G.service_tier),y?.serviceTier==="priority"&&!E.supportsPriorityProcessing&&(g.push({type:"unsupported-setting",setting:"serviceTier",details:"priority processing is only available for supported models (gpt-4, gpt-5, gpt-5-mini, o3, o4-mini) and requires Enterprise access. gpt-5-nano is not supported"}),delete G.service_tier);let{tools:z,toolChoice:ae,toolWarnings:W}=await Y3({tools:u,toolChoice:d,strictJsonSchema:I});return{webSearchToolName:B,args:{...G,tools:z,tool_choice:ae},warnings:[...g,...W],store:F}}async doGenerate(t){var e,r,n,o,i,a,s,c,l,u,d,p,m,f,h,S,g,E,y,b,C,I,_,R,M,P,B,F;let{args:G,warnings:z,webSearchToolName:ae}=await this.getArgs(t),W=this.config.url({path:"/responses",modelId:this.modelId}),q=this.config.provider.replace(".responses",""),{responseHeaders:X,value:ne,rawValue:de}=await Xr({url:W,headers:br(this.config.headers(),t.headers),body:G,failedResponseHandler:Yo,successfulResponseHandler:Zn(W3),abortSignal:t.abortSignal,fetch:this.config.fetch});if(ne.error)throw new z3({message:ne.error.message,url:W,requestBodyValues:G,statusCode:400,responseHeaders:X,responseBody:de,isRetryable:!1});let Te=[],te=[],be=!1;for(let x of ne.output)switch(x.type){case"reasoning":{x.summary.length===0&&x.summary.push({type:"summary_text",text:""});for(let se of x.summary)Te.push({type:"reasoning",text:se.text,providerMetadata:{[q]:{itemId:x.id,reasoningEncryptedContent:(e=x.encrypted_content)!=null?e:null}}});break}case"image_generation_call":{Te.push({type:"tool-call",toolCallId:x.id,toolName:"image_generation",input:"{}",providerExecuted:!0}),Te.push({type:"tool-result",toolCallId:x.id,toolName:"image_generation",result:{result:x.result},providerExecuted:!0});break}case"local_shell_call":{Te.push({type:"tool-call",toolCallId:x.call_id,toolName:"local_shell",input:JSON.stringify({action:x.action}),providerMetadata:{[q]:{itemId:x.id}}});break}case"message":{for(let se of x.content){(n=(r=t.providerOptions)==null?void 0:r.openai)!=null&&n.logprobs&&se.logprobs&&te.push(se.logprobs),Te.push({type:"text",text:se.text,providerMetadata:{[q]:{itemId:x.id}}});for(let Ae of se.annotations)Ae.type==="url_citation"?Te.push({type:"source",sourceType:"url",id:(a=(i=(o=this.config).generateId)==null?void 0:i.call(o))!=null?a:vn(),url:Ae.url,title:Ae.title}):Ae.type==="file_citation"?Te.push({type:"source",sourceType:"document",id:(l=(c=(s=this.config).generateId)==null?void 0:c.call(s))!=null?l:vn(),mediaType:"text/plain",title:(d=(u=Ae.quote)!=null?u:Ae.filename)!=null?d:"Document",filename:(p=Ae.filename)!=null?p:Ae.file_id,...Ae.file_id?{providerMetadata:{[q]:{fileId:Ae.file_id}}}:{}}):Ae.type==="container_file_citation"?Te.push({type:"source",sourceType:"document",id:(h=(f=(m=this.config).generateId)==null?void 0:f.call(m))!=null?h:vn(),mediaType:"text/plain",title:(g=(S=Ae.filename)!=null?S:Ae.file_id)!=null?g:"Document",filename:(E=Ae.filename)!=null?E:Ae.file_id,providerMetadata:{[q]:{fileId:Ae.file_id,containerId:Ae.container_id,...Ae.index!=null?{index:Ae.index}:{}}}}):Ae.type==="file_path"&&Te.push({type:"source",sourceType:"document",id:(C=(b=(y=this.config).generateId)==null?void 0:b.call(y))!=null?C:vn(),mediaType:"application/octet-stream",title:Ae.file_id,filename:Ae.file_id,providerMetadata:{[q]:{fileId:Ae.file_id,...Ae.index!=null?{index:Ae.index}:{}}}})}break}case"function_call":{be=!0,Te.push({type:"tool-call",toolCallId:x.call_id,toolName:x.name,input:x.arguments,providerMetadata:{[q]:{itemId:x.id}}});break}case"web_search_call":{Te.push({type:"tool-call",toolCallId:x.id,toolName:ae??"web_search",input:JSON.stringify({}),providerExecuted:!0}),Te.push({type:"tool-result",toolCallId:x.id,toolName:ae??"web_search",result:wD(x.action),providerExecuted:!0});break}case"computer_call":{Te.push({type:"tool-call",toolCallId:x.id,toolName:"computer_use",input:"",providerExecuted:!0}),Te.push({type:"tool-result",toolCallId:x.id,toolName:"computer_use",result:{type:"computer_use_tool_result",status:x.status||"completed"},providerExecuted:!0});break}case"file_search_call":{Te.push({type:"tool-call",toolCallId:x.id,toolName:"file_search",input:"{}",providerExecuted:!0}),Te.push({type:"tool-result",toolCallId:x.id,toolName:"file_search",result:{queries:x.queries,results:(_=(I=x.results)==null?void 0:I.map(se=>({attributes:se.attributes,fileId:se.file_id,filename:se.filename,score:se.score,text:se.text})))!=null?_:null},providerExecuted:!0});break}case"code_interpreter_call":{Te.push({type:"tool-call",toolCallId:x.id,toolName:"code_interpreter",input:JSON.stringify({code:x.code,containerId:x.container_id}),providerExecuted:!0}),Te.push({type:"tool-result",toolCallId:x.id,toolName:"code_interpreter",result:{outputs:x.outputs},providerExecuted:!0});break}}let Pe={[q]:{...ne.id!=null?{responseId:ne.id}:{}}};te.length>0&&(Pe[q].logprobs=te),typeof ne.service_tier=="string"&&(Pe[q].serviceTier=ne.service_tier);let ve=ne.usage;return{content:Te,finishReason:CD({finishReason:(R=ne.incomplete_details)==null?void 0:R.reason,hasFunctionCall:be}),usage:{inputTokens:ve.input_tokens,outputTokens:ve.output_tokens,totalTokens:ve.input_tokens+ve.output_tokens,reasoningTokens:(P=(M=ve.output_tokens_details)==null?void 0:M.reasoning_tokens)!=null?P:void 0,cachedInputTokens:(F=(B=ve.input_tokens_details)==null?void 0:B.cached_tokens)!=null?F:void 0},request:{body:G},response:{id:ne.id,timestamp:new Date(ne.created_at*1e3),modelId:ne.model,headers:X,body:de},providerMetadata:Pe,warnings:z}}async doStream(t){let{args:e,warnings:r,webSearchToolName:n,store:o}=await this.getArgs(t),{responseHeaders:i,value:a}=await Xr({url:this.config.url({path:"/responses",modelId:this.modelId}),headers:br(this.config.headers(),t.headers),body:{...e,stream:!0},failedResponseHandler:Yo,successfulResponseHandler:Rc(V3),abortSignal:t.abortSignal,fetch:this.config.fetch}),s=this,c=this.config.provider.replace(".responses",""),l="unknown",u={inputTokens:void 0,outputTokens:void 0,totalTokens:void 0},d=[],p=null,m={},f=[],h=!1,S={},g;return{stream:a.pipeThrough(new TransformStream({start(E){E.enqueue({type:"stream-start",warnings:r})},transform(E,y){var b,C,I,_,R,M,P,B,F,G,z,ae,W,q,X,ne,de,Te,te,be,Pe,ve;if(t.includeRawChunks&&y.enqueue({type:"raw",rawValue:E.rawValue}),!E.success){l="error",y.enqueue({type:"error",error:E.error});return}let x=E.value;if(RD(x))x.item.type==="function_call"?(m[x.output_index]={toolName:x.item.name,toolCallId:x.item.call_id},y.enqueue({type:"tool-input-start",id:x.item.call_id,toolName:x.item.name})):x.item.type==="web_search_call"?(m[x.output_index]={toolName:n??"web_search",toolCallId:x.item.id},y.enqueue({type:"tool-input-start",id:x.item.id,toolName:n??"web_search",providerExecuted:!0}),y.enqueue({type:"tool-input-end",id:x.item.id}),y.enqueue({type:"tool-call",toolCallId:x.item.id,toolName:n??"web_search",input:JSON.stringify({}),providerExecuted:!0})):x.item.type==="computer_call"?(m[x.output_index]={toolName:"computer_use",toolCallId:x.item.id},y.enqueue({type:"tool-input-start",id:x.item.id,toolName:"computer_use",providerExecuted:!0})):x.item.type==="code_interpreter_call"?(m[x.output_index]={toolName:"code_interpreter",toolCallId:x.item.id,codeInterpreter:{containerId:x.item.container_id}},y.enqueue({type:"tool-input-start",id:x.item.id,toolName:"code_interpreter",providerExecuted:!0}),y.enqueue({type:"tool-input-delta",id:x.item.id,delta:`{"containerId":"${x.item.container_id}","code":"`})):x.item.type==="file_search_call"?y.enqueue({type:"tool-call",toolCallId:x.item.id,toolName:"file_search",input:"{}",providerExecuted:!0}):x.item.type==="image_generation_call"?y.enqueue({type:"tool-call",toolCallId:x.item.id,toolName:"image_generation",input:"{}",providerExecuted:!0}):x.item.type==="message"?(f.splice(0,f.length),y.enqueue({type:"text-start",id:x.item.id,providerMetadata:{[c]:{itemId:x.item.id}}})):RD(x)&&x.item.type==="reasoning"&&(S[x.item.id]={encryptedContent:x.item.encrypted_content,summaryParts:{0:"active"}},y.enqueue({type:"reasoning-start",id:`${x.item.id}:0`,providerMetadata:{[c]:{itemId:x.item.id,reasoningEncryptedContent:(b=x.item.encrypted_content)!=null?b:null}}}));else if(Q3(x)){if(x.item.type==="message")y.enqueue({type:"text-end",id:x.item.id,providerMetadata:{[c]:{itemId:x.item.id,...f.length>0&&{annotations:f}}}});else if(x.item.type==="function_call")m[x.output_index]=void 0,h=!0,y.enqueue({type:"tool-input-end",id:x.item.call_id}),y.enqueue({type:"tool-call",toolCallId:x.item.call_id,toolName:x.item.name,input:x.item.arguments,providerMetadata:{[c]:{itemId:x.item.id}}});else if(x.item.type==="web_search_call")m[x.output_index]=void 0,y.enqueue({type:"tool-result",toolCallId:x.item.id,toolName:n??"web_search",result:wD(x.item.action),providerExecuted:!0});else if(x.item.type==="computer_call")m[x.output_index]=void 0,y.enqueue({type:"tool-input-end",id:x.item.id}),y.enqueue({type:"tool-call",toolCallId:x.item.id,toolName:"computer_use",input:"",providerExecuted:!0}),y.enqueue({type:"tool-result",toolCallId:x.item.id,toolName:"computer_use",result:{type:"computer_use_tool_result",status:x.item.status||"completed"},providerExecuted:!0});else if(x.item.type==="file_search_call")m[x.output_index]=void 0,y.enqueue({type:"tool-result",toolCallId:x.item.id,toolName:"file_search",result:{queries:x.item.queries,results:(I=(C=x.item.results)==null?void 0:C.map(se=>({attributes:se.attributes,fileId:se.file_id,filename:se.filename,score:se.score,text:se.text})))!=null?I:null},providerExecuted:!0});else if(x.item.type==="code_interpreter_call")m[x.output_index]=void 0,y.enqueue({type:"tool-result",toolCallId:x.item.id,toolName:"code_interpreter",result:{outputs:x.item.outputs},providerExecuted:!0});else if(x.item.type==="image_generation_call")y.enqueue({type:"tool-result",toolCallId:x.item.id,toolName:"image_generation",result:{result:x.item.result},providerExecuted:!0});else if(x.item.type==="local_shell_call")m[x.output_index]=void 0,y.enqueue({type:"tool-call",toolCallId:x.item.call_id,toolName:"local_shell",input:JSON.stringify({action:{type:"exec",command:x.item.action.command,timeoutMs:x.item.action.timeout_ms,user:x.item.action.user,workingDirectory:x.item.action.working_directory,env:x.item.action.env}}),providerMetadata:{[c]:{itemId:x.item.id}}});else if(x.item.type==="reasoning"){let se=S[x.item.id],Ae=Object.entries(se.summaryParts).filter(([dn,Mo])=>Mo==="active"||Mo==="can-conclude").map(([dn])=>dn);for(let dn of Ae)y.enqueue({type:"reasoning-end",id:`${x.item.id}:${dn}`,providerMetadata:{[c]:{itemId:x.item.id,reasoningEncryptedContent:(_=x.item.encrypted_content)!=null?_:null}}});delete S[x.item.id]}}else if(tJ(x)){let se=m[x.output_index];se!=null&&y.enqueue({type:"tool-input-delta",id:se.toolCallId,delta:x.delta})}else if(rJ(x)){let se=m[x.output_index];se!=null&&y.enqueue({type:"tool-input-delta",id:se.toolCallId,delta:JSON.stringify(x.delta).slice(1,-1)})}else if(nJ(x)){let se=m[x.output_index];se!=null&&(y.enqueue({type:"tool-input-delta",id:se.toolCallId,delta:'"}'}),y.enqueue({type:"tool-input-end",id:se.toolCallId}),y.enqueue({type:"tool-call",toolCallId:se.toolCallId,toolName:"code_interpreter",input:JSON.stringify({code:x.code,containerId:se.codeInterpreter.containerId}),providerExecuted:!0}))}else if(eJ(x))p=x.response.id,y.enqueue({type:"response-metadata",id:x.response.id,timestamp:new Date(x.response.created_at*1e3),modelId:x.response.model});else if(J3(x))y.enqueue({type:"text-delta",id:x.item_id,delta:x.delta}),(M=(R=t.providerOptions)==null?void 0:R.openai)!=null&&M.logprobs&&x.logprobs&&d.push(x.logprobs);else if(x.type==="response.reasoning_summary_part.added"){if(x.summary_index>0){let se=S[x.item_id];se.summaryParts[x.summary_index]="active";for(let Ae of Object.keys(se.summaryParts))se.summaryParts[Ae]==="can-conclude"&&(y.enqueue({type:"reasoning-end",id:`${x.item_id}:${Ae}`,providerMetadata:{[c]:{itemId:x.item_id}}}),se.summaryParts[Ae]="concluded");y.enqueue({type:"reasoning-start",id:`${x.item_id}:${x.summary_index}`,providerMetadata:{[c]:{itemId:x.item_id,reasoningEncryptedContent:(B=(P=S[x.item_id])==null?void 0:P.encryptedContent)!=null?B:null}}})}}else x.type==="response.reasoning_summary_text.delta"?y.enqueue({type:"reasoning-delta",id:`${x.item_id}:${x.summary_index}`,delta:x.delta,providerMetadata:{[c]:{itemId:x.item_id}}}):x.type==="response.reasoning_summary_part.done"?o?(y.enqueue({type:"reasoning-end",id:`${x.item_id}:${x.summary_index}`,providerMetadata:{[c]:{itemId:x.item_id}}}),S[x.item_id].summaryParts[x.summary_index]="concluded"):S[x.item_id].summaryParts[x.summary_index]="can-conclude":Z3(x)?(l=CD({finishReason:(F=x.response.incomplete_details)==null?void 0:F.reason,hasFunctionCall:h}),u.inputTokens=x.response.usage.input_tokens,u.outputTokens=x.response.usage.output_tokens,u.totalTokens=x.response.usage.input_tokens+x.response.usage.output_tokens,u.reasoningTokens=(z=(G=x.response.usage.output_tokens_details)==null?void 0:G.reasoning_tokens)!=null?z:void 0,u.cachedInputTokens=(W=(ae=x.response.usage.input_tokens_details)==null?void 0:ae.cached_tokens)!=null?W:void 0,typeof x.response.service_tier=="string"&&(g=x.response.service_tier)):oJ(x)?(f.push(x.annotation),x.annotation.type==="url_citation"?y.enqueue({type:"source",sourceType:"url",id:(ne=(X=(q=s.config).generateId)==null?void 0:X.call(q))!=null?ne:vn(),url:x.annotation.url,title:x.annotation.title}):x.annotation.type==="file_citation"&&y.enqueue({type:"source",sourceType:"document",id:(te=(Te=(de=s.config).generateId)==null?void 0:Te.call(de))!=null?te:vn(),mediaType:"text/plain",title:(Pe=(be=x.annotation.quote)!=null?be:x.annotation.filename)!=null?Pe:"Document",filename:(ve=x.annotation.filename)!=null?ve:x.annotation.file_id,...x.annotation.file_id?{providerMetadata:{[c]:{fileId:x.annotation.file_id}}}:{}})):iJ(x)&&y.enqueue({type:"error",error:x})},flush(E){let y={[c]:{responseId:p}};d.length>0&&(y[c].logprobs=d),g!==void 0&&(y[c].serviceTier=g),E.enqueue({type:"finish",finishReason:l,usage:u,providerMetadata:y})}})),request:{body:e},response:{headers:i}}}};function J3(t){return t.type==="response.output_text.delta"}function Q3(t){return t.type==="response.output_item.done"}function Z3(t){return t.type==="response.completed"||t.type==="response.incomplete"}function eJ(t){return t.type==="response.created"}function tJ(t){return t.type==="response.function_call_arguments.delta"}function rJ(t){return t.type==="response.code_interpreter_call_code.delta"}function nJ(t){return t.type==="response.code_interpreter_call_code.done"}function RD(t){return t.type==="response.output_item.added"}function oJ(t){return t.type==="response.output_text.annotation.added"}function iJ(t){return t.type==="error"}function wD(t){var e;switch(t.type){case"search":return{action:{type:"search",query:(e=t.query)!=null?e:void 0},...t.sources!=null&&{sources:t.sources}};case"open_page":return{action:{type:"openPage",url:t.url}};case"find_in_page":return{action:{type:"findInPage",url:t.url,pattern:t.pattern}}}}var aJ=Tt(()=>Ee(xb.object({instructions:xb.string().nullish(),speed:xb.number().min(.25).max(4).default(1).nullish()}))),sJ=class{constructor(t,e){this.modelId=t,this.config=e,this.specificationVersion="v2"}get provider(){return this.config.provider}async getArgs({text:t,voice:e="alloy",outputFormat:r="mp3",speed:n,instructions:o,language:i,providerOptions:a}){let s=[],c=await Yr({provider:"openai",providerOptions:a,schema:aJ}),l={model:this.modelId,input:t,voice:e,response_format:"mp3",speed:n,instructions:o};if(r&&(["mp3","opus","aac","flac","wav","pcm"].includes(r)?l.response_format=r:s.push({type:"unsupported-setting",setting:"outputFormat",details:`Unsupported output format: ${r}. Using mp3 instead.`})),c){let u={};for(let d in u){let p=u[d];p!==void 0&&(l[d]=p)}}return i&&s.push({type:"unsupported-setting",setting:"language",details:`OpenAI speech models do not support language selection. Language parameter "${i}" was ignored.`}),{requestBody:l,warnings:s}}async doGenerate(t){var e,r,n;let o=(n=(r=(e=this.config._internal)==null?void 0:e.currentDate)==null?void 0:r.call(e))!=null?n:new Date,{requestBody:i,warnings:a}=await this.getArgs(t),{value:s,responseHeaders:c,rawValue:l}=await Xr({url:this.config.url({path:"/audio/speech",modelId:this.modelId}),headers:br(this.config.headers(),t.headers),body:i,failedResponseHandler:Yo,successfulResponseHandler:uD(),abortSignal:t.abortSignal,fetch:this.config.fetch});return{audio:s,warnings:a,request:{body:JSON.stringify(i)},response:{timestamp:o,modelId:this.modelId,headers:c,body:l}}}},lJ=Tt(()=>Ee(zt.object({text:zt.string(),language:zt.string().nullish(),duration:zt.number().nullish(),words:zt.array(zt.object({word:zt.string(),start:zt.number(),end:zt.number()})).nullish(),segments:zt.array(zt.object({id:zt.number(),seek:zt.number(),start:zt.number(),end:zt.number(),text:zt.string(),tokens:zt.array(zt.number()),temperature:zt.number(),avg_logprob:zt.number(),compression_ratio:zt.number(),no_speech_prob:zt.number()})).nullish()}))),cJ=Tt(()=>Ee(ha.object({include:ha.array(ha.string()).optional(),language:ha.string().optional(),prompt:ha.string().optional(),temperature:ha.number().min(0).max(1).default(0).optional(),timestampGranularities:ha.array(ha.enum(["word","segment"])).default(["segment"]).optional()}))),xD={afrikaans:"af",arabic:"ar",armenian:"hy",azerbaijani:"az",belarusian:"be",bosnian:"bs",bulgarian:"bg",catalan:"ca",chinese:"zh",croatian:"hr",czech:"cs",danish:"da",dutch:"nl",english:"en",estonian:"et",finnish:"fi",french:"fr",galician:"gl",german:"de",greek:"el",hebrew:"he",hindi:"hi",hungarian:"hu",icelandic:"is",indonesian:"id",italian:"it",japanese:"ja",kannada:"kn",kazakh:"kk",korean:"ko",latvian:"lv",lithuanian:"lt",macedonian:"mk",malay:"ms",marathi:"mr",maori:"mi",nepali:"ne",norwegian:"no",persian:"fa",polish:"pl",portuguese:"pt",romanian:"ro",russian:"ru",serbian:"sr",slovak:"sk",slovenian:"sl",spanish:"es",swahili:"sw",swedish:"sv",tagalog:"tl",tamil:"ta",thai:"th",turkish:"tr",ukrainian:"uk",urdu:"ur",vietnamese:"vi",welsh:"cy"},uJ=class{constructor(t,e){this.modelId=t,this.config=e,this.specificationVersion="v2"}get provider(){return this.config.provider}async getArgs({audio:t,mediaType:e,providerOptions:r}){let n=[],o=await Yr({provider:"openai",providerOptions:r,schema:cJ}),i=new FormData,a=t instanceof Uint8Array?new Blob([t]):new Blob([gD(t)]);i.append("model",this.modelId);let s=iD(e);if(i.append("file",new File([a],"audio",{type:e}),`audio.${s}`),o){let c={include:o.include,language:o.language,prompt:o.prompt,response_format:["gpt-4o-transcribe","gpt-4o-mini-transcribe"].includes(this.modelId)?"json":"verbose_json",temperature:o.temperature,timestamp_granularities:o.timestampGranularities};for(let[l,u]of Object.entries(c))if(u!=null)if(Array.isArray(u))for(let d of u)i.append(`${l}[]`,String(d));else i.append(l,String(u))}return{formData:i,warnings:n}}async doGenerate(t){var e,r,n,o,i,a,s,c;let l=(n=(r=(e=this.config._internal)==null?void 0:e.currentDate)==null?void 0:r.call(e))!=null?n:new Date,{formData:u,warnings:d}=await this.getArgs(t),{value:p,responseHeaders:m,rawValue:f}=await sD({url:this.config.url({path:"/audio/transcriptions",modelId:this.modelId}),headers:br(this.config.headers(),t.headers),formData:u,failedResponseHandler:Yo,successfulResponseHandler:Zn(lJ),abortSignal:t.abortSignal,fetch:this.config.fetch}),h=p.language!=null&&p.language in xD?xD[p.language]:void 0;return{text:p.text,segments:(s=(a=(o=p.segments)==null?void 0:o.map(S=>({text:S.text,startSecond:S.start,endSecond:S.end})))!=null?a:(i=p.words)==null?void 0:i.map(S=>({text:S.word,startSecond:S.start,endSecond:S.end})))!=null?s:[],language:h,durationInSeconds:(c=p.duration)!=null?c:void 0,warnings:d,response:{timestamp:l,modelId:this.modelId,headers:m,body:f}}}},dJ="2.0.89";function Ib(t={}){var e,r;let n=(e=SD(oD({settingValue:t.baseURL,environmentVariableName:"OPENAI_BASE_URL"})))!=null?e:"https://api.openai.com/v1",o=(r=t.name)!=null?r:"openai",i=()=>Eb({Authorization:`Bearer ${nD({apiKey:t.apiKey,environmentVariableName:"OPENAI_API_KEY",description:"OpenAI"})}`,"OpenAI-Organization":t.organization,"OpenAI-Project":t.project,...t.headers},`ai-sdk/openai/${dJ}`),a=h=>new r3(h,{provider:`${o}.chat`,url:({path:S})=>`${n}${S}`,headers:i,fetch:t.fetch}),s=h=>new s3(h,{provider:`${o}.completion`,url:({path:S})=>`${n}${S}`,headers:i,fetch:t.fetch}),c=h=>new d3(h,{provider:`${o}.embedding`,url:({path:S})=>`${n}${S}`,headers:i,fetch:t.fetch}),l=h=>new h3(h,{provider:`${o}.image`,url:({path:S})=>`${n}${S}`,headers:i,fetch:t.fetch}),u=h=>new uJ(h,{provider:`${o}.transcription`,url:({path:S})=>`${n}${S}`,headers:i,fetch:t.fetch}),d=h=>new sJ(h,{provider:`${o}.speech`,url:({path:S})=>`${n}${S}`,headers:i,fetch:t.fetch}),p=h=>{if(new.target)throw new Error("The OpenAI model function cannot be called with the new keyword.");return m(h)},m=h=>new X3(h,{provider:`${o}.responses`,url:({path:S})=>`${n}${S}`,headers:i,fetch:t.fetch,fileIdPrefixes:["file-"]}),f=function(h){return p(h)};return f.languageModel=p,f.chat=a,f.completion=s,f.responses=m,f.embedding=c,f.textEmbedding=c,f.textEmbeddingModel=c,f.image=l,f.imageModel=l,f.transcription=u,f.transcriptionModel=u,f.speech=d,f.speechModel=d,f.tools=B3,f}var a$e=Ib();function ND(t){let{apiKey:e,sessionId:r,extraHeaders:n,loggerTags:o}=t,i={Authorization:`Bearer ${e}`,[Vm]:Ms??"",...r&&{[C_]:r},...n||{}};return o&&(i[A_]=JSON.stringify(o)),i}var Hh=t=>e=>{let r=ND(t);return pJ({baseURL:`${t.baseUrl}/v1/llm/anthropic/${e}`,headers:r,apiKey:t.apiKey})(e)},Pb=t=>e=>{let r=ND(t);return Ib({baseURL:`${t.baseUrl}/v1/llm/openai/${e}`,headers:r,apiKey:t.apiKey})(e)};var cn=class extends Tr{agentConfig;constructor(e,r){let n={...xl,...e};super(r),this.agentConfig=n}getAgentConfig(){return this.agentConfig}async rankChunksWithAi(e,r){let n={...e,loggerTags:r.loggerTags},o=await this.sendRequest(`/${Y}/web-agent/recommend-chunks-ai`,{method:"POST",body:n,signal:r.abortSignal});return Ew.parse(o)}async rankChunksWithRag(e,r){let n=await this.sendRequest(`/${Y}/web-agent/recommend-chunks`,{method:"POST",body:{cliVersion:Ms,...e},signal:r.abortSignal});return yw.parse(n)}async getScreenshotFromS3(e){let r=await this.sendRequest(`/${Y}/s3/visual-diff-screenshot`,{method:"POST",body:{url:e}});return mJ.string().parse(r)}async getElementLocation(e,r){let n={...e,disableCache:r.disableCache,loggerTags:r.loggerTags,useMemory:r.useMemory,agentConfigVersion:this.agentConfig?.locator},o=await this.sendRequest(`/${Y}/web-agent/locate-element`,{method:"POST",body:n,signal:r.abortSignal});return P_.parse(o)}async getAssertionResult(e,r){let n={...e,disableCache:!!r.disableCache,useConsensus:!!r.useConsensus,attemptNumber:r.attemptNumber,loggerTags:r.loggerTags,useMemory:r.useMemory,agentConfigVersion:this.agentConfig?.assertion},o=await this.sendRequest(`/${Y}/web-agent/assertion`,{method:"POST",body:n,signal:r.abortSignal});return fE.parse(o)}async getLintStepResult(e,r){let n={...e,disableCache:!!r.disableCache,loggerTags:r.loggerTags},o=await this.sendRequest(`/${Y}/web-agent/lint/step`,{method:"POST",body:n,signal:r.abortSignal});return I_.parse(o)}async getLintMcpCopilotMessageResult(e,r){let n={message:e.message,disableCache:!!r.disableCache,loggerTags:r.loggerTags},o=await this.sendRequest(`/${Y}/web-agent/lint/mcp-copilot`,{method:"POST",body:n,signal:r.abortSignal});return w_.parse(o)}async getMcpCopilotConversationEvaluation(e,r){let n={messagesAndToolCalls:e.messagesAndToolCalls,disableCache:!!r.disableCache,loggerTags:r.loggerTags},o=await this.sendRequest(`/${Y}/web-agent/mcp-copilot-conversation-evaluator`,{method:"POST",body:n,signal:r.abortSignal});return x_.parse(o)}async getMcpCopilotChatSummary(e,r){let n={messagesAndToolCalls:e.messagesAndToolCalls,disableCache:!!r.disableCache,loggerTags:r.loggerTags},o=await this.sendRequest(`/${Y}/web-agent/mcp-copilot-chat-summary`,{method:"POST",body:n,signal:r.abortSignal});return __.parse(o)}async getVisualAssertionResult(e,r){let n={...e,disableCache:!!r.disableCache,useConsensus:!!r.useConsensus,attemptNumber:r.attemptNumber,loggerTags:r.loggerTags,useMemory:r.useMemory,agentConfigVersion:this.agentConfig?.["visual-assertion"]},o=await this.sendRequest(`/${Y}/web-agent/visual-assertion`,{method:"POST",body:n,signal:r.abortSignal});return fE.parse(o)}async getAiActionCommand(e,r){let n=await this.sendRequest(`/${Y}/web-agent/next-command-dynamic`,{method:"POST",body:{...e,disableCache:r.disableCache,loggerTags:r.loggerTags},signal:r.abortSignal});return R_.parse(n)}async getMultiturnAiActionCommand(e,r){return await this.sendRequest(`/${Y}/web-agent/ai-action/next-command`,{method:"POST",body:{...e,disableCache:r.disableCache,loggerTags:r.loggerTags},signal:r.abortSignal})}async getMultiturnAiActionEvaluation(e,r){let n=await this.sendRequest(`/${Y}/web-agent/ai-action/evaluate`,{method:"POST",body:{...e,disableCache:r.disableCache,loggerTags:r.loggerTags},signal:r.abortSignal});return ZS.parse(n)}async getReverseMappedDescription(e,r){let n=await this.sendRequest(`/${Y}/web-agent/reverse-mapped-description`,{method:"POST",body:{...e,disableCache:r.disableCache,loggerTags:r.loggerTags},signal:r.abortSignal});return M_.parse(n)}async getTextExtraction(e,r){let n={...e,disableCache:r.disableCache,loggerTags:r.loggerTags,agentConfigVersion:this.agentConfig?.["text-extraction"]},o=await this.sendRequest(`/${Y}/web-agent/text-extraction`,{method:"POST",body:n,signal:r.abortSignal});return Zp.parse(o)}async getPageSummary(e,r){let n={...e,disableCache:r.disableCache,loggerTags:r.loggerTags},o=await this.sendRequest(`/${Y}/web-agent/page-summary`,{method:"POST",body:n,signal:r.abortSignal});return qR.parse(o)}async getSmartWaitingDecision(e,r){let n={...e,disableCache:r.disableCache,loggerTags:r.loggerTags},o=await this.sendRequest(`/${Y}/web-agent/smart-waiting`,{method:"POST",body:n,signal:r.abortSignal});return KR.parse(o)}async getTestResultClassification(e,r){let n=await this.sendRequest(`/${Y}/web-agent/result-classification`,{method:"POST",body:{...e,loggerTags:r.loggerTags},signal:r.abortSignal});return FS.parse(n)}async getExtractedKeywords(e,r){let n=await this.sendRequest(`/${Y}/web-agent/extract-keywords`,{method:"POST",body:e,signal:r.abortSignal});return Nw.parse(n)}async getAutohealingProposal(e,r){let n=await this.sendRequest(`/${Y}/web-agent/autoheal-section`,{method:"POST",body:{...e,loggerTags:r.loggerTags},signal:r.abortSignal});return jR.parse(n)}async getFailureRecoveryProposal(e,r){let n=await this.sendRequest(`/${Y}/web-agent/failure-recovery`,{method:"POST",body:{...e,loggerTags:r.loggerTags},signal:r.abortSignal});return WR.parse(n)}async getFailureRecoveryPlan(e,r){let n=await this.sendRequest(`/${Y}/web-agent/failure-recovery-plan`,{method:"POST",body:{...e,loggerTags:r.loggerTags},signal:r.abortSignal});return VR.parse(n)}async getIframeRegex(e,r){let n=await this.sendRequest(`/${Y}/web-agent/iframe-regex`,{method:"POST",body:e,signal:r.abortSignal});return ZA.parse(n)}getAnthropicModelFactory(e){let{sessionId:r,logger:n,streamType:o}=e;return Hh({baseUrl:this.baseUrl,apiKey:this.apiKey,loggerTags:{...ot(n),promptType:o},sessionId:r})}getOpenAIModelFactory(e){let{sessionId:r,logger:n,streamType:o}=e;return Pb({baseUrl:this.baseUrl,apiKey:this.apiKey,loggerTags:{...ot(n),promptType:o},sessionId:r})}};import{z as Mb}from"zod";var pt=class extends Tr{constructor(e){super({...e,mode:void 0})}getAppUrl(){return jl(this.baseUrl)}async getAuthInfo(){let e=await this.sendRequest(`/${Y}/auth/check`,{method:"GET",retries:10,requestTimeoutMs:5e3,onFailedRequest:r=>{v.warn(`API key check failed: ${r.message}`)}});return V_.parse(e)}async bulkGetRunStatus(e){let r=await this.sendRequest(`/${Y}/runs/status`,{method:"POST",body:e,retries:3,requestTimeoutMs:1e4});return z_.parse(r)}async getTestYAMLExport(e){let r=await this.sendRequest(`/${Y}/tests/export`,{method:"POST",body:e,retries:3,requestTimeoutMs:3e4});return L_.parse(r)}async updateStepCaches(e,r){await this.sendRequest(`/${Y}/cache`,{method:"PATCH",body:e,extraHeaders:r,retries:3,requestTimeoutMs:1e4,initialRetryDelayMs:3e3})}async getStepCacheForTest(e,r){let n=await this.sendRequest(`/${Y}/cache`,{method:"POST",body:e,extraHeaders:r,retries:10,requestTimeoutMs:3e4,initialRetryDelayMs:3e3});return D_.parse(n)}async getWebStepCacheMemoryTraces(e){let r=await this.sendRequest(`/${Y}/cache/traces`,{method:"POST",body:e,retries:10,requestTimeoutMs:3e4,initialRetryDelayMs:3e3});return gE.parse(r)}cacheRouteForPlatform(e){switch(e){case"ANDROID":return"android-cache";case"IOS":return"ios-cache"}}async getMobileStepCacheMemoryTraces(e,r){let n=await this.sendRequest(`/${Y}/${this.cacheRouteForPlatform(e)}/traces`,{method:"POST",body:r,retries:10,requestTimeoutMs:3e4,initialRetryDelayMs:3e3});return gE.parse(n)}async updateMobileStepCaches(e){await this.sendRequest(`/${Y}/${this.cacheRouteForPlatform(e.platform)}`,{method:"PATCH",body:e.body,extraHeaders:e.headers,retries:3,requestTimeoutMs:1e4,initialRetryDelayMs:3e3})}async getMobileStepCacheForTest({platform:e,body:r,headers:n}){let o=await this.sendRequest(`/${Y}/${this.cacheRouteForPlatform(e)}`,{method:"POST",body:r,extraHeaders:n,retries:10,requestTimeoutMs:3e4,initialRetryDelayMs:3e3});return k_(xm(e)).parse(o)}async queueTests(e){let r=await this.sendRequest(`/${Y}/tests/queue`,{method:"POST",body:e,retries:3,requestTimeoutMs:1e4});return O_.parse(r)}async uploadScreenshot(e){let r=await this.sendRequest(`/${Y}/screenshots`,{method:"POST",body:e,retries:3,requestTimeoutMs:5e3});return j_.parse(r)}async uploadOnDemandScreenshot(e){return await this.sendRequest(`/${Y}/on-demand-screenshots`,{method:"POST",body:e,retries:3,requestTimeoutMs:5e3}),{apiServerUrl:`${this.baseUrl}/${Y}/on-demand-screenshots/${e.id}`}}async fetchOnDemandScreenshot(e){let r={};return{data:await this.sendRequest(`/${Y}/on-demand-screenshots/${encodeURIComponent(e)}`,{method:"GET",retries:3,requestTimeoutMs:5e3,responseType:"buffer",responseHeadersObject:r}),contentType:r["content-type"]??"image/jpeg"}}async getAllEnvironments(){let e=await this.sendRequest(`/${Y}/environments`,{method:"GET",retries:3,requestTimeoutMs:5e3});return W_.parse(e)}async acquireCacheLock(e,r){let n=await this.sendRequest(`/${Y}/result-cache/lock`,{method:"POST",body:e,signal:r,retries:3,requestTimeoutMs:3e4});return cI.parse(n)}async releaseCacheLock(e){await this.sendRequest(`/${Y}/result-cache/lock`,{method:"DELETE",body:{key:e},retries:3,requestTimeoutMs:5e3})}async deleteCacheResult(e){await this.sendRequest(`/${Y}/result-cache/entry`,{method:"DELETE",body:e,retries:3,requestTimeoutMs:5e3})}async setCacheResult(e){await this.sendRequest(`/${Y}/result-cache/entry`,{method:"PATCH",body:e,retries:3,requestTimeoutMs:5e3})}async getCacheResult(e){try{return await this.sendRequest(`/${Y}/result-cache/entry`,{method:"POST",body:e,retries:3,requestTimeoutMs:5e3})}catch(r){if(r instanceof Error&&r.message.includes("404"))return null;throw r}}async queueSuiteRuns(e){let r=await this.sendRequest(`/${Y}/suites/queue`,{method:"POST",body:e,retries:3,requestTimeoutMs:5e3});return $_.parse(r)}async bulkGetRunGroupStatus(e){let r={runGroupIds:e},n=await this.sendRequest(`/${Y}/run-groups/status`,{method:"POST",body:r,retries:3,requestTimeoutMs:5e3});return fw.array().parse(n)}async uploadProposedSteps(e,r){try{await this.sendRequest(`/${Y}/test-fragments/`,{method:"POST",body:e,retries:3,requestTimeoutMs:1e4})}catch(n){r.error({err:n},"Failed to upload proposed steps")}}async reportBillableEvents(e,r){try{await this.sendRequest(`/${Y}/billing/events`,{method:"POST",body:r,retries:10,requestTimeoutMs:1e4})}catch(n){e.error({err:n},"Failed to report billable event")}}async fetchTestFragment(e){let r=await this.sendRequest(`/${Y}/test-fragments/${e}`,{method:"GET",retries:3,requestTimeoutMs:1e4});return q_.parse(r)}async patchTestFragment(e,r){await this.sendRequest(`/${Y}/test-fragments/${e}`,{method:"PATCH",body:r,retries:3,requestTimeoutMs:1e4})}async getPastTestResults(e,r){let n=await this.sendRequest(`/${Y}/results/tests/${e}`,{method:"POST",body:r,retries:3,requestTimeoutMs:1e4});return K_.parse(n)}async generateTestResultsUploadUrl(){let e=await this.sendRequest(`/${Y}/results/uploads`,{method:"POST",retries:3,requestTimeoutMs:1e4});return Y_.parse(e)}async startProcessingResultsUpload(e,r){let n=await this.sendRequest(`/${Y}/results/uploads/${e}/process`,{method:"POST",body:r,retries:3,requestTimeoutMs:1e4});return X_.parse(n)}async fetchIconKnowledgeBase(e){try{let r=await this.sendRequest(`/${Y}/knowledge-base/icons`,{method:"GET",retries:3,requestTimeoutMs:5e3});return fI.parse(r)}catch(r){return e.error({err:r},"Failed to fetch icon knowledge base"),null}}async saveNewIcons(e,r){try{await this.sendRequest(`/${Y}/knowledge-base/icons`,{method:"POST",body:e,retries:3,requestTimeoutMs:5e3})}catch(n){r.error({err:n},"Failed to save new icons to icon knowledge base")}}async getMergeBaseCommitFromGithub(e,r,n,o){let i=new URLSearchParams;i.set("base",n),i.set("head",o);let a=await this.sendRequest(`/${Y}/git/github/${e}/${r}/merge-base-commit?${i.toString()}`,{method:"GET",retries:3,requestTimeoutMs:1e4});return ad.parse(a)}async getCommitFromGithub(e,r,n){let o=await this.sendRequest(`/${Y}/git/github/${e}/${r}/commits/${n}`,{method:"GET",retries:3,requestTimeoutMs:1e4});return ad.parse(o)}async getMergedBranchFromGithub(e,r,n,o){let i=encodeURIComponent(n),a=await this.sendRequest(`/${Y}/git/github/${e}/${r}/${i}/${o}/merged-branch`,{method:"GET",retries:3,requestTimeoutMs:1e4});return EE.parse(a)}async getMergeBaseCommitFromGitlab(e,r,n){let o=new URLSearchParams;o.set("base",r),o.set("head",n);let i=encodeURIComponent(e),a=await this.sendRequest(`/${Y}/git/gitlab/${i}/merge-base-commit?${o.toString()}`,{method:"GET",retries:3,requestTimeoutMs:5e3});return ad.parse(a)}async getCommitFromGitlab(e,r){let n=encodeURIComponent(e),o=await this.sendRequest(`/${Y}/git/gitlab/${n}/commits/${r}`,{method:"GET",retries:3,requestTimeoutMs:1e4});return ad.parse(o)}async getMergedBranchFromGitlab(e,r,n){let o=encodeURIComponent(r),i=encodeURIComponent(e),a=await this.sendRequest(`/${Y}/git/gitlab/${i}/${o}/${n}/merged-branch`,{method:"GET",retries:3,requestTimeoutMs:1e4});return EE.parse(a)}async getAgentConfig(){let e=await this.sendRequest(`/${Y}/web-agent/agent-config`,{method:"GET",retries:3,requestTimeoutMs:5e3});return Mb.record(Mb.string(),Mb.string()).parse(e)}async getQuarantinedTests(){let e=await this.sendRequest(`/${Y}/quarantine`,{method:"GET"});return J_.parse(e)}async quarantineTest(e,r,n){await this.sendRequest(`/${Y}/quarantine`,{method:"POST",body:{testId:e.id,testName:e.name,reason:r,...n??{}},retries:3,requestTimeoutMs:1e4})}async unquarantineTest(e,r,n){await this.sendRequest(`/${Y}/quarantine/${e.id}`,{method:"DELETE",body:{testName:e.name,reason:r,...n??{}},retries:3,requestTimeoutMs:1e4})}platformRoute(e){switch(e){case"ANDROID":return"android";case"IOS":return"ios"}}async createAndroidEmulator(e){let r=await this.sendRequest(`/${Y}/limbar/android`,{method:"POST",retries:3,body:e,requestTimeoutMs:9e4,initialRetryDelayMs:5e3,maxRetryDelayMs:15e3});return Q_.parse(r)}async extendEmulatorTtl(e,r){try{await this.sendRequest(`/${Y}/limbar/${this.platformRoute(e)}/${r}/keepalive`,{method:"POST",retries:3,requestTimeoutMs:15e3})}catch{}}async generateAssetUploadUrl({channel:e,tag:r,md5:n,platform:o}){let i={channel:e,tag:r,md5:n},a=await this.sendRequest(`/${Y}/limbar/${this.platformRoute(o)}/upload-url`,{method:"POST",retries:3,body:i,requestTimeoutMs:15e3,logResponse:!0});return eI.parse(a)}async deleteAndroidEmulator(e){await this.sendRequest(`/${Y}/limbar/android/${e}`,{method:"DELETE",retries:3,requestTimeoutMs:3e4})}async getMobileAssets(){let e=await this.sendRequest(`/${Y}/limbar/assets`,{method:"GET",retries:3,requestTimeoutMs:1e4});return tI.parse(e)}async getLimbarAssetDownloadUrl(e,r,n){let o=await this.sendRequest(`/${Y}/limbar/assets/${e}/${r}/${this.platformRoute(n)}/download-url`,{method:"GET",retries:2,requestTimeoutMs:3e4});return rI.parse(o)}async deleteAsset(e,r,n){await this.sendRequest(`/${Y}/limbar/assets/${e}/${r}/${this.platformRoute(n)}`,{method:"DELETE",retries:3,requestTimeoutMs:1e4})}async createIosEmulator(e){let r=await this.sendRequest(`/${Y}/limbar/ios`,{method:"POST",retries:3,body:e,requestTimeoutMs:9e4,initialRetryDelayMs:5e3,maxRetryDelayMs:15e3});return Z_.parse(r)}async deleteIosEmulator(e){await this.sendRequest(`/${Y}/limbar/ios/${e}`,{method:"DELETE",retries:3,requestTimeoutMs:3e4})}async generateMobileLogcatUploadUrl(e){let r=await this.sendRequest(`/${Y}/logcat/mobile/upload`,{method:"POST",body:e,retries:3,requestTimeoutMs:1e4});return zx.parse(r)}};async function Gh(t){let e=process.versions.node,r=parseInt(e.split(".")[0]);(isNaN(r)||r<18)&&(v.error(`Node.js version 20 or higher is required to run the CLI. Detected: ${process.versions.node}.`),process.exit(1)),v.debug(`Identified node version ${e}`);let n=await t.client.getAuthInfo();return v.debug("Got auth info from API"),n}var jh=class{apiClient;constructor(e){this.apiClient=e}async reportBillableEvents(e,r){await this.apiClient.reportBillableEvents(e,r)}};var ga=class extends Tr{generator;constructor(e,r){super(e),this.generator=r}async runTemplateMatching(e,r={}){let n=await this.sendRequest(`/${Y}/web-agent/template-matching`,{method:"POST",body:e,signal:r?.signal});return eC.parse(n)}async constructIframeRegex(e,r={}){return this.generator.getIframeRegex(e,{abortSignal:r.signal})}};var wc=class{constructor(e,r){this.client=e;this.orgId=r}getApiServerUrl(){return this.client.baseUrl}getAppServerUrl(){let e=this.getApiServerUrl();return jl(e)}async acquireCacheLock(e,r){return this.client.acquireCacheLock(e,r)}async createOnDemandScreenshot(e,r,n){let{apiServerUrl:o}=await this.client.uploadOnDemandScreenshot({id:e,screenshot:r.toString("base64"),contentType:n});return{apiServerUrl:o,appServerUrl:`${this.getAppServerUrl()}/api/on-demand-screenshots/${e}`,universalHandle:{id:e,contentType:n}}}async fetchOnDemandScreenshot(e){return this.client.fetchOnDemandScreenshot(e.id)}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,r){return this.client.saveNewIcons(e,r)}};import{Faker as fJ,en as hJ}from"@faker-js/faker";var xc="v1",Xo=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 fJ({locale:hJ}),this.fakerInstance.seed(e.fakerSeed))}async sendAiGenerate(e){let r=typeof e=="string"?{input:e}:e;return this.httpClient.sendRequest(`/${xc}/tools/ai/generate`,{method:"POST",body:r}).catch(n=>{throw n instanceof Co?new Error(n.rawError):new Error(`Failed to send AI generation: ${n.message}`)})}async sendSms(e){return this.httpClient.sendRequest(`/${xc}/tools/sms/send`,{method:"POST",body:e}).then(()=>{}).catch(r=>{throw r instanceof Co?new Error(r.rawError):new Error(`Failed to send sms: ${r.message}`)})}async fetchLatestSms(e){return this.httpClient.sendRequest(`/${xc}/tools/sms/fetchLatest`,{method:"POST",body:e}).catch(r=>{throw r instanceof Co?new Error(r.rawError):r})}async sendEmail(e){return this.httpClient.sendRequest(`/${xc}/tools/email/send`,{method:"POST",body:e}).then(()=>{}).catch(r=>{throw r instanceof Co?new Error(r.rawError):new Error(`Failed to send email: ${r.message}`)})}async fetchAllEmails(e){return this.httpClient.sendRequest(`/${xc}/tools/email/fetchAll`,{method:"POST",body:e}).catch(r=>{throw r instanceof Co?new Error(r.rawError):new Error(`Failed to fetch all emails: ${r.message}`)})}async fetchLatestEmail(e){return this.httpClient.sendRequest(`/${xc}/tools/email/fetchLatest`,{method:"POST",body:e}).catch(r=>{throw r instanceof Co?new Error(r.rawError):new Error(`Failed to fetch latest emails: ${r.message}`)})}};function DD(t,e,r){return fetch(t,{method:"PUT",body:r,headers:{"Content-Type":e}})}var Vh=class{constructor(e){this.client=e}async uploadResultsArchive(e,r){let{uploadUrl:n,id:o}=await this.client.generateTestResultsUploadUrl(),i=await DD(n,"application/zip",r);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}};function xo({logger:t,orgId:e,client:r,gitMetadata:n,regenerateCache:o,alwaysSaveCache:i,noCache:a,isolateCachesByEnvironment:s=!1,bustOldestCachePercentage:c}){return a?new Wm:new Ob(t,e,r,n,{regenerateCache:o,alwaysSaveCache:i,bustOldestCachePercentage:c,isolateCachesByEnvironment:s})}var Ob=class{constructor(e,r,n,o,i){this.orgId=r;this.client=n;let{regenerateCache:a,alwaysSaveCache:s,bustOldestCachePercentage:c,isolateCachesByEnvironment:l}=i,{gitBranchName:u,gitProtectedBranches:d}=o;e.info({options:i,gitBranchName:u,gitProtectedBranches:d},"Cache storage initialization options"),this.cacheHeaders=hE(o),this.isolateCachesByEnvironment=l,this.readCaches=!a;let p=u&&d.includes(u);s||!p?this.writeCaches=!0:this.writeCaches=!1,p||(this.bustOldestCachePercentage=c)}cacheHeaders;readCaches;writeCaches;isolateCachesByEnvironment;bustOldestCachePercentage;async saveStepCacheEntries({entries:e,logger:r}){if(!this.writeCaches){r.debug("Skipping cache storage because branch is protected");return}try{await this.client.updateStepCaches({entries:TE(e,this.isolateCachesByEnvironment)},this.cacheHeaders)}catch(n){r.error({err:n},"Failed to save step cache entries")}}async resolveStepCacheEntries(e){if(!this.readCaches){e.logger.debug("Skipping cache resolution because of regenerate flag");return}let{steps:r,beforeSteps:n,afterSteps:o}=e.stepLists,i=await this.client.getStepCacheForTest({testId:e.testId,environment:this.isolateCachesByEnvironment?e.environment:void 0},this.cacheHeaders);if(this.bustOldestCachePercentage!==void 0){let s=Object.entries(i).map(([u,d])=>({key:u,time:d.value.cache?.updatedAt?.getTime()??0}));s.sort((u,d)=>u.time-d.time);let c=s.length,l=Math.max(1,Math.floor(c*this.bustOldestCachePercentage/100));s.slice(0,l).forEach(({key:u})=>{delete i[u]}),e.logger.info({nCachesToBust:l,bustOldestCachePercentage:this.bustOldestCachePercentage,totalCaches:c},"Busted oldest caches")}for(let s of[r,n,o])s&&mc({steps:s,stepCacheEntries:i,logger:e.logger});if(!this.writeCaches){e.logger.debug("Skipping cache last used at update because branch is protected");return}let{cachesToSave:a}=await Ft({stepLists:e.stepLists,cacheCreationParams:{environment:e.environment,testId:e.testId,orgId:this.orgId}});this.saveStepCacheEntries({entries:a,logger:e.logger})}};import Wh from"path";function gJ(t){let e=new kD,r=Wh.join(t,"metadata.json"),n=Wl.parse(JSON.parse(Lb.readFileSync(r,"utf-8")));e.addLocalFile(r);for(let o of Lb.readdirSync(Wh.join(t,"runs"))){if(!o.endsWith(".zip"))continue;let i=o.replace(/\.zip$/,""),a=new kD(Wh.join(t,"runs",o));for(let s of a.getEntries())s.isDirectory||e.addFile(Wh.join("runs",i,s.entryName),s.getData())}return{runGroupId:n.id,buffer:e.toBuffer()}}async function $h(t){let{client:e,consoleLogger:r,resultsPath:n}=t;if(!Lb.existsSync(n)){r.warn("Results path does not exist, skipping upload.");return}let o=new Vh(e);try{let{runGroupId:i,buffer:a}=gJ(n),s=await o.uploadResultsArchive(i,a),c=`${e.getAppUrl()}/run-groups/${s}`;r.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",r.error(`Failed to upload test results: ${a}.`);return}}import SJ from"adm-zip";import Dr from"fs";import eo from"path";var Xd=class t{constructor(e){this.filePath=e;Dr.rmSync(this.filePath,{recursive:!0,force:!0}),Dr.mkdirSync(this.filePath,{recursive:!0})}children=[];streams=[];close(){for(let e of this.children)e.close();for(let e of this.streams)e.end()}cd(e){let r=new t(eo.join(this.filePath,e));return this.children.push(r),r}cwd(){return this.filePath}mkdir(e){Dr.mkdirSync(eo.join(this.filePath,e),{recursive:!0})}readFile(e){let r=eo.join(this.filePath,e);if(Dr.existsSync(r))return Dr.readFileSync(r)}storeFile(e){let{name:r,contents:n}=e,o=eo.join(this.filePath,r);try{Dr.writeFileSync(o,n)}catch{}}createFileStream(e){let r=eo.join(this.filePath,e),n=Dr.createWriteStream(r);return this.streams.push(n),n}createRunArchive(e){let r=new Nb(eo.join(this.filePath,"runs"),e);return this.children.push(r),r}},Nb=class{children=[];tempPath;finalPath;constructor(e,r){this.tempPath=eo.join(e,`temp-storage-${r}`),this.finalPath=eo.join(e,`${r}.zip`),Dr.rmSync(this.tempPath,{recursive:!0,force:!0}),Dr.rmSync(this.finalPath,{recursive:!0,force:!0}),Dr.mkdirSync(this.tempPath,{recursive:!0})}readFile(e){let r=eo.join(this.tempPath,e);if(Dr.existsSync(r))return Dr.readFileSync(r)}mkdir(e){Dr.mkdirSync(eo.join(this.tempPath,e),{recursive:!0})}cd(e){let r=new Xd(eo.join(this.tempPath,e));return this.children.push(r),r}cwd(){return this.tempPath}storeFile(e){let{name:r,contents:n}=e,o=eo.join(this.tempPath,r);Dr.writeFileSync(o,n)}close(){for(let n of this.children)n.close();let e=new SJ;e.addLocalFolder(this.tempPath,void 0,n=>n!==".DS_Store");let r=e.toBuffer();Dr.writeFileSync(this.finalPath,r),Dr.rmSync(this.tempPath,{recursive:!0,force:!0})}};import yJ from"adm-zip";import{randomUUID as EJ}from"crypto";import rr from"fs";import Ar from"path";function zD(t){try{return rr.existsSync(t)?JSON.parse(rr.readFileSync(t,"utf-8")):void 0}catch{return}}function FD(t){return rr.existsSync(t)?rr.readFileSync(t,"utf-8").split(`
|
|
88
|
+
${e}:`]}}function TD({id:t,model:e,created:r}){return{id:t??void 0,modelId:e??void 0,timestamp:r!=null?new Date(r*1e3):void 0}}function bD(t){switch(t){case"stop":return"stop";case"length":return"length";case"content_filter":return"content-filter";case"function_call":case"tool_calls":return"tool-calls";default:return"unknown"}}var i3=Tt(()=>Ee(Ie.object({id:Ie.string().nullish(),created:Ie.number().nullish(),model:Ie.string().nullish(),choices:Ie.array(Ie.object({text:Ie.string(),finish_reason:Ie.string(),logprobs:Ie.object({tokens:Ie.array(Ie.string()),token_logprobs:Ie.array(Ie.number()),top_logprobs:Ie.array(Ie.record(Ie.string(),Ie.number())).nullish()}).nullish()})),usage:Ie.object({prompt_tokens:Ie.number(),completion_tokens:Ie.number(),total_tokens:Ie.number()}).nullish()}))),a3=Tt(()=>Ee(Ie.union([Ie.object({id:Ie.string().nullish(),created:Ie.number().nullish(),model:Ie.string().nullish(),choices:Ie.array(Ie.object({text:Ie.string(),finish_reason:Ie.string().nullish(),index:Ie.number(),logprobs:Ie.object({tokens:Ie.array(Ie.string()),token_logprobs:Ie.array(Ie.number()),top_logprobs:Ie.array(Ie.record(Ie.string(),Ie.number())).nullish()}).nullish()})),usage:Ie.object({prompt_tokens:Ie.number(),completion_tokens:Ie.number(),total_tokens:Ie.number()}).nullish()}),_b]))),vD=Tt(()=>Ee(Ko.object({echo:Ko.boolean().optional(),logitBias:Ko.record(Ko.string(),Ko.number()).optional(),suffix:Ko.string().optional(),user:Ko.string().optional(),logprobs:Ko.union([Ko.boolean(),Ko.number()]).optional()}))),s3=class{constructor(t,e){this.specificationVersion="v2",this.supportedUrls={},this.modelId=t,this.config=e}get providerOptionsName(){return this.config.provider.split(".")[0].trim()}get provider(){return this.config.provider}async getArgs({prompt:t,maxOutputTokens:e,temperature:r,topP:n,topK:o,frequencyPenalty:i,presencePenalty:a,stopSequences:s,responseFormat:c,tools:l,toolChoice:u,seed:d,providerOptions:p}){let m=[],f={...await Yr({provider:"openai",providerOptions:p,schema:vD}),...await Yr({provider:this.providerOptionsName,providerOptions:p,schema:vD})};o!=null&&m.push({type:"unsupported-setting",setting:"topK"}),l?.length&&m.push({type:"unsupported-setting",setting:"tools"}),u!=null&&m.push({type:"unsupported-setting",setting:"toolChoice"}),c!=null&&c.type!=="text"&&m.push({type:"unsupported-setting",setting:"responseFormat",details:"JSON response format is not supported."});let{prompt:h,stopSequences:S}=o3({prompt:t}),g=[...S??[],...s??[]];return{args:{model:this.modelId,echo:f.echo,logit_bias:f.logitBias,logprobs:f?.logprobs===!0?0:f?.logprobs===!1?void 0:f?.logprobs,suffix:f.suffix,user:f.user,max_tokens:e,temperature:r,top_p:n,frequency_penalty:i,presence_penalty:a,seed:d,prompt:h,stop:g.length>0?g:void 0},warnings:m}}async doGenerate(t){var e,r,n;let{args:o,warnings:i}=await this.getArgs(t),{responseHeaders:a,value:s,rawValue:c}=await Xr({url:this.config.url({path:"/completions",modelId:this.modelId}),headers:br(this.config.headers(),t.headers),body:o,failedResponseHandler:Yo,successfulResponseHandler:Zn(i3),abortSignal:t.abortSignal,fetch:this.config.fetch}),l=s.choices[0],u={openai:{}};return l.logprobs!=null&&(u.openai.logprobs=l.logprobs),{content:[{type:"text",text:l.text}],usage:{inputTokens:(e=s.usage)==null?void 0:e.prompt_tokens,outputTokens:(r=s.usage)==null?void 0:r.completion_tokens,totalTokens:(n=s.usage)==null?void 0:n.total_tokens},finishReason:bD(l.finish_reason),request:{body:o},response:{...TD(s),headers:a,body:c},providerMetadata:u,warnings:i}}async doStream(t){let{args:e,warnings:r}=await this.getArgs(t),n={...e,stream:!0,stream_options:{include_usage:!0}},{responseHeaders:o,value:i}=await Xr({url:this.config.url({path:"/completions",modelId:this.modelId}),headers:br(this.config.headers(),t.headers),body:n,failedResponseHandler:Yo,successfulResponseHandler:Rc(a3),abortSignal:t.abortSignal,fetch:this.config.fetch}),a="unknown",s={openai:{}},c={inputTokens:void 0,outputTokens:void 0,totalTokens:void 0},l=!0;return{stream:i.pipeThrough(new TransformStream({start(u){u.enqueue({type:"stream-start",warnings:r})},transform(u,d){if(t.includeRawChunks&&d.enqueue({type:"raw",rawValue:u.rawValue}),!u.success){a="error",d.enqueue({type:"error",error:u.error});return}let p=u.value;if("error"in p){a="error",d.enqueue({type:"error",error:p.error});return}l&&(l=!1,d.enqueue({type:"response-metadata",...TD(p)}),d.enqueue({type:"text-start",id:"0"})),p.usage!=null&&(c.inputTokens=p.usage.prompt_tokens,c.outputTokens=p.usage.completion_tokens,c.totalTokens=p.usage.total_tokens);let m=p.choices[0];m?.finish_reason!=null&&(a=bD(m.finish_reason)),m?.logprobs!=null&&(s.openai.logprobs=m.logprobs),m?.text!=null&&m.text.length>0&&d.enqueue({type:"text-delta",id:"0",delta:m.text})},flush(u){l||u.enqueue({type:"text-end",id:"0"}),u.enqueue({type:"finish",finishReason:a,providerMetadata:s,usage:c})}})),request:{body:n},response:{headers:o}}}},c3=Tt(()=>Ee(Rb.object({dimensions:Rb.number().optional(),user:Rb.string().optional()}))),u3=Tt(()=>Ee(Os.object({data:Os.array(Os.object({embedding:Os.array(Os.number())})),usage:Os.object({prompt_tokens:Os.number()}).nullish()}))),d3=class{constructor(t,e){this.specificationVersion="v2",this.maxEmbeddingsPerCall=2048,this.supportsParallelCalls=!0,this.modelId=t,this.config=e}get provider(){return this.config.provider}async doEmbed({values:t,headers:e,abortSignal:r,providerOptions:n}){var o;if(t.length>this.maxEmbeddingsPerCall)throw new l3({provider:this.provider,modelId:this.modelId,maxEmbeddingsPerCall:this.maxEmbeddingsPerCall,values:t});let i=(o=await Yr({provider:"openai",providerOptions:n,schema:c3}))!=null?o:{},{responseHeaders:a,value:s,rawValue:c}=await Xr({url:this.config.url({path:"/embeddings",modelId:this.modelId}),headers:br(this.config.headers(),e),body:{model:this.modelId,input:t,encoding_format:"float",dimensions:i.dimensions,user:i.user},failedResponseHandler:Yo,successfulResponseHandler:Zn(u3),abortSignal:r,fetch:this.config.fetch});return{embeddings:s.data.map(l=>l.embedding),usage:s.usage?{tokens:s.usage.prompt_tokens}:void 0,response:{headers:a,body:c}}}},p3=Tt(()=>Ee(vr.object({created:vr.number().nullish(),data:vr.array(vr.object({b64_json:vr.string(),revised_prompt:vr.string().nullish()})),background:vr.string().nullish(),output_format:vr.string().nullish(),size:vr.string().nullish(),quality:vr.string().nullish(),usage:vr.object({input_tokens:vr.number().nullish(),output_tokens:vr.number().nullish(),total_tokens:vr.number().nullish(),input_tokens_details:vr.object({image_tokens:vr.number().nullish(),text_tokens:vr.number().nullish()}).nullish()}).nullish()}))),m3={"dall-e-3":1,"dall-e-2":10,"gpt-image-1":10,"gpt-image-1-mini":10,"gpt-image-1.5":10},f3=new Set(["gpt-image-1","gpt-image-1-mini","gpt-image-1.5"]),h3=class{constructor(t,e){this.modelId=t,this.config=e,this.specificationVersion="v2"}get maxImagesPerCall(){var t;return(t=m3[this.modelId])!=null?t:1}get provider(){return this.config.provider}async doGenerate({prompt:t,n:e,size:r,aspectRatio:n,seed:o,providerOptions:i,headers:a,abortSignal:s}){var c,l,u,d;let p=[];n!=null&&p.push({type:"unsupported-setting",setting:"aspectRatio",details:"This model does not support aspect ratio. Use `size` instead."}),o!=null&&p.push({type:"unsupported-setting",setting:"seed"});let m=(u=(l=(c=this.config._internal)==null?void 0:c.currentDate)==null?void 0:l.call(c))!=null?u:new Date,{value:f,responseHeaders:h}=await Xr({url:this.config.url({path:"/images/generations",modelId:this.modelId}),headers:br(this.config.headers(),a),body:{model:this.modelId,prompt:t,n:e,size:r,...(d=i.openai)!=null?d:{},...f3.has(this.modelId)?{}:{response_format:"b64_json"}},failedResponseHandler:Yo,successfulResponseHandler:Zn(p3),abortSignal:s,fetch:this.config.fetch});return{images:f.data.map(S=>S.b64_json),warnings:p,response:{timestamp:m,modelId:this.modelId,headers:h},providerMetadata:{openai:{images:f.data.map(S=>({...S.revised_prompt?{revisedPrompt:S.revised_prompt}:{},...f.created!=null?{created:f.created}:{},...f.size!=null?{size:f.size}:{},...f.quality!=null?{quality:f.quality}:{},...f.background!=null?{background:f.background}:{},...f.output_format!=null?{outputFormat:f.output_format}:{}}))}}}}},g3=Bt(()=>Ee(cr.object({code:cr.string().nullish(),containerId:cr.string()}))),S3=Bt(()=>Ee(cr.object({outputs:cr.array(cr.discriminatedUnion("type",[cr.object({type:cr.literal("logs"),logs:cr.string()}),cr.object({type:cr.literal("image"),url:cr.string()})])).nullish()}))),y3=Bt(()=>Ee(cr.object({container:cr.union([cr.string(),cr.object({fileIds:cr.array(cr.string()).optional()})]).optional()}))),E3=Qn({id:"openai.code_interpreter",name:"code_interpreter",inputSchema:g3,outputSchema:S3}),T3=(t={})=>E3(t),ID=Je.object({key:Je.string(),type:Je.enum(["eq","ne","gt","gte","lt","lte","in","nin"]),value:Je.union([Je.string(),Je.number(),Je.boolean(),Je.array(Je.string())])}),PD=Je.object({type:Je.enum(["and","or"]),filters:Je.array(Je.union([ID,Je.lazy(()=>PD)]))}),b3=Bt(()=>Ee(Je.object({vectorStoreIds:Je.array(Je.string()),maxNumResults:Je.number().optional(),ranking:Je.object({ranker:Je.string().optional(),scoreThreshold:Je.number().optional()}).optional(),filters:Je.union([ID,PD]).optional()}))),v3=Bt(()=>Ee(Je.object({queries:Je.array(Je.string()),results:Je.array(Je.object({attributes:Je.record(Je.string(),Je.unknown()),fileId:Je.string(),filename:Je.string(),score:Je.number(),text:Je.string()})).nullable()}))),A3=Qn({id:"openai.file_search",name:"file_search",inputSchema:Je.object({}),outputSchema:v3}),C3=Bt(()=>Ee(Nr.object({background:Nr.enum(["auto","opaque","transparent"]).optional(),inputFidelity:Nr.enum(["low","high"]).optional(),inputImageMask:Nr.object({fileId:Nr.string().optional(),imageUrl:Nr.string().optional()}).optional(),model:Nr.string().optional(),moderation:Nr.enum(["auto"]).optional(),outputCompression:Nr.number().int().min(0).max(100).optional(),outputFormat:Nr.enum(["png","jpeg","webp"]).optional(),partialImages:Nr.number().int().min(0).max(3).optional(),quality:Nr.enum(["auto","low","medium","high"]).optional(),size:Nr.enum(["1024x1024","1024x1536","1536x1024","auto"]).optional()}).strict())),R3=Bt(()=>Ee(Nr.object({}))),w3=Bt(()=>Ee(Nr.object({result:Nr.string()}))),x3=Qn({id:"openai.image_generation",name:"image_generation",inputSchema:R3,outputSchema:w3}),_3=(t={})=>x3(t),MD=Bt(()=>Ee(An.object({action:An.object({type:An.literal("exec"),command:An.array(An.string()),timeoutMs:An.number().optional(),user:An.string().optional(),workingDirectory:An.string().optional(),env:An.record(An.string(),An.string()).optional()})}))),OD=Bt(()=>Ee(An.object({output:An.string()}))),I3=Qn({id:"openai.local_shell",name:"local_shell",inputSchema:MD,outputSchema:OD}),P3=Bt(()=>Ee(it.object({externalWebAccess:it.boolean().optional(),filters:it.object({allowedDomains:it.array(it.string()).optional()}).optional(),searchContextSize:it.enum(["low","medium","high"]).optional(),userLocation:it.object({type:it.literal("approximate"),country:it.string().optional(),city:it.string().optional(),region:it.string().optional(),timezone:it.string().optional()}).optional()}))),M3=Bt(()=>Ee(it.object({}))),O3=Bt(()=>Ee(it.object({action:it.discriminatedUnion("type",[it.object({type:it.literal("search"),query:it.string().optional()}),it.object({type:it.literal("openPage"),url:it.string().nullish()}),it.object({type:it.literal("findInPage"),url:it.string().nullish(),pattern:it.string().nullish()})]),sources:it.array(it.discriminatedUnion("type",[it.object({type:it.literal("url"),url:it.string()}),it.object({type:it.literal("api"),name:it.string()})])).optional()}))),L3=Qn({id:"openai.web_search",name:"web_search",inputSchema:M3,outputSchema:O3}),N3=(t={})=>L3(t),D3=Bt(()=>Ee($t.object({searchContextSize:$t.enum(["low","medium","high"]).optional(),userLocation:$t.object({type:$t.literal("approximate"),country:$t.string().optional(),city:$t.string().optional(),region:$t.string().optional(),timezone:$t.string().optional()}).optional()}))),k3=Bt(()=>Ee($t.object({}))),F3=Bt(()=>Ee($t.object({action:$t.discriminatedUnion("type",[$t.object({type:$t.literal("search"),query:$t.string().optional()}),$t.object({type:$t.literal("openPage"),url:$t.string().nullish()}),$t.object({type:$t.literal("findInPage"),url:$t.string().nullish(),pattern:$t.string().nullish()})])}))),U3=Qn({id:"openai.web_search_preview",name:"web_search_preview",inputSchema:k3,outputSchema:F3}),B3={codeInterpreter:T3,fileSearch:A3,imageGeneration:_3,localShell:I3,webSearchPreview:U3,webSearch:N3};function AD(t,e){return e?e.some(r=>t.startsWith(r)):!1}async function G3({prompt:t,systemMessageMode:e,fileIdPrefixes:r,store:n,hasLocalShellTool:o=!1}){var i,a,s,c;let l=[],u=[];for(let{role:d,content:p}of t)switch(d){case"system":{switch(e){case"system":{l.push({role:"system",content:p});break}case"developer":{l.push({role:"developer",content:p});break}case"remove":{u.push({type:"other",message:"system messages are removed for this model"});break}default:{let m=e;throw new Error(`Unsupported system message mode: ${m}`)}}break}case"user":{l.push({role:"user",content:p.map((m,f)=>{var h,S,g;switch(m.type){case"text":return{type:"input_text",text:m.text};case"file":if(m.mediaType.startsWith("image/")){let E=m.mediaType==="image/*"?"image/jpeg":m.mediaType;return{type:"input_image",...m.data instanceof URL?{image_url:m.data.toString()}:typeof m.data=="string"&&AD(m.data,r)?{file_id:m.data}:{image_url:`data:${E};base64,${ma(m.data)}`},detail:(S=(h=m.providerOptions)==null?void 0:h.openai)==null?void 0:S.imageDetail}}else{if(m.mediaType==="application/pdf")return m.data instanceof URL?{type:"input_file",file_url:m.data.toString()}:{type:"input_file",...typeof m.data=="string"&&AD(m.data,r)?{file_id:m.data}:{filename:(g=m.filename)!=null?g:`part-${f}.pdf`,file_data:`data:application/pdf;base64,${ma(m.data)}`}};throw new H3({functionality:`file part media type ${m.mediaType}`})}}})});break}case"assistant":{let m={},f={};for(let h of p)switch(h.type){case"text":{let S=(a=(i=h.providerOptions)==null?void 0:i.openai)==null?void 0:a.itemId;if(n&&S!=null){l.push({type:"item_reference",id:S});break}l.push({role:"assistant",content:[{type:"output_text",text:h.text}],id:S});break}case"tool-call":{if(f[h.toolCallId]=h,h.providerExecuted)break;let S=(c=(s=h.providerOptions)==null?void 0:s.openai)==null?void 0:c.itemId;if(n&&S!=null){l.push({type:"item_reference",id:S});break}if(o&&h.toolName==="local_shell"){let g=await qo({value:h.input,schema:MD});l.push({type:"local_shell_call",call_id:h.toolCallId,id:S,action:{type:"exec",command:g.action.command,timeout_ms:g.action.timeoutMs,user:g.action.user,working_directory:g.action.workingDirectory,env:g.action.env}});break}l.push({type:"function_call",call_id:h.toolCallId,name:h.toolName,arguments:JSON.stringify(h.input),id:S});break}case"tool-result":{n?l.push({type:"item_reference",id:h.toolCallId}):u.push({type:"other",message:`Results for OpenAI tool ${h.toolName} are not sent to the API when store is false`});break}case"reasoning":{let S=await Yr({provider:"openai",providerOptions:h.providerOptions,schema:j3}),g=S?.itemId;if(g!=null){let E=m[g];if(n)E===void 0&&(l.push({type:"item_reference",id:g}),m[g]={type:"reasoning",id:g,summary:[]});else{let y=[];h.text.length>0?y.push({type:"summary_text",text:h.text}):E!==void 0&&u.push({type:"other",message:`Cannot append empty reasoning part to existing reasoning sequence. Skipping reasoning part: ${JSON.stringify(h)}.`}),E===void 0?(m[g]={type:"reasoning",id:g,encrypted_content:S?.reasoningEncryptedContent,summary:y},l.push(m[g])):(E.summary.push(...y),S?.reasoningEncryptedContent!=null&&(E.encrypted_content=S.reasoningEncryptedContent))}}else u.push({type:"other",message:`Non-OpenAI reasoning parts are not supported. Skipping reasoning part: ${JSON.stringify(h)}.`});break}}break}case"tool":{for(let m of p){let f=m.output;if(o&&m.toolName==="local_shell"&&f.type==="json"){let S=await qo({value:f.value,schema:OD});l.push({type:"local_shell_call_output",call_id:m.toolCallId,output:S.output});break}let h;switch(f.type){case"text":case"error-text":h=f.value;break;case"json":case"error-json":h=JSON.stringify(f.value);break;case"content":h=f.value.map(S=>{switch(S.type){case"text":return{type:"input_text",text:S.text};case"media":return S.mediaType.startsWith("image/")?{type:"input_image",image_url:`data:${S.mediaType};base64,${S.data}`}:{type:"input_file",filename:"data",file_data:`data:${S.mediaType};base64,${S.data}`}}});break}l.push({type:"function_call_output",call_id:m.toolCallId,output:h})}break}default:{let m=d;throw new Error(`Unsupported role: ${m}`)}}return{input:l,warnings:u}}var j3=wb.object({itemId:wb.string().nullish(),reasoningEncryptedContent:wb.string().nullish()});function CD({finishReason:t,hasFunctionCall:e}){switch(t){case void 0:case null:return e?"tool-calls":"stop";case"max_output_tokens":return"length";case"content_filter":return"content-filter";default:return e?"tool-calls":"unknown"}}var V3=Tt(()=>Ee(T.union([T.object({type:T.literal("response.output_text.delta"),item_id:T.string(),delta:T.string(),logprobs:T.array(T.object({token:T.string(),logprob:T.number(),top_logprobs:T.array(T.object({token:T.string(),logprob:T.number()}))})).nullish()}),T.object({type:T.enum(["response.completed","response.incomplete"]),response:T.object({incomplete_details:T.object({reason:T.string()}).nullish(),usage:T.object({input_tokens:T.number(),input_tokens_details:T.object({cached_tokens:T.number().nullish()}).nullish(),output_tokens:T.number(),output_tokens_details:T.object({reasoning_tokens:T.number().nullish()}).nullish()}),service_tier:T.string().nullish()})}),T.object({type:T.literal("response.created"),response:T.object({id:T.string(),created_at:T.number(),model:T.string(),service_tier:T.string().nullish()})}),T.object({type:T.literal("response.output_item.added"),output_index:T.number(),item:T.discriminatedUnion("type",[T.object({type:T.literal("message"),id:T.string()}),T.object({type:T.literal("reasoning"),id:T.string(),encrypted_content:T.string().nullish()}),T.object({type:T.literal("function_call"),id:T.string(),call_id:T.string(),name:T.string(),arguments:T.string()}),T.object({type:T.literal("web_search_call"),id:T.string(),status:T.string()}),T.object({type:T.literal("computer_call"),id:T.string(),status:T.string()}),T.object({type:T.literal("file_search_call"),id:T.string()}),T.object({type:T.literal("image_generation_call"),id:T.string()}),T.object({type:T.literal("code_interpreter_call"),id:T.string(),container_id:T.string(),code:T.string().nullable(),outputs:T.array(T.discriminatedUnion("type",[T.object({type:T.literal("logs"),logs:T.string()}),T.object({type:T.literal("image"),url:T.string()})])).nullable(),status:T.string()})])}),T.object({type:T.literal("response.output_item.done"),output_index:T.number(),item:T.discriminatedUnion("type",[T.object({type:T.literal("message"),id:T.string()}),T.object({type:T.literal("reasoning"),id:T.string(),encrypted_content:T.string().nullish()}),T.object({type:T.literal("function_call"),id:T.string(),call_id:T.string(),name:T.string(),arguments:T.string(),status:T.literal("completed")}),T.object({type:T.literal("code_interpreter_call"),id:T.string(),code:T.string().nullable(),container_id:T.string(),outputs:T.array(T.discriminatedUnion("type",[T.object({type:T.literal("logs"),logs:T.string()}),T.object({type:T.literal("image"),url:T.string()})])).nullable()}),T.object({type:T.literal("image_generation_call"),id:T.string(),result:T.string()}),T.object({type:T.literal("web_search_call"),id:T.string(),status:T.string(),action:T.discriminatedUnion("type",[T.object({type:T.literal("search"),query:T.string().nullish(),sources:T.array(T.discriminatedUnion("type",[T.object({type:T.literal("url"),url:T.string()}),T.object({type:T.literal("api"),name:T.string()})])).nullish()}),T.object({type:T.literal("open_page"),url:T.string().nullish()}),T.object({type:T.literal("find_in_page"),url:T.string().nullish(),pattern:T.string().nullish()})])}),T.object({type:T.literal("file_search_call"),id:T.string(),queries:T.array(T.string()),results:T.array(T.object({attributes:T.record(T.string(),T.unknown()),file_id:T.string(),filename:T.string(),score:T.number(),text:T.string()})).nullish()}),T.object({type:T.literal("local_shell_call"),id:T.string(),call_id:T.string(),action:T.object({type:T.literal("exec"),command:T.array(T.string()),timeout_ms:T.number().optional(),user:T.string().optional(),working_directory:T.string().optional(),env:T.record(T.string(),T.string()).optional()})}),T.object({type:T.literal("computer_call"),id:T.string(),status:T.literal("completed")})])}),T.object({type:T.literal("response.function_call_arguments.delta"),item_id:T.string(),output_index:T.number(),delta:T.string()}),T.object({type:T.literal("response.image_generation_call.partial_image"),item_id:T.string(),output_index:T.number(),partial_image_b64:T.string()}),T.object({type:T.literal("response.code_interpreter_call_code.delta"),item_id:T.string(),output_index:T.number(),delta:T.string()}),T.object({type:T.literal("response.code_interpreter_call_code.done"),item_id:T.string(),output_index:T.number(),code:T.string()}),T.object({type:T.literal("response.output_text.annotation.added"),annotation:T.discriminatedUnion("type",[T.object({type:T.literal("url_citation"),start_index:T.number(),end_index:T.number(),url:T.string(),title:T.string()}),T.object({type:T.literal("file_citation"),file_id:T.string(),filename:T.string().nullish(),index:T.number().nullish(),start_index:T.number().nullish(),end_index:T.number().nullish(),quote:T.string().nullish()})])}),T.object({type:T.literal("response.reasoning_summary_part.added"),item_id:T.string(),summary_index:T.number()}),T.object({type:T.literal("response.reasoning_summary_text.delta"),item_id:T.string(),summary_index:T.number(),delta:T.string()}),T.object({type:T.literal("response.reasoning_summary_part.done"),item_id:T.string(),summary_index:T.number()}),T.object({type:T.literal("error"),sequence_number:T.number(),error:T.object({type:T.string(),code:T.string(),message:T.string(),param:T.string().nullish()})}),T.object({type:T.string()}).loose().transform(t=>({type:"unknown_chunk",message:t.type}))]))),W3=Tt(()=>Ee(T.object({id:T.string().optional(),created_at:T.number().optional(),error:T.object({message:T.string(),type:T.string(),param:T.string().nullish(),code:T.string()}).nullish(),model:T.string().optional(),output:T.array(T.discriminatedUnion("type",[T.object({type:T.literal("message"),role:T.literal("assistant"),id:T.string(),content:T.array(T.object({type:T.literal("output_text"),text:T.string(),logprobs:T.array(T.object({token:T.string(),logprob:T.number(),top_logprobs:T.array(T.object({token:T.string(),logprob:T.number()}))})).nullish(),annotations:T.array(T.discriminatedUnion("type",[T.object({type:T.literal("url_citation"),start_index:T.number(),end_index:T.number(),url:T.string(),title:T.string()}),T.object({type:T.literal("file_citation"),file_id:T.string(),filename:T.string().nullish(),index:T.number().nullish(),start_index:T.number().nullish(),end_index:T.number().nullish(),quote:T.string().nullish()}),T.object({type:T.literal("container_file_citation"),container_id:T.string(),file_id:T.string(),filename:T.string().nullish(),start_index:T.number().nullish(),end_index:T.number().nullish(),index:T.number().nullish()}),T.object({type:T.literal("file_path"),file_id:T.string(),index:T.number().nullish()})]))}))}),T.object({type:T.literal("web_search_call"),id:T.string(),status:T.string(),action:T.discriminatedUnion("type",[T.object({type:T.literal("search"),query:T.string().nullish(),sources:T.array(T.discriminatedUnion("type",[T.object({type:T.literal("url"),url:T.string()}),T.object({type:T.literal("api"),name:T.string()})])).nullish()}),T.object({type:T.literal("open_page"),url:T.string().nullish()}),T.object({type:T.literal("find_in_page"),url:T.string().nullish(),pattern:T.string().nullish()})])}),T.object({type:T.literal("file_search_call"),id:T.string(),queries:T.array(T.string()),results:T.array(T.object({attributes:T.record(T.string(),T.union([T.string(),T.number(),T.boolean()])),file_id:T.string(),filename:T.string(),score:T.number(),text:T.string()})).nullish()}),T.object({type:T.literal("code_interpreter_call"),id:T.string(),code:T.string().nullable(),container_id:T.string(),outputs:T.array(T.discriminatedUnion("type",[T.object({type:T.literal("logs"),logs:T.string()}),T.object({type:T.literal("image"),url:T.string()})])).nullable()}),T.object({type:T.literal("image_generation_call"),id:T.string(),result:T.string()}),T.object({type:T.literal("local_shell_call"),id:T.string(),call_id:T.string(),action:T.object({type:T.literal("exec"),command:T.array(T.string()),timeout_ms:T.number().optional(),user:T.string().optional(),working_directory:T.string().optional(),env:T.record(T.string(),T.string()).optional()})}),T.object({type:T.literal("function_call"),call_id:T.string(),name:T.string(),arguments:T.string(),id:T.string()}),T.object({type:T.literal("computer_call"),id:T.string(),status:T.string().optional()}),T.object({type:T.literal("reasoning"),id:T.string(),encrypted_content:T.string().nullish(),summary:T.array(T.object({type:T.literal("summary_text"),text:T.string()}))})])).optional(),service_tier:T.string().nullish(),incomplete_details:T.object({reason:T.string()}).nullish(),usage:T.object({input_tokens:T.number(),input_tokens_details:T.object({cached_tokens:T.number().nullish()}).nullish(),output_tokens:T.number(),output_tokens_details:T.object({reasoning_tokens:T.number().nullish()}).nullish()}).optional()}))),LD=20,$3=["o1","o1-2024-12-17","o3","o3-2025-04-16","o3-deep-research","o3-deep-research-2025-06-26","o3-mini","o3-mini-2025-01-31","o4-mini","o4-mini-2025-04-16","o4-mini-deep-research","o4-mini-deep-research-2025-06-26","codex-mini-latest","computer-use-preview","gpt-5","gpt-5-2025-08-07","gpt-5-codex","gpt-5-mini","gpt-5-mini-2025-08-07","gpt-5-nano","gpt-5-nano-2025-08-07","gpt-5-pro","gpt-5-pro-2025-10-06","gpt-5.1","gpt-5.1-chat-latest","gpt-5.1-codex-mini","gpt-5.1-codex","gpt-5.1-codex-max","gpt-5.2","gpt-5.2-chat-latest","gpt-5.2-pro"],XWe=["gpt-4.1","gpt-4.1-2025-04-14","gpt-4.1-mini","gpt-4.1-mini-2025-04-14","gpt-4.1-nano","gpt-4.1-nano-2025-04-14","gpt-4o","gpt-4o-2024-05-13","gpt-4o-2024-08-06","gpt-4o-2024-11-20","gpt-4o-audio-preview","gpt-4o-audio-preview-2024-10-01","gpt-4o-audio-preview-2024-12-17","gpt-4o-search-preview","gpt-4o-search-preview-2025-03-11","gpt-4o-mini-search-preview","gpt-4o-mini-search-preview-2025-03-11","gpt-4o-mini","gpt-4o-mini-2024-07-18","gpt-4-turbo","gpt-4-turbo-2024-04-09","gpt-4-turbo-preview","gpt-4-0125-preview","gpt-4-1106-preview","gpt-4","gpt-4-0613","gpt-4.5-preview","gpt-4.5-preview-2025-02-27","gpt-3.5-turbo-0125","gpt-3.5-turbo","gpt-3.5-turbo-1106","chatgpt-4o-latest","gpt-5-chat-latest",...$3],q3=Tt(()=>Ee(Lt.object({conversation:Lt.string().nullish(),include:Lt.array(Lt.enum(["reasoning.encrypted_content","file_search_call.results","message.output_text.logprobs"])).nullish(),instructions:Lt.string().nullish(),logprobs:Lt.union([Lt.boolean(),Lt.number().min(1).max(LD)]).optional(),maxToolCalls:Lt.number().nullish(),metadata:Lt.any().nullish(),parallelToolCalls:Lt.boolean().nullish(),previousResponseId:Lt.string().nullish(),promptCacheKey:Lt.string().nullish(),promptCacheRetention:Lt.enum(["in_memory","24h"]).nullish(),reasoningEffort:Lt.string().nullish(),reasoningSummary:Lt.string().nullish(),safetyIdentifier:Lt.string().nullish(),serviceTier:Lt.enum(["auto","flex","priority","default"]).nullish(),store:Lt.boolean().nullish(),strictJsonSchema:Lt.boolean().nullish(),textVerbosity:Lt.enum(["low","medium","high"]).nullish(),truncation:Lt.enum(["auto","disabled"]).nullish(),user:Lt.string().nullish()})));async function Y3({tools:t,toolChoice:e,strictJsonSchema:r}){t=t?.length?t:void 0;let n=[];if(t==null)return{tools:void 0,toolChoice:void 0,toolWarnings:n};let o=[];for(let a of t)switch(a.type){case"function":o.push({type:"function",name:a.name,description:a.description,parameters:a.inputSchema,strict:r});break;case"provider-defined":{switch(a.id){case"openai.file_search":{let s=await qo({value:a.args,schema:b3});o.push({type:"file_search",vector_store_ids:s.vectorStoreIds,max_num_results:s.maxNumResults,ranking_options:s.ranking?{ranker:s.ranking.ranker,score_threshold:s.ranking.scoreThreshold}:void 0,filters:s.filters});break}case"openai.local_shell":{o.push({type:"local_shell"});break}case"openai.web_search_preview":{let s=await qo({value:a.args,schema:D3});o.push({type:"web_search_preview",search_context_size:s.searchContextSize,user_location:s.userLocation});break}case"openai.web_search":{let s=await qo({value:a.args,schema:P3});o.push({type:"web_search",filters:s.filters!=null?{allowed_domains:s.filters.allowedDomains}:void 0,external_web_access:s.externalWebAccess,search_context_size:s.searchContextSize,user_location:s.userLocation});break}case"openai.code_interpreter":{let s=await qo({value:a.args,schema:y3});o.push({type:"code_interpreter",container:s.container==null?{type:"auto",file_ids:void 0}:typeof s.container=="string"?s.container:{type:"auto",file_ids:s.container.fileIds}});break}case"openai.image_generation":{let s=await qo({value:a.args,schema:C3});o.push({type:"image_generation",background:s.background,input_fidelity:s.inputFidelity,input_image_mask:s.inputImageMask?{file_id:s.inputImageMask.fileId,image_url:s.inputImageMask.imageUrl}:void 0,model:s.model,size:s.size,quality:s.quality,moderation:s.moderation,output_format:s.outputFormat,output_compression:s.outputCompression});break}}break}default:n.push({type:"unsupported-tool",tool:a});break}if(e==null)return{tools:o,toolChoice:void 0,toolWarnings:n};let i=e.type;switch(i){case"auto":case"none":case"required":return{tools:o,toolChoice:i,toolWarnings:n};case"tool":return{tools:o,toolChoice:e.toolName==="code_interpreter"||e.toolName==="file_search"||e.toolName==="image_generation"||e.toolName==="web_search_preview"||e.toolName==="web_search"?{type:e.toolName}:{type:"function",name:e.toolName},toolWarnings:n};default:{let a=i;throw new K3({functionality:`tool choice type: ${a}`})}}}var X3=class{constructor(t,e){this.specificationVersion="v2",this.supportedUrls={"image/*":[/^https?:\/\/.*$/],"application/pdf":[/^https?:\/\/.*$/]},this.modelId=t,this.config=e}get provider(){return this.config.provider}async getArgs({maxOutputTokens:t,temperature:e,stopSequences:r,topP:n,topK:o,presencePenalty:i,frequencyPenalty:a,seed:s,prompt:c,providerOptions:l,tools:u,toolChoice:d,responseFormat:p}){var m,f,h,S;let g=[],E=_D(this.modelId);o!=null&&g.push({type:"unsupported-setting",setting:"topK"}),s!=null&&g.push({type:"unsupported-setting",setting:"seed"}),i!=null&&g.push({type:"unsupported-setting",setting:"presencePenalty"}),a!=null&&g.push({type:"unsupported-setting",setting:"frequencyPenalty"}),r!=null&&g.push({type:"unsupported-setting",setting:"stopSequences"});let y=await Yr({provider:"openai",providerOptions:l,schema:q3});y?.conversation&&y?.previousResponseId&&g.push({type:"unsupported-setting",setting:"conversation",details:"conversation and previousResponseId cannot be used together"});let{input:b,warnings:C}=await G3({prompt:c,systemMessageMode:E.systemMessageMode,fileIdPrefixes:this.config.fileIdPrefixes,store:(m=y?.store)!=null?m:!0,hasLocalShellTool:M("openai.local_shell")});g.push(...C);let I=(f=y?.strictJsonSchema)!=null?f:!1,_=y?.include;function R(q){_==null?_=[q]:_.includes(q)||(_=[..._,q])}function M(q){return u?.find(X=>X.type==="provider-defined"&&X.id===q)!=null}let P=typeof y?.logprobs=="number"?y?.logprobs:y?.logprobs===!0?LD:void 0;P&&R("message.output_text.logprobs");let B=(h=u?.find(q=>q.type==="provider-defined"&&(q.id==="openai.web_search"||q.id==="openai.web_search_preview")))==null?void 0:h.name;B&&R("web_search_call.action.sources"),M("openai.code_interpreter")&&R("code_interpreter_call.outputs");let F=y?.store;F===!1&&E.isReasoningModel&&R("reasoning.encrypted_content");let G={model:this.modelId,input:b,temperature:e,top_p:n,max_output_tokens:t,...(p?.type==="json"||y?.textVerbosity)&&{text:{...p?.type==="json"&&{format:p.schema!=null?{type:"json_schema",strict:I,name:(S=p.name)!=null?S:"response",description:p.description,schema:p.schema}:{type:"json_object"}},...y?.textVerbosity&&{verbosity:y.textVerbosity}}},conversation:y?.conversation,max_tool_calls:y?.maxToolCalls,metadata:y?.metadata,parallel_tool_calls:y?.parallelToolCalls,previous_response_id:y?.previousResponseId,store:F,user:y?.user,instructions:y?.instructions,service_tier:y?.serviceTier,include:_,prompt_cache_key:y?.promptCacheKey,prompt_cache_retention:y?.promptCacheRetention,safety_identifier:y?.safetyIdentifier,top_logprobs:P,truncation:y?.truncation,...E.isReasoningModel&&(y?.reasoningEffort!=null||y?.reasoningSummary!=null)&&{reasoning:{...y?.reasoningEffort!=null&&{effort:y.reasoningEffort},...y?.reasoningSummary!=null&&{summary:y.reasoningSummary}}}};E.isReasoningModel?y?.reasoningEffort==="none"&&E.supportsNonReasoningParameters||(G.temperature!=null&&(G.temperature=void 0,g.push({type:"unsupported-setting",setting:"temperature",details:"temperature is not supported for reasoning models"})),G.top_p!=null&&(G.top_p=void 0,g.push({type:"unsupported-setting",setting:"topP",details:"topP is not supported for reasoning models"}))):(y?.reasoningEffort!=null&&g.push({type:"unsupported-setting",setting:"reasoningEffort",details:"reasoningEffort is not supported for non-reasoning models"}),y?.reasoningSummary!=null&&g.push({type:"unsupported-setting",setting:"reasoningSummary",details:"reasoningSummary is not supported for non-reasoning models"})),y?.serviceTier==="flex"&&!E.supportsFlexProcessing&&(g.push({type:"unsupported-setting",setting:"serviceTier",details:"flex processing is only available for o3, o4-mini, and gpt-5 models"}),delete G.service_tier),y?.serviceTier==="priority"&&!E.supportsPriorityProcessing&&(g.push({type:"unsupported-setting",setting:"serviceTier",details:"priority processing is only available for supported models (gpt-4, gpt-5, gpt-5-mini, o3, o4-mini) and requires Enterprise access. gpt-5-nano is not supported"}),delete G.service_tier);let{tools:z,toolChoice:ae,toolWarnings:W}=await Y3({tools:u,toolChoice:d,strictJsonSchema:I});return{webSearchToolName:B,args:{...G,tools:z,tool_choice:ae},warnings:[...g,...W],store:F}}async doGenerate(t){var e,r,n,o,i,a,s,c,l,u,d,p,m,f,h,S,g,E,y,b,C,I,_,R,M,P,B,F;let{args:G,warnings:z,webSearchToolName:ae}=await this.getArgs(t),W=this.config.url({path:"/responses",modelId:this.modelId}),q=this.config.provider.replace(".responses",""),{responseHeaders:X,value:ne,rawValue:de}=await Xr({url:W,headers:br(this.config.headers(),t.headers),body:G,failedResponseHandler:Yo,successfulResponseHandler:Zn(W3),abortSignal:t.abortSignal,fetch:this.config.fetch});if(ne.error)throw new z3({message:ne.error.message,url:W,requestBodyValues:G,statusCode:400,responseHeaders:X,responseBody:de,isRetryable:!1});let Te=[],te=[],be=!1;for(let x of ne.output)switch(x.type){case"reasoning":{x.summary.length===0&&x.summary.push({type:"summary_text",text:""});for(let se of x.summary)Te.push({type:"reasoning",text:se.text,providerMetadata:{[q]:{itemId:x.id,reasoningEncryptedContent:(e=x.encrypted_content)!=null?e:null}}});break}case"image_generation_call":{Te.push({type:"tool-call",toolCallId:x.id,toolName:"image_generation",input:"{}",providerExecuted:!0}),Te.push({type:"tool-result",toolCallId:x.id,toolName:"image_generation",result:{result:x.result},providerExecuted:!0});break}case"local_shell_call":{Te.push({type:"tool-call",toolCallId:x.call_id,toolName:"local_shell",input:JSON.stringify({action:x.action}),providerMetadata:{[q]:{itemId:x.id}}});break}case"message":{for(let se of x.content){(n=(r=t.providerOptions)==null?void 0:r.openai)!=null&&n.logprobs&&se.logprobs&&te.push(se.logprobs),Te.push({type:"text",text:se.text,providerMetadata:{[q]:{itemId:x.id}}});for(let Ae of se.annotations)Ae.type==="url_citation"?Te.push({type:"source",sourceType:"url",id:(a=(i=(o=this.config).generateId)==null?void 0:i.call(o))!=null?a:vn(),url:Ae.url,title:Ae.title}):Ae.type==="file_citation"?Te.push({type:"source",sourceType:"document",id:(l=(c=(s=this.config).generateId)==null?void 0:c.call(s))!=null?l:vn(),mediaType:"text/plain",title:(d=(u=Ae.quote)!=null?u:Ae.filename)!=null?d:"Document",filename:(p=Ae.filename)!=null?p:Ae.file_id,...Ae.file_id?{providerMetadata:{[q]:{fileId:Ae.file_id}}}:{}}):Ae.type==="container_file_citation"?Te.push({type:"source",sourceType:"document",id:(h=(f=(m=this.config).generateId)==null?void 0:f.call(m))!=null?h:vn(),mediaType:"text/plain",title:(g=(S=Ae.filename)!=null?S:Ae.file_id)!=null?g:"Document",filename:(E=Ae.filename)!=null?E:Ae.file_id,providerMetadata:{[q]:{fileId:Ae.file_id,containerId:Ae.container_id,...Ae.index!=null?{index:Ae.index}:{}}}}):Ae.type==="file_path"&&Te.push({type:"source",sourceType:"document",id:(C=(b=(y=this.config).generateId)==null?void 0:b.call(y))!=null?C:vn(),mediaType:"application/octet-stream",title:Ae.file_id,filename:Ae.file_id,providerMetadata:{[q]:{fileId:Ae.file_id,...Ae.index!=null?{index:Ae.index}:{}}}})}break}case"function_call":{be=!0,Te.push({type:"tool-call",toolCallId:x.call_id,toolName:x.name,input:x.arguments,providerMetadata:{[q]:{itemId:x.id}}});break}case"web_search_call":{Te.push({type:"tool-call",toolCallId:x.id,toolName:ae??"web_search",input:JSON.stringify({}),providerExecuted:!0}),Te.push({type:"tool-result",toolCallId:x.id,toolName:ae??"web_search",result:wD(x.action),providerExecuted:!0});break}case"computer_call":{Te.push({type:"tool-call",toolCallId:x.id,toolName:"computer_use",input:"",providerExecuted:!0}),Te.push({type:"tool-result",toolCallId:x.id,toolName:"computer_use",result:{type:"computer_use_tool_result",status:x.status||"completed"},providerExecuted:!0});break}case"file_search_call":{Te.push({type:"tool-call",toolCallId:x.id,toolName:"file_search",input:"{}",providerExecuted:!0}),Te.push({type:"tool-result",toolCallId:x.id,toolName:"file_search",result:{queries:x.queries,results:(_=(I=x.results)==null?void 0:I.map(se=>({attributes:se.attributes,fileId:se.file_id,filename:se.filename,score:se.score,text:se.text})))!=null?_:null},providerExecuted:!0});break}case"code_interpreter_call":{Te.push({type:"tool-call",toolCallId:x.id,toolName:"code_interpreter",input:JSON.stringify({code:x.code,containerId:x.container_id}),providerExecuted:!0}),Te.push({type:"tool-result",toolCallId:x.id,toolName:"code_interpreter",result:{outputs:x.outputs},providerExecuted:!0});break}}let Pe={[q]:{...ne.id!=null?{responseId:ne.id}:{}}};te.length>0&&(Pe[q].logprobs=te),typeof ne.service_tier=="string"&&(Pe[q].serviceTier=ne.service_tier);let ve=ne.usage;return{content:Te,finishReason:CD({finishReason:(R=ne.incomplete_details)==null?void 0:R.reason,hasFunctionCall:be}),usage:{inputTokens:ve.input_tokens,outputTokens:ve.output_tokens,totalTokens:ve.input_tokens+ve.output_tokens,reasoningTokens:(P=(M=ve.output_tokens_details)==null?void 0:M.reasoning_tokens)!=null?P:void 0,cachedInputTokens:(F=(B=ve.input_tokens_details)==null?void 0:B.cached_tokens)!=null?F:void 0},request:{body:G},response:{id:ne.id,timestamp:new Date(ne.created_at*1e3),modelId:ne.model,headers:X,body:de},providerMetadata:Pe,warnings:z}}async doStream(t){let{args:e,warnings:r,webSearchToolName:n,store:o}=await this.getArgs(t),{responseHeaders:i,value:a}=await Xr({url:this.config.url({path:"/responses",modelId:this.modelId}),headers:br(this.config.headers(),t.headers),body:{...e,stream:!0},failedResponseHandler:Yo,successfulResponseHandler:Rc(V3),abortSignal:t.abortSignal,fetch:this.config.fetch}),s=this,c=this.config.provider.replace(".responses",""),l="unknown",u={inputTokens:void 0,outputTokens:void 0,totalTokens:void 0},d=[],p=null,m={},f=[],h=!1,S={},g;return{stream:a.pipeThrough(new TransformStream({start(E){E.enqueue({type:"stream-start",warnings:r})},transform(E,y){var b,C,I,_,R,M,P,B,F,G,z,ae,W,q,X,ne,de,Te,te,be,Pe,ve;if(t.includeRawChunks&&y.enqueue({type:"raw",rawValue:E.rawValue}),!E.success){l="error",y.enqueue({type:"error",error:E.error});return}let x=E.value;if(RD(x))x.item.type==="function_call"?(m[x.output_index]={toolName:x.item.name,toolCallId:x.item.call_id},y.enqueue({type:"tool-input-start",id:x.item.call_id,toolName:x.item.name})):x.item.type==="web_search_call"?(m[x.output_index]={toolName:n??"web_search",toolCallId:x.item.id},y.enqueue({type:"tool-input-start",id:x.item.id,toolName:n??"web_search",providerExecuted:!0}),y.enqueue({type:"tool-input-end",id:x.item.id}),y.enqueue({type:"tool-call",toolCallId:x.item.id,toolName:n??"web_search",input:JSON.stringify({}),providerExecuted:!0})):x.item.type==="computer_call"?(m[x.output_index]={toolName:"computer_use",toolCallId:x.item.id},y.enqueue({type:"tool-input-start",id:x.item.id,toolName:"computer_use",providerExecuted:!0})):x.item.type==="code_interpreter_call"?(m[x.output_index]={toolName:"code_interpreter",toolCallId:x.item.id,codeInterpreter:{containerId:x.item.container_id}},y.enqueue({type:"tool-input-start",id:x.item.id,toolName:"code_interpreter",providerExecuted:!0}),y.enqueue({type:"tool-input-delta",id:x.item.id,delta:`{"containerId":"${x.item.container_id}","code":"`})):x.item.type==="file_search_call"?y.enqueue({type:"tool-call",toolCallId:x.item.id,toolName:"file_search",input:"{}",providerExecuted:!0}):x.item.type==="image_generation_call"?y.enqueue({type:"tool-call",toolCallId:x.item.id,toolName:"image_generation",input:"{}",providerExecuted:!0}):x.item.type==="message"?(f.splice(0,f.length),y.enqueue({type:"text-start",id:x.item.id,providerMetadata:{[c]:{itemId:x.item.id}}})):RD(x)&&x.item.type==="reasoning"&&(S[x.item.id]={encryptedContent:x.item.encrypted_content,summaryParts:{0:"active"}},y.enqueue({type:"reasoning-start",id:`${x.item.id}:0`,providerMetadata:{[c]:{itemId:x.item.id,reasoningEncryptedContent:(b=x.item.encrypted_content)!=null?b:null}}}));else if(Q3(x)){if(x.item.type==="message")y.enqueue({type:"text-end",id:x.item.id,providerMetadata:{[c]:{itemId:x.item.id,...f.length>0&&{annotations:f}}}});else if(x.item.type==="function_call")m[x.output_index]=void 0,h=!0,y.enqueue({type:"tool-input-end",id:x.item.call_id}),y.enqueue({type:"tool-call",toolCallId:x.item.call_id,toolName:x.item.name,input:x.item.arguments,providerMetadata:{[c]:{itemId:x.item.id}}});else if(x.item.type==="web_search_call")m[x.output_index]=void 0,y.enqueue({type:"tool-result",toolCallId:x.item.id,toolName:n??"web_search",result:wD(x.item.action),providerExecuted:!0});else if(x.item.type==="computer_call")m[x.output_index]=void 0,y.enqueue({type:"tool-input-end",id:x.item.id}),y.enqueue({type:"tool-call",toolCallId:x.item.id,toolName:"computer_use",input:"",providerExecuted:!0}),y.enqueue({type:"tool-result",toolCallId:x.item.id,toolName:"computer_use",result:{type:"computer_use_tool_result",status:x.item.status||"completed"},providerExecuted:!0});else if(x.item.type==="file_search_call")m[x.output_index]=void 0,y.enqueue({type:"tool-result",toolCallId:x.item.id,toolName:"file_search",result:{queries:x.item.queries,results:(I=(C=x.item.results)==null?void 0:C.map(se=>({attributes:se.attributes,fileId:se.file_id,filename:se.filename,score:se.score,text:se.text})))!=null?I:null},providerExecuted:!0});else if(x.item.type==="code_interpreter_call")m[x.output_index]=void 0,y.enqueue({type:"tool-result",toolCallId:x.item.id,toolName:"code_interpreter",result:{outputs:x.item.outputs},providerExecuted:!0});else if(x.item.type==="image_generation_call")y.enqueue({type:"tool-result",toolCallId:x.item.id,toolName:"image_generation",result:{result:x.item.result},providerExecuted:!0});else if(x.item.type==="local_shell_call")m[x.output_index]=void 0,y.enqueue({type:"tool-call",toolCallId:x.item.call_id,toolName:"local_shell",input:JSON.stringify({action:{type:"exec",command:x.item.action.command,timeoutMs:x.item.action.timeout_ms,user:x.item.action.user,workingDirectory:x.item.action.working_directory,env:x.item.action.env}}),providerMetadata:{[c]:{itemId:x.item.id}}});else if(x.item.type==="reasoning"){let se=S[x.item.id],Ae=Object.entries(se.summaryParts).filter(([dn,Mo])=>Mo==="active"||Mo==="can-conclude").map(([dn])=>dn);for(let dn of Ae)y.enqueue({type:"reasoning-end",id:`${x.item.id}:${dn}`,providerMetadata:{[c]:{itemId:x.item.id,reasoningEncryptedContent:(_=x.item.encrypted_content)!=null?_:null}}});delete S[x.item.id]}}else if(tJ(x)){let se=m[x.output_index];se!=null&&y.enqueue({type:"tool-input-delta",id:se.toolCallId,delta:x.delta})}else if(rJ(x)){let se=m[x.output_index];se!=null&&y.enqueue({type:"tool-input-delta",id:se.toolCallId,delta:JSON.stringify(x.delta).slice(1,-1)})}else if(nJ(x)){let se=m[x.output_index];se!=null&&(y.enqueue({type:"tool-input-delta",id:se.toolCallId,delta:'"}'}),y.enqueue({type:"tool-input-end",id:se.toolCallId}),y.enqueue({type:"tool-call",toolCallId:se.toolCallId,toolName:"code_interpreter",input:JSON.stringify({code:x.code,containerId:se.codeInterpreter.containerId}),providerExecuted:!0}))}else if(eJ(x))p=x.response.id,y.enqueue({type:"response-metadata",id:x.response.id,timestamp:new Date(x.response.created_at*1e3),modelId:x.response.model});else if(J3(x))y.enqueue({type:"text-delta",id:x.item_id,delta:x.delta}),(M=(R=t.providerOptions)==null?void 0:R.openai)!=null&&M.logprobs&&x.logprobs&&d.push(x.logprobs);else if(x.type==="response.reasoning_summary_part.added"){if(x.summary_index>0){let se=S[x.item_id];se.summaryParts[x.summary_index]="active";for(let Ae of Object.keys(se.summaryParts))se.summaryParts[Ae]==="can-conclude"&&(y.enqueue({type:"reasoning-end",id:`${x.item_id}:${Ae}`,providerMetadata:{[c]:{itemId:x.item_id}}}),se.summaryParts[Ae]="concluded");y.enqueue({type:"reasoning-start",id:`${x.item_id}:${x.summary_index}`,providerMetadata:{[c]:{itemId:x.item_id,reasoningEncryptedContent:(B=(P=S[x.item_id])==null?void 0:P.encryptedContent)!=null?B:null}}})}}else x.type==="response.reasoning_summary_text.delta"?y.enqueue({type:"reasoning-delta",id:`${x.item_id}:${x.summary_index}`,delta:x.delta,providerMetadata:{[c]:{itemId:x.item_id}}}):x.type==="response.reasoning_summary_part.done"?o?(y.enqueue({type:"reasoning-end",id:`${x.item_id}:${x.summary_index}`,providerMetadata:{[c]:{itemId:x.item_id}}}),S[x.item_id].summaryParts[x.summary_index]="concluded"):S[x.item_id].summaryParts[x.summary_index]="can-conclude":Z3(x)?(l=CD({finishReason:(F=x.response.incomplete_details)==null?void 0:F.reason,hasFunctionCall:h}),u.inputTokens=x.response.usage.input_tokens,u.outputTokens=x.response.usage.output_tokens,u.totalTokens=x.response.usage.input_tokens+x.response.usage.output_tokens,u.reasoningTokens=(z=(G=x.response.usage.output_tokens_details)==null?void 0:G.reasoning_tokens)!=null?z:void 0,u.cachedInputTokens=(W=(ae=x.response.usage.input_tokens_details)==null?void 0:ae.cached_tokens)!=null?W:void 0,typeof x.response.service_tier=="string"&&(g=x.response.service_tier)):oJ(x)?(f.push(x.annotation),x.annotation.type==="url_citation"?y.enqueue({type:"source",sourceType:"url",id:(ne=(X=(q=s.config).generateId)==null?void 0:X.call(q))!=null?ne:vn(),url:x.annotation.url,title:x.annotation.title}):x.annotation.type==="file_citation"&&y.enqueue({type:"source",sourceType:"document",id:(te=(Te=(de=s.config).generateId)==null?void 0:Te.call(de))!=null?te:vn(),mediaType:"text/plain",title:(Pe=(be=x.annotation.quote)!=null?be:x.annotation.filename)!=null?Pe:"Document",filename:(ve=x.annotation.filename)!=null?ve:x.annotation.file_id,...x.annotation.file_id?{providerMetadata:{[c]:{fileId:x.annotation.file_id}}}:{}})):iJ(x)&&y.enqueue({type:"error",error:x})},flush(E){let y={[c]:{responseId:p}};d.length>0&&(y[c].logprobs=d),g!==void 0&&(y[c].serviceTier=g),E.enqueue({type:"finish",finishReason:l,usage:u,providerMetadata:y})}})),request:{body:e},response:{headers:i}}}};function J3(t){return t.type==="response.output_text.delta"}function Q3(t){return t.type==="response.output_item.done"}function Z3(t){return t.type==="response.completed"||t.type==="response.incomplete"}function eJ(t){return t.type==="response.created"}function tJ(t){return t.type==="response.function_call_arguments.delta"}function rJ(t){return t.type==="response.code_interpreter_call_code.delta"}function nJ(t){return t.type==="response.code_interpreter_call_code.done"}function RD(t){return t.type==="response.output_item.added"}function oJ(t){return t.type==="response.output_text.annotation.added"}function iJ(t){return t.type==="error"}function wD(t){var e;switch(t.type){case"search":return{action:{type:"search",query:(e=t.query)!=null?e:void 0},...t.sources!=null&&{sources:t.sources}};case"open_page":return{action:{type:"openPage",url:t.url}};case"find_in_page":return{action:{type:"findInPage",url:t.url,pattern:t.pattern}}}}var aJ=Tt(()=>Ee(xb.object({instructions:xb.string().nullish(),speed:xb.number().min(.25).max(4).default(1).nullish()}))),sJ=class{constructor(t,e){this.modelId=t,this.config=e,this.specificationVersion="v2"}get provider(){return this.config.provider}async getArgs({text:t,voice:e="alloy",outputFormat:r="mp3",speed:n,instructions:o,language:i,providerOptions:a}){let s=[],c=await Yr({provider:"openai",providerOptions:a,schema:aJ}),l={model:this.modelId,input:t,voice:e,response_format:"mp3",speed:n,instructions:o};if(r&&(["mp3","opus","aac","flac","wav","pcm"].includes(r)?l.response_format=r:s.push({type:"unsupported-setting",setting:"outputFormat",details:`Unsupported output format: ${r}. Using mp3 instead.`})),c){let u={};for(let d in u){let p=u[d];p!==void 0&&(l[d]=p)}}return i&&s.push({type:"unsupported-setting",setting:"language",details:`OpenAI speech models do not support language selection. Language parameter "${i}" was ignored.`}),{requestBody:l,warnings:s}}async doGenerate(t){var e,r,n;let o=(n=(r=(e=this.config._internal)==null?void 0:e.currentDate)==null?void 0:r.call(e))!=null?n:new Date,{requestBody:i,warnings:a}=await this.getArgs(t),{value:s,responseHeaders:c,rawValue:l}=await Xr({url:this.config.url({path:"/audio/speech",modelId:this.modelId}),headers:br(this.config.headers(),t.headers),body:i,failedResponseHandler:Yo,successfulResponseHandler:uD(),abortSignal:t.abortSignal,fetch:this.config.fetch});return{audio:s,warnings:a,request:{body:JSON.stringify(i)},response:{timestamp:o,modelId:this.modelId,headers:c,body:l}}}},lJ=Tt(()=>Ee(zt.object({text:zt.string(),language:zt.string().nullish(),duration:zt.number().nullish(),words:zt.array(zt.object({word:zt.string(),start:zt.number(),end:zt.number()})).nullish(),segments:zt.array(zt.object({id:zt.number(),seek:zt.number(),start:zt.number(),end:zt.number(),text:zt.string(),tokens:zt.array(zt.number()),temperature:zt.number(),avg_logprob:zt.number(),compression_ratio:zt.number(),no_speech_prob:zt.number()})).nullish()}))),cJ=Tt(()=>Ee(ha.object({include:ha.array(ha.string()).optional(),language:ha.string().optional(),prompt:ha.string().optional(),temperature:ha.number().min(0).max(1).default(0).optional(),timestampGranularities:ha.array(ha.enum(["word","segment"])).default(["segment"]).optional()}))),xD={afrikaans:"af",arabic:"ar",armenian:"hy",azerbaijani:"az",belarusian:"be",bosnian:"bs",bulgarian:"bg",catalan:"ca",chinese:"zh",croatian:"hr",czech:"cs",danish:"da",dutch:"nl",english:"en",estonian:"et",finnish:"fi",french:"fr",galician:"gl",german:"de",greek:"el",hebrew:"he",hindi:"hi",hungarian:"hu",icelandic:"is",indonesian:"id",italian:"it",japanese:"ja",kannada:"kn",kazakh:"kk",korean:"ko",latvian:"lv",lithuanian:"lt",macedonian:"mk",malay:"ms",marathi:"mr",maori:"mi",nepali:"ne",norwegian:"no",persian:"fa",polish:"pl",portuguese:"pt",romanian:"ro",russian:"ru",serbian:"sr",slovak:"sk",slovenian:"sl",spanish:"es",swahili:"sw",swedish:"sv",tagalog:"tl",tamil:"ta",thai:"th",turkish:"tr",ukrainian:"uk",urdu:"ur",vietnamese:"vi",welsh:"cy"},uJ=class{constructor(t,e){this.modelId=t,this.config=e,this.specificationVersion="v2"}get provider(){return this.config.provider}async getArgs({audio:t,mediaType:e,providerOptions:r}){let n=[],o=await Yr({provider:"openai",providerOptions:r,schema:cJ}),i=new FormData,a=t instanceof Uint8Array?new Blob([t]):new Blob([gD(t)]);i.append("model",this.modelId);let s=iD(e);if(i.append("file",new File([a],"audio",{type:e}),`audio.${s}`),o){let c={include:o.include,language:o.language,prompt:o.prompt,response_format:["gpt-4o-transcribe","gpt-4o-mini-transcribe"].includes(this.modelId)?"json":"verbose_json",temperature:o.temperature,timestamp_granularities:o.timestampGranularities};for(let[l,u]of Object.entries(c))if(u!=null)if(Array.isArray(u))for(let d of u)i.append(`${l}[]`,String(d));else i.append(l,String(u))}return{formData:i,warnings:n}}async doGenerate(t){var e,r,n,o,i,a,s,c;let l=(n=(r=(e=this.config._internal)==null?void 0:e.currentDate)==null?void 0:r.call(e))!=null?n:new Date,{formData:u,warnings:d}=await this.getArgs(t),{value:p,responseHeaders:m,rawValue:f}=await sD({url:this.config.url({path:"/audio/transcriptions",modelId:this.modelId}),headers:br(this.config.headers(),t.headers),formData:u,failedResponseHandler:Yo,successfulResponseHandler:Zn(lJ),abortSignal:t.abortSignal,fetch:this.config.fetch}),h=p.language!=null&&p.language in xD?xD[p.language]:void 0;return{text:p.text,segments:(s=(a=(o=p.segments)==null?void 0:o.map(S=>({text:S.text,startSecond:S.start,endSecond:S.end})))!=null?a:(i=p.words)==null?void 0:i.map(S=>({text:S.word,startSecond:S.start,endSecond:S.end})))!=null?s:[],language:h,durationInSeconds:(c=p.duration)!=null?c:void 0,warnings:d,response:{timestamp:l,modelId:this.modelId,headers:m,body:f}}}},dJ="2.0.89";function Ib(t={}){var e,r;let n=(e=SD(oD({settingValue:t.baseURL,environmentVariableName:"OPENAI_BASE_URL"})))!=null?e:"https://api.openai.com/v1",o=(r=t.name)!=null?r:"openai",i=()=>Eb({Authorization:`Bearer ${nD({apiKey:t.apiKey,environmentVariableName:"OPENAI_API_KEY",description:"OpenAI"})}`,"OpenAI-Organization":t.organization,"OpenAI-Project":t.project,...t.headers},`ai-sdk/openai/${dJ}`),a=h=>new r3(h,{provider:`${o}.chat`,url:({path:S})=>`${n}${S}`,headers:i,fetch:t.fetch}),s=h=>new s3(h,{provider:`${o}.completion`,url:({path:S})=>`${n}${S}`,headers:i,fetch:t.fetch}),c=h=>new d3(h,{provider:`${o}.embedding`,url:({path:S})=>`${n}${S}`,headers:i,fetch:t.fetch}),l=h=>new h3(h,{provider:`${o}.image`,url:({path:S})=>`${n}${S}`,headers:i,fetch:t.fetch}),u=h=>new uJ(h,{provider:`${o}.transcription`,url:({path:S})=>`${n}${S}`,headers:i,fetch:t.fetch}),d=h=>new sJ(h,{provider:`${o}.speech`,url:({path:S})=>`${n}${S}`,headers:i,fetch:t.fetch}),p=h=>{if(new.target)throw new Error("The OpenAI model function cannot be called with the new keyword.");return m(h)},m=h=>new X3(h,{provider:`${o}.responses`,url:({path:S})=>`${n}${S}`,headers:i,fetch:t.fetch,fileIdPrefixes:["file-"]}),f=function(h){return p(h)};return f.languageModel=p,f.chat=a,f.completion=s,f.responses=m,f.embedding=c,f.textEmbedding=c,f.textEmbeddingModel=c,f.image=l,f.imageModel=l,f.transcription=u,f.transcriptionModel=u,f.speech=d,f.speechModel=d,f.tools=B3,f}var s$e=Ib();function ND(t){let{apiKey:e,sessionId:r,extraHeaders:n,loggerTags:o}=t,i={Authorization:`Bearer ${e}`,[Vm]:Ms??"",...r&&{[C_]:r},...n||{}};return o&&(i[A_]=JSON.stringify(o)),i}var Hh=t=>e=>{let r=ND(t);return pJ({baseURL:`${t.baseUrl}/v1/llm/anthropic/${e}`,headers:r,apiKey:t.apiKey})(e)},Pb=t=>e=>{let r=ND(t);return Ib({baseURL:`${t.baseUrl}/v1/llm/openai/${e}`,headers:r,apiKey:t.apiKey})(e)};var cn=class extends Tr{agentConfig;constructor(e,r){let n={...xl,...e};super(r),this.agentConfig=n}getAgentConfig(){return this.agentConfig}async rankChunksWithAi(e,r){let n={...e,loggerTags:r.loggerTags},o=await this.sendRequest(`/${Y}/web-agent/recommend-chunks-ai`,{method:"POST",body:n,signal:r.abortSignal});return Ew.parse(o)}async rankChunksWithRag(e,r){let n=await this.sendRequest(`/${Y}/web-agent/recommend-chunks`,{method:"POST",body:{cliVersion:Ms,...e},signal:r.abortSignal});return yw.parse(n)}async getScreenshotFromS3(e){let r=await this.sendRequest(`/${Y}/s3/visual-diff-screenshot`,{method:"POST",body:{url:e}});return mJ.string().parse(r)}async getElementLocation(e,r){let n={...e,disableCache:r.disableCache,loggerTags:r.loggerTags,useMemory:r.useMemory,agentConfigVersion:this.agentConfig?.locator},o=await this.sendRequest(`/${Y}/web-agent/locate-element`,{method:"POST",body:n,signal:r.abortSignal});return P_.parse(o)}async getAssertionResult(e,r){let n={...e,disableCache:!!r.disableCache,useConsensus:!!r.useConsensus,attemptNumber:r.attemptNumber,loggerTags:r.loggerTags,useMemory:r.useMemory,agentConfigVersion:this.agentConfig?.assertion},o=await this.sendRequest(`/${Y}/web-agent/assertion`,{method:"POST",body:n,signal:r.abortSignal});return fE.parse(o)}async getLintStepResult(e,r){let n={...e,disableCache:!!r.disableCache,loggerTags:r.loggerTags},o=await this.sendRequest(`/${Y}/web-agent/lint/step`,{method:"POST",body:n,signal:r.abortSignal});return I_.parse(o)}async getLintMcpCopilotMessageResult(e,r){let n={message:e.message,disableCache:!!r.disableCache,loggerTags:r.loggerTags},o=await this.sendRequest(`/${Y}/web-agent/lint/mcp-copilot`,{method:"POST",body:n,signal:r.abortSignal});return w_.parse(o)}async getMcpCopilotConversationEvaluation(e,r){let n={messagesAndToolCalls:e.messagesAndToolCalls,disableCache:!!r.disableCache,loggerTags:r.loggerTags},o=await this.sendRequest(`/${Y}/web-agent/mcp-copilot-conversation-evaluator`,{method:"POST",body:n,signal:r.abortSignal});return x_.parse(o)}async getMcpCopilotChatSummary(e,r){let n={messagesAndToolCalls:e.messagesAndToolCalls,disableCache:!!r.disableCache,loggerTags:r.loggerTags},o=await this.sendRequest(`/${Y}/web-agent/mcp-copilot-chat-summary`,{method:"POST",body:n,signal:r.abortSignal});return __.parse(o)}async getVisualAssertionResult(e,r){let n={...e,disableCache:!!r.disableCache,useConsensus:!!r.useConsensus,attemptNumber:r.attemptNumber,loggerTags:r.loggerTags,useMemory:r.useMemory,agentConfigVersion:this.agentConfig?.["visual-assertion"]},o=await this.sendRequest(`/${Y}/web-agent/visual-assertion`,{method:"POST",body:n,signal:r.abortSignal});return fE.parse(o)}async getAiActionCommand(e,r){let n=await this.sendRequest(`/${Y}/web-agent/next-command-dynamic`,{method:"POST",body:{...e,disableCache:r.disableCache,loggerTags:r.loggerTags},signal:r.abortSignal});return R_.parse(n)}async getMultiturnAiActionCommand(e,r){return await this.sendRequest(`/${Y}/web-agent/ai-action/next-command`,{method:"POST",body:{...e,disableCache:r.disableCache,loggerTags:r.loggerTags},signal:r.abortSignal})}async getMultiturnAiActionEvaluation(e,r){let n=await this.sendRequest(`/${Y}/web-agent/ai-action/evaluate`,{method:"POST",body:{...e,disableCache:r.disableCache,loggerTags:r.loggerTags},signal:r.abortSignal});return ZS.parse(n)}async getReverseMappedDescription(e,r){let n=await this.sendRequest(`/${Y}/web-agent/reverse-mapped-description`,{method:"POST",body:{...e,disableCache:r.disableCache,loggerTags:r.loggerTags},signal:r.abortSignal});return M_.parse(n)}async getTextExtraction(e,r){let n={...e,disableCache:r.disableCache,loggerTags:r.loggerTags,agentConfigVersion:this.agentConfig?.["text-extraction"]},o=await this.sendRequest(`/${Y}/web-agent/text-extraction`,{method:"POST",body:n,signal:r.abortSignal});return Zp.parse(o)}async getPageSummary(e,r){let n={...e,disableCache:r.disableCache,loggerTags:r.loggerTags},o=await this.sendRequest(`/${Y}/web-agent/page-summary`,{method:"POST",body:n,signal:r.abortSignal});return qR.parse(o)}async getSmartWaitingDecision(e,r){let n={...e,disableCache:r.disableCache,loggerTags:r.loggerTags},o=await this.sendRequest(`/${Y}/web-agent/smart-waiting`,{method:"POST",body:n,signal:r.abortSignal});return KR.parse(o)}async getTestResultClassification(e,r){let n=await this.sendRequest(`/${Y}/web-agent/result-classification`,{method:"POST",body:{...e,loggerTags:r.loggerTags},signal:r.abortSignal});return FS.parse(n)}async getExtractedKeywords(e,r){let n=await this.sendRequest(`/${Y}/web-agent/extract-keywords`,{method:"POST",body:e,signal:r.abortSignal});return Nw.parse(n)}async getAutohealingProposal(e,r){let n=await this.sendRequest(`/${Y}/web-agent/autoheal-section`,{method:"POST",body:{...e,loggerTags:r.loggerTags},signal:r.abortSignal});return jR.parse(n)}async getFailureRecoveryProposal(e,r){let n=await this.sendRequest(`/${Y}/web-agent/failure-recovery`,{method:"POST",body:{...e,loggerTags:r.loggerTags},signal:r.abortSignal});return WR.parse(n)}async getFailureRecoveryPlan(e,r){let n=await this.sendRequest(`/${Y}/web-agent/failure-recovery-plan`,{method:"POST",body:{...e,loggerTags:r.loggerTags},signal:r.abortSignal});return VR.parse(n)}async getIframeRegex(e,r){let n=await this.sendRequest(`/${Y}/web-agent/iframe-regex`,{method:"POST",body:e,signal:r.abortSignal});return ZA.parse(n)}getAnthropicModelFactory(e){let{sessionId:r,logger:n,streamType:o}=e;return Hh({baseUrl:this.baseUrl,apiKey:this.apiKey,loggerTags:{...ot(n),promptType:o},sessionId:r})}getOpenAIModelFactory(e){let{sessionId:r,logger:n,streamType:o}=e;return Pb({baseUrl:this.baseUrl,apiKey:this.apiKey,loggerTags:{...ot(n),promptType:o},sessionId:r})}};import{z as Mb}from"zod";var pt=class extends Tr{constructor(e){super({...e,mode:void 0})}getAppUrl(){return jl(this.baseUrl)}async getAuthInfo(){let e=await this.sendRequest(`/${Y}/auth/check`,{method:"GET",retries:10,requestTimeoutMs:5e3,onFailedRequest:r=>{v.warn(`API key check failed: ${r.message}`)}});return V_.parse(e)}async bulkGetRunStatus(e){let r=await this.sendRequest(`/${Y}/runs/status`,{method:"POST",body:e,retries:3,requestTimeoutMs:1e4});return z_.parse(r)}async getTestYAMLExport(e){let r=await this.sendRequest(`/${Y}/tests/export`,{method:"POST",body:e,retries:3,requestTimeoutMs:3e4});return L_.parse(r)}async updateStepCaches(e,r){await this.sendRequest(`/${Y}/cache`,{method:"PATCH",body:e,extraHeaders:r,retries:3,requestTimeoutMs:1e4,initialRetryDelayMs:3e3})}async getStepCacheForTest(e,r){let n=await this.sendRequest(`/${Y}/cache`,{method:"POST",body:e,extraHeaders:r,retries:10,requestTimeoutMs:3e4,initialRetryDelayMs:3e3});return D_.parse(n)}async getWebStepCacheMemoryTraces(e){let r=await this.sendRequest(`/${Y}/cache/traces`,{method:"POST",body:e,retries:10,requestTimeoutMs:3e4,initialRetryDelayMs:3e3});return gE.parse(r)}cacheRouteForPlatform(e){switch(e){case"ANDROID":return"android-cache";case"IOS":return"ios-cache"}}async getMobileStepCacheMemoryTraces(e,r){let n=await this.sendRequest(`/${Y}/${this.cacheRouteForPlatform(e)}/traces`,{method:"POST",body:r,retries:10,requestTimeoutMs:3e4,initialRetryDelayMs:3e3});return gE.parse(n)}async updateMobileStepCaches(e){await this.sendRequest(`/${Y}/${this.cacheRouteForPlatform(e.platform)}`,{method:"PATCH",body:e.body,extraHeaders:e.headers,retries:3,requestTimeoutMs:1e4,initialRetryDelayMs:3e3})}async getMobileStepCacheForTest({platform:e,body:r,headers:n}){let o=await this.sendRequest(`/${Y}/${this.cacheRouteForPlatform(e)}`,{method:"POST",body:r,extraHeaders:n,retries:10,requestTimeoutMs:3e4,initialRetryDelayMs:3e3});return k_(xm(e)).parse(o)}async queueTests(e){let r=await this.sendRequest(`/${Y}/tests/queue`,{method:"POST",body:e,retries:3,requestTimeoutMs:1e4});return O_.parse(r)}async uploadScreenshot(e){let r=await this.sendRequest(`/${Y}/screenshots`,{method:"POST",body:e,retries:3,requestTimeoutMs:5e3});return j_.parse(r)}async uploadOnDemandScreenshot(e){return await this.sendRequest(`/${Y}/on-demand-screenshots`,{method:"POST",body:e,retries:3,requestTimeoutMs:5e3}),{apiServerUrl:`${this.baseUrl}/${Y}/on-demand-screenshots/${e.id}`}}async fetchOnDemandScreenshot(e){let r={};return{data:await this.sendRequest(`/${Y}/on-demand-screenshots/${encodeURIComponent(e)}`,{method:"GET",retries:3,requestTimeoutMs:5e3,responseType:"buffer",responseHeadersObject:r}),contentType:r["content-type"]??"image/jpeg"}}async getAllEnvironments(){let e=await this.sendRequest(`/${Y}/environments`,{method:"GET",retries:3,requestTimeoutMs:5e3});return W_.parse(e)}async acquireCacheLock(e,r){let n=await this.sendRequest(`/${Y}/result-cache/lock`,{method:"POST",body:e,signal:r,retries:3,requestTimeoutMs:3e4});return cI.parse(n)}async releaseCacheLock(e){await this.sendRequest(`/${Y}/result-cache/lock`,{method:"DELETE",body:{key:e},retries:3,requestTimeoutMs:5e3})}async deleteCacheResult(e){await this.sendRequest(`/${Y}/result-cache/entry`,{method:"DELETE",body:e,retries:3,requestTimeoutMs:5e3})}async setCacheResult(e){await this.sendRequest(`/${Y}/result-cache/entry`,{method:"PATCH",body:e,retries:3,requestTimeoutMs:5e3})}async getCacheResult(e){try{return await this.sendRequest(`/${Y}/result-cache/entry`,{method:"POST",body:e,retries:3,requestTimeoutMs:5e3})}catch(r){if(r instanceof Error&&r.message.includes("404"))return null;throw r}}async queueSuiteRuns(e){let r=await this.sendRequest(`/${Y}/suites/queue`,{method:"POST",body:e,retries:3,requestTimeoutMs:5e3});return $_.parse(r)}async bulkGetRunGroupStatus(e){let r={runGroupIds:e},n=await this.sendRequest(`/${Y}/run-groups/status`,{method:"POST",body:r,retries:3,requestTimeoutMs:5e3});return fw.array().parse(n)}async uploadProposedSteps(e,r){try{await this.sendRequest(`/${Y}/test-fragments/`,{method:"POST",body:e,retries:3,requestTimeoutMs:1e4})}catch(n){r.error({err:n},"Failed to upload proposed steps")}}async reportBillableEvents(e,r){try{await this.sendRequest(`/${Y}/billing/events`,{method:"POST",body:r,retries:10,requestTimeoutMs:1e4})}catch(n){e.error({err:n},"Failed to report billable event")}}async fetchTestFragment(e){let r=await this.sendRequest(`/${Y}/test-fragments/${e}`,{method:"GET",retries:3,requestTimeoutMs:1e4});return q_.parse(r)}async patchTestFragment(e,r){await this.sendRequest(`/${Y}/test-fragments/${e}`,{method:"PATCH",body:r,retries:3,requestTimeoutMs:1e4})}async getPastTestResults(e,r){let n=await this.sendRequest(`/${Y}/results/tests/${e}`,{method:"POST",body:r,retries:3,requestTimeoutMs:1e4});return K_.parse(n)}async generateTestResultsUploadUrl(){let e=await this.sendRequest(`/${Y}/results/uploads`,{method:"POST",retries:3,requestTimeoutMs:1e4});return Y_.parse(e)}async startProcessingResultsUpload(e,r){let n=await this.sendRequest(`/${Y}/results/uploads/${e}/process`,{method:"POST",body:r,retries:3,requestTimeoutMs:1e4});return X_.parse(n)}async fetchIconKnowledgeBase(e){try{let r=await this.sendRequest(`/${Y}/knowledge-base/icons`,{method:"GET",retries:3,requestTimeoutMs:5e3});return fI.parse(r)}catch(r){return e.error({err:r},"Failed to fetch icon knowledge base"),null}}async saveNewIcons(e,r){try{await this.sendRequest(`/${Y}/knowledge-base/icons`,{method:"POST",body:e,retries:3,requestTimeoutMs:5e3})}catch(n){r.error({err:n},"Failed to save new icons to icon knowledge base")}}async getMergeBaseCommitFromGithub(e,r,n,o){let i=new URLSearchParams;i.set("base",n),i.set("head",o);let a=await this.sendRequest(`/${Y}/git/github/${e}/${r}/merge-base-commit?${i.toString()}`,{method:"GET",retries:3,requestTimeoutMs:1e4});return ad.parse(a)}async getCommitFromGithub(e,r,n){let o=await this.sendRequest(`/${Y}/git/github/${e}/${r}/commits/${n}`,{method:"GET",retries:3,requestTimeoutMs:1e4});return ad.parse(o)}async getMergedBranchFromGithub(e,r,n,o){let i=encodeURIComponent(n),a=await this.sendRequest(`/${Y}/git/github/${e}/${r}/${i}/${o}/merged-branch`,{method:"GET",retries:3,requestTimeoutMs:1e4});return EE.parse(a)}async getMergeBaseCommitFromGitlab(e,r,n){let o=new URLSearchParams;o.set("base",r),o.set("head",n);let i=encodeURIComponent(e),a=await this.sendRequest(`/${Y}/git/gitlab/${i}/merge-base-commit?${o.toString()}`,{method:"GET",retries:3,requestTimeoutMs:5e3});return ad.parse(a)}async getCommitFromGitlab(e,r){let n=encodeURIComponent(e),o=await this.sendRequest(`/${Y}/git/gitlab/${n}/commits/${r}`,{method:"GET",retries:3,requestTimeoutMs:1e4});return ad.parse(o)}async getMergedBranchFromGitlab(e,r,n){let o=encodeURIComponent(r),i=encodeURIComponent(e),a=await this.sendRequest(`/${Y}/git/gitlab/${i}/${o}/${n}/merged-branch`,{method:"GET",retries:3,requestTimeoutMs:1e4});return EE.parse(a)}async getAgentConfig(){let e=await this.sendRequest(`/${Y}/web-agent/agent-config`,{method:"GET",retries:3,requestTimeoutMs:5e3});return Mb.record(Mb.string(),Mb.string()).parse(e)}async getQuarantinedTests(){let e=await this.sendRequest(`/${Y}/quarantine`,{method:"GET"});return J_.parse(e)}async quarantineTest(e,r,n){await this.sendRequest(`/${Y}/quarantine`,{method:"POST",body:{testId:e.id,testName:e.name,reason:r,...n??{}},retries:3,requestTimeoutMs:1e4})}async unquarantineTest(e,r,n){await this.sendRequest(`/${Y}/quarantine/${e.id}`,{method:"DELETE",body:{testName:e.name,reason:r,...n??{}},retries:3,requestTimeoutMs:1e4})}platformRoute(e){switch(e){case"ANDROID":return"android";case"IOS":return"ios"}}async createAndroidEmulator(e){let r=await this.sendRequest(`/${Y}/limbar/android`,{method:"POST",retries:3,body:e,requestTimeoutMs:9e4,initialRetryDelayMs:5e3,maxRetryDelayMs:15e3});return Q_.parse(r)}async extendEmulatorTtl(e,r){try{await this.sendRequest(`/${Y}/limbar/${this.platformRoute(e)}/${r}/keepalive`,{method:"POST",retries:3,requestTimeoutMs:15e3})}catch{}}async generateAssetUploadUrl({channel:e,tag:r,md5:n,platform:o}){let i={channel:e,tag:r,md5:n},a=await this.sendRequest(`/${Y}/limbar/${this.platformRoute(o)}/upload-url`,{method:"POST",retries:3,body:i,requestTimeoutMs:15e3,logResponse:!0});return eI.parse(a)}async deleteAndroidEmulator(e){await this.sendRequest(`/${Y}/limbar/android/${e}`,{method:"DELETE",retries:3,requestTimeoutMs:3e4})}async getMobileAssets(){let e=await this.sendRequest(`/${Y}/limbar/assets`,{method:"GET",retries:3,requestTimeoutMs:1e4});return tI.parse(e)}async getLimbarAssetDownloadUrl(e,r,n){let o=await this.sendRequest(`/${Y}/limbar/assets/${e}/${r}/${this.platformRoute(n)}/download-url`,{method:"GET",retries:2,requestTimeoutMs:3e4});return rI.parse(o)}async deleteAsset(e,r,n){await this.sendRequest(`/${Y}/limbar/assets/${e}/${r}/${this.platformRoute(n)}`,{method:"DELETE",retries:3,requestTimeoutMs:1e4})}async createIosEmulator(e){let r=await this.sendRequest(`/${Y}/limbar/ios`,{method:"POST",retries:3,body:e,requestTimeoutMs:9e4,initialRetryDelayMs:5e3,maxRetryDelayMs:15e3});return Z_.parse(r)}async deleteIosEmulator(e){await this.sendRequest(`/${Y}/limbar/ios/${e}`,{method:"DELETE",retries:3,requestTimeoutMs:3e4})}async generateMobileLogcatUploadUrl(e){let r=await this.sendRequest(`/${Y}/logcat/mobile/upload`,{method:"POST",body:e,retries:3,requestTimeoutMs:1e4});return zx.parse(r)}};async function Gh(t){let e=process.versions.node,r=parseInt(e.split(".")[0]);(isNaN(r)||r<18)&&(v.error(`Node.js version 20 or higher is required to run the CLI. Detected: ${process.versions.node}.`),process.exit(1)),v.debug(`Identified node version ${e}`);let n=await t.client.getAuthInfo();return v.debug("Got auth info from API"),n}var jh=class{apiClient;constructor(e){this.apiClient=e}async reportBillableEvents(e,r){await this.apiClient.reportBillableEvents(e,r)}};var ga=class extends Tr{generator;constructor(e,r){super(e),this.generator=r}async runTemplateMatching(e,r={}){let n=await this.sendRequest(`/${Y}/web-agent/template-matching`,{method:"POST",body:e,signal:r?.signal});return eC.parse(n)}async constructIframeRegex(e,r={}){return this.generator.getIframeRegex(e,{abortSignal:r.signal})}};var wc=class{constructor(e,r){this.client=e;this.orgId=r}getApiServerUrl(){return this.client.baseUrl}getAppServerUrl(){let e=this.getApiServerUrl();return jl(e)}async acquireCacheLock(e,r){return this.client.acquireCacheLock(e,r)}async createOnDemandScreenshot(e,r,n){let{apiServerUrl:o}=await this.client.uploadOnDemandScreenshot({id:e,screenshot:r.toString("base64"),contentType:n});return{apiServerUrl:o,appServerUrl:`${this.getAppServerUrl()}/api/on-demand-screenshots/${e}`,universalHandle:{id:e,contentType:n}}}async fetchOnDemandScreenshot(e){return this.client.fetchOnDemandScreenshot(e.id)}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,r){return this.client.saveNewIcons(e,r)}};import{Faker as fJ,en as hJ}from"@faker-js/faker";var xc="v1",Xo=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 fJ({locale:hJ}),this.fakerInstance.seed(e.fakerSeed))}async sendAiGenerate(e){let r=typeof e=="string"?{input:e}:e;return this.httpClient.sendRequest(`/${xc}/tools/ai/generate`,{method:"POST",body:r}).catch(n=>{throw n instanceof Co?new Error(n.rawError):new Error(`Failed to send AI generation: ${n.message}`)})}async sendSms(e){return this.httpClient.sendRequest(`/${xc}/tools/sms/send`,{method:"POST",body:e}).then(()=>{}).catch(r=>{throw r instanceof Co?new Error(r.rawError):new Error(`Failed to send sms: ${r.message}`)})}async fetchLatestSms(e){return this.httpClient.sendRequest(`/${xc}/tools/sms/fetchLatest`,{method:"POST",body:e}).catch(r=>{throw r instanceof Co?new Error(r.rawError):r})}async sendEmail(e){return this.httpClient.sendRequest(`/${xc}/tools/email/send`,{method:"POST",body:e}).then(()=>{}).catch(r=>{throw r instanceof Co?new Error(r.rawError):new Error(`Failed to send email: ${r.message}`)})}async fetchAllEmails(e){return this.httpClient.sendRequest(`/${xc}/tools/email/fetchAll`,{method:"POST",body:e}).catch(r=>{throw r instanceof Co?new Error(r.rawError):new Error(`Failed to fetch all emails: ${r.message}`)})}async fetchLatestEmail(e){return this.httpClient.sendRequest(`/${xc}/tools/email/fetchLatest`,{method:"POST",body:e}).catch(r=>{throw r instanceof Co?new Error(r.rawError):new Error(`Failed to fetch latest emails: ${r.message}`)})}};function DD(t,e,r){return fetch(t,{method:"PUT",body:r,headers:{"Content-Type":e}})}var Vh=class{constructor(e){this.client=e}async uploadResultsArchive(e,r){let{uploadUrl:n,id:o}=await this.client.generateTestResultsUploadUrl(),i=await DD(n,"application/zip",r);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}};function xo({logger:t,orgId:e,client:r,gitMetadata:n,regenerateCache:o,alwaysSaveCache:i,noCache:a,isolateCachesByEnvironment:s=!1,bustOldestCachePercentage:c}){return a?new Wm:new Ob(t,e,r,n,{regenerateCache:o,alwaysSaveCache:i,bustOldestCachePercentage:c,isolateCachesByEnvironment:s})}var Ob=class{constructor(e,r,n,o,i){this.orgId=r;this.client=n;let{regenerateCache:a,alwaysSaveCache:s,bustOldestCachePercentage:c,isolateCachesByEnvironment:l}=i,{gitBranchName:u,gitProtectedBranches:d}=o;e.info({options:i,gitBranchName:u,gitProtectedBranches:d},"Cache storage initialization options"),this.cacheHeaders=hE(o),this.isolateCachesByEnvironment=l,this.readCaches=!a;let p=u&&d.includes(u);s||!p?this.writeCaches=!0:this.writeCaches=!1,p||(this.bustOldestCachePercentage=c)}cacheHeaders;readCaches;writeCaches;isolateCachesByEnvironment;bustOldestCachePercentage;async saveStepCacheEntries({entries:e,logger:r}){if(!this.writeCaches){r.debug("Skipping cache storage because branch is protected");return}try{await this.client.updateStepCaches({entries:TE(e,this.isolateCachesByEnvironment)},this.cacheHeaders)}catch(n){r.error({err:n},"Failed to save step cache entries")}}async resolveStepCacheEntries(e){if(!this.readCaches){e.logger.debug("Skipping cache resolution because of regenerate flag");return}let{steps:r,beforeSteps:n,afterSteps:o}=e.stepLists,i=await this.client.getStepCacheForTest({testId:e.testId,environment:this.isolateCachesByEnvironment?e.environment:void 0},this.cacheHeaders);if(this.bustOldestCachePercentage!==void 0){let s=Object.entries(i).map(([u,d])=>({key:u,time:d.value.cache?.updatedAt?.getTime()??0}));s.sort((u,d)=>u.time-d.time);let c=s.length,l=Math.max(1,Math.floor(c*this.bustOldestCachePercentage/100));s.slice(0,l).forEach(({key:u})=>{delete i[u]}),e.logger.info({nCachesToBust:l,bustOldestCachePercentage:this.bustOldestCachePercentage,totalCaches:c},"Busted oldest caches")}for(let s of[r,n,o])s&&mc({steps:s,stepCacheEntries:i,logger:e.logger});if(!this.writeCaches){e.logger.debug("Skipping cache last used at update because branch is protected");return}let{cachesToSave:a}=await Ft({stepLists:e.stepLists,cacheCreationParams:{environment:e.environment,testId:e.testId,orgId:this.orgId}});this.saveStepCacheEntries({entries:a,logger:e.logger})}};import Wh from"path";function gJ(t){let e=new kD,r=Wh.join(t,"metadata.json"),n=Wl.parse(JSON.parse(Lb.readFileSync(r,"utf-8")));e.addLocalFile(r);for(let o of Lb.readdirSync(Wh.join(t,"runs"))){if(!o.endsWith(".zip"))continue;let i=o.replace(/\.zip$/,""),a=new kD(Wh.join(t,"runs",o));for(let s of a.getEntries())s.isDirectory||e.addFile(Wh.join("runs",i,s.entryName),s.getData())}return{runGroupId:n.id,buffer:e.toBuffer()}}async function $h(t){let{client:e,consoleLogger:r,resultsPath:n}=t;if(!Lb.existsSync(n)){r.warn("Results path does not exist, skipping upload.");return}let o=new Vh(e);try{let{runGroupId:i,buffer:a}=gJ(n),s=await o.uploadResultsArchive(i,a),c=`${e.getAppUrl()}/run-groups/${s}`;r.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",r.error(`Failed to upload test results: ${a}.`);return}}import SJ from"adm-zip";import Dr from"fs";import eo from"path";var Xd=class t{constructor(e){this.filePath=e;Dr.rmSync(this.filePath,{recursive:!0,force:!0}),Dr.mkdirSync(this.filePath,{recursive:!0})}children=[];streams=[];close(){for(let e of this.children)e.close();for(let e of this.streams)e.end()}cd(e){let r=new t(eo.join(this.filePath,e));return this.children.push(r),r}cwd(){return this.filePath}mkdir(e){Dr.mkdirSync(eo.join(this.filePath,e),{recursive:!0})}readFile(e){let r=eo.join(this.filePath,e);if(Dr.existsSync(r))return Dr.readFileSync(r)}storeFile(e){let{name:r,contents:n}=e,o=eo.join(this.filePath,r);try{Dr.writeFileSync(o,n)}catch{}}createFileStream(e){let r=eo.join(this.filePath,e),n=Dr.createWriteStream(r);return this.streams.push(n),n}createRunArchive(e){let r=new Nb(eo.join(this.filePath,"runs"),e);return this.children.push(r),r}},Nb=class{children=[];tempPath;finalPath;constructor(e,r){this.tempPath=eo.join(e,`temp-storage-${r}`),this.finalPath=eo.join(e,`${r}.zip`),Dr.rmSync(this.tempPath,{recursive:!0,force:!0}),Dr.rmSync(this.finalPath,{recursive:!0,force:!0}),Dr.mkdirSync(this.tempPath,{recursive:!0})}readFile(e){let r=eo.join(this.tempPath,e);if(Dr.existsSync(r))return Dr.readFileSync(r)}mkdir(e){Dr.mkdirSync(eo.join(this.tempPath,e),{recursive:!0})}cd(e){let r=new Xd(eo.join(this.tempPath,e));return this.children.push(r),r}cwd(){return this.tempPath}storeFile(e){let{name:r,contents:n}=e,o=eo.join(this.tempPath,r);Dr.writeFileSync(o,n)}close(){for(let n of this.children)n.close();let e=new SJ;e.addLocalFolder(this.tempPath,void 0,n=>n!==".DS_Store");let r=e.toBuffer();Dr.writeFileSync(this.finalPath,r),Dr.rmSync(this.tempPath,{recursive:!0,force:!0})}};import yJ from"adm-zip";import{randomUUID as EJ}from"crypto";import rr from"fs";import Ar from"path";function zD(t){try{return rr.existsSync(t)?JSON.parse(rr.readFileSync(t,"utf-8")):void 0}catch{return}}function FD(t){return rr.existsSync(t)?rr.readFileSync(t,"utf-8").split(`
|
|
89
89
|
`).map(r=>r.trim()).filter(r=>r.length>0):[]}function TJ(t,e){let r=t.attemptIdToAttemptNumber.get(e);if(r)return Ar.join(t.inflatedPath,"attempts",r);let n=Ar.join(t.inflatedPath,"attempts");if(!rr.existsSync(n))return;let o=rr.readdirSync(n,{withFileTypes:!0}).filter(i=>i.isDirectory()).map(i=>i.name);for(let i of o){let a=Ar.join(n,i,"metadata.json"),s=zD(a);if(typeof s!="object"||s===null)continue;let c=s.id;if(typeof c=="string"&&c===e)return t.attemptIdToAttemptNumber.set(e,i),Ar.join(n,i)}}function UD(t,e,r){let n=Ar.join(t,"attempts");if(!rr.existsSync(n))return;let o=rr.readdirSync(n,{withFileTypes:!0}).filter(i=>i.isDirectory()).map(i=>i.name);for(let i of o){let a=Ar.join(n,i,"assets",`${e}.${r}`);if(rr.existsSync(a))return a}}var qh=class{constructor(e,r,n){this.outputDir=e;this.runId=r;this.runAttemptId=n;this.runsDir=Ar.join(e,"runs"),this.zipPath=Ar.join(this.runsDir,`${r}.zip`)}inflatedByRunId=new Map;zipPath;runsDir;ensureInflatedRun(e){let r=this.inflatedByRunId.get(e);if(r)return r;if(e!==this.runId||!rr.existsSync(this.zipPath))return;let n=Ar.join(this.runsDir,`temp-unzipped-${e}-${EJ()}`);rr.mkdirSync(n,{recursive:!0}),new yJ(this.zipPath).extractAllTo(n,!0);let i={runId:e,zipPath:this.zipPath,inflatedPath:n,attemptIdToAttemptNumber:new Map};return this.inflatedByRunId.set(e,i),i}close(){for(let e of this.inflatedByRunId.values())rr.rmSync(e.inflatedPath,{recursive:!0,force:!0});this.inflatedByRunId.clear()}getAttemptDir(){let e=this.ensureInflatedRun(this.runId);if(e)return TJ(e,this.runAttemptId)}listVideoAssetPaths(){let e=this.getAttemptDir();if(!e)return[];let r=Ar.join(e,"assets");return rr.existsSync(r)?rr.readdirSync(r,{withFileTypes:!0}).filter(o=>o.isFile()).map(o=>Ar.join(r,o.name)).filter(o=>{let i=Ar.extname(o).toLowerCase();return i===".webm"||i===".mp4"}):[]}readAttemptAssetText(e,r){let n=this.getAttemptDir();if(!n)return;let o=Ar.join(n,"assets",`${e}.${r}`);if(rr.existsSync(o))try{return rr.readFileSync(o,"utf-8")}catch{return}}async getConsoleLogsForRunAttempt(e,r,n){if(r!==this.runId||n!==this.runAttemptId)return;let o=this.getAttemptDir();if(!o)return;let i=zD(Ar.join(o,"console.json")),a=oE.safeParse(i);return a.success?a.data:void 0}async getNetworkLogsForRunAttempt(e,r,n){if(r!==this.runId||n!==this.runAttemptId)return;let o=this.getAttemptDir();if(!o)return;let i=Ar.join(o,"assets","har-pages.log"),a=Ar.join(o,"assets","har-entries.log"),s={};for(let u of FD(i)){let d=td.safeParse(BD(u));d.success&&(s[d.data.id]=d.data)}let c={},l=FD(a);for(let u=0;u<l.length;u++){let d=l[u],p=rd.safeParse(BD(d));if(!p.success)continue;let m=`${p.data.startedDateTime}-${u}`;c[m]=p.data}if(Object.keys(c).length!==0)return aE(s,c)}async getHtmlSnapshot(e,r){let n=this.readAttemptAssetText(r,"html");if(n)return n;let o=this.ensureInflatedRun(this.runId);if(!o)return;let i=UD(o.inflatedPath,r,"html");if(i)try{return rr.readFileSync(i,"utf-8")}catch{return}}async getA11yTreeSnapshot(e,r){let n=this.readAttemptAssetText(r,"xml");if(n)return n;let o=this.ensureInflatedRun(this.runId);if(!o)return;let i=UD(o.inflatedPath,r,"xml");if(i)try{return rr.readFileSync(i,"utf-8")}catch{return}}async getScreenshot(e,r){if(!this.ensureInflatedRun(this.runId))return;let o=this.getAttemptDir(),i=o?Ar.join(o,"assets",`${r}.jpeg`):void 0;if(i)try{return rr.readFileSync(i)}catch{return}}};function BD(t){try{return JSON.parse(t)}catch{return}}function Kh({test:t,envNameOverride:e,urlOverride:r,resolveEnv:n}){let o=e??bJ(t),i,a={};if(o){try{i=n(o)}catch(c){throw new Error(`Failed to resolve environment ${o} for test ${t.name}: ${String(c)}`)}a=i.variables}let s=t.baseUrl;if(r)s=r;else if(!s){let c=a[ir];typeof c=="string"&&(s=c)}if(!s)throw new Error(`Cannot run test with no base URL and no ${ir} variable defined in its environment`);return{envName:o,resolvedEnv:i,environmentVariables:a,baseUrl:s}}function bJ(t){for(let e of t.envs??[])if(e.default)return e.name}var vJ={test:"tests",module:"modules",mobileTest:"mobileTests",mobileModule:"mobileModules"};async function Ls(t,e,r){let n=await fe(t),o=n[vJ[r]],i=AJ(o,e);if(e.id){if(i.length===0)throw new or(`No ${r} found with id '${e.id}' in project '${t.rootDir}'.`);return Yh(i,n)}if(e.name){if(i.length===0)throw new or(`No ${r} found with exact name '${e.name}' in project '${t.rootDir}'.`);if(i.length>1){let a=i.map(s=>({id:s.id,path:s.relativePath}));throw new or([`Multiple ${r}s found with exact name '${e.name}'. Please disambiguate by id or path.`,JSON.stringify(a,null,2)].join(`
|
|
90
90
|
`))}return Yh(i,n)}if(e.path){let a=e.path;if(i.length===0)throw new or(`No ${r} found at path '${a}'. Provide an absolute path or a path relative to '${t.rootDir}'.`);if(i.length>1){let s=i.filter(l=>l.fullFilePath===a||l.relativePath===a||l.fullFilePath.endsWith(`/${a}`)||l.relativePath.endsWith(`/${a}`));if(s.length===1)return Yh(s,n);let c=i.map(l=>({id:l.id,path:l.fullFilePath}));throw new or([`Multiple ${r}s matched the provided path '${a}'. Please pass the absolute path.`,JSON.stringify(c,null,2)].join(`
|
|
91
|
-
`))}return Yh(i,n)}throw new Error("No valid selector field provided. Exactly one of id, name, or path must be specified.")}function Yh(t,e){let r=t[0];if(!r)throw t.length>0?new Error("No entity found: matches array is not empty. Unknown error."):new Error("No entity found.");return{entity:r,momenticFiles:e}}function AJ(t,e){if(e.id){let r=Object.values(t).find(n=>n.id===e.id);return r?[r]:[]}if(e.name)return Object.values(t).filter(r=>r.name===e.name);if(e.path){let r=e.path;return Object.values(t).filter(n=>n.fullFilePath.includes(r)||n.relativePath.includes(r))}throw new Error("No valid selector field provided: expected exactly one of 'id', 'name', or 'path'.")}import Xh from"fs";import CJ from"path";var RJ=new mh(30,60*1e3),Qh="https://api.momentic.ai",kb,HD,Zh=t=>{Qh=t},qt=()=>Qh,GD=()=>jl(Qh),eg=t=>{HD=t},Ns=()=>HD,Ic=()=>kb;var _c,Fb,Jh,tg=async t=>{if(kb&&_c&&Jh)return _c;let e=new pt({baseUrl:Qh,apiKey:t,logger:v});kb=e;try{let r=await e.getAuthInfo();return _c=r.orgId,Fb=r.userId,Jh=t,_c}catch(r){throw new Error(`Error checking API key against server: ${r}`,{cause:r})}},Kt=()=>{if(!_c)throw new Error("Your organization ID is invalid.");return _c},Jo=()=>{if(!Fb)throw new Error("Your user ID is invalid.");return Fb},Cr=()=>{if(!Jh)throw new Error("Your API key is invalid.");return Jh},Ub,Db,Pc=(t,e)=>{Ub=t,Db?.abort(),Db=new AbortController;let r=Db.signal,n=[t.configFilePath];t.config.environments?.forEach(o=>{if(!o.envFile)return;let i=CJ.resolve(t.rootDir,o.envFile);try{if(Xh.lstatSync(i).isSymbolicLink())return;Xh.existsSync(i)&&n.push(i)}catch(a){v.warn({err:a},`Failed to check if env file ${i} exists`)}});try{wJ({filesToWatch:n,revalidator:e,signal:r,project:t})}catch(o){v.error({err:o},"Failed to start config file watchers")}},Re=()=>Ub;function wJ({filesToWatch:t,revalidator:e,signal:r,project:n}){v.debug("Starting watch on the following files:"),t.forEach(o=>{v.debug(`- ${o}`)}),t.forEach(o=>{let i=async(s,c)=>{s.mtime.getTime()!==c.mtime.getTime()&&(RJ.increment("setLocalProject")&&v.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.`),Ub=await Promise.resolve(e(n.configFilePath)))};Xh.watchFile(o,{persistent:!1},i);let a=()=>{Xh.unwatchFile(o,i),r.removeEventListener("abort",a)};r.addEventListener("abort",a),process.once("SIGUSR2",()=>{a(),process.kill(process.pid,"SIGUSR2")})})}function je(t){return function(...e){let r=e[e.length-1],n=t(...e);Promise.resolve(n).catch(r)}}import{hostname as xJ}from"os";var _J="2.71.1",Ds=ql({app:"desktop-server",hostname:xJ(),disableConsoleLogs:!0,captureExceptions:!0}).child({cliVersion:_J});(async()=>{try{let t=await _i(Ds);t.gitBranchName&&Ds.addBinding("branch",t.gitBranchName)}catch{}})();var jD=IJ();jD.get("/",async(t,e)=>{let r=Re(),n=Ic();if(!n){e.status(500).json({message:"API client not initialized"});return}let o=await Er(Ds,n,r),i=o?.gitProtectedBranches&&o?.gitBranchName&&o.gitProtectedBranches.includes(o.gitBranchName),{noCache:a,alwaysSaveCache:s}=Ns(),c=!a&&(s||!i);e.status(200).json({saveCaches:c,checkedOutBranch:o?.gitBranchName})});var Bb=jD;import{Router as PJ}from"express";import kr from"fs";import{glob as MJ}from"glob";import ur from"path";var OJ=5e3;function zb(t={}){let e=PJ();function r(i){let a=Re(),s=ur.dirname(a.configFilePath);return ur.join(s,...i)}function n(i){let a=Re(),s=ur.dirname(a.configFilePath),c=ur.relative(s,i);return c?c.split(ur.sep):[]}function o(i,a){let s=kr.statSync(i),c=n(i);return cE.parse({name:a,absolutePath:i,relativePath:c.join(ur.sep),pathSegments:c,isDirectory:s.isDirectory(),size:s.size,createdAt:s.birthtime,modifiedAt:s.mtime,accessedAt:s.atime})}return e.post("/",je(async(i,a,s)=>{let c;try{c=l_.parse(i.body).pathSegments}catch(g){a.status(400).json({error:`Failed to parse folder read body: ${g}`});return}let l=r(c);if(!kr.existsSync(l)){a.status(404).json({error:`Path not found: ${c.join(ur.sep)}`});return}if(!kr.statSync(l).isDirectory()){a.status(400).json({error:`Path is not a directory: ${c.join(ur.sep)}`});return}let d=Re(),p=Array.from(d.config.exclude??[]).concat(Um),m=AbortSignal.timeout(OJ),f;try{f=await MJ("*",{absolute:!1,cwd:l,ignore:p,dotRelative:!1,maxDepth:1,nodir:!1,signal:m})}catch(g){if(g instanceof Error&&g.name==="TimeoutError"){a.status(408).json({error:"Folder listing timed out. This directory may contain too many files."});return}throw g}let h=f.map(g=>{let E=ur.join(l,g);return o(E,g)});if(t.allowedFileTypes){let g=new Set(t.allowedFileTypes);h=(await Promise.all(h.map(async E=>{if(E.isDirectory||!(E.name.endsWith(".test.yaml")||E.name.endsWith(".module.yaml")))return E;let b=await LJ(E.absolutePath);return b!==void 0&&g.has(b)?E:null}))).filter(E=>E!==null)}let S={absolutePath:l,pathSegments:c,contents:h};a.status(200).json(S)})),e.put("/",je(async(i,a,s)=>{let c;try{c=c_.parse(i.body).pathSegments}catch(d){a.status(400).json({error:`Failed to parse folder create body: ${d}`});return}let l=r(c);if(kr.existsSync(l)){a.status(200).json({success:!0,message:`Folder already exists: ${c.join(ur.sep)}`,pathSegments:c});return}kr.mkdirSync(l,{recursive:!0});let u={success:!0,message:`Folder created: ${c.join(ur.sep)}`,pathSegments:c};a.status(201).json(u)})),e.patch("/",je(async(i,a,s)=>{let c,l;try{let f=u_.parse(i.body);c=f.pathSegments,l=f.newPathSegments}catch(f){a.status(400).json({error:`Failed to parse folder update body: ${f}`});return}let u=r(c),d=r(l);if(!kr.existsSync(u)){a.status(400).json({error:`Folder not found: ${c.join(ur.sep)}`});return}if(kr.existsSync(d)){a.status(400).json({error:`Destination already exists: ${l.join(ur.sep)}`});return}let p=ur.dirname(d);kr.existsSync(p)||kr.mkdirSync(p,{recursive:!0}),kr.renameSync(u,d);let m={success:!0,message:`Folder moved from ${c.join(ur.sep)} to ${l.join(ur.sep)}`,pathSegments:l};a.status(200).json(m)})),e.delete("/",je(async(i,a,s)=>{let c,l=!0;try{let m=d_.parse(i.body);c=m.pathSegments,l=m.recursive??!0}catch(m){a.status(400).json({error:`Failed to parse folder delete body: ${m}`});return}let u=r(c);if(!kr.existsSync(u)){a.status(200).json({success:!0,message:`Folder not found: ${c.join(ur.sep)}`,pathSegments:c});return}if(!kr.statSync(u).isDirectory()){a.status(400).json({error:`Path is not a directory: ${c.join(ur.sep)}`});return}if(l)kr.rmSync(u,{recursive:!0,force:!0});else{if(kr.readdirSync(u).length>0){a.status(409).json({error:`Cannot delete non-empty directory without recursive flag: ${c.join("/")}`});return}kr.rmdirSync(u)}let p={success:!0,message:`Folder deleted: ${c.join("/")}`,pathSegments:c};a.status(200).json(p)})),e}async function LJ(t){try{let e=await kr.promises.open(t,"r");try{let r=Buffer.alloc(4096),{bytesRead:n}=await e.read(r,0,r.length,0);return r.toString("utf-8",0,n).match(/^fileType:\s*(.+)$/m)?.[1]?.trim()}finally{await e.close()}}catch{}}import{Router as NJ}from"express";var VD=NJ();VD.get("/",async(t,e)=>{let r=Re(),n=Ic();if(!n){e.status(500).json({message:"API client not initialized"});return}let o=await Er(Ds,n,r);e.status(200).json(o)});var Hb=VD;import gee from"events";import HB,{Router as See}from"express";import yee from"http";import Eee from"path";import{Server as Z9}from"socket.io";var DJ=({metadata:t,logger:e,globalE2eStateManager:r})=>{let{sessionId:n}=t;return async()=>{e.info({sessionId:n},"Cancel event received");let o=r.getSession(n);if(!o)throw new Error("No active session found");try{o.controller.setClosed()}catch{}}},WD={event:"cancel",createHandler:DJ};var kJ=({metadata:t,logger:e,globalE2eStateManager:r})=>{let{sessionId:n}=t;return async(o,i)=>{let a=r.getSession(n);if(!a)throw new Error("No active session found");a.controller.setOpen();let s=a.controller.browser;try{let l=(await s.getBrowserState({skipWait:!0})).serialize();e.debug({a11yTree:l},"Fetched a11y tree from the browser"),i({a11yTree:l})}catch(c){e.error({err:c},"Error fetching a11y tree from the browser"),i({err:c.message})}}},$D={event:"fetchA11yTree",createHandler:kJ};var FJ=({metadata:t,logger:e,globalE2eStateManager:r})=>{let{sessionId:n}=t;return async(o,i)=>{let a=r.getSession(n);if(!a)throw new Error("No active session found");a.controller.setOpen();let s=a.controller.browser;try{let c=await s.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})}}},qD={event:"fetchDom",createHandler:FJ};var UJ=({metadata:t,logger:e,globalE2eStateManager:r})=>{let{sessionId:n}=t;return o=>{e.info({sessionId:n,reason:o},`Disconnect event received (${o})`),r.removeSession(n,e)}},KD={event:"disconnect",createHandler:UJ};function to(t){let{result:e,nestedResults:r}=t;if(!t.nestedResults.length)return;let{firstMetadata:n,lastMetadata:o}=BJ(r);zJ(e,n,o);let i=[...t.asyncTasks];t.asyncTasks.push((async()=>{try{await HJ(i,e,n,o)}catch(a){t.logger.error({result:t.result,err:a},"Error hoisting scalar result metadata")}})())}function BJ(t){let e=t[0],r;for(;;){switch(e.type){case"PRESET_ACTION":{r=e;break}case"CONDITIONAL":r=t[0];break;case"AI_ACTION_DYNAMIC":case"AI_ACTION":case"MODULE":case"SECTION":if(!e.results.length){r=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(r)break}let n=t[t.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:r,lastMetadata:o}}function zJ(t,e,r){e&&(t.beforeUrl=e.beforeUrl),r&&(t.afterUrl=r.afterUrl,t.data=r.data,r.status!=="SUCCESS"&&(t.message=r.message))}async function HJ(t,e,r,n){await Promise.allSettled(t),r&&(e.beforeSnapshot=r.beforeSnapshot),n&&(e.afterSnapshot=n.afterSnapshot)}import{randomUUID as QJ}from"crypto";import{faker as GJ}from"@faker-js/faker";import jJ from"assert";import VJ from"axios";import*as WJ from"child_process";import $J from"moment";import*as qJ from"otpauth";import KJ from"pg";async function YD(t){let e;try{e=new URL(t.url).hostname}catch{}let r=[];return t.headers.getSetCookie()?.forEach(n=>{let o=Rm(n,e);r.push(...o)}),r}function YJ(t,e){if(!t&&!e)return;let r;if(t){let{url:o,options:i}=t;r=new Request(o,i)}let n;if(e){let{body:o,options:i}=e;n=new Response(o??null,i)}return{request:r,response:n}}async function XJ(t,e){switch(t){case"RAW":return e;case"RESPONSE":if(e instanceof Response){let r=[];return e.headers.forEach((o,i)=>{r.push([i,o])}),{status:e.status,headers:r,body:await e.text()}}else throw new Error("Result is not a Response object")}}var JJ=Object.getPrototypeOf(async function(){}).constructor;async function XD(t,e,r){let n=e.code;e.options.fragment&&(n=`return ${e.code}`);let{env:o,additionalBindings:i,request:a,response:s}=e.bindings,c=e.tools,l={},u=(y,b)=>{o[y]=b,l[y]=b},d={},p=(y,b)=>{o[y]=b,d[y]=b},m;n.includes("Octokit")&&(m=(await import("@octokit/rest")).Octokit);let f;n.includes("createAppAuth")&&(f=(await import("@octokit/auth-app")).createAppAuth);let h=async()=>await Promise.resolve(new JJ("axios","moment","faker","assert","pg","Octokit","createAppAuth","OTPAuth","child_process","extractCookiesFromResponse","env","setVariable","setPersistentVariable","sendSms","waitForLatestSms","email","sms","ai","mock",...Object.keys(i??{}),n)(VJ,$J,c.fakerInstance??GJ,jJ,KJ,m,f,qJ,WJ,YD,o,e.options.disallowVariableUpdates?void 0:u,e.options.disallowVariableUpdates?void 0:p,b=>c.sms.send(b),b=>c.sms.fetchLatest(b),c.email,c.sms,c.ai,YJ(a,s),...Object.values(i??{}))),S=!0,g,E;try{let y=await J(h(),{milliseconds:e.options.timeoutMs,message:`Timeout of ${e.options.timeoutMs}ms exceeded for code execution`,signal:e.signal});g=await XJ(e.options.responseSerialization??"RAW",y)}catch(y){r.error({err:y,env:o,evalCode:n},`[${t}] Error executing code: ${y}`),S=!1,y instanceof ra?E=`Timeout of ${e.options.timeoutMs}ms exceeded for code execution`:E=y instanceof Error?y.message:`${y}`}return{result:g,variableUpdates:l,persistentVariableUpdates:d,success:S,error:E}}async function JD({code:t,fragment:e,context:r,localTools:n,logger:o,signal:i,timeoutMs:a=Ji,disallowVariableUpdates:s,additionalBindings:c,responseSerialization:l,mock:u}){let d=QJ(),p=await XD(d,{code:t,options:{fragment:e,timeoutMs:a,disallowVariableUpdates:s,responseSerialization:l},bindings:{...r.toObjectCopy(),...u,additionalBindings:c},tools:n,signal:i},o);return v.debug(`[${d}] Got execution result: ${JSON.stringify(p)}`),p}import{createHmac as ZJ,randomUUID as e6}from"crypto";import t6 from"fetch-retry";var r6=t6(global.fetch,{retries:3,retryOn:function(t,e,r){return!!(e!==null||r&&r.status>=500)},retryDelay:function(t){return Math.pow(2,t)*500}}),QD=process.env.GCP_JS_EVAL_FUNCTION_ENDPOINT,ZD=process.env.MOMENTIC_LAMBDA_AUTH_SECRET;async function ek({orgId:t,code:e,fragment:r,context:n,timeoutMs:o=Ji,retries:i=2,signal:a,logger:s,additionalBindings:c,disallowVariableUpdates:l,responseSerialization:u,mock:d}){if(!QD)throw new Error("GCP_JS_EVAL_FUNCTION_ENDPOINT environment variable not set");let p,m,f=0;if(!ZD)throw new Error("Missing lambda auth secret.");let h=ZJ("sha256",ZD).update(t).digest("hex");for(;f<=i;){f++,a?.throwIfAborted();let g={id:e6(),orgId:t,momenticLambdaAuthHash:h,code:e,fragment:r,state:{...n.toObjectCopy(),...d,additionalBindings:c},timeoutMs:o,disallowVariableUpdates:l,responseSerialization:u};try{if(p=await J(r6(QD,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(g)}),{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(E){m=E}}if(m)throw s.error({err:m},"Failed to evaluate code remotely"),m;if(!p)throw new Error(`An unexpected code evaluation error occurred${m?`: ${m}`:""}`);let S;try{S=jx.parse(await p.json())}catch(g){throw new Error(`Code evaluation server returned invalid response: ${g}`)}if(S.error)throw new Error(`Code evaluation error: ${S.error}`);return S}async function Sa(t){let e;if(process.env.GCP_JS_EVAL_FUNCTION_ENDPOINT)e=await ek(t);else if(t.localTools)e=await JD({...t,localTools:t.localTools});else throw new Error("No code evaluation environment available");if(e.error){let r=`Failed to evaluate code:
|
|
91
|
+
`))}return Yh(i,n)}throw new Error("No valid selector field provided. Exactly one of id, name, or path must be specified.")}function Yh(t,e){let r=t[0];if(!r)throw t.length>0?new Error("No entity found: matches array is not empty. Unknown error."):new Error("No entity found.");return{entity:r,momenticFiles:e}}function AJ(t,e){if(e.id){let r=Object.values(t).find(n=>n.id===e.id);return r?[r]:[]}if(e.name)return Object.values(t).filter(r=>r.name===e.name);if(e.path){let r=e.path;return Object.values(t).filter(n=>n.fullFilePath.includes(r)||n.relativePath.includes(r))}throw new Error("No valid selector field provided: expected exactly one of 'id', 'name', or 'path'.")}import Xh from"fs";import CJ from"path";var RJ=new mh(30,60*1e3),Qh="https://api.momentic.ai",kb,HD,Zh=t=>{Qh=t},qt=()=>Qh,GD=()=>jl(Qh),eg=t=>{HD=t},Ns=()=>HD,Ic=()=>kb;var _c,Fb,Jh,tg=async t=>{if(kb&&_c&&Jh)return _c;let e=new pt({baseUrl:Qh,apiKey:t,logger:v});kb=e;try{let r=await e.getAuthInfo();return _c=r.orgId,Fb=r.userId,Jh=t,_c}catch(r){throw new Error(`Error checking API key against server: ${r}`,{cause:r})}},Kt=()=>{if(!_c)throw new Error("Your organization ID is invalid.");return _c},Jo=()=>{if(!Fb)throw new Error("Your user ID is invalid.");return Fb},Cr=()=>{if(!Jh)throw new Error("Your API key is invalid.");return Jh},Ub,Db,Pc=(t,e)=>{Ub=t,Db?.abort(),Db=new AbortController;let r=Db.signal,n=[t.configFilePath];t.config.environments?.forEach(o=>{if(!o.envFile)return;let i=CJ.resolve(t.rootDir,o.envFile);try{if(Xh.lstatSync(i).isSymbolicLink())return;Xh.existsSync(i)&&n.push(i)}catch(a){v.warn({err:a},`Failed to check if env file ${i} exists`)}});try{wJ({filesToWatch:n,revalidator:e,signal:r,project:t})}catch(o){v.error({err:o},"Failed to start config file watchers")}},Re=()=>Ub;function wJ({filesToWatch:t,revalidator:e,signal:r,project:n}){v.debug("Starting watch on the following files:"),t.forEach(o=>{v.debug(`- ${o}`)}),t.forEach(o=>{let i=async(s,c)=>{s.mtime.getTime()!==c.mtime.getTime()&&(RJ.increment("setLocalProject")&&v.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.`),Ub=await Promise.resolve(e(n.configFilePath)))};Xh.watchFile(o,{persistent:!1},i);let a=()=>{Xh.unwatchFile(o,i),r.removeEventListener("abort",a)};r.addEventListener("abort",a),process.once("SIGUSR2",()=>{a(),process.kill(process.pid,"SIGUSR2")})})}function je(t){return function(...e){let r=e[e.length-1],n=t(...e);Promise.resolve(n).catch(r)}}import{hostname as xJ}from"os";var _J="2.71.2",Ds=ql({app:"desktop-server",hostname:xJ(),disableConsoleLogs:!0,captureExceptions:!0}).child({cliVersion:_J});(async()=>{try{let t=await _i(Ds);t.gitBranchName&&Ds.addBinding("branch",t.gitBranchName)}catch{}})();var jD=IJ();jD.get("/",async(t,e)=>{let r=Re(),n=Ic();if(!n){e.status(500).json({message:"API client not initialized"});return}let o=await Er(Ds,n,r),i=o?.gitProtectedBranches&&o?.gitBranchName&&o.gitProtectedBranches.includes(o.gitBranchName),{noCache:a,alwaysSaveCache:s}=Ns(),c=!a&&(s||!i);e.status(200).json({saveCaches:c,checkedOutBranch:o?.gitBranchName})});var Bb=jD;import{Router as PJ}from"express";import kr from"fs";import{glob as MJ}from"glob";import ur from"path";var OJ=5e3;function zb(t={}){let e=PJ();function r(i){let a=Re(),s=ur.dirname(a.configFilePath);return ur.join(s,...i)}function n(i){let a=Re(),s=ur.dirname(a.configFilePath),c=ur.relative(s,i);return c?c.split(ur.sep):[]}function o(i,a){let s=kr.statSync(i),c=n(i);return cE.parse({name:a,absolutePath:i,relativePath:c.join(ur.sep),pathSegments:c,isDirectory:s.isDirectory(),size:s.size,createdAt:s.birthtime,modifiedAt:s.mtime,accessedAt:s.atime})}return e.post("/",je(async(i,a,s)=>{let c;try{c=l_.parse(i.body).pathSegments}catch(g){a.status(400).json({error:`Failed to parse folder read body: ${g}`});return}let l=r(c);if(!kr.existsSync(l)){a.status(404).json({error:`Path not found: ${c.join(ur.sep)}`});return}if(!kr.statSync(l).isDirectory()){a.status(400).json({error:`Path is not a directory: ${c.join(ur.sep)}`});return}let d=Re(),p=Array.from(d.config.exclude??[]).concat(Um),m=AbortSignal.timeout(OJ),f;try{f=await MJ("*",{absolute:!1,cwd:l,ignore:p,dotRelative:!1,maxDepth:1,nodir:!1,signal:m})}catch(g){if(g instanceof Error&&g.name==="TimeoutError"){a.status(408).json({error:"Folder listing timed out. This directory may contain too many files."});return}throw g}let h=f.map(g=>{let E=ur.join(l,g);return o(E,g)});if(t.allowedFileTypes){let g=new Set(t.allowedFileTypes);h=(await Promise.all(h.map(async E=>{if(E.isDirectory||!(E.name.endsWith(".test.yaml")||E.name.endsWith(".module.yaml")))return E;let b=await LJ(E.absolutePath);return b!==void 0&&g.has(b)?E:null}))).filter(E=>E!==null)}let S={absolutePath:l,pathSegments:c,contents:h};a.status(200).json(S)})),e.put("/",je(async(i,a,s)=>{let c;try{c=c_.parse(i.body).pathSegments}catch(d){a.status(400).json({error:`Failed to parse folder create body: ${d}`});return}let l=r(c);if(kr.existsSync(l)){a.status(200).json({success:!0,message:`Folder already exists: ${c.join(ur.sep)}`,pathSegments:c});return}kr.mkdirSync(l,{recursive:!0});let u={success:!0,message:`Folder created: ${c.join(ur.sep)}`,pathSegments:c};a.status(201).json(u)})),e.patch("/",je(async(i,a,s)=>{let c,l;try{let f=u_.parse(i.body);c=f.pathSegments,l=f.newPathSegments}catch(f){a.status(400).json({error:`Failed to parse folder update body: ${f}`});return}let u=r(c),d=r(l);if(!kr.existsSync(u)){a.status(400).json({error:`Folder not found: ${c.join(ur.sep)}`});return}if(kr.existsSync(d)){a.status(400).json({error:`Destination already exists: ${l.join(ur.sep)}`});return}let p=ur.dirname(d);kr.existsSync(p)||kr.mkdirSync(p,{recursive:!0}),kr.renameSync(u,d);let m={success:!0,message:`Folder moved from ${c.join(ur.sep)} to ${l.join(ur.sep)}`,pathSegments:l};a.status(200).json(m)})),e.delete("/",je(async(i,a,s)=>{let c,l=!0;try{let m=d_.parse(i.body);c=m.pathSegments,l=m.recursive??!0}catch(m){a.status(400).json({error:`Failed to parse folder delete body: ${m}`});return}let u=r(c);if(!kr.existsSync(u)){a.status(200).json({success:!0,message:`Folder not found: ${c.join(ur.sep)}`,pathSegments:c});return}if(!kr.statSync(u).isDirectory()){a.status(400).json({error:`Path is not a directory: ${c.join(ur.sep)}`});return}if(l)kr.rmSync(u,{recursive:!0,force:!0});else{if(kr.readdirSync(u).length>0){a.status(409).json({error:`Cannot delete non-empty directory without recursive flag: ${c.join("/")}`});return}kr.rmdirSync(u)}let p={success:!0,message:`Folder deleted: ${c.join("/")}`,pathSegments:c};a.status(200).json(p)})),e}async function LJ(t){try{let e=await kr.promises.open(t,"r");try{let r=Buffer.alloc(4096),{bytesRead:n}=await e.read(r,0,r.length,0);return r.toString("utf-8",0,n).match(/^fileType:\s*(.+)$/m)?.[1]?.trim()}finally{await e.close()}}catch{}}import{Router as NJ}from"express";var VD=NJ();VD.get("/",async(t,e)=>{let r=Re(),n=Ic();if(!n){e.status(500).json({message:"API client not initialized"});return}let o=await Er(Ds,n,r);e.status(200).json(o)});var Hb=VD;import gee from"events";import HB,{Router as See}from"express";import yee from"http";import Eee from"path";import{Server as Z9}from"socket.io";var DJ=({metadata:t,logger:e,globalE2eStateManager:r})=>{let{sessionId:n}=t;return async()=>{e.info({sessionId:n},"Cancel event received");let o=r.getSession(n);if(!o)throw new Error("No active session found");try{o.controller.setClosed()}catch{}}},WD={event:"cancel",createHandler:DJ};var kJ=({metadata:t,logger:e,globalE2eStateManager:r})=>{let{sessionId:n}=t;return async(o,i)=>{let a=r.getSession(n);if(!a)throw new Error("No active session found");a.controller.setOpen();let s=a.controller.browser;try{let l=(await s.getBrowserState({skipWait:!0})).serialize();e.debug({a11yTree:l},"Fetched a11y tree from the browser"),i({a11yTree:l})}catch(c){e.error({err:c},"Error fetching a11y tree from the browser"),i({err:c.message})}}},$D={event:"fetchA11yTree",createHandler:kJ};var FJ=({metadata:t,logger:e,globalE2eStateManager:r})=>{let{sessionId:n}=t;return async(o,i)=>{let a=r.getSession(n);if(!a)throw new Error("No active session found");a.controller.setOpen();let s=a.controller.browser;try{let c=await s.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})}}},qD={event:"fetchDom",createHandler:FJ};var UJ=({metadata:t,logger:e,globalE2eStateManager:r})=>{let{sessionId:n}=t;return o=>{e.info({sessionId:n,reason:o},`Disconnect event received (${o})`),r.removeSession(n,e)}},KD={event:"disconnect",createHandler:UJ};function to(t){let{result:e,nestedResults:r}=t;if(!t.nestedResults.length)return;let{firstMetadata:n,lastMetadata:o}=BJ(r);zJ(e,n,o);let i=[...t.asyncTasks];t.asyncTasks.push((async()=>{try{await HJ(i,e,n,o)}catch(a){t.logger.error({result:t.result,err:a},"Error hoisting scalar result metadata")}})())}function BJ(t){let e=t[0],r;for(;;){switch(e.type){case"PRESET_ACTION":{r=e;break}case"CONDITIONAL":r=t[0];break;case"AI_ACTION_DYNAMIC":case"AI_ACTION":case"MODULE":case"SECTION":if(!e.results.length){r=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(r)break}let n=t[t.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:r,lastMetadata:o}}function zJ(t,e,r){e&&(t.beforeUrl=e.beforeUrl),r&&(t.afterUrl=r.afterUrl,t.data=r.data,r.status!=="SUCCESS"&&(t.message=r.message))}async function HJ(t,e,r,n){await Promise.allSettled(t),r&&(e.beforeSnapshot=r.beforeSnapshot),n&&(e.afterSnapshot=n.afterSnapshot)}import{randomUUID as QJ}from"crypto";import{faker as GJ}from"@faker-js/faker";import jJ from"assert";import VJ from"axios";import*as WJ from"child_process";import $J from"moment";import*as qJ from"otpauth";import KJ from"pg";async function YD(t){let e;try{e=new URL(t.url).hostname}catch{}let r=[];return t.headers.getSetCookie()?.forEach(n=>{let o=Rm(n,e);r.push(...o)}),r}function YJ(t,e){if(!t&&!e)return;let r;if(t){let{url:o,options:i}=t;r=new Request(o,i)}let n;if(e){let{body:o,options:i}=e;n=new Response(o??null,i)}return{request:r,response:n}}async function XJ(t,e){switch(t){case"RAW":return e;case"RESPONSE":if(e instanceof Response){let r=[];return e.headers.forEach((o,i)=>{r.push([i,o])}),{status:e.status,headers:r,body:await e.text()}}else throw new Error("Result is not a Response object")}}var JJ=Object.getPrototypeOf(async function(){}).constructor;async function XD(t,e,r){let n=e.code;e.options.fragment&&(n=`return ${e.code}`);let{env:o,additionalBindings:i,request:a,response:s}=e.bindings,c=e.tools,l={},u=(y,b)=>{o[y]=b,l[y]=b},d={},p=(y,b)=>{o[y]=b,d[y]=b},m;n.includes("Octokit")&&(m=(await import("@octokit/rest")).Octokit);let f;n.includes("createAppAuth")&&(f=(await import("@octokit/auth-app")).createAppAuth);let h=async()=>await Promise.resolve(new JJ("axios","moment","faker","assert","pg","Octokit","createAppAuth","OTPAuth","child_process","extractCookiesFromResponse","env","setVariable","setPersistentVariable","sendSms","waitForLatestSms","email","sms","ai","mock",...Object.keys(i??{}),n)(VJ,$J,c.fakerInstance??GJ,jJ,KJ,m,f,qJ,WJ,YD,o,e.options.disallowVariableUpdates?void 0:u,e.options.disallowVariableUpdates?void 0:p,b=>c.sms.send(b),b=>c.sms.fetchLatest(b),c.email,c.sms,c.ai,YJ(a,s),...Object.values(i??{}))),S=!0,g,E;try{let y=await J(h(),{milliseconds:e.options.timeoutMs,message:`Timeout of ${e.options.timeoutMs}ms exceeded for code execution`,signal:e.signal});g=await XJ(e.options.responseSerialization??"RAW",y)}catch(y){r.error({err:y,env:o,evalCode:n},`[${t}] Error executing code: ${y}`),S=!1,y instanceof ra?E=`Timeout of ${e.options.timeoutMs}ms exceeded for code execution`:E=y instanceof Error?y.message:`${y}`}return{result:g,variableUpdates:l,persistentVariableUpdates:d,success:S,error:E}}async function JD({code:t,fragment:e,context:r,localTools:n,logger:o,signal:i,timeoutMs:a=Ji,disallowVariableUpdates:s,additionalBindings:c,responseSerialization:l,mock:u}){let d=QJ(),p=await XD(d,{code:t,options:{fragment:e,timeoutMs:a,disallowVariableUpdates:s,responseSerialization:l},bindings:{...r.toObjectCopy(),...u,additionalBindings:c},tools:n,signal:i},o);return v.debug(`[${d}] Got execution result: ${JSON.stringify(p)}`),p}import{createHmac as ZJ,randomUUID as e6}from"crypto";import t6 from"fetch-retry";var r6=t6(global.fetch,{retries:3,retryOn:function(t,e,r){return!!(e!==null||r&&r.status>=500)},retryDelay:function(t){return Math.pow(2,t)*500}}),QD=process.env.GCP_JS_EVAL_FUNCTION_ENDPOINT,ZD=process.env.MOMENTIC_LAMBDA_AUTH_SECRET;async function ek({orgId:t,code:e,fragment:r,context:n,timeoutMs:o=Ji,retries:i=2,signal:a,logger:s,additionalBindings:c,disallowVariableUpdates:l,responseSerialization:u,mock:d}){if(!QD)throw new Error("GCP_JS_EVAL_FUNCTION_ENDPOINT environment variable not set");let p,m,f=0;if(!ZD)throw new Error("Missing lambda auth secret.");let h=ZJ("sha256",ZD).update(t).digest("hex");for(;f<=i;){f++,a?.throwIfAborted();let g={id:e6(),orgId:t,momenticLambdaAuthHash:h,code:e,fragment:r,state:{...n.toObjectCopy(),...d,additionalBindings:c},timeoutMs:o,disallowVariableUpdates:l,responseSerialization:u};try{if(p=await J(r6(QD,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(g)}),{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(E){m=E}}if(m)throw s.error({err:m},"Failed to evaluate code remotely"),m;if(!p)throw new Error(`An unexpected code evaluation error occurred${m?`: ${m}`:""}`);let S;try{S=jx.parse(await p.json())}catch(g){throw new Error(`Code evaluation server returned invalid response: ${g}`)}if(S.error)throw new Error(`Code evaluation error: ${S.error}`);return S}async function Sa(t){let e;if(process.env.GCP_JS_EVAL_FUNCTION_ENDPOINT)e=await ek(t);else if(t.localTools)e=await JD({...t,localTools:t.localTools});else throw new Error("No code evaluation environment available");if(e.error){let r=`Failed to evaluate code:
|
|
92
92
|
${e.error}
|
|
93
93
|
Code received:
|
|
94
|
-
${t.code}`;throw t.logger.error({err:e.error,code:t.code,env:t.context.toObjectCopy()},r),new Error(r)}if(e.variableUpdates)for(let[r,n]of Object.entries(e.variableUpdates))t.context.setVariable(r,n);if(e.persistentVariableUpdates&&Object.keys(e.persistentVariableUpdates).length>0){await t.callbacks?.onPersistentVariableUpdates?.(e.persistentVariableUpdates);for(let[r,n]of Object.entries(e.persistentVariableUpdates))t.context.setVariable(r,n)}return e.result}import{set as n6}from"lodash-es";async function Jr(t){let{orgId:e,s:r,context:n,logger:o,signal:i,retries:a=2,timeoutMs:s=Ji,allowUndefined:c=!1}=t,l=/{{(.*?)}}/g,u=r.matchAll(l),d=r;for(let p of u){if(p.length<2)continue;let m=p[1].trim(),f;try{f=await Sa({orgId:e,code:m,fragment:!0,context:n,timeoutMs:s,logger:o,retries:a,localTools:t.localTools,signal:i})}catch(S){throw o.error({err:S,value:r},"Error evaluating template string"),S}if(f===void 0&&!c)throw new L("UserConfigurationError",`Template fragment '${m}' evaluated to undefined. Please ensure that the variable name is spelled correctly and it is only referenced after being assigned a value.`);let h=typeof f=="string"?f:`${f}`;h=h.replaceAll(/\$/g,"$$$$"),d=d.replace(p[0],h)}return d}async function rg(t){return tk(t)}async function tk({obj:t,bannedKeys:e,allowList:r,context:n,prefixPath:o=[],replacements:i=[],...a}){for(let s in t){if(e.includes(s))continue;let c=!1;if(r)if(r.includes(s))c=!0;else continue;let l=t[s],u=[...o,s];if(typeof l=="string"&&l.includes("{{")){let d=await Jr({s:l,context:n,...a});if(l===d)continue;i.push({path:u,original:l}),t[s]=d}else typeof l=="object"&&l!==null&&!Array.isArray(l)&&await tk({obj:l,bannedKeys:e,context:n,prefixPath:u,replacements:i,allowList:c?void 0:r,...a})}return i}function rk(t,e){for(let{path:r,original:n}of e)n6(t,r,n)}import o6 from"fetch-retry";var lXe=process.env.MAILINATOR_API_KEY,cXe=o6(global.fetch,{retryOn:function(t,e,r){return t>3?!1:!!(e!==null||r&&r.status>=400)},retryDelay:function(t){return 500}});import{hostname as Y8}from"os";var Gb={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
|
|
94
|
+
${t.code}`;throw t.logger.error({err:e.error,code:t.code,env:t.context.toObjectCopy()},r),new Error(r)}if(e.variableUpdates)for(let[r,n]of Object.entries(e.variableUpdates))t.context.setVariable(r,n);if(e.persistentVariableUpdates&&Object.keys(e.persistentVariableUpdates).length>0){await t.callbacks?.onPersistentVariableUpdates?.(e.persistentVariableUpdates);for(let[r,n]of Object.entries(e.persistentVariableUpdates))t.context.setVariable(r,n)}return e.result}import{set as n6}from"lodash-es";async function Jr(t){let{orgId:e,s:r,context:n,logger:o,signal:i,retries:a=2,timeoutMs:s=Ji,allowUndefined:c=!1}=t,l=/{{(.*?)}}/g,u=r.matchAll(l),d=r;for(let p of u){if(p.length<2)continue;let m=p[1].trim(),f;try{f=await Sa({orgId:e,code:m,fragment:!0,context:n,timeoutMs:s,logger:o,retries:a,localTools:t.localTools,signal:i})}catch(S){throw o.error({err:S,value:r},"Error evaluating template string"),S}if(f===void 0&&!c)throw new L("UserConfigurationError",`Template fragment '${m}' evaluated to undefined. Please ensure that the variable name is spelled correctly and it is only referenced after being assigned a value.`);let h=typeof f=="string"?f:`${f}`;h=h.replaceAll(/\$/g,"$$$$"),d=d.replace(p[0],h)}return d}async function rg(t){return tk(t)}async function tk({obj:t,bannedKeys:e,allowList:r,context:n,prefixPath:o=[],replacements:i=[],...a}){for(let s in t){if(e.includes(s))continue;let c=!1;if(r)if(r.includes(s))c=!0;else continue;let l=t[s],u=[...o,s];if(typeof l=="string"&&l.includes("{{")){let d=await Jr({s:l,context:n,...a});if(l===d)continue;i.push({path:u,original:l}),t[s]=d}else typeof l=="object"&&l!==null&&!Array.isArray(l)&&await tk({obj:l,bannedKeys:e,context:n,prefixPath:u,replacements:i,allowList:c?void 0:r,...a})}return i}function rk(t,e){for(let{path:r,original:n}of e)n6(t,r,n)}import o6 from"fetch-retry";var cXe=process.env.MAILINATOR_API_KEY,uXe=o6(global.fetch,{retryOn:function(t,e,r){return t>3?!1:!!(e!==null||r&&r.status>=400)},retryDelay:function(t){return 500}});import{hostname as Y8}from"os";var Gb={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
|
|
95
95
|
var momenticConstants = {
|
|
96
96
|
bannedClassSubstrings: [
|
|
97
97
|
"relative",
|
|
@@ -1259,8 +1259,8 @@ function elementMeetsRequirements(logs, element, rootBoundingBox, requirements)
|
|
|
1259
1259
|
meetsRequirements: true
|
|
1260
1260
|
};
|
|
1261
1261
|
}
|
|
1262
|
-
var ANGLE_TOLERANCE_RADIANS =
|
|
1263
|
-
var DISTANCE_TOLERANCE_PERCENT = 0.
|
|
1262
|
+
var ANGLE_TOLERANCE_RADIANS = 10 * Math.PI / 180;
|
|
1263
|
+
var DISTANCE_TOLERANCE_PERCENT = 0.2;
|
|
1264
1264
|
function additionalElementPositionMatches(mainElementBoundingBox, additionalElementBoundingBox, additionalElement) {
|
|
1265
1265
|
const mainElementCenterX = mainElementBoundingBox.x + mainElementBoundingBox.width / 2;
|
|
1266
1266
|
const mainElementCenterY = mainElementBoundingBox.y + mainElementBoundingBox.height / 2;
|
|
@@ -1280,9 +1280,10 @@ function additionalElementPositionMatches(mainElementBoundingBox, additionalElem
|
|
|
1280
1280
|
if (additionalElement.relativeAngleRadians !== void 0) {
|
|
1281
1281
|
const angleRadians = Math.atan2(deltaY, deltaX);
|
|
1282
1282
|
const normalizedAngleRadians = angleRadians < 0 ? angleRadians + 2 * Math.PI : angleRadians;
|
|
1283
|
-
const
|
|
1283
|
+
const rawAngleDiff = Math.abs(
|
|
1284
1284
|
normalizedAngleRadians - additionalElement.relativeAngleRadians
|
|
1285
1285
|
);
|
|
1286
|
+
const angleDiff = Math.min(rawAngleDiff, 2 * Math.PI - rawAngleDiff);
|
|
1286
1287
|
if (angleDiff > ANGLE_TOLERANCE_RADIANS) {
|
|
1287
1288
|
return false;
|
|
1288
1289
|
}
|
|
@@ -4591,7 +4592,7 @@ ${c}`,{errOptions:{cause:t}})}if(i.includes("element is not visible")){let c="Th
|
|
|
4591
4592
|
writable: false,
|
|
4592
4593
|
configurable: false,
|
|
4593
4594
|
});`),`${r}
|
|
4594
|
-
//# sourceURL=momentic-injected/extra-scripts.js`}function uv(t){let e=[],r="";for(let n of t)n==="+"&&r?(e.push(r),r=""):r+=n;return e.push(r),e}var Q6=["clipboard-read","clipboard-write","microphone","camera","geolocation","local-network-access"],Z6=["local-network-access"];function jk(t){return Gn?t.filter(e=>!Z6.includes(e)):t}function Vk(t){return jk(t||Q6)}var dv="__momentic_session_storage_initialized";function Wk(t){return t.parentFrame!==void 0}async function $k(t,e,r){try{let n=await eQ(t);if(n.entries.length===0)return;let o=e.origins?.find(i=>i.origin===n.origin);o?o.sessionStorage=n.entries:(e.origins=e.origins??[],e.origins.push({origin:n.origin,localStorage:[],sessionStorage:n.entries})),r.info(`Saved ${n.entries.length} session storage entries`)}catch(n){r.warn({err:n},"Failed to extract session storage, continuing...")}}async function eQ(t){return t.evaluate(e=>{let r=[];for(let n=0;n<window.sessionStorage.length;n++){let o=window.sessionStorage.key(n);if(o&&o!==e){let i=window.sessionStorage.getItem(o);i!==null&&r.push({name:o,value:i})}}return{origin:window.location.origin,entries:r}},dv)}function qk(t,e){if(!t||!e)return;let r=t.x+t.width/2,n=t.y+t.height/2,o=e.x+e.width/2,i=e.y+e.height/2,a=o-r,s=i-n,c=Math.atan2(s,a);return c<0?c+2*Math.PI:c}function Kk(t,e){if(!t||!e)return;let r=t.x+t.width/2,n=t.y+t.height/2,o=e.x+e.width/2,i=e.y+e.height/2,a=o-r,s=i-n;return Math.sqrt(a*a+s*s)}function tQ(t){return t?t.match(/^\s*<\s*([a-zA-Z0-9-]+)/)?.[1]?.toLowerCase():void 0}function rQ(t){if(!t)return;let e=t.match(/\srole\s*=\s*(?:"([^"]+)"|'([^']+)'|([^\s>]+))/i);return e?.[1]??e?.[2]??e?.[3]}function pv(t,e){let r=e?.tagName??tQ(t.nodeOnlySerializedHtml);if(r&&fk.includes(r.toLowerCase()))return!0;let n=rQ(t.nodeOnlySerializedHtml);return!!(n&&hk.includes(n.toLowerCase()))}async function nQ(t){let{initialLocationResult:e,cacheEvaluationParams:r,locator:n}=t;return n.evaluate((o,i)=>{let a=window,{initialLocationResult:s,cacheEvaluationParams:c}=i;if(!a.momenticConstants)throw new Error("Momentic constants not found");if(o.tagName.toLowerCase()!==s.tagName.toLowerCase())return"Tag name mismatch";let l=(o.textContent??"").slice(0,a.momenticConstants.serializedElementForCachingTruncateLength),u=(s.textContent??"").slice(0,a.momenticConstants.serializedElementForCachingTruncateLength);if(l!==u)return"Text content mismatch";for(let[m,f]of Object.entries(s.importantAttributes))if(o.getAttribute(m)!==f)return`Attribute ${m} mismatch`;let d=s.boundingBox.width*s.boundingBox.height,p=o.getBoundingClientRect().width*o.getBoundingClientRect().height;if(d===0||p===0){if(d!==p)return"Area mismatch"}else if(Math.abs(d-p)/d>.05)return"Area mismatch";if(s.identityHash&&a?.getElementIdentityHash&&s.identityHash!==a.getElementIdentityHash(o))return"Identity hash mismatch";if(c&&a.evaluatePrimaryCaches){let{css:m,hybrid:f}=a.evaluatePrimaryCaches(c);if(f?.result&&f.result.mPath&&s.mPath&&JSON.stringify(f.result.mPath)!==JSON.stringify(s.mPath))return"Hybrid selector returned a different element than the original";if(!f&&m&&m.result&&m.result.dataMomenticId!==s.dataMomenticId)return"CSS selector returned a different element than the original"}},{initialLocationResult:e,cacheEvaluationParams:r},{timeout:pe})}async function mv(t){let{logger:e}=t;try{let r=await nQ(t);if(!r)return;throw e.warn({failReason:r},"Locator no longer matches cache, re-triggering evaluation"),new ji("Locator no longer matches cache")}catch(r){if(r instanceof ji)throw r;e.warn({err:r},"Failed to check whether locator has drifted from cache")}}import Yk from"jpeg-js";import oQ from"pixelmatch";function Xk(t,e,r=.01){if(t.equals(e))return 0;let n=Yk.decode(t),o=Yk.decode(e);if(n.width!==o.width||n.height!==o.height)return 100;let i=n.width,a=n.height,s=Buffer.alloc(i*a*4);return oQ(n.data,o.data,s,i,a,{threshold:r})/(i*a)*100}var Qk=["date","datetime-local","month","time","week"],Jk={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 Zk(t){try{await J(iQ(t),{milliseconds:pe})}catch(e){t.logger.warn({err:e},"Failed to transform native datetime input, continuing...")}}async function iQ({root:t,text:e,options:r,logger:n,callbacks:o}){let i=(await Qt({root:t,fn:()=>document.activeElement?.getAttribute("type")??"",timeout:Qe,arg:void 0,waitForPageLoad:o.waitForPageLoad,codePath:"transforming native datetime input"})).toLowerCase();if(!Jk[i])return;Jk[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`),r.clearContent=!1,n.info("Transforming datetime input to use sequential key presses")}import{z as Qr}from"zod";var e0=Qr.object({doubleClick:Qr.boolean().optional(),rightClick:Qr.boolean().optional(),force:Qr.boolean().optional(),waitForDownload:Qr.boolean().optional(),delayMs:Qr.number().optional(),downloadTimeoutMs:Qr.number().optional(),relativePosition:Qr.object({x:Qr.number(),y:Qr.number()}).optional(),iterations:Qr.number().optional()}),e6e=Qr.object({repeat:Qr.number().optional(),convertMeta:Qr.boolean().optional().describe("misleading name due to backcompat. converts keyshortcuts + meta/control to platform-specific combos. defaults to true"),delayMs:Qr.number().optional()});async function cg({locator:t,callbacks:e,logger:r,timeoutMs:n=Qe}){try{await fv(e,n);let o=t.evaluate(a=>{let s=window;s.momenticIsEligible=p=>{let f=window.getComputedStyle(p,null).getPropertyValue("display");if(f==="none"||f==="contents")return!1;let h=p.getBoundingClientRect();return!(!h.height||!h.width)},s.removeHighlightTimers=s.removeHighlightTimers||[],s.removeHighlightFunctions=s.removeHighlightFunctions||{};let c=0;for(;!s.momenticIsEligible(a)&&c<3;){if(!a.parentElement)throw new Error("No eligible non-empty parent found for highlighting");a=a.parentElement,c++}let l=a.style.getPropertyValue("outline"),u=a.style.getPropertyPriority("outline");a.style.setProperty("outline","5px dashed rgb(255, 0, 153)","important");let d=`momentic${Math.floor(Math.random()*1e7)}`;s[d]=()=>{a.style.removeProperty("outline"),a.style.setProperty("outline",l,u),a.getAttribute("style")||a.removeAttribute("style")},s.removeHighlightTimers.push(setTimeout(()=>{s[d](),s.removeHighlightFunctions?.[d]&&delete s.removeHighlightFunctions[d]},5e3)),s.removeHighlightFunctions[d]=s[d]},void 0,{timeout:n}).then(()=>!0).catch(a=>(r.debug({err:a},"Failed to add node highlight, a page navigation likely occurred. This is non-fatal for tests."),!1));return await J(o,{milliseconds:n})}catch(o){return r.debug({err:o},"Failed to add node highlight, a page navigation likely occurred. This is non-fatal for tests."),!1}}async function fv(t,e=Qe){let r=await t.state.getRoot();await Qt({root:r,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:t.waitForPageLoad,codePath:"removing element highlights"})}async function hv(t){let e=!!t.browserCallbacks.state.userBrowserSettings.visualActions;return Us({action:"clicking element",targetingResult:t.targetingResult,logger:t.logger,retryTimeoutMs:t.retryTimeoutMs,callbacks:t.browserCallbacks,func:async r=>r0({...t,targetingResult:r,useVisualClick:e})})}async function cQ({actionSource:t,position:e,targetingResult:r,logger:n}){let{locator:o}=r;if(t!=="click"||e)return{locator:o,position:e,redirected:!1};let i=await yk({targetingResult:r,logger:n});return i?{locator:i.locator,position:i.relativePoint,redirected:!0}:{locator:o,position:e,redirected:!1}}async function uQ(t,e){try{return await dQ(t,e)}catch(r){throw e.logger.warn({redirectionAttemptError:r,originalError:t},"Error handling click error, rethrowing original error"),t}}async function dQ(t,e){let{logger:r,redirectionAttempts:n=0}=e,o=e.targetingResult.locator;if(t.message.includes("label")&&t.message.includes("for=")&&t.message.includes("intercepts pointer events")){let i=await o.getAttribute("id",{timeout:Qe});if(!i)throw t;let a=o.page().locator(`[for=${JSON.stringify(i)}]`),s=await a.boundingBox({timeout:Qe});if(!s||s.width===0||s.height===0)throw r.warn("Label element has no bounding box, throwing original error..."),t;return r.warn({err:t},"Attempting locator redirection due to input being covered by label"),r0({...e,targetingResult:{locator:a,originalElementLocationResult:void 0,serverSideBoundingBox:s},redirectionAttempts:n+1})}else throw r.warn({err:t},"Click error does not match any known recoverable patterns, rethrowing"),t}async function pQ(t){let{logger:e,targetingResult:r,position:n,options:o}=t,i=e0.safeParse(o),a=Date.now(),{clickX:s,clickY:c,reason:l}=await hQ({targetingResult:r,position:n,options:o,logger:e,isAndroid:t.isAndroid});return e.info({position:n,options:i.success?i.data:void 0,clickLocation:{clickX:s,clickY:c,reason:l},duration:Date.now()-a},"Visual click"),{x:s,y:c}}async function mQ(t){let{actionSource:e,targetingResult:r,options:n,logger:o}=t,i=t.targetingResult.locator,a=n?.relativePosition??t.position;({locator:i,position:a}=await cQ({actionSource:e,position:a,targetingResult:r,logger:o}));let s=n?.force||r.hints?.force||!1;s&&!a&&r.hints?.relativeXYToLocator&&(a=r.hints.relativeXYToLocator);let c=i.toString();o.info({locator:c,position:a},"Locator click");try{n?.doubleClick?await i.dblclick({button:n.rightClick?"right":"left",timeout:pe,position:a,delay:n?.delayMs??25,force:s}):await i.click({button:n?.rightClick?"right":"left",timeout:pe,position:a,delay:n?.delayMs??25,force:s,clickCount:n?.iterations})}catch(l){if(SQ(l))o.warn({err:l},"Click action timed out while waiting for navigation after completion, continuing...");else{if((t.redirectionAttempts??0)<1)return o.warn({err:l},"Error clicking on locator, attempting to recover..."),uQ(l,{...t,targetingResult:r});throw l}}return{locatorSource:c}}async function r0(t){let{options:e,logger:r,browserCallbacks:n,controllerCallbacks:o,useVisualClick:i,targetingResult:a}=t,s;e?.waitForDownload&&(s=(async()=>{let u=e.downloadTimeoutMs??Vb;try{return await a.locator.page().waitForEvent("download",{timeout:u})}catch(d){return d instanceof lQ.TimeoutError?new L("ActionFailureError",`Download did not complete in ${u}ms`):new L("ActionFailureError",`Download failed: ${d.message}`)}})());try{await cg({locator:a.locator,callbacks:n,logger:r,timeoutMs:Qe})}catch(u){r.warn({err:u},"Error highlighting locator in click, continuing...")}let c,l;if(i?c=await pQ(t):l=(await mQ(t)).locatorSource,e?.waitForDownload)if(s){if(!o?.createIsolatedFolder)throw new L("InternalWebAgentError","Cannot wait for download without a callback to create an isolated folder");r.info("Waiting for download to start and complete");let u=await J(s,{milliseconds:e.downloadTimeoutMs??Vb});if(u instanceof Error)throw u;return{downloadedFile:await gQ(u,o.createIsolatedFolder,r),coordinates:c,locatorSource:l}}else throw new Error("No download promise or error but the step requested to wait for a download");return{coordinates:c,locatorSource:l}}async function fQ(t,e){let r=t.serverSideBoundingBox??await t.locator.boundingBox({timeout:pe});if(!r){let i=t.originalElementLocationResult?.serializedElement;throw new L("ActionFailureError",`${US}${i?`: ${i}`:""}`)}if(t.hints?.relativeXYToLocator){let i=r.x+t.hints.relativeXYToLocator.x,a=r.y+t.hints.relativeXYToLocator.y;return[{x:i,y:a},"targeting hint"]}let n=r.x+r.width/2,o=r.y+r.height/2;return[{x:n,y:o},"halfway point"]}async function hQ({options:t,targetingResult:e,position:r,logger:n}){let o,i,a;if(t?.relativePosition){let u=e.serverSideBoundingBox??await e.locator.boundingBox({timeout:pe}),d=t.relativePosition.x,p=t.relativePosition.y;u?.width&&(d=Math.max(0,Math.min(t.relativePosition.x,u.width))),u?.height&&(p=Math.max(0,Math.min(t.relativePosition.y,u.height))),o=(u?.x??0)+d,i=(u?.y??0)+p,a="relative position from user"}else if(r){let u=e.serverSideBoundingBox??await e.locator.boundingBox({timeout:pe});o=(u?.x??0)+r.x,i=(u?.y??0)+r.y,a="predefined position"}else{let[u,d]=await fQ(e,n);o=u.x,i=u.y,a=d}let s=e.locator.page(),c=t?.rightClick?"right":"left",l=t?.delayMs??25;return t?.doubleClick?await s.mouse.dblclick(o,i,{button:c,delay:l}):await s.mouse.click(o,i,{button:c,delay:l,clickCount:t?.iterations}),{clickX:o,clickY:i,reason:a}}async function gQ(t,e,r){r.info("Download detected, saving file to disk");let n=await t.path(),o=Zb(t.suggestedFilename()),i=e();await t.saveAs(sQ(i,o)),t0(n,{force:!0}),setTimeout(()=>{t0(i,{recursive:!0,force:!0})},5*60*1e3);let a=bk(aQ(i),o);return r.info({uri:a,downloadFolder:i},"Saved download to isolated folder"),a}function SQ(t){return t.message.includes("locator.click: Timeout")&&t.message.includes("click action done")}import{platform as yQ}from"os";var EQ={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 TQ(){let t=yQ();return t==="win32"?"win32":t==="darwin"?"darwin":"linux"}function n0(t){return JSON.stringify(t.split("+").sort())}function ug(t,e){let r=TQ(),n=n0(t);for(let o of Object.values(EQ))if(Object.values(o).some(i=>n0(i)===n))return o[r];return process.platform==="darwin"&&!e?t=t.replaceAll("Control","Meta"):t=t.replaceAll("Meta","Control"),t}async function gv({frame:t,page:e,deltaX:r,directionX:n,deltaY:o,directionY:i,signal:a,callbacks:s,logger:c}){if(!r&&!o)return;let l=n==="left"?-1:1,u=i==="up"?-1:1;if(t)await Qt({root:t,fn:([d,p,m,f])=>window.scrollTo(window.scrollX+(d??window.innerWidth)*m,window.scrollY+(p??window.innerHeight)*f),arg:[r,o,l,u],waitForPageLoad:s.waitForPageLoad,timeout:st,codePath:"scrolling page"});else{let d=e.viewportSize()||Ir,p=await Qt({root:e,fn:()=>document.body.scrollHeight,arg:void 0,waitForPageLoad:s.waitForPageLoad,timeout:st,codePath:"computing page height"}),[m,f,h]=await Qt({root:e,fn:()=>{let S=document.activeElement;if(!S)return[void 0,void 0,void 0];let g=S.getBoundingClientRect();return[S.scrollTop,g.x,g.y]},arg:void 0,waitForPageLoad:s.waitForPageLoad,timeout:st,codePath:"computing active element position"});await e.mouse.wheel((r??d.width)*l,(o??d.height)*u);try{let S=Date.now();for(;Date.now()-S<st;){a?.throwIfAborted();let g=await J(e.evaluate(()=>document.body.scrollHeight),{milliseconds:Qe}),[E,y,b]=await J(e.evaluate(()=>{let C=document.activeElement;if(!C)return[void 0,void 0,void 0];let I=C.getBoundingClientRect();return[C.scrollTop,I.x,I.y]}),{milliseconds:Qe});if(g===p&&E===m&&y===f&&b===h)break;p=g,m=E,f=y,h=b,await xe(dr)}}catch(S){c.warn({err:S},"Failed to wait for scroll to complete, continuing...")}}}async function Sv(t,e){let r,n;for(let o=0;o<4;o++)try{return r=t.pages(),await Promise.all(r.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 xe(dr)}throw new Error(`Failed to get tab titles after all retries: ${n?.message}`)}async function yv(t){let{page:e,deltaX:r,deltaY:n,steps:o,visualTarget:i,isAndroid:a,hoverDurationMs:s}=t;if(a){await bQ(t);return}await e.mouse.move(i.x,i.y),await e.mouse.down(),await e.mouse.move(r+i.x,n+i.y,{steps:o}),await xe(s??ya),await e.mouse.up()}async function o0({page:t,fromLocator:e,toLocator:r,stepCount:n,dragDurationMs:o,hoverDurationMs:i}){let a=await r.boundingBox({timeout:pe});if(!a)throw new L("ActionFailureError","Could not get bounding box of 'to' target element");let s=await e.boundingBox({timeout:pe});if(!s)throw new L("ActionFailureError","Could not get bounding box of 'from' target element");let c=a.x+a.width/2,l=a.y+a.height/2,u=s.x+s.width/2,d=s.y+s.height/2;await yv({page:t,deltaX:c-u,deltaY:l-d,steps:n,dragDurationMs:o,hoverDurationMs:i,visualTarget:{x:u,y:d},isAndroid:!0})}async function i0(t,e,r,n){await t.mouse.move(e.x,e.y,{steps:3}),await t.mouse.down(),await t.mouse.move(r.x,r.y,{steps:3}),await xe(Math.min(n.hoverDurationMs??500,og)),await t.mouse.up()}async function bQ(t){let{page:e,deltaX:r,deltaY:n,steps:o,visualTarget:i,dragDurationMs:a,hoverDurationMs:s}=t,c=Math.max(1,o??1),l=i.x,u=i.y,d=i.x+r,p=i.y+n;await e.evaluate(async({startX:m,startY:f,endX:h,endY:S,stepCount:g,dragDurationMs:E,hoverDurationMs:y})=>{let b=document.elementFromPoint(m,f)??document.body??document.documentElement,I=window._momenticMobileUtilities.dispatchTouch;I(b,"touchstart",m,f);for(let _=1;_<=g;_+=1){let R=m+(h-m)*_/g,M=f+(S-f)*_/g;I(b,"touchmove",R,M),await new Promise(P=>setTimeout(P,Math.floor((E??500)/g)))}y&&await new Promise(_=>setTimeout(_,y)),I(b,"touchend",h,S)},{startX:l,startY:u,endX:d,endY:p,stepCount:c,dragDurationMs:a,hoverDurationMs:s})}import{randomUUID as IQ}from"crypto";import{cloneDeep as bv}from"lodash-es";function va(t,e){let r=t.findIndex(n=>n===e);if(!(r===-1||!t[r+1]))return t[r+1]}import{createHash as vQ}from"crypto";var AQ="v1";function Ev(t,e){if(t.tagName.toLowerCase()==="svg"&&!RQ(t))try{let r=a0(t,e),n=CQ(JSON.stringify(r));return{version:AQ,json:r,hash:n}}catch{return}}function CQ(t){return vQ("md5").update(t).digest("hex")}function a0(t,e){let r=t.tagName.toLowerCase(),n=wQ(t);if(r==="image"&&n["xlink:href"])throw new Error("Image tags within SVGs are not supported");let o={type:r,props:n,children:[]};for(let i of t.childrenBackendIds){let a=e.backendIdToNode[i];if(a&&a.nodeType===1){let s=a0(a,e);s&&o.children.push(s)}}return o}function RQ(t){let e=t.computedStyles.display,r=t.computedStyles.visibility,n=t.computedStyles.opacity;return e==="none"||r==="hidden"||n==="0"}function wQ(t){let e={},r=t.attributes;for(let n of Object.keys(r))Cn.visualAttributesForSvgSerialization.includes(n)&&(e[n]=r[n]);return r.id&&t.tagName.toLowerCase()!=="svg"&&(e.id=r.id),e}var Bs={r:147,g:196,b:125,a:.55},l0={showRulers:!1,showStyles:!1,showExtensionLines:!1,contrastAlgorithm:"aa",contentColor:Bs,paddingColor:Bs,borderColor:Bs,marginColor:Bs,eventTargetColor:Bs,shapeColor:Bs,shapeMarginColor:Bs,showInfo:!0,showAccessibilityInfo:!0};function c0({snapshot:t,devicePixelRatio:e,computedStylesToFetch:r,logger:n}){let o=t.strings,i=t.documents,a={},s={},c={roots:[],backendIdToNode:a,frameIndexToIframeNode:s};return i.forEach((l,u)=>{let d=xQ({allDocuments:i,stringConstants:o,computedStylesToFetch:r,devicePixelRatio:e,frameIndex:u,backendIdToNode:a,frameIndexToIframeNode:s,logger:n});c.roots.push(d)}),c}function xQ({allDocuments:t,stringConstants:e,computedStylesToFetch:r,devicePixelRatio:n,frameIndex:o,frameIndexToIframeNode:i,backendIdToNode:a,logger:s}){let c=t[o],l=c.layout,u={};l.nodeIndex.forEach((_,R)=>{u[_]=R});let d=l.styles,p=l.bounds??[],m=c.nodes,f=m.contentDocumentIndex??{index:[],value:[]},h=m.backendNodeId??[],S=m.attributes??[],g=m.parentIndex??[],E=m.nodeName??[],y=m.nodeType??[],b=m.pseudoType??{index:[],value:[]},C=m.inputChecked??{index:[]},I=e[c.frameId];for(let _=0;_<h.length;_++){let R=h[_],M=y[_],P=S[_]??[],B=g[_]!==void 0&&g[_]>=0?g[_]:void 0,F=B!==void 0?h[B]:void 0,G=F!==void 0?a[F]:void 0,z=b.index.indexOf(_),ae=z!==-1?e[b.value[z]]:void 0,W=u[_],q;W?q=p[W]??[]:q=[];let X=E[_]!==void 0?e[E[_]]?.toLowerCase():void 0;if(!X){s.warn({backendNodeId:R,frameId:I,frameIndex:o,nodeBounds:q},"DOM node has no tag name");continue}let ne={backendNodeId:R,psuedoType:ae,nodeType:M,frameIndex:o,parentFrameId:I,ownedFrameId:void 0,bounds:{x:q[0]??null,y:q[1]??null,width:q[2]??null,height:q[3]??null},computedStyles:{},attributes:{},parentBackendNodeId:F??null,tagName:X,parent:G??void 0,childrenBackendIds:[],momenticIgnored:void 0,mPathSelector:void 0};G&&G.childrenBackendIds.push(R);let de=f.index.indexOf(_);if(de!==-1){let te=f.value[de];i[te]=ne;let be=t[te]?.frameId;ne.ownedFrameId=be!==void 0?e[be]:void 0}for(let te of Object.keys(ne.bounds)){let be=te;ne.bounds[be]!==null&&(ne.bounds[be]/=n)}let Te=W!==void 0?d[W]??[]:[];for(let te=0;te<Te.length&&!(te>=r.length);te++){let be=Te[te];if(be===void 0||isNaN(be))continue;let Pe=e[be];if(Pe===void 0)continue;let ve=r[te];ne.computedStyles[ve]=Pe}for(let te=0;te<P.length;te+=2){let be=P[te],Pe=P[te+1];if(!be||!Pe)continue;let ve=e[be],x=e[Pe];!ve||!x||(ne.attributes[ve]=x)}C.index.includes(_)&&(ne.attributes.checked="true"),a[ne.backendNodeId]=ne}return a[h[0]]}function Tv(t,e){if(t.mPathSelector)return t.mPathSelector;let r=t.parent,n;if(!r)n=t.tagName;else if(t.tagName==="body")n="body";else{let i=r.childrenBackendIds.filter(c=>e.backendIdToNode[c]?.nodeType===1&&!e.backendIdToNode[c]?.psuedoType).indexOf(t.backendNodeId),a=` > ${t.tagName}:nth-child(${i+1})`;n=`${Tv(r,e)}${a}`}return t.mPathSelector=n,n}function s0(t,e){return t.parentBackendNodeId!==null?e.backendIdToNode[t.parentBackendNodeId]:t.frameIndex===0?void 0:e.frameIndexToIframeNode[t.frameIndex]}var _Q=["html","#document","#document-fragment"];function u0({node:t,domGraph:e}){let r=[],n=t,o=s0(t,e);if(!o)return[t.tagName];let i=()=>{if(n=o,o=s0(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++,_Q.includes(n.tagName)){i();continue}if(n.tagName==="body")r.push("body");else{let c=!1,l=1;for(let u=0;u<o.childrenBackendIds.length;u++){let d=o.childrenBackendIds[u],p=e.backendIdToNode[d];if(d===n.backendNodeId){r.push(`${n.tagName}:nth-child(${l})`),c=!0;break}else p?.nodeType===1&&!p.psuedoType&&l++}if(!c)throw new Error(`Could not find child (${n.tagName}) in parent's children list (${o.tagName})`)}i()}return r.reverse()}function d0(t,e){let r=t.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?r=r.frameLocator(a):r=r.locator(a)}}if(n.length&&(r=r.locator(n.join(" > "))),"owner"in r)throw new Error("Final locator from mpath is a frame locator");return r}async function p0(t,e){await t.send({method:"DOM.getDocument",params:{depth:0},timeout:st});let r=await t.send({method:"DOM.requestNode",params:{objectId:e},timeout:st}),o=(await t.send({method:"DOM.getAttributes",params:{nodeId:r.nodeId},timeout:st})).attributes,i=va(o,ks);if(!i)throw new Error(`Could not find attribute ${ks} for object ${e}`);return i}var PQ=["svg","i"],MQ=["focusable","keyshortcuts","controls","live","relevant","orientation"],OQ=["selected","readonly","modal","required","invalid"],LQ=["id","name","role","content"],m0=["absolute","fixed","sticky"],NQ=["i","label"],DQ=["path"],kQ=["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","LabelText"],g0=["ariaHiddenElement","ariaHiddenSubtree","hiddenByChildTree","inertElement","inertSubtree","notRendered","notVisible"],S0=["activeAriaModalDialog","activeFullscreenElement","activeModalDialog"],FQ=["menulistpopup","statictext","inlinetextbox"],UQ=80,f0=100,vv=50,Rv=["StaticText","ListMarker","RootWebArea","LineBreak","::before","::after"],BQ=["cite"],zQ={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"],emphasis:["em"]},HQ={name:!0,value:!0,title:!0,alt:!0,placeholder:!0,checked:!0,selected:!0,contenteditable:!0},h0={indentLevel:0},Av=class t{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(r=>{r.name==="keyshortcuts"?this.dataMomenticId=parseInt(r.value.value):this.properties[r.name]=r.value.value}),e.domNode){this.domNode=e.domNode,this.tagName=e.domNode.tagName||void 0;let r=e.domNode.attributes.id;this.name=this.name||e.domNode.attributes.name||(r&&r.length<vv?r:""),this.role=this.role||(e.domNode.attributes.role??""),WQ(this.properties,e.domNode,e.importantProperties)}qQ(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&&DQ.includes(this.domNode.tagName)&&!this.domNode.attributes["aria-label"]||this.ignoredReasons.some(n=>S0.includes(n)))return!1;if(e){if(Object.keys(this.domNode?.attributes??{}).some(o=>v0(o,e)))return!0;let n=this.domNode?.attributes.class?.split(" ");if(n&&n.length>0&&n.some(o=>A0(o,e))||e.styles?.some(o=>{let i=o.split(":");if(i.length!==2)return!1;let a=i[0]?.trim(),s=i[1]?.trim();if(a===void 0||s===void 0)return!1;let c=this.domNode?.computedStyles[a];return c!==void 0&&(c===s||s==="*")}))return!0}if(this.domNode&&NQ.includes(this.domNode.tagName)||kQ.includes(this.role.toLowerCase())||this.domNode?.computedStyles["background-image"]&&this.domNode?.computedStyles["background-image"]!=="none"&&this.children.length===0||this.role.toLowerCase()==="inlinetextbox"&&this.tagName||!this.properties.hidden&&(this.properties.focusable||this.properties.settable)||Cn.alwaysInterestingTruthyPropertyNames.some(n=>!!this.properties[n]))return!0;let r=this.properties.class;return typeof r=="string"&&r.split(" ").some(n=>b0(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")||this.children.some(n=>n.isIneligible())?!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"))}isIneligible(){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))}canRedirectFromIneligibleTag(){if(!this.domNode)return!1;let e=this.internalProperties.hasExplicitPointingLabel===!0;return Sk({tagName:this.domNode.tagName,width:this.domNode.bounds.width,height:this.domNode.bounds.height})&&e}serialize(e=h0){let r=Object.assign({},h0,e),{indentLevel:n,noChildren:o,noProperties:i,noId:a,noContent:s,condensedMode:c}=r,l=bv(this.properties),u=" ".repeat(n),d=this.role||"",p=this.tagName??"unknown",m=this.name;d==="heading"&&m==="heading"&&(m="");let f=this.nameSources?.find(R=>!R.superseded&&R.type==="contents"),h=this.domNode?.attributes.id;f&&this.children.length>0&&(m=h&&h.length<vv?h:"");let S=this.nameSources?.find(R=>!R.superseded);if(S&&!S.nativeSource&&S.type==="relatedElement"){let R=S.attributeValue?.relatedNodes??[];R.length===1&&R[0].text&&R[0].text===m&&(m="")}let g=Rv.includes(this.role)||BQ.includes(this.tagName||"");if(this.role==="StaticText")return`${u}${m}
|
|
4595
|
+
//# sourceURL=momentic-injected/extra-scripts.js`}function uv(t){let e=[],r="";for(let n of t)n==="+"&&r?(e.push(r),r=""):r+=n;return e.push(r),e}var Q6=["clipboard-read","clipboard-write","microphone","camera","geolocation","local-network-access"],Z6=["local-network-access"];function jk(t){return Gn?t.filter(e=>!Z6.includes(e)):t}function Vk(t){return jk(t||Q6)}var dv="__momentic_session_storage_initialized";function Wk(t){return t.parentFrame!==void 0}async function $k(t,e,r){try{let n=await eQ(t);if(n.entries.length===0)return;let o=e.origins?.find(i=>i.origin===n.origin);o?o.sessionStorage=n.entries:(e.origins=e.origins??[],e.origins.push({origin:n.origin,localStorage:[],sessionStorage:n.entries})),r.info(`Saved ${n.entries.length} session storage entries`)}catch(n){r.warn({err:n},"Failed to extract session storage, continuing...")}}async function eQ(t){return t.evaluate(e=>{let r=[];for(let n=0;n<window.sessionStorage.length;n++){let o=window.sessionStorage.key(n);if(o&&o!==e){let i=window.sessionStorage.getItem(o);i!==null&&r.push({name:o,value:i})}}return{origin:window.location.origin,entries:r}},dv)}function qk(t,e){if(!t||!e)return;let r=t.x+t.width/2,n=t.y+t.height/2,o=e.x+e.width/2,i=e.y+e.height/2,a=o-r,s=i-n,c=Math.atan2(s,a);return c<0?c+2*Math.PI:c}function Kk(t,e){if(!t||!e)return;let r=t.x+t.width/2,n=t.y+t.height/2,o=e.x+e.width/2,i=e.y+e.height/2,a=o-r,s=i-n;return Math.sqrt(a*a+s*s)}function tQ(t){return t?t.match(/^\s*<\s*([a-zA-Z0-9-]+)/)?.[1]?.toLowerCase():void 0}function rQ(t){if(!t)return;let e=t.match(/\srole\s*=\s*(?:"([^"]+)"|'([^']+)'|([^\s>]+))/i);return e?.[1]??e?.[2]??e?.[3]}function pv(t,e){let r=e?.tagName??tQ(t.nodeOnlySerializedHtml);if(r&&fk.includes(r.toLowerCase()))return!0;let n=rQ(t.nodeOnlySerializedHtml);return!!(n&&hk.includes(n.toLowerCase()))}async function nQ(t){let{initialLocationResult:e,cacheEvaluationParams:r,locator:n}=t;return n.evaluate((o,i)=>{let a=window,{initialLocationResult:s,cacheEvaluationParams:c}=i;if(!a.momenticConstants)throw new Error("Momentic constants not found");if(o.tagName.toLowerCase()!==s.tagName.toLowerCase())return"Tag name mismatch";let l=(o.textContent??"").slice(0,a.momenticConstants.serializedElementForCachingTruncateLength),u=(s.textContent??"").slice(0,a.momenticConstants.serializedElementForCachingTruncateLength);if(l!==u)return"Text content mismatch";for(let[m,f]of Object.entries(s.importantAttributes))if(o.getAttribute(m)!==f)return`Attribute ${m} mismatch`;let d=s.boundingBox.width*s.boundingBox.height,p=o.getBoundingClientRect().width*o.getBoundingClientRect().height;if(d===0||p===0){if(d!==p)return"Area mismatch"}else if(Math.abs(d-p)/d>.05)return"Area mismatch";if(s.identityHash&&a?.getElementIdentityHash&&s.identityHash!==a.getElementIdentityHash(o))return"Identity hash mismatch";if(c&&a.evaluatePrimaryCaches){let{css:m,hybrid:f}=a.evaluatePrimaryCaches(c);if(f?.result&&f.result.mPath&&s.mPath&&JSON.stringify(f.result.mPath)!==JSON.stringify(s.mPath))return"Hybrid selector returned a different element than the original";if(!f&&m&&m.result&&m.result.dataMomenticId!==s.dataMomenticId)return"CSS selector returned a different element than the original"}},{initialLocationResult:e,cacheEvaluationParams:r},{timeout:pe})}async function mv(t){let{logger:e}=t;try{let r=await nQ(t);if(!r)return;throw e.warn({failReason:r},"Locator no longer matches cache, re-triggering evaluation"),new ji("Locator no longer matches cache")}catch(r){if(r instanceof ji)throw r;e.warn({err:r},"Failed to check whether locator has drifted from cache")}}import Yk from"jpeg-js";import oQ from"pixelmatch";function Xk(t,e,r=.01){if(t.equals(e))return 0;let n=Yk.decode(t),o=Yk.decode(e);if(n.width!==o.width||n.height!==o.height)return 100;let i=n.width,a=n.height,s=Buffer.alloc(i*a*4);return oQ(n.data,o.data,s,i,a,{threshold:r})/(i*a)*100}var Qk=["date","datetime-local","month","time","week"],Jk={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 Zk(t){try{await J(iQ(t),{milliseconds:pe})}catch(e){t.logger.warn({err:e},"Failed to transform native datetime input, continuing...")}}async function iQ({root:t,text:e,options:r,logger:n,callbacks:o}){let i=(await Qt({root:t,fn:()=>document.activeElement?.getAttribute("type")??"",timeout:Qe,arg:void 0,waitForPageLoad:o.waitForPageLoad,codePath:"transforming native datetime input"})).toLowerCase();if(!Jk[i])return;Jk[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`),r.clearContent=!1,n.info("Transforming datetime input to use sequential key presses")}import{z as Qr}from"zod";var e0=Qr.object({doubleClick:Qr.boolean().optional(),rightClick:Qr.boolean().optional(),force:Qr.boolean().optional(),waitForDownload:Qr.boolean().optional(),delayMs:Qr.number().optional(),downloadTimeoutMs:Qr.number().optional(),relativePosition:Qr.object({x:Qr.number(),y:Qr.number()}).optional(),iterations:Qr.number().optional()}),t6e=Qr.object({repeat:Qr.number().optional(),convertMeta:Qr.boolean().optional().describe("misleading name due to backcompat. converts keyshortcuts + meta/control to platform-specific combos. defaults to true"),delayMs:Qr.number().optional()});async function cg({locator:t,callbacks:e,logger:r,timeoutMs:n=Qe}){try{await fv(e,n);let o=t.evaluate(a=>{let s=window;s.momenticIsEligible=p=>{let f=window.getComputedStyle(p,null).getPropertyValue("display");if(f==="none"||f==="contents")return!1;let h=p.getBoundingClientRect();return!(!h.height||!h.width)},s.removeHighlightTimers=s.removeHighlightTimers||[],s.removeHighlightFunctions=s.removeHighlightFunctions||{};let c=0;for(;!s.momenticIsEligible(a)&&c<3;){if(!a.parentElement)throw new Error("No eligible non-empty parent found for highlighting");a=a.parentElement,c++}let l=a.style.getPropertyValue("outline"),u=a.style.getPropertyPriority("outline");a.style.setProperty("outline","5px dashed rgb(255, 0, 153)","important");let d=`momentic${Math.floor(Math.random()*1e7)}`;s[d]=()=>{a.style.removeProperty("outline"),a.style.setProperty("outline",l,u),a.getAttribute("style")||a.removeAttribute("style")},s.removeHighlightTimers.push(setTimeout(()=>{s[d](),s.removeHighlightFunctions?.[d]&&delete s.removeHighlightFunctions[d]},5e3)),s.removeHighlightFunctions[d]=s[d]},void 0,{timeout:n}).then(()=>!0).catch(a=>(r.debug({err:a},"Failed to add node highlight, a page navigation likely occurred. This is non-fatal for tests."),!1));return await J(o,{milliseconds:n})}catch(o){return r.debug({err:o},"Failed to add node highlight, a page navigation likely occurred. This is non-fatal for tests."),!1}}async function fv(t,e=Qe){let r=await t.state.getRoot();await Qt({root:r,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:t.waitForPageLoad,codePath:"removing element highlights"})}async function hv(t){let e=!!t.browserCallbacks.state.userBrowserSettings.visualActions;return Us({action:"clicking element",targetingResult:t.targetingResult,logger:t.logger,retryTimeoutMs:t.retryTimeoutMs,callbacks:t.browserCallbacks,func:async r=>r0({...t,targetingResult:r,useVisualClick:e})})}async function cQ({actionSource:t,position:e,targetingResult:r,logger:n}){let{locator:o}=r;if(t!=="click"||e)return{locator:o,position:e,redirected:!1};let i=await yk({targetingResult:r,logger:n});return i?{locator:i.locator,position:i.relativePoint,redirected:!0}:{locator:o,position:e,redirected:!1}}async function uQ(t,e){try{return await dQ(t,e)}catch(r){throw e.logger.warn({redirectionAttemptError:r,originalError:t},"Error handling click error, rethrowing original error"),t}}async function dQ(t,e){let{logger:r,redirectionAttempts:n=0}=e,o=e.targetingResult.locator;if(t.message.includes("label")&&t.message.includes("for=")&&t.message.includes("intercepts pointer events")){let i=await o.getAttribute("id",{timeout:Qe});if(!i)throw t;let a=o.page().locator(`[for=${JSON.stringify(i)}]`),s=await a.boundingBox({timeout:Qe});if(!s||s.width===0||s.height===0)throw r.warn("Label element has no bounding box, throwing original error..."),t;return r.warn({err:t},"Attempting locator redirection due to input being covered by label"),r0({...e,targetingResult:{locator:a,originalElementLocationResult:void 0,serverSideBoundingBox:s},redirectionAttempts:n+1})}else throw r.warn({err:t},"Click error does not match any known recoverable patterns, rethrowing"),t}async function pQ(t){let{logger:e,targetingResult:r,position:n,options:o}=t,i=e0.safeParse(o),a=Date.now(),{clickX:s,clickY:c,reason:l}=await hQ({targetingResult:r,position:n,options:o,logger:e,isAndroid:t.isAndroid});return e.info({position:n,options:i.success?i.data:void 0,clickLocation:{clickX:s,clickY:c,reason:l},duration:Date.now()-a},"Visual click"),{x:s,y:c}}async function mQ(t){let{actionSource:e,targetingResult:r,options:n,logger:o}=t,i=t.targetingResult.locator,a=n?.relativePosition??t.position;({locator:i,position:a}=await cQ({actionSource:e,position:a,targetingResult:r,logger:o}));let s=n?.force||r.hints?.force||!1;s&&!a&&r.hints?.relativeXYToLocator&&(a=r.hints.relativeXYToLocator);let c=i.toString();o.info({locator:c,position:a},"Locator click");try{n?.doubleClick?await i.dblclick({button:n.rightClick?"right":"left",timeout:pe,position:a,delay:n?.delayMs??25,force:s}):await i.click({button:n?.rightClick?"right":"left",timeout:pe,position:a,delay:n?.delayMs??25,force:s,clickCount:n?.iterations})}catch(l){if(SQ(l))o.warn({err:l},"Click action timed out while waiting for navigation after completion, continuing...");else{if((t.redirectionAttempts??0)<1)return o.warn({err:l},"Error clicking on locator, attempting to recover..."),uQ(l,{...t,targetingResult:r});throw l}}return{locatorSource:c}}async function r0(t){let{options:e,logger:r,browserCallbacks:n,controllerCallbacks:o,useVisualClick:i,targetingResult:a}=t,s;e?.waitForDownload&&(s=(async()=>{let u=e.downloadTimeoutMs??Vb;try{return await a.locator.page().waitForEvent("download",{timeout:u})}catch(d){return d instanceof lQ.TimeoutError?new L("ActionFailureError",`Download did not complete in ${u}ms`):new L("ActionFailureError",`Download failed: ${d.message}`)}})());try{await cg({locator:a.locator,callbacks:n,logger:r,timeoutMs:Qe})}catch(u){r.warn({err:u},"Error highlighting locator in click, continuing...")}let c,l;if(i?c=await pQ(t):l=(await mQ(t)).locatorSource,e?.waitForDownload)if(s){if(!o?.createIsolatedFolder)throw new L("InternalWebAgentError","Cannot wait for download without a callback to create an isolated folder");r.info("Waiting for download to start and complete");let u=await J(s,{milliseconds:e.downloadTimeoutMs??Vb});if(u instanceof Error)throw u;return{downloadedFile:await gQ(u,o.createIsolatedFolder,r),coordinates:c,locatorSource:l}}else throw new Error("No download promise or error but the step requested to wait for a download");return{coordinates:c,locatorSource:l}}async function fQ(t,e){let r=t.serverSideBoundingBox??await t.locator.boundingBox({timeout:pe});if(!r){let i=t.originalElementLocationResult?.serializedElement;throw new L("ActionFailureError",`${US}${i?`: ${i}`:""}`)}if(t.hints?.relativeXYToLocator){let i=r.x+t.hints.relativeXYToLocator.x,a=r.y+t.hints.relativeXYToLocator.y;return[{x:i,y:a},"targeting hint"]}let n=r.x+r.width/2,o=r.y+r.height/2;return[{x:n,y:o},"halfway point"]}async function hQ({options:t,targetingResult:e,position:r,logger:n}){let o,i,a;if(t?.relativePosition){let u=e.serverSideBoundingBox??await e.locator.boundingBox({timeout:pe}),d=t.relativePosition.x,p=t.relativePosition.y;u?.width&&(d=Math.max(0,Math.min(t.relativePosition.x,u.width))),u?.height&&(p=Math.max(0,Math.min(t.relativePosition.y,u.height))),o=(u?.x??0)+d,i=(u?.y??0)+p,a="relative position from user"}else if(r){let u=e.serverSideBoundingBox??await e.locator.boundingBox({timeout:pe});o=(u?.x??0)+r.x,i=(u?.y??0)+r.y,a="predefined position"}else{let[u,d]=await fQ(e,n);o=u.x,i=u.y,a=d}let s=e.locator.page(),c=t?.rightClick?"right":"left",l=t?.delayMs??25;return t?.doubleClick?await s.mouse.dblclick(o,i,{button:c,delay:l}):await s.mouse.click(o,i,{button:c,delay:l,clickCount:t?.iterations}),{clickX:o,clickY:i,reason:a}}async function gQ(t,e,r){r.info("Download detected, saving file to disk");let n=await t.path(),o=Zb(t.suggestedFilename()),i=e();await t.saveAs(sQ(i,o)),t0(n,{force:!0}),setTimeout(()=>{t0(i,{recursive:!0,force:!0})},5*60*1e3);let a=bk(aQ(i),o);return r.info({uri:a,downloadFolder:i},"Saved download to isolated folder"),a}function SQ(t){return t.message.includes("locator.click: Timeout")&&t.message.includes("click action done")}import{platform as yQ}from"os";var EQ={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 TQ(){let t=yQ();return t==="win32"?"win32":t==="darwin"?"darwin":"linux"}function n0(t){return JSON.stringify(t.split("+").sort())}function ug(t,e){let r=TQ(),n=n0(t);for(let o of Object.values(EQ))if(Object.values(o).some(i=>n0(i)===n))return o[r];return process.platform==="darwin"&&!e?t=t.replaceAll("Control","Meta"):t=t.replaceAll("Meta","Control"),t}async function gv({frame:t,page:e,deltaX:r,directionX:n,deltaY:o,directionY:i,signal:a,callbacks:s,logger:c}){if(!r&&!o)return;let l=n==="left"?-1:1,u=i==="up"?-1:1;if(t)await Qt({root:t,fn:([d,p,m,f])=>window.scrollTo(window.scrollX+(d??window.innerWidth)*m,window.scrollY+(p??window.innerHeight)*f),arg:[r,o,l,u],waitForPageLoad:s.waitForPageLoad,timeout:st,codePath:"scrolling page"});else{let d=e.viewportSize()||Ir,p=await Qt({root:e,fn:()=>document.body.scrollHeight,arg:void 0,waitForPageLoad:s.waitForPageLoad,timeout:st,codePath:"computing page height"}),[m,f,h]=await Qt({root:e,fn:()=>{let S=document.activeElement;if(!S)return[void 0,void 0,void 0];let g=S.getBoundingClientRect();return[S.scrollTop,g.x,g.y]},arg:void 0,waitForPageLoad:s.waitForPageLoad,timeout:st,codePath:"computing active element position"});await e.mouse.wheel((r??d.width)*l,(o??d.height)*u);try{let S=Date.now();for(;Date.now()-S<st;){a?.throwIfAborted();let g=await J(e.evaluate(()=>document.body.scrollHeight),{milliseconds:Qe}),[E,y,b]=await J(e.evaluate(()=>{let C=document.activeElement;if(!C)return[void 0,void 0,void 0];let I=C.getBoundingClientRect();return[C.scrollTop,I.x,I.y]}),{milliseconds:Qe});if(g===p&&E===m&&y===f&&b===h)break;p=g,m=E,f=y,h=b,await xe(dr)}}catch(S){c.warn({err:S},"Failed to wait for scroll to complete, continuing...")}}}async function Sv(t,e){let r,n;for(let o=0;o<4;o++)try{return r=t.pages(),await Promise.all(r.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 xe(dr)}throw new Error(`Failed to get tab titles after all retries: ${n?.message}`)}async function yv(t){let{page:e,deltaX:r,deltaY:n,steps:o,visualTarget:i,isAndroid:a,hoverDurationMs:s}=t;if(a){await bQ(t);return}await e.mouse.move(i.x,i.y),await e.mouse.down(),await e.mouse.move(r+i.x,n+i.y,{steps:o}),await xe(s??ya),await e.mouse.up()}async function o0({page:t,fromLocator:e,toLocator:r,stepCount:n,dragDurationMs:o,hoverDurationMs:i}){let a=await r.boundingBox({timeout:pe});if(!a)throw new L("ActionFailureError","Could not get bounding box of 'to' target element");let s=await e.boundingBox({timeout:pe});if(!s)throw new L("ActionFailureError","Could not get bounding box of 'from' target element");let c=a.x+a.width/2,l=a.y+a.height/2,u=s.x+s.width/2,d=s.y+s.height/2;await yv({page:t,deltaX:c-u,deltaY:l-d,steps:n,dragDurationMs:o,hoverDurationMs:i,visualTarget:{x:u,y:d},isAndroid:!0})}async function i0(t,e,r,n){await t.mouse.move(e.x,e.y,{steps:3}),await t.mouse.down(),await t.mouse.move(r.x,r.y,{steps:3}),await xe(Math.min(n.hoverDurationMs??500,og)),await t.mouse.up()}async function bQ(t){let{page:e,deltaX:r,deltaY:n,steps:o,visualTarget:i,dragDurationMs:a,hoverDurationMs:s}=t,c=Math.max(1,o??1),l=i.x,u=i.y,d=i.x+r,p=i.y+n;await e.evaluate(async({startX:m,startY:f,endX:h,endY:S,stepCount:g,dragDurationMs:E,hoverDurationMs:y})=>{let b=document.elementFromPoint(m,f)??document.body??document.documentElement,I=window._momenticMobileUtilities.dispatchTouch;I(b,"touchstart",m,f);for(let _=1;_<=g;_+=1){let R=m+(h-m)*_/g,M=f+(S-f)*_/g;I(b,"touchmove",R,M),await new Promise(P=>setTimeout(P,Math.floor((E??500)/g)))}y&&await new Promise(_=>setTimeout(_,y)),I(b,"touchend",h,S)},{startX:l,startY:u,endX:d,endY:p,stepCount:c,dragDurationMs:a,hoverDurationMs:s})}import{randomUUID as IQ}from"crypto";import{cloneDeep as bv}from"lodash-es";function va(t,e){let r=t.findIndex(n=>n===e);if(!(r===-1||!t[r+1]))return t[r+1]}import{createHash as vQ}from"crypto";var AQ="v1";function Ev(t,e){if(t.tagName.toLowerCase()==="svg"&&!RQ(t))try{let r=a0(t,e),n=CQ(JSON.stringify(r));return{version:AQ,json:r,hash:n}}catch{return}}function CQ(t){return vQ("md5").update(t).digest("hex")}function a0(t,e){let r=t.tagName.toLowerCase(),n=wQ(t);if(r==="image"&&n["xlink:href"])throw new Error("Image tags within SVGs are not supported");let o={type:r,props:n,children:[]};for(let i of t.childrenBackendIds){let a=e.backendIdToNode[i];if(a&&a.nodeType===1){let s=a0(a,e);s&&o.children.push(s)}}return o}function RQ(t){let e=t.computedStyles.display,r=t.computedStyles.visibility,n=t.computedStyles.opacity;return e==="none"||r==="hidden"||n==="0"}function wQ(t){let e={},r=t.attributes;for(let n of Object.keys(r))Cn.visualAttributesForSvgSerialization.includes(n)&&(e[n]=r[n]);return r.id&&t.tagName.toLowerCase()!=="svg"&&(e.id=r.id),e}var Bs={r:147,g:196,b:125,a:.55},l0={showRulers:!1,showStyles:!1,showExtensionLines:!1,contrastAlgorithm:"aa",contentColor:Bs,paddingColor:Bs,borderColor:Bs,marginColor:Bs,eventTargetColor:Bs,shapeColor:Bs,shapeMarginColor:Bs,showInfo:!0,showAccessibilityInfo:!0};function c0({snapshot:t,devicePixelRatio:e,computedStylesToFetch:r,logger:n}){let o=t.strings,i=t.documents,a={},s={},c={roots:[],backendIdToNode:a,frameIndexToIframeNode:s};return i.forEach((l,u)=>{let d=xQ({allDocuments:i,stringConstants:o,computedStylesToFetch:r,devicePixelRatio:e,frameIndex:u,backendIdToNode:a,frameIndexToIframeNode:s,logger:n});c.roots.push(d)}),c}function xQ({allDocuments:t,stringConstants:e,computedStylesToFetch:r,devicePixelRatio:n,frameIndex:o,frameIndexToIframeNode:i,backendIdToNode:a,logger:s}){let c=t[o],l=c.layout,u={};l.nodeIndex.forEach((_,R)=>{u[_]=R});let d=l.styles,p=l.bounds??[],m=c.nodes,f=m.contentDocumentIndex??{index:[],value:[]},h=m.backendNodeId??[],S=m.attributes??[],g=m.parentIndex??[],E=m.nodeName??[],y=m.nodeType??[],b=m.pseudoType??{index:[],value:[]},C=m.inputChecked??{index:[]},I=e[c.frameId];for(let _=0;_<h.length;_++){let R=h[_],M=y[_],P=S[_]??[],B=g[_]!==void 0&&g[_]>=0?g[_]:void 0,F=B!==void 0?h[B]:void 0,G=F!==void 0?a[F]:void 0,z=b.index.indexOf(_),ae=z!==-1?e[b.value[z]]:void 0,W=u[_],q;W?q=p[W]??[]:q=[];let X=E[_]!==void 0?e[E[_]]?.toLowerCase():void 0;if(!X){s.warn({backendNodeId:R,frameId:I,frameIndex:o,nodeBounds:q},"DOM node has no tag name");continue}let ne={backendNodeId:R,psuedoType:ae,nodeType:M,frameIndex:o,parentFrameId:I,ownedFrameId:void 0,bounds:{x:q[0]??null,y:q[1]??null,width:q[2]??null,height:q[3]??null},computedStyles:{},attributes:{},parentBackendNodeId:F??null,tagName:X,parent:G??void 0,childrenBackendIds:[],momenticIgnored:void 0,mPathSelector:void 0};G&&G.childrenBackendIds.push(R);let de=f.index.indexOf(_);if(de!==-1){let te=f.value[de];i[te]=ne;let be=t[te]?.frameId;ne.ownedFrameId=be!==void 0?e[be]:void 0}for(let te of Object.keys(ne.bounds)){let be=te;ne.bounds[be]!==null&&(ne.bounds[be]/=n)}let Te=W!==void 0?d[W]??[]:[];for(let te=0;te<Te.length&&!(te>=r.length);te++){let be=Te[te];if(be===void 0||isNaN(be))continue;let Pe=e[be];if(Pe===void 0)continue;let ve=r[te];ne.computedStyles[ve]=Pe}for(let te=0;te<P.length;te+=2){let be=P[te],Pe=P[te+1];if(!be||!Pe)continue;let ve=e[be],x=e[Pe];!ve||!x||(ne.attributes[ve]=x)}C.index.includes(_)&&(ne.attributes.checked="true"),a[ne.backendNodeId]=ne}return a[h[0]]}function Tv(t,e){if(t.mPathSelector)return t.mPathSelector;let r=t.parent,n;if(!r)n=t.tagName;else if(t.tagName==="body")n="body";else{let i=r.childrenBackendIds.filter(c=>e.backendIdToNode[c]?.nodeType===1&&!e.backendIdToNode[c]?.psuedoType).indexOf(t.backendNodeId),a=` > ${t.tagName}:nth-child(${i+1})`;n=`${Tv(r,e)}${a}`}return t.mPathSelector=n,n}function s0(t,e){return t.parentBackendNodeId!==null?e.backendIdToNode[t.parentBackendNodeId]:t.frameIndex===0?void 0:e.frameIndexToIframeNode[t.frameIndex]}var _Q=["html","#document","#document-fragment"];function u0({node:t,domGraph:e}){let r=[],n=t,o=s0(t,e);if(!o)return[t.tagName];let i=()=>{if(n=o,o=s0(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++,_Q.includes(n.tagName)){i();continue}if(n.tagName==="body")r.push("body");else{let c=!1,l=1;for(let u=0;u<o.childrenBackendIds.length;u++){let d=o.childrenBackendIds[u],p=e.backendIdToNode[d];if(d===n.backendNodeId){r.push(`${n.tagName}:nth-child(${l})`),c=!0;break}else p?.nodeType===1&&!p.psuedoType&&l++}if(!c)throw new Error(`Could not find child (${n.tagName}) in parent's children list (${o.tagName})`)}i()}return r.reverse()}function d0(t,e){let r=t.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?r=r.frameLocator(a):r=r.locator(a)}}if(n.length&&(r=r.locator(n.join(" > "))),"owner"in r)throw new Error("Final locator from mpath is a frame locator");return r}async function p0(t,e){await t.send({method:"DOM.getDocument",params:{depth:0},timeout:st});let r=await t.send({method:"DOM.requestNode",params:{objectId:e},timeout:st}),o=(await t.send({method:"DOM.getAttributes",params:{nodeId:r.nodeId},timeout:st})).attributes,i=va(o,ks);if(!i)throw new Error(`Could not find attribute ${ks} for object ${e}`);return i}var PQ=["svg","i"],MQ=["focusable","keyshortcuts","controls","live","relevant","orientation"],OQ=["selected","readonly","modal","required","invalid"],LQ=["id","name","role","content"],m0=["absolute","fixed","sticky"],NQ=["i","label"],DQ=["path"],kQ=["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","LabelText"],g0=["ariaHiddenElement","ariaHiddenSubtree","hiddenByChildTree","inertElement","inertSubtree","notRendered","notVisible"],S0=["activeAriaModalDialog","activeFullscreenElement","activeModalDialog"],FQ=["menulistpopup","statictext","inlinetextbox"],UQ=80,f0=100,vv=50,Rv=["StaticText","ListMarker","RootWebArea","LineBreak","::before","::after"],BQ=["cite"],zQ={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"],emphasis:["em"]},HQ={name:!0,value:!0,title:!0,alt:!0,placeholder:!0,checked:!0,selected:!0,contenteditable:!0},h0={indentLevel:0},Av=class t{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(r=>{r.name==="keyshortcuts"?this.dataMomenticId=parseInt(r.value.value):this.properties[r.name]=r.value.value}),e.domNode){this.domNode=e.domNode,this.tagName=e.domNode.tagName||void 0;let r=e.domNode.attributes.id;this.name=this.name||e.domNode.attributes.name||(r&&r.length<vv?r:""),this.role=this.role||(e.domNode.attributes.role??""),WQ(this.properties,e.domNode,e.importantProperties)}qQ(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&&DQ.includes(this.domNode.tagName)&&!this.domNode.attributes["aria-label"]||this.ignoredReasons.some(n=>S0.includes(n)))return!1;if(e){if(Object.keys(this.domNode?.attributes??{}).some(o=>v0(o,e)))return!0;let n=this.domNode?.attributes.class?.split(" ");if(n&&n.length>0&&n.some(o=>A0(o,e))||e.styles?.some(o=>{let i=o.split(":");if(i.length!==2)return!1;let a=i[0]?.trim(),s=i[1]?.trim();if(a===void 0||s===void 0)return!1;let c=this.domNode?.computedStyles[a];return c!==void 0&&(c===s||s==="*")}))return!0}if(this.domNode&&NQ.includes(this.domNode.tagName)||kQ.includes(this.role.toLowerCase())||this.domNode?.computedStyles["background-image"]&&this.domNode?.computedStyles["background-image"]!=="none"&&this.children.length===0||this.role.toLowerCase()==="inlinetextbox"&&this.tagName||!this.properties.hidden&&(this.properties.focusable||this.properties.settable)||Cn.alwaysInterestingTruthyPropertyNames.some(n=>!!this.properties[n]))return!0;let r=this.properties.class;return typeof r=="string"&&r.split(" ").some(n=>b0(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")||this.children.some(n=>n.isIneligible())?!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"))}isIneligible(){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))}canRedirectFromIneligibleTag(){if(!this.domNode)return!1;let e=this.internalProperties.hasExplicitPointingLabel===!0;return Sk({tagName:this.domNode.tagName,width:this.domNode.bounds.width,height:this.domNode.bounds.height})&&e}serialize(e=h0){let r=Object.assign({},h0,e),{indentLevel:n,noChildren:o,noProperties:i,noId:a,noContent:s,condensedMode:c}=r,l=bv(this.properties),u=" ".repeat(n),d=this.role||"",p=this.tagName??"unknown",m=this.name;d==="heading"&&m==="heading"&&(m="");let f=this.nameSources?.find(R=>!R.superseded&&R.type==="contents"),h=this.domNode?.attributes.id;f&&this.children.length>0&&(m=h&&h.length<vv?h:"");let S=this.nameSources?.find(R=>!R.superseded);if(S&&!S.nativeSource&&S.type==="relatedElement"){let R=S.attributeValue?.relatedNodes??[];R.length===1&&R[0].text&&R[0].text===m&&(m="")}let g=Rv.includes(this.role)||BQ.includes(this.tagName||"");if(this.role==="StaticText")return`${u}${m}
|
|
4595
4596
|
`;let E=`${u}<${p}`;!a&&!g&&(E+=` id="${this.id}"`);let y=s??!1;(l.multiline||l.contenteditable)&&this.children.length>0&&(y=!0),d&&d!=="generic"&&d!==p&&!(zQ[d]??[]).includes(p)&&(E+=` role=${JSON.stringify(d)}`),m&&(E+=` name=${JSON.stringify(m)}`),this.content&&!y&&(E+=` content=${JSON.stringify(this.content)}`);let b=this.isIneligible(),C=b&&this.canRedirectFromIneligibleTag();if(this.flagNotActionableNodes&&this.tagName!=="#document"&&b&&!C&&(E+=` ${Cn.ineligibleElementAttribute}`),this.shouldSerializeBounds()&&this.domNode?.bounds){let R=this.domNode.bounds,M=Math.round(R.x??0),P=Math.round(R.y??0),B=Math.round((R.x??0)+(R.width??0)),F=Math.round((R.y??0)+(R.height??0));E+=` bounds=[${M} ${P} ${B} ${F}]`}let I=Date.now();if(Object.keys(l).length>0&&!i){if(Date.now()-I>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(l).forEach(([R,M])=>{if(!MQ.includes(R)){{if(OQ.includes(R)&&(!M||M==="false"))return;if(R==="value"&&y&&(l.type==="text"||this.role==="textbox"))return;if(R==="level"&&`${M}`=="1")return;if(R==="url"&&l.src&&p==="img")return;if(R==="url"&&l.href&&p==="a")return;if(R==="editable"&&M==="plaintext")return;if(R==="type"&&M===p)return;if(c&&!HQ[R])return}typeof M=="string"?E+=` ${R}="${vt(M,f0,!0)}"`:typeof M=="boolean"?M?E+=` ${R}`:E+=` ${R}={false}`:typeof M<"u"&&(E+=` ${R}={${vt(JSON.stringify(M),f0,!0)}}`)}})}if(p==="::before"||p==="::after"){let R="";for(let M of this.children)R+=M.serialize({...e,indentLevel:n,neighbors:0});return R}let _=e.maxLevel!==void 0&&n/2>=e.maxLevel;if(this.children.length===0||o||_)E+=` />
|
|
4596
4597
|
`;else{let R="";for(let P of this.children)R+=P.serialize({...e,indentLevel:n+2,neighbors:0});let M=R.trim();M.length<=UQ&&!M.includes(`
|
|
4597
4598
|
`)?E+=`>${M}</${p}>
|
|
@@ -4599,7 +4600,7 @@ ${c}`,{errOptions:{cause:t}})}if(i.includes("element is not visible")){let c="Th
|
|
|
4599
4600
|
${R}${u}</${p}>
|
|
4600
4601
|
`}if(e.neighbors!==void 0&&e.neighbors>0&&this.parent){let R=this.parent.children.findIndex(B=>B.id===this.id),M=R>0?this.parent.children[R-1]?.serialize({...e,neighbors:0}):"",P=R<this.parent.children.length-1?this.parent.children[R+1]?.serialize({...e,neighbors:0}):"";return`${M||""}
|
|
4601
4602
|
${E}
|
|
4602
|
-
${P||""}`}return E}shallowClone(){let e=new t({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:bv(this.internalProperties),importantProperties:this.importantProperties,parentFrame:this.parentFrame,flagNotActionableNodes:this.flagNotActionableNodes});return e.tagName=this.tagName,e.dataMomenticId=this.dataMomenticId,e.properties=bv(this.properties),e}},Cv=class t{constructor(e,r,n,o,i={}){this.root=e;this.a11yIdNodeMap=r;this.dataMomenticIdMap=n;this.selectorToNodeMap=o;this.nodeIdHasPointingLabelMap=i}serialize(e){return this.root.serialize(e)}pruneUsingSummaries(e){let r=this.root;if(!r)throw new Error("Cannot prune a11y tree with no root");let n={},o={},i={},a=c=>{let l=c.shallowClone();if(e[c.id])return l.properties["data-momentic-summary"]=e[c.id],n[c.id]=l,c.dataMomenticId&&(o[c.dataMomenticId]=l),c.mPathSelector&&(i[c.mPathSelector]=l),l;let u=[];for(let d of c.children){let p=a(d);p&&(u.push(p),p.parent=l)}return l.children=u,n[c.id]=l,c.dataMomenticId&&(o[c.dataMomenticId]=l),c.mPathSelector&&(i[c.mPathSelector]=l),l},s=a(r);return new t(s,n,o,i,this.nodeIdHasPointingLabelMap)}pruneUsingRelevantIds(e){let r=this.root;if(!r)throw new Error("Cannot prune a11y tree with no root");function n(i,a=!1){let s=e.has(`${i.id}`)||i.id===r?.id,c=i.shallowClone(),l=i.children,u=!1,d=[];for(let p of l){let m=n(p,s||u);m&&(d.push(m),m.parent=c,u=!0)}if(c.children=d,s||u)return c;if(Rv.includes(i.role)&&a)return c}let o=n(r);return new t(o,this.a11yIdNodeMap,this.dataMomenticIdMap,this.selectorToNodeMap,this.nodeIdHasPointingLabelMap)}pruneToSerializedCharLimit(e){let r=this.root;if(!r)throw new Error("Cannot prune a11y tree with no root");let n=new WeakMap,o=(s,c)=>{if(n.has(s))return n.get(s);let l=s.serialize({indentLevel:c,noChildren:!0});return n.set(s,l),l},i=(s,c,l)=>{let u=s.shallowClone();u.children=[];let d=o(s,c).length;if(l<=d)return{clone:u,used:d};if(s.role==="StaticText"||s.children.length===0)return{clone:u,used:d};let p=d,m=l-p;for(let f of s.children){let h=c+2,S=o(f,h).length;if(m<S)break;let{clone:g,used:E}=i(f,h,m);if(E>m)break;u.children.push(g),g.parent=u,p+=E,m-=E}return{clone:u,used:p}},{clone:a}=i(r,0,Math.max(1e4,e));return new t(a,this.a11yIdNodeMap,this.dataMomenticIdMap,this.selectorToNodeMap,this.nodeIdHasPointingLabelMap)}};function GQ(t){return t.name?.value?`"${t.name.value}"`:t.role?.value&&t.role.value!=="none"&&t.role.value!=="generic"?`"${t.role.value}"`:`"${t.nodeId}"`}function jQ(t,e,r,n){return t.bounds.x===null||t.bounds.y===null||t.bounds.height===null||t.bounds.width===null||t.bounds.width===0||t.bounds.height===0?!0:t.bounds.x+t.bounds.width<e.leftBound||t.bounds.x>e.rightBound?(Hm({logger:r,logKey:n,maxCount:5,intervalMs:3e3},{domNode:t,logKey:n},"Filtering out node since it is not in the viewport horizontally"),!1):t.bounds.y+t.bounds.height<e.upperBound||t.bounds.y>e.lowerBound?(Hm({logger:r,logKey:n,maxCount:5,intervalMs:3e3},{domNode:t,logKey:n},"Filtering out node since it is not in the viewport vertically"),!1):t.computedStyles.display==="none"?(r.debug({domNode:t},"Filtering out node since it has display none"),!1):!0}async function y0({node:t,parent:e,frameId:r,frameContext:n,axGraph:o,domGraph:i,inputNodeMap:a,explicitLabelTargetDomIds:s,flagNotActionableNodes:c,showZeroOpacityElements:l,filterByViewport:u,viewportDetails:d,useMPaths:p,importantProperties:m,allowedA11yIgnoreReasonsOverride:f,cdpClient:h,logger:S,callId:g}){if(!e&&t.parentId)throw new Error(`Got no parent for accessibility node ${t.nodeId}: ${JSON.stringify(t)}`);let E=(W,q={})=>{},y=t.backendDOMNodeId,b=FQ.includes(t.role?.value?.toLowerCase()??"");if(!b&&y===void 0)return E("Filtering out node since it doesn't exist in the DOM"),[];let C=y?i.backendIdToNode[y]:void 0;if(!b&&!C)try{let W=await J(h.send({method:"DOM.describeNode",params:{backendNodeId:y}}),{milliseconds:750,fallback:()=>{S.debug("Timeout getting node from CDP while processing a11y tree")}});if(W&&W.node.nodeName.toLowerCase()==="slot"&&W.node.distributedNodes?.length)S.debug({parentAXNode:e?.getNodeOnlySerializedForm(),originalAXNodeName:t.name?.value},"Redirecting node to assigned slot");else return E("Filtering out node since it doesn't exist in the DOM",{cdpResult:W?.node.name??W?.node.nodeName}),[]}catch(W){return E("Filtering out node since it doesn't exist in the DOM",{err:W}),[]}if(C&&e&&u&&d&&t.backendDOMNodeId&&!jQ(C,d,S,g))return C.momenticIgnored=!0,[];if(C&&C.computedStyles.display==="none")return C.momenticIgnored=!0,[];if(C&&C.computedStyles.opacity==="0"&&l!==!0){if(l==="inputs-only"&&C.tagName.toLowerCase()!=="input")return C.momenticIgnored=!0,[];if(l===!1)return C.momenticIgnored=!0,[]}let I=t.name?.value?typeof t.name.value=="string"?t.name.value:`${t.name.value}`:"",_=t.value?.value?typeof t.value.value=="string"?t.value.value:`${t.value.value}`:"",R=new Av({domNode:C,id:parseInt(t.nodeId),role:t.role?.value||"",name:I,nameSources:t.name?.sources,content:_,properties:t.properties,children:[],ignoredReasons:t.ignoredReasons?.filter(W=>(f??g0).includes(W.name)||S0.includes(W.name))??[],pathFromRoot:(e?`${e.pathFromRoot} `:"")+GQ(t),backendNodeID:t.backendDOMNodeId,ignoredByCDP:t.ignored,internalProperties:{inCodeMirrorEditor:e?.internalProperties?.inCodeMirrorEditor},importantProperties:m,parentFrame:n.type==="root"?void 0:n,flagNotActionableNodes:c}),M=n,P=a[r],B=r;if(C?.tagName.toLowerCase()==="iframe"&&C.ownedFrameId){let W=n.childFrames.find(ne=>ne.frameId===C.ownedFrameId),q=o[W?.frameId??""]?.root,X=a[W?.frameId??""];if(W&&q&&X){t.childIds&&t.childIds.length>0&&S.debug("Replacing existing node's children with children from the iframe");let ne=q;t.childIds=ne.childIds,M=W,P=X,B=W.frameId}}let F=C?.childrenBackendIds?.length??0,G=(t.childIds??[]).filter(W=>!!P.get(parseInt(W))).length;if(F>G){let W=t.childIds?.map(X=>P.get(parseInt(X))).filter(Boolean).map(X=>X?.backendDOMNodeId).filter(X=>X!==void 0)??[],q=0;for(let X of C?.childrenBackendIds??[]){if(W.includes(X)){q=(t.childIds?.findIndex(be=>P.get(parseInt(be))?.backendDOMNodeId===X)??0)+1;continue}let ne=i.backendIdToNode[X];if(!ne||ne?.tagName.toLowerCase()!=="svg")continue;let de=Math.floor(-1*Math.random()*1e7),Te={nodeId:de.toString(),parentId:t.nodeId,ignored:!1,backendDOMNodeId:X,frameId:B,role:{type:"string",value:"graphics-symbol"}};P.set(de,Te),t.childIds||(t.childIds=[]),t.childIds.splice(q,0,de.toString()),q++}}if(t.childIds?.length===1&&C){let W=P.get(parseInt(t.childIds[0])),q=W?.role?.value,X=C.childrenBackendIds;if(W&&q==="StaticText"&&X.length===1){let ne=i.backendIdToNode[X[0]];if(ne?.tagName?.toLowerCase()==="span"){let de=Math.floor(-1*Math.random()*1e7).toString(),Te={nodeId:de,parentId:t.nodeId,ignored:!1,backendDOMNodeId:ne.backendNodeId,frameId:B,childIds:[W.nodeId]};W.parentId=de,P.set(parseInt(de),Te),t.childIds=[de]}}}if(C?.tagName.toLowerCase()==="label"){let W=C.attributes.for?.trim();W&&s.add(W)}for(let W of t.childIds??[]){if(!W)continue;let q=P.get(parseInt(W));if(!q)continue;let X=await y0({node:q,parent:R,domGraph:i,explicitLabelTargetDomIds:s,axGraph:o,frameId:B,frameContext:M,inputNodeMap:a,cdpClient:h,logger:S,callId:g,filterByViewport:u,showZeroOpacityElements:l,importantProperties:m,viewportDetails:d,useMPaths:p,flagNotActionableNodes:c});X.length&&(R.children=R.children.concat(X))}if(R.role==="StaticText"&&(R.children=[]),R.role==="ListMarker")if(R.children.length!==1||R.children[0].role!=="StaticText")S.debug({childLen:R.children.length,childRoles:R.children.map(W=>W.role),childTags:R.children.map(W=>W.tagName),currentTag:R.tagName,currentName:R.name},"Unexpected ListMarker structure (processA11yTreeDFS)");else return R.children;if(R.children.length===1&&R.children[0].role==="StaticText"){let W=R.name,X=R.children[0].name;(W===X||!X)&&(R.name="")}let z=[];for(let W=R.children.length-1;W>=0;W--){let q=R.children[W];if(q.role!=="StaticText"){z.push(q);continue}if(W===0||R.children[W-1].role!=="StaticText"){z.push(q);continue}R.children[W-1].name+=q.name}if(R.children=z.reverse(),!R.isInteresting(m)&&t.parentId)return C&&(C.momenticIgnored=!0),R.children;for(let W of R.children)W.parent=R;return $Q(R),C&&p&&Tv(C,i),[R]}function E0({node:t,a11yIdNodeMap:e,dataMomenticIdMap:r,logger:n,callId:o,domGraph:i,useMPaths:a,selectorToNodeMap:s,nodeIdHasPointingLabelMap:c,explicitLabelTargetDomIds:l,iconKnowledgeBase:u,startId:d=1}){t.id=d,d+=1,e[t.id]=t,t.dataMomenticId?r[t.dataMomenticId]=t:Rv.includes(t.role);let p=t.backendNodeId,m=p!==void 0?i.backendIdToNode[p]:void 0;a&&m&&m.mPathSelector&&(s[m.mPathSelector]=t,t.mPathSelector=m.mPathSelector);let f=m?.attributes.id?.trim();if(f&&l.has(f)&&(t.internalProperties.hasExplicitPointingLabel=!0,c[t.id]=!0),u&&m&&m.tagName?.toLowerCase()==="svg"){let h=Ev(m,i),S=h?u[h.hash]:void 0,g=S?S.description:void 0;S&&(t.properties["data-momentic-description"]=g)}for(let h of t.children)d=E0({node:h,a11yIdNodeMap:e,dataMomenticIdMap:r,logger:n,callId:o,startId:d,useMPaths:a,domGraph:i,selectorToNodeMap:s,nodeIdHasPointingLabelMap:c,explicitLabelTargetDomIds:l,iconKnowledgeBase:u});return d}async function T0({rawA11yGraph:t,domGraph:e,startingFrameId:r,logger:n,cdpClient:o,filterByViewport:i,showZeroOpacityElements:a,flagNotActionableNodes:s,importantProperties:c,viewportDetails:l,useMPaths:u,frameContext:d,iconKnowledgeBase:p,allowedA11yIgnoreReasonsOverride:m}){let f=r??"root",h=t[f]?.root;if(!h)throw new Error("A11y tree has no root");let S=IQ(),g=new Set,E=M=>{let P=M.allNodes.filter(F=>!F.ignoredReasons?.find(z=>(m??g0).includes(z.name))),B=new Map;return P.forEach(F=>{B.set(parseInt(F.nodeId),F)}),B},y={};Object.entries(t).forEach(([M,P])=>{y[M]=E(P)});let b=await y0({node:h,domGraph:e,explicitLabelTargetDomIds:g,parent:null,inputNodeMap:y,axGraph:t,frameId:f,frameContext:d,cdpClient:o,logger:n,callId:S,showZeroOpacityElements:a,importantProperties:c,filterByViewport:i,viewportDetails:l,useMPaths:u,flagNotActionableNodes:s,allowedA11yIgnoreReasonsOverride:m});if(b.length>1)throw new Error(`Something went horribly wrong processing the a11y tree, we got: ${JSON.stringify(b)}`);if(b.length===0)throw new Error("There are no accessible elements on this page or frame. Are you sure this website loads properly?");let C={},I={},_={},R={};return E0({node:b[0],a11yIdNodeMap:C,dataMomenticIdMap:I,selectorToNodeMap:_,nodeIdHasPointingLabelMap:R,explicitLabelTargetDomIds:g,domGraph:e,logger:n,callId:S,useMPaths:u,iconKnowledgeBase:p}),new Cv(b[0],C,I,_,R)}function VQ(t,e,r,n){if(t==="class"){if(PQ.includes(r.tagName?.toLowerCase()??""))return e.split(" ").filter(a=>a.length<vv&&!Cn.bannedClassSubstrings.some(s=>a.includes(s))).slice(0,3).join(" ");let o=e.split(" "),i=[];for(let a of o)if(b0(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=Number(e);if(!Number.isNaN(o))return o}catch{}return t==="src"&&e.includes("base64")?e.slice(0,e.indexOf("base64")+6)+"...":e.length>60?e.slice(0,50)+"...":e}function WQ(t,e,r){if(!e)return;Object.entries(e.attributes).forEach(([a,s])=>{let c=t[a]||a.startsWith("aria")||LQ.includes(a);if((Cn.relevantElementAttributes.includes(a)||v0(a,r))&&!c){let u=VQ(a,s,e,r);u!==null&&(t[a]=u)}});let n,o=[];if(e.computedStyles.position&&m0.includes(e.computedStyles.position))n=e.computedStyles.position;else if(e.attributes.style){for(let a of m0)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 r?.styles??[]){let s=a.split(":"),c=s[0]?.trim(),l=s[1]?.trim(),u=e.computedStyles[c??""];if(c!==void 0&&l!==void 0&&u!==void 0&&(l==="*"||u===l)){let d=e.computedStyles[c],p=`${c}: ${d}`;o.includes(p)||o.push(p)}}o.length>0&&(t.style=o.join("; "))}function $Q(t){let e=t.properties.class;if(typeof e=="string"&&e.includes("cm-content")){t.children.forEach((i,a)=>{i.properties["cm-line-number"]=`${a+1}`});return}if(typeof e=="string"&&e.includes("notion-page-content")){t.children.forEach((i,a)=>{i.properties["block-number"]=`${a+1}`}),t.children.length>0&&(t.children[t.children.length-1].properties.description="This is the last block in the document. Click here to add new text to the end.");return}if(t.tagName==="table"){let i=[],a=t.children.find(c=>c.tagName==="thead");if(a){let c=a.children.find(l=>l.tagName==="tr");if(c){let l=c.children.filter(u=>u.tagName==="th");l.forEach((u,d)=>{u.properties["col-index"]||(u.properties["col-index"]=d+1),i?.push(vt(u.name,100,!1))}),i?.length!==l.length&&(i=void 0)}}let s=0;for(let c of t.children)if(c.tagName==="tbody")for(let l=0;l<c.children.length;l++){let u=c.children[l];if(u.tagName!=="tr")continue;if(l===0&&!i?.length){let m=u.children.filter(f=>f.tagName==="th");if(m.length){if(i=m.map(f=>vt(f.name,100,!1)),i.length===m.length)continue;i=void 0}}s+=1,u.properties["row-index"]||(u.properties["row-index"]=s);let d=u.children.filter(m=>m.tagName==="td"||m.tagName==="th"),p=d.length===i?.length;d.forEach((m,f)=>{m.tagName!=="th"&&(m.properties["col-index"]||(m.properties["col-index"]=f+1),p&&(m.properties.col||(m.properties.col=i[f])))})}}}function qQ(t){let e=t.properties.class,r=typeof e=="string"&&e.includes("cm-content");t.internalProperties.inCodeMirrorEditor=t.internalProperties?.inCodeMirrorEditor||r}function b0(t,e){if(e&&A0(t,e))return!0;if(Cn.bannedClassSubstrings.some(r=>t.includes(r)))return!1;if(Cn.alwaysInterestingClassNames.includes(t))return!0;for(let r of Cn.alwaysInterestingClassPrefixes)if(t.startsWith(r))return!0;return!1}function v0(t,e){if(e?.attributes?.includes(t))return!0;for(let r of e?.attributes??[])if(r.endsWith("*")){let n=r.slice(0,-1);if(t.startsWith(n))return!0}return!1}function A0(t,e){if(e?.classes?.includes(t))return!0;for(let r of e?.classes??[])if(r.endsWith("*")){let n=r.slice(0,-1);if(t.startsWith(n))return!0}return!1}var KQ=["Accessibility","DOMSnapshot","DOMStorage"],dg=class t{constructor(e,r,n,o,i){this.session=e;this.logger=r;this.contextGetter=n;this.pageGetter=o;this.defaultTimeoutMs=i}cdpInitializingPromise=void 0;cdpCrashDetails=void 0;cdpFullyDead=!1;scopedDomainQueues={};scopedDomainScopeCounts={};static async init({logger:e,contextGetter:r,pageGetter:n,defaultTimeoutMs:o}){let i=r(),a=n(),s,c;for(let u=0;u<2;u++)try{s=await J(i.newCDPSession(a),{milliseconds:o*u,fallback:()=>{throw new L("UserInfrastructureError",`Failed to initialize Chrome session within the page load timeout (${a.url()})`)}});break}catch(d){await xe(dr),c=d}if(!s)throw c;let l=new t(s,e,r,n,o);try{await J(l.registerHandlers(s),{milliseconds:o,message:`CDP handler registration timed out after ${o}ms`})}catch(u){throw l.cdpFullyDead=!0,new L("UserInfrastructureError",`Failed to initialize CDP client: ${u}`)}return l}async registerHandlers(e){e.on("Target.attachedToTarget",async()=>{try{await e.send("Runtime.runIfWaitingForDebugger")}catch(r){this.logger.warn({err:r},"Failed to run Runtime.runIfWaitingForDebugger")}}),e.on("Target.targetCrashed",r=>{this.cdpCrashDetails={...this.cdpCrashDetails??{},targetCrashDetails:JSON.stringify(r)},this.logger.error({payload:r},"CDP session crashed, Momentic will likely not function correctly")}),e.on("Inspector.targetCrashed",r=>{this.cdpCrashDetails={...this.cdpCrashDetails??{},inspectorCrashDetails:JSON.stringify(r)},this.logger.error({payload:r},"CDP inspector session crashed, Momentic will likely not function correctly")}),await Promise.all([e.send("Page.enable"),e.send("DOM.enable"),e.send("CSS.enable"),e.send("Overlay.enable")])}async send({method:e,params:r,timeout:n=this.defaultTimeoutMs,timeoutMsg:o}){let i=this.getScopedDomainForMethod(e);return i?(this.scopedDomainScopeCounts[i]??0)>0?this.sendWithoutScopedDomain({method:e,params:r,timeout:n,timeoutMsg:o}):this.sendWithScopedDomain({domain:i,method:e,params:r,timeout:n,timeoutMsg:o}):this.sendWithoutScopedDomain({method:e,params:r,timeout:n,timeoutMsg:o})}getScopedDomainForMethod(e){let r=e;for(let n of KQ)if(r.startsWith(`${n}.`)&&r!==`${n}.enable`&&r!==`${n}.disable`)return n}async withDomainEnabled({domain:e,timeout:r=this.defaultTimeoutMs,fn:n}){if((this.scopedDomainScopeCounts[e]??0)>0){this.scopedDomainScopeCounts[e]=(this.scopedDomainScopeCounts[e]??0)+1;try{return await n()}finally{let o=Math.max((this.scopedDomainScopeCounts[e]??1)-1,0);this.scopedDomainScopeCounts[e]=o,o===0&&await this.withDomainLock(e,async()=>{if(!((this.scopedDomainScopeCounts[e]??0)>0))try{await this.sendWithoutScopedDomain({method:`${e}.disable`,params:void 0,timeout:r})}catch(i){this.logger.warn({err:i,domain:e},`Failed to disable ${e} domain after scoped CDP command block`)}})}}return this.withDomainLock(e,async()=>{await this.sendWithoutScopedDomain({method:`${e}.enable`,params:void 0,timeout:r}),this.scopedDomainScopeCounts[e]=(this.scopedDomainScopeCounts[e]??0)+1;try{return await n()}finally{let o=Math.max((this.scopedDomainScopeCounts[e]??1)-1,0);if(this.scopedDomainScopeCounts[e]=o,o===0)try{await this.sendWithoutScopedDomain({method:`${e}.disable`,params:void 0,timeout:r})}catch(i){this.logger.warn({err:i,domain:e},`Failed to disable ${e} domain after scoped CDP command block`)}}})}async withDomainLock(e,r){let n=this.scopedDomainQueues[e]??Promise.resolve(),o,i=new Promise(a=>{o=a});this.scopedDomainQueues[e]=n.catch(()=>{}).then(()=>i),await n.catch(()=>{});try{return await r()}finally{o?.()}}async sendWithScopedDomain({domain:e,method:r,params:n,timeout:o,timeoutMsg:i}){return this.withDomainLock(e,async()=>{try{return await this.sendWithoutScopedDomain({method:`${e}.enable`,params:void 0,timeout:o}),await this.sendWithoutScopedDomain({method:r,params:n,timeout:o,timeoutMsg:i})}finally{try{await this.sendWithoutScopedDomain({method:`${e}.disable`,params:void 0,timeout:o})}catch(a){this.logger.warn({err:a,domain:e},`Failed to disable ${e} domain after scoped CDP command`)}}})}async sendWithoutScopedDomain({method:e,params:r,timeout:n=this.defaultTimeoutMs,timeoutMsg:o}){for(;this.cdpInitializingPromise;)await J(this.cdpInitializingPromise,{milliseconds:n});if(this.cdpCrashDetails){if(this.cdpFullyDead)throw new L("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 J(this.session.send(e,r),{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 r=e,n=this.pageGetter(),o=await J(this.contextGetter().newCDPSession(n),{milliseconds:r,fallback:()=>{throw this.logger.warn(`Failed to initialize CDP session within the page load timeout (${n.url()})`),new L("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 r=this.session;this.session=await this.createRawCDPSession(e),await J(this.registerHandlers(this.session),{milliseconds:e,message:`Failed to register CDP handlers within ${e}ms`}),this.scopedDomainQueues={},this.scopedDomainScopeCounts={},this.logger.debug("Successfully reinitialized and attached new handlers to CDP session");try{await J(r.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(r){this.cdpCrashDetails={...this.cdpCrashDetails??{},reinitializeError:`${r}`},this.cdpFullyDead=!0}finally{this.cdpInitializingPromise=void 0}})(),await this.cdpInitializingPromise}on(e,r){return this.session.on(e,r),this.session}off(e,r){return this.session.off(e,r),this.session}addListener(e,r){return this.session.addListener(e,r),this.session}removeListener(e,r){return this.session.removeListener(e,r),this.session}};var Oc="<empty>";function YQ(t){return t.includes("doubleclick.net")||t.includes("googletagmanager.com")||t.includes("googlesyndication.com")||t.includes("s.amazon-adsystem.com")||t.includes("smartadserver.com")||t.includes("omnitagjs.com")||t.includes("x.adroll.com")}function R0(t){let e=t.adFrameStatus?.adFrameType;return e==="child"||e==="root"||YQ(t.url)}async function XQ(t,e){let r=await t.send({timeout:pe,method:"DOM.getFrameOwner",params:{frameId:e}}),o=(await t.send({timeout:pe,method:"DOM.pushNodesByBackendIdsToFrontend",params:{backendNodeIds:[r.backendNodeId]}})).nodeIds[0],a=(await t.send({timeout:pe,method:"DOM.describeNode",params:{backendNodeId:r.backendNodeId}})).node;return a.nodeId=o,a}async function Lc({cdpClient:t,page:e,logger:r}){let n={type:"root",childFrames:[],page:e},o=[],[i,a]=await Promise.all([t.send({timeout:Mc,method:"Page.getFrameTree",params:{}}),t.send({timeout:Mc,method:"DOM.getDocument",params:{depth:0}})]),l=(i.frameTree.childFrames??[]).map(async(d,p)=>{if(R0(d.frame))return null;try{return await w0({cdpClient:t,rawFrameTree:d,indices:[p],parent:n,warnings:o,logger:r})}catch(m){return o.push(`Failed to get child frame: ${m}`),null}}),u=await Promise.all(l);return n.childFrames=u.filter(d=>d!==null),o.length&&r?.warn({warnings:o},"Got warnings when fetching frame tree"),n}async function w0({cdpClient:t,rawFrameTree:e,indices:r,parent:n,warnings:o,logger:i}){let a=e.frame.id,s=await XQ(t,a),c=s.attributes??[],l=null,u=[];for(let f of["src","name","id","title","srcdoc","sandbox"]){let h=va(c,f);h&&(u.push(`${f}=${JSON.stringify(h)}`),f==="src"&&(l=h))}let d={type:"frame",cdpFrame:e.frame,url:e.frame.url,frameId:a,locationData:{indices:r,attributeSelectors:u},src:l,childFrames:[],parent:n,domNode:s},m=(e.childFrames??[]).map(async(f,h)=>{if(R0(f.frame))return null;try{return await w0({cdpClient:t,rawFrameTree:f,indices:[...r,h],parent:d,warnings:o,logger:i})}catch(S){return o.push(`Failed to get child frame (child ${h} of frame with url ${e.frame.url}): ${S}`),null}});return d.childFrames=(await Promise.all(m)).filter(f=>f!==null),d}async function JQ(t){try{return await t.owner().count()===1}catch{return!1}}async function QQ(t){try{return await t.count()===1}catch{return!1}}async function Zo(t,e){let r=[],n=t;for(;n.parent.type==="frame";)r.push(n.parent),n=n.parent;r.reverse();let o=e,i=[];for(let l of r){let u=!1;for(let d of[...l.locationData.attributeSelectors,Oc]){let p=o.frameLocator(d===Oc?"iframe":`iframe[${d}]`);if(await JQ(p)){u=!0,o=p,i.push(d);break}}if(!u)throw new L("ActionFailureError",`Failed to find a unique attribute to identify intermediate frame with url matching '${l.url}'. Please attach a unique 'id', 'name', 'title', or 'src' attribute to the frame.`)}let a;for(let l of[...t.locationData.attributeSelectors,Oc]){let u=o.locator(l===Oc?"iframe":`iframe[${l}]`);if(await QQ(u)){a=u,i.push(l);break}}if(!a)throw new L("ActionFailureError",`Failed to find a unique attribute to identify target frame with url matching '${t.url}'. Please attach a unique 'id', 'name', 'title', or 'src' attribute to the frame.`);let s=await a.evaluateHandle(l=>l),c=await s.asElement().contentFrame();if(!c)throw new L("InternalWebAgentError",`Failed to load Playwright Frame for iframe with url '${t.url}'`);return await s.dispose(),{frame:c,mPathSelectorTokens:i}}function C0(t,e){let r=[...t],n=[];for(;r.length;){let o=r.shift();e(o)&&n.push(o),r.push(...o.childFrames)}return n}async function x0({page:t,frameTree:e,cache:r}){let n,o=e.childFrames,i=[];if(r.mPathSelectorTokens.length){let s=o;for(let u=0;u<r.mPathSelectorTokens.length-1;u++){let d=r.mPathSelectorTokens[u];d===Oc?s=s.length===1?s[0].childFrames:[]:s=s.filter(p=>p.locationData.attributeSelectors.includes(d)).map(p=>p.childFrames).flat()}let c=[],l=r.mPathSelectorTokens[r.mPathSelectorTokens.length-1];if(l===Oc?c=s:c=s.filter(u=>u.locationData.attributeSelectors.includes(l)),c.length===1)return n=c[0],i.push(`Found unique frame with mpath ${r.mPathSelectorTokens.join(" > ")}`),{resolution:{type:"auto",frame:(await Zo(n,t)).frame,handle:n,mPathSelectorTokens:r.mPathSelectorTokens,frameTree:e},logs:i};i.push(`Found ${c.length} frames with mpath ${r.mPathSelectorTokens.join(" > ")}`)}if(r.frameSrcRegex){let s=new RegExp(r.frameSrcRegex),c=C0(o,l=>!!l.src&&s.test(l.src));if(c.length===1)return n=c[0],i.push(`Found unique frame with src regex ${r.frameSrcRegex}`),{resolution:{type:"auto",frame:(await Zo(n,t)).frame,handle:n,mPathSelectorTokens:r.mPathSelectorTokens,frameTree:e},logs:i};i.push(`Found ${c.length} frames with src regex ${r.frameSrcRegex}`),r.frameSrcRegex=void 0}if(r.frameUrlRegex){let s=new RegExp(r.frameUrlRegex),c=C0(o,l=>!!l.url&&s.test(l.url));if(c.length===1)return n=c[0],i.push(`Found unique frame with url regex ${r.frameUrlRegex}`),{resolution:{type:"auto",frame:(await Zo(n,t)).frame,handle:n,mPathSelectorTokens:r.mPathSelectorTokens,frameTree:e},logs:i};i.push(`Found ${c.length} frames with url regex ${r.frameUrlRegex}`),r.frameUrlRegex=void 0}let a=o;for(let s=0;s<r.indices.length-1;s++)a=a[r.indices[s]]?.childFrames??[];if(n=a[r.indices[r.indices.length-1]],n)return i.push(`Found unique frame with indices ${r.indices.join(" > ")}`),{resolution:{type:"auto",frame:(await Zo(n,t)).frame,handle:n,mPathSelectorTokens:r.mPathSelectorTokens,frameTree:e},logs:i};throw i.push(`Found ${a.length} frames with indices ${r.indices}`),new fn("Failed to find the iframe that previously contained this element",[{type:"AUTO_FRAME",matched:!1,logs:i}],"could-not-find-iframe")}function pg(t){return t.type==="auto"?JSON.stringify({type:"auto",frameId:t.handle.frameId}):JSON.stringify(t)}function wv(t){for(;t.parent.type==="frame";)t=t.parent;return t.parent}function _0(t){let e=wv(t),r=t.src??"",n=t.url??"",o=[],i=[],a=[...e.childFrames];for(;a.length;){let s=a.shift();s.src&&o.push(s.src),s.url&&i.push(s.url),a.push(...s.childFrames)}return{srcs:o,urls:i,desiredSrc:r,desiredUrl:n}}function I0(t){return t.type==="auto"?{type:"auto",frameId:t.handle.frameId,url:t.handle.url,src:t.handle.src??"",mPathSelectorTokens:t.mPathSelectorTokens.join(" > ")}:{type:"url",url:t.url}}async function P0({frame:t,logger:e,signal:r}){let n;try{n=await t.frameElement(),await ZQ({frameElementHandle:n,logger:e,signal:r})}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 ZQ({frameElementHandle:t,logger:e,signal:r}){let n=await t.boundingBox(),i=await Wd({promiseGenerator:async()=>t.evaluate(async a=>{let s=a.scrollTop,c=a.getBoundingClientRect(),l=0,u=0,d=window.innerWidth,p=window.innerHeight;if(c.top>=l&&c.left>=u&&c.bottom<=p&&c.right<=d)return{didScroll:!1,reason:"already-fully-visible"};a.scrollIntoView({behavior:"instant",block:"center",inline:"center"}),await new Promise(g=>setTimeout(g,250));let f=Date.now();for(;Date.now()-f<1e3;){let g=a.scrollTop;if(g===s)break;s=g,await new Promise(E=>setTimeout(E,250))}let h=a.getBoundingClientRect();return h.top!==c.top||h.left!==c.left||h.right!==c.right||h.bottom!==c.bottom?{didScroll:!0,reason:"scrolled",afterRect:h}:{didScroll:!1,reason:"no-more-scroll-possible",afterRect:h}}),timeoutMs:st,codePath:"scrollIframeIntoView",signal:r});i.didScroll&&e.info({oldBb:n,newBb:await t.boundingBox(),evalResult:i},"Successfully scrolled iframe into view")}var xv=()=>{let t,e,r=new Promise((n,o)=>{t=n,e=o});return{resolve:t,reject:e,value:r}};var M0=(t,e)=>{let r=t.name??`batcher:${Math.random().toString(16).slice(2)})`,n=t.scheduler??e8(10),o=globalThis.__BATSHIT_DEVTOOLS__?.for(r),i=e??{seq:0,batch:new Set,currentRequest:xv(),timer:void 0,start:null,latest:null,abortController:new AbortController};o?.create({seq:i.seq});let a=()=>{i.batch=new Set,i.currentRequest=xv(),i.timer=void 0,i.start=null,i.latest=null,i.abortController=new AbortController},s=()=>{let d=i.seq,p=t.fetcher([...i.batch],i.abortController.signal),m=i.currentRequest;return o?.fetch({seq:d,batch:[...i.batch]}),a(),p.then(f=>{o?.data({seq:d,data:f}),m.resolve(f)}).catch(f=>{o?.error({seq:d,error:f}),m.reject(f)}),i.seq++,p};return{fetch:d=>{i.start||(i.start=Date.now()),i.latest=Date.now(),i.batch.add(d),clearTimeout(i.timer);let p=n(i.start,i.latest,i.batch.size);if(o?.queue({seq:i.seq,query:d,batch:[...i.batch],scheduled:p,latest:i.latest,start:i.start}),p==="immediate"){let m=i.currentRequest;return s(),m.value.then(f=>t.resolver(f,d))}else return p==="never"?i.currentRequest.value.then(m=>t.resolver(m,d)):(i.timer=setTimeout(s,p),i.currentRequest.value.then(m=>t.resolver(m,d)))},next:()=>{s()},abort:()=>{i.abortController.abort(),i.currentRequest.reject(new DOMException("Aborted","AbortError")),a()}}};var e8=t=>(e,r)=>{let n=r-e;return t-n};var O0=({windowMs:t,maxBatchSize:e})=>(r,n,o)=>{if(o>=e)return"immediate";let i=n-r;return t-i};import{reduce as t8}from"lodash-es";var r8=100,n8=2e3;function L0(t){return M0({fetcher:async r=>{t(t8(r,(n,o)=>({...n,...o}),{}))},resolver:()=>{},scheduler:O0({windowMs:n8,maxBatchSize:r8})})}async function N0({event:t,transformer:e,enricher:r,frame:n,lastScreenshotForRecording:o,logger:i}){let{warnings:a,error:s,properties:c}=t.target;if(s){i.error({error:s,warnings:a},"Error while capturing passive click");return}if(a.length&&i.warn({warnings:a},"Warnings while capturing passive click"),!c)return;let l=n.parentFrame()?n.url():void 0,d=n.page().frames().map(f=>f.url());i.debug({frameUrl:l,...t},"Passive click event captured on element");let p,m;if(l)try{let f=await n.frameElement();p=await J(f?.boundingBox(),{milliseconds:pe})??void 0;let h=await r.constructIframeRegex({urls:d,srcs:[],desiredUrl:l});if(h.urlRegex)m={type:"url",url:`/${h.urlRegex}/`};else throw new Error(`Got no url regex options: ${JSON.stringify(h)}`)}catch(f){i.warn({err:f},"Failed to construct iframe details for recorded action, using hardcoded URL only"),m={type:"url",url:l}}(async()=>{try{await e.recordElementAction({...t,screenshotBase64:o,frameConfig:m,frameBoundingBox:p})}catch(f){i.error({err:f},"Failed to transform passive click action")}})()}import{randomUUID as ei}from"crypto";import o8 from"js-beautify";var i8=["Dead"],mg=class{recordedSteps=new Map;callbacks;signal;generator;testId;orgId;nextStepOffset=0;logger;constructor({signal:e,callbacks:r,generator:n,testId:o,orgId:i,logger:a}){this.signal=e,this.logger=a,this.testId=o,this.orgId=i,this.callbacks={onStepRecorded:(s,c)=>{this.recordedSteps.set(c,{step:s}),r.onStepRecorded(s,c)},onActionReceived:(s,c)=>{this.recordedSteps.set(c,{step:s}),r.onActionReceived?.(s,c)}},this.generator=n}reserveIndexForCommand(e){let r=this.nextStepOffset;return this.recordedSteps.set(r,{step:{id:ei(),type:"PRESET_ACTION",command:ci(e)}}),this.nextStepOffset++,r}async recordElementAction(e){let{type:r,target:n,frameConfig:o}=e;if(this.signal.aborted){this.logger.debug("Transformer was already cleaned up, ignoring click...");return}let i,a,s=n.properties.attributes.nodeOnlySerializedHtml.trim(),c=s,l;switch(e.frameConfig?e.frameBoundingBox?l={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"):l=n.properties.boundingBox,r){case"CLICK":{i="CLICK";let h=ci(i);a={id:ei(),type:"PRESET_ACTION",command:{...h,target:{type:"description",elementDescriptor:c},iframeUrl:o?.url,cache:{target:{id:-1,...n.properties.attributes,targetSource:"RECORDING",targetUpdateTime:new Date().toUTCString(),boundingBox:l}}}};break}case"SELECT":{i="SELECT_OPTION";let h=ci(i);a={id:ei(),type:"PRESET_ACTION",command:{...h,type:"SELECT_OPTION",iframeUrl:o?.url,target:{type:"description",elementDescriptor:c},cache:{target:{id:-1,...n.properties.attributes,targetSource:"RECORDING",targetUpdateTime:new Date().toUTCString(),boundingBox:l}},choice:{type:"VALUE",value:e.selectedValue??"Unknown option"}}};break}case"MOUSE_DRAG":{i="MOUSE_DRAG";let h=ci(i);a={id:ei(),type:"PRESET_ACTION",command:{...h,target:{type:"description",elementDescriptor:c},deltaX:e.deltaX.toString(),deltaY:e.deltaY.toString(),iframeUrl:o?.url,cache:{target:{id:-1,...n.properties.attributes,targetSource:"RECORDING",targetUpdateTime:new Date().toUTCString(),targetUpdateLoggerTags:ot(this.logger),boundingBox:l}}}};break}default:throw new Error(`Unknown action type: ${r}`)}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=o8.html(d,{indent_size:1,indent_with_tabs:!1,preserve_newlines:!1}),d=ak(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,...ot(this.logger)}})).phrase}catch(h){this.logger.error({err:h},"Error generating reverse mapping description"),p=s}let m=this.recordedSteps.get(u)?.step??a,f=m?.command;f&&"target"in f&&f.target?(f.target={type:"description",elementDescriptor:p},this.callbacks.onStepRecorded({...m,command:f},u)):this.logger.warn("Could not find existing command to update after description mapping")}recordKeystroke(e){let{key:r,combinable:n}=e;if(i8.includes(r)||this.signal.aborted)return;let o="normal";r.length>1&&(o="special");let i;if(o==="normal"){let d=ci("TYPE");i={id:ei(),type:"PRESET_ACTION",command:{...d,target:void 0,value:r,clearContent:!1}}}else{let d=ci("PRESS");i={id:ei(),type:"PRESET_ACTION",command:{...d,value:r}}}let a,s=this.nextStepOffset-1,c=this.recordedSteps.get(s),l=c?.step,u=l?.command;if(n){if(u?.type===i.command.type){let d=u.value,p=i.command.value;i={id:ei(),type:"PRESET_ACTION",command:{...u,value:i.command.type==="PRESS"?`${d}+${p}`:`${d}${p}`}},a=s}else if(u?.type==="CLICK"&&i.command.type==="TYPE")l.command={...i.command,target:u.target,cache:u.cache},i=c.step,a=s;else if(u?.type==="TYPE"&&i.command.type==="PRESS"&&i.command.value==="Backspace"){let d=u.value;i={id:ei(),type:"PRESET_ACTION",command:{...u,value:d.slice(0,d.length-1)}},a=s}}a===void 0&&(a=this.nextStepOffset,this.nextStepOffset++),this.callbacks.onStepRecorded(i,a)}recordScroll(e){if(this.signal.aborted)return;let r=()=>{let{deltaY:i}=e;if(!i)return;let a=this.nextStepOffset-1,s=this.recordedSteps.get(a)?.step.command,c;s?.type==="SCROLL_DOWN"&&s.deltaY?(i+=s.deltaY,c=a):s?.type==="SCROLL_UP"&&s.deltaY?(i-=s.deltaY,c=a):(c=this.nextStepOffset,this.nextStepOffset++);let l=i>0?"SCROLL_DOWN":"SCROLL_UP",u=ci(l);u.deltaY=Math.abs(i);let d={id:ei(),type:"PRESET_ACTION",command:u};this.callbacks.onStepRecorded(d,c)},n=()=>{let{deltaX:i}=e;if(!i)return;let a=this.nextStepOffset-1,s=this.recordedSteps.get(a)?.step.command,c;s?.type==="SCROLL_RIGHT"&&s.deltaX?(i+=s.deltaX,c=a):s?.type==="SCROLL_LEFT"&&s.deltaX?(i-=s.deltaX,c=a):(c=this.nextStepOffset,this.nextStepOffset++);let l=i>0?"SCROLL_RIGHT":"SCROLL_LEFT",u=ci(l);u.deltaX=Math.abs(i);let d={id:ei(),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&&r()):(r(),e.deltaX>=20&&n())}};import{z as _v}from"zod";var S8e=_v.object({type:_v.literal("url"),url:_v.string()});var fg=class{smartWaitingTimeoutMs;pageLoadTimeoutMs;allowPartialAccessibilityTree;logger;cdpClient;pageGetter;abortSignalGetter;userControlledBrowserSettings;enricher;iconKnowledgeBase;computedStylesToFetch=["display","opacity","visibility","height","position","background-image"];activeFrameCache;activeFrameConfig;lastA11yIdToNodeMap={};lastDataMomenticIdToNodeMap={};lastSelectorToNodeMap={};lastA11yTreeRoot;lastDomGraph;lastA11yTreeFetchTimeMs;allowedA11yIgnoreReasonsOverride;constructor({smartWaitingTimeoutMs:e,pageLoadTimeoutMs:r,allowPartialAccessibilityTree:n,logger:o,cdpClient:i,pageGetter:a,abortSignalGetter:s,enricher:c,iconKnowledgeBase:l,userBrowserSettings:u,allowedA11yIgnoreReasonsOverride:d}){if(this.smartWaitingTimeoutMs=e,this.pageLoadTimeoutMs=r,this.allowPartialAccessibilityTree=n,this.logger=o,this.cdpClient=i,this.pageGetter=a,this.abortSignalGetter=s,this.enricher=c,this.iconKnowledgeBase=l,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 f=m[0]?.trim(),h=m[1]?.trim();if(f===void 0||h===void 0){this.logger.warn({style:p},"Invalid style property passed to importantStyles");continue}this.computedStylesToFetch.includes(f)||this.computedStylesToFetch.push(f)}}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,this.lastA11yTreeFetchTimeMs=void 0}saveAutoFrameCacheDetails(e){if(!this.activeFrameConfig||this.activeFrameConfig.type!=="auto"||!this.userControlledBrowserSettings.autoExpandIframes)return;let r={...e,indices:this.activeFrameConfig.handle.locationData.indices,mPathSelectorTokens:this.activeFrameConfig.mPathSelectorTokens};return this.constructIframeRegexAsync(this.activeFrameConfig.handle,r),r}async getAutoFrameDetailsFromHandle(e){let r=this.pageGetter(),n=wv(e),{frame:o,mPathSelectorTokens:i}=await Zo(e,r),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 r=this.pageGetter(),n=await Lc({cdpClient:this.cdpClient,page:r,logger:this.logger}),{resolution:o,logs:i}=await x0({page:r,frameTree:n,cache:e});return this.logger.info({logs:i},"Resolved auto frame cache"),{...o,cache:e}}async resolveActiveFrameConfig({logger:e=this.logger,signal:r=this.abortSignalGetter()}){if(!this.frameConfig)return null;if(this.activeFrameCache)if(pg(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:r}):n={source:"auto",frame:this.frameConfig.frame,handle:this.frameConfig.handle,frameIdentifierStringified:pg(this.frameConfig),cacheTime:Date.now(),frameTree:this.frameConfig.frameTree,mPathSelectorTokens:this.frameConfig.mPathSelectorTokens},await P0({frame:n.frame,logger:e,signal:r}),this.activeFrameCache=n,n}async executeFunctionInAllFrames(e,r){let n=this.pageGetter(),o=await Lc({cdpClient:this.cdpClient,page:n,logger:this.logger}),i=[J(n.evaluate(e,r),{milliseconds:st})],a=Array.from(o.childFrames);for(;a.length>0;){let c=a.shift(),l=c.url;l==="about:blank"||l.startsWith("chrome-error://")||(a.push(...c.childFrames),i.push(Zo(c,n).then(({frame:u})=>J(u.evaluate(e,r),{milliseconds:st})).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(),r=await Lc({cdpClient:this.cdpClient,page:e,logger:this.logger}),n=Array.from(r.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:r,logger:n}){let o=await this.getDOMTree({devicePixelRatio:e??1,signal:r,logger:n??this.logger});return this.lastDomGraph=o,o}async getA11yTree(e){let r={},n=e.logger??this.logger,o=e.abortSignal??this.abortSignalGetter(),{frameContext:i,startingFrameId:a}=await this.getFrameTreeAndAddMomenticIds({skipPageLoad:e.skipPageLoad,logger:n,signal:o,logTimings:r}),s=await ro({fn:()=>this.getDomGraph({devicePixelRatio:e.devicePixelRatio??1,signal:o,logger:n}),codePath:"domFetch",logObject:r,signal:o,logger:n}),c=await ro({fn:()=>this.getRawA11yGraph({cdpClient:this.cdpClient,frameId:a,childFrames:i.childFrames,logTimings:r,logger:n,signal:o}),codePath:"totalA11yFetch",logObject:r,signal:o,logger:n}),{tree:l}=await ro({fn:()=>this.composeA11yDomGraph({opts:e,a11yGraph:c,domGraph:s,startingFrameId:a,frameContext:i,logger:n,iconKnowledgeBase:this.iconKnowledgeBase,showZeroOpacityElements:e.showZeroOpacityElements,flagNotActionableNodes:e.flagNotActionableNodes}),codePath:"a11yProcess",logObject:r,signal:o,logger:n});return Object.values(r).some(u=>u>750)&&n.warn({logTimings:r},"A11y tree fetch component took a long time"),this.lastA11yIdToNodeMap=l.a11yIdNodeMap,this.lastDataMomenticIdToNodeMap=l.dataMomenticIdMap,this.lastA11yTreeRoot=l.root,this.lastDomGraph=s,this.lastSelectorToNodeMap=l.selectorToNodeMap,this.lastA11yTreeFetchTimeMs=Date.now(),l}getNodeUsingDataMomenticId(e){if(this.lastA11yTreeFetchTimeMs&&!(Date.now()-this.lastA11yTreeFetchTimeMs>1e4))return this.lastDataMomenticIdToNodeMap[e]}async getFrameTreeAndAddMomenticIds({skipPageLoad:e,logger:r=this.logger,signal:n=this.abortSignalGetter(),logTimings:o}){let i=this.pageGetter();if(!e)try{await i.waitForLoadState("load",{timeout:this.pageLoadTimeoutMs})}catch(l){r.warn({err:l},"Failed to wait for page load event before a11y tree fetch, attempting to continue without it..."),await this.cdpClient.reinitialize()}let a,s,c=null;if(this.frameConfig?.type==="url"){if(a=await ro({fn:()=>this.resolveActiveFrameConfig({logger:r,signal:n}),codePath:"getActiveFrameDetails",logObject:o,signal:n,logger:r})??void 0,!a)throw new L("ActionFailureError","Got null frame details despite active frame config");s=a.handle,c=s.frameId}else this.userControlledBrowserSettings.autoExpandIframes?(s=await ro({fn:()=>Lc({cdpClient:this.cdpClient,page:this.pageGetter(),logger:r}),codePath:"getMomenticFrameTree",logObject:o,signal:n,logger:r}),c=null):(s={type:"root",page:i,childFrames:[]},c=null);return await ro({fn:async()=>this.addMomenticIds({rootPage:i,childFrames:s.childFrames,frameFilter:a?.frame,logger:r}),codePath:"addIdsToElement",logObject:o,signal:n,logger:r}),{startingFrameOverride:a,frameContext:s,startingFrameId:c}}async fetchA11yTreeForRecording(e,r){if(await this.getA11yTree({devicePixelRatio:e,abortSignal:r,logger:zo,filterByViewport:!1,flagNotActionableNodes:!1,skipPageLoad:!0}),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:r,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=u0({node:o,domGraph:this.domGraph});return d0(e,i)}else return n.domNode||this.logger.warn({a11yRole:n.role,content:n.content},"Attempting to get locator from a11y node with no DOM node"),this.getLocatorFromBackendId(r,n.backendNodeId)}async getLocatorFromBackendId(e,r){let n=await this.cdpClient.send({method:"DOM.resolveNode",params:{backendNodeId:r},timeout:st});if(!n||!n.object.objectId)throw new Error(`Could not resolve backend node ${r}`);let o;try{o=await p0(this.cdpClient,n.object.objectId)}catch(i){throw this.logger.debug({err:i,object:JSON.stringify(n.object)},"Failed to get ID attribute for target"),i}return e.locator(Ii(o))}getNodeUsingMPathSelector(e){let r=this.selectorToNodeMap[e];if(r)return r;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}}}async resolveUrlMatcherFrameConfig({config:e,signal:r=this.abortSignalGetter(),logger:n=this.logger}){let o=Date.now(),i,a,s,c=0;for(;Date.now()-o<this.smartWaitingTimeoutMs;)try{i=await Lc({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(l){if(s=l,l instanceof L&&l.reason==="UserInfrastructureError")throw l;c%3===0&&this.logger.warn({attempt:c,err:l},"Failed to resolve active frame, retrying..."),await xe(dr,r)}finally{c++}if(a)return{source:"url",frame:a.frame,handle:a.handle,frameIdentifierStringified:pg(e),cacheTime:Date.now(),frameTree:i,mPathSelectorTokens:[]};throw s}async getMatchingFrameByUrlWithCdp(e,r){let n=r.url,o=this.pageGetter(),i=Array.from(e.childFrames),a=[];for(;i.length>0;){let s=i.shift(),c=s.domNode;i.push(...s.childFrames);let l=va(c.attributes??[],"src"),u=c.contentDocument?.documentURL;if(!l&&!u){this.logger.debug("Skipping frame with no URL or src");continue}for(let d of[l,u])if(d){if(n.startsWith("/")&&n.endsWith("/")){if(new RegExp(n.slice(1,-1)).test(d)){a.push({handle:s,matchType:"regex",...await Zo(s,o)});break}}else if(n.trim()===d.trim()){a.push({handle:s,matchType:"url",...await Zo(s,o)});break}}}if(a.length===1){let s=a[0];return this.userControlledBrowserSettings.autoExpandIframes||(s.handle.childFrames=[]),s}else throw a.length>1?new Error(`Found multiple frames with src matching '${n}'. Please use a more specific selector.`):new L("ActionFailureError",`Failed to find frame with src matching: ${n}`)}async composeA11yDomGraph({opts:e,a11yGraph:r,domGraph:n,startingFrameId:o,frameContext:i,logger:a,iconKnowledgeBase:s,showZeroOpacityElements:c,flagNotActionableNodes:l}){let u=await T0({rawA11yGraph:r,startingFrameId:o,frameContext:i,domGraph:n,logger:a,cdpClient:this.cdpClient,showZeroOpacityElements:c,flagNotActionableNodes:l,filterByViewport:e.filterByViewport,importantProperties:{attributes:this.userControlledBrowserSettings.importantAttributes,classes:this.userControlledBrowserSettings.importantClasses,styles:this.userControlledBrowserSettings.importantStyles},viewportDetails:void 0,iconKnowledgeBase:s,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:r,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(r),s=[];for(;a.length>0;){let c=a.shift();a.push(...c.childFrames);let l=async()=>{try{let{frame:u}=await Zo(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...")}};s.push(l())}await Promise.all(s)}async addMomenticIdsHelper(e,r){if(this.userControlledBrowserSettings.visualActions)return r;let n=this.logger;return await Qt({root:e,fn:i=>window.addIdsToElement?.(document.body,i),arg:r,timeout:st,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"})??r}getPageDomain(e){try{let r=new URL(e);if(!r.hostname)return null;let n=r.hostname.split("."),o=n.length>2?n.slice(-2).join("."):r.hostname;return`${r.protocol}//${o}`}catch{return null}}async decideChildFrameUnrollEligibility({logger:e,warnings:r,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 r?.push(i),e?.warn({err:o},i),{shouldUnroll:!0}}}async decideChildFrameUnrollEligibilityHelper({domNode:e}){let r=e.attributes??[];if(va(r,"aria-hidden")==="true")return{shouldUnroll:!1,reason:"aria-hidden"};let n=va(r,"style");if(n?.includes("display: none")||n?.includes("visibility: hidden"))return{shouldUnroll:!1,reason:"hidden CSS style"};await this.cdpClient.send({timeout:pe,method:"DOM.pushNodesByBackendIdsToFrontend",params:{backendNodeIds:[e.backendNodeId]}});let[o,i]=await Promise.all([this.cdpClient.send({timeout:pe,method:"DOM.getBoxModel",params:{backendNodeId:e.backendNodeId}}),this.cdpClient.send({timeout:pe,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:r,childFrames:n,logTimings:o,logger:i=this.logger,signal:a=this.abortSignalGetter()}){let s=[],c,l;for(let m=0;m<3;m++)try{l=await ro({fn:()=>this.getRawA11yTreeForFrame({frameId:r,timeoutMs:this.pageLoadTimeoutMs,logTimings:o}),codePath:"a11y-tree-fetch-root",logObject:o,logger:i});break}catch(f){c=f,i.warn({err:f},"Reinitializing CDP client before retrying a11y graph fetch"),await this.cdpClient.reinitialize()}if(!l)throw new Error(`Failed to fetch accessibility tree for root page: ${c}`);let u={};if(u[r??"root"]=l,!this.userControlledBrowserSettings.autoExpandIframes)return u;let d=Array.from(n),p=[];for(;d.length>0;){let m=d.shift();try{let{shouldUnroll:h}=await this.decideChildFrameUnrollEligibility({handle:m,warnings:s});if(!h)continue}catch(h){if(h.message.includes("Could not compute box model"))continue;s.push(`Got error when determining whether to filter frame ${m.frameId} with url ${m.url}, allowing it to be fetched: ${h}`)}d.push(...m.childFrames);let f=async()=>{try{let h=await ro({fn:()=>this.getRawA11yTreeForFrame({frameId:m.frameId,timeoutMs:this.smartWaitingTimeoutMs,logTimings:o}),codePath:`a11y-tree-fetch-child-${m.frameId}`,logObject:o,logger:i});u[m.frameId]=h}catch(h){i.warn({err:h,url:m.url,src:m.src},`Error getting raw a11y tree for child frame ${m.frameId}, continuing...`)}};p.push(f())}return await Promise.all(p),s.length>0&&this.logger.warn({warnings:s},"Got warnings when fetching the raw a11y graph"),u}async getRawA11yTreeForFrame({frameId:e,timeoutMs:r,logTimings:n}){let o=await this.cdpClient.withDomainEnabled({domain:"Accessibility",fn:async()=>{if(this.allowPartialAccessibilityTree)return(await ro({fn:()=>this.cdpClient.send({method:"Accessibility.getFullAXTree",params:{frameId:e??void 0},timeout:r,timeoutMsg:`Fetching the document tree took over ${r}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;let a=(await ro({fn:()=>this.cdpClient.send({method:"Accessibility.getRootAXNode",params:{frameId:e??void 0},timeout:st}),codePath:"cdp-get-root-ax-node",logObject:n,logger:this.logger})).node.backendDOMNodeId;return(await ro({fn:()=>this.cdpClient.send({method:"Accessibility.queryAXTree",params:{backendNodeId:a},timeout:r,timeoutMsg:`Fetching the document tree took over ${r}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:r,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:pe}),!o||!o.documents.length)throw new Error("Got empty DOM tree")}catch(s){await xe(dr,r),i++,a=s}if(!o||!o.documents.length)throw n.error({err:a},"Fatal error fetching DOM tree"),new L("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 c0({snapshot:o,devicePixelRatio:e,computedStylesToFetch:this.computedStylesToFetch,logger:n})}constructIframeRegexAsync(e,r){if(r.frameSrcRegex||r.frameUrlRegex)return;let n=_0(e);(async()=>{try{let o=await this.enricher?.constructIframeRegex(n);o?.srcRegex&&(r.frameSrcRegex=o.srcRegex),o?.urlRegex&&(r.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...")}})()}};var no=class t{static USER_AGENT=ig;abortSignal=void 0;contextInitialized=!1;cleanedUp=!1;browser;context;properties;page;userControlledBrowserSettings;pageLoadPromises={};lastTabChangeEventTimeout=void 0;pageLoadAbortControllers=new Set;pageLoadAbortListenerCleanup;clientCallbacks;harBatcher;iconKnowledgeBase;cdpClient;debugData={logsPerPage:[]};recentFrameNavigations={};requestRecorders={};mocks={};customHeaders=[];enricher;storage;logger;stateManager;transformer;lastScreenshotForRecording=void 0;originsVisited=new Set;viewport;onVideoPageChange;baseUrl;constructor({storage:e,enricher:r,browser:n,context:o,page:i,baseUrl:a,logger:s,userBrowserSettings:c,viewport:l,properties:u,clientCallbacks:d,iconKnowledgeBase:p,onVideoPageChange:m}){gI(c),this.storage=e,this.enricher=r,this.browser=n,this.context=o,this.page=i,this.baseUrl=a,this.logger=s,this.userControlledBrowserSettings=c,this.viewport=l,this.properties=u,this.clientCallbacks=d,this.iconKnowledgeBase=p,this.onVideoPageChange=m}registerAbortSignal(e){if(this.pageLoadAbortListenerCleanup&&(this.pageLoadAbortListenerCleanup(),this.pageLoadAbortListenerCleanup=void 0),this.abortSignal=e,!this.abortSignal)return;let r=()=>{for(let n of this.pageLoadAbortControllers)n.abort();this.pageLoadAbortControllers.clear()};if(this.abortSignal.aborted){r();return}this.abortSignal.addEventListener("abort",r),this.pageLoadAbortListenerCleanup=()=>{this.abortSignal?.removeEventListener("abort",r)}}async initialize({grantPermissions:e,permissionsToGrant:r,runInitScripts:n,timingRecorder:o}){if(this.contextInitialized)return;let i={[ik]:this.userBrowserSettings.visualActions},a=[];this.userControlledBrowserSettings.extraHeaders&&a.push(this.context.setExtraHTTPHeaders(this.userControlledBrowserSettings.extraHeaders)),e&&a.push(this.context.grantPermissions(Vk(r))),a.push(this.context.addInitScript({content:`${Gb.htmlUtilsLibJs}
|
|
4603
|
+
${P||""}`}return E}shallowClone(){let e=new t({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:bv(this.internalProperties),importantProperties:this.importantProperties,parentFrame:this.parentFrame,flagNotActionableNodes:this.flagNotActionableNodes});return e.tagName=this.tagName,e.dataMomenticId=this.dataMomenticId,e.properties=bv(this.properties),e}},Cv=class t{constructor(e,r,n,o,i={}){this.root=e;this.a11yIdNodeMap=r;this.dataMomenticIdMap=n;this.selectorToNodeMap=o;this.nodeIdHasPointingLabelMap=i}serialize(e){return this.root.serialize(e)}pruneUsingSummaries(e){let r=this.root;if(!r)throw new Error("Cannot prune a11y tree with no root");let n={},o={},i={},a=c=>{let l=c.shallowClone();if(e[c.id])return l.properties["data-momentic-summary"]=e[c.id],n[c.id]=l,c.dataMomenticId&&(o[c.dataMomenticId]=l),c.mPathSelector&&(i[c.mPathSelector]=l),l;let u=[];for(let d of c.children){let p=a(d);p&&(u.push(p),p.parent=l)}return l.children=u,n[c.id]=l,c.dataMomenticId&&(o[c.dataMomenticId]=l),c.mPathSelector&&(i[c.mPathSelector]=l),l},s=a(r);return new t(s,n,o,i,this.nodeIdHasPointingLabelMap)}pruneUsingRelevantIds(e){let r=this.root;if(!r)throw new Error("Cannot prune a11y tree with no root");function n(i,a=!1){let s=e.has(`${i.id}`)||i.id===r?.id,c=i.shallowClone(),l=i.children,u=!1,d=[];for(let p of l){let m=n(p,s||u);m&&(d.push(m),m.parent=c,u=!0)}if(c.children=d,s||u)return c;if(Rv.includes(i.role)&&a)return c}let o=n(r);return new t(o,this.a11yIdNodeMap,this.dataMomenticIdMap,this.selectorToNodeMap,this.nodeIdHasPointingLabelMap)}pruneToSerializedCharLimit(e){let r=this.root;if(!r)throw new Error("Cannot prune a11y tree with no root");let n=new WeakMap,o=(s,c)=>{if(n.has(s))return n.get(s);let l=s.serialize({indentLevel:c,noChildren:!0});return n.set(s,l),l},i=(s,c,l)=>{let u=s.shallowClone();u.children=[];let d=o(s,c).length;if(l<=d)return{clone:u,used:d};if(s.role==="StaticText"||s.children.length===0)return{clone:u,used:d};let p=d,m=l-p;for(let f of s.children){let h=c+2,S=o(f,h).length;if(m<S)break;let{clone:g,used:E}=i(f,h,m);if(E>m)break;u.children.push(g),g.parent=u,p+=E,m-=E}return{clone:u,used:p}},{clone:a}=i(r,0,Math.max(1e4,e));return new t(a,this.a11yIdNodeMap,this.dataMomenticIdMap,this.selectorToNodeMap,this.nodeIdHasPointingLabelMap)}};function GQ(t){return t.name?.value?`"${t.name.value}"`:t.role?.value&&t.role.value!=="none"&&t.role.value!=="generic"?`"${t.role.value}"`:`"${t.nodeId}"`}function jQ(t,e,r,n){return t.bounds.x===null||t.bounds.y===null||t.bounds.height===null||t.bounds.width===null||t.bounds.width===0||t.bounds.height===0?!0:t.bounds.x+t.bounds.width<e.leftBound||t.bounds.x>e.rightBound?(Hm({logger:r,logKey:n,maxCount:5,intervalMs:3e3},{domNode:t,logKey:n},"Filtering out node since it is not in the viewport horizontally"),!1):t.bounds.y+t.bounds.height<e.upperBound||t.bounds.y>e.lowerBound?(Hm({logger:r,logKey:n,maxCount:5,intervalMs:3e3},{domNode:t,logKey:n},"Filtering out node since it is not in the viewport vertically"),!1):t.computedStyles.display==="none"?(r.debug({domNode:t},"Filtering out node since it has display none"),!1):!0}async function y0({node:t,parent:e,frameId:r,frameContext:n,axGraph:o,domGraph:i,inputNodeMap:a,explicitLabelTargetDomIds:s,flagNotActionableNodes:c,showZeroOpacityElements:l,filterByViewport:u,viewportDetails:d,useMPaths:p,importantProperties:m,allowedA11yIgnoreReasonsOverride:f,cdpClient:h,logger:S,callId:g}){if(!e&&t.parentId)throw new Error(`Got no parent for accessibility node ${t.nodeId}: ${JSON.stringify(t)}`);let E=(W,q={})=>{},y=t.backendDOMNodeId,b=FQ.includes(t.role?.value?.toLowerCase()??"");if(!b&&y===void 0)return E("Filtering out node since it doesn't exist in the DOM"),[];let C=y?i.backendIdToNode[y]:void 0;if(!b&&!C)try{let W=await J(h.send({method:"DOM.describeNode",params:{backendNodeId:y}}),{milliseconds:750,fallback:()=>{S.debug("Timeout getting node from CDP while processing a11y tree")}});if(W&&W.node.nodeName.toLowerCase()==="slot"&&W.node.distributedNodes?.length)S.debug({parentAXNode:e?.getNodeOnlySerializedForm(),originalAXNodeName:t.name?.value},"Redirecting node to assigned slot");else return E("Filtering out node since it doesn't exist in the DOM",{cdpResult:W?.node.name??W?.node.nodeName}),[]}catch(W){return E("Filtering out node since it doesn't exist in the DOM",{err:W}),[]}if(C&&e&&u&&d&&t.backendDOMNodeId&&!jQ(C,d,S,g))return C.momenticIgnored=!0,[];if(C&&C.computedStyles.display==="none")return C.momenticIgnored=!0,[];if(C&&C.computedStyles.opacity==="0"&&l!==!0){if(l==="inputs-only"&&C.tagName.toLowerCase()!=="input")return C.momenticIgnored=!0,[];if(l===!1)return C.momenticIgnored=!0,[]}let I=t.name?.value?typeof t.name.value=="string"?t.name.value:`${t.name.value}`:"",_=t.value?.value?typeof t.value.value=="string"?t.value.value:`${t.value.value}`:"",R=new Av({domNode:C,id:parseInt(t.nodeId),role:t.role?.value||"",name:I,nameSources:t.name?.sources,content:_,properties:t.properties,children:[],ignoredReasons:t.ignoredReasons?.filter(W=>(f??g0).includes(W.name)||S0.includes(W.name))??[],pathFromRoot:(e?`${e.pathFromRoot} `:"")+GQ(t),backendNodeID:t.backendDOMNodeId,ignoredByCDP:t.ignored,internalProperties:{inCodeMirrorEditor:e?.internalProperties?.inCodeMirrorEditor},importantProperties:m,parentFrame:n.type==="root"?void 0:n,flagNotActionableNodes:c}),M=n,P=a[r],B=r;if(C?.tagName.toLowerCase()==="iframe"&&C.ownedFrameId){let W=n.childFrames.find(ne=>ne.frameId===C.ownedFrameId),q=o[W?.frameId??""]?.root,X=a[W?.frameId??""];if(W&&q&&X){t.childIds&&t.childIds.length>0&&S.debug("Replacing existing node's children with children from the iframe");let ne=q;t.childIds=ne.childIds,M=W,P=X,B=W.frameId}}let F=C?.childrenBackendIds?.length??0,G=(t.childIds??[]).filter(W=>!!P.get(parseInt(W))).length;if(F>G){let W=t.childIds?.map(X=>P.get(parseInt(X))).filter(Boolean).map(X=>X?.backendDOMNodeId).filter(X=>X!==void 0)??[],q=0;for(let X of C?.childrenBackendIds??[]){if(W.includes(X)){q=(t.childIds?.findIndex(be=>P.get(parseInt(be))?.backendDOMNodeId===X)??0)+1;continue}let ne=i.backendIdToNode[X];if(!ne||ne?.tagName.toLowerCase()!=="svg")continue;let de=Math.floor(-1*Math.random()*1e7),Te={nodeId:de.toString(),parentId:t.nodeId,ignored:!1,backendDOMNodeId:X,frameId:B,role:{type:"string",value:"graphics-symbol"}};P.set(de,Te),t.childIds||(t.childIds=[]),t.childIds.splice(q,0,de.toString()),q++}}if(t.childIds?.length===1&&C){let W=P.get(parseInt(t.childIds[0])),q=W?.role?.value,X=C.childrenBackendIds;if(W&&q==="StaticText"&&X.length===1){let ne=i.backendIdToNode[X[0]];if(ne?.tagName?.toLowerCase()==="span"){let de=Math.floor(-1*Math.random()*1e7).toString(),Te={nodeId:de,parentId:t.nodeId,ignored:!1,backendDOMNodeId:ne.backendNodeId,frameId:B,childIds:[W.nodeId]};W.parentId=de,P.set(parseInt(de),Te),t.childIds=[de]}}}if(C?.tagName.toLowerCase()==="label"){let W=C.attributes.for?.trim();W&&s.add(W)}for(let W of t.childIds??[]){if(!W)continue;let q=P.get(parseInt(W));if(!q)continue;let X=await y0({node:q,parent:R,domGraph:i,explicitLabelTargetDomIds:s,axGraph:o,frameId:B,frameContext:M,inputNodeMap:a,cdpClient:h,logger:S,callId:g,filterByViewport:u,showZeroOpacityElements:l,importantProperties:m,viewportDetails:d,useMPaths:p,flagNotActionableNodes:c});X.length&&(R.children=R.children.concat(X))}if(R.role==="StaticText"&&(R.children=[]),R.role==="ListMarker")if(R.children.length!==1||R.children[0].role!=="StaticText")S.debug({childLen:R.children.length,childRoles:R.children.map(W=>W.role),childTags:R.children.map(W=>W.tagName),currentTag:R.tagName,currentName:R.name},"Unexpected ListMarker structure (processA11yTreeDFS)");else return R.children;if(R.children.length===1&&R.children[0].role==="StaticText"){let W=R.name,X=R.children[0].name;(W===X||!X)&&(R.name="")}let z=[];for(let W=R.children.length-1;W>=0;W--){let q=R.children[W];if(q.role!=="StaticText"){z.push(q);continue}if(W===0||R.children[W-1].role!=="StaticText"){z.push(q);continue}R.children[W-1].name+=q.name}if(R.children=z.reverse(),!R.isInteresting(m)&&t.parentId)return C&&(C.momenticIgnored=!0),R.children;for(let W of R.children)W.parent=R;return $Q(R),C&&p&&Tv(C,i),[R]}function E0({node:t,a11yIdNodeMap:e,dataMomenticIdMap:r,logger:n,callId:o,domGraph:i,useMPaths:a,selectorToNodeMap:s,nodeIdHasPointingLabelMap:c,explicitLabelTargetDomIds:l,iconKnowledgeBase:u,startId:d=1}){t.id=d,d+=1,e[t.id]=t,t.dataMomenticId?r[t.dataMomenticId]=t:Rv.includes(t.role);let p=t.backendNodeId,m=p!==void 0?i.backendIdToNode[p]:void 0;a&&m&&m.mPathSelector&&(s[m.mPathSelector]=t,t.mPathSelector=m.mPathSelector);let f=m?.attributes.id?.trim();if(f&&l.has(f)&&(t.internalProperties.hasExplicitPointingLabel=!0,c[t.id]=!0),u&&m&&m.tagName?.toLowerCase()==="svg"){let h=Ev(m,i),S=h?u[h.hash]:void 0,g=S?S.description:void 0;S&&(t.properties["data-momentic-description"]=g)}for(let h of t.children)d=E0({node:h,a11yIdNodeMap:e,dataMomenticIdMap:r,logger:n,callId:o,startId:d,useMPaths:a,domGraph:i,selectorToNodeMap:s,nodeIdHasPointingLabelMap:c,explicitLabelTargetDomIds:l,iconKnowledgeBase:u});return d}async function T0({rawA11yGraph:t,domGraph:e,startingFrameId:r,logger:n,cdpClient:o,filterByViewport:i,showZeroOpacityElements:a,flagNotActionableNodes:s,importantProperties:c,viewportDetails:l,useMPaths:u,frameContext:d,iconKnowledgeBase:p,allowedA11yIgnoreReasonsOverride:m}){let f=r??"root",h=t[f]?.root;if(!h)throw new Error("A11y tree has no root");let S=IQ(),g=new Set,E=M=>{let P=M.allNodes.filter(F=>!F.ignoredReasons?.find(z=>(m??g0).includes(z.name))),B=new Map;return P.forEach(F=>{B.set(parseInt(F.nodeId),F)}),B},y={};Object.entries(t).forEach(([M,P])=>{y[M]=E(P)});let b=await y0({node:h,domGraph:e,explicitLabelTargetDomIds:g,parent:null,inputNodeMap:y,axGraph:t,frameId:f,frameContext:d,cdpClient:o,logger:n,callId:S,showZeroOpacityElements:a,importantProperties:c,filterByViewport:i,viewportDetails:l,useMPaths:u,flagNotActionableNodes:s,allowedA11yIgnoreReasonsOverride:m});if(b.length>1)throw new Error(`Something went horribly wrong processing the a11y tree, we got: ${JSON.stringify(b)}`);if(b.length===0)throw new Error("There are no accessible elements on this page or frame. Are you sure this website loads properly?");let C={},I={},_={},R={};return E0({node:b[0],a11yIdNodeMap:C,dataMomenticIdMap:I,selectorToNodeMap:_,nodeIdHasPointingLabelMap:R,explicitLabelTargetDomIds:g,domGraph:e,logger:n,callId:S,useMPaths:u,iconKnowledgeBase:p}),new Cv(b[0],C,I,_,R)}function VQ(t,e,r,n){if(t==="class"){if(PQ.includes(r.tagName?.toLowerCase()??""))return e.split(" ").filter(a=>a.length<vv&&!Cn.bannedClassSubstrings.some(s=>a.includes(s))).slice(0,3).join(" ");let o=e.split(" "),i=[];for(let a of o)if(b0(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=Number(e);if(!Number.isNaN(o))return o}catch{}return t==="src"&&e.includes("base64")?e.slice(0,e.indexOf("base64")+6)+"...":e.length>60?e.slice(0,50)+"...":e}function WQ(t,e,r){if(!e)return;Object.entries(e.attributes).forEach(([a,s])=>{let c=t[a]||a.startsWith("aria")||LQ.includes(a);if((Cn.relevantElementAttributes.includes(a)||v0(a,r))&&!c){let u=VQ(a,s,e,r);u!==null&&(t[a]=u)}});let n,o=[];if(e.computedStyles.position&&m0.includes(e.computedStyles.position))n=e.computedStyles.position;else if(e.attributes.style){for(let a of m0)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 r?.styles??[]){let s=a.split(":"),c=s[0]?.trim(),l=s[1]?.trim(),u=e.computedStyles[c??""];if(c!==void 0&&l!==void 0&&u!==void 0&&(l==="*"||u===l)){let d=e.computedStyles[c],p=`${c}: ${d}`;o.includes(p)||o.push(p)}}o.length>0&&(t.style=o.join("; "))}function $Q(t){let e=t.properties.class;if(typeof e=="string"&&e.includes("cm-content")){t.children.forEach((i,a)=>{i.properties["cm-line-number"]=`${a+1}`});return}if(typeof e=="string"&&e.includes("notion-page-content")){t.children.forEach((i,a)=>{i.properties["block-number"]=`${a+1}`}),t.children.length>0&&(t.children[t.children.length-1].properties.description="This is the last block in the document. Click here to add new text to the end.");return}if(t.tagName==="table"){let i=[],a=t.children.find(c=>c.tagName==="thead");if(a){let c=a.children.find(l=>l.tagName==="tr");if(c){let l=c.children.filter(u=>u.tagName==="th");l.forEach((u,d)=>{u.properties["col-index"]||(u.properties["col-index"]=d+1),i?.push(vt(u.name,100,!1))}),i?.length!==l.length&&(i=void 0)}}let s=0;for(let c of t.children)if(c.tagName==="tbody")for(let l=0;l<c.children.length;l++){let u=c.children[l];if(u.tagName!=="tr")continue;if(l===0&&!i?.length){let m=u.children.filter(f=>f.tagName==="th");if(m.length){if(i=m.map(f=>vt(f.name,100,!1)),i.length===m.length)continue;i=void 0}}s+=1,u.properties["row-index"]||(u.properties["row-index"]=s);let d=u.children.filter(m=>m.tagName==="td"||m.tagName==="th"),p=d.length===i?.length;d.forEach((m,f)=>{m.tagName!=="th"&&(m.properties["col-index"]||(m.properties["col-index"]=f+1),p&&(m.properties.col||(m.properties.col=i[f])))})}}}function qQ(t){let e=t.properties.class,r=typeof e=="string"&&e.includes("cm-content");t.internalProperties.inCodeMirrorEditor=t.internalProperties?.inCodeMirrorEditor||r}function b0(t,e){if(e&&A0(t,e))return!0;if(Cn.bannedClassSubstrings.some(r=>t.includes(r)))return!1;if(Cn.alwaysInterestingClassNames.includes(t))return!0;for(let r of Cn.alwaysInterestingClassPrefixes)if(t.startsWith(r))return!0;return!1}function v0(t,e){if(e?.attributes?.includes(t))return!0;for(let r of e?.attributes??[])if(r.endsWith("*")){let n=r.slice(0,-1);if(t.startsWith(n))return!0}return!1}function A0(t,e){if(e?.classes?.includes(t))return!0;for(let r of e?.classes??[])if(r.endsWith("*")){let n=r.slice(0,-1);if(t.startsWith(n))return!0}return!1}var KQ=["Accessibility","DOMSnapshot","DOMStorage"],dg=class t{constructor(e,r,n,o,i){this.session=e;this.logger=r;this.contextGetter=n;this.pageGetter=o;this.defaultTimeoutMs=i}cdpInitializingPromise=void 0;cdpCrashDetails=void 0;cdpFullyDead=!1;scopedDomainQueues={};scopedDomainScopeCounts={};static async init({logger:e,contextGetter:r,pageGetter:n,defaultTimeoutMs:o}){let i=r(),a=n(),s,c;for(let u=0;u<2;u++)try{s=await J(i.newCDPSession(a),{milliseconds:o*u,fallback:()=>{throw new L("UserInfrastructureError",`Failed to initialize Chrome session within the page load timeout (${a.url()})`)}});break}catch(d){await xe(dr),c=d}if(!s)throw c;let l=new t(s,e,r,n,o);try{await J(l.registerHandlers(s),{milliseconds:o,message:`CDP handler registration timed out after ${o}ms`})}catch(u){throw l.cdpFullyDead=!0,new L("UserInfrastructureError",`Failed to initialize CDP client: ${u}`)}return l}async registerHandlers(e){e.on("Target.attachedToTarget",async()=>{try{await e.send("Runtime.runIfWaitingForDebugger")}catch(r){this.logger.warn({err:r},"Failed to run Runtime.runIfWaitingForDebugger")}}),e.on("Target.targetCrashed",r=>{this.cdpCrashDetails={...this.cdpCrashDetails??{},targetCrashDetails:JSON.stringify(r)},this.logger.error({payload:r},"CDP session crashed, Momentic will likely not function correctly")}),e.on("Inspector.targetCrashed",r=>{this.cdpCrashDetails={...this.cdpCrashDetails??{},inspectorCrashDetails:JSON.stringify(r)},this.logger.error({payload:r},"CDP inspector session crashed, Momentic will likely not function correctly")}),await Promise.all([e.send("Page.enable"),e.send("DOM.enable"),e.send("CSS.enable"),e.send("Overlay.enable")])}async send({method:e,params:r,timeout:n=this.defaultTimeoutMs,timeoutMsg:o}){let i=this.getScopedDomainForMethod(e);return i?(this.scopedDomainScopeCounts[i]??0)>0?this.sendWithoutScopedDomain({method:e,params:r,timeout:n,timeoutMsg:o}):this.sendWithScopedDomain({domain:i,method:e,params:r,timeout:n,timeoutMsg:o}):this.sendWithoutScopedDomain({method:e,params:r,timeout:n,timeoutMsg:o})}getScopedDomainForMethod(e){let r=e;for(let n of KQ)if(r.startsWith(`${n}.`)&&r!==`${n}.enable`&&r!==`${n}.disable`)return n}async withDomainEnabled({domain:e,timeout:r=this.defaultTimeoutMs,fn:n}){if((this.scopedDomainScopeCounts[e]??0)>0){this.scopedDomainScopeCounts[e]=(this.scopedDomainScopeCounts[e]??0)+1;try{return await n()}finally{let o=Math.max((this.scopedDomainScopeCounts[e]??1)-1,0);this.scopedDomainScopeCounts[e]=o,o===0&&await this.withDomainLock(e,async()=>{if(!((this.scopedDomainScopeCounts[e]??0)>0))try{await this.sendWithoutScopedDomain({method:`${e}.disable`,params:void 0,timeout:r})}catch(i){this.logger.warn({err:i,domain:e},`Failed to disable ${e} domain after scoped CDP command block`)}})}}return this.withDomainLock(e,async()=>{await this.sendWithoutScopedDomain({method:`${e}.enable`,params:void 0,timeout:r}),this.scopedDomainScopeCounts[e]=(this.scopedDomainScopeCounts[e]??0)+1;try{return await n()}finally{let o=Math.max((this.scopedDomainScopeCounts[e]??1)-1,0);if(this.scopedDomainScopeCounts[e]=o,o===0)try{await this.sendWithoutScopedDomain({method:`${e}.disable`,params:void 0,timeout:r})}catch(i){this.logger.warn({err:i,domain:e},`Failed to disable ${e} domain after scoped CDP command block`)}}})}async withDomainLock(e,r){let n=this.scopedDomainQueues[e]??Promise.resolve(),o,i=new Promise(a=>{o=a});this.scopedDomainQueues[e]=n.catch(()=>{}).then(()=>i),await n.catch(()=>{});try{return await r()}finally{o?.()}}async sendWithScopedDomain({domain:e,method:r,params:n,timeout:o,timeoutMsg:i}){return this.withDomainLock(e,async()=>{try{return await this.sendWithoutScopedDomain({method:`${e}.enable`,params:void 0,timeout:o}),await this.sendWithoutScopedDomain({method:r,params:n,timeout:o,timeoutMsg:i})}finally{try{await this.sendWithoutScopedDomain({method:`${e}.disable`,params:void 0,timeout:o})}catch(a){this.logger.warn({err:a,domain:e},`Failed to disable ${e} domain after scoped CDP command`)}}})}async sendWithoutScopedDomain({method:e,params:r,timeout:n=this.defaultTimeoutMs,timeoutMsg:o}){for(;this.cdpInitializingPromise;)await J(this.cdpInitializingPromise,{milliseconds:n});if(this.cdpCrashDetails){if(this.cdpFullyDead)throw new L("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 J(this.session.send(e,r),{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 r=e,n=this.pageGetter(),o=await J(this.contextGetter().newCDPSession(n),{milliseconds:r,fallback:()=>{throw this.logger.warn(`Failed to initialize CDP session within the page load timeout (${n.url()})`),new L("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 r=this.session;this.session=await this.createRawCDPSession(e),await J(this.registerHandlers(this.session),{milliseconds:e,message:`Failed to register CDP handlers within ${e}ms`}),this.scopedDomainQueues={},this.scopedDomainScopeCounts={},this.logger.debug("Successfully reinitialized and attached new handlers to CDP session");try{await J(r.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(r){this.cdpCrashDetails={...this.cdpCrashDetails??{},reinitializeError:`${r}`},this.cdpFullyDead=!0}finally{this.cdpInitializingPromise=void 0}})(),await this.cdpInitializingPromise}on(e,r){return this.session.on(e,r),this.session}off(e,r){return this.session.off(e,r),this.session}addListener(e,r){return this.session.addListener(e,r),this.session}removeListener(e,r){return this.session.removeListener(e,r),this.session}};var Oc="<empty>";function YQ(t){return t.includes("doubleclick.net")||t.includes("googletagmanager.com")||t.includes("googlesyndication.com")||t.includes("s.amazon-adsystem.com")||t.includes("smartadserver.com")||t.includes("omnitagjs.com")||t.includes("x.adroll.com")}function R0(t){let e=t.adFrameStatus?.adFrameType;return e==="child"||e==="root"||YQ(t.url)}async function XQ(t,e){let r=await t.send({timeout:pe,method:"DOM.getFrameOwner",params:{frameId:e}}),o=(await t.send({timeout:pe,method:"DOM.pushNodesByBackendIdsToFrontend",params:{backendNodeIds:[r.backendNodeId]}})).nodeIds[0],a=(await t.send({timeout:pe,method:"DOM.describeNode",params:{backendNodeId:r.backendNodeId}})).node;return a.nodeId=o,a}async function Lc({cdpClient:t,page:e,logger:r}){let n={type:"root",childFrames:[],page:e},o=[],[i,a]=await Promise.all([t.send({timeout:Mc,method:"Page.getFrameTree",params:{}}),t.send({timeout:Mc,method:"DOM.getDocument",params:{depth:0}})]),l=(i.frameTree.childFrames??[]).map(async(d,p)=>{if(R0(d.frame))return null;try{return await w0({cdpClient:t,rawFrameTree:d,indices:[p],parent:n,warnings:o,logger:r})}catch(m){return o.push(`Failed to get child frame: ${m}`),null}}),u=await Promise.all(l);return n.childFrames=u.filter(d=>d!==null),o.length&&r?.warn({warnings:o},"Got warnings when fetching frame tree"),n}async function w0({cdpClient:t,rawFrameTree:e,indices:r,parent:n,warnings:o,logger:i}){let a=e.frame.id,s=await XQ(t,a),c=s.attributes??[],l=null,u=[];for(let f of["src","name","id","title","srcdoc","sandbox"]){let h=va(c,f);h&&(u.push(`${f}=${JSON.stringify(h)}`),f==="src"&&(l=h))}let d={type:"frame",cdpFrame:e.frame,url:e.frame.url,frameId:a,locationData:{indices:r,attributeSelectors:u},src:l,childFrames:[],parent:n,domNode:s},m=(e.childFrames??[]).map(async(f,h)=>{if(R0(f.frame))return null;try{return await w0({cdpClient:t,rawFrameTree:f,indices:[...r,h],parent:d,warnings:o,logger:i})}catch(S){return o.push(`Failed to get child frame (child ${h} of frame with url ${e.frame.url}): ${S}`),null}});return d.childFrames=(await Promise.all(m)).filter(f=>f!==null),d}async function JQ(t){try{return await t.owner().count()===1}catch{return!1}}async function QQ(t){try{return await t.count()===1}catch{return!1}}async function Zo(t,e){let r=[],n=t;for(;n.parent.type==="frame";)r.push(n.parent),n=n.parent;r.reverse();let o=e,i=[];for(let l of r){let u=!1;for(let d of[...l.locationData.attributeSelectors,Oc]){let p=o.frameLocator(d===Oc?"iframe":`iframe[${d}]`);if(await JQ(p)){u=!0,o=p,i.push(d);break}}if(!u)throw new L("ActionFailureError",`Failed to find a unique attribute to identify intermediate frame with url matching '${l.url}'. Please attach a unique 'id', 'name', 'title', or 'src' attribute to the frame.`)}let a;for(let l of[...t.locationData.attributeSelectors,Oc]){let u=o.locator(l===Oc?"iframe":`iframe[${l}]`);if(await QQ(u)){a=u,i.push(l);break}}if(!a)throw new L("ActionFailureError",`Failed to find a unique attribute to identify target frame with url matching '${t.url}'. Please attach a unique 'id', 'name', 'title', or 'src' attribute to the frame.`);let s=await a.evaluateHandle(l=>l),c=await s.asElement().contentFrame();if(!c)throw new L("InternalWebAgentError",`Failed to load Playwright Frame for iframe with url '${t.url}'`);return await s.dispose(),{frame:c,mPathSelectorTokens:i}}function C0(t,e){let r=[...t],n=[];for(;r.length;){let o=r.shift();e(o)&&n.push(o),r.push(...o.childFrames)}return n}async function x0({page:t,frameTree:e,cache:r}){let n,o=e.childFrames,i=[];if(r.mPathSelectorTokens.length){let s=o;for(let u=0;u<r.mPathSelectorTokens.length-1;u++){let d=r.mPathSelectorTokens[u];d===Oc?s=s.length===1?s[0].childFrames:[]:s=s.filter(p=>p.locationData.attributeSelectors.includes(d)).map(p=>p.childFrames).flat()}let c=[],l=r.mPathSelectorTokens[r.mPathSelectorTokens.length-1];if(l===Oc?c=s:c=s.filter(u=>u.locationData.attributeSelectors.includes(l)),c.length===1)return n=c[0],i.push(`Found unique frame with mpath ${r.mPathSelectorTokens.join(" > ")}`),{resolution:{type:"auto",frame:(await Zo(n,t)).frame,handle:n,mPathSelectorTokens:r.mPathSelectorTokens,frameTree:e},logs:i};i.push(`Found ${c.length} frames with mpath ${r.mPathSelectorTokens.join(" > ")}`)}if(r.frameSrcRegex){let s=new RegExp(r.frameSrcRegex),c=C0(o,l=>!!l.src&&s.test(l.src));if(c.length===1)return n=c[0],i.push(`Found unique frame with src regex ${r.frameSrcRegex}`),{resolution:{type:"auto",frame:(await Zo(n,t)).frame,handle:n,mPathSelectorTokens:r.mPathSelectorTokens,frameTree:e},logs:i};i.push(`Found ${c.length} frames with src regex ${r.frameSrcRegex}`),r.frameSrcRegex=void 0}if(r.frameUrlRegex){let s=new RegExp(r.frameUrlRegex),c=C0(o,l=>!!l.url&&s.test(l.url));if(c.length===1)return n=c[0],i.push(`Found unique frame with url regex ${r.frameUrlRegex}`),{resolution:{type:"auto",frame:(await Zo(n,t)).frame,handle:n,mPathSelectorTokens:r.mPathSelectorTokens,frameTree:e},logs:i};i.push(`Found ${c.length} frames with url regex ${r.frameUrlRegex}`),r.frameUrlRegex=void 0}let a=o;for(let s=0;s<r.indices.length-1;s++)a=a[r.indices[s]]?.childFrames??[];if(n=a[r.indices[r.indices.length-1]],n)return i.push(`Found unique frame with indices ${r.indices.join(" > ")}`),{resolution:{type:"auto",frame:(await Zo(n,t)).frame,handle:n,mPathSelectorTokens:r.mPathSelectorTokens,frameTree:e},logs:i};throw i.push(`Found ${a.length} frames with indices ${r.indices}`),new fn("Failed to find the iframe that previously contained this element",[{type:"AUTO_FRAME",matched:!1,logs:i}],"could-not-find-iframe")}function pg(t){return t.type==="auto"?JSON.stringify({type:"auto",frameId:t.handle.frameId}):JSON.stringify(t)}function wv(t){for(;t.parent.type==="frame";)t=t.parent;return t.parent}function _0(t){let e=wv(t),r=t.src??"",n=t.url??"",o=[],i=[],a=[...e.childFrames];for(;a.length;){let s=a.shift();s.src&&o.push(s.src),s.url&&i.push(s.url),a.push(...s.childFrames)}return{srcs:o,urls:i,desiredSrc:r,desiredUrl:n}}function I0(t){return t.type==="auto"?{type:"auto",frameId:t.handle.frameId,url:t.handle.url,src:t.handle.src??"",mPathSelectorTokens:t.mPathSelectorTokens.join(" > ")}:{type:"url",url:t.url}}async function P0({frame:t,logger:e,signal:r}){let n;try{n=await t.frameElement(),await ZQ({frameElementHandle:n,logger:e,signal:r})}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 ZQ({frameElementHandle:t,logger:e,signal:r}){let n=await t.boundingBox(),i=await Wd({promiseGenerator:async()=>t.evaluate(async a=>{let s=a.scrollTop,c=a.getBoundingClientRect(),l=0,u=0,d=window.innerWidth,p=window.innerHeight;if(c.top>=l&&c.left>=u&&c.bottom<=p&&c.right<=d)return{didScroll:!1,reason:"already-fully-visible"};a.scrollIntoView({behavior:"instant",block:"center",inline:"center"}),await new Promise(g=>setTimeout(g,250));let f=Date.now();for(;Date.now()-f<1e3;){let g=a.scrollTop;if(g===s)break;s=g,await new Promise(E=>setTimeout(E,250))}let h=a.getBoundingClientRect();return h.top!==c.top||h.left!==c.left||h.right!==c.right||h.bottom!==c.bottom?{didScroll:!0,reason:"scrolled",afterRect:h}:{didScroll:!1,reason:"no-more-scroll-possible",afterRect:h}}),timeoutMs:st,codePath:"scrollIframeIntoView",signal:r});i.didScroll&&e.info({oldBb:n,newBb:await t.boundingBox(),evalResult:i},"Successfully scrolled iframe into view")}var xv=()=>{let t,e,r=new Promise((n,o)=>{t=n,e=o});return{resolve:t,reject:e,value:r}};var M0=(t,e)=>{let r=t.name??`batcher:${Math.random().toString(16).slice(2)})`,n=t.scheduler??e8(10),o=globalThis.__BATSHIT_DEVTOOLS__?.for(r),i=e??{seq:0,batch:new Set,currentRequest:xv(),timer:void 0,start:null,latest:null,abortController:new AbortController};o?.create({seq:i.seq});let a=()=>{i.batch=new Set,i.currentRequest=xv(),i.timer=void 0,i.start=null,i.latest=null,i.abortController=new AbortController},s=()=>{let d=i.seq,p=t.fetcher([...i.batch],i.abortController.signal),m=i.currentRequest;return o?.fetch({seq:d,batch:[...i.batch]}),a(),p.then(f=>{o?.data({seq:d,data:f}),m.resolve(f)}).catch(f=>{o?.error({seq:d,error:f}),m.reject(f)}),i.seq++,p};return{fetch:d=>{i.start||(i.start=Date.now()),i.latest=Date.now(),i.batch.add(d),clearTimeout(i.timer);let p=n(i.start,i.latest,i.batch.size);if(o?.queue({seq:i.seq,query:d,batch:[...i.batch],scheduled:p,latest:i.latest,start:i.start}),p==="immediate"){let m=i.currentRequest;return s(),m.value.then(f=>t.resolver(f,d))}else return p==="never"?i.currentRequest.value.then(m=>t.resolver(m,d)):(i.timer=setTimeout(s,p),i.currentRequest.value.then(m=>t.resolver(m,d)))},next:()=>{s()},abort:()=>{i.abortController.abort(),i.currentRequest.reject(new DOMException("Aborted","AbortError")),a()}}};var e8=t=>(e,r)=>{let n=r-e;return t-n};var O0=({windowMs:t,maxBatchSize:e})=>(r,n,o)=>{if(o>=e)return"immediate";let i=n-r;return t-i};import{reduce as t8}from"lodash-es";var r8=100,n8=2e3;function L0(t){return M0({fetcher:async r=>{t(t8(r,(n,o)=>({...n,...o}),{}))},resolver:()=>{},scheduler:O0({windowMs:n8,maxBatchSize:r8})})}async function N0({event:t,transformer:e,enricher:r,frame:n,lastScreenshotForRecording:o,logger:i}){let{warnings:a,error:s,properties:c}=t.target;if(s){i.error({error:s,warnings:a},"Error while capturing passive click");return}if(a.length&&i.warn({warnings:a},"Warnings while capturing passive click"),!c)return;let l=n.parentFrame()?n.url():void 0,d=n.page().frames().map(f=>f.url());i.debug({frameUrl:l,...t},"Passive click event captured on element");let p,m;if(l)try{let f=await n.frameElement();p=await J(f?.boundingBox(),{milliseconds:pe})??void 0;let h=await r.constructIframeRegex({urls:d,srcs:[],desiredUrl:l});if(h.urlRegex)m={type:"url",url:`/${h.urlRegex}/`};else throw new Error(`Got no url regex options: ${JSON.stringify(h)}`)}catch(f){i.warn({err:f},"Failed to construct iframe details for recorded action, using hardcoded URL only"),m={type:"url",url:l}}(async()=>{try{await e.recordElementAction({...t,screenshotBase64:o,frameConfig:m,frameBoundingBox:p})}catch(f){i.error({err:f},"Failed to transform passive click action")}})()}import{randomUUID as ei}from"crypto";import o8 from"js-beautify";var i8=["Dead"],mg=class{recordedSteps=new Map;callbacks;signal;generator;testId;orgId;nextStepOffset=0;logger;constructor({signal:e,callbacks:r,generator:n,testId:o,orgId:i,logger:a}){this.signal=e,this.logger=a,this.testId=o,this.orgId=i,this.callbacks={onStepRecorded:(s,c)=>{this.recordedSteps.set(c,{step:s}),r.onStepRecorded(s,c)},onActionReceived:(s,c)=>{this.recordedSteps.set(c,{step:s}),r.onActionReceived?.(s,c)}},this.generator=n}reserveIndexForCommand(e){let r=this.nextStepOffset;return this.recordedSteps.set(r,{step:{id:ei(),type:"PRESET_ACTION",command:ci(e)}}),this.nextStepOffset++,r}async recordElementAction(e){let{type:r,target:n,frameConfig:o}=e;if(this.signal.aborted){this.logger.debug("Transformer was already cleaned up, ignoring click...");return}let i,a,s=n.properties.attributes.nodeOnlySerializedHtml.trim(),c=s,l;switch(e.frameConfig?e.frameBoundingBox?l={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"):l=n.properties.boundingBox,r){case"CLICK":{i="CLICK";let h=ci(i);a={id:ei(),type:"PRESET_ACTION",command:{...h,target:{type:"description",elementDescriptor:c},iframeUrl:o?.url,cache:{target:{id:-1,...n.properties.attributes,targetSource:"RECORDING",targetUpdateTime:new Date().toUTCString(),boundingBox:l}}}};break}case"SELECT":{i="SELECT_OPTION";let h=ci(i);a={id:ei(),type:"PRESET_ACTION",command:{...h,type:"SELECT_OPTION",iframeUrl:o?.url,target:{type:"description",elementDescriptor:c},cache:{target:{id:-1,...n.properties.attributes,targetSource:"RECORDING",targetUpdateTime:new Date().toUTCString(),boundingBox:l}},choice:{type:"VALUE",value:e.selectedValue??"Unknown option"}}};break}case"MOUSE_DRAG":{i="MOUSE_DRAG";let h=ci(i);a={id:ei(),type:"PRESET_ACTION",command:{...h,target:{type:"description",elementDescriptor:c},deltaX:e.deltaX.toString(),deltaY:e.deltaY.toString(),iframeUrl:o?.url,cache:{target:{id:-1,...n.properties.attributes,targetSource:"RECORDING",targetUpdateTime:new Date().toUTCString(),targetUpdateLoggerTags:ot(this.logger),boundingBox:l}}}};break}default:throw new Error(`Unknown action type: ${r}`)}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=o8.html(d,{indent_size:1,indent_with_tabs:!1,preserve_newlines:!1}),d=ak(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,...ot(this.logger)}})).phrase}catch(h){this.logger.error({err:h},"Error generating reverse mapping description"),p=s}let m=this.recordedSteps.get(u)?.step??a,f=m?.command;f&&"target"in f&&f.target?(f.target={type:"description",elementDescriptor:p},this.callbacks.onStepRecorded({...m,command:f},u)):this.logger.warn("Could not find existing command to update after description mapping")}recordKeystroke(e){let{key:r,combinable:n}=e;if(i8.includes(r)||this.signal.aborted)return;let o="normal";r.length>1&&(o="special");let i;if(o==="normal"){let d=ci("TYPE");i={id:ei(),type:"PRESET_ACTION",command:{...d,target:void 0,value:r,clearContent:!1}}}else{let d=ci("PRESS");i={id:ei(),type:"PRESET_ACTION",command:{...d,value:r}}}let a,s=this.nextStepOffset-1,c=this.recordedSteps.get(s),l=c?.step,u=l?.command;if(n){if(u?.type===i.command.type){let d=u.value,p=i.command.value;i={id:ei(),type:"PRESET_ACTION",command:{...u,value:i.command.type==="PRESS"?`${d}+${p}`:`${d}${p}`}},a=s}else if(u?.type==="CLICK"&&i.command.type==="TYPE")l.command={...i.command,target:u.target,cache:u.cache},i=c.step,a=s;else if(u?.type==="TYPE"&&i.command.type==="PRESS"&&i.command.value==="Backspace"){let d=u.value;i={id:ei(),type:"PRESET_ACTION",command:{...u,value:d.slice(0,d.length-1)}},a=s}}a===void 0&&(a=this.nextStepOffset,this.nextStepOffset++),this.callbacks.onStepRecorded(i,a)}recordScroll(e){if(this.signal.aborted)return;let r=()=>{let{deltaY:i}=e;if(!i)return;let a=this.nextStepOffset-1,s=this.recordedSteps.get(a)?.step.command,c;s?.type==="SCROLL_DOWN"&&s.deltaY?(i+=s.deltaY,c=a):s?.type==="SCROLL_UP"&&s.deltaY?(i-=s.deltaY,c=a):(c=this.nextStepOffset,this.nextStepOffset++);let l=i>0?"SCROLL_DOWN":"SCROLL_UP",u=ci(l);u.deltaY=Math.abs(i);let d={id:ei(),type:"PRESET_ACTION",command:u};this.callbacks.onStepRecorded(d,c)},n=()=>{let{deltaX:i}=e;if(!i)return;let a=this.nextStepOffset-1,s=this.recordedSteps.get(a)?.step.command,c;s?.type==="SCROLL_RIGHT"&&s.deltaX?(i+=s.deltaX,c=a):s?.type==="SCROLL_LEFT"&&s.deltaX?(i-=s.deltaX,c=a):(c=this.nextStepOffset,this.nextStepOffset++);let l=i>0?"SCROLL_RIGHT":"SCROLL_LEFT",u=ci(l);u.deltaX=Math.abs(i);let d={id:ei(),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&&r()):(r(),e.deltaX>=20&&n())}};import{z as _v}from"zod";var y8e=_v.object({type:_v.literal("url"),url:_v.string()});var fg=class{smartWaitingTimeoutMs;pageLoadTimeoutMs;allowPartialAccessibilityTree;logger;cdpClient;pageGetter;abortSignalGetter;userControlledBrowserSettings;enricher;iconKnowledgeBase;computedStylesToFetch=["display","opacity","visibility","height","position","background-image"];activeFrameCache;activeFrameConfig;lastA11yIdToNodeMap={};lastDataMomenticIdToNodeMap={};lastSelectorToNodeMap={};lastA11yTreeRoot;lastDomGraph;lastA11yTreeFetchTimeMs;allowedA11yIgnoreReasonsOverride;constructor({smartWaitingTimeoutMs:e,pageLoadTimeoutMs:r,allowPartialAccessibilityTree:n,logger:o,cdpClient:i,pageGetter:a,abortSignalGetter:s,enricher:c,iconKnowledgeBase:l,userBrowserSettings:u,allowedA11yIgnoreReasonsOverride:d}){if(this.smartWaitingTimeoutMs=e,this.pageLoadTimeoutMs=r,this.allowPartialAccessibilityTree=n,this.logger=o,this.cdpClient=i,this.pageGetter=a,this.abortSignalGetter=s,this.enricher=c,this.iconKnowledgeBase=l,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 f=m[0]?.trim(),h=m[1]?.trim();if(f===void 0||h===void 0){this.logger.warn({style:p},"Invalid style property passed to importantStyles");continue}this.computedStylesToFetch.includes(f)||this.computedStylesToFetch.push(f)}}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,this.lastA11yTreeFetchTimeMs=void 0}saveAutoFrameCacheDetails(e){if(!this.activeFrameConfig||this.activeFrameConfig.type!=="auto"||!this.userControlledBrowserSettings.autoExpandIframes)return;let r={...e,indices:this.activeFrameConfig.handle.locationData.indices,mPathSelectorTokens:this.activeFrameConfig.mPathSelectorTokens};return this.constructIframeRegexAsync(this.activeFrameConfig.handle,r),r}async getAutoFrameDetailsFromHandle(e){let r=this.pageGetter(),n=wv(e),{frame:o,mPathSelectorTokens:i}=await Zo(e,r),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 r=this.pageGetter(),n=await Lc({cdpClient:this.cdpClient,page:r,logger:this.logger}),{resolution:o,logs:i}=await x0({page:r,frameTree:n,cache:e});return this.logger.info({logs:i},"Resolved auto frame cache"),{...o,cache:e}}async resolveActiveFrameConfig({logger:e=this.logger,signal:r=this.abortSignalGetter()}){if(!this.frameConfig)return null;if(this.activeFrameCache)if(pg(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:r}):n={source:"auto",frame:this.frameConfig.frame,handle:this.frameConfig.handle,frameIdentifierStringified:pg(this.frameConfig),cacheTime:Date.now(),frameTree:this.frameConfig.frameTree,mPathSelectorTokens:this.frameConfig.mPathSelectorTokens},await P0({frame:n.frame,logger:e,signal:r}),this.activeFrameCache=n,n}async executeFunctionInAllFrames(e,r){let n=this.pageGetter(),o=await Lc({cdpClient:this.cdpClient,page:n,logger:this.logger}),i=[J(n.evaluate(e,r),{milliseconds:st})],a=Array.from(o.childFrames);for(;a.length>0;){let c=a.shift(),l=c.url;l==="about:blank"||l.startsWith("chrome-error://")||(a.push(...c.childFrames),i.push(Zo(c,n).then(({frame:u})=>J(u.evaluate(e,r),{milliseconds:st})).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(),r=await Lc({cdpClient:this.cdpClient,page:e,logger:this.logger}),n=Array.from(r.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:r,logger:n}){let o=await this.getDOMTree({devicePixelRatio:e??1,signal:r,logger:n??this.logger});return this.lastDomGraph=o,o}async getA11yTree(e){let r={},n=e.logger??this.logger,o=e.abortSignal??this.abortSignalGetter(),{frameContext:i,startingFrameId:a}=await this.getFrameTreeAndAddMomenticIds({skipPageLoad:e.skipPageLoad,logger:n,signal:o,logTimings:r}),s=await ro({fn:()=>this.getDomGraph({devicePixelRatio:e.devicePixelRatio??1,signal:o,logger:n}),codePath:"domFetch",logObject:r,signal:o,logger:n}),c=await ro({fn:()=>this.getRawA11yGraph({cdpClient:this.cdpClient,frameId:a,childFrames:i.childFrames,logTimings:r,logger:n,signal:o}),codePath:"totalA11yFetch",logObject:r,signal:o,logger:n}),{tree:l}=await ro({fn:()=>this.composeA11yDomGraph({opts:e,a11yGraph:c,domGraph:s,startingFrameId:a,frameContext:i,logger:n,iconKnowledgeBase:this.iconKnowledgeBase,showZeroOpacityElements:e.showZeroOpacityElements,flagNotActionableNodes:e.flagNotActionableNodes}),codePath:"a11yProcess",logObject:r,signal:o,logger:n});return Object.values(r).some(u=>u>750)&&n.warn({logTimings:r},"A11y tree fetch component took a long time"),this.lastA11yIdToNodeMap=l.a11yIdNodeMap,this.lastDataMomenticIdToNodeMap=l.dataMomenticIdMap,this.lastA11yTreeRoot=l.root,this.lastDomGraph=s,this.lastSelectorToNodeMap=l.selectorToNodeMap,this.lastA11yTreeFetchTimeMs=Date.now(),l}getNodeUsingDataMomenticId(e){if(this.lastA11yTreeFetchTimeMs&&!(Date.now()-this.lastA11yTreeFetchTimeMs>1e4))return this.lastDataMomenticIdToNodeMap[e]}async getFrameTreeAndAddMomenticIds({skipPageLoad:e,logger:r=this.logger,signal:n=this.abortSignalGetter(),logTimings:o}){let i=this.pageGetter();if(!e)try{await i.waitForLoadState("load",{timeout:this.pageLoadTimeoutMs})}catch(l){r.warn({err:l},"Failed to wait for page load event before a11y tree fetch, attempting to continue without it..."),await this.cdpClient.reinitialize()}let a,s,c=null;if(this.frameConfig?.type==="url"){if(a=await ro({fn:()=>this.resolveActiveFrameConfig({logger:r,signal:n}),codePath:"getActiveFrameDetails",logObject:o,signal:n,logger:r})??void 0,!a)throw new L("ActionFailureError","Got null frame details despite active frame config");s=a.handle,c=s.frameId}else this.userControlledBrowserSettings.autoExpandIframes?(s=await ro({fn:()=>Lc({cdpClient:this.cdpClient,page:this.pageGetter(),logger:r}),codePath:"getMomenticFrameTree",logObject:o,signal:n,logger:r}),c=null):(s={type:"root",page:i,childFrames:[]},c=null);return await ro({fn:async()=>this.addMomenticIds({rootPage:i,childFrames:s.childFrames,frameFilter:a?.frame,logger:r}),codePath:"addIdsToElement",logObject:o,signal:n,logger:r}),{startingFrameOverride:a,frameContext:s,startingFrameId:c}}async fetchA11yTreeForRecording(e,r){if(await this.getA11yTree({devicePixelRatio:e,abortSignal:r,logger:zo,filterByViewport:!1,flagNotActionableNodes:!1,skipPageLoad:!0}),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:r,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=u0({node:o,domGraph:this.domGraph});return d0(e,i)}else return n.domNode||this.logger.warn({a11yRole:n.role,content:n.content},"Attempting to get locator from a11y node with no DOM node"),this.getLocatorFromBackendId(r,n.backendNodeId)}async getLocatorFromBackendId(e,r){let n=await this.cdpClient.send({method:"DOM.resolveNode",params:{backendNodeId:r},timeout:st});if(!n||!n.object.objectId)throw new Error(`Could not resolve backend node ${r}`);let o;try{o=await p0(this.cdpClient,n.object.objectId)}catch(i){throw this.logger.debug({err:i,object:JSON.stringify(n.object)},"Failed to get ID attribute for target"),i}return e.locator(Ii(o))}getNodeUsingMPathSelector(e){let r=this.selectorToNodeMap[e];if(r)return r;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}}}async resolveUrlMatcherFrameConfig({config:e,signal:r=this.abortSignalGetter(),logger:n=this.logger}){let o=Date.now(),i,a,s,c=0;for(;Date.now()-o<this.smartWaitingTimeoutMs;)try{i=await Lc({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(l){if(s=l,l instanceof L&&l.reason==="UserInfrastructureError")throw l;c%3===0&&this.logger.warn({attempt:c,err:l},"Failed to resolve active frame, retrying..."),await xe(dr,r)}finally{c++}if(a)return{source:"url",frame:a.frame,handle:a.handle,frameIdentifierStringified:pg(e),cacheTime:Date.now(),frameTree:i,mPathSelectorTokens:[]};throw s}async getMatchingFrameByUrlWithCdp(e,r){let n=r.url,o=this.pageGetter(),i=Array.from(e.childFrames),a=[];for(;i.length>0;){let s=i.shift(),c=s.domNode;i.push(...s.childFrames);let l=va(c.attributes??[],"src"),u=c.contentDocument?.documentURL;if(!l&&!u){this.logger.debug("Skipping frame with no URL or src");continue}for(let d of[l,u])if(d){if(n.startsWith("/")&&n.endsWith("/")){if(new RegExp(n.slice(1,-1)).test(d)){a.push({handle:s,matchType:"regex",...await Zo(s,o)});break}}else if(n.trim()===d.trim()){a.push({handle:s,matchType:"url",...await Zo(s,o)});break}}}if(a.length===1){let s=a[0];return this.userControlledBrowserSettings.autoExpandIframes||(s.handle.childFrames=[]),s}else throw a.length>1?new Error(`Found multiple frames with src matching '${n}'. Please use a more specific selector.`):new L("ActionFailureError",`Failed to find frame with src matching: ${n}`)}async composeA11yDomGraph({opts:e,a11yGraph:r,domGraph:n,startingFrameId:o,frameContext:i,logger:a,iconKnowledgeBase:s,showZeroOpacityElements:c,flagNotActionableNodes:l}){let u=await T0({rawA11yGraph:r,startingFrameId:o,frameContext:i,domGraph:n,logger:a,cdpClient:this.cdpClient,showZeroOpacityElements:c,flagNotActionableNodes:l,filterByViewport:e.filterByViewport,importantProperties:{attributes:this.userControlledBrowserSettings.importantAttributes,classes:this.userControlledBrowserSettings.importantClasses,styles:this.userControlledBrowserSettings.importantStyles},viewportDetails:void 0,iconKnowledgeBase:s,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:r,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(r),s=[];for(;a.length>0;){let c=a.shift();a.push(...c.childFrames);let l=async()=>{try{let{frame:u}=await Zo(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...")}};s.push(l())}await Promise.all(s)}async addMomenticIdsHelper(e,r){if(this.userControlledBrowserSettings.visualActions)return r;let n=this.logger;return await Qt({root:e,fn:i=>window.addIdsToElement?.(document.body,i),arg:r,timeout:st,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"})??r}getPageDomain(e){try{let r=new URL(e);if(!r.hostname)return null;let n=r.hostname.split("."),o=n.length>2?n.slice(-2).join("."):r.hostname;return`${r.protocol}//${o}`}catch{return null}}async decideChildFrameUnrollEligibility({logger:e,warnings:r,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 r?.push(i),e?.warn({err:o},i),{shouldUnroll:!0}}}async decideChildFrameUnrollEligibilityHelper({domNode:e}){let r=e.attributes??[];if(va(r,"aria-hidden")==="true")return{shouldUnroll:!1,reason:"aria-hidden"};let n=va(r,"style");if(n?.includes("display: none")||n?.includes("visibility: hidden"))return{shouldUnroll:!1,reason:"hidden CSS style"};await this.cdpClient.send({timeout:pe,method:"DOM.pushNodesByBackendIdsToFrontend",params:{backendNodeIds:[e.backendNodeId]}});let[o,i]=await Promise.all([this.cdpClient.send({timeout:pe,method:"DOM.getBoxModel",params:{backendNodeId:e.backendNodeId}}),this.cdpClient.send({timeout:pe,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:r,childFrames:n,logTimings:o,logger:i=this.logger,signal:a=this.abortSignalGetter()}){let s=[],c,l;for(let m=0;m<3;m++)try{l=await ro({fn:()=>this.getRawA11yTreeForFrame({frameId:r,timeoutMs:this.pageLoadTimeoutMs,logTimings:o}),codePath:"a11y-tree-fetch-root",logObject:o,logger:i});break}catch(f){c=f,i.warn({err:f},"Reinitializing CDP client before retrying a11y graph fetch"),await this.cdpClient.reinitialize()}if(!l)throw new Error(`Failed to fetch accessibility tree for root page: ${c}`);let u={};if(u[r??"root"]=l,!this.userControlledBrowserSettings.autoExpandIframes)return u;let d=Array.from(n),p=[];for(;d.length>0;){let m=d.shift();try{let{shouldUnroll:h}=await this.decideChildFrameUnrollEligibility({handle:m,warnings:s});if(!h)continue}catch(h){if(h.message.includes("Could not compute box model"))continue;s.push(`Got error when determining whether to filter frame ${m.frameId} with url ${m.url}, allowing it to be fetched: ${h}`)}d.push(...m.childFrames);let f=async()=>{try{let h=await ro({fn:()=>this.getRawA11yTreeForFrame({frameId:m.frameId,timeoutMs:this.smartWaitingTimeoutMs,logTimings:o}),codePath:`a11y-tree-fetch-child-${m.frameId}`,logObject:o,logger:i});u[m.frameId]=h}catch(h){i.warn({err:h,url:m.url,src:m.src},`Error getting raw a11y tree for child frame ${m.frameId}, continuing...`)}};p.push(f())}return await Promise.all(p),s.length>0&&this.logger.warn({warnings:s},"Got warnings when fetching the raw a11y graph"),u}async getRawA11yTreeForFrame({frameId:e,timeoutMs:r,logTimings:n}){let o=await this.cdpClient.withDomainEnabled({domain:"Accessibility",fn:async()=>{if(this.allowPartialAccessibilityTree)return(await ro({fn:()=>this.cdpClient.send({method:"Accessibility.getFullAXTree",params:{frameId:e??void 0},timeout:r,timeoutMsg:`Fetching the document tree took over ${r}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;let a=(await ro({fn:()=>this.cdpClient.send({method:"Accessibility.getRootAXNode",params:{frameId:e??void 0},timeout:st}),codePath:"cdp-get-root-ax-node",logObject:n,logger:this.logger})).node.backendDOMNodeId;return(await ro({fn:()=>this.cdpClient.send({method:"Accessibility.queryAXTree",params:{backendNodeId:a},timeout:r,timeoutMsg:`Fetching the document tree took over ${r}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:r,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:pe}),!o||!o.documents.length)throw new Error("Got empty DOM tree")}catch(s){await xe(dr,r),i++,a=s}if(!o||!o.documents.length)throw n.error({err:a},"Fatal error fetching DOM tree"),new L("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 c0({snapshot:o,devicePixelRatio:e,computedStylesToFetch:this.computedStylesToFetch,logger:n})}constructIframeRegexAsync(e,r){if(r.frameSrcRegex||r.frameUrlRegex)return;let n=_0(e);(async()=>{try{let o=await this.enricher?.constructIframeRegex(n);o?.srcRegex&&(r.frameSrcRegex=o.srcRegex),o?.urlRegex&&(r.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...")}})()}};var no=class t{static USER_AGENT=ig;abortSignal=void 0;contextInitialized=!1;cleanedUp=!1;browser;context;properties;page;userControlledBrowserSettings;pageLoadPromises={};lastTabChangeEventTimeout=void 0;pageLoadAbortControllers=new Set;pageLoadAbortListenerCleanup;clientCallbacks;harBatcher;iconKnowledgeBase;cdpClient;debugData={logsPerPage:[]};recentFrameNavigations={};requestRecorders={};mocks={};customHeaders=[];enricher;storage;logger;stateManager;transformer;lastScreenshotForRecording=void 0;originsVisited=new Set;viewport;onVideoPageChange;baseUrl;constructor({storage:e,enricher:r,browser:n,context:o,page:i,baseUrl:a,logger:s,userBrowserSettings:c,viewport:l,properties:u,clientCallbacks:d,iconKnowledgeBase:p,onVideoPageChange:m}){gI(c),this.storage=e,this.enricher=r,this.browser=n,this.context=o,this.page=i,this.baseUrl=a,this.logger=s,this.userControlledBrowserSettings=c,this.viewport=l,this.properties=u,this.clientCallbacks=d,this.iconKnowledgeBase=p,this.onVideoPageChange=m}registerAbortSignal(e){if(this.pageLoadAbortListenerCleanup&&(this.pageLoadAbortListenerCleanup(),this.pageLoadAbortListenerCleanup=void 0),this.abortSignal=e,!this.abortSignal)return;let r=()=>{for(let n of this.pageLoadAbortControllers)n.abort();this.pageLoadAbortControllers.clear()};if(this.abortSignal.aborted){r();return}this.abortSignal.addEventListener("abort",r),this.pageLoadAbortListenerCleanup=()=>{this.abortSignal?.removeEventListener("abort",r)}}async initialize({grantPermissions:e,permissionsToGrant:r,runInitScripts:n,timingRecorder:o}){if(this.contextInitialized)return;let i={[ik]:this.userBrowserSettings.visualActions},a=[];this.userControlledBrowserSettings.extraHeaders&&a.push(this.context.setExtraHTTPHeaders(this.userControlledBrowserSettings.extraHeaders)),e&&a.push(this.context.grantPermissions(Vk(r))),a.push(this.context.addInitScript({content:`${Gb.htmlUtilsLibJs}
|
|
4603
4604
|
//# sourceURL=momentic-injected/browser-scripts.js`}),this.context.addInitScript({content:cv(i,this.userBrowserSettings.disableFullStory)}),this.exposeRecordingBindings());let s=d=>this.handleNewPageEvent(d);this.context.on("page",s),this.handleNewPageEventHelper(this.page),this.context.on("close",()=>{this.context.off("page",s)});let c=!1;if(n){let d=async()=>{let p=Date.now();try{await Promise.all([this.page.addScriptTag({content:`${Gb.htmlUtilsLibJs}
|
|
4604
4605
|
//# sourceURL=momentic-injected/browser-scripts.js`}),this.page.addScriptTag({content:cv(i,this.userBrowserSettings.disableFullStory)})])}catch(m){if(m instanceof Error&&(m.message.includes("Content Security Policy")||m.message.includes("TrustedScript")))this.logger.warn({err:m},"Content Security Policy error from adding Momentic scripts, reloading page instead"),c=!0;else throw m}(o??{})["add-init-scripts"]=Date.now()-p};a.push(d())}if(!this.properties.systemDevicePixelRatio)if(process.env.MOMENTIC_LOCAL_DEV==="1"&&p8()==="darwin"&&a8("system_profiler SPDisplaysDataType").toString().includes("Retina"))v.warn("[DEV] Setting device pixel ratio to 2 in local dev since a Retina display was detected"),this.properties.systemDevicePixelRatio=2;else{let d=async()=>{let p=Date.now();this.properties.systemDevicePixelRatio=await this.page.evaluate(()=>window.devicePixelRatio),(o??{})["fetch-dpr"]=Date.now()-p};a.push(d())}let l=Date.now();await J(Promise.all(a),{milliseconds:this.pageLoadTimeout,message:"Timed out attaching Chrome permissions and initialization scripts",signal:this.abortSignal});let u=Date.now();(o??{})["ops-attach"]=u-l,c&&await this.page.reload(),this.cdpClient=await dg.init({logger:this.logger,contextGetter:()=>this.context,pageGetter:()=>this.page,defaultTimeoutMs:this.pageLoadTimeout}),(o??{})["cdp-init"]=Date.now()-u,await this.initializeScreencast(),this.stateManager=new fg({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 r=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:r}})}catch{}})()})}))}static async init(e){let r=await Gk(e),n=new t(r);return await n.initialize({grantPermissions:!0,permissionsToGrant:e.userBrowserSettings.grantedPermissions,runInitScripts:!1}),n}static async fromExistingContext({context:e,page:r,attachTimeoutMs:n,storage:o,enricher:i,userBrowserSettings:a,properties:s,logger:c,timingRecorder:l}){let u=r??e.pages()[0];if(!u)throw new Error("No page found in existing context");let d=u.viewportSize();if(!d){let f=Date.now();d=await J(u.evaluate(()=>({width:window.innerWidth,height:window.innerHeight})),{milliseconds:n??1/0,message:"Timed out connecting Playwright to the webview"}),l["eval-viewport"]=Date.now()-f}let p=u?.url(),m=new t({browser:e.browser(),context:e,page:u,baseUrl:p,logger:c,storage:o,enricher:i,userBrowserSettings:a,viewport:d,properties:s,clientCallbacks:void 0,iconKnowledgeBase:null});try{await J(m.initialize({grantPermissions:!1,runInitScripts:!0,timingRecorder:l}),{milliseconds:n??1/0,message:"Timed out connecting Playwright to the webview"})}catch(f){throw await m.cleanup(),f}return m}async handleAvailableTabsChangeHelper(){try{let e=await Sv(this.context,{getTitles:!0}),r=this.page.url();this.clientCallbacks?.onTabsChange?.(e,r)}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,r){let n=hg(),o=`${e}-${n}`,i=Date.now(),a=!1,s=new AbortController;this.pageLoadAbortControllers.add(s);let c=async()=>{try{await J(r(),{signal:s.signal,milliseconds:this.pageLoadTimeout,message:`Page load promise for code path ${e} timed out after ${this.pageLoadTimeout}ms`})}catch(l){l.name!=="AbortError"&&!this.closed&&this.logger.error({err:l,promiseKey:o,codePath:e,duration:Date.now()-i},`Page load promise for code path ${e} encountered error`)}finally{delete this.pageLoadPromises[o],this.pageLoadAbortControllers.delete(s),a=!0}};this.pageLoadPromises[o]=c().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 r=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()||!Cs(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()=>r())}handleNewPageEvent(e){let r=e.url();this.logger.info({url:r},"Detected new page event, registering handlers and waiting for load to complete");try{this.handleNewPageEventHelper(e)}catch(n){this.logger.warn({err:n},"Error handling new page open, continuing....")}}handleNewPageEventHelper(e){let r=hg(),n="new-page-load-handler";e.on("close",a=>this.handlePageClosedEvent(a)),e.on("framenavigated",a=>this.handleFrameNavigationEvent(a)),e.on("crash",()=>{this.logger.error("Page crashed at the Playwright level!")});let o=this.context.pages().indexOf(e);!this.userBrowserSettings.disableBrowserMonitoring&&!this.userControlledBrowserSettings.disableConsoleLogs&&e.on("console",a=>{Rk(e,o,this.debugData,a,this.logger)});let i=async()=>{!this.userBrowserSettings.disableBrowserMonitoring&&!this.userControlledBrowserSettings.disableNetworkLogs&&(_k(this.logger,r,this.clientCallbacks?.onNetworkPage,e),!this.harBatcher&&this.clientCallbacks?.onNetworkLogs&&(this.harBatcher=L0(this.clientCallbacks.onNetworkLogs)),await e.route("**/*",async(a,s)=>{await rv({pageId:r,route:a,request:s,onHarEntry:(c,l)=>{this.harBatcher?.fetch({[c]:l}).catch(()=>{})},logger:this.logger,requestRecorders:this.requestRecorders,mocks:this.mocks,isBrowserClosed:()=>this.closed})}),await e.route("**/*",Nk(this.customHeaders,this.logger))),Gn&&await e.route("**/*",Zd),await this.loadFrameAndRecordUrl({root:e,codePath:n}),this.handleAvailableTabsChange()};this.addToPageLoadPromises(n,async()=>i())}async handleCollectSvgs(e){}handleFrameNavigationEvent(e){let r=e.url(),n=e.parentFrame()?"has-parent":"no-parent",o=`frame-navigation-handler-${r.slice(0,50)} (${n})`;if(!r||r==="about:blank"||!Cs(r))return;let i=this.recentFrameNavigations[o];if(i&&Date.now()-i<1e3)return;this.recentFrameNavigations[o]=Date.now();let a=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(c){this.logger.warn({err:c},"Failed to collect SVGs on page, continuing...")}})()},5e3),this.transformer&&await this.injectKnowledgeBaseIntoBrowser(e))}catch(s){s.name!=="AbortError"&&this.logger.warn({err:s,url:r,codePath:o},"Failed to handle frame navigation event, continuing...")}};this.addToPageLoadPromises(o,async()=>a())}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(r){this.logger.warn({err:r},"Failed to inject icon knowledge base into browser, continuing...")}}getBrowserCallbacks(){return{waitForPageLoad:()=>this.waitForPageLoad(),waitForUrl:e=>this.waitForUrl(e),waitForStability:e=>this.waitForStability(e),state:{url:()=>this.url(),getDomGraph:()=>this.stateManager.domGraph,getOpenPages:()=>this.getOpenPages(),getRoot:()=>this.getActivePageOrFrame(),userBrowserSettings:this.userBrowserSettings},pageLoadTimeoutMs:this.pageLoadTimeout,signal:this.abortSignal}}ping(){if(this.closed)throw new Error("Page has been closed")}setActiveFrameConfig(e){this.stateManager.setActiveFrameConfig(e)}async reset(e){this.abortSignal=void 0,this.debugData.logsPerPage=[],this.pageLoadPromises={},await this.clearAuthState({closeNonActiveTabs:!0}),await this.stopScreencast(),await this.reinitializeCDPClient(),await this.navigate({url:e.newUrl??this.baseUrl,initialNavigation:!0,loadTimeoutMs:e.timeout}),this.stateManager.reset()}async clearHighlights(){try{await J(fv(this.getBrowserCallbacks()),{milliseconds:Qe})}catch(e){this.logger.debug({err:e},"Failed to clear highlights, continuing...")}}async cleanup(){this.abortSignal=void 0,this.cleanedUp=!0;try{this.pageLoadAbortListenerCleanup?.(),this.pageLoadAbortListenerCleanup=void 0,this.pageLoadAbortControllers.forEach(e=>e.abort()),this.pageLoadAbortControllers.clear(),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.cleanedUp||this.context.pages().every(e=>e.isClosed())||!!this.browser&&!this.browser.isConnected()}async ensureMomenticBrowserScriptsLoaded(e,r,n){let o=Date.now(),i=0,a=0;for(;Date.now()-o<Mc;){a++,n?.throwIfAborted();try{if(await Qt({fn:()=>{let c=window;return!!(c.generateCssSelectors&&c.evaluateCssSelectors&&c.evaluatePrimaryCaches&&c.generateHtmlCacheAttributes&&c.ldist)},timeout:Qe,arg:void 0,waitForPageLoad:()=>this.waitForPageLoad(),root:e,codePath:"ensuring Momentic system scripts are loaded"}))return}catch(s){if(i++,i>=3){r.warn({err:s},"Multiple errors checking if Momentic scripts are loaded, aborting...");return}}await xe(dr),a%2===0&&r.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),Qt({root:e,fn:()=>{let r=window;if(!r?.getFullHtmlTree)throw new Error("Missing Momentic HTML library when fetching page HTML");return r.getFullHtmlTree()},arg:void 0,timeout:pe,waitForPageLoad:()=>this.waitForPageLoad(),codePath:"getting the full HTML tree"})}url(){return this.page.url()}async stabilizePageForScreenshot(){try{await this.evaluateFunctionInPage(()=>{let e=window,r=[],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")}),r.push(()=>{for(let[o,i]of n)o.style.setProperty("caret-color",i.value,i.priority)}),e._MOMENTIC_SCREENSHOT_CLEANUP=()=>{for(let o of r)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:r=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:r});if(a.byteLength>5e6)this.logger.warn("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(r<=0||a.message.includes("has been closed"))throw a;return this.logger.warn({err:a,pageUrl:o},"Failed taking screenshot, retrying..."),await xe(ya),this.screenshot({...e,retries:r-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:r,saveToDiskPath:n,timeout:o,respectActiveFrame:i,clearHighlights:a=!1}){a&&await this.clearHighlights(),i&&this.stateManager.frameConfig&&(e=await(await this.getActivePageOrFrame()).frameElement());let s=await this.cdpClient.send({method:"Page.captureScreenshot",params:{format:"jpeg",quality:r,optimizeForSpeed:!0},timeout:o??st}),c=Buffer.from(s.data,"base64"),l=await k0.fromBuffer(c),{width:u,height:d}=this.getViewport()??{};if(u&&d&&(l.bitmap.width!==u||l.bitmap.height!==d)&&(c=await l.resize({w:u,h:d}).getBuffer("image/jpeg")),n&&c8(n,c),this.lastScreenshotForRecording=c,!e)return c;let p=await e.boundingBox({timeout:pe});if(!p)throw new Error("Attempted to screenshot an element that is not visible on the page");let{x:m,y:f,width:h,height:S}=p;if(!h||!S)throw new Error("Attempted to screenshot an element with zero width or height");m=Math.floor(m),f=Math.floor(f),h=Math.floor(h),S=Math.floor(S);try{let g=await k0.fromBuffer(c),E=g.bitmap.width,y=g.bitmap.height;m=Math.max(0,Math.min(m,E-1)),f=Math.max(0,Math.min(f,y-1)),h=Math.max(1,Math.min(h,E-m)),S=Math.max(1,Math.min(S,y-f)),c=await g.crop({x:m,y:f,w:h,h:S}).getBuffer("image/jpeg")}catch(g){throw new Error(`Failed taking element screenshot at coordinates (${m}, ${f}) with size (${h}, ${S}): ${g}`)}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:r=!1,loadTimeoutMs:n=this.pageLoadTimeout}){CN(e)&&(e=new URL(e,this.baseUrl).toString());let o=Date.now();r||(await this.waitForPageLoad(),await this.waitForStability());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(l){if(a=l,this.abortSignal?.throwIfAborted(),this.shouldIgnorePageLoadTimeout(a)){i=!0,this.logger.warn({err:a,url:e},"DOMContentLoaded timed out during navigation, continuing due to browser setting");break}if(this.logger.warn({err:l},`Error occurred during navigation${c===0?", retrying...":" (fatal)"}`),await xe(dr),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:Qe})}if(!i)throw new L("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 s=this.url();if(mk.has(s))throw new L("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,r={},n=!1){await this.directTypeHelper(e,r,n)}async getActiveElementHandle(e){return e.evaluateHandle(()=>document.activeElement)}async getActiveElement(e){try{return await Qt({root:e,fn:()=>{let n=document.activeElement?.textContent??void 0;n&&n.length>100&&(n=n.slice(0,100)+"...[TRUNCATED]");let o=!1,i=window.getSelection();i&&!i.isCollapsed&&i.toString().trim().length>0&&(o=!0);let a=document.activeElement;return a&&"selectionStart"in a&&typeof a.selectionStart=="number"&&typeof a.selectionEnd=="number"&&a.selectionStart!==a.selectionEnd&&(o=!0),document.activeElement?{tag:document.activeElement.tagName.toLowerCase(),contentEditable:document.activeElement.getAttribute("contenteditable")??void 0,textContent:n,hasTextSelected:o}:{hasTextSelected:o}},arg:void 0,timeout:Qe,waitForPageLoad:()=>this.waitForPageLoad(),codePath:"getting the active element"})}catch(r){this.logger.warn({err:r},"Failed to get active element");return}}async directTypeHelper(e,r={},n=!1){let o=await this.getActivePageOrFrame();await Zk({root:o,text:e,options:r,logger:this.logger,callbacks:this.getBrowserCallbacks()});let i=await this.getActiveElement(o);if(n){let s=Date.now();for(;Date.now()-s<this.smartWaitingTimeout&&(!i||i.tag==="body");)await xe(ya),this.abortSignal?.throwIfAborted(),i=await this.getActiveElement(o);i||this.logger.warn("No active element found to type into, attempting anyways")}let a=i?.tag==="input"||i?.tag==="textarea";if(r.clearContent)if(a||r.forceClearContent)if(this.properties.isAndroid&&!a&&i?.textContent){this.logger.info("Clearing content using backspaces");let s=0,c=i.textContent?.length;for(;c&&s<50;){s++;let l=[...Array(c)].map(()=>"Backspace").join("+");await this.page.keyboard.press(l),i=await this.getActiveElement(o),c=i?.textContent?.length}c&&this.logger.warn("Content still remains after clearing existing")}else 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);else this.logger.info({activeElementDetails:i},"Currently active element is not eligible for replace content, skipping...");await this.page.keyboard.type(e,{delay:r.delay??gC}),r.pressEnter&&await this.press("Enter",{}),await this.waitForStability()}async scrollIntoViewIfNeeded(e){try{await e.scrollIntoViewIfNeeded({timeout:st})}catch(r){this.logger.warn({err:r},"Failed to scroll into view, trying with raw JS");try{await e.evaluate(async n=>{let o=n.scrollTop;n.scrollIntoView({block:"nearest"}),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(s=>setTimeout(s,250))}},void 0,{timeout:st})}catch(n){this.logger.warn({err:n},"Failed to scroll into view using JS, continuing...")}}}async highlightA11yId(e){try{let{resolution:r}=await this.createTargetFromA11yId({id:e,description:null,targetSource:"AI",skipSaveToCache:!0});return await this.highlight(r.locator),!0}catch(r){return this.logger.debug({err:r,id:e},"Failed to highlight target"),!1}}async highlight(e){return cg({locator:e,callbacks:this.getBrowserCallbacks(),logger:this.logger})}recordUrlVisited(e){try{let r=new URL(e).origin;if(r==="null")return;this.originsVisited.add(r)}catch(r){this.logger.warn({err:r},"Failed to record origin visited")}}async waitForPageLoad(){let e=Date.now(),r=Object.values(this.pageLoadPromises),n=Object.keys(this.pageLoadPromises),o=-1,i=0;for(;r.length!==0;){if(Date.now()-e>this.pageLoadTimeout&&this.logger.warn({outstandingPromiseKeys:n,outstandingPromises:r},"Still waiting on page load promises"),Date.now()-o<20&&(i++,i>2)){this.logger.error({outstandingPromiseKeys:n,outstandingPromises:r},"Synchronous waiting loop detected, exiting page load wait");return}o=Date.now(),await Promise.allSettled(r),r=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:Qe}),this.originsVisited.delete(o);let r=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 Ck(i,this.logger),o!==r&&e.closeNonActiveTabs&&(this.logger.info(`Closing tab ${o} with URL ${a}`),await i.close())}}async loadAuthState(e){await this.waitForPageLoad(),await this.waitForStability(),!e||Object.keys(e).length===0?await this.clearAuthState({closeNonActiveTabs:!1}):await this.loadAuthStateHelper(e),await this.refresh(),await this.waitForStability()}async loadAuthStateHelper(e){let r=[];for(let c of e.cookies??[]){let l=await this.setCookie(c);r=r.concat(l)}this.logger.info(`Loaded ${e.cookies?.length??0} cookies`);let n=0,o=[];await this.cdpClient.withDomainEnabled({domain:"DOMStorage",timeout:Qe,fn:async()=>{for(let c of e.origins??[])for(let l of c.localStorage)try{await this.cdpClient.send({timeout:Qe,method:"DOMStorage.setDOMStorageItem",params:{storageId:{securityOrigin:new URL(c.origin).origin,isLocalStorage:!0},key:l.name,value:l.value}}),n++}catch(u){o.some(d=>d.origin===c.origin&&d.key===l.name)||o.push({key:l.name,origin:c.origin,err:u});continue}}}),o.length>0&&this.logger.warn({failedOrigins:o,currentPageUrl:this.page.url()},"Failed to set localStorage for entries, continuing..."),this.logger.info(`Loaded ${n} local storage entries`);let i={},a=0;for(let c of e.origins??[])if(c.sessionStorage&&c.sessionStorage.length>0){let l={};for(let u of c.sessionStorage)l[u.name]=u.value,a++;i[new URL(c.origin).origin]=l}a>0&&await this.context.addInitScript(({storageByOrigin:c,markerKey:l})=>{let u=window.location.origin,d=c[u];if(d&&!window.sessionStorage.getItem(l)){for(let[p,m]of Object.entries(d))window.sessionStorage.setItem(p,m);window.sessionStorage.setItem(l,"1")}},{storageByOrigin:i,markerKey:dv}),this.logger.info(`Loaded ${a} session storage entries`);let s=e.idb;s&&Object.keys(s).length>0&&(await Ak(this.page,s,this.logger),this.logger.info(`Loaded ${Object.keys(s??{}).length} indexedDB databases`))}async saveAuthState(){let r=0,n=null;for(;r<=2;)try{await this.waitForPageLoad(),await this.waitForStability();let o=await this.context.storageState();return o.idb=await vk(this.page,this.logger),await $k(this.page,o,this.logger),o}catch(o){if(n=o,r++,r<=2){this.logger.warn({err:o,retryCount:r,maxRetries:2},`Error saving auth state, retrying (${r}/2)...`);let i=Math.pow(2,r)*100;await new Promise(a=>setTimeout(a,i))}}throw this.logger.error({err:n},"Failed to save auth state after 2 retries"),new L("ActionFailureError",`Failed to save auth state: ${n?.message}`)}async getOpenPages(e){return Sv(this.context,e)}saveA11yDetailsToCache(e,r){r.content=e.content,r.name=e.name,r.role=e.role,r.numChildren=e.children.length,delete r.serializedForm,delete r.nodeOnlySerializedForm}async updateCacheWithNewNodeDetails({node:e,target:r,locator:n,originalElementLocationResult:o,allowNotActionableNodesOverride:i,logger:a=this.logger,skipSavingVisualAttributes:s=!1}){if(e&&this.saveA11yDetailsToCache(e,r),r.frameCache=this.stateManager.saveAutoFrameCacheDetails(r.frameCache),n)try{let c=await this.fetchHtmlAttributes({locator:n,logger:a,originalElementLocationResult:o,allowNotActionableNodesOverride:i});c?(r.generatedSelectors=c.generatedSelectors,r.serializedHtml=c.serializedHtml,r.nodeOnlySerializedHtml=c.nodeOnlySerializedHtml,r.hybridSelector=c.hybridSelector):a.warn("Got undefined HTML attributes when trying to update cache")}catch(c){if(c instanceof yl)throw a.warn({err:c},"Error while fetching HTML attributes triggering retry"),c;a.warn({err:c},"Failed to fetch HTML attributes for target, continuing...")}try{s||await this.saveElementVisualAttributes({target:r,locator:n,originalElementLocationResult:o,logger:a})}catch(c){a.debug({err:c},"Failed to save element visual details, continuing...")}}async saveElementVisualAttributes({target:e,locator:r,originalElementLocationResult:n,logger:o}){if(!r||!pv(e,n))return;let i=await r.boundingBox({timeout:Qe});if(!i||!i.width||!i.height){o.debug("Skipping visual attributes saving for element with no bounding box after action"),e.boundingBox=void 0,e.screenshotUrl=void 0;return}let a=this.getViewport();if(i.x<0||i.y<0||!a||i.x+i.width>a.width||i.y+i.height>a.height)return;let{x:s=0,y:c=0,width:l=0,height:u=0}=i;if(e.boundingBox&&Math.abs(e.boundingBox.width-l)<1&&Math.abs(e.boundingBox.height-u)<1&&Math.abs((e.boundingBox.x??0)-s)<1&&Math.abs((e.boundingBox.y??0)-c)<1)return;e.boundingBox=i;let d=await this.screenshot({locator:r,quality:75,retries:0}),p=hg(),m="image/jpeg";(async()=>{try{await this.storage.createOnDemandScreenshot(p,d,m)}catch(f){this.logger.warn({err:f,screenshotId:p},"Failed to persist on-demand screenshot")}})(),e.screenshotUrl={id:p,contentType:"image/jpeg"}}async resolveAutoFrameCache(e){return this.stateManager.resolveAutoFrameCache(e)}async getElementRequiredValues({logger:e,boundingBox:r,locator:n,requirements:o}){let i={},a=!!o?.position&&o.position!=="irrelevant",s=!!o?.shape&&o.shape!=="irrelevant";if(a||s){if(!r||!r.width||!r.height)throw new L("ActionFailureError","Element does not have a bounding box as required");s&&(i.shape={width:r.width,height:r.height,tolerance:o.shape}),a&&(i.position={x1:r.x,y1:r.y,x2:r.x+r.width,y2:r.y+r.height,tolerance:o.position})}if(o?.text){let c=await n.textContent({timeout:pe});i.text=c?.trim().slice(0,Cn.serializedElementForCachingTruncateLength)}if(o?.attributes&&o.attributes.length>0){let c={};for(let l of o.attributes){let u=l.trim().toLowerCase();if(!(!u||Cn.bannedAiRequiredCacheAttributes.includes(u)))try{let d=await n.getAttribute(u,{timeout:pe});d!==null&&(c[l]=d)}catch(d){e.warn({err:d,attr:l},"Failed to fetch required attribute, continuing...")}}i.attributes=c}return i}async getAdditionalDetailsForElement({mainLocator:e,mainBoundingBox:r,additionalElement:n,root:o,logger:i}){let a=this.stateManager.a11yIdToNodeMap[n.id];if(!a)return;let s=await this.stateManager.getLocatorFromA11yNode({page:this.page,root:o,node:a});if(e.contentFrame!==s.contentFrame)return;let c=await this.fetchHtmlAttributes({locator:s,logger:i});if(!c?.generatedSelectors||c.generatedSelectors.length===0)return;let l=await s.boundingBox({timeout:pe}),u={selectors:c.generatedSelectors,relativeAngleRadians:qk(r,l),relativeDistance:Kk(r,l)};return n.requirements&&(u.requirements=await this.getElementRequiredValues({logger:i,locator:s,boundingBox:l,requirements:n.requirements})),u}async getAllAdditionalElementsDetails({mainElementId:e,mainLocator:r,mainBoundingBox:n,additionalElements:o,root:i,logger:a}){let s=new Set,c=[];for(let d of o)d.id!==e&&(s.has(d.id)||(s.add(d.id),c.push(d)));let l=await Promise.allSettled(c.map(d=>this.getAdditionalDetailsForElement({mainLocator:r,mainBoundingBox:n,additionalElement:d,root:i,logger:a}))),u=[];for(let[d,p]of l.entries()){let m=c[d];if(m){if(p.status==="fulfilled"){let f=p.value;if(!f)continue;u.push(f);continue}this.logger.warn({err:p.reason,additionalElement:m},"Failed to fetch additional element details, continuing...")}}return u}async updateCacheWithAdditionalRequirements({mainElementId:e,requirements:r,additionalElements:n,target:o,locator:i,root:a,logger:s}){let c=await i.boundingBox({timeout:pe});if(r)try{o.requirements=await this.getElementRequiredValues({logger:s,boundingBox:c,locator:i,requirements:r})}catch(l){s.warn({err:l},"Failed to generate required values for target")}n&&n.length>0&&(o.additionalElements=await this.getAllAdditionalElementsDetails({mainElementId:e,mainBoundingBox:c,mainLocator:i,additionalElements:n,root:a,logger:s}))}async createTargetFromA11yId({id:e,description:r,targetSource:n,skipSaveToCache:o,skipSavingVisualAttributes:i,logger:a=this.logger,requirements:s,additionalElements:c}){if(e<0)throw new L("InternalWebAgentError","Only positive IDs should be passed to resolveAllyIdToTarget");let l=this.stateManager.a11yIdToNodeMap[e];if(!l)throw new L("InternalWebAgentError",`Resolving target failed because id ${e} does not exist on the page. This generally indicates an incorrect element was targeted.`);let u=this.stateManager.frameConfig,d,p,m,f;if(this.userBrowserSettings.autoExpandIframes&&!u&&l.parentFrame){let b=l.parentFrame,{cache:C,config:I}=await this.stateManager.getAutoFrameDetailsFromHandle(b);p=C,m=I,d=I.frame,f="auto iframe"}else l.parentFrame&&u?(m=u,d=await this.getActivePageOrFrame(),f="hardcoded url already on the state manager"):(d=await this.getActivePageOrFrame(),f="should not be possible");let h=await this.stateManager.getLocatorFromA11yNode({page:this.page,root:d,node:l}),S=await h.evaluate(b=>window.generateCommonLocationResultMetadata(b),void 0,{timeout:st}),g={id:e,inputDescription:r??void 0,targetSource:n,targetUpdateTime:new Date().toISOString(),targetUpdateLoggerTags:ot(a),frameCache:p},E,y=!1;o||(m&&(a.info({frameConfigSource:f,frameConfig:I0(m)},"A11y node was resolved to a target within an iframe"),E=this.stateManager.frameConfig,this.stateManager.setActiveFrameConfig(m),y=!0),await this.updateCacheWithAdditionalRequirements({mainElementId:e,requirements:s,additionalElements:c,target:g,root:d,locator:h,logger:a}),await this.updateCacheWithNewNodeDetails({node:l,target:g,locator:h,logger:a,allowNotActionableNodesOverride:!0,skipSavingVisualAttributes:i,originalElementLocationResult:S}));try{return{resolution:{locator:h,a11yNode:l,displayString:l.getNodeOnlySerializedForm(),originalElementLocationResult:S,decisions:[]},target:g,frameConfig:m,frameConfigSource:f}}finally{y&&this.stateManager.setActiveFrameConfig(E)}}async resolveTarget(e,r={}){let{logger:n=this.logger,signal:o=this.abortSignal,allowNotActionableNodesOverride:i,skipWaitForPageLoad:a}=r;if(e.frameCache&&this.userBrowserSettings.autoExpandIframes){let d,p=!1,m=Date.now();for(;Date.now()-m<this.smartWaitingTimeout;)try{let f=await this.stateManager.resolveAutoFrameCache(e.frameCache);this.setActiveFrameConfig(f),p=!0;break}catch(f){d=f,await xe(dr,o)}if(!p)throw d}let s=await this.getActivePageOrFrame();await this.ensureMomenticBrowserScriptsLoaded(s,n,o);let c=Date.now(),l=0,u;for(;Date.now()-c<this.smartWaitingTimeout;){this.abortSignal?.throwIfAborted(),l++;let d=l===2||Date.now()-c>this.smartWaitingTimeout-2e3&&l%2===0;try{u=await this.resolveTargetHelper({root:s,target:e,primaryOnly:!0,shouldLogOnFailure:d,logger:n,allowNotActionableNodesOverride:i,signal:o,skipWaitForPageLoad:a});break}catch(p){if(p instanceof mu)break;o?.throwIfAborted(),d&&n.warn({err:p},`Could not resolve target using primary cache only (x${l})`),await xe(dr,o)}}return u||(u=await this.resolveTargetHelper({root:s,target:e,primaryOnly:!1,logger:n,signal:o,allowNotActionableNodesOverride:i}),n.info({decisions:u.decisions},"Target resolution succeeded after waiting")),u}async resolveTargetHelper({root:e,target:r,primaryOnly:n,logger:o,signal:i,allowNotActionableNodesOverride:a,shouldLogOnFailure:s,skipWaitForPageLoad:c,skipSavingVisualAttributes:l}){let u=[],d;if(c||await this.waitForPageLoad(),this.userBrowserSettings.visualActions)await this.waitForStability({logger:o,signal:i});else{let m={};await this.stateManager.getFrameTreeAndAddMomenticIds({skipPageLoad:!0,logger:o,signal:i,logTimings:m}),Object.values(m).some(f=>f>750)&&o.warn({logTimings:m},"Momentic ID attach took a long time")}let p;if(r.generatedSelectors||r.hybridSelector){let m;try{m=await this.resolveTargetWithPrimaryMethods({root:e,target:r,logger:o,allowNotActionableNodesOverride:a,shouldLogOnFailure:s,skipSavingVisualAttributes:l})}catch(f){p=f,f instanceof fn&&(u.push(...f.decisions),d=f.cacheMissReason)}if(m)return{...m,decisions:[...u,...m.decisions]};n||(u.push({type:"CSS_SELECTOR",matched:!1,reason:p?.message,selectors:tp(r.generatedSelectors??[])}),r.generatedSelectors=void 0,r.hybridSelector=void 0)}if(n)throw p;if(!this.userBrowserSettings.disableSecondaryCacheResolution){let m=await this.resolveTargetWithSecondaryMethods({root:e,target:r,decisions:u,logger:o,signal:i,allowNotActionableNodesOverride:a,skipSavingVisualAttributes:l});if(m)return r.targetSource="HEURISTIC_HEALED",r.targetUpdateTime=new Date().toISOString(),r.targetUpdateLoggerTags=ot(o),m;d=d??"secondary-resolution-failed"}throw new fn("Could not find any relevant node given target",u,d)}async resolveTargetWithPrimaryMethods({root:e,target:r,logger:n,allowNotActionableNodesOverride:o,shouldLogOnFailure:i,skipSavingVisualAttributes:a}){if(!r.nodeOnlySerializedHtml)throw new mu("Insufficient data to resolve target using primary methods (missing node HTML)");let s={x:0,y:0};if(Wk(e)){let P=await(await e.frameElement()).boundingBox();P&&(s=P)}let c=i?n:zo,l=this.userControlledBrowserSettings.hybridSelectorMode,u=r.boundingBox,d=!!u?.width&&!!u?.height,p=!o&&d,m=this.userControlledBrowserSettings.bustCacheOnBoundingBoxChange&&d?u:void 0,f={ldistThreshold:pk,requireBoundingBox:p,ignoreHrefForCaching:this.userControlledBrowserSettings.ignoreHrefForCaching,requireMatchingBoundingBox:m,requirements:r.requirements,additionalElements:r.additionalElements,importantProperties:{attributes:this.userControlledBrowserSettings.importantAttributes,classes:this.userControlledBrowserSettings.importantClasses,styles:this.userControlledBrowserSettings.importantStyles},rootBoundingBox:s},h={cssParams:{selectors:r.generatedSelectors??[],cachedElementSerialized:r.nodeOnlySerializedHtml,opts:f},hybridParams:l&&r.hybridSelector?{nodes:r.hybridSelector,cachedElementSerialized:r.nodeOnlySerializedHtml,opts:f}:void 0},{css:S,hybrid:g}=await Qt({fn:P=>window.evaluatePrimaryCaches(P),arg:h,root:e,timeout:pe,waitForPageLoad:()=>this.waitForPageLoad(),codePath:"evaluating target caches"}),E,y,b=[];if(l==="prefer"&&g?.result){E=g.result;let P={type:"HYBRID_SELECTOR",matched:!0,logs:g.logs,reason:"Discovered a match using Momentic's hybrid text and CSS selector approach"};b.push(P),y="HYBRID_SELECTOR"}else if(S?.result){E=S.result;let P=`${E.workingSelectors.length} CSS selectors matched the following element: ${E.serializedElement}`,B=E.workingSelectors.slice(0,5);b.push({type:"CSS_SELECTOR",matched:!0,logs:S.logs,reason:P,selectors:B}),n.debug({reason:P,workingSelectors:B},"Resolved with CSS selectors"),y="CSS_SELECTOR"}else throw b.push({type:"CSS_SELECTOR",matched:!1,reason:S.logs.length===1?"CSS evaluation failed":"No CSS selectors matched",selectors:[],logs:S.logs}),g&&b.push({type:"HYBRID_SELECTOR",matched:!1,reason:g.logs.length===1?"Hybrid evaluation failed":"No hybrid selectors matched",logs:g.logs}),S?.error&&n.error({err:new Error(S.error)},"Cache evaluation errored unexpectedly (CSS)"),g?.error&&n.error({err:new Error(g.error)},"Cache evaluation errored unexpectedly (Hybrid)"),new fn("Cache evaluation failed",b,S.cacheMissReason);let C,I,_;if(this.userBrowserSettings.visualActions){let P=E.mPath;if(!P)throw new Error("Found element did not have an mPath despite using visual actions");let B=P.join(" > ");C=e.locator(B),I=this.stateManager.getNodeUsingMPathSelector(B)}else if(E.dataMomenticId!==void 0)_=parseInt(E.dataMomenticId),I=this.stateManager.getNodeUsingDataMomenticId(_),"workingSelectors"in E?C=e.locator(E.workingSelectors[0]):C=e.locator(Ii(_));else throw new L("InternalWebAgentError","Received an element resolution result with no identifying attributes");let R=tp(r);await this.updateCacheWithNewNodeDetails({node:I,target:r,locator:C,logger:n,originalElementLocationResult:E,allowNotActionableNodesOverride:o,skipSavingVisualAttributes:a});let M=Iv(R,r);return M&&Object.keys(M).length>0&&(r.cacheResolutionUpdateTime=new Date().toISOString(),r.cacheResolutionUpdateLoggerTags=ot(n),r.cacheResolutionUpdateSource=y),{a11yNode:I,displayString:E.serializedElement,locator:C,decisions:b,originalElementLocationResult:E,revalidator:async()=>{await mv({initialLocationResult:E,cacheEvaluationParams:h,locator:C,logger:n})}}}async resolveHardcodedCssSelector(e){let{selector:r,signal:n=this.abortSignal,timeoutMs:o=this.smartWaitingTimeout}=e,i=await this.getActivePageOrFrame(),a=Date.now(),s=0,c,l=[];for(;Date.now()-a<o;){n?.throwIfAborted(),s++;let u=i.locator(r),d;try{await u.waitFor({state:"attached",timeout:Qe});let p=await u.evaluate(m=>window.generateCommonLocationResultMetadata?.(m),void 0,{timeout:st});return d=p?.serializedElement??"unknown element",l.push({type:"USER_SELECTOR",matched:!0,reason:`The user-provided CSS selector ${r} matched an element on the page.`}),{locator:u,originalElementLocationResult:p,displayString:d,decisions:l}}catch(p){let m=p.message;c=new L("ActionFailureError",`CSS selector '${r}' failed to resolve after ${s} attempts: ${m.includes("locator.waitFor: Timeout")?"the selector did not match any element on the page":m}`),await xe(dr,n)}}throw c}async resolveTargetWithSecondaryMethods(e){if(!e.target.boundingBox)return;let{x:r,y:n,width:o,height:i}=e.target.boundingBox,a=await this.resolveTargetWithSecondaryMethodsHelper(e);if(!a)return;let s=await a.locator.boundingBox({timeout:pe});if(!s){this.logger.debug({proposedNode:a.displayString},"Rejecting secondary matching result due to lack of a bounding box");return}let{x:c,y:l,width:u,height:d}=s;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(!r||!n||!c||!l){this.logger.debug({oldX:r,oldY:n,newX:c,newY:l,proposedNode:a.displayString},"Rejecting secondary matching result due to missing x/y coords");return}else if(Math.abs(c-r)>100||Math.abs(l-n)>100){this.logger.debug({newX:c,newY:l,oldX:r,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:r,decisions:n,logger:o,signal:i,allowNotActionableNodesOverride:a,skipSavingVisualAttributes:s}){if(r.nodeOnlySerializedHtml&&r.nodeOnlySerializedHtml.trim().length<dk){let l="Refusing to attempt HTML comparison since the saved element is too short.";n.push({type:"HTML_DISTANCE",matched:!1,reason:l})}else if(r.nodeOnlySerializedHtml&&r.nodeOnlySerializedHtml.length>50)try{let l=await Qt({fn:u=>window.findClosestElementByLDist?.(u),arg:{nodeOnlySerializedHtml:r.nodeOnlySerializedHtml},timeout:st,root:e,waitForPageLoad:()=>this.waitForPageLoad(),codePath:"finding the closest element on the page"});if(!l)throw new Error(`Got invalid HTML evaluation result: ${JSON.stringify(l)}`);if("closestDistance"in l&&("dataMomenticId"in l&&l?.dataMomenticId||"mPath"in l&&l?.mPath)){let u=l.dataMomenticId?parseInt(l.dataMomenticId):void 0,d,p;if(u)d=this.stateManager.getNodeUsingDataMomenticId(u),p=e.locator(Ii(u));else if(l.mPath){let S=l.mPath.join(" > ");d=this.stateManager.getNodeUsingMPathSelector(S),p=e.locator(S)}else throw new Error("HTML ldist comparison returned no error, data momentic id, or mPath selector");let m=l.serializedElement;o.warn({result:l,originalTarget:r,displayString:m},"Resolved cached target to new node with pure html levenshtein distance");let f=tp(r);await this.updateCacheWithNewNodeDetails({node:d,target:r,locator:p,logger:o,originalElementLocationResult:l,allowNotActionableNodesOverride:a,skipSavingVisualAttributes:s});let h=Iv(f,r);return h&&Object.keys(h).length>0&&(r.cacheResolutionUpdateTime=new Date().toISOString(),r.cacheResolutionUpdateLoggerTags=ot(o),r.cacheResolutionUpdateSource="HTML_DISTANCE",o.info({diffs:h,result:l},"Updated cache after l-dist resolution")),n.push({type:"HTML_DISTANCE",matched:!0,reason:"Found an element on the page with the same string representation as the saved element.",logs:l.logs,distance:l.closestDistance,closestElement:m,savedElement:r.nodeOnlySerializedHtml}),{locator:p,a11yNode:d,displayString:m,decisions:n,originalElementLocationResult:l,revalidator:async()=>{await mv({initialLocationResult:l,locator:p,logger:o})}}}else if("cacheMissReason"in l)throw new Error(l.error??l.cacheMissReason)}catch(l){o.info({err:l},"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: ${l}`})}let c=r.screenshotUrl;if(c&&pv(r))try{let l=await this.resolveTargetWithTemplateMatching({root:e,oldTarget:r,screenshot:c,signal:i,allowNotActionableNodesOverride:a});return{...l,decisions:[...n,...l.decisions]}}catch(l){i?.throwIfAborted(),n.push({type:"TEMPLATE_MATCHING",matched:!1,reason:`Error finding closest element using saved screenshot: ${l}`}),o.warn({err:l},"Did not find any close element using saved screenshot")}}async resolveTargetWithTemplateMatching({screenshot:e,oldTarget:r,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}),s;if(typeof e=="string"){let E=await fetch(e);s=Buffer.from(await E.arrayBuffer())}else({data:s}=await this.storage.fetchOnDemandScreenshot(e));let c=h8(),l=await this.enricher.runTemplateMatching({id:c,searchImageBase64String:s.toString("base64"),pageImageBase64String:a.toString("base64")},{signal:n});await this.stateManager.getDomGraph({devicePixelRatio:this.devicePixelRatio,logger:this.logger,signal:n});let{target:u,locator:d}=await this.getTargetFromPositionPercentages({percentX:l.x,percentY:l.y,allowNotActionableNodesOverride:o}),p=u.boundingBox?.width,m=u.boundingBox?.height;if(!p||!m)throw i="Rejecting target from screenshot due to no bounding box",new Error(i);let f=u.dataMomenticId??(u.id>0?u.id:void 0),h=f!==void 0?this.stateManager.getNodeUsingDataMomenticId(f):void 0,S=tp(r);await this.updateCacheWithNewNodeDetails({target:r,node:h,locator:d,allowNotActionableNodesOverride:o});let g=Iv(S,r);return g&&Object.keys(g).length>0&&(r.cacheResolutionUpdateTime=new Date().toISOString(),r.cacheResolutionUpdateLoggerTags=ot(this.logger),r.cacheResolutionUpdateSource="TEMPLATE_MATCHING",this.logger.info({id:c,diffs:g,templateMatch:l},"Updated cache after template matching resolution")),{locator:d,originalElementLocationResult:void 0,a11yNode:h,displayString:u.nodeOnlySerializedHtml??"",decisions:[{type:"TEMPLATE_MATCHING",matched:!0,reason:"Found element using screenshot"}]}}async typeIntoTarget(e,r,n={}){await this.highlight(r.locator);let o;r.originalElementLocationResult?o=r.originalElementLocationResult.importantAttributes.type??"":o=await r.locator.getAttribute("type",{timeout:Qe})??"";let i=Qk.some(a=>a===o.toLowerCase());return await hv({targetingResult:r,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(),isAndroid:this.properties.isAndroid??!1}),await this.page.waitForTimeout(150),this.directTypeHelper(e,n)}async click(e,r,n={}){return hv({targetingResult:e,options:n,logger:this.logger,actionSource:"click",retryTimeoutMs:this.smartWaitingTimeout,controllerCallbacks:r,browserCallbacks:this.getBrowserCallbacks(),isAndroid:this.properties.isAndroid??!1})}async waitForUrl({beforeUrl:e,matcher:r},n){let o=n?.timeout??this.pageLoadTimeout,i=Date.now(),a=!1,s=e;for(;Date.now()-i<o;){if(this.abortSignal?.throwIfAborted(),s=this.url(),bh(s,r,n)){a=!0;break}await xe(dr,this.abortSignal)}if(!a)throw new L("ActionFailureError",`The active page URL ${n?.negated?"still does":"does not"} ${ih(r)} in ${o}ms.
|
|
4605
4606
|
Current tab: ${s}`);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,r,n={}){let o=n.steps??5,i=Math.min(n.hoverDurationMs??500,st);if(await this.highlight(e.locator),this.properties.isAndroid){await o0({page:this.page,fromLocator:e.locator,toLocator:r.locator,stepCount:o,dragDurationMs:n.dragDurationMs??1e3,hoverDurationMs:i}),await this.highlight(r.locator);return}await this.hover(e),await this.page.mouse.down();let a=await r.locator.boundingBox({timeout:pe});if(!a)throw new L("ActionFailureError","Could not get bounding box of target element");let s=a.x+a.width/2,c=a.y+a.height/2;await this.page.mouse.move(s,c,{steps:o}),await xe(i),await this.highlight(r.locator),await this.page.mouse.up()}async mouseDrag(e,r,n,o){o&&await this.hover({locator:o,originalElementLocationResult:void 0,serverSideBoundingBox:null}),await this.page.mouse.down();let i;if(o){let a=await o.boundingBox({timeout:pe});a&&(i={x:a.x+a.width/2,y:a.y+a.height/2})}i||(this.logger.warn("Could not get starting position from fromTarget, falling back to (0,0)"),i={x:0,y:0}),await this.page.mouse.move(i.x+e,i.y+r,{steps:n}),await xe(ya),await this.page.mouse.up()}async hover(e){await this.highlight(e.locator),await Us({func:async r=>{await this.scrollIntoViewIfNeeded(r.locator);let n=await r.locator.boundingBox({timeout:pe});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 Us({func:r=>r.locator.focus({timeout:st}),action:"focusing element",logger:this.logger,retryTimeoutMs:this.smartWaitingTimeout,callbacks:this.getBrowserCallbacks(),targetingResult:e})}async blur(e){if(!e){let r=await this.getActivePageOrFrame();await Qt({fn:()=>{let n=document.activeElement;n&&n.nodeType===1&&n.blur()},root:r,arg:void 0,waitForPageLoad:()=>this.waitForPageLoad(),timeout:Qe,codePath:"blurring the active element"});return}await this.highlight(e.locator),await Us({func:r=>r.locator.blur({timeout:st}),action:"blurring element",logger:this.logger,retryTimeoutMs:this.smartWaitingTimeout,callbacks:this.getBrowserCallbacks(),targetingResult:e})}async selectOption(e,r,n=!1){await this.highlight(e.locator),await Us({action:"selecting option from dropdown",logger:this.logger,retryTimeoutMs:this.smartWaitingTimeout,callbacks:this.getBrowserCallbacks(),func:async o=>{if(r.type==="INDEX"){let i=Number(r.index);if(isNaN(i))throw new L("UserConfigurationError",`Page index ${r.index} is not a number`)}await o.locator.selectOption({value:r.type==="VALUE"?r.value:void 0,label:r.type==="LABEL"?r.label:void 0,index:r.type==="INDEX"?Number(r.index):void 0},{force:n,timeout:pe})},targetingResult:e})}async press(e,r){let n=r.repeat??1;if(r.convertMeta){let o=ug(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:r.delayMs??0});await this.waitForStability()}async keyDown(e,r){if(r.convertMeta){let n=ug(e,this.properties.isAndroid);n!==e&&(this.logger.info({keyString:e,convertedKey:n},"Converted platform dependent keys"),e=n)}for(let n of uv(e))await this.page.keyboard.down(n)}async keyUp(e,r){if(r.convertMeta){let n=ug(e,this.properties.isAndroid);n!==e&&(this.logger.info({keyString:e,convertedKey:n},"Converted platform dependent keys"),e=n)}for(let n of uv(e))await this.page.keyboard.up(n)}async refresh(e){let r=e?.loadTimeoutMs??this.pageLoadTimeout;await this.waitForPageLoad();let n=0,o=2;for(;n<o;){n++;try{await this.page.reload({waitUntil:"domcontentloaded",timeout:r});break}catch(i){if(this.abortSignal?.throwIfAborted(),this.shouldIgnorePageLoadTimeout(i)){this.logger.warn({err:i,attempt:n},"DOMContentLoaded timed out during reload, continuing due to browser setting");break}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.waitForStability()}async getBrowserState(e){let{maxAttempts:r=2,logger:n=this.logger,skipWaitForPageLoad:o,allowNotActionableNodesOverride:i,shouldLogOnFailure:a}=e,s=e.abortSignal??this.abortSignal,c=!i,l=i?!0:this.userControlledBrowserSettings.showZeroOpacityElements,u=a?n:zo;o||await this.waitForPageLoad(),e.skipWait||await this.waitForStability({logger:n,signal:s});let d=0,p;for(;d<r;){d++;try{return await J(this.stateManager.getA11yTree({devicePixelRatio:this.devicePixelRatio,abortSignal:s,logger:n,filterByViewport:e.filterByViewport,showZeroOpacityElements:l,flagNotActionableNodes:c,skipPageLoad:e.skipWaitForPageLoad}),{milliseconds:this.pageLoadTimeout*d,signal:s,message:"Getting browser state took too long"})}catch(m){if(s?.throwIfAborted(),p=m instanceof Error?m.message:`${m}`,d>=r)throw m;u.warn({err:m,url:this.url()},"Error getting a11y tree, retrying...")}}throw new L("ActionFailureError",`Getting page content failed after ${r} attempts. Error: ${p}`)}async getViewportOffsetDetails(e){let[r,n,o,i,a]=await Qt({root:e,fn:()=>[window.scrollY,window.scrollX,window.screen.width,window.screen.height,window.devicePixelRatio],arg:void 0,timeout:pe,waitForPageLoad:async()=>{},codePath:"getting current viewport details"});return{upperBound:r,lowerBound:r+i,leftBound:n,rightBound:n+o,width:o,height:i,devicePixelRatio:this.properties.systemDevicePixelRatio??a}}async waitForStability(e){return un().startAsyncSpan("WAIT_FOR_STABILITY",async()=>{let{logger:n=this.logger,timeout:o=this.smartWaitingTimeout,signal:i}=e??{},a={value:Date.now()},s=m=>{a.value=Date.now()},c=()=>s("DOM.documentUpdated");this.cdpClient.addListener("DOM.documentUpdated",c);let l=()=>s("Page.frameDetached");this.cdpClient.addListener("Page.frameDetached",l);let u=()=>s("Page.frameStartedLoading");this.cdpClient.addListener("Page.frameStartedLoading",u);let d=()=>s("Page.navigatedWithinDocument");this.cdpClient.addListener("Page.navigatedWithinDocument",d);let p=()=>s("frameRequestedNavListener");this.cdpClient.addListener("Page.frameRequestedNavigation",p);try{await this.waitForStabilityHelper(a,n,o,i)}finally{this.cdpClient.removeListener("DOM.documentUpdated",c),this.cdpClient.removeListener("Page.frameDetached",l),this.cdpClient.removeListener("Page.frameStartedLoading",u),this.cdpClient.removeListener("Page.navigatedWithinDocument",d),this.cdpClient.removeListener("Page.frameRequestedNavigation",p)}},{})}async waitForStabilityHelper(e,r,n,o=this.abortSignal){let i=!1,a=Date.now(),s,c={quality:25,retries:0,stabilizeBeforeScreenshot:!0},l=!1,u=0,d;for(;Date.now()-a<n;){o?.throwIfAborted();let p=Date.now();if(d!==void 0&&p-d<ya&&await xe(ya-(p-d),o),d=Date.now(),!(Date.now()-e.value<jb)){if(s)try{let m=await this.screenshot(c);if(Xk(s,m)>1){s=m,l=!1;continue}l=!0}catch(m){u++,u%3===0&&r.warn({err:m,screenshotErrors:u},"Failed to take screenshot for DOM stability check"),o?.throwIfAborted()}else try{s=await this.screenshot(c)}catch(m){u++,u%3===0&&r.warn({err:m,screenshotErrors:u},"Failed to take screenshot for DOM stability check"),o?.throwIfAborted()}if(!(Date.now()-e.value<jb)){i=!0;break}}}i||r.warn({duration:Date.now()-a,stable:{a11y:i,screenshot:l}},"A11y wait phase completed due to timeout, continuing...")}async clickUsingVisualCoordinates(e,r){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:r.rightClick?"right":"left",clickCount:r.doubleClick?2:1})}async dragAndDropUsingVisualCoordinates(e,r,n){await i0(this.page,e,r,n)}async mouseDragUsingVisualCoordinates(e){let{fromTarget:r,...n}=e;await yv({...n,page:this.page,visualTarget:r,isAndroid:this.properties.isAndroid??!1})}async hoverUsingVisualCoordinates(e){await this.page.mouse.move(e.x,e.y,{steps:3})}async getElementLocation(e){let r=await this.cdpClient.send({method:"DOMSnapshot.captureSnapshot",params:{computedStyles:[],includeDOMRects:!0,includePaintOrder:!0},timeout:pe}),n=await J(this.page.evaluate(()=>window.devicePixelRatio),{milliseconds:st});process.platform==="darwin"&&n===1&&(n=ck);let o=r.documents[0],i=o.layout,a=o.nodes,s=a.nodeName||[],c=a.backendNodeId||[],l=i.nodeIndex,u=i.bounds,d=-1;for(let E=0;E<s.length;E++)if(c[E]===e){d=l.indexOf(E);break}if(d===-1)throw new Error(`Could not find any backend node with ID ${e}`);let[p=0,m=0,f=0,h=0]=u[d];p/=n,m/=n,f/=n,h/=n;let S=p+f/2,g=m+h/2;return{centerX:S,centerY:g}}async scrollVertical(e){return gv({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 gv({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();try{await this.page.goForward({waitUntil:"domcontentloaded",timeout:this.pageLoadTimeout})}catch(e){if(this.abortSignal?.throwIfAborted(),!this.shouldIgnorePageLoadTimeout(e))throw e;this.logger.warn({err:e},"DOMContentLoaded timed out during forward navigation, continuing due to browser setting")}await this.loadFrameAndRecordUrl({root:this.page,signal:this.abortSignal,codePath:"go-forward"})}async goBack(){await this.waitForPageLoad();try{await this.page.goBack({waitUntil:"domcontentloaded",timeout:this.pageLoadTimeout})}catch(e){if(this.abortSignal?.throwIfAborted(),!this.shouldIgnorePageLoadTimeout(e))throw e;this.logger.warn({err:e},"DOMContentLoaded timed out during back navigation, continuing due to browser setting")}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,r){if(await this.stopScreencast(),this.recordUrlVisited(e.url()),this.onVideoPageChange){let n=new Date,o=await e.video()?.path();if(o){let i=F0(o);this.onVideoPageChange({videoName:i,timestamp:n})}}this.page=e,await this.reinitializeCDPClient(r??this.pageLoadTimeout)}async createNewTab(e,r){let n=await this.context.newPage();await this.changeActivePage(n,r?.loadTimeoutMs),await this.navigate({url:e,initialNavigation:!0,...r}),this.handleAvailableTabsChange()}async switchToPage(e,r){let n,o=0,i=Date.now();for(;o<2||r?.retry&&Date.now()-i<this.smartWaitingTimeout;)try{await this.switchToPageHelper(e,r);return}catch(a){this.logger.warn({err:a},"Error switching to page, retrying..."),n=a,o++,await xe(dr)}throw n}async switchToPageHelper(e,r){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 L("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)}.
|
|
@@ -4608,7 +4609,7 @@ ${t}`;case"ELEMENT_CHECK":return`${G0}
|
|
|
4608
4609
|
${t}`;default:return t}}async function oo({frameConfig:t,action:e,browser:r}){let n=r.getActiveFrameConfig();t?r.setActiveFrameConfig(t):n?.type==="auto"&&r.setActiveFrameConfig(void 0);try{return await e()}finally{r.setActiveFrameConfig(n)}}var y8=["NAVIGATE","NEW_TAB","TAB","REFRESH","WAIT_FOR_URL"];async function W0({beforeUrl:t,beforePages:e,browser:r,command:n,logger:o}){if(y8.includes(n.type))return;let s=("cache"in n&&n.cache&&"target"in n.cache?n.cache.target:void 0)?.nodeOnlySerializedHtml?.includes("<a")??!1?300:3e3,c=Date.now(),l=0;for(;l===0||Date.now()-c<s;){await xe(250),l++;let u=(await r.getOpenPages()).map(p=>p.url),d=r.url();if(u.length!==e.length)for(let p=u.length-1;p>=e.length;p--){let m=u[p];if(Cs(m,o)&&m!==t&&m!==d){o.info({beforePages:e,afterPages:u,beforeUrl:t},"Auto-following new tab after preset action"),await r.switchToPage({type:"INDEX",index:String(p)});break}}}}async function ti(t,e={}){let r=await t.getBrowserState(e);return{serializedTree:r.serialize(e.serializationOpts),tree:r}}var $0=t=>!!t&&rl(t),q0=t=>{let{cache:e,description:r,disableSecondaryCacheResolution:n,logger:o}=t,i=e,a=!1,s;return i&&n&&i.targetSource==="HEURISTIC_HEALED"&&(a=!0,s="Heuristic healed cache incompatible",i=void 0),i?.inputDescription&&!j0(r,i.inputDescription)&&(o.warn({old:i.inputDescription,new:r},"Target cache was generated with a different description, clearing it automatically"),a=!0,s="Description changed",i=void 0),{cache:i,cacheBustedBeforeAction:a,cacheBustReason:s}};import{randomUUID as R8}from"crypto";var Y0={minChunkTokenCount:500,acceptableChunkTokenCount:3e3,maxChunkTokenCount:8e3,maxLineLength:4e3},X0={minChunkTokenCount:5e3,acceptableChunkTokenCount:1e4,maxChunkTokenCount:3e4,maxLineLength:500},K0=/<(\S+) id="(\d+)".*?>/g,T8=/(<\/(\S+)>)|(<(\S+).*?\/>)/g,J0=["h1","h2","section","footer","nav","aside","form","label","dialog"],b8=[...J0,"span","div","h3"],v8=["table","select","form","ul","ol","menu","pre","code","dialog"],A8=["table","form","dialog","nav","section","ul","select"];function Sg(t){return C8(t)}function C8({logger:t,serializedTree:e,options:r}){let{minChunkTokenCount:n,acceptableChunkTokenCount:o,maxChunkTokenCount:i,maxLineLength:a}=r,s=[],c=e.split(`
|
|
4609
4610
|
`),l=0,u=[],d=0,p=[],m=[],f=!1;for(;l<c.length;){f&&(s.push({ids:p,content:u.join(`
|
|
4610
4611
|
`),tokenLength:d}),u=[],d=0,p=m.length?[m[m.length-1].id]:[],f=!1);let h=c[l],S=et(h);d+=S,h.length>a&&(h=h.slice(0,a));let y=Array.from(h.matchAll(K0)).map(z=>z&&z.length>=3?{tagName:z[1],id:z[2]}:void 0).filter(z=>!!z),C=Array.from(h.matchAll(T8)).map(z=>z&&(z[2]||z[4])).filter(z=>!!z);C.reverse();let I=h.replace(/ id="[0-9]+"/g,"");u.push(I);for(let z of y)p.push(z.id),m.push(z);for(let z of C){let ae=m[m.length-1];ae&&ae.tagName===z&&m.pop()}let _=m.some(z=>v8.includes(z.tagName)),R=c[l+1]??"",M=et(R),B=Array.from(R.matchAll(K0)).map(z=>z&&z.length>2?z[1]:void 0).filter(z=>!!z),F=B.some(z=>J0.includes(z)),G=B.some(z=>b8.includes(z));d+M>=i&&(f=!0),d>=n&&(F&&!_||C.some(z=>A8.includes(z)))&&(f=!0),d>=o&&G&&!_&&(f=!0),l++}return u.length&&s.push({ids:p,content:u.join(`
|
|
4611
|
-
`),tokenLength:d}),s.forEach((h,S)=>{let g=h.ids[0],E=h.ids[h.ids.length-1];t.debug({tokenLength:h.tokenLength,minId:g,maxId:E},`Chunk for page filtering (index ${S+1}/${s.length})`)}),{chunks:s}}var w8=75e4,yg=3e5;async function zs(t){let{options:e,fixtures:r,screenshot:n}=t,{aiPageFiltering:o}=e,{logger:i,generator:a,orgId:s,signal:c}=r,l=t.tree,u=t.serializedTree,d=et(u);if(d>w8)try{let p=Sg({serializedTree:u,options:{minChunkTokenCount:1e4,maxChunkTokenCount:1e5,acceptableChunkTokenCount:5e4,maxLineLength:4e3},logger:i});l=await _8({...t,tokenLimit:yg-1e4,chunks:p.chunks}),u=l.serialize();let m=et(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"),l=l.pruneToSerializedCharLimit(yg*ca),u=l.serialize();let m=et(u);i.info({oldTokens:d,newTokens:m},"Filtered page using naive truncation"),d=m}if(d>yg)try{if(o){let p=Sg({serializedTree:u,options:X0,logger:i}),m=R8();l=await J(x8({...t,chunks:p.chunks,callId:m}),{milliseconds:12e3,signal:c}),u=l.serialize();let f=et(u);i.info({oldTokens:d,newTokens:f,langfuseCallId:m},"Filtered page using AI chunk ranking"),d=f}else{let p=Sg({serializedTree:u,options:Y0,logger:i});l=await J(I8({...t,chunkResult:p,tokenLimit:4e4}),{milliseconds:12e3,signal:c}),u=l.serialize();let m=et(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"),l=l.pruneToSerializedCharLimit(yg*ca),u=l.serialize(),i.info("Filtered page using naive truncation")}return u}async function x8({type:t,callId:e,chunks:r,description:n,fixtures:o,tree:i}){let{generator:a,signal:s,logger:c}=o,l=await a.rankChunksWithAi({chunks:r,description:n,type:t,softTokenLimit:4e4,hardTokenLimit:8e4,callId:e},{abortSignal:s,logger:c,loggerTags:ot(c)}),u=[];return r.forEach((p,m)=>{l.indices.includes(m)&&(u=u.concat(p.ids))}),i.pruneUsingRelevantIds(new Set(u))}async function _8(t){let{description:e,fixtures:r,tree:n}=t,{generator:o,logger:i,signal:a}=r;if(!e.trim())throw new Error("Empty description passed to page filtering");let s=await o.getExtractedKeywords({goal:e},{logger:i,loggerTags:ot(i),abortSignal:a});i.info({keywordsResult:s},"Got keywords for page filtering");for(let c of s.keywords){let l=t.chunks.filter(m=>m.content.toLowerCase().includes(c.toLowerCase()));if(!l.length||l.reduce((m,f)=>m+f.tokenLength,0)>t.tokenLimit&&l.length>1)continue;let d=l.flatMap(m=>m.ids);return n.pruneUsingRelevantIds(new Set(d))}throw new Error("No keywords were unique enough for page filtering")}async function I8(t){let{description:e,fixtures:r,chunkResult:n,tokenLimit:o,tree:i}=t,{generator:a,logger:s,signal:c}=r,l=await a.rankChunksWithRag({description:e,chunks:n.chunks,tokenLimit:o},{abortSignal:c,logger:s,loggerTags:ot(s)});if(l.ids.length===0)throw new Error("RAG returned no important ids");return i.pruneUsingRelevantIds(new Set(l.ids.map(d=>`${d}`)))}async function Mv(t,e){if(!t.description)throw new L("UserConfigurationError","Cannot locate element with empty description");return oo({action:async()=>P8(t,e),frameConfig:t.iframeUrl?{type:"url",url:t.iframeUrl}:void 0,browser:e.browser,logger:t.logger})}async function P8(t,e){let{disableCache:r,testContext:n,filterByViewport:o,skipWait:i,source:a,memory:s,aiPageFiltering:c,logger:l,allowNotActionableNodesOverride:u,skipSavingVisualAttributes:d,isAutoHeal:p,cacheBustReason:m}=t,{orgId:f,browser:h,localCodeEvalTools:S,generator:g,abortSignal:E}=e,y=t.description,b=un(),C=t.useMemory&&!r;n&&(y=await Jr({orgId:f,s:y,context:n,localTools:S,signal:E,logger:l})),a&&(y=V0(y,a));let{serializedTree:I,tree:_}=await b.startAsyncSpan("GET_PAGE_STATE",async()=>ti(h,{allowNotActionableNodesOverride:u,filterByViewport:o,abortSignal:E,skipWait:i,logger:l}),{}),R=await b.startAsyncSpan("GET_PAGE_SCREENSHOT",async()=>{let X,ne=Date.now(),de;for(;!X&&Date.now()-ne<3e3;){E.throwIfAborted();try{X=await h.screenshot({clearHighlights:!0,respectActiveFrame:!0,retries:2})}catch(Te){de=Te}}if(!X)throw new L("ActionFailureError",`Failed to take screenshot of page to locate element. The page may be unresponsive, or your machine might be severely resource constrained. Error: ${de?.message}`);return X}),M=I,P=!1,F=`data:image/jpeg;base64,${R.toString("base64")}`;M=await zs({type:"locator",description:y,screenshot:F,serializedTree:I,options:{aiPageFiltering:c},tree:_,fixtures:{generator:g,signal:E,logger:l,orgId:f}}),M!==I&&(P=!0);let G=await b.startAsyncSpan("AI_LOCATOR_CALL",async X=>{p&&(X.attributes.isAutoHeal=!0),m&&(X.attributes.cacheBustReason=m);let ne=await g.getElementLocation({browserState:M,goal:y,screenshot:F,source:a,memory:C?s:void 0},{disableCache:r,abortSignal:E,loggerTags:ot(l),useMemory:C});if(X.result=ne,b.storeTraceAsset){let de=Q0();b.storeTraceAsset({snapshotId:de,data:R}),X.screenshotSnapshotId=de}return ne});if(l.debug({usedRag:P,result:G},"Got locator result"),!(G.id>0))throw new Sl(`Could not find any relevant element: ${G.thoughts}`,G.updatedMemory?{type:"GCS_TRACES",traces:G.updatedMemory}:void 0);let{resolution:ae,target:W,frameConfig:q}=await b.startAsyncSpan("TARGET_RESOLUTION",async X=>{let ne=await h.createTargetFromA11yId({id:G.id,requirements:G.requirements,additionalElements:G.additionalElements,description:y,targetSource:"AI",logger:l,skipSavingVisualAttributes:d});if(X.result={serializedElement:ne.target.nodeOnlySerializedHtml??"Unknown HTML element"},b.storeTraceAsset)try{let de=await h.screenshot({locator:ne.resolution.locator,clearHighlights:!0}),Te=Q0();b.storeTraceAsset({snapshotId:Te,data:de}),X.elementScreenshotSnapshotId=Te}catch(de){l.debug({err:de},"Failed to capture element screenshot for locator trace, continuing...")}return ne});if(ae.a11yNode?.properties?.hidden&&ae.a11yNode?.properties?.hidden!=="false")throw new L("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: ${ae.displayString}`);return C&&(G.updatedMemory?W.memory={type:"GCS_TRACES",traces:G.updatedMemory}:s&&(W.memory=s)),{thoughts:G.thoughts,target:W,resolution:ae,frameConfig:q,screenshot:F}}import{randomUUID as Z0}from"crypto";var M8=15;async function Eg({command:t,aiPageFiltering:e,logger:r,fixtures:n,useMemory:o,maxRetries:i=M8}){if(!t.assertion.trim())throw new L("ActionFailureError","Assertion command is missing the assertion content");let a=dy.optional().catch(void 0).parse(t.source);t.source&&!a&&r.warn(`Invalid source ${t.source} for AI assertion, ignoring...`);let s=un();return s.startAsyncSpan("AI_ASSERTION_CALL",async c=>{let{browser:l}=n,u=t.timeout?t.timeout*1e3:l.smartWaitingTimeout,d=AN(u,i-1),p=0,m=Date.now(),f=m+u,h=m,S,g,E;try{await oo({action:()=>l.clearHighlights(),frameConfig:t.iframeUrl?{type:"url",url:t.iframeUrl}:void 0,browser:l,logger:r})}catch(C){r.warn({err:C},"Failed to clear highlights before AI check, continuing...")}for(;p<i;){n.abortSignal.throwIfAborted();let C=Date.now();if(p>0){if(C>=f)break;let R=f-C,M=h-C,P=Math.min(M,R);P>0&&await xe(P,n.abortSignal)}let I=Date.now();if(p>0&&I>=f)break;let _=!1;try{if(S=await oo({action:async()=>{let M=await eF(l,r,n.abortSignal);return g&&g.serializedTree===M.serializedTree&&g.screenshotBuff.equals(M.screenshotBuff)?(_=!0,S):(g=M,tF({command:t,state:M,fixtures:n,useMemory:o,useConsensus:!1,highlightElementsOnFailure:!1,attemptNumber:p,aiPageFiltering:e,logger:r,source:a}))},frameConfig:t.iframeUrl?{type:"url",url:t.iframeUrl}:void 0,logger:r,browser:l}),S?.success){S?.updatedMemory&&Bd(t,S.updatedMemory,r);break}else throw S?.thoughts?new L("AssertionFailureError",S.thoughts):new L("InternalPlatformError","No thoughts were provided for AI assertion failure")}catch(R){n.abortSignal.throwIfAborted(),E=R instanceof Error?R:new Error(`${R}`),_?r.info(`AI check attempt ${p} failed (re-used previous result)`):r.info({err:R},`AI check assert attempt ${p} failed, retrying...`)}finally{p++,h=I+d}}if(!S?.success){let C=f-Date.now();C>0&&await xe(C,n.abortSignal)}if(!S?.success)try{S=await oo({action:async()=>tF({command:t,state:await eF(l,r,n.abortSignal),fixtures:n,useMemory:o,useConsensus:!0,highlightElementsOnFailure:!0,attemptNumber:p,aiPageFiltering:e,logger:r}),frameConfig:t.iframeUrl?{type:"url",url:t.iframeUrl}:void 0,logger:r,browser:l})}catch(C){n.abortSignal.throwIfAborted(),E=C instanceof Error?C:new Error(`${C}`)}finally{p++}S?.updatedMemory&&Bd(t,S.updatedMemory,r);let y=S?.afterScreenshotOverride;if(y&&s.storeTraceAsset){let C=Z0();s.storeTraceAsset({snapshotId:C,data:y}),c.screenshotSnapshotId=C}let b=S?.elementScreenshotOverride;if(b&&s.storeTraceAsset){let C=Z0();s.storeTraceAsset({snapshotId:C,data:b}),c.elementScreenshotSnapshotId=C}if(!S?.success){c.result={thoughts:E?.message??"AI check failed after all attempts",result:!1};let C=`AI check still failing after ${p} attempts.`;throw E&&(C+=` Latest result: ${E.message}`),new L("AssertionFailureError",C)}return c.result={thoughts:S.thoughts,result:!0},{...S,succeedImmediately:!1,urlAfterCommand:l.url()}})}async function eF(t,e,r){let[n,o]=await Promise.all([ti(t,{abortSignal:r,skipWait:!0,skipWaitForPageLoad:!0,logger:e}),t.screenshot({retries:1,respectActiveFrame:!0})]);return{...n,screenshotBuff:o}}async function tF({command:t,state:e,fixtures:r,useConsensus:n,useMemory:o,highlightElementsOnFailure:i,aiPageFiltering:a,attemptNumber:s,source:c,logger:l}){let{browser:u,generator:d,abortSignal:p}=r,m={type:"ASSERTION"},{serializedTree:f,tree:h}=e,S=e.screenshotBuff,g=S.toString("base64"),E=u.url(),y=t.contextChoice??"MULTIMODAL",b=f;y!=="VISION_ONLY"&&(b=await zs({type:"assertion",serializedTree:f,tree:h,description:t.assertion,screenshot:g,options:{aiPageFiltering:a},fixtures:{generator:d,signal:p,logger:l,orgId:r.orgId}}),b!==f&&(m.ragUsed=!0),m.pageState=b);let C={goal:t.assertion,url:E,memory:o?t.cache?.memory:void 0,browserState:b,screenshot:g,contextChoice:y,source:c},_=await(y==="VISION_ONLY"?(M,P)=>d.getVisualAssertionResult(M,P):(M,P)=>d.getAssertionResult(M,P))(C,{useConsensus:n,attemptNumber:s,useMemory:o,disableCache:!!t.disableCache,abortSignal:p,logger:l,loggerTags:ot(l)}),R;if((_.result||i)&&_.relevantElements?.length){m.relevantElementsSerialized=_.relevantElements.map(M=>u.getSerializedFormFromA11yId(M)).filter(M=>!!M);try{let M=_.relevantElements[0],{resolution:P}=await u.createTargetFromA11yId({id:M,description:null,targetSource:"AI",skipSaveToCache:!0});R=await u.screenshot({locator:P.locator,clearHighlights:!0,respectActiveFrame:!0})}catch(M){l.debug({err:M},"Failed to capture element screenshot for trace, continuing...")}await O8(_.relevantElements,u,l)}return{success:_.result,thoughts:_.thoughts,afterScreenshotOverride:S,elementScreenshotOverride:R,updatedMemory:o?_.updatedMemory:void 0}}async function O8(t,e,r){let n=Date.now();for(let o of t){if(Date.now()-n>2e3){r.debug("Highlighting relevant elements took over 2s, aborting...");return}try{let i=new AbortController;await J(e.highlightA11yId(o),{milliseconds:1e3,fallback:()=>{throw i.abort(),new Error("Timed out waiting for highlighting to complete")}})}catch(i){r.debug({err:i},"Failed to highlight relevant element after assertion, continuing...");return}}}var L8=1e5,Tg=class extends Error{constructor(){super("The page content exceeds the maximum token limit for AI smart waiting."),this.name="ExceededMaxAISmartWaitingTokensError"}};async function rF(t,e){let{logger:r}=t,{abortSignal:n,browser:o}=e,i=Date.now();try{await N8(i,t,e)}catch(a){if(a instanceof Error&&(a.name==="AbortError"||a.name==="TimeoutError")||n.aborted)return;a instanceof Tg?r.warn("Skipping AI smart waiting due to excessive page size - falling back to naive waiting"):r.warn({err:a},"Unexpected error occurred during AI smart waiting");let s=o.smartWaitingTimeout-(Date.now()-i);s>0&&await xe(s,n)}finally{r.debug({durationMs:Date.now()-i},"AI smart waiting complete")}}async function N8(t,e,r){let{abortSignal:n,browser:o}=r;if(o.smartWaitingTimeout<3e3){await xe(o.smartWaitingTimeout,n);return}if(!e.description)throw new L("UserConfigurationError","Cannot locate element with empty description");await J(D8(t,e,r),{milliseconds:o.smartWaitingTimeout})}async function D8(t,e,r){let{logger:n,iframeUrl:o}=e,{browser:i}=r;for(;Date.now()-t<i.smartWaitingTimeout;)if(await oo({action:async()=>k8(e,r),frameConfig:o?{type:"url",url:o}:void 0,browser:i,logger:n}))return}async function k8(t,e){let{testContext:r,logger:n,filterByViewport:o,allowNotActionableNodesOverride:i}=t,{browser:a,abortSignal:s,localCodeEvalTools:c,orgId:l,generator:u}=e,d=t.description;r&&(d=await Jr({orgId:l,s:d,context:r,localTools:c,signal:s,logger:n}));let{serializedTree:p}=await ti(a,{allowNotActionableNodesOverride:i,filterByViewport:o,abortSignal:s,logger:n});if(et(p)>L8)throw new Tg;s.throwIfAborted();let f;try{f=await a.screenshot({clearHighlights:!0,respectActiveFrame:!0,retries:2})}catch(E){throw new L("ActionFailureError",`Failed to take screenshot of page to perform smart waiting. The page may be unresponsive, or your machine might be severely resource constrained. Error: ${E instanceof Error?E.message:E}`)}let S=`data:image/jpeg;base64,${f.toString("base64")}`;s.throwIfAborted();let g=await u.getSmartWaitingDecision({browserState:p,description:d,screenshot:S},{abortSignal:s,loggerTags:ot(n)});return n.debug({result:g},"Got smart waiting result"),g.isPageReady}import{cloneDeep as oF}from"lodash-es";async function iF(t){return un().startAsyncSpan("ELEMENT_ASSERTION",async r=>F8(t,r),{name:"Element check"})}async function F8(t,e){let{command:r,timeoutMs:n,fixtures:o,disableCache:i}=t,{abortSignal:a}=o,s=()=>Bp(r.cache)?r.cache:void 0,c=s(),l=!i&&!!c?.target&&rl(c.target),u=oF(c),d=(E=!1)=>{if(c=s(),!!c)if(E){let y=jT(u,c);c.target=y.target,c.updatedAt=y.updatedAt}else{if(!u){c=void 0;return}c.target=u.target,c.updatedAt=u.updatedAt}},p=Date.now(),m=0,f,h=500,S=!1;for(;m<2||Date.now()-p<n;){m++,m>1&&await xe(h,a),a?.throwIfAborted(),c=s();let E=m===1,{result:y,elementWasFound:b}=await nF({cacheToUse:c,skipAISmartWaiting:!E,useAIIfCacheFails:!l,params:t});if(f=y,S=S||b,y.success)break;d(),h=Math.min(h*1.25,1e4)}if(!f)throw new L("InternalPlatformError",`Failed to evaluate manual element assertion in ${n}ms.`);if(a?.throwIfAborted(),!f.success){let E=s(),y=E?.target?.memory?{target:{id:-1,memory:E.target.memory}}:void 0,{result:b,elementWasFound:C}=await nF({cacheToUse:y,skipAISmartWaiting:!0,useAIIfCacheFails:!0,params:t});f=b,S=S||C,f.success||d(!0)}let g=s();return f.success&&g?.target&&!S&&(g.target=Ud(g.target),g.updatedAt=new Date),e.result={success:f.success,message:f.err?.message},f}async function nF({cacheToUse:t,skipAISmartWaiting:e,useAIIfCacheFails:r,params:n}){let{command:o,disableCache:i,fixtures:a,tracer:s,targetingWrapper:c}=n,{logger:l}=a;if(o.target&&!zi(o.target))throw new Error("Element assertion with x/y is not supported yet");let u=hL(o.assertion),d,p=!1,m=oF(t);try{let{elementInteractedDisplayString:f,result:h,thoughts:S}=await c({tracer:s,command:o,target:o.target,cache:m?.target,action:async g=>U8(g.locator,n),options:{...o,allowNotActionableNodesOverride:!0,disableCache:i,memory:m?.target?.memory,disableGlobalLocatorRedirect:!0,source:qa(o),skipAISmartWaiting:e,targetName:"target"},retriesWithAI:r?1:0});return d={success:h.success,data:h.data,err:h.err,elementInteractedDisplayString:f,thoughts:S},p=!0,h.success||(l.warn({aiThoughts:S,elementString:f,err:h.err},"Element check found an element but failed"),d={...h,thoughts:S}),{result:d,elementWasFound:p}}catch(f){if(u)return d={success:!0,thoughts:`The element described does not exist on the page: ${f.message}`,err:void 0,data:void 0},{result:d,elementWasFound:p};if(!(f instanceof L)||f.reason!="ActionFailureError")throw f;return d={success:!1,err:f,data:void 0,thoughts:void 0},l.warn({err:f},"Element check did not find an element and failed"),{result:d,elementWasFound:p}}}async function U8(t,{command:e,fixtures:r}){return await r.browser.highlight(t),await B8(t,e.assertion)}async function B8(t,e){let r=!0,n,o;switch(e.type){case"ELEMENT_CONTENT":{let a=await t.textContent()??"";if(o={elementTextContent:vt(a,500,!0)},!kd(a,e.value,e.operation,{negated:!!e.negated,ignoreCase:!1})){let s=pc(e);r=!1,n=new L("AssertionFailureError",`The content ${s} '${e.value}': ${a}`)}break}case"ELEMENT_ATTRIBUTE":{o={elementOuterHtml:vt(await t.evaluate(s=>s.cloneNode(!1).outerHTML),500,!0)};let a=null;try{a=await t.getAttribute(e.attr,{timeout:3e3})}catch(s){n=new L("AssertionFailureError",s instanceof Error?s.message:String(s)),r=!1;break}if(!kd(a,e.value,e.operation,{negated:!!e.negated,ignoreCase:!1})){let s=pc(e);r=!1,e.operation==="EXISTS"?n=new L("AssertionFailureError",`The attribute ${e.attr} ${s}`):n=new L("AssertionFailureError",`The attribute ${e.attr} ${s} '${e.value}': ${a}`)}break}case"ELEMENT_EXISTENCE":{switch(e.condition){case"VISIBLE":{r=await t.evaluate(async(s,c)=>{let l=Date.now();for(;Date.now()-l<c;){await new Promise(d=>setTimeout(d,250));let u=s.getBoundingClientRect();if(!(u.width===0||u.height===0)&&window.getComputedStyle(s).visibility!=="hidden"&&window.getComputedStyle(s).display!=="none")return!0}return!1},Nn*1e3);break}case"EDITABLE":{r=await t.isEditable({timeout:Nn*1e3});break}case"EXISTS":{r=!0;break}case"ENABLED":{r=await t.isEnabled({timeout:Nn*1e3});break}case"FOCUSED":{r=await t.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"})(e.condition)}if(r=e.negated?!r:r,!r){let a=pc(e);n=new L("AssertionFailureError",`The element ${a}`)}break}case"ELEMENT_NAME":{let a=await t.evaluate(s=>s.tagName);if(!kd(a,e.value,e.operation,{negated:!!e.negated,ignoreCase:!0})){let s=pc(e);r=!1,n=new L("AssertionFailureError",`The element tag name ${s} '${e.value}': ${a}`)}break}case"ELEMENT_STYLE":{let a=await t.evaluate((s,c)=>window.getComputedStyle(s).getPropertyValue(c),e.property);if(!kd(a,e.value,e.operation,{negated:!!e.negated,ignoreCase:!1})){let s=pc(e);r=!1,e.operation==="EXISTS"?n=new L("AssertionFailureError",`The style property ${e.property} ${s}`):n=new L("AssertionFailureError",`The style property ${e.property} ${s} '${e.value}': ${a}`)}break}default:return(a=>{throw"If Typescript complains about the line below, you missed a case or break in the switch above"})(e)}return{thoughts:void 0,success:r,data:o,err:n}}function aF(t){return t.type==="ELEMENT_EXISTENCE"&&t.negated&&t.condition==="EXISTS"}import{Jimp as z8}from"jimp";async function rp(t,e){let r=await t.screenshot(e),n=await z8.fromBuffer(r);return{buffer:r,width:Math.ceil(n.bitmap.width??0),height:Math.ceil(n.bitmap.height??0)}}import{Jimp as sF}from"jimp";import Ov from"jpeg-js";import H8 from"pixelmatch";async function lF({tracer:t,command:e,disableCache:r,browser:n,targetingWrapper:o,logger:i,screenshotStorage:a}){if(e.target&&!zi(e.target))throw new Error("Visual Diff with x/y is not supported yet");await n.waitForStability({logger:i});let s={clearHighlights:!0,hideCaret:!0},c;e.target?.elementDescriptor?c=(await o({tracer:t,command:e,target:e.target,cache:e.cache?.target,action:async P=>rp(n,{locator:P.locator,...s}),options:{...e,disableCache:r,disableGlobalLocatorRedirect:!0,memory:e.cache?.target?.memory,targetName:"target"}})).result:c=await rp(n,s);let l=await a.prepareGoldenScreenshotForComparison(i,e,c);if((c.height!==l.height||c.width!==l.width)&&i.warn({currHeight:c.height,currWidth:c.width,savedHeight:l.height,savedWidth:l.width},"Mismatched before and after visual diff screenshot sizes"),Math.abs(c.height-l.height)>10||Math.abs(c.width-l.width)>10){let M=`${c.width}x${c.height}`,P=`${l.width}x${l.height}`;return{fail:!0,thoughts:`Current screenshot (${M}) does not match saved screenshot dimensions (${P}) - did you change the size of the target or the viewport?`,beforeScreenshotOverride:l.buffer,afterScreenshotOverride:c.buffer,succeedImmediately:!1,urlAfterCommand:n.url()}}let u=await sF.fromBuffer(c.buffer),d={width:c.width,height:c.height},p=await sF.fromBuffer(l.buffer),m={width:l.width,height:l.height},f,h=d.width*d.height,S=m.width*m.height,g=Math.abs(d.height-m.height),E=Math.abs(d.width-m.width);if(h>S){let M=u.cover({w:m.width,h:m.height});c.buffer=await M.getBuffer("image/jpeg"),f="current",c.width=m.width,c.height=m.height}else if(S>h){let M=p.cover({w:d.width,h:d.height});l.buffer=await M.getBuffer("image/jpeg"),f="saved"}let y={data:Buffer.alloc(c.width*c.height*4),width:c.width,height:c.height},b=e.threshold??.1,I=H8(Ov.decode(l.buffer).data,Ov.decode(c.buffer).data,y.data,c.width,c.height,{threshold:b,diffColorAlt:[0,255,0]})/(c.width*c.height)*100,_=I>b*100,R=`Visual diff of ${I.toFixed(2)}% detected, which is ${_?"over":"under"} the threshold of ${b*100}%.`;if(f&&(R+=` The ${f} screenshot was cropped since it was taller by ${g} pixels and wider by ${E} pixels.`),_)throw new L("ActionFailureError",R);return{fail:_,thoughts:R,beforeScreenshotOverride:c.buffer,afterScreenshotOverride:Ov.encode(y,75).data,succeedImmediately:!1,urlAfterCommand:n.url()}}var G8=3e4;function j8(t){if(!t.body)return{};switch(t.body.type){case"json":return{content:t.body.content,contentType:"application/json"};case"form-urlencoded":{let e=new URLSearchParams;return Object.entries(t.body.content).forEach(([r,n])=>{e.append(r,n)}),{content:e.toString(),contentType:"application/x-www-form-urlencoded;charset=UTF-8"}}}}async function cF({command:t,logger:e,baseUrl:r,fetchImplementation:n=fetch}){let o=t.timeout??G8/1e3,i=Object.fromEntries(Object.entries(t.headers||{}).filter(([f,h])=>f&&h)),a=new URLSearchParams;Object.entries(t.params||{}).filter(([f,h])=>f&&h).forEach(([f,h])=>{a.append(f,h)});let s=a.toString(),c;if(yc(t.url)&&(c=t.url),r&&Ec(t.url,r)&&(c=new URL(t.url,r).toString()),!c)throw new L("ActionFailureError",`Invalid URL: ${t.url}`);let l=c;e.info({url:l,searchParams:s,headers:i,body:t.body,method:t.method},"Making HTTP request");let d=await J((async()=>{let f=s?`${l}?${s}`:l;try{let h=j8(t),S=new Headers(i);return h.contentType&&!S.has("Content-Type")&&S.set("Content-Type",h.contentType),await n(f,{headers:S,method:t.method,body:h.content})}catch(h){throw new Error(`Failed to make HTTP request: ${h}`,{cause:h})}})(),{milliseconds:o*1e3,fallback:()=>{throw new L("ActionFailureError",`Fetch request timed out after ${o} seconds`)}});if(!d.ok){let f;try{f=await d.text()}catch(h){f=`Failed to read response body: ${h}`}throw new L("ActionFailureError",`Fetch request failed with status ${d.status}: ${f}`)}let p={};d.headers.forEach((f,h)=>{p[h]=f});let m={status:d.status,headers:p,request:{url:d.url,method:t.method,headers:i}};if(t.body?.type==="json"&&t.body.content)try{m.request.json=JSON.parse(t.body.content)}catch{}if(d.headers.get("content-type")?.includes("json"))try{m.json=await d.json()}catch{}else d.headers.get("content-type")?.includes("text")&&(m.text=await d.text());return m}var V8=5e3;async function bg({timeout:t=Nn,...e}){let r=Date.now(),n=t*1e3,o=n+1e4,i,a=0,s=500;for(;a-r<n;){if(Date.now()-r>o){e.logger.warn("Exceeded max system timeout for page assertion, exiting...");break}e.signal?.throwIfAborted();let c=Date.now();i=await uF(e),a=Date.now();let l=a-c;if(l>1e3&&e.logger.warn({pageAssertDuration:l},"Page assertion took longer than expected"),!i.success)await xe(s,e.signal),s=Math.min(Math.floor(s*1.5),V8);else return i}return i=await uF(e),i}async function uF({assertion:t,browser:e,autoExpandIframes:r}){switch(t.type){case"CONTENT":case"CONTENT":{let o,i=!1,a;try{let s;if(r){let c=await e.evaluateFunctionInAllFrames(dF,{value:t.value,negated:!!t.negated,returnHtml:!1});i=t.negated?c.every(l=>l.evaluation):c.some(l=>l.evaluation),s=c.find(l=>l.pageHtml)?.pageHtml}else({evaluation:i,pageHtml:s}=await e.evaluateFunctionInPage(dF,{value:t.value,negated:!!t.negated,returnHtml:!0},"checking page content"));if(!i){let c=t.negated?Ei.CONTAINS:Ti.CONTAINS;a=new L("AssertionFailureError",`The page ${c} '${t.value}'.`),o=s}}catch(s){a=new L("AssertionFailureError",`Failed to evaluate page content assertion: ${s instanceof Error?s.message:`${s}`}`)}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"})(t)}}function dF({value:t,negated:e,returnHtml:r}){let n=document.body.innerHTML,o=n.includes(t)===!e;return n.length>1e4&&(n=n.slice(0,1e4)+"...TRUNCATED"),{evaluation:o,pageHtml:!o&&r?n:void 0}}var W8=3e4;async function pF({command:t,logger:e,baseUrl:r,fetchImplementation:n=fetch}){let o=t.timeout??W8/1e3,i=new AbortController,a=Object.fromEntries(Object.entries(t.headers||{}).filter(([d,p])=>d&&p));a["Content-Type"]="application/json";let s;if(yc(t.url)&&(s=t.url),r&&Ec(t.url,r)&&(s=new URL(t.url,r).toString()),!s)throw new L("ActionFailureError",`Invalid URL: ${t.url}`);let l=await J((async()=>{try{return await n(s,{headers:a,method:"POST",body:JSON.stringify({query:t.query,variables:t.variables?JSON.parse(t.variables):void 0}),signal:i.signal})}catch(d){throw new Error(`Failed to make HTTP request: ${d}`,{cause:d})}})(),{milliseconds:o*1e3});if(!l)throw new L("ActionFailureError",`GraphQL request timed out after ${o} seconds`);if(!l.ok){let d,p=await l.text();try{d=JSON.parse(p)}catch{throw new L("ActionFailureError",`GraphQL request failed with status ${l.status}: ${p}`)}throw d?.errors?.length&&d?.errors[0]?.message?new L("ActionFailureError",`GraphQL request failed with status ${l.status}: ${d.errors[0].message}`):new L("ActionFailureError",`GraphQL request failed with status ${l.status}: ${p}`)}let u={};return l.headers.forEach((d,p)=>{u[p]=d}),{status:l.status,headers:u,json:await l.json()}}var Aa=class{orgId;options;storage;localCodeEvalTools;uploadedFileStorage;visualDiffScreenshotStorage;browser;generator;executeAbortController=new AbortController;logger;executionOptionsStack=[];recordAbortController=null;registeredListeners={};recordedRequests={};constructor({browser:e,generator:r,logger:n,storage:o,orgId:i,localCodeEvalTools:a,uploadedFileStorage:s,visualDiffScreenshotStorage:c,options:l}){this.orgId=i,this.options=l,this.browser=e,this.browser.registerAbortSignal(this.executeAbortController.signal),this.storage=o,this.uploadedFileStorage=s,this.visualDiffScreenshotStorage=c,this.localCodeEvalTools=a,this.generator=r,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 withExecutionOptions(e,r){this.executionOptionsStack.push(e);try{return await r()}finally{this.executionOptionsStack.pop()}}getCurrentExecutionOptions(){return this.executionOptionsStack[this.executionOptionsStack.length-1]??{}}async evaluateAiAction({goal:e,startingScreenshot:r,history:n,disableCache:o,langfuseSessionId:i,lastError:a,logger:s=this.logger}){let[c,l]=await Promise.all([ti(this.browser,{abortSignal:this.executeAbortController.signal,skipWait:!0,skipWaitForPageLoad:!0,logger:s}),this.browser.screenshot({retries:1,clearHighlights:!0})]),u=`data:image/jpeg;base64,${l.toString("base64")}`,d=await zs({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:s,orgId:this.orgId}}),p={url:this.browser.url(),browserState:d,startingScreenshot:r,history:n,goal:e,screenshot:u,lastError:a};return await this.generator.getMultiturnAiActionEvaluation(p,{disableCache:o,abortSignal:this.executeAbortController.signal,loggerTags:{...ot(s)},langfuseSessionId:i})}async promptToCommand({goal:e,startingScreenshot:r,history:n,actionHint:o,disableCache:i,logger:a=this.logger,langfuseSessionId:s}){let c=this.browser.url(),[l,u]=await Promise.all([ti(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 zs({type:"ai-action",description:e,screenshot:d,serializedTree:l.serializedTree,tree:l.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:r,history:n,goal:e,actionHint:o,screenshot:d};try{return await this.generator.getMultiturnAiActionCommand(m,{disableCache:i,abortSignal:this.executeAbortController.signal,loggerTags:{...ot(a)},langfuseSessionId:s})}catch(f){throw new L("InternalWebAgentError",`Error generating command: ${f instanceof Error?f.message:f}`,{errOptions:{cause:f}})}}async getBrowserState(e){return ti(this.browser,e)}async locateElement(e){return await Mv({...e,aiPageFiltering:!!this.options?.aiPageFiltering},this.getControllerFixtures())}async locateElementWithSelector(e,r){return oo({action:async()=>{let n=await this.browser.resolveHardcodedCssSelector({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:r?{type:"url",url:r}:void 0,browser:this.browser,logger:this.logger})}getControllerFixtures(){return{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({tracer:e,command:r,targetNames:n,descriptions:o,caches:i,action:a,options:s,retriesWithAI:c=1}){let l=[];for(let u=0;u<o.length;u++){let d=o[u],p=await this.wrapElementTargetingCommand({tracer:e,command:r,target:d,cache:i[u],action:async m=>m,options:{...s,targetName:n[u]}});l.push(p)}try{let u=await a(...l.map(m=>m.result)),d=m=>m==="fromTarget"?"From Target":m==="toTarget"?"To Target":"Target",p=l.map((m,f)=>m.thoughts?`${d(n[f])}: ${m.thoughts}`:void 0).filter(m=>!!m).join(" -------------- ")||void 0;return{result:u,elementInteractedDisplayStrings:l.map(m=>m.elementInteractedDisplayString),thoughts:p}}catch(u){if(this.throwIfClosed(),c>0)return this.logger.warn({err:u},"Failed to execute action with multiple cached targets, retrying with AI"),this.wrapMultiElementTargetingCommand({tracer:e,command:r,targetNames:n,descriptions:o,caches:o.map(()=>{}),action:a,options:s,retriesWithAI:c-1});throw new L("ActionFailureError",u.message,{errOptions:{cause:u}})}}async wrapHardcodedCssTargetingCommandHelper({target:e,action:r,options:n,command:o}){let i=this.logger.child({commandId:o.id}),{targetName:a}=n;if(e.type!=="description")throw new L("ActionFailureError","Cannot use selector with non-description target");let s,c=Date.now(),l=Date.now();for(;Date.now()-l<this.browser.smartWaitingTimeout;){c=Date.now();try{let u=await this.browser.resolveHardcodedCssSelector({selector:e.elementDescriptor,targetName:a,logger:i});return{result:await r({locator:u.locator,originalElementLocationResult:void 0,serverSideBoundingBox:null}),elementInteractedDisplayString:u.displayString}}catch(u){if(u.name==="AbortError")throw u;s=u,i.warn({err:u},"Failed to action on hardcoded css selector"),Date.now()-c<500&&await xe(500)}}throw s}async scrollIntoViewAndResolveFinalTarget(e){let{resolutionResult:r,disableGlobalLocatorRedirect:n,logger:o}=e,i=un(),a=!n&&this.browser.userBrowserSettings.globalLocatorRedirect!==!1;(this.browser.userBrowserSettings.visualActions||a)&&await i.startAsyncSpan("SCROLL_ELEMENT_INTO_VIEW",async()=>{await this.browser.scrollIntoViewIfNeeded(r.locator)});let s;return a&&(s=await i.startAsyncSpan("LOCATOR_REDIRECT",async c=>{let{targetingResult:l,metadata:u}=await this.browser.performTargetRedirection(r,o);if(c.result=u,l&&i.storeTraceAsset)try{let d=await this.browser.screenshot({locator:l.locator,clearHighlights:!0}),p=$8();i.storeTraceAsset({snapshotId:p,data:d}),c.elementScreenshotSnapshotId=p}catch(d){o.debug({err:d},"Failed to capture element screenshot for redirect trace")}return l})),s||(s={locator:r.locator,serverSideBoundingBox:await r.locator.boundingBox({timeout:pe}),originalElementLocationResult:r.originalElementLocationResult}),s}async resolveCachedTargetForAction(e){let{cache:r,options:n,logger:o}=e,a=await un().startAsyncSpan("CACHE_RESOLUTION",async c=>{c.targetSource=r.targetSource;try{let l=await this.browser.resolveTarget(r,{allowNotActionableNodesOverride:n.allowNotActionableNodesOverride,logger:o,signal:this.executeAbortController.signal,...n.resolveTargetOptions});c.attributes.targetDisplayString=l.displayString,c.attributes.decisions=l.decisions;let u=l.decisions.find(d=>d.matched);return u&&(c.resolutionMethod=u.type),l}catch(l){throw l instanceof fn&&(c.cacheMissReason=l.cacheMissReason,c.attributes.decisions=l.decisions),l}}),s=await this.scrollIntoViewAndResolveFinalTarget({resolutionResult:a,disableGlobalLocatorRedirect:n.disableGlobalLocatorRedirect,logger:o});return await a.revalidator?.(),{resolutionResult:a,finalTarget:s}}async wrapElementTargetingCommand(e){return await oo({action:()=>this.wrapElementTargetingCommandHelper(e),frameConfig:e.options.iframeUrl?{type:"url",url:e.options.iframeUrl}:void 0,browser:this.browser,logger:this.logger})}async wrapElementTargetingCommandHelper(e){let{tracer:r,target:n,action:o,options:i,command:a,finalAttempt:s=!1,originalCache:c=e.cache}=e,{retriesWithAI:l=1}=e,{disableCache:u,useSelector:d,targetName:p}=i,m=un(),f=this.logger.child({commandId:a.id}),h=this.shouldUseMemory(),S=mF(e.cache);if((!S||u)&&!CS(n))throw new L("ActionFailureError","Cannot target element with no cached data or element descriptor");if(d)return this.wrapHardcodedCssTargetingCommandHelper(e);let g=!1,E;u&&(f.info("Cache explicitly disabled for this step"),g=!0,E="Cache explicitly disabled",S=void 0);let y=q0({cache:S,description:n.elementDescriptor,disableSecondaryCacheResolution:!!this.browser.userBrowserSettings.disableSecondaryCacheResolution,logger:f});S=y.cache,g=g||y.cacheBustedBeforeAction,!E&&y.cacheBustReason&&(E=y.cacheBustReason);let b=!0;if(!$0(S))return l--,b=!1,this.executeTargetingCommandWithAI({tracer:m,stepTracer:r,target:n,options:i,command:a,action:o,originalCache:c,logger:f,useMemory:h,cacheBustedBeforeAction:g,cacheBustReason:E});try{let{resolutionResult:C,finalTarget:I}=await this.resolveCachedTargetForAction({cache:S,options:i,logger:f}),_=await o(I);if(Wt.increment("cache_target_resolution_v2",1,["outcome:hit","platform:web",`hasRequirements:${!!S.requirements}`,`hasAdditionalElements:${!!S.additionalElements}`,`orgId:${this.orgId}`,"cliVersion:2.71.1"]),uh({cmd:a,key:p,newTarget:S,logger:f,updatedWithAI:!1}),b){let R=C.decisions.filter(M=>M.matched);if(R.length!==1)f.warn({decisions:C.decisions},"Expected exactly 1 matching method for element location, got more or less");else{let M=R[0].type;r.recordTargetAutoHeal({healType:M})}}return{result:_,elementInteractedDisplayString:C.displayString}}catch(C){this.throwIfClosed();let I=BS(C);if(I&&!s)return f.warn({err:C},"Encountered error that is retryable with cache"),this.wrapElementTargetingCommandHelper({tracer:r,command:a,target:n,action:o,cache:c,originalCache:c,retriesWithAI:l,finalAttempt:!0,options:i});if(C instanceof L&&!I)throw f.warn({err:C},"Failed to execute command with target (fatal)"),C;if(l>0&&n){f.info({err:C},"Failed to execute action with cached target, retrying with AI"),Wt.increment("cache_target_resolution_v2",1,["outcome:miss","platform:web",`hasRequirements:${!!S.requirements}`,`hasAdditionalElements:${!!S.additionalElements}`,`orgId:${this.orgId}`,"cliVersion:2.71.1",`missReason:${C instanceof fn?C.cacheMissReason:"unknown"}`]);let _;return S.memory&&kp(S.memory)&&(_=S.memory),this.wrapElementTargetingCommandHelper({tracer:r,command:a,target:n,cache:void 0,action:o,originalCache:c,retriesWithAI:l,finalAttempt:!0,options:{...i,memory:_,targetHealingInProgress:!0}})}throw new L("ActionFailureError",`Failed to execute interactive command: ${C instanceof Error?C.message:`${C}`}`,{errOptions:{cause:C}})}}async executeTargetingCommandWithAI(e){let{tracer:r,stepTracer:n,target:o,options:i,command:a,action:s,originalCache:c,logger:l,useMemory:u,cacheBustedBeforeAction:d,cacheBustReason:p}=e;l.info({description:o.elementDescriptor,targetHealingInProgress:i.targetHealingInProgress,cacheBustedBeforeAction:d,memory:i.memory,useMemory:u},"Prompting AI for an updated element location"),(d||!c)&&!this.getCurrentExecutionOptions().skipAISmartWaiting&&!i.skipAISmartWaiting?await r.startAsyncSpan("SMART_WAITING",async()=>await rF({description:o.elementDescriptor,iframeUrl:i.iframeUrl,source:i.source,logger:l,allowNotActionableNodesOverride:i.allowNotActionableNodesOverride},this.getControllerFixtures())):(d||!c)&&(i.skipAISmartWaiting?l.debug("Skipping AI smart waiting for this targeting attempt"):l.debug("Skipping AI smart waiting due to controller execution options"));let m=2;for(let f=1;f<=m;f++){let h=!1,S=this.browser.getActiveFrameConfig();try{let g;try{g=await Mv({description:o.elementDescriptor,disableCache:!!i.disableCache,iframeUrl:i.iframeUrl,source:i.source,useMemory:u,memory:u?i.memory:void 0,aiPageFiltering:!!this.options?.aiPageFiltering,allowNotActionableNodesOverride:i.allowNotActionableNodesOverride,logger:l,isAutoHeal:!!i.targetHealingInProgress,cacheBustReason:p},this.getControllerFixtures())}catch(b){if(b instanceof Sl&&b.updatedLocatorMemory){let C={id:-1,...c,memory:b.updatedLocatorMemory};uh({cmd:a,key:i.targetName,newTarget:C,logger:l,updatedWithAI:!0})}throw b}g.frameConfig&&(this.browser.setActiveFrameConfig(g.frameConfig),h=!0);let E=await this.scrollIntoViewAndResolveFinalTarget({resolutionResult:g.resolution,disableGlobalLocatorRedirect:i.disableGlobalLocatorRedirect,logger:l}),y=await s(E);return uh({cmd:a,key:i.targetName,newTarget:g.target,logger:l,updatedWithAI:!0}),i.targetHealingInProgress&&(n.recordTargetAutoHeal({healType:"AI"}),g.target.targetSource="AI_HEALED",g.target.targetUpdateTime=new Date().toUTCString(),g.target.targetUpdateLoggerTags=ot(l)),{result:y,elementInteractedDisplayString:g.resolution.displayString,thoughts:g.thoughts}}catch(g){if(h&&this.browser.setActiveFrameConfig(S),this.throwIfClosed(),f<m&&BS(g)){l.warn({err:g,aiAttempt:f},"Encountered retryable AI targeting error; retrying with AI once");continue}throw g instanceof L?g:new L("ActionFailureError",g.message)}}throw new L("ActionFailureError","Failed to execute AI targeting after retry")}async screenshotWithDimensions(e){return rp(this.browser,e)}async executePresetCommand(e,r,n,o){this.options?.slowMoMs&&await xe(this.options.slowMoMs);let i=await this.browser.getOpenPages(),a=this.browser.url(),s;try{s=await this.resolveCommandTemplateStrings(r,n)}catch(c){throw this.throwIfClosed(),new L("ActionFailureError",`Failed to substitute template strings in command: ${c.message}`,{errOptions:{cause:c}})}try{let c=await this.executePresetCommandHelper(e,r,n,o);return this.options?.autoFollowNewTabs&&await W0({beforeUrl:a,command:r,beforePages:i.map(l=>l.url),browser:this.browser,logger:this.logger}),c}catch(c){throw c.name!=="AbortError"&&this.logger.error({err:c},"Error thrown in action controller"),c}finally{rk(r,s)}}createCallbacksForBrowser(e){return{createIsolatedFolder:()=>Qb(e)}}async traceBrowserInteraction(e,r,n){return un().startAsyncSpan("BROWSER_INTERACTION",async()=>r(),{name:e,...n})}async resolveCommandTemplateStrings(e,r){return rg({obj:e,context:r,bannedKeys:["type","a11yData","thoughts","cache","code"],orgId:this.orgId,logger:this.logger,signal:this.executeAbortController.signal,localTools:this.localCodeEvalTools})}async executePresetCommandHelper(e,r,n,o){o=o||"disableCache"in r&&!!r.disableCache;let i=this.logger.child({commandId:r.id});switch(r.type){case"SUCCESS":{let a=r.condition;return a?.assertion.trim()?Eg({command:a,fixtures:this.getControllerFixtures(),useMemory:this.shouldUseMemory(),aiPageFiltering:!!this.options?.aiPageFiltering,logger:i}):{succeedImmediately:!1,urlAfterCommand:this.browser.url()}}case"AI_ASSERTION":{if(!r.assertion.trim())throw new L("ActionFailureError","Missing assertion");if(r.timeout&&r.timeout>1800)throw new L("AssertionFailureError",`AI check timeout of ${r.timeout} exceeds the maximum allowed value of 30 minutes.`);return Eg({command:r,fixtures:this.getControllerFixtures(),useMemory:this.shouldUseMemory(),aiPageFiltering:!!this.options?.aiPageFiltering,logger:i})}case"AI_EXTRACT":{if(!r.goal.trim())throw new L("ActionFailureError","Cannot perform AI extraction without goal");if(r.schema){let c=hI(r.schema);if(c)throw new L("UserConfigurationError",c)}let a=await this.browser.getCondensedHtml(),s=await this.browser.screenshot({retries:2});try{let c=await this.generator.getTextExtraction({goal:r.goal,browserState:a,returnSchema:r.schema,screenshot:`data:image/jpeg;base64,${s.toString("base64")}`},{disableCache:o,abortSignal:this.executeAbortController.signal,loggerTags:ot(i)});if(c.result==="NOT_FOUND")throw new L("ActionFailureError","No relevant data found for extraction goal on this page");if(c.thoughts?.includes("MaxGenerationLengthExceededError"))throw new L("UserConfigurationError",c.thoughts);return{thoughts:c.thoughts||void 0,data:c.result,succeedImmediately:!1,urlAfterCommand:this.browser.url()}}catch(c){let l=c.message;throw l.includes("MaxGenerationLengthExceededError")?new L("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."):l.includes("AIProviderError")&&l.includes("time")?new L("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:c}}):c}}case"NAVIGATE":if(!yc(r.url)&&!Ec(r.url,this.browser.baseUrl))throw new L("ActionFailureError",`Invalid URL provided to navigate command: ${r.url}`);await this.traceBrowserInteraction("Navigate",()=>this.browser.navigate({url:r.url,loadTimeoutMs:r.loadTimeout?r.loadTimeout*1e3:void 0}));break;case"DIALOG":this.browser.registerDialogHandler(r.action);break;case"CAPTCHA":throw new L("UserConfigurationError","Captcha solving is no longer available on Momentic");case"GO_BACK":await this.traceBrowserInteraction("Go back",()=>this.browser.goBack());break;case"GO_FORWARD":await this.traceBrowserInteraction("Go forward",()=>this.browser.goForward());break;case"SCROLL_LEFT":case"SCROLL_RIGHT":case"SCROLL_DOWN":case"SCROLL_UP":{let a,s;if(r.target&&No(r.target))await this.browser.hoverUsingVisualCoordinates(r.target.pixels);else if(r.target&&r.target.elementDescriptor.trim()){let{elementInteractedDisplayString:u,thoughts:d}=await this.wrapElementTargetingCommand({tracer:e,command:r,target:r.target,cache:r.cache?.target,action:p=>this.browser.hover(p),options:{...r,targetName:"target",disableGlobalLocatorRedirect:!0,disableCache:o}});a=u,s=d}let c=this.browser.getViewport()?.height??Ir.height,l=this.browser.getViewport()?.width??Ir.width;switch(r.type){case"SCROLL_UP":await this.traceBrowserInteraction("Scroll up",()=>this.browser.scrollVertical(-(r.deltaY??c)));break;case"SCROLL_DOWN":await this.traceBrowserInteraction("Scroll down",()=>this.browser.scrollVertical(r.deltaY??c));break;case"SCROLL_LEFT":await this.traceBrowserInteraction("Scroll left",()=>this.browser.scrollHorizontal(-(r.deltaX??l)));break;case"SCROLL_RIGHT":await this.traceBrowserInteraction("Scroll right",()=>this.browser.scrollHorizontal(r.deltaX??l));break}return{succeedImmediately:!1,urlAfterCommand:this.browser.url(),elementInteracted:a,thoughts:s}}case"WAIT_FOR_URL":{if(r.timeout&&r.timeout>1800)throw new L("UserConfigurationError",`Wait for URL timeout of ${r.timeout} exceeds the maximum allowed value of 30 minutes.`);let a=r.matcher;await this.browser.waitForUrl({beforeUrl:this.browser.url(),matcher:a},{timeout:r.timeout?r.timeout*1e3:void 0,negated:r.negated,caseInsensitive:r.caseInsensitive});break}case"WAIT":{if(r.delay>1800)throw new L("UserConfigurationError",`Wait timeout of ${r.delay} seconds exceeds the maximum allowed value of 30 minutes`);let a=r.delay*1e3;await xe(a,this.executeAbortController.signal);break}case"REFRESH":await this.traceBrowserInteraction("Refresh",()=>this.browser.refresh({loadTimeoutMs:r.loadTimeout?r.loadTimeout*1e3:void 0}));break;case"CLICK":{if(No(r.target)){let{pixels:d}=r.target;await this.traceBrowserInteraction("Click",()=>this.browser.clickUsingVisualCoordinates(d,r),{coordinates:d});break}let a=this.browser.url(),{elementInteractedDisplayString:s,result:c,thoughts:l}=await this.wrapElementTargetingCommand({tracer:e,target:r.target,command:r,cache:r.cache?.target,action:d=>this.traceBrowserInteraction("Click",()=>this.browser.click(d,this.createCallbacksForBrowser(this.orgId),r),{selector:d.locator.toString()}),options:{disableCache:o,targetName:"target",...r}}),u={urlAfterCommand:this.browser.url(),succeedImmediately:!1,elementInteracted:s,thoughts:l,data:c.downloadedFile?{downloadedFile:c.downloadedFile}:void 0};return vh(a,u.urlAfterCommand)&&(u.succeedImmediately=!0,u.succeedImmediatelyReason="URL changed"),u}case"COPY":return await this.browser.copy(r.value),{succeedImmediately:!1,data:r.value,urlAfterCommand:this.browser.url()};case"PASTE":{await this.browser.paste();break}case"DRAG":{if(No(r.fromTarget)&&No(r.toTarget)){let c=r.fromTarget.pixels,l=r.toTarget.pixels;await this.traceBrowserInteraction("Drag",()=>this.browser.dragAndDropUsingVisualCoordinates(c,l,{hoverDurationMs:r.hoverSeconds?r.hoverSeconds*1e3:void 0}),{coordinates:c});break}if(No(r.fromTarget)||No(r.toTarget))throw new Error("Drag and drop targets must be both coordinates or both descriptions");let{elementInteractedDisplayStrings:a,thoughts:s}=await this.wrapMultiElementTargetingCommand({tracer:e,command:r,targetNames:["fromTarget","toTarget"],descriptions:[r.fromTarget,r.toTarget],caches:[r.cache?.fromTarget,r.cache?.toTarget],action:(c,l)=>this.traceBrowserInteraction("Drag",()=>this.browser.dragAndDrop(c,l,{hoverDurationMs:r.hoverSeconds?r.hoverSeconds*1e3:void 0,steps:r.steps})),options:{useSelector:!!r.useSelector,disableCache:o}});return{succeedImmediately:!1,urlAfterCommand:this.browser.url(),elementInteracted:a[0],thoughts:s}}case"MOUSE_DRAG":{let a=parseInt(r.deltaX),s=parseInt(r.deltaY),c=r.steps??5;if(isNaN(a)||isNaN(s))throw new L("ActionFailureError",`Invalid pixel values passed to mouse drag command: (${r.deltaX}, ${r.deltaY})`);if(r.target&&No(r.target)){let d=r.target.pixels;await this.traceBrowserInteraction("Mouse drag",()=>this.browser.mouseDragUsingVisualCoordinates({deltaX:a,deltaY:s,steps:c,fromTarget:d}),{coordinates:d});break}let l,u;if(r.target?.elementDescriptor){let{elementInteractedDisplayString:d,thoughts:p}=await this.wrapElementTargetingCommand({tracer:e,command:r,target:r.target,cache:r.cache?.target,action:async m=>this.traceBrowserInteraction("Mouse drag",()=>this.browser.mouseDrag(a,s,c,m.locator,{force:r.force})),options:{disableCache:o,targetName:"target",...r}});l=d,u=p}else await this.traceBrowserInteraction("Mouse drag",()=>this.browser.mouseDrag(a,s,c,void 0,{force:r.force}));return{succeedImmediately:!1,urlAfterCommand:this.browser.url(),elementInteracted:l,thoughts:u}}case"SELECT_OPTION":{if(!zi(r.target))throw new Error("Select with x/y is not supported yet");let a=r.target.elementDescriptor,s=r.choice,{elementInteractedDisplayString:c,thoughts:l}=await this.wrapElementTargetingCommand({tracer:e,command:r,target:{type:"description",elementDescriptor:a},cache:r.cache?.target,action:u=>this.traceBrowserInteraction("Select option",()=>this.browser.selectOption(u,s,r.force),{value:s.type==="LABEL"?s.label:s.type==="VALUE"?s.value:s.index}),options:{...r,targetName:"target",disableCache:o,source:qa(r)}});return{succeedImmediately:!1,urlAfterCommand:this.browser.url(),elementInteracted:c,thoughts:l}}case"TAB":{let a={loadTimeoutMs:r.loadTimeout?r.loadTimeout*1e3:void 0,retry:!0};await this.browser.switchToPage(r.action,a);break}case"NEW_TAB":await this.browser.createNewTab(r.url,{loadTimeoutMs:r.loadTimeout?r.loadTimeout*1e3:void 0});break;case"COOKIE":{if(!r.value)break;let a=await this.browser.setCookie(r.value);i.debug({results:a},"Set cookies");break}case"LOCAL_STORAGE":if(!r.value||!r.key)break;await this.browser.setLocalStorage(r.key,r.value);break;case"JAVASCRIPT":{let a;try{r.environment==="BROWSER"?(a=await this.browser.evaluateCodeInPage({code:r.code,fragment:r.fragment??!1,context:n.toObjectCopy(),timeoutMs:r.timeout?r.timeout*1e3:void 0}),i.info({result:a},"Executed JavaScript in browser")):a=await Sa({orgId:this.orgId,code:r.code,fragment:!!r.fragment,context:n,timeoutMs:r.timeout?r.timeout*1e3:void 0,logger:i,localTools:this.localCodeEvalTools,signal:this.executeAbortController.signal,callbacks:{onPersistentVariableUpdates:async s=>{if(!this.options?.scratchPadId){i.warn({updates:s},"Got persistent variable updates but scratch pad is not available");return}await this.storage.savePersistentVariables?.({scratchPadId:this.options?.scratchPadId,orgId:this.orgId,updates:s,logger:i})}}})}catch(s){throw this.throwIfClosed(),new L("ActionFailureError",s instanceof Error?s.message:`${s}`,{errOptions:{cause:s}})}try{JSON.stringify(a)}catch(s){throw new L("ActionFailureError",`Return value is not serializable: ${s instanceof Error?s.message:`${s}`}`,{errOptions:{cause:s}})}return{urlAfterCommand:this.browser.url(),succeedImmediately:!1,data:a}}case"TYPE":{if(r.target&&No(r.target)){await this.browser.clickUsingVisualCoordinates(r.target.pixels,r),await this.traceBrowserInteraction("Type",()=>this.browser.type(r.value,{force:r.force,clearContent:r.clearContent,forceClearContent:r.forceClearContent,delay:r.delay,pressEnter:r.pressEnter},!0),{value:r.value});break}let a=this.browser.url(),s,c,l=mF(r.target),u=this.browser.userBrowserSettings.globalLocatorRedirect===void 0||this.browser.userBrowserSettings.globalLocatorRedirect==="always";if(l){let{elementInteractedDisplayString:p,thoughts:m}=await this.wrapElementTargetingCommand({tracer:e,command:r,target:l,cache:r.cache?.target,action:f=>this.traceBrowserInteraction("Type",()=>this.browser.typeIntoTarget(r.value,f,{force:r.force,clearContent:r.clearContent,forceClearContent:r.forceClearContent,delay:r.delay,pressEnter:r.pressEnter,relativePosition:r.relativePosition}),{value:r.value,selector:f.locator.toString()}),options:{...r,targetName:"target",disableCache:o,disableGlobalLocatorRedirect:!u,source:qa(r)}});s=p,c=m}else await this.traceBrowserInteraction("Type",()=>this.browser.type(r.value,{force:r.force,clearContent:r.clearContent,forceClearContent:r.forceClearContent,delay:r.delay,pressEnter:r.pressEnter},!0),{value:r.value});let d={urlAfterCommand:this.browser.url(),succeedImmediately:!1,elementInteracted:s,thoughts:c};return vh(a,d.urlAfterCommand)&&(d.succeedImmediately=!0,d.succeedImmediatelyReason="URL changed"),d}case"HOVER":{if(No(r.target)){let{pixels:c}=r.target;await this.traceBrowserInteraction("Hover",()=>this.browser.hoverUsingVisualCoordinates(c),{coordinates:c});break}let{elementInteractedDisplayString:a,thoughts:s}=await this.wrapElementTargetingCommand({tracer:e,command:r,target:r.target,cache:r.cache?.target,action:c=>this.traceBrowserInteraction("Hover",()=>this.browser.hover(c),{selector:c.locator.toString()}),options:{...r,targetName:"target",disableCache:o}});return{succeedImmediately:!1,urlAfterCommand:this.browser.url(),elementInteracted:a,thoughts:s}}case"FOCUS":{if(!zi(r.target))throw new Error("Focus with x/y is not supported yet");let{elementInteractedDisplayString:a,thoughts:s}=await this.wrapElementTargetingCommand({tracer:e,command:r,target:r.target,cache:r.cache?.target,action:c=>this.browser.focus(c),options:{...r,targetName:"target",disableCache:o}});return{succeedImmediately:!1,urlAfterCommand:this.browser.url(),elementInteracted:a,thoughts:s}}case"BLUR":{if(r.target&&!zi(r.target))throw new Error("Blur with x/y is not supported yet");if(!r.target||!r.target.elementDescriptor)return await this.browser.blur(null),{succeedImmediately:!1,urlAfterCommand:this.browser.url()};let{elementInteractedDisplayString:a,thoughts:s}=await this.wrapElementTargetingCommand({tracer:e,target:r.target,command:r,cache:r.cache?.target,action:c=>this.browser.blur(c),options:{...r,targetName:"target",disableCache:o}});return{succeedImmediately:!1,urlAfterCommand:this.browser.url(),elementInteracted:a,thoughts:s}}case"PRESS":{let a=this.browser.url();await this.traceBrowserInteraction("Press key",()=>this.browser.press(r.value,{repeat:r.repeat,convertMeta:r.convertMeta??!0,delayMs:r.delayMs}),{value:r.value});let s={urlAfterCommand:this.browser.url(),succeedImmediately:!1};return vh(a,s.urlAfterCommand)&&(s.succeedImmediately=!0,s.succeedImmediatelyReason="URL changed"),s}case"KEY_DOWN":return await this.browser.keyDown(r.value,{convertMeta:r.convertMeta??!0}),{urlAfterCommand:this.browser.url(),succeedImmediately:!1};case"KEY_UP":return await this.browser.keyUp(r.value,{convertMeta:r.convertMeta??!0}),{urlAfterCommand:this.browser.url(),succeedImmediately:!1};case"REQUEST":{let a=new K8,s=q8(fetch,a),c;try{c=new URL(r.url).hostname}catch{}let l=await cF({command:r,baseUrl:this.browser.baseUrl,logger:i,fetchImplementation:s});return{data:su.parse({...l,cookies:hx(a,c)}),succeedImmediately:!1,urlAfterCommand:this.browser.url()}}case"GRAPHQL_REQUEST":return{data:await pF({command:r,baseUrl:this.browser.baseUrl,logger:i}),succeedImmediately:!1,urlAfterCommand:this.browser.url()};case"VISUAL_DIFF":return lF({tracer:e,command:r,disableCache:o,browser:this.browser,logger:i,screenshotStorage:this.visualDiffScreenshotStorage,targetingWrapper:a=>this.wrapElementTargetingCommand(a)});case"FILE_UPLOAD":{let a,s;if(r.fileSource.type==="URL"?(s=r.fileSource.url,a=await Tk({uri:r.fileSource.url,logger:i,orgId:this.orgId})):r.fileSource.type==="USER_FILE"&&(s=r.fileSource.name,a=await this.uploadedFileStorage?.getFileForUpload(r.fileSource.name,this.orgId)),!a)throw new L("UserConfigurationError",`Attempted to use non-existent file for upload step: ${s}`);await this.browser.setFileChooserHandler({...a,filename:r.filename});break}case"AUTH_SAVE":return{data:await this.browser.saveAuthState(),succeedImmediately:!1,urlAfterCommand:this.browser.url()};case"AUTH_LOAD":{let a;if(!r.storageState.trim())a=void 0;else if(a=await Sa({orgId:this.orgId,code:r.storageState,fragment:!1,context:n,logger:i,localTools:this.localCodeEvalTools,signal:this.executeAbortController.signal}),typeof a!="object")throw new L("ActionFailureError",`Credentials must evaluate to an object (received ${typeof a} instead)`);let s;try{s=wm.optional().parse(a)}catch(c){throw new L("ActionFailureError",`Credentials provided do not follow the required format: ${c}`)}await this.browser.loadAuthState(s);break}case"ELEMENT_CHECK":{let a=(r.timeout??Nn)*1e3,s=this.generator.getAgentConfig()?.assertion;if(aF(r.assertion)&&!r.useSelector&&r.target.type==="description"&&s&&s!=="v1"){let l={id:r.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: ${r.target.elementDescriptor}`,iframeUrl:r.iframeUrl,timeout:r.timeout,source:"NEGATED_CHECK",cache:r.cache&&"memory"in r.cache?{memory:r.cache?.memory}:void 0};try{let u=await Eg({command:l,logger:i,aiPageFiltering:!!this.options?.aiPageFiltering,fixtures:this.getControllerFixtures(),useMemory:this.shouldUseMemory()});return{succeedImmediately:!1,thoughts:`The element described does not exist on the page: ${u.thoughts}`,urlAfterCommand:this.browser.url(),afterScreenshotOverride:u.afterScreenshotOverride}}finally{l.cache?.memory&&Bd(r,l.cache?.memory.traces,i)}}let c=await iF({command:r,tracer:e,timeoutMs:a,targetingWrapper:l=>this.wrapElementTargetingCommand(l),fixtures:this.getControllerFixtures(),disableCache:o});return{fail:!c.success,data:c.data,elementInteracted:c.elementInteractedDisplayString,thoughts:c.err?.message??c.thoughts??`Element assertion ${c.success?"succeeded":"failed"}.`,succeedImmediately:!1,urlAfterCommand:this.browser.url()}}case"PAGE_CHECK":{let a=await oo({action:async()=>bg({assertion:r.assertion,browser:this.browser,logger:i,timeout:r.timeout,signal:this.executeAbortController.signal,autoExpandIframes:!!this.browser.userBrowserSettings.autoExpandIframes}),frameConfig:r.iframeUrl?{type:"url",url:r.iframeUrl}:void 0,browser:this.browser,logger:i});return{fail:!a.success,data:a.data,thoughts:a.success?"Page assertion passed.":a.err?.message??`Page assertion still failing after ${r.timeout} seconds.`,urlAfterCommand:this.browser.url(),succeedImmediately:!1}}case"REGISTER_REQUEST_LISTENER":{let a=new Ta(r.requestMatcher),s=this.browser.registerRequestListener(a);return this.registeredListeners[r.key]=s.then(async c=>await nv(c)).catch(c=>{i.error({err:c},"Failed to get request listener response")}),{succeedImmediately:!1,urlAfterCommand:this.browser.url()}}case"AWAIT_LISTENER":{let a=this.registeredListeners[r.key];if(!a)throw new L("ActionFailureError",`No listener registered with key: ${r.key}`);let s=r.timeout??10;return{data:await J(a,{milliseconds:s*1e3,message:`Request listener timed out after ${s} seconds`}),succeedImmediately:!1,urlAfterCommand:this.browser.url()}}case"RECORD_REQUESTS":{let a=new Ta(r.requestMatcher);return this.recordedRequests[r.key]={},this.browser.registerRequestRecorder(r.key,{matches:s=>a.matches({url:s.request.url,method:s.request.method}),onRequestStart:(s,c)=>{this.recordedRequests[r.key][s]=sg(c)},onRequestComplete:(s,c)=>{this.recordedRequests[r.key]?.[s]&&(this.recordedRequests[r.key][s]=sg(c))}}),{succeedImmediately:!1,urlAfterCommand:this.browser.url()}}case"GET_RECORDED_REQUESTS":{let a=this.recordedRequests[r.key];if(!a)throw new L("ActionFailureError",`No recorder registered with key: ${r.key}`);return delete this.recordedRequests[r.key],{data:Object.values(a),succeedImmediately:!1,urlAfterCommand:this.browser.url()}}case"SET_HEADER":{let a;return r.requestMatcher&&(a=new Ta(r.requestMatcher)),this.browser.setHeader(r.name,r.value,a),{succeedImmediately:!1,urlAfterCommand:this.browser.url()}}case"MOCK_ROUTE":return{data:{key:this.browser.registerMock(r.key,new Ta(r.requestMatcher),async(s,c)=>{let l=await Sa({orgId:this.orgId,code:r.responseGenerator,fragment:!1,context:n,timeoutMs:void 0,logger:i,localTools:this.localCodeEvalTools,mock:{request:s,response:c},disallowVariableUpdates:!0,responseSerialization:"RESPONSE"}),u=Gx.parse(l);return new Response(u.body,{status:u.status,headers:u.headers})},r.fetchOriginalResponse??!1)},succeedImmediately:!1,urlAfterCommand:this.browser.url()};case"REMOVE_ROUTE_MOCK":return this.browser.removeMock(r.key),{succeedImmediately:!1,urlAfterCommand:this.browser.url()};case"OFFLINE_MODE":return await this.browser.setOfflineMode(r.enable),{succeedImmediately:!1,urlAfterCommand:this.browser.url()};default:return(s=>{throw"If Typescript complains about the line below, you missed a case or break in the switch above"})(r)}return{succeedImmediately:!1,urlAfterCommand:this.browser.url()}}async getReverseMappedDescription({browserState:e,targetId:r,disableCache:n,screenshot:o}){return(await this.generator.getReverseMappedDescription({browserState:e,target:r,screenshot:o},{disableCache:n,abortSignal:this.executeAbortController.signal,loggerTags:ot(this.logger)})).phrase}async stopRecordMode(){this.recordAbortController?.abort(),await this.browser.clearAllCdpHighlights()}async startRecordMode({params:e,abortController:r,isClickToRecord:n}){this.recordAbortController=r;let o=new mg({signal:r.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:ot(this.logger)})}async getFailureRecoveryPlan(e,r){return this.generator.getFailureRecoveryPlan(e,{disableCache:!0,abortSignal:this.executeAbortController.signal,loggerTags:ot(r??this.logger)})}};var Lv=async t=>{let{step:e,resolvedInputs:r}=t.moduleParams,{logger:n,context:o,storage:i,codeEvalTools:a,controller:s}=t.fixtures,c=s.browser,{orgId:l,runId:u}=t.inputs,d=s.executeAbortController.signal;Object.keys(r).length>0&&(o.setInputs(r),n.info(Gd({json:{inputs:r,moduleId:e.moduleId},maxJsonStringSize:1e3}),"Set module inputs"));let p,m=!1,f,h;if(e.cacheConfig||e.defaultCacheAllInvocations){let S=e.cacheConfig?.cacheKey||e.defaultCacheKey||"",g=await Jr({orgId:l,s:S,context:o,logger:n,localTools:a,signal:d});h={orgId:l,cacheKeys:[g,...Object.entries(r).map(([y,b])=>`${y}:${b}`)]},n.info({original:S,keyParams:h},"Module cache key params");let E=Date.now();for(;Date.now()-E<E_;){d?.throwIfAborted();let y=await i.getCacheResult(h);if(y){n.info({cacheResult:vt(y,1e3,!0)},"Got result from module execution cache"),p=vg(e,r,"SUCCESS"),p.message="Used cached module result.",p.data=JSON.parse(y),m=!0;break}else n.info({cacheKey:S,keyParams:h},"No cache result found, continuing with lock acquisition");let b=await i.acquireCacheLock({keyParams:h,clientMetadata:`hostName:${Y8()};runId:${u}`},d);if(b.acquired){f=b.keyPrefix,n.info({cacheKeyPrefixIfLockAcquired:f,cacheKey:S,keyParams:h},"Acquired cache lock and proceeding with module execution");break}else n.debug({cacheKeyPrefixIfLockAcquired:f,cacheKey:S,keyParams:h},"Failed to acquire cache lock, retrying...");await xe(2500+Math.random()*1e4,d)}}try{if(!p)p=await X8(t);else if(e.autoAuth){let S=wm.safeParse(p.data);if(!S.success)throw new L("UserConfigurationError",`Cached authentication module result is not a valid storage state: ${S.error.message}`);n.debug("Automatically loading auth state after cached module result"),await c.loadAuthState(S.data);let g=!1,E=e.advanced?.cacheInvalidation;if(E&&E.type==="PAGE_CHECK"){let y={type:"CONTENT",value:E.substring},b=await bg({timeout:Nn,assertion:y,browser:c,logger:n,signal:d,autoExpandIframes:!!c.userBrowserSettings.autoExpandIframes});b.success?n.debug({invalResult:b},"Cached result still valid after page check, continuing..."):(n.info({invalResult:b},"Invalidating cached result due to page check failure"),g=!0)}if(h&&g)return await i.deleteCacheResult(h),Lv(t)}}finally{try{f!==void 0&&!m&&p?.status==="SUCCESS"&&await J8({step:e,result:p,browser:s.browser,cacheKeyPrefix:f,logger:n,storage:i})}finally{f!==void 0&&await i.releaseCacheLock(f)}}return p},X8=async t=>{let{currentParentIdChain:e}=t,{step:r,tracer:n}=t.moduleParams,o=vg(r,t.moduleParams.resolvedInputs,"SUCCESS"),i=await n.startSubSteps(),{status:a,results:s}=await t.executeStepList({...t,listParams:{steps:r.steps,containerName:`module ('${r.name}')`,tracer:i,currentParentIdChain:e}});return o.results=s,o.status=a,o.finishedAt=new Date,to({asyncTasks:t.work.asyncTasks,nestedResults:s,result:o,logger:t.fixtures.logger}),o};function vg(t,e,r){let n={};return Object.entries(e).forEach(([i,a])=>{n[i]=JSON.stringify(a)}),{type:"MODULE",id:t.id,moduleId:t.moduleId,moduleName:t.name,startedAt:new Date,cacheConfig:t.cacheConfig,inputs:n,results:[],finishedAt:new Date,status:r}}async function fF({orgId:t,step:e,context:r,logger:n,codeEvalTools:o,signal:i}){let a={};try{for(let s of e.parameters??[]){let c=e.inputs?.[s]??e.defaultParameters?.[s];if(!c){n.warn(`No value or default found for parameter '${s}' that is required by module '${e.name}'`);continue}a[s]=await Sa({orgId:t,code:c,fragment:!0,context:r,logger:n,localTools:o,signal:i})}return a}catch(s){throw i?.throwIfAborted(),new L("UserConfigurationError",`Failed to evaluate module inputs: ${s}`)}}async function J8({step:t,result:e,browser:r,cacheKeyPrefix:n,logger:o,storage:i}){let a=t.cacheConfig?.cacheExpiryMs;(!a||a===uI)&&(a=t.defaultCacheTtl??dI);let s;t.autoAuth?s=JSON.stringify(await r.saveAuthState()):e.data!==void 0?s=JSON.stringify(e.data):s='""',o.debug({cacheKeyPrefix:n,ttlMs:a,truncatedCacheResultJson:Gd({json:s,maxJsonStringSize:1e4})},"Setting module cache result"),await i.setCacheResult({result:s,keyPrefix:n,ttlMs:a})}async function Hs(t,e,r){return Q8(t,e,r)}async function Q8(t,e,r){let n=new Date;try{return r.throwIfAborted(),await e()}catch(o){let i=new Date,a="FAILED",s;if(r.aborted||o instanceof DOMException&&o.name==="AbortError"?(s="Step aborted by user.",a="CANCELLED"):o instanceof L?s=`${o}`:s=`An unexpected error occurred: ${o.message}`,t.type==="RESOLVED_MODULE"){let c=vg(t,{},"FAILED");return c.message=s,c.startedAt=n,c.finishedAt=i,c}return{...Th(t),startedAt:n,finishedAt:i,status:a,data:null,message:s,results:[]}}}async function _o(t,e){let r=!1;try{return t&&!t.state.failureRecoveryDisabled&&(t.state.failureRecoveryDisabled=!0,r=!0),await e()}finally{t&&r&&(t.state.failureRecoveryDisabled=void 0)}}import{cloneDeep as x9}from"lodash-es";import{randomUUID as hF}from"crypto";import{diff as Z8}from"deep-object-diff";import{cloneDeep as gF}from"lodash-es";var Ag=async t=>{let{step:e,tracer:r}=t.presetParams,{logger:n,controller:o,context:i}=t.fixtures,{collectDebugData:a}=t.options,{testMetadata:s}=t.inputs,c=e.command.type,l=n.child({commandType:c,stepId:e.id,commandId:e.command.id}),u="cache"in e.command&&e.command.cache?gF(e.command.cache):{},d=o.browser.url(),p=new Date,m,f=hF(),h=hF();if(a)try{if(m=await o.browser.screenshot({retries:1,clearHighlights:!0,quality:75}),!o.browser.userBrowserSettings.disableHtmlSnapshots){let y=await o.browser.getRawCondensedHtml();r.attachBeforeHtmlSnapshot({logger:l,snapshotId:f,html:y})}}catch(y){l.debug({err:y},"Failed to take before screenshot, continuing...")}let S,g,E;try{let y=await o.executePresetCommand(r,e.command,i,s?.advanced.disableAICaching??!1);y.beforeScreenshotOverride&&(m=y.beforeScreenshotOverride),E=y.afterScreenshotOverride;let b=new Date,C=o.browser.url();g={beforeUrl:d,afterUrl:C,startedAt:p,finishedAt:b,viewport:o.browser.getViewport(),status:y.fail?"FAILED":"SUCCESS",elementInteracted:y.elementInteracted},S={...e,message:y.thoughts??"Successfully executed preset action.",beforeUrl:d,afterUrl:C,finishedAt:b,startedAt:p,status:y.fail?"FAILED":"SUCCESS",data:y.data,results:[g]},"assertion"in e.command&&(S.message=y.thoughts||"Assertion passed.")}catch(y){l.error({message:y.message,stack:y.stack},`Failed executing preset step ${bi(e.command)}`);let b=o.browser.url(),C=new Date,I=y instanceof Error?y.message:`${y}`;g={beforeUrl:d,afterUrl:b,startedAt:p,finishedAt:C,viewport:o.browser.getViewport(),status:y instanceof DOMException&&y.name==="AbortError"?"CANCELLED":"FAILED",message:I},S={...e,startedAt:p,finishedAt:C,beforeUrl:d,afterUrl:b,status:y instanceof DOMException&&y.name==="AbortError"?"CANCELLED":"FAILED",message:I,failureReason:y instanceof L?y.reason:void 0,results:[g]}}finally{let y="cache"in e.command&&e.command.cache?gF(e.command.cache):{},b=Z8(u,y);b&&Object.keys(b).length>0&&l.info({diffs:Im(b)},"Updated cache")}if(a)try{if(E||(E=await o.browser.screenshot({retries:1,quality:75})),!o.browser.userBrowserSettings.disableHtmlSnapshots){let y=await o.browser.getRawCondensedHtml();r.attachAfterHtmlSnapshot({logger:l,snapshotId:h,html:y})}}catch(y){l.debug({err:y},"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 g.beforeSnapshot=f,S.beforeSnapshot=f,g.afterSnapshot=h,S.afterSnapshot=h,m&&r.attachBeforeScreenshot({snapshotId:f,screenshot:m}),E&&r.attachAfterScreenshot({snapshotId:h,screenshot:E}),S};async function e9(t,e,r){let{tracer:n}=t.conditionalParams,{logger:o,controller:i}=t.fixtures,a=e.assertion.command;a.type==="AI_ASSERTION"&&(a.source="CONDITIONAL_CHECK");try{let s=await _o(t.work,()=>Ag({...t,presetParams:{tracer:n,step:e.assertion}}));switch(a.type){case"AI_ASSERTION":case"ELEMENT_CHECK":case"PAGE_CHECK":return s.status==="SUCCESS"?{type:"passed",conditionResult:s,steps:e.steps}:(o.info(s.message,`${a.type} condition ${r} resolved to false`),{type:"failed",conditionResult:s});case"JAVASCRIPT":{if(s.status==="FAILED")return{type:"execution_error",conditionResult:s};let c=!!s.data;return s.status=c?"SUCCESS":"FAILED",s.message=c?`JavaScript condition evaluated to true (${JSON.stringify(s.data)})`:`JavaScript condition evaluated to false (${JSON.stringify(s.data)})`,o.info({returnValue:s.data,conditionPassed:c},`JavaScript condition ${r} evaluated`),c?{type:"passed",conditionResult:s,steps:e.steps}:{type:"failed",conditionResult:s}}default:return(l=>{throw new Error(`Unsupported conditional command type: ${l}`)})(a.type)}}catch(s){o.error({err:s},`Condition ${r} failed with error`);let c=s instanceof Error?s.message:"Unknown error during condition evaluation";return{type:"execution_error",conditionResult:{...e.assertion,status:"FAILED",message:c,startedAt:new Date,finishedAt:new Date,results:[]}}}finally{a.type==="AI_ASSERTION"&&delete a.source,i.throwIfClosed()}}function t9(t,e,r,n){let o=n.slice(r.length);for(let i=0;i<t.blocks.length;i++){let a=t.blocks[i],{result:s}=Ts(a.steps,e,o);if(s)return i}return-1}async function SF(t){let{currentParentIdChain:e}=t,{step:r}=t.conditionalParams,{logger:n}=t.fixtures,{fromStep:o}=t.inputs,i=new Date,a=Th(r),s=!!o&&Fd(e,o.parentStepIdChain),c=r.elseSteps,l=!0,u=[],d,p=!1;if(s&&o){let g=t9(r,o.fromStepId,e,o.parentStepIdChain);g>=0&&(c=r.blocks[g].steps,l=!1,p=!0,n.info(`Skipping conditional assertion (execution starts from step within block ${g}), running ${c.length} steps`))}if(!p)for(let g=0;g<r.blocks.length;g++){n.info(`Evaluating condition ${g} in conditional step`);let E=r.blocks[g],y=await e9(t,E,g);if(u.push(y.conditionResult),d=y.conditionResult,y.type==="execution_error"){let b={...a,assertionResult:y.conditionResult,status:"FAILED",startedAt:i,finishedAt:new Date,message:y.conditionResult.message,results:[]};return to({asyncTasks:t.work.asyncTasks,nestedResults:u,result:b,logger:n}),b}if(y.type==="passed"){n.info(`Condition ${g} resolved to true, executing the corresponding ${y.steps.length} steps`),l=!1,c=y.steps;break}}if(c)l&&n.info("No conditions resolved to true, executing the else block steps");else{n.warn("No conditions resolved to true and no else block was provided, causing the entire conditional step to be skipped");let g={...a,assertionResult:d,status:"SUCCESS",startedAt:i,data:u[u.length-1]?.data,message:u[u.length-1]?.message,results:[],finishedAt:new Date};return to({asyncTasks:t.work.asyncTasks,nestedResults:[...u],result:g,logger:n}),g}n.info(`Executing ${c.length} steps in the selected conditional block`);let m=await t.conditionalParams.tracer.startSubSteps(),f=await t.executeStepList({...t,listParams:{steps:c,containerName:"conditional block",tracer:m,currentParentIdChain:e}}),S={...a,assertionResult:d,...f,startedAt:i,finishedAt:new Date};return to({asyncTasks:t.work.asyncTasks,nestedResults:[...u,...f.results],result:S,logger:n}),S}import{randomUUID as yF}from"crypto";var EF=async t=>{let{tracer:e}=t.aiStepParams,{controller:r}=t.fixtures;await r.browser.waitForStability();let n=await r.browser.screenshot({}),o=await r9(t);o.finishedAt=new Date,to({asyncTasks:t.work.asyncTasks,result:o,nestedResults:o.results,logger:t.fixtures.logger});let i=await r.browser.screenshot({}),a=yF();o.beforeSnapshot=a,e.attachBeforeScreenshot({snapshotId:a,screenshot:n});let s=yF();return o.afterSnapshot=s,e.attachAfterScreenshot({snapshotId:s,screenshot:i}),o},r9=async t=>{let{currentParentIdChain:e}=t,{step:r,tracer:n}=t.aiStepParams,{controller:o,context:i,logger:a}=t.fixtures,s={...r,startedAt:new Date,beforeTestContext:i.toRedactedDisplayCopy(),finishedAt:new Date,results:[],status:"SUCCESS"};if(!("steps"in r&&r.steps&&r.steps.length>0&&r.steps[r.steps.length-1]?.command.type==="SUCCESS"))throw new L("UserConfigurationError","AI action has been fully deprecated. Please delete this step and transition to Dynamic AI Action.");try{let l=await n.startSubSteps(),{status:u}=await t.executeStepList({...t,listParams:{steps:r.steps,containerName:"AI action",results:s.results,tracer:l,currentParentIdChain:e}});return s.finishedAt=new Date,s.status=u,s}catch(l){a.warn({err:l},"Failed executing saved deprecated AI action steps");let u=o.executeAbortController.signal.aborted;s.message=l instanceof Error?l.message:`${l}`,s.status=u?"CANCELLED":"FAILED"}return s};import{randomUUID as Fv}from"crypto";var TF=t=>{throw new Error(`Exhaustive check failed for value: ${t}`)};import{streamText as f9}from"ai";var Cg=class{controller;logger;rootStep;subStepIndex=0;callbacks;results=[];constructor(e){this.controller=e.controller,this.logger=e.logger,this.rootStep=e.rootStep,this.callbacks=e.callbacks}finalState=void 0;async createAndExecuteStep(e){this.callbacks.onAiActionEvent?.({type:"SUBSTEP_CREATED",rootStep:this.rootStep,step:e});let r=this.subStepIndex++,n=await this.callbacks.executeStep(e,r);return this.results.push(n),n}recordGenericToolCall(e){this.callbacks.onAiActionEvent?.({type:"GENERIC_TOOL_CALLED",toolName:e,rootStep:this.rootStep})}};import{hasToolCall as d9,stepCountIs as p9}from"ai";import bF from"dedent";var o9=bF`
|
|
4612
|
+
`),tokenLength:d}),s.forEach((h,S)=>{let g=h.ids[0],E=h.ids[h.ids.length-1];t.debug({tokenLength:h.tokenLength,minId:g,maxId:E},`Chunk for page filtering (index ${S+1}/${s.length})`)}),{chunks:s}}var w8=75e4,yg=3e5;async function zs(t){let{options:e,fixtures:r,screenshot:n}=t,{aiPageFiltering:o}=e,{logger:i,generator:a,orgId:s,signal:c}=r,l=t.tree,u=t.serializedTree,d=et(u);if(d>w8)try{let p=Sg({serializedTree:u,options:{minChunkTokenCount:1e4,maxChunkTokenCount:1e5,acceptableChunkTokenCount:5e4,maxLineLength:4e3},logger:i});l=await _8({...t,tokenLimit:yg-1e4,chunks:p.chunks}),u=l.serialize();let m=et(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"),l=l.pruneToSerializedCharLimit(yg*ca),u=l.serialize();let m=et(u);i.info({oldTokens:d,newTokens:m},"Filtered page using naive truncation"),d=m}if(d>yg)try{if(o){let p=Sg({serializedTree:u,options:X0,logger:i}),m=R8();l=await J(x8({...t,chunks:p.chunks,callId:m}),{milliseconds:12e3,signal:c}),u=l.serialize();let f=et(u);i.info({oldTokens:d,newTokens:f,langfuseCallId:m},"Filtered page using AI chunk ranking"),d=f}else{let p=Sg({serializedTree:u,options:Y0,logger:i});l=await J(I8({...t,chunkResult:p,tokenLimit:4e4}),{milliseconds:12e3,signal:c}),u=l.serialize();let m=et(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"),l=l.pruneToSerializedCharLimit(yg*ca),u=l.serialize(),i.info("Filtered page using naive truncation")}return u}async function x8({type:t,callId:e,chunks:r,description:n,fixtures:o,tree:i}){let{generator:a,signal:s,logger:c}=o,l=await a.rankChunksWithAi({chunks:r,description:n,type:t,softTokenLimit:4e4,hardTokenLimit:8e4,callId:e},{abortSignal:s,logger:c,loggerTags:ot(c)}),u=[];return r.forEach((p,m)=>{l.indices.includes(m)&&(u=u.concat(p.ids))}),i.pruneUsingRelevantIds(new Set(u))}async function _8(t){let{description:e,fixtures:r,tree:n}=t,{generator:o,logger:i,signal:a}=r;if(!e.trim())throw new Error("Empty description passed to page filtering");let s=await o.getExtractedKeywords({goal:e},{logger:i,loggerTags:ot(i),abortSignal:a});i.info({keywordsResult:s},"Got keywords for page filtering");for(let c of s.keywords){let l=t.chunks.filter(m=>m.content.toLowerCase().includes(c.toLowerCase()));if(!l.length||l.reduce((m,f)=>m+f.tokenLength,0)>t.tokenLimit&&l.length>1)continue;let d=l.flatMap(m=>m.ids);return n.pruneUsingRelevantIds(new Set(d))}throw new Error("No keywords were unique enough for page filtering")}async function I8(t){let{description:e,fixtures:r,chunkResult:n,tokenLimit:o,tree:i}=t,{generator:a,logger:s,signal:c}=r,l=await a.rankChunksWithRag({description:e,chunks:n.chunks,tokenLimit:o},{abortSignal:c,logger:s,loggerTags:ot(s)});if(l.ids.length===0)throw new Error("RAG returned no important ids");return i.pruneUsingRelevantIds(new Set(l.ids.map(d=>`${d}`)))}async function Mv(t,e){if(!t.description)throw new L("UserConfigurationError","Cannot locate element with empty description");return oo({action:async()=>P8(t,e),frameConfig:t.iframeUrl?{type:"url",url:t.iframeUrl}:void 0,browser:e.browser,logger:t.logger})}async function P8(t,e){let{disableCache:r,testContext:n,filterByViewport:o,skipWait:i,source:a,memory:s,aiPageFiltering:c,logger:l,allowNotActionableNodesOverride:u,skipSavingVisualAttributes:d,isAutoHeal:p,cacheBustReason:m}=t,{orgId:f,browser:h,localCodeEvalTools:S,generator:g,abortSignal:E}=e,y=t.description,b=un(),C=t.useMemory&&!r;n&&(y=await Jr({orgId:f,s:y,context:n,localTools:S,signal:E,logger:l})),a&&(y=V0(y,a));let{serializedTree:I,tree:_}=await b.startAsyncSpan("GET_PAGE_STATE",async()=>ti(h,{allowNotActionableNodesOverride:u,filterByViewport:o,abortSignal:E,skipWait:i,logger:l}),{}),R=await b.startAsyncSpan("GET_PAGE_SCREENSHOT",async()=>{let X,ne=Date.now(),de;for(;!X&&Date.now()-ne<3e3;){E.throwIfAborted();try{X=await h.screenshot({clearHighlights:!0,respectActiveFrame:!0,retries:2})}catch(Te){de=Te}}if(!X)throw new L("ActionFailureError",`Failed to take screenshot of page to locate element. The page may be unresponsive, or your machine might be severely resource constrained. Error: ${de?.message}`);return X}),M=I,P=!1,F=`data:image/jpeg;base64,${R.toString("base64")}`;M=await zs({type:"locator",description:y,screenshot:F,serializedTree:I,options:{aiPageFiltering:c},tree:_,fixtures:{generator:g,signal:E,logger:l,orgId:f}}),M!==I&&(P=!0);let G=await b.startAsyncSpan("AI_LOCATOR_CALL",async X=>{p&&(X.attributes.isAutoHeal=!0),m&&(X.attributes.cacheBustReason=m);let ne=await g.getElementLocation({browserState:M,goal:y,screenshot:F,source:a,memory:C?s:void 0},{disableCache:r,abortSignal:E,loggerTags:ot(l),useMemory:C});if(X.result=ne,b.storeTraceAsset){let de=Q0();b.storeTraceAsset({snapshotId:de,data:R}),X.screenshotSnapshotId=de}return ne});if(l.debug({usedRag:P,result:G},"Got locator result"),!(G.id>0))throw new Sl(`Could not find any relevant element: ${G.thoughts}`,G.updatedMemory?{type:"GCS_TRACES",traces:G.updatedMemory}:void 0);let{resolution:ae,target:W,frameConfig:q}=await b.startAsyncSpan("TARGET_RESOLUTION",async X=>{let ne=await h.createTargetFromA11yId({id:G.id,requirements:G.requirements,additionalElements:G.additionalElements,description:y,targetSource:"AI",logger:l,skipSavingVisualAttributes:d});if(X.result={serializedElement:ne.target.nodeOnlySerializedHtml??"Unknown HTML element"},b.storeTraceAsset)try{let de=await h.screenshot({locator:ne.resolution.locator,clearHighlights:!0}),Te=Q0();b.storeTraceAsset({snapshotId:Te,data:de}),X.elementScreenshotSnapshotId=Te}catch(de){l.debug({err:de},"Failed to capture element screenshot for locator trace, continuing...")}return ne});if(ae.a11yNode?.properties?.hidden&&ae.a11yNode?.properties?.hidden!=="false")throw new L("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: ${ae.displayString}`);return C&&(G.updatedMemory?W.memory={type:"GCS_TRACES",traces:G.updatedMemory}:s&&(W.memory=s)),{thoughts:G.thoughts,target:W,resolution:ae,frameConfig:q,screenshot:F}}import{randomUUID as Z0}from"crypto";var M8=15;async function Eg({command:t,aiPageFiltering:e,logger:r,fixtures:n,useMemory:o,maxRetries:i=M8}){if(!t.assertion.trim())throw new L("ActionFailureError","Assertion command is missing the assertion content");let a=dy.optional().catch(void 0).parse(t.source);t.source&&!a&&r.warn(`Invalid source ${t.source} for AI assertion, ignoring...`);let s=un();return s.startAsyncSpan("AI_ASSERTION_CALL",async c=>{let{browser:l}=n,u=t.timeout?t.timeout*1e3:l.smartWaitingTimeout,d=AN(u,i-1),p=0,m=Date.now(),f=m+u,h=m,S,g,E;try{await oo({action:()=>l.clearHighlights(),frameConfig:t.iframeUrl?{type:"url",url:t.iframeUrl}:void 0,browser:l,logger:r})}catch(C){r.warn({err:C},"Failed to clear highlights before AI check, continuing...")}for(;p<i;){n.abortSignal.throwIfAborted();let C=Date.now();if(p>0){if(C>=f)break;let R=f-C,M=h-C,P=Math.min(M,R);P>0&&await xe(P,n.abortSignal)}let I=Date.now();if(p>0&&I>=f)break;let _=!1;try{if(S=await oo({action:async()=>{let M=await eF(l,r,n.abortSignal);return g&&g.serializedTree===M.serializedTree&&g.screenshotBuff.equals(M.screenshotBuff)?(_=!0,S):(g=M,tF({command:t,state:M,fixtures:n,useMemory:o,useConsensus:!1,highlightElementsOnFailure:!1,attemptNumber:p,aiPageFiltering:e,logger:r,source:a}))},frameConfig:t.iframeUrl?{type:"url",url:t.iframeUrl}:void 0,logger:r,browser:l}),S?.success){S?.updatedMemory&&Bd(t,S.updatedMemory,r);break}else throw S?.thoughts?new L("AssertionFailureError",S.thoughts):new L("InternalPlatformError","No thoughts were provided for AI assertion failure")}catch(R){n.abortSignal.throwIfAborted(),E=R instanceof Error?R:new Error(`${R}`),_?r.info(`AI check attempt ${p} failed (re-used previous result)`):r.info({err:R},`AI check assert attempt ${p} failed, retrying...`)}finally{p++,h=I+d}}if(!S?.success){let C=f-Date.now();C>0&&await xe(C,n.abortSignal)}if(!S?.success)try{S=await oo({action:async()=>tF({command:t,state:await eF(l,r,n.abortSignal),fixtures:n,useMemory:o,useConsensus:!0,highlightElementsOnFailure:!0,attemptNumber:p,aiPageFiltering:e,logger:r}),frameConfig:t.iframeUrl?{type:"url",url:t.iframeUrl}:void 0,logger:r,browser:l})}catch(C){n.abortSignal.throwIfAborted(),E=C instanceof Error?C:new Error(`${C}`)}finally{p++}S?.updatedMemory&&Bd(t,S.updatedMemory,r);let y=S?.afterScreenshotOverride;if(y&&s.storeTraceAsset){let C=Z0();s.storeTraceAsset({snapshotId:C,data:y}),c.screenshotSnapshotId=C}let b=S?.elementScreenshotOverride;if(b&&s.storeTraceAsset){let C=Z0();s.storeTraceAsset({snapshotId:C,data:b}),c.elementScreenshotSnapshotId=C}if(!S?.success){c.result={thoughts:E?.message??"AI check failed after all attempts",result:!1};let C=`AI check still failing after ${p} attempts.`;throw E&&(C+=` Latest result: ${E.message}`),new L("AssertionFailureError",C)}return c.result={thoughts:S.thoughts,result:!0},{...S,succeedImmediately:!1,urlAfterCommand:l.url()}})}async function eF(t,e,r){let[n,o]=await Promise.all([ti(t,{abortSignal:r,skipWait:!0,skipWaitForPageLoad:!0,logger:e}),t.screenshot({retries:1,respectActiveFrame:!0})]);return{...n,screenshotBuff:o}}async function tF({command:t,state:e,fixtures:r,useConsensus:n,useMemory:o,highlightElementsOnFailure:i,aiPageFiltering:a,attemptNumber:s,source:c,logger:l}){let{browser:u,generator:d,abortSignal:p}=r,m={type:"ASSERTION"},{serializedTree:f,tree:h}=e,S=e.screenshotBuff,g=S.toString("base64"),E=u.url(),y=t.contextChoice??"MULTIMODAL",b=f;y!=="VISION_ONLY"&&(b=await zs({type:"assertion",serializedTree:f,tree:h,description:t.assertion,screenshot:g,options:{aiPageFiltering:a},fixtures:{generator:d,signal:p,logger:l,orgId:r.orgId}}),b!==f&&(m.ragUsed=!0),m.pageState=b);let C={goal:t.assertion,url:E,memory:o?t.cache?.memory:void 0,browserState:b,screenshot:g,contextChoice:y,source:c},_=await(y==="VISION_ONLY"?(M,P)=>d.getVisualAssertionResult(M,P):(M,P)=>d.getAssertionResult(M,P))(C,{useConsensus:n,attemptNumber:s,useMemory:o,disableCache:!!t.disableCache,abortSignal:p,logger:l,loggerTags:ot(l)}),R;if((_.result||i)&&_.relevantElements?.length){m.relevantElementsSerialized=_.relevantElements.map(M=>u.getSerializedFormFromA11yId(M)).filter(M=>!!M);try{let M=_.relevantElements[0],{resolution:P}=await u.createTargetFromA11yId({id:M,description:null,targetSource:"AI",skipSaveToCache:!0});R=await u.screenshot({locator:P.locator,clearHighlights:!0,respectActiveFrame:!0})}catch(M){l.debug({err:M},"Failed to capture element screenshot for trace, continuing...")}await O8(_.relevantElements,u,l)}return{success:_.result,thoughts:_.thoughts,afterScreenshotOverride:S,elementScreenshotOverride:R,updatedMemory:o?_.updatedMemory:void 0}}async function O8(t,e,r){let n=Date.now();for(let o of t){if(Date.now()-n>2e3){r.debug("Highlighting relevant elements took over 2s, aborting...");return}try{let i=new AbortController;await J(e.highlightA11yId(o),{milliseconds:1e3,fallback:()=>{throw i.abort(),new Error("Timed out waiting for highlighting to complete")}})}catch(i){r.debug({err:i},"Failed to highlight relevant element after assertion, continuing...");return}}}var L8=1e5,Tg=class extends Error{constructor(){super("The page content exceeds the maximum token limit for AI smart waiting."),this.name="ExceededMaxAISmartWaitingTokensError"}};async function rF(t,e){let{logger:r}=t,{abortSignal:n,browser:o}=e,i=Date.now();try{await N8(i,t,e)}catch(a){if(a instanceof Error&&(a.name==="AbortError"||a.name==="TimeoutError")||n.aborted)return;a instanceof Tg?r.warn("Skipping AI smart waiting due to excessive page size - falling back to naive waiting"):r.warn({err:a},"Unexpected error occurred during AI smart waiting");let s=o.smartWaitingTimeout-(Date.now()-i);s>0&&await xe(s,n)}finally{r.debug({durationMs:Date.now()-i},"AI smart waiting complete")}}async function N8(t,e,r){let{abortSignal:n,browser:o}=r;if(o.smartWaitingTimeout<3e3){await xe(o.smartWaitingTimeout,n);return}if(!e.description)throw new L("UserConfigurationError","Cannot locate element with empty description");await J(D8(t,e,r),{milliseconds:o.smartWaitingTimeout})}async function D8(t,e,r){let{logger:n,iframeUrl:o}=e,{browser:i}=r;for(;Date.now()-t<i.smartWaitingTimeout;)if(await oo({action:async()=>k8(e,r),frameConfig:o?{type:"url",url:o}:void 0,browser:i,logger:n}))return}async function k8(t,e){let{testContext:r,logger:n,filterByViewport:o,allowNotActionableNodesOverride:i}=t,{browser:a,abortSignal:s,localCodeEvalTools:c,orgId:l,generator:u}=e,d=t.description;r&&(d=await Jr({orgId:l,s:d,context:r,localTools:c,signal:s,logger:n}));let{serializedTree:p}=await ti(a,{allowNotActionableNodesOverride:i,filterByViewport:o,abortSignal:s,logger:n});if(et(p)>L8)throw new Tg;s.throwIfAborted();let f;try{f=await a.screenshot({clearHighlights:!0,respectActiveFrame:!0,retries:2})}catch(E){throw new L("ActionFailureError",`Failed to take screenshot of page to perform smart waiting. The page may be unresponsive, or your machine might be severely resource constrained. Error: ${E instanceof Error?E.message:E}`)}let S=`data:image/jpeg;base64,${f.toString("base64")}`;s.throwIfAborted();let g=await u.getSmartWaitingDecision({browserState:p,description:d,screenshot:S},{abortSignal:s,loggerTags:ot(n)});return n.debug({result:g},"Got smart waiting result"),g.isPageReady}import{cloneDeep as oF}from"lodash-es";async function iF(t){return un().startAsyncSpan("ELEMENT_ASSERTION",async r=>F8(t,r),{name:"Element check"})}async function F8(t,e){let{command:r,timeoutMs:n,fixtures:o,disableCache:i}=t,{abortSignal:a}=o,s=()=>Bp(r.cache)?r.cache:void 0,c=s(),l=!i&&!!c?.target&&rl(c.target),u=oF(c),d=(E=!1)=>{if(c=s(),!!c)if(E){let y=jT(u,c);c.target=y.target,c.updatedAt=y.updatedAt}else{if(!u){c=void 0;return}c.target=u.target,c.updatedAt=u.updatedAt}},p=Date.now(),m=0,f,h=500,S=!1;for(;m<2||Date.now()-p<n;){m++,m>1&&await xe(h,a),a?.throwIfAborted(),c=s();let E=m===1,{result:y,elementWasFound:b}=await nF({cacheToUse:c,skipAISmartWaiting:!E,useAIIfCacheFails:!l,params:t});if(f=y,S=S||b,y.success)break;d(),h=Math.min(h*1.25,1e4)}if(!f)throw new L("InternalPlatformError",`Failed to evaluate manual element assertion in ${n}ms.`);if(a?.throwIfAborted(),!f.success){let E=s(),y=E?.target?.memory?{target:{id:-1,memory:E.target.memory}}:void 0,{result:b,elementWasFound:C}=await nF({cacheToUse:y,skipAISmartWaiting:!0,useAIIfCacheFails:!0,params:t});f=b,S=S||C,f.success||d(!0)}let g=s();return f.success&&g?.target&&!S&&(g.target=Ud(g.target),g.updatedAt=new Date),e.result={success:f.success,message:f.err?.message},f}async function nF({cacheToUse:t,skipAISmartWaiting:e,useAIIfCacheFails:r,params:n}){let{command:o,disableCache:i,fixtures:a,tracer:s,targetingWrapper:c}=n,{logger:l}=a;if(o.target&&!zi(o.target))throw new Error("Element assertion with x/y is not supported yet");let u=hL(o.assertion),d,p=!1,m=oF(t);try{let{elementInteractedDisplayString:f,result:h,thoughts:S}=await c({tracer:s,command:o,target:o.target,cache:m?.target,action:async g=>U8(g.locator,n),options:{...o,allowNotActionableNodesOverride:!0,disableCache:i,memory:m?.target?.memory,disableGlobalLocatorRedirect:!0,source:qa(o),skipAISmartWaiting:e,targetName:"target"},retriesWithAI:r?1:0});return d={success:h.success,data:h.data,err:h.err,elementInteractedDisplayString:f,thoughts:S},p=!0,h.success||(l.warn({aiThoughts:S,elementString:f,err:h.err},"Element check found an element but failed"),d={...h,thoughts:S}),{result:d,elementWasFound:p}}catch(f){if(u)return d={success:!0,thoughts:`The element described does not exist on the page: ${f.message}`,err:void 0,data:void 0},{result:d,elementWasFound:p};if(!(f instanceof L)||f.reason!="ActionFailureError")throw f;return d={success:!1,err:f,data:void 0,thoughts:void 0},l.warn({err:f},"Element check did not find an element and failed"),{result:d,elementWasFound:p}}}async function U8(t,{command:e,fixtures:r}){return await r.browser.highlight(t),await B8(t,e.assertion)}async function B8(t,e){let r=!0,n,o;switch(e.type){case"ELEMENT_CONTENT":{let a=await t.textContent()??"";if(o={elementTextContent:vt(a,500,!0)},!kd(a,e.value,e.operation,{negated:!!e.negated,ignoreCase:!1})){let s=pc(e);r=!1,n=new L("AssertionFailureError",`The content ${s} '${e.value}': ${a}`)}break}case"ELEMENT_ATTRIBUTE":{o={elementOuterHtml:vt(await t.evaluate(s=>s.cloneNode(!1).outerHTML),500,!0)};let a=null;try{a=await t.getAttribute(e.attr,{timeout:3e3})}catch(s){n=new L("AssertionFailureError",s instanceof Error?s.message:String(s)),r=!1;break}if(!kd(a,e.value,e.operation,{negated:!!e.negated,ignoreCase:!1})){let s=pc(e);r=!1,e.operation==="EXISTS"?n=new L("AssertionFailureError",`The attribute ${e.attr} ${s}`):n=new L("AssertionFailureError",`The attribute ${e.attr} ${s} '${e.value}': ${a}`)}break}case"ELEMENT_EXISTENCE":{switch(e.condition){case"VISIBLE":{r=await t.evaluate(async(s,c)=>{let l=Date.now();for(;Date.now()-l<c;){await new Promise(d=>setTimeout(d,250));let u=s.getBoundingClientRect();if(!(u.width===0||u.height===0)&&window.getComputedStyle(s).visibility!=="hidden"&&window.getComputedStyle(s).display!=="none")return!0}return!1},Nn*1e3);break}case"EDITABLE":{r=await t.isEditable({timeout:Nn*1e3});break}case"EXISTS":{r=!0;break}case"ENABLED":{r=await t.isEnabled({timeout:Nn*1e3});break}case"FOCUSED":{r=await t.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"})(e.condition)}if(r=e.negated?!r:r,!r){let a=pc(e);n=new L("AssertionFailureError",`The element ${a}`)}break}case"ELEMENT_NAME":{let a=await t.evaluate(s=>s.tagName);if(!kd(a,e.value,e.operation,{negated:!!e.negated,ignoreCase:!0})){let s=pc(e);r=!1,n=new L("AssertionFailureError",`The element tag name ${s} '${e.value}': ${a}`)}break}case"ELEMENT_STYLE":{let a=await t.evaluate((s,c)=>window.getComputedStyle(s).getPropertyValue(c),e.property);if(!kd(a,e.value,e.operation,{negated:!!e.negated,ignoreCase:!1})){let s=pc(e);r=!1,e.operation==="EXISTS"?n=new L("AssertionFailureError",`The style property ${e.property} ${s}`):n=new L("AssertionFailureError",`The style property ${e.property} ${s} '${e.value}': ${a}`)}break}default:return(a=>{throw"If Typescript complains about the line below, you missed a case or break in the switch above"})(e)}return{thoughts:void 0,success:r,data:o,err:n}}function aF(t){return t.type==="ELEMENT_EXISTENCE"&&t.negated&&t.condition==="EXISTS"}import{Jimp as z8}from"jimp";async function rp(t,e){let r=await t.screenshot(e),n=await z8.fromBuffer(r);return{buffer:r,width:Math.ceil(n.bitmap.width??0),height:Math.ceil(n.bitmap.height??0)}}import{Jimp as sF}from"jimp";import Ov from"jpeg-js";import H8 from"pixelmatch";async function lF({tracer:t,command:e,disableCache:r,browser:n,targetingWrapper:o,logger:i,screenshotStorage:a}){if(e.target&&!zi(e.target))throw new Error("Visual Diff with x/y is not supported yet");await n.waitForStability({logger:i});let s={clearHighlights:!0,hideCaret:!0},c;e.target?.elementDescriptor?c=(await o({tracer:t,command:e,target:e.target,cache:e.cache?.target,action:async P=>rp(n,{locator:P.locator,...s}),options:{...e,disableCache:r,disableGlobalLocatorRedirect:!0,memory:e.cache?.target?.memory,targetName:"target"}})).result:c=await rp(n,s);let l=await a.prepareGoldenScreenshotForComparison(i,e,c);if((c.height!==l.height||c.width!==l.width)&&i.warn({currHeight:c.height,currWidth:c.width,savedHeight:l.height,savedWidth:l.width},"Mismatched before and after visual diff screenshot sizes"),Math.abs(c.height-l.height)>10||Math.abs(c.width-l.width)>10){let M=`${c.width}x${c.height}`,P=`${l.width}x${l.height}`;return{fail:!0,thoughts:`Current screenshot (${M}) does not match saved screenshot dimensions (${P}) - did you change the size of the target or the viewport?`,beforeScreenshotOverride:l.buffer,afterScreenshotOverride:c.buffer,succeedImmediately:!1,urlAfterCommand:n.url()}}let u=await sF.fromBuffer(c.buffer),d={width:c.width,height:c.height},p=await sF.fromBuffer(l.buffer),m={width:l.width,height:l.height},f,h=d.width*d.height,S=m.width*m.height,g=Math.abs(d.height-m.height),E=Math.abs(d.width-m.width);if(h>S){let M=u.cover({w:m.width,h:m.height});c.buffer=await M.getBuffer("image/jpeg"),f="current",c.width=m.width,c.height=m.height}else if(S>h){let M=p.cover({w:d.width,h:d.height});l.buffer=await M.getBuffer("image/jpeg"),f="saved"}let y={data:Buffer.alloc(c.width*c.height*4),width:c.width,height:c.height},b=e.threshold??.1,I=H8(Ov.decode(l.buffer).data,Ov.decode(c.buffer).data,y.data,c.width,c.height,{threshold:b,diffColorAlt:[0,255,0]})/(c.width*c.height)*100,_=I>b*100,R=`Visual diff of ${I.toFixed(2)}% detected, which is ${_?"over":"under"} the threshold of ${b*100}%.`;if(f&&(R+=` The ${f} screenshot was cropped since it was taller by ${g} pixels and wider by ${E} pixels.`),_)throw new L("ActionFailureError",R);return{fail:_,thoughts:R,beforeScreenshotOverride:c.buffer,afterScreenshotOverride:Ov.encode(y,75).data,succeedImmediately:!1,urlAfterCommand:n.url()}}var G8=3e4;function j8(t){if(!t.body)return{};switch(t.body.type){case"json":return{content:t.body.content,contentType:"application/json"};case"form-urlencoded":{let e=new URLSearchParams;return Object.entries(t.body.content).forEach(([r,n])=>{e.append(r,n)}),{content:e.toString(),contentType:"application/x-www-form-urlencoded;charset=UTF-8"}}}}async function cF({command:t,logger:e,baseUrl:r,fetchImplementation:n=fetch}){let o=t.timeout??G8/1e3,i=Object.fromEntries(Object.entries(t.headers||{}).filter(([f,h])=>f&&h)),a=new URLSearchParams;Object.entries(t.params||{}).filter(([f,h])=>f&&h).forEach(([f,h])=>{a.append(f,h)});let s=a.toString(),c;if(yc(t.url)&&(c=t.url),r&&Ec(t.url,r)&&(c=new URL(t.url,r).toString()),!c)throw new L("ActionFailureError",`Invalid URL: ${t.url}`);let l=c;e.info({url:l,searchParams:s,headers:i,body:t.body,method:t.method},"Making HTTP request");let d=await J((async()=>{let f=s?`${l}?${s}`:l;try{let h=j8(t),S=new Headers(i);return h.contentType&&!S.has("Content-Type")&&S.set("Content-Type",h.contentType),await n(f,{headers:S,method:t.method,body:h.content})}catch(h){throw new Error(`Failed to make HTTP request: ${h}`,{cause:h})}})(),{milliseconds:o*1e3,fallback:()=>{throw new L("ActionFailureError",`Fetch request timed out after ${o} seconds`)}});if(!d.ok){let f;try{f=await d.text()}catch(h){f=`Failed to read response body: ${h}`}throw new L("ActionFailureError",`Fetch request failed with status ${d.status}: ${f}`)}let p={};d.headers.forEach((f,h)=>{p[h]=f});let m={status:d.status,headers:p,request:{url:d.url,method:t.method,headers:i}};if(t.body?.type==="json"&&t.body.content)try{m.request.json=JSON.parse(t.body.content)}catch{}if(d.headers.get("content-type")?.includes("json"))try{m.json=await d.json()}catch{}else d.headers.get("content-type")?.includes("text")&&(m.text=await d.text());return m}var V8=5e3;async function bg({timeout:t=Nn,...e}){let r=Date.now(),n=t*1e3,o=n+1e4,i,a=0,s=500;for(;a-r<n;){if(Date.now()-r>o){e.logger.warn("Exceeded max system timeout for page assertion, exiting...");break}e.signal?.throwIfAborted();let c=Date.now();i=await uF(e),a=Date.now();let l=a-c;if(l>1e3&&e.logger.warn({pageAssertDuration:l},"Page assertion took longer than expected"),!i.success)await xe(s,e.signal),s=Math.min(Math.floor(s*1.5),V8);else return i}return i=await uF(e),i}async function uF({assertion:t,browser:e,autoExpandIframes:r}){switch(t.type){case"CONTENT":case"CONTENT":{let o,i=!1,a;try{let s;if(r){let c=await e.evaluateFunctionInAllFrames(dF,{value:t.value,negated:!!t.negated,returnHtml:!1});i=t.negated?c.every(l=>l.evaluation):c.some(l=>l.evaluation),s=c.find(l=>l.pageHtml)?.pageHtml}else({evaluation:i,pageHtml:s}=await e.evaluateFunctionInPage(dF,{value:t.value,negated:!!t.negated,returnHtml:!0},"checking page content"));if(!i){let c=t.negated?Ei.CONTAINS:Ti.CONTAINS;a=new L("AssertionFailureError",`The page ${c} '${t.value}'.`),o=s}}catch(s){a=new L("AssertionFailureError",`Failed to evaluate page content assertion: ${s instanceof Error?s.message:`${s}`}`)}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"})(t)}}function dF({value:t,negated:e,returnHtml:r}){let n=document.body.innerHTML,o=n.includes(t)===!e;return n.length>1e4&&(n=n.slice(0,1e4)+"...TRUNCATED"),{evaluation:o,pageHtml:!o&&r?n:void 0}}var W8=3e4;async function pF({command:t,logger:e,baseUrl:r,fetchImplementation:n=fetch}){let o=t.timeout??W8/1e3,i=new AbortController,a=Object.fromEntries(Object.entries(t.headers||{}).filter(([d,p])=>d&&p));a["Content-Type"]="application/json";let s;if(yc(t.url)&&(s=t.url),r&&Ec(t.url,r)&&(s=new URL(t.url,r).toString()),!s)throw new L("ActionFailureError",`Invalid URL: ${t.url}`);let l=await J((async()=>{try{return await n(s,{headers:a,method:"POST",body:JSON.stringify({query:t.query,variables:t.variables?JSON.parse(t.variables):void 0}),signal:i.signal})}catch(d){throw new Error(`Failed to make HTTP request: ${d}`,{cause:d})}})(),{milliseconds:o*1e3});if(!l)throw new L("ActionFailureError",`GraphQL request timed out after ${o} seconds`);if(!l.ok){let d,p=await l.text();try{d=JSON.parse(p)}catch{throw new L("ActionFailureError",`GraphQL request failed with status ${l.status}: ${p}`)}throw d?.errors?.length&&d?.errors[0]?.message?new L("ActionFailureError",`GraphQL request failed with status ${l.status}: ${d.errors[0].message}`):new L("ActionFailureError",`GraphQL request failed with status ${l.status}: ${p}`)}let u={};return l.headers.forEach((d,p)=>{u[p]=d}),{status:l.status,headers:u,json:await l.json()}}var Aa=class{orgId;options;storage;localCodeEvalTools;uploadedFileStorage;visualDiffScreenshotStorage;browser;generator;executeAbortController=new AbortController;logger;executionOptionsStack=[];recordAbortController=null;registeredListeners={};recordedRequests={};constructor({browser:e,generator:r,logger:n,storage:o,orgId:i,localCodeEvalTools:a,uploadedFileStorage:s,visualDiffScreenshotStorage:c,options:l}){this.orgId=i,this.options=l,this.browser=e,this.browser.registerAbortSignal(this.executeAbortController.signal),this.storage=o,this.uploadedFileStorage=s,this.visualDiffScreenshotStorage=c,this.localCodeEvalTools=a,this.generator=r,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 withExecutionOptions(e,r){this.executionOptionsStack.push(e);try{return await r()}finally{this.executionOptionsStack.pop()}}getCurrentExecutionOptions(){return this.executionOptionsStack[this.executionOptionsStack.length-1]??{}}async evaluateAiAction({goal:e,startingScreenshot:r,history:n,disableCache:o,langfuseSessionId:i,lastError:a,logger:s=this.logger}){let[c,l]=await Promise.all([ti(this.browser,{abortSignal:this.executeAbortController.signal,skipWait:!0,skipWaitForPageLoad:!0,logger:s}),this.browser.screenshot({retries:1,clearHighlights:!0})]),u=`data:image/jpeg;base64,${l.toString("base64")}`,d=await zs({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:s,orgId:this.orgId}}),p={url:this.browser.url(),browserState:d,startingScreenshot:r,history:n,goal:e,screenshot:u,lastError:a};return await this.generator.getMultiturnAiActionEvaluation(p,{disableCache:o,abortSignal:this.executeAbortController.signal,loggerTags:{...ot(s)},langfuseSessionId:i})}async promptToCommand({goal:e,startingScreenshot:r,history:n,actionHint:o,disableCache:i,logger:a=this.logger,langfuseSessionId:s}){let c=this.browser.url(),[l,u]=await Promise.all([ti(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 zs({type:"ai-action",description:e,screenshot:d,serializedTree:l.serializedTree,tree:l.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:r,history:n,goal:e,actionHint:o,screenshot:d};try{return await this.generator.getMultiturnAiActionCommand(m,{disableCache:i,abortSignal:this.executeAbortController.signal,loggerTags:{...ot(a)},langfuseSessionId:s})}catch(f){throw new L("InternalWebAgentError",`Error generating command: ${f instanceof Error?f.message:f}`,{errOptions:{cause:f}})}}async getBrowserState(e){return ti(this.browser,e)}async locateElement(e){return await Mv({...e,aiPageFiltering:!!this.options?.aiPageFiltering},this.getControllerFixtures())}async locateElementWithSelector(e,r){return oo({action:async()=>{let n=await this.browser.resolveHardcodedCssSelector({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:r?{type:"url",url:r}:void 0,browser:this.browser,logger:this.logger})}getControllerFixtures(){return{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({tracer:e,command:r,targetNames:n,descriptions:o,caches:i,action:a,options:s,retriesWithAI:c=1}){let l=[];for(let u=0;u<o.length;u++){let d=o[u],p=await this.wrapElementTargetingCommand({tracer:e,command:r,target:d,cache:i[u],action:async m=>m,options:{...s,targetName:n[u]}});l.push(p)}try{let u=await a(...l.map(m=>m.result)),d=m=>m==="fromTarget"?"From Target":m==="toTarget"?"To Target":"Target",p=l.map((m,f)=>m.thoughts?`${d(n[f])}: ${m.thoughts}`:void 0).filter(m=>!!m).join(" -------------- ")||void 0;return{result:u,elementInteractedDisplayStrings:l.map(m=>m.elementInteractedDisplayString),thoughts:p}}catch(u){if(this.throwIfClosed(),c>0)return this.logger.warn({err:u},"Failed to execute action with multiple cached targets, retrying with AI"),this.wrapMultiElementTargetingCommand({tracer:e,command:r,targetNames:n,descriptions:o,caches:o.map(()=>{}),action:a,options:s,retriesWithAI:c-1});throw new L("ActionFailureError",u.message,{errOptions:{cause:u}})}}async wrapHardcodedCssTargetingCommandHelper({target:e,action:r,options:n,command:o}){let i=this.logger.child({commandId:o.id}),{targetName:a}=n;if(e.type!=="description")throw new L("ActionFailureError","Cannot use selector with non-description target");let s,c=Date.now(),l=Date.now();for(;Date.now()-l<this.browser.smartWaitingTimeout;){c=Date.now();try{let u=await this.browser.resolveHardcodedCssSelector({selector:e.elementDescriptor,targetName:a,logger:i});return{result:await r({locator:u.locator,originalElementLocationResult:void 0,serverSideBoundingBox:null}),elementInteractedDisplayString:u.displayString}}catch(u){if(u.name==="AbortError")throw u;s=u,i.warn({err:u},"Failed to action on hardcoded css selector"),Date.now()-c<500&&await xe(500)}}throw s}async scrollIntoViewAndResolveFinalTarget(e){let{resolutionResult:r,disableGlobalLocatorRedirect:n,logger:o}=e,i=un(),a=!n&&this.browser.userBrowserSettings.globalLocatorRedirect!==!1;(this.browser.userBrowserSettings.visualActions||a)&&await i.startAsyncSpan("SCROLL_ELEMENT_INTO_VIEW",async()=>{await this.browser.scrollIntoViewIfNeeded(r.locator)});let s;return a&&(s=await i.startAsyncSpan("LOCATOR_REDIRECT",async c=>{let{targetingResult:l,metadata:u}=await this.browser.performTargetRedirection(r,o);if(c.result=u,l&&i.storeTraceAsset)try{let d=await this.browser.screenshot({locator:l.locator,clearHighlights:!0}),p=$8();i.storeTraceAsset({snapshotId:p,data:d}),c.elementScreenshotSnapshotId=p}catch(d){o.debug({err:d},"Failed to capture element screenshot for redirect trace")}return l})),s||(s={locator:r.locator,serverSideBoundingBox:await r.locator.boundingBox({timeout:pe}),originalElementLocationResult:r.originalElementLocationResult}),s}async resolveCachedTargetForAction(e){let{cache:r,options:n,logger:o}=e,a=await un().startAsyncSpan("CACHE_RESOLUTION",async c=>{c.targetSource=r.targetSource;try{let l=await this.browser.resolveTarget(r,{allowNotActionableNodesOverride:n.allowNotActionableNodesOverride,logger:o,signal:this.executeAbortController.signal,...n.resolveTargetOptions});c.attributes.targetDisplayString=l.displayString,c.attributes.decisions=l.decisions;let u=l.decisions.find(d=>d.matched);return u&&(c.resolutionMethod=u.type),l}catch(l){throw l instanceof fn&&(c.cacheMissReason=l.cacheMissReason,c.attributes.decisions=l.decisions),l}}),s=await this.scrollIntoViewAndResolveFinalTarget({resolutionResult:a,disableGlobalLocatorRedirect:n.disableGlobalLocatorRedirect,logger:o});return await a.revalidator?.(),{resolutionResult:a,finalTarget:s}}async wrapElementTargetingCommand(e){return await oo({action:()=>this.wrapElementTargetingCommandHelper(e),frameConfig:e.options.iframeUrl?{type:"url",url:e.options.iframeUrl}:void 0,browser:this.browser,logger:this.logger})}async wrapElementTargetingCommandHelper(e){let{tracer:r,target:n,action:o,options:i,command:a,finalAttempt:s=!1,originalCache:c=e.cache}=e,{retriesWithAI:l=1}=e,{disableCache:u,useSelector:d,targetName:p}=i,m=un(),f=this.logger.child({commandId:a.id}),h=this.shouldUseMemory(),S=mF(e.cache);if((!S||u)&&!CS(n))throw new L("ActionFailureError","Cannot target element with no cached data or element descriptor");if(d)return this.wrapHardcodedCssTargetingCommandHelper(e);let g=!1,E;u&&(f.info("Cache explicitly disabled for this step"),g=!0,E="Cache explicitly disabled",S=void 0);let y=q0({cache:S,description:n.elementDescriptor,disableSecondaryCacheResolution:!!this.browser.userBrowserSettings.disableSecondaryCacheResolution,logger:f});S=y.cache,g=g||y.cacheBustedBeforeAction,!E&&y.cacheBustReason&&(E=y.cacheBustReason);let b=!0;if(!$0(S))return l--,b=!1,this.executeTargetingCommandWithAI({tracer:m,stepTracer:r,target:n,options:i,command:a,action:o,originalCache:c,logger:f,useMemory:h,cacheBustedBeforeAction:g,cacheBustReason:E});try{let{resolutionResult:C,finalTarget:I}=await this.resolveCachedTargetForAction({cache:S,options:i,logger:f}),_=await o(I);if(Wt.increment("cache_target_resolution_v2",1,["outcome:hit","platform:web",`hasRequirements:${!!S.requirements}`,`hasAdditionalElements:${!!S.additionalElements}`,`orgId:${this.orgId}`,"cliVersion:2.71.2"]),uh({cmd:a,key:p,newTarget:S,logger:f,updatedWithAI:!1}),b){let R=C.decisions.filter(M=>M.matched);if(R.length!==1)f.warn({decisions:C.decisions},"Expected exactly 1 matching method for element location, got more or less");else{let M=R[0].type;r.recordTargetAutoHeal({healType:M})}}return{result:_,elementInteractedDisplayString:C.displayString}}catch(C){this.throwIfClosed();let I=BS(C);if(I&&!s)return f.warn({err:C},"Encountered error that is retryable with cache"),this.wrapElementTargetingCommandHelper({tracer:r,command:a,target:n,action:o,cache:c,originalCache:c,retriesWithAI:l,finalAttempt:!0,options:i});if(C instanceof L&&!I)throw f.warn({err:C},"Failed to execute command with target (fatal)"),C;if(l>0&&n){f.info({err:C},"Failed to execute action with cached target, retrying with AI"),Wt.increment("cache_target_resolution_v2",1,["outcome:miss","platform:web",`hasRequirements:${!!S.requirements}`,`hasAdditionalElements:${!!S.additionalElements}`,`orgId:${this.orgId}`,"cliVersion:2.71.2",`missReason:${C instanceof fn?C.cacheMissReason:"unknown"}`]);let _;return S.memory&&kp(S.memory)&&(_=S.memory),this.wrapElementTargetingCommandHelper({tracer:r,command:a,target:n,cache:void 0,action:o,originalCache:c,retriesWithAI:l,finalAttempt:!0,options:{...i,memory:_,targetHealingInProgress:!0}})}throw new L("ActionFailureError",`Failed to execute interactive command: ${C instanceof Error?C.message:`${C}`}`,{errOptions:{cause:C}})}}async executeTargetingCommandWithAI(e){let{tracer:r,stepTracer:n,target:o,options:i,command:a,action:s,originalCache:c,logger:l,useMemory:u,cacheBustedBeforeAction:d,cacheBustReason:p}=e;l.info({description:o.elementDescriptor,targetHealingInProgress:i.targetHealingInProgress,cacheBustedBeforeAction:d,memory:i.memory,useMemory:u},"Prompting AI for an updated element location"),(d||!c)&&!this.getCurrentExecutionOptions().skipAISmartWaiting&&!i.skipAISmartWaiting?await r.startAsyncSpan("SMART_WAITING",async()=>await rF({description:o.elementDescriptor,iframeUrl:i.iframeUrl,source:i.source,logger:l,allowNotActionableNodesOverride:i.allowNotActionableNodesOverride},this.getControllerFixtures())):(d||!c)&&(i.skipAISmartWaiting?l.debug("Skipping AI smart waiting for this targeting attempt"):l.debug("Skipping AI smart waiting due to controller execution options"));let m=2;for(let f=1;f<=m;f++){let h=!1,S=this.browser.getActiveFrameConfig();try{let g;try{g=await Mv({description:o.elementDescriptor,disableCache:!!i.disableCache,iframeUrl:i.iframeUrl,source:i.source,useMemory:u,memory:u?i.memory:void 0,aiPageFiltering:!!this.options?.aiPageFiltering,allowNotActionableNodesOverride:i.allowNotActionableNodesOverride,logger:l,isAutoHeal:!!i.targetHealingInProgress,cacheBustReason:p},this.getControllerFixtures())}catch(b){if(b instanceof Sl&&b.updatedLocatorMemory){let C={id:-1,...c,memory:b.updatedLocatorMemory};uh({cmd:a,key:i.targetName,newTarget:C,logger:l,updatedWithAI:!0})}throw b}g.frameConfig&&(this.browser.setActiveFrameConfig(g.frameConfig),h=!0);let E=await this.scrollIntoViewAndResolveFinalTarget({resolutionResult:g.resolution,disableGlobalLocatorRedirect:i.disableGlobalLocatorRedirect,logger:l}),y=await s(E);return uh({cmd:a,key:i.targetName,newTarget:g.target,logger:l,updatedWithAI:!0}),i.targetHealingInProgress&&(n.recordTargetAutoHeal({healType:"AI"}),g.target.targetSource="AI_HEALED",g.target.targetUpdateTime=new Date().toUTCString(),g.target.targetUpdateLoggerTags=ot(l)),{result:y,elementInteractedDisplayString:g.resolution.displayString,thoughts:g.thoughts}}catch(g){if(h&&this.browser.setActiveFrameConfig(S),this.throwIfClosed(),f<m&&BS(g)){l.warn({err:g,aiAttempt:f},"Encountered retryable AI targeting error; retrying with AI once");continue}throw g instanceof L?g:new L("ActionFailureError",g.message)}}throw new L("ActionFailureError","Failed to execute AI targeting after retry")}async screenshotWithDimensions(e){return rp(this.browser,e)}async executePresetCommand(e,r,n,o){this.options?.slowMoMs&&await xe(this.options.slowMoMs);let i=await this.browser.getOpenPages(),a=this.browser.url(),s;try{s=await this.resolveCommandTemplateStrings(r,n)}catch(c){throw this.throwIfClosed(),new L("ActionFailureError",`Failed to substitute template strings in command: ${c.message}`,{errOptions:{cause:c}})}try{let c=await this.executePresetCommandHelper(e,r,n,o);return this.options?.autoFollowNewTabs&&await W0({beforeUrl:a,command:r,beforePages:i.map(l=>l.url),browser:this.browser,logger:this.logger}),c}catch(c){throw c.name!=="AbortError"&&this.logger.error({err:c},"Error thrown in action controller"),c}finally{rk(r,s)}}createCallbacksForBrowser(e){return{createIsolatedFolder:()=>Qb(e)}}async traceBrowserInteraction(e,r,n){return un().startAsyncSpan("BROWSER_INTERACTION",async()=>r(),{name:e,...n})}async resolveCommandTemplateStrings(e,r){return rg({obj:e,context:r,bannedKeys:["type","a11yData","thoughts","cache","code"],orgId:this.orgId,logger:this.logger,signal:this.executeAbortController.signal,localTools:this.localCodeEvalTools})}async executePresetCommandHelper(e,r,n,o){o=o||"disableCache"in r&&!!r.disableCache;let i=this.logger.child({commandId:r.id});switch(r.type){case"SUCCESS":{let a=r.condition;return a?.assertion.trim()?Eg({command:a,fixtures:this.getControllerFixtures(),useMemory:this.shouldUseMemory(),aiPageFiltering:!!this.options?.aiPageFiltering,logger:i}):{succeedImmediately:!1,urlAfterCommand:this.browser.url()}}case"AI_ASSERTION":{if(!r.assertion.trim())throw new L("ActionFailureError","Missing assertion");if(r.timeout&&r.timeout>1800)throw new L("AssertionFailureError",`AI check timeout of ${r.timeout} exceeds the maximum allowed value of 30 minutes.`);return Eg({command:r,fixtures:this.getControllerFixtures(),useMemory:this.shouldUseMemory(),aiPageFiltering:!!this.options?.aiPageFiltering,logger:i})}case"AI_EXTRACT":{if(!r.goal.trim())throw new L("ActionFailureError","Cannot perform AI extraction without goal");if(r.schema){let c=hI(r.schema);if(c)throw new L("UserConfigurationError",c)}let a=await this.browser.getCondensedHtml(),s=await this.browser.screenshot({retries:2});try{let c=await this.generator.getTextExtraction({goal:r.goal,browserState:a,returnSchema:r.schema,screenshot:`data:image/jpeg;base64,${s.toString("base64")}`},{disableCache:o,abortSignal:this.executeAbortController.signal,loggerTags:ot(i)});if(c.result==="NOT_FOUND")throw new L("ActionFailureError","No relevant data found for extraction goal on this page");if(c.thoughts?.includes("MaxGenerationLengthExceededError"))throw new L("UserConfigurationError",c.thoughts);return{thoughts:c.thoughts||void 0,data:c.result,succeedImmediately:!1,urlAfterCommand:this.browser.url()}}catch(c){let l=c.message;throw l.includes("MaxGenerationLengthExceededError")?new L("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."):l.includes("AIProviderError")&&l.includes("time")?new L("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:c}}):c}}case"NAVIGATE":if(!yc(r.url)&&!Ec(r.url,this.browser.baseUrl))throw new L("ActionFailureError",`Invalid URL provided to navigate command: ${r.url}`);await this.traceBrowserInteraction("Navigate",()=>this.browser.navigate({url:r.url,loadTimeoutMs:r.loadTimeout?r.loadTimeout*1e3:void 0}));break;case"DIALOG":this.browser.registerDialogHandler(r.action);break;case"CAPTCHA":throw new L("UserConfigurationError","Captcha solving is no longer available on Momentic");case"GO_BACK":await this.traceBrowserInteraction("Go back",()=>this.browser.goBack());break;case"GO_FORWARD":await this.traceBrowserInteraction("Go forward",()=>this.browser.goForward());break;case"SCROLL_LEFT":case"SCROLL_RIGHT":case"SCROLL_DOWN":case"SCROLL_UP":{let a,s;if(r.target&&No(r.target))await this.browser.hoverUsingVisualCoordinates(r.target.pixels);else if(r.target&&r.target.elementDescriptor.trim()){let{elementInteractedDisplayString:u,thoughts:d}=await this.wrapElementTargetingCommand({tracer:e,command:r,target:r.target,cache:r.cache?.target,action:p=>this.browser.hover(p),options:{...r,targetName:"target",disableGlobalLocatorRedirect:!0,disableCache:o}});a=u,s=d}let c=this.browser.getViewport()?.height??Ir.height,l=this.browser.getViewport()?.width??Ir.width;switch(r.type){case"SCROLL_UP":await this.traceBrowserInteraction("Scroll up",()=>this.browser.scrollVertical(-(r.deltaY??c)));break;case"SCROLL_DOWN":await this.traceBrowserInteraction("Scroll down",()=>this.browser.scrollVertical(r.deltaY??c));break;case"SCROLL_LEFT":await this.traceBrowserInteraction("Scroll left",()=>this.browser.scrollHorizontal(-(r.deltaX??l)));break;case"SCROLL_RIGHT":await this.traceBrowserInteraction("Scroll right",()=>this.browser.scrollHorizontal(r.deltaX??l));break}return{succeedImmediately:!1,urlAfterCommand:this.browser.url(),elementInteracted:a,thoughts:s}}case"WAIT_FOR_URL":{if(r.timeout&&r.timeout>1800)throw new L("UserConfigurationError",`Wait for URL timeout of ${r.timeout} exceeds the maximum allowed value of 30 minutes.`);let a=r.matcher;await this.browser.waitForUrl({beforeUrl:this.browser.url(),matcher:a},{timeout:r.timeout?r.timeout*1e3:void 0,negated:r.negated,caseInsensitive:r.caseInsensitive});break}case"WAIT":{if(r.delay>1800)throw new L("UserConfigurationError",`Wait timeout of ${r.delay} seconds exceeds the maximum allowed value of 30 minutes`);let a=r.delay*1e3;await xe(a,this.executeAbortController.signal);break}case"REFRESH":await this.traceBrowserInteraction("Refresh",()=>this.browser.refresh({loadTimeoutMs:r.loadTimeout?r.loadTimeout*1e3:void 0}));break;case"CLICK":{if(No(r.target)){let{pixels:d}=r.target;await this.traceBrowserInteraction("Click",()=>this.browser.clickUsingVisualCoordinates(d,r),{coordinates:d});break}let a=this.browser.url(),{elementInteractedDisplayString:s,result:c,thoughts:l}=await this.wrapElementTargetingCommand({tracer:e,target:r.target,command:r,cache:r.cache?.target,action:d=>this.traceBrowserInteraction("Click",()=>this.browser.click(d,this.createCallbacksForBrowser(this.orgId),r),{selector:d.locator.toString()}),options:{disableCache:o,targetName:"target",...r}}),u={urlAfterCommand:this.browser.url(),succeedImmediately:!1,elementInteracted:s,thoughts:l,data:c.downloadedFile?{downloadedFile:c.downloadedFile}:void 0};return vh(a,u.urlAfterCommand)&&(u.succeedImmediately=!0,u.succeedImmediatelyReason="URL changed"),u}case"COPY":return await this.browser.copy(r.value),{succeedImmediately:!1,data:r.value,urlAfterCommand:this.browser.url()};case"PASTE":{await this.browser.paste();break}case"DRAG":{if(No(r.fromTarget)&&No(r.toTarget)){let c=r.fromTarget.pixels,l=r.toTarget.pixels;await this.traceBrowserInteraction("Drag",()=>this.browser.dragAndDropUsingVisualCoordinates(c,l,{hoverDurationMs:r.hoverSeconds?r.hoverSeconds*1e3:void 0}),{coordinates:c});break}if(No(r.fromTarget)||No(r.toTarget))throw new Error("Drag and drop targets must be both coordinates or both descriptions");let{elementInteractedDisplayStrings:a,thoughts:s}=await this.wrapMultiElementTargetingCommand({tracer:e,command:r,targetNames:["fromTarget","toTarget"],descriptions:[r.fromTarget,r.toTarget],caches:[r.cache?.fromTarget,r.cache?.toTarget],action:(c,l)=>this.traceBrowserInteraction("Drag",()=>this.browser.dragAndDrop(c,l,{hoverDurationMs:r.hoverSeconds?r.hoverSeconds*1e3:void 0,steps:r.steps})),options:{useSelector:!!r.useSelector,disableCache:o}});return{succeedImmediately:!1,urlAfterCommand:this.browser.url(),elementInteracted:a[0],thoughts:s}}case"MOUSE_DRAG":{let a=parseInt(r.deltaX),s=parseInt(r.deltaY),c=r.steps??5;if(isNaN(a)||isNaN(s))throw new L("ActionFailureError",`Invalid pixel values passed to mouse drag command: (${r.deltaX}, ${r.deltaY})`);if(r.target&&No(r.target)){let d=r.target.pixels;await this.traceBrowserInteraction("Mouse drag",()=>this.browser.mouseDragUsingVisualCoordinates({deltaX:a,deltaY:s,steps:c,fromTarget:d}),{coordinates:d});break}let l,u;if(r.target?.elementDescriptor){let{elementInteractedDisplayString:d,thoughts:p}=await this.wrapElementTargetingCommand({tracer:e,command:r,target:r.target,cache:r.cache?.target,action:async m=>this.traceBrowserInteraction("Mouse drag",()=>this.browser.mouseDrag(a,s,c,m.locator,{force:r.force})),options:{disableCache:o,targetName:"target",...r}});l=d,u=p}else await this.traceBrowserInteraction("Mouse drag",()=>this.browser.mouseDrag(a,s,c,void 0,{force:r.force}));return{succeedImmediately:!1,urlAfterCommand:this.browser.url(),elementInteracted:l,thoughts:u}}case"SELECT_OPTION":{if(!zi(r.target))throw new Error("Select with x/y is not supported yet");let a=r.target.elementDescriptor,s=r.choice,{elementInteractedDisplayString:c,thoughts:l}=await this.wrapElementTargetingCommand({tracer:e,command:r,target:{type:"description",elementDescriptor:a},cache:r.cache?.target,action:u=>this.traceBrowserInteraction("Select option",()=>this.browser.selectOption(u,s,r.force),{value:s.type==="LABEL"?s.label:s.type==="VALUE"?s.value:s.index}),options:{...r,targetName:"target",disableCache:o,source:qa(r)}});return{succeedImmediately:!1,urlAfterCommand:this.browser.url(),elementInteracted:c,thoughts:l}}case"TAB":{let a={loadTimeoutMs:r.loadTimeout?r.loadTimeout*1e3:void 0,retry:!0};await this.browser.switchToPage(r.action,a);break}case"NEW_TAB":await this.browser.createNewTab(r.url,{loadTimeoutMs:r.loadTimeout?r.loadTimeout*1e3:void 0});break;case"COOKIE":{if(!r.value)break;let a=await this.browser.setCookie(r.value);i.debug({results:a},"Set cookies");break}case"LOCAL_STORAGE":if(!r.value||!r.key)break;await this.browser.setLocalStorage(r.key,r.value);break;case"JAVASCRIPT":{let a;try{r.environment==="BROWSER"?(a=await this.browser.evaluateCodeInPage({code:r.code,fragment:r.fragment??!1,context:n.toObjectCopy(),timeoutMs:r.timeout?r.timeout*1e3:void 0}),i.info({result:a},"Executed JavaScript in browser")):a=await Sa({orgId:this.orgId,code:r.code,fragment:!!r.fragment,context:n,timeoutMs:r.timeout?r.timeout*1e3:void 0,logger:i,localTools:this.localCodeEvalTools,signal:this.executeAbortController.signal,callbacks:{onPersistentVariableUpdates:async s=>{if(!this.options?.scratchPadId){i.warn({updates:s},"Got persistent variable updates but scratch pad is not available");return}await this.storage.savePersistentVariables?.({scratchPadId:this.options?.scratchPadId,orgId:this.orgId,updates:s,logger:i})}}})}catch(s){throw this.throwIfClosed(),new L("ActionFailureError",s instanceof Error?s.message:`${s}`,{errOptions:{cause:s}})}try{JSON.stringify(a)}catch(s){throw new L("ActionFailureError",`Return value is not serializable: ${s instanceof Error?s.message:`${s}`}`,{errOptions:{cause:s}})}return{urlAfterCommand:this.browser.url(),succeedImmediately:!1,data:a}}case"TYPE":{if(r.target&&No(r.target)){await this.browser.clickUsingVisualCoordinates(r.target.pixels,r),await this.traceBrowserInteraction("Type",()=>this.browser.type(r.value,{force:r.force,clearContent:r.clearContent,forceClearContent:r.forceClearContent,delay:r.delay,pressEnter:r.pressEnter},!0),{value:r.value});break}let a=this.browser.url(),s,c,l=mF(r.target),u=this.browser.userBrowserSettings.globalLocatorRedirect===void 0||this.browser.userBrowserSettings.globalLocatorRedirect==="always";if(l){let{elementInteractedDisplayString:p,thoughts:m}=await this.wrapElementTargetingCommand({tracer:e,command:r,target:l,cache:r.cache?.target,action:f=>this.traceBrowserInteraction("Type",()=>this.browser.typeIntoTarget(r.value,f,{force:r.force,clearContent:r.clearContent,forceClearContent:r.forceClearContent,delay:r.delay,pressEnter:r.pressEnter,relativePosition:r.relativePosition}),{value:r.value,selector:f.locator.toString()}),options:{...r,targetName:"target",disableCache:o,disableGlobalLocatorRedirect:!u,source:qa(r)}});s=p,c=m}else await this.traceBrowserInteraction("Type",()=>this.browser.type(r.value,{force:r.force,clearContent:r.clearContent,forceClearContent:r.forceClearContent,delay:r.delay,pressEnter:r.pressEnter},!0),{value:r.value});let d={urlAfterCommand:this.browser.url(),succeedImmediately:!1,elementInteracted:s,thoughts:c};return vh(a,d.urlAfterCommand)&&(d.succeedImmediately=!0,d.succeedImmediatelyReason="URL changed"),d}case"HOVER":{if(No(r.target)){let{pixels:c}=r.target;await this.traceBrowserInteraction("Hover",()=>this.browser.hoverUsingVisualCoordinates(c),{coordinates:c});break}let{elementInteractedDisplayString:a,thoughts:s}=await this.wrapElementTargetingCommand({tracer:e,command:r,target:r.target,cache:r.cache?.target,action:c=>this.traceBrowserInteraction("Hover",()=>this.browser.hover(c),{selector:c.locator.toString()}),options:{...r,targetName:"target",disableCache:o}});return{succeedImmediately:!1,urlAfterCommand:this.browser.url(),elementInteracted:a,thoughts:s}}case"FOCUS":{if(!zi(r.target))throw new Error("Focus with x/y is not supported yet");let{elementInteractedDisplayString:a,thoughts:s}=await this.wrapElementTargetingCommand({tracer:e,command:r,target:r.target,cache:r.cache?.target,action:c=>this.browser.focus(c),options:{...r,targetName:"target",disableCache:o}});return{succeedImmediately:!1,urlAfterCommand:this.browser.url(),elementInteracted:a,thoughts:s}}case"BLUR":{if(r.target&&!zi(r.target))throw new Error("Blur with x/y is not supported yet");if(!r.target||!r.target.elementDescriptor)return await this.browser.blur(null),{succeedImmediately:!1,urlAfterCommand:this.browser.url()};let{elementInteractedDisplayString:a,thoughts:s}=await this.wrapElementTargetingCommand({tracer:e,target:r.target,command:r,cache:r.cache?.target,action:c=>this.browser.blur(c),options:{...r,targetName:"target",disableCache:o}});return{succeedImmediately:!1,urlAfterCommand:this.browser.url(),elementInteracted:a,thoughts:s}}case"PRESS":{let a=this.browser.url();await this.traceBrowserInteraction("Press key",()=>this.browser.press(r.value,{repeat:r.repeat,convertMeta:r.convertMeta??!0,delayMs:r.delayMs}),{value:r.value});let s={urlAfterCommand:this.browser.url(),succeedImmediately:!1};return vh(a,s.urlAfterCommand)&&(s.succeedImmediately=!0,s.succeedImmediatelyReason="URL changed"),s}case"KEY_DOWN":return await this.browser.keyDown(r.value,{convertMeta:r.convertMeta??!0}),{urlAfterCommand:this.browser.url(),succeedImmediately:!1};case"KEY_UP":return await this.browser.keyUp(r.value,{convertMeta:r.convertMeta??!0}),{urlAfterCommand:this.browser.url(),succeedImmediately:!1};case"REQUEST":{let a=new K8,s=q8(fetch,a),c;try{c=new URL(r.url).hostname}catch{}let l=await cF({command:r,baseUrl:this.browser.baseUrl,logger:i,fetchImplementation:s});return{data:su.parse({...l,cookies:hx(a,c)}),succeedImmediately:!1,urlAfterCommand:this.browser.url()}}case"GRAPHQL_REQUEST":return{data:await pF({command:r,baseUrl:this.browser.baseUrl,logger:i}),succeedImmediately:!1,urlAfterCommand:this.browser.url()};case"VISUAL_DIFF":return lF({tracer:e,command:r,disableCache:o,browser:this.browser,logger:i,screenshotStorage:this.visualDiffScreenshotStorage,targetingWrapper:a=>this.wrapElementTargetingCommand(a)});case"FILE_UPLOAD":{let a,s;if(r.fileSource.type==="URL"?(s=r.fileSource.url,a=await Tk({uri:r.fileSource.url,logger:i,orgId:this.orgId})):r.fileSource.type==="USER_FILE"&&(s=r.fileSource.name,a=await this.uploadedFileStorage?.getFileForUpload(r.fileSource.name,this.orgId)),!a)throw new L("UserConfigurationError",`Attempted to use non-existent file for upload step: ${s}`);await this.browser.setFileChooserHandler({...a,filename:r.filename});break}case"AUTH_SAVE":return{data:await this.browser.saveAuthState(),succeedImmediately:!1,urlAfterCommand:this.browser.url()};case"AUTH_LOAD":{let a;if(!r.storageState.trim())a=void 0;else if(a=await Sa({orgId:this.orgId,code:r.storageState,fragment:!1,context:n,logger:i,localTools:this.localCodeEvalTools,signal:this.executeAbortController.signal}),typeof a!="object")throw new L("ActionFailureError",`Credentials must evaluate to an object (received ${typeof a} instead)`);let s;try{s=wm.optional().parse(a)}catch(c){throw new L("ActionFailureError",`Credentials provided do not follow the required format: ${c}`)}await this.browser.loadAuthState(s);break}case"ELEMENT_CHECK":{let a=(r.timeout??Nn)*1e3,s=this.generator.getAgentConfig()?.assertion;if(aF(r.assertion)&&!r.useSelector&&r.target.type==="description"&&s&&s!=="v1"){let l={id:r.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: ${r.target.elementDescriptor}`,iframeUrl:r.iframeUrl,timeout:r.timeout,source:"NEGATED_CHECK",cache:r.cache&&"memory"in r.cache?{memory:r.cache?.memory}:void 0};try{let u=await Eg({command:l,logger:i,aiPageFiltering:!!this.options?.aiPageFiltering,fixtures:this.getControllerFixtures(),useMemory:this.shouldUseMemory()});return{succeedImmediately:!1,thoughts:`The element described does not exist on the page: ${u.thoughts}`,urlAfterCommand:this.browser.url(),afterScreenshotOverride:u.afterScreenshotOverride}}finally{l.cache?.memory&&Bd(r,l.cache?.memory.traces,i)}}let c=await iF({command:r,tracer:e,timeoutMs:a,targetingWrapper:l=>this.wrapElementTargetingCommand(l),fixtures:this.getControllerFixtures(),disableCache:o});return{fail:!c.success,data:c.data,elementInteracted:c.elementInteractedDisplayString,thoughts:c.err?.message??c.thoughts??`Element assertion ${c.success?"succeeded":"failed"}.`,succeedImmediately:!1,urlAfterCommand:this.browser.url()}}case"PAGE_CHECK":{let a=await oo({action:async()=>bg({assertion:r.assertion,browser:this.browser,logger:i,timeout:r.timeout,signal:this.executeAbortController.signal,autoExpandIframes:!!this.browser.userBrowserSettings.autoExpandIframes}),frameConfig:r.iframeUrl?{type:"url",url:r.iframeUrl}:void 0,browser:this.browser,logger:i});return{fail:!a.success,data:a.data,thoughts:a.success?"Page assertion passed.":a.err?.message??`Page assertion still failing after ${r.timeout} seconds.`,urlAfterCommand:this.browser.url(),succeedImmediately:!1}}case"REGISTER_REQUEST_LISTENER":{let a=new Ta(r.requestMatcher),s=this.browser.registerRequestListener(a);return this.registeredListeners[r.key]=s.then(async c=>await nv(c)).catch(c=>{i.error({err:c},"Failed to get request listener response")}),{succeedImmediately:!1,urlAfterCommand:this.browser.url()}}case"AWAIT_LISTENER":{let a=this.registeredListeners[r.key];if(!a)throw new L("ActionFailureError",`No listener registered with key: ${r.key}`);let s=r.timeout??10;return{data:await J(a,{milliseconds:s*1e3,message:`Request listener timed out after ${s} seconds`}),succeedImmediately:!1,urlAfterCommand:this.browser.url()}}case"RECORD_REQUESTS":{let a=new Ta(r.requestMatcher);return this.recordedRequests[r.key]={},this.browser.registerRequestRecorder(r.key,{matches:s=>a.matches({url:s.request.url,method:s.request.method}),onRequestStart:(s,c)=>{this.recordedRequests[r.key][s]=sg(c)},onRequestComplete:(s,c)=>{this.recordedRequests[r.key]?.[s]&&(this.recordedRequests[r.key][s]=sg(c))}}),{succeedImmediately:!1,urlAfterCommand:this.browser.url()}}case"GET_RECORDED_REQUESTS":{let a=this.recordedRequests[r.key];if(!a)throw new L("ActionFailureError",`No recorder registered with key: ${r.key}`);return delete this.recordedRequests[r.key],{data:Object.values(a),succeedImmediately:!1,urlAfterCommand:this.browser.url()}}case"SET_HEADER":{let a;return r.requestMatcher&&(a=new Ta(r.requestMatcher)),this.browser.setHeader(r.name,r.value,a),{succeedImmediately:!1,urlAfterCommand:this.browser.url()}}case"MOCK_ROUTE":return{data:{key:this.browser.registerMock(r.key,new Ta(r.requestMatcher),async(s,c)=>{let l=await Sa({orgId:this.orgId,code:r.responseGenerator,fragment:!1,context:n,timeoutMs:void 0,logger:i,localTools:this.localCodeEvalTools,mock:{request:s,response:c},disallowVariableUpdates:!0,responseSerialization:"RESPONSE"}),u=Gx.parse(l);return new Response(u.body,{status:u.status,headers:u.headers})},r.fetchOriginalResponse??!1)},succeedImmediately:!1,urlAfterCommand:this.browser.url()};case"REMOVE_ROUTE_MOCK":return this.browser.removeMock(r.key),{succeedImmediately:!1,urlAfterCommand:this.browser.url()};case"OFFLINE_MODE":return await this.browser.setOfflineMode(r.enable),{succeedImmediately:!1,urlAfterCommand:this.browser.url()};default:return(s=>{throw"If Typescript complains about the line below, you missed a case or break in the switch above"})(r)}return{succeedImmediately:!1,urlAfterCommand:this.browser.url()}}async getReverseMappedDescription({browserState:e,targetId:r,disableCache:n,screenshot:o}){return(await this.generator.getReverseMappedDescription({browserState:e,target:r,screenshot:o},{disableCache:n,abortSignal:this.executeAbortController.signal,loggerTags:ot(this.logger)})).phrase}async stopRecordMode(){this.recordAbortController?.abort(),await this.browser.clearAllCdpHighlights()}async startRecordMode({params:e,abortController:r,isClickToRecord:n}){this.recordAbortController=r;let o=new mg({signal:r.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:ot(this.logger)})}async getFailureRecoveryPlan(e,r){return this.generator.getFailureRecoveryPlan(e,{disableCache:!0,abortSignal:this.executeAbortController.signal,loggerTags:ot(r??this.logger)})}};var Lv=async t=>{let{step:e,resolvedInputs:r}=t.moduleParams,{logger:n,context:o,storage:i,codeEvalTools:a,controller:s}=t.fixtures,c=s.browser,{orgId:l,runId:u}=t.inputs,d=s.executeAbortController.signal;Object.keys(r).length>0&&(o.setInputs(r),n.info(Gd({json:{inputs:r,moduleId:e.moduleId},maxJsonStringSize:1e3}),"Set module inputs"));let p,m=!1,f,h;if(e.cacheConfig||e.defaultCacheAllInvocations){let S=e.cacheConfig?.cacheKey||e.defaultCacheKey||"",g=await Jr({orgId:l,s:S,context:o,logger:n,localTools:a,signal:d});h={orgId:l,cacheKeys:[g,...Object.entries(r).map(([y,b])=>`${y}:${b}`)]},n.info({original:S,keyParams:h},"Module cache key params");let E=Date.now();for(;Date.now()-E<E_;){d?.throwIfAborted();let y=await i.getCacheResult(h);if(y){n.info({cacheResult:vt(y,1e3,!0)},"Got result from module execution cache"),p=vg(e,r,"SUCCESS"),p.message="Used cached module result.",p.data=JSON.parse(y),m=!0;break}else n.info({cacheKey:S,keyParams:h},"No cache result found, continuing with lock acquisition");let b=await i.acquireCacheLock({keyParams:h,clientMetadata:`hostName:${Y8()};runId:${u}`},d);if(b.acquired){f=b.keyPrefix,n.info({cacheKeyPrefixIfLockAcquired:f,cacheKey:S,keyParams:h},"Acquired cache lock and proceeding with module execution");break}else n.debug({cacheKeyPrefixIfLockAcquired:f,cacheKey:S,keyParams:h},"Failed to acquire cache lock, retrying...");await xe(2500+Math.random()*1e4,d)}}try{if(!p)p=await X8(t);else if(e.autoAuth){let S=wm.safeParse(p.data);if(!S.success)throw new L("UserConfigurationError",`Cached authentication module result is not a valid storage state: ${S.error.message}`);n.debug("Automatically loading auth state after cached module result"),await c.loadAuthState(S.data);let g=!1,E=e.advanced?.cacheInvalidation;if(E&&E.type==="PAGE_CHECK"){let y={type:"CONTENT",value:E.substring},b=await bg({timeout:Nn,assertion:y,browser:c,logger:n,signal:d,autoExpandIframes:!!c.userBrowserSettings.autoExpandIframes});b.success?n.debug({invalResult:b},"Cached result still valid after page check, continuing..."):(n.info({invalResult:b},"Invalidating cached result due to page check failure"),g=!0)}if(h&&g)return await i.deleteCacheResult(h),Lv(t)}}finally{try{f!==void 0&&!m&&p?.status==="SUCCESS"&&await J8({step:e,result:p,browser:s.browser,cacheKeyPrefix:f,logger:n,storage:i})}finally{f!==void 0&&await i.releaseCacheLock(f)}}return p},X8=async t=>{let{currentParentIdChain:e}=t,{step:r,tracer:n}=t.moduleParams,o=vg(r,t.moduleParams.resolvedInputs,"SUCCESS"),i=await n.startSubSteps(),{status:a,results:s}=await t.executeStepList({...t,listParams:{steps:r.steps,containerName:`module ('${r.name}')`,tracer:i,currentParentIdChain:e}});return o.results=s,o.status=a,o.finishedAt=new Date,to({asyncTasks:t.work.asyncTasks,nestedResults:s,result:o,logger:t.fixtures.logger}),o};function vg(t,e,r){let n={};return Object.entries(e).forEach(([i,a])=>{n[i]=JSON.stringify(a)}),{type:"MODULE",id:t.id,moduleId:t.moduleId,moduleName:t.name,startedAt:new Date,cacheConfig:t.cacheConfig,inputs:n,results:[],finishedAt:new Date,status:r}}async function fF({orgId:t,step:e,context:r,logger:n,codeEvalTools:o,signal:i}){let a={};try{for(let s of e.parameters??[]){let c=e.inputs?.[s]??e.defaultParameters?.[s];if(!c){n.warn(`No value or default found for parameter '${s}' that is required by module '${e.name}'`);continue}a[s]=await Sa({orgId:t,code:c,fragment:!0,context:r,logger:n,localTools:o,signal:i})}return a}catch(s){throw i?.throwIfAborted(),new L("UserConfigurationError",`Failed to evaluate module inputs: ${s}`)}}async function J8({step:t,result:e,browser:r,cacheKeyPrefix:n,logger:o,storage:i}){let a=t.cacheConfig?.cacheExpiryMs;(!a||a===uI)&&(a=t.defaultCacheTtl??dI);let s;t.autoAuth?s=JSON.stringify(await r.saveAuthState()):e.data!==void 0?s=JSON.stringify(e.data):s='""',o.debug({cacheKeyPrefix:n,ttlMs:a,truncatedCacheResultJson:Gd({json:s,maxJsonStringSize:1e4})},"Setting module cache result"),await i.setCacheResult({result:s,keyPrefix:n,ttlMs:a})}async function Hs(t,e,r){return Q8(t,e,r)}async function Q8(t,e,r){let n=new Date;try{return r.throwIfAborted(),await e()}catch(o){let i=new Date,a="FAILED",s;if(r.aborted||o instanceof DOMException&&o.name==="AbortError"?(s="Step aborted by user.",a="CANCELLED"):o instanceof L?s=`${o}`:s=`An unexpected error occurred: ${o.message}`,t.type==="RESOLVED_MODULE"){let c=vg(t,{},"FAILED");return c.message=s,c.startedAt=n,c.finishedAt=i,c}return{...Th(t),startedAt:n,finishedAt:i,status:a,data:null,message:s,results:[]}}}async function _o(t,e){let r=!1;try{return t&&!t.state.failureRecoveryDisabled&&(t.state.failureRecoveryDisabled=!0,r=!0),await e()}finally{t&&r&&(t.state.failureRecoveryDisabled=void 0)}}import{cloneDeep as x9}from"lodash-es";import{randomUUID as hF}from"crypto";import{diff as Z8}from"deep-object-diff";import{cloneDeep as gF}from"lodash-es";var Ag=async t=>{let{step:e,tracer:r}=t.presetParams,{logger:n,controller:o,context:i}=t.fixtures,{collectDebugData:a}=t.options,{testMetadata:s}=t.inputs,c=e.command.type,l=n.child({commandType:c,stepId:e.id,commandId:e.command.id}),u="cache"in e.command&&e.command.cache?gF(e.command.cache):{},d=o.browser.url(),p=new Date,m,f=hF(),h=hF();if(a)try{if(m=await o.browser.screenshot({retries:1,clearHighlights:!0,quality:75}),!o.browser.userBrowserSettings.disableHtmlSnapshots){let y=await o.browser.getRawCondensedHtml();r.attachBeforeHtmlSnapshot({logger:l,snapshotId:f,html:y})}}catch(y){l.debug({err:y},"Failed to take before screenshot, continuing...")}let S,g,E;try{let y=await o.executePresetCommand(r,e.command,i,s?.advanced.disableAICaching??!1);y.beforeScreenshotOverride&&(m=y.beforeScreenshotOverride),E=y.afterScreenshotOverride;let b=new Date,C=o.browser.url();g={beforeUrl:d,afterUrl:C,startedAt:p,finishedAt:b,viewport:o.browser.getViewport(),status:y.fail?"FAILED":"SUCCESS",elementInteracted:y.elementInteracted},S={...e,message:y.thoughts??"Successfully executed preset action.",beforeUrl:d,afterUrl:C,finishedAt:b,startedAt:p,status:y.fail?"FAILED":"SUCCESS",data:y.data,results:[g]},"assertion"in e.command&&(S.message=y.thoughts||"Assertion passed.")}catch(y){l.error({message:y.message,stack:y.stack},`Failed executing preset step ${bi(e.command)}`);let b=o.browser.url(),C=new Date,I=y instanceof Error?y.message:`${y}`;g={beforeUrl:d,afterUrl:b,startedAt:p,finishedAt:C,viewport:o.browser.getViewport(),status:y instanceof DOMException&&y.name==="AbortError"?"CANCELLED":"FAILED",message:I},S={...e,startedAt:p,finishedAt:C,beforeUrl:d,afterUrl:b,status:y instanceof DOMException&&y.name==="AbortError"?"CANCELLED":"FAILED",message:I,failureReason:y instanceof L?y.reason:void 0,results:[g]}}finally{let y="cache"in e.command&&e.command.cache?gF(e.command.cache):{},b=Z8(u,y);b&&Object.keys(b).length>0&&l.info({diffs:Im(b)},"Updated cache")}if(a)try{if(E||(E=await o.browser.screenshot({retries:1,quality:75})),!o.browser.userBrowserSettings.disableHtmlSnapshots){let y=await o.browser.getRawCondensedHtml();r.attachAfterHtmlSnapshot({logger:l,snapshotId:h,html:y})}}catch(y){l.debug({err:y},"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 g.beforeSnapshot=f,S.beforeSnapshot=f,g.afterSnapshot=h,S.afterSnapshot=h,m&&r.attachBeforeScreenshot({snapshotId:f,screenshot:m}),E&&r.attachAfterScreenshot({snapshotId:h,screenshot:E}),S};async function e9(t,e,r){let{tracer:n}=t.conditionalParams,{logger:o,controller:i}=t.fixtures,a=e.assertion.command;a.type==="AI_ASSERTION"&&(a.source="CONDITIONAL_CHECK");try{let s=await _o(t.work,()=>Ag({...t,presetParams:{tracer:n,step:e.assertion}})),c=a.type;switch(c){case"AI_ASSERTION":case"ELEMENT_CHECK":case"PAGE_CHECK":return s.status==="SUCCESS"?{type:"passed",conditionResult:s,steps:e.steps}:(o.info(s.message,`${a.type} condition ${r} resolved to false`),{type:"failed",conditionResult:s});case"JAVASCRIPT":{if(s.status==="FAILED")return{type:"execution_error",conditionResult:s};let l=!!s.data;return s.status=l?"SUCCESS":"FAILED",s.message=l?`JavaScript condition evaluated to true (${JSON.stringify(s.data)})`:`JavaScript condition evaluated to false (${JSON.stringify(s.data)})`,o.info({returnValue:s.data,conditionPassed:l},`JavaScript condition ${r} evaluated`),l?{type:"passed",conditionResult:s,steps:e.steps}:{type:"failed",conditionResult:s}}default:return(u=>{throw new Error(`Unsupported conditional command type: ${u}`)})(c)}}catch(s){o.error({err:s},`Condition ${r} failed with error`);let c=s instanceof Error?s.message:"Unknown error during condition evaluation";return{type:"execution_error",conditionResult:{...e.assertion,status:"FAILED",message:c,startedAt:new Date,finishedAt:new Date,results:[]}}}finally{a.type==="AI_ASSERTION"&&delete a.source,i.throwIfClosed()}}function t9(t,e,r,n){let o=n.slice(r.length);for(let i=0;i<t.blocks.length;i++){let a=t.blocks[i],{result:s}=Ts(a.steps,e,o);if(s)return i}return-1}async function SF(t){let{currentParentIdChain:e}=t,{step:r}=t.conditionalParams,{logger:n}=t.fixtures,{fromStep:o}=t.inputs,i=new Date,a=Th(r),s=!!o&&Fd(e,o.parentStepIdChain),c=r.elseSteps,l=!0,u=[],d,p=!1;if(s&&o){let g=t9(r,o.fromStepId,e,o.parentStepIdChain);g>=0&&(c=r.blocks[g].steps,l=!1,p=!0,n.info(`Skipping conditional assertion (execution starts from step within block ${g}), running ${c.length} steps`))}if(!p)for(let g=0;g<r.blocks.length;g++){n.info(`Evaluating condition ${g} in conditional step`);let E=r.blocks[g],y=await e9(t,E,g);if(u.push(y.conditionResult),d=y.conditionResult,y.type==="execution_error"){let b={...a,assertionResult:y.conditionResult,status:"FAILED",startedAt:i,finishedAt:new Date,message:y.conditionResult.message,results:[]};return to({asyncTasks:t.work.asyncTasks,nestedResults:u,result:b,logger:n}),b}if(y.type==="passed"){n.info(`Condition ${g} resolved to true, executing the corresponding ${y.steps.length} steps`),l=!1,c=y.steps;break}}if(c)l&&n.info("No conditions resolved to true, executing the else block steps");else{n.warn("No conditions resolved to true and no else block was provided, causing the entire conditional step to be skipped");let g={...a,assertionResult:d,status:"SUCCESS",startedAt:i,data:u[u.length-1]?.data,message:u[u.length-1]?.message,results:[],finishedAt:new Date};return to({asyncTasks:t.work.asyncTasks,nestedResults:[...u],result:g,logger:n}),g}n.info(`Executing ${c.length} steps in the selected conditional block`);let m=await t.conditionalParams.tracer.startSubSteps(),f=await t.executeStepList({...t,listParams:{steps:c,containerName:"conditional block",tracer:m,currentParentIdChain:e}}),S={...a,assertionResult:d,...f,startedAt:i,finishedAt:new Date};return to({asyncTasks:t.work.asyncTasks,nestedResults:[...u,...f.results],result:S,logger:n}),S}import{randomUUID as yF}from"crypto";var EF=async t=>{let{tracer:e}=t.aiStepParams,{controller:r}=t.fixtures;await r.browser.waitForStability();let n=await r.browser.screenshot({}),o=await r9(t);o.finishedAt=new Date,to({asyncTasks:t.work.asyncTasks,result:o,nestedResults:o.results,logger:t.fixtures.logger});let i=await r.browser.screenshot({}),a=yF();o.beforeSnapshot=a,e.attachBeforeScreenshot({snapshotId:a,screenshot:n});let s=yF();return o.afterSnapshot=s,e.attachAfterScreenshot({snapshotId:s,screenshot:i}),o},r9=async t=>{let{currentParentIdChain:e}=t,{step:r,tracer:n}=t.aiStepParams,{controller:o,context:i,logger:a}=t.fixtures,s={...r,startedAt:new Date,beforeTestContext:i.toRedactedDisplayCopy(),finishedAt:new Date,results:[],status:"SUCCESS"};if(!("steps"in r&&r.steps&&r.steps.length>0&&r.steps[r.steps.length-1]?.command.type==="SUCCESS"))throw new L("UserConfigurationError","AI action has been fully deprecated. Please delete this step and transition to Dynamic AI Action.");try{let l=await n.startSubSteps(),{status:u}=await t.executeStepList({...t,listParams:{steps:r.steps,containerName:"AI action",results:s.results,tracer:l,currentParentIdChain:e}});return s.finishedAt=new Date,s.status=u,s}catch(l){a.warn({err:l},"Failed executing saved deprecated AI action steps");let u=o.executeAbortController.signal.aborted;s.message=l instanceof Error?l.message:`${l}`,s.status=u?"CANCELLED":"FAILED"}return s};import{randomUUID as Fv}from"crypto";var TF=t=>{throw new Error(`Exhaustive check failed for value: ${t}`)};import{streamText as f9}from"ai";var Cg=class{controller;logger;rootStep;subStepIndex=0;callbacks;results=[];constructor(e){this.controller=e.controller,this.logger=e.logger,this.rootStep=e.rootStep,this.callbacks=e.callbacks}finalState=void 0;async createAndExecuteStep(e){this.callbacks.onAiActionEvent?.({type:"SUBSTEP_CREATED",rootStep:this.rootStep,step:e});let r=this.subStepIndex++,n=await this.callbacks.executeStep(e,r);return this.results.push(n),n}recordGenericToolCall(e){this.callbacks.onAiActionEvent?.({type:"GENERIC_TOOL_CALLED",toolName:e,rootStep:this.rootStep})}};import{hasToolCall as d9,stepCountIs as p9}from"ai";import bF from"dedent";var o9=bF`
|
|
4612
4613
|
You cannot interact with the user directly. If you feel like you need to ask the user for clarification, or you are stuck, call the "finish" tool with success=false. Never output text without calling a tool.
|
|
4613
4614
|
`,vF=t=>bF`
|
|
4614
4615
|
<background>
|
|
@@ -5264,10 +5265,10 @@ with this test we are editing:
|
|
|
5264
5265
|
to pick which of these modules are relevant:
|
|
5265
5266
|
|
|
5266
5267
|
`;let h=qZ(p);f+=h;let S=HZ({schema:eA,model:m("claude-sonnet-4-5-20250929"),system:$Z,messages:[{role:"user",content:f}]}),g=[];for await(let I of S.textStream)g.push(I);let E=g.join(""),y;try{let I=JSON.parse(E);y=eA.parse(I)}catch(I){i.error({rawResponse:E,parseError:I},"Failed to parse AI response as JSON"),r.addError(`Failed to parse AI response: ${Yt(I)}. Raw response: ${E}`);return}let b=new Set(p.map(I=>I.moduleId)),C=y.recommendations.filter(I=>b.has(I.moduleId)?!0:(i.warn({moduleId:I.moduleId,moduleName:I.moduleName},"AI recommended a module that doesn't exist"),!1));r.addPartFromText(JSON.stringify({recommendations:C,totalModulesAnalyzed:p.length},null,2))}catch(u){i.error({err:u},"Error in module recommendation"),r.addError(`Failed to recommend modules: ${Yt(u)}`)}}}),kg=[YZ,jZ,VZ];var FU=Zt({schema:{name:ls,description:"Get the initial data for the agent: project root, cwd, and the step schema. Always call this first before performing any other momentic actions.",inputSchema:{}},handle:async(t,e,r)=>{let n=t.project.rootDir,o=process.cwd(),i=Mg(),a=["## Project context","",`- **projectRoot**: \`${n}\``,`- **cwd**: \`${o}\``,"","## Step schema","",i].join(`
|
|
5267
|
-
`);r.addPartFromText(a)}});import{z as Fg}from"zod";var UU=Zt({schema:{name:RI,description:"Get the current browser state for a granular session. Defaults: screenshot on, browser snapshot off. The browser snapshot includes the URL, accessibility tree, and other context. Ask for it (returnBrowserState: true) when you need it for locator resolution or richer page structure\u2014e.g. when screenshot-only output is insufficient.",inputSchema:{sessionId:Fg.string().describe("The session id to query."),returnBrowserState:Fg.boolean().default(!1).describe("Include the serialized browser snapshot. Default false. Set to true when you need the browser snapshot for element targeting or page structure."),returnScreenshot:Fg.boolean().default(!0).describe("Include a screenshot. Default true. Set to false if you already have a screenshot of the present state and don't need a new one. EX: you just previewed a step and see that the page is too complicated and need the browser snapshot.")}},handle:async(t,e,r)=>{let n=Vs(r,e.sessionId);if(!n)return;n.controller.setOpen();let o=await Jv({browser:n.controller.browser,supportsFileOutput:t.supportsFileOutput,returnBrowserState:e.returnBrowserState,returnScreenshot:e.returnScreenshot});r.addContentParts(o)}}),BU=Zt({schema:{name:wI,description:"Get the current environment variables for a session.",inputSchema:{sessionId:Fg.string()}},handle:async(t,e,r)=>{let n=Vs(r,e.sessionId);if(!n)return;let o=await io({testContext:n.context,supportsFileOutput:t.supportsFileOutput});r.addContentParts(o)}});import{z as Fc}from"zod";var zU=Zt({schema:{name:AI,description:"Start a granular browser session for a specific test. Requires a testId. Returns session metadata (sessionId, testId, testFileAbsolutePath, viewport, etc.). Use testFileAbsolutePath to read the test file for step IDs when calling tools that require step IDs.",inputSchema:{testId:Fc.string().describe("The test id to target when starting a session."),envName:Fc.string().optional().describe("Optional environment override (matches CLI --env behavior). Defaults to the test's default env when omitted."),projectConfigPath:Fc.string().optional().describe("Optional path to a momentic.config.yaml file (matches CLI --config)."),projectNameFilter:Fc.string().optional().describe("Optional project name filter for workspace configs (matches CLI --filter)."),headfulBrowser:Fc.boolean().optional().describe("Whether to launch a headful browser for the session. When omitted, uses the MCP server default if configured.")}},handle:async(t,e,r)=>{let{logger:n}=t,o;try{o=await oi.startSession({logger:n,testId:e.testId,idleTimeoutMs:t.sessionIdleTimeoutMs,envName:e.envName,projectConfigPath:e.projectConfigPath??t.project.configFilePath,projectNameFilter:e.projectNameFilter,headfulOverride:e.headfulBrowser??t.headfulBrowserDefault??!0,customHeaders:t.customHeaders,devicePixelRatio:t.devicePixelRatio,skipExitOnError:!0})}catch(l){r.addError(Yt(l));return}let{session:i,baseUrl:a,envName:s}=o,c=i.controller.browser.getViewport();r.addPartFromText(JSON.stringify({sessionId:i.sessionId,testId:i.testId,testFileAbsolutePath:i.testFileAbsolutePath,createdAt:i.createdAt,expiresAt:i.lastAccessedAt+i.idleTimeoutMs,idleTimeoutMinutes:i.idleTimeoutMs/(60*1e3),envName:s,baseUrl:a,viewport:c},null,2));try{r.addContentParts(await Fr({browser:i.controller.browser,supportsFileOutput:t.supportsFileOutput}))}catch(l){n.warn({sessionId:i.sessionId,err:l},"Session started but initial screenshot capture failed"),r.addPartFromText(JSON.stringify({warning:"Session started successfully, but initial screenshot capture failed.",screenshotError:Yt(l)},null,2))}}}),HU=Zt({schema:{name:CI,description:"Kill a granular browser session by sessionId. Returns available session ids if the target is missing.",inputSchema:{sessionId:Fc.string().describe("The session id to terminate.")}},handle:async(t,e,r)=>{try{if(!await oi.killSession(e.sessionId,"explicit kill")){r.addError(JSON.stringify({message:`No active session found for id '${e.sessionId}'.`,availableSessionIds:oi.listSessionIds()},null,2));return}r.addPartFromText(JSON.stringify({sessionId:e.sessionId,killed:!0},null,2))}catch(n){r.addError(String(n))}}});import{z as ao}from"zod";import GU from"path";import{v4 as XZ}from"uuid";async function cp({project:t,input:e}){try{go(e.name)}catch(l){throw new or(`${l} when validating the test entity name`)}if(!e.baseUrl&&!e.environment)throw new or("Either 'baseUrl' or 'environment' must be provided when creating a test.");let r=await fe(t);if(Object.values(r.tests).find(l=>l.name===e.name))throw new or(`A test with the name "${e.name}" already exists. Please use a different name.`);let i={id:XZ(),name:e.name,description:e.description,baseUrl:e.baseUrl,schemaVersion:De,advanced:{browserType:e.browserType??"Chromium",viewport:e.viewport??Ir},retries:1,steps:[]};e.environment&&(i.envs=[{name:e.environment,default:!0}]);let a=GU.join(t.rootDir,...e.pathSegments||[]),s=await LN({test:i,name:e.name,folder:a});return{...i,relativeFilePath:GU.relative(t.rootDir,s)}}import{randomUUID as QZ}from"crypto";import{cloneDeep as ZZ}from"lodash-es";import{randomUUID as JZ}from"crypto";var Uc=async({step:t,controller:e,executionOptions:r,storage:n,codeEvalTools:o,logger:i,socket:a,testContext:s,orgId:c})=>{let{results:l}=await tA({steps:[t],controller:e,executionOptions:r,storage:n,codeEvalTools:o,logger:i,socket:a,testContext:s,orgId:c});return l[0]},tA=async({steps:t,fromStep:e,toStep:r,tracer:n,controller:o,executionOptions:i,storage:a,codeEvalTools:s,logger:c,socket:l,testContext:u,orgId:d})=>{let p={controller:o,storage:a,codeEvalTools:s,logger:c,context:u,usageTracker:new Dl},m=n??(l?new Oi({orgId:d,parentStep:null,parentTracer:null,socket:l}):new sd);o.setOpen();let f={results:[],asyncTasks:[],state:{autoHealingDisabled:!0,failureRecoveryDisabled:!0,failureRecoveryAttempts:0},...e&&{fastForwardingToStep:!0}},h=()=>Io({listParams:{containerName:"copilot-steps",steps:t,tracer:m},fixtures:p,options:{collectDebugData:!1,reinitializeBrowser:!1,disableHealing:!0},inputs:{orgId:d,runId:JZ(),steps:t,testMetadata:null,orgSettings:{},fromStep:e,toStep:r},callbacks:{test:{},step:{}},work:f});return i?o.withExecutionOptions(i,h):h()};async function Ug({step:t,project:e,logger:r,storage:n,controller:o,codeEvalTools:i,socket:a,orgId:s,testContext:c,supportsFileOutput:l,tempCaches:u}){let d=await Pg(t,{project:e,logger:r,tempCaches:u});switch(d.type){case"PRESET_ACTION":return e7({step:d,logger:r,storage:n,controller:o,codeEvalTools:i,socket:a,orgId:s,testContext:c,supportsFileOutput:l,tempCaches:u});case"AI_ACTION_DYNAMIC":return t7({step:d,logger:r,storage:n,controller:o,codeEvalTools:i,socket:a,orgId:s,testContext:c,supportsFileOutput:l});case"RESOLVED_MODULE":return r7({step:d,logger:r,storage:n,controller:o,codeEvalTools:i,socket:a,orgId:s,testContext:c,supportsFileOutput:l});default:{let[p,m]=await Promise.all([Fr({browser:o.browser,supportsFileOutput:l}),io({testContext:c,supportsFileOutput:l})]);return[...me({text:`Preview for step type ${d.type} is not supported. Only PRESET_ACTION, RESOLVED_MODULE, and AI_ACTION_DYNAMIC are supported.`,section:"Error"}),...p,...m]}}}async function e7({step:t,logger:e,storage:r,controller:n,codeEvalTools:o,socket:i,orgId:a,testContext:s,supportsFileOutput:c,tempCaches:l}){let u=await Uc({step:t,logger:e,storage:r,controller:n,executionOptions:{skipAISmartWaiting:!0},codeEvalTools:o,socket:i,orgId:a,testContext:s}),d=[];u?u.status==="SUCCESS"?(n7({logger:e,tempCaches:l,command:t.command,parts:d}),d.push(...me({text:`Step Execution successful: ${u.message}`,section:"Successful Result"}))):d.push(...me({text:`Step Execution failed: ${u.message}`,section:"Error"})):d.push(...me({text:"Step Execution errored for an unknown reason.",section:"Error"}));let[p,m]=await Promise.all([Fr({browser:n.browser,supportsFileOutput:c}),io({testContext:s,supportsFileOutput:c})]);return d.push(...p,...m),d}async function t7({step:t,logger:e,storage:r,controller:n,codeEvalTools:o,socket:i,orgId:a,testContext:s,supportsFileOutput:c}){let l=await Uc({step:t,logger:e,storage:r,controller:n,executionOptions:{skipAISmartWaiting:!0},codeEvalTools:o,socket:i,orgId:a,testContext:s}),u=[];l?l.status==="SUCCESS"?u.push(...me({text:`AI action completed successfully: ${l.message??"Goal achieved"}`,section:"Successful Result"})):u.push(...me({text:`AI action failed: ${l.message??"Unknown error while previewing AI action"}`,section:"Error"})):u.push(...me({text:"AI action executed with unknown result.",section:"Error"}));let[d,p]=await Promise.all([Fr({browser:n.browser,supportsFileOutput:c}),io({testContext:s,supportsFileOutput:c})]);return u.push(...d,...p),u}async function r7({step:t,logger:e,storage:r,controller:n,codeEvalTools:o,socket:i,orgId:a,testContext:s,supportsFileOutput:c}){let l=await Uc({step:t,logger:e,storage:r,controller:n,executionOptions:{skipAISmartWaiting:!0},codeEvalTools:o,socket:i,orgId:a,testContext:s}),u=[];l?l.status==="SUCCESS"?u.push(...me({text:`Module executed successfully: ${l.message}`,section:"Successful Result"})):u.push(...me({text:`Module execution failed: ${l.message}`,section:"Error"})):u.push(...me({text:"Module execution errored for an unknown reason.",section:"Error"}));let[d,p]=await Promise.all([Fr({browser:n.browser,supportsFileOutput:c}),io({testContext:s,supportsFileOutput:c})]);return u.push(...d,...p),u}function n7({logger:t,tempCaches:e,command:r,parts:n}){if(e&&Hi(r)&&r.cache)try{let o=QZ();e[o]=po.parse(ZZ({type:r.type,cache:r.cache})),n.push(...me({text:o,section:"CacheId"}))}catch(o){t.warn({err:o},"Failed to save temp cache for step. Continuing...")}}import{cloneDeep as h7}from"lodash-es";import rB from"path";var dA=Symbol.for("immer-nothing"),up=Symbol.for("immer-draftable"),Rn=Symbol.for("immer-state");function Ur(t,...e){throw new Error(`[Immer] minified error nr: ${t}. Full error at: https://bit.ly/3cXEKWf`)}var $s=Object.getPrototypeOf;function qs(t){return!!t&&!!t[Rn]}function _a(t){return t?qU(t)||Array.isArray(t)||!!t[up]||!!t.constructor?.[up]||hp(t)||gp(t):!1}var o7=Object.prototype.constructor.toString();function qU(t){if(!t||typeof t!="object")return!1;let e=$s(t);if(e===null)return!0;let r=Object.hasOwnProperty.call(e,"constructor")&&e.constructor;return r===Object?!0:typeof r=="function"&&Function.toString.call(r)===o7}function dp(t,e){Ks(t)===0?Reflect.ownKeys(t).forEach(r=>{e(r,t[r],t)}):t.forEach((r,n)=>e(n,r,t))}function Ks(t){let e=t[Rn];return e?e.type_:Array.isArray(t)?1:hp(t)?2:gp(t)?3:0}function pp(t,e){return Ks(t)===2?t.has(e):Object.prototype.hasOwnProperty.call(t,e)}function rA(t,e){return Ks(t)===2?t.get(e):t[e]}function KU(t,e,r){let n=Ks(t);n===2?t.set(e,r):n===3?t.add(r):t[e]=r}function i7(t,e){return t===e?t!==0||1/t===1/e:t!==t&&e!==e}function hp(t){return t instanceof Map}function gp(t){return t instanceof Set}function Ws(t){return t.copy_||t.base_}function iA(t,e){if(hp(t))return new Map(t);if(gp(t))return new Set(t);if(Array.isArray(t))return Array.prototype.slice.call(t);let r=qU(t);if(e===!0||e==="class_only"&&!r){let n=Object.getOwnPropertyDescriptors(t);delete n[Rn];let o=Reflect.ownKeys(n);for(let i=0;i<o.length;i++){let a=o[i],s=n[a];s.writable===!1&&(s.writable=!0,s.configurable=!0),(s.get||s.set)&&(n[a]={configurable:!0,writable:!0,enumerable:s.enumerable,value:t[a]})}return Object.create($s(t),n)}else{let n=$s(t);if(n!==null&&r)return{...t};let o=Object.create(n);return Object.assign(o,t)}}function pA(t,e=!1){return Hg(t)||qs(t)||!_a(t)||(Ks(t)>1&&(t.set=t.add=t.clear=t.delete=a7),Object.freeze(t),e&&Object.entries(t).forEach(([r,n])=>pA(n,!0))),t}function a7(){Ur(2)}function Hg(t){return Object.isFrozen(t)}var aA={};function Ys(t){let e=aA[t];return e||Ur(0,t),e}function s7(t,e){aA[t]||(aA[t]=e)}var mp;function YU(){return mp}function l7(t,e){return{drafts_:[],parent_:t,immer_:e,canAutoFreeze_:!0,unfinalizedDrafts_:0}}function jU(t,e){e&&(Ys("Patches"),t.patches_=[],t.inversePatches_=[],t.patchListener_=e)}function sA(t){lA(t),t.drafts_.forEach(c7),t.drafts_=null}function lA(t){t===mp&&(mp=t.parent_)}function VU(t){return mp=l7(mp,t)}function c7(t){let e=t[Rn];e.type_===0||e.type_===1?e.revoke_():e.revoked_=!0}function WU(t,e){e.unfinalizedDrafts_=e.drafts_.length;let r=e.drafts_[0];return t!==void 0&&t!==r?(r[Rn].modified_&&(sA(e),Ur(4)),_a(t)&&(t=Bg(e,t),e.parent_||zg(e,t)),e.patches_&&Ys("Patches").generateReplacementPatches_(r[Rn].base_,t,e.patches_,e.inversePatches_)):t=Bg(e,r,[]),sA(e),e.patches_&&e.patchListener_(e.patches_,e.inversePatches_),t!==dA?t:void 0}function Bg(t,e,r){if(Hg(e))return e;let n=e[Rn];if(!n)return dp(e,(o,i)=>$U(t,n,e,o,i,r)),e;if(n.scope_!==t)return e;if(!n.modified_)return zg(t,n.base_,!0),n.base_;if(!n.finalized_){n.finalized_=!0,n.scope_.unfinalizedDrafts_--;let o=n.copy_,i=o,a=!1;n.type_===3&&(i=new Set(o),o.clear(),a=!0),dp(i,(s,c)=>$U(t,n,o,s,c,r,a)),zg(t,o,!1),r&&t.patches_&&Ys("Patches").generatePatches_(n,r,t.patches_,t.inversePatches_)}return n.copy_}function $U(t,e,r,n,o,i,a){if(qs(o)){let s=i&&e&&e.type_!==3&&!pp(e.assigned_,n)?i.concat(n):void 0,c=Bg(t,o,s);if(KU(r,n,c),qs(c))t.canAutoFreeze_=!1;else return}else a&&r.add(o);if(_a(o)&&!Hg(o)){if(!t.immer_.autoFreeze_&&t.unfinalizedDrafts_<1)return;Bg(t,o),(!e||!e.scope_.parent_)&&typeof n!="symbol"&&Object.prototype.propertyIsEnumerable.call(r,n)&&zg(t,o)}}function zg(t,e,r=!1){!t.parent_&&t.immer_.autoFreeze_&&t.canAutoFreeze_&&pA(e,r)}function u7(t,e){let r=Array.isArray(t),n={type_:r?1:0,scope_:e?e.scope_:YU(),modified_:!1,finalized_:!1,assigned_:{},parent_:e,base_:t,draft_:null,copy_:null,revoke_:null,isManual_:!1},o=n,i=mA;r&&(o=[n],i=fp);let{revoke:a,proxy:s}=Proxy.revocable(o,i);return n.draft_=s,n.revoke_=a,s}var mA={get(t,e){if(e===Rn)return t;let r=Ws(t);if(!pp(r,e))return d7(t,r,e);let n=r[e];return t.finalized_||!_a(n)?n:n===nA(t.base_,e)?(oA(t),t.copy_[e]=uA(n,t)):n},has(t,e){return e in Ws(t)},ownKeys(t){return Reflect.ownKeys(Ws(t))},set(t,e,r){let n=XU(Ws(t),e);if(n?.set)return n.set.call(t.draft_,r),!0;if(!t.modified_){let o=nA(Ws(t),e),i=o?.[Rn];if(i&&i.base_===r)return t.copy_[e]=r,t.assigned_[e]=!1,!0;if(i7(r,o)&&(r!==void 0||pp(t.base_,e)))return!0;oA(t),cA(t)}return t.copy_[e]===r&&(r!==void 0||e in t.copy_)||Number.isNaN(r)&&Number.isNaN(t.copy_[e])||(t.copy_[e]=r,t.assigned_[e]=!0),!0},deleteProperty(t,e){return nA(t.base_,e)!==void 0||e in t.base_?(t.assigned_[e]=!1,oA(t),cA(t)):delete t.assigned_[e],t.copy_&&delete t.copy_[e],!0},getOwnPropertyDescriptor(t,e){let r=Ws(t),n=Reflect.getOwnPropertyDescriptor(r,e);return n&&{writable:!0,configurable:t.type_!==1||e!=="length",enumerable:n.enumerable,value:r[e]}},defineProperty(){Ur(11)},getPrototypeOf(t){return $s(t.base_)},setPrototypeOf(){Ur(12)}},fp={};dp(mA,(t,e)=>{fp[t]=function(){return arguments[0]=arguments[0][0],e.apply(this,arguments)}});fp.deleteProperty=function(t,e){return fp.set.call(this,t,e,void 0)};fp.set=function(t,e,r){return mA.set.call(this,t[0],e,r,t[0])};function nA(t,e){let r=t[Rn];return(r?Ws(r):t)[e]}function d7(t,e,r){let n=XU(e,r);return n?"value"in n?n.value:n.get?.call(t.draft_):void 0}function XU(t,e){if(!(e in t))return;let r=$s(t);for(;r;){let n=Object.getOwnPropertyDescriptor(r,e);if(n)return n;r=$s(r)}}function cA(t){t.modified_||(t.modified_=!0,t.parent_&&cA(t.parent_))}function oA(t){t.copy_||(t.copy_=iA(t.base_,t.scope_.immer_.useStrictShallowCopy_))}var p7=class{constructor(t){this.autoFreeze_=!0,this.useStrictShallowCopy_=!1,this.produce=(e,r,n)=>{if(typeof e=="function"&&typeof r!="function"){let i=r;r=e;let a=this;return function(c=i,...l){return a.produce(c,u=>r.call(this,u,...l))}}typeof r!="function"&&Ur(6),n!==void 0&&typeof n!="function"&&Ur(7);let o;if(_a(e)){let i=VU(this),a=uA(e,void 0),s=!0;try{o=r(a),s=!1}finally{s?sA(i):lA(i)}return jU(i,n),WU(o,i)}else if(!e||typeof e!="object"){if(o=r(e),o===void 0&&(o=e),o===dA&&(o=void 0),this.autoFreeze_&&pA(o,!0),n){let i=[],a=[];Ys("Patches").generateReplacementPatches_(e,o,i,a),n(i,a)}return o}else Ur(1,e)},this.produceWithPatches=(e,r)=>{if(typeof e=="function")return(a,...s)=>this.produceWithPatches(a,c=>e(c,...s));let n,o;return[this.produce(e,r,(a,s)=>{n=a,o=s}),n,o]},typeof t?.autoFreeze=="boolean"&&this.setAutoFreeze(t.autoFreeze),typeof t?.useStrictShallowCopy=="boolean"&&this.setUseStrictShallowCopy(t.useStrictShallowCopy)}createDraft(t){_a(t)||Ur(8),qs(t)&&(t=m7(t));let e=VU(this),r=uA(t,void 0);return r[Rn].isManual_=!0,lA(e),r}finishDraft(t,e){let r=t&&t[Rn];(!r||!r.isManual_)&&Ur(9);let{scope_:n}=r;return jU(n,e),WU(void 0,n)}setAutoFreeze(t){this.autoFreeze_=t}setUseStrictShallowCopy(t){this.useStrictShallowCopy_=t}applyPatches(t,e){let r;for(r=e.length-1;r>=0;r--){let o=e[r];if(o.path.length===0&&o.op==="replace"){t=o.value;break}}r>-1&&(e=e.slice(r+1));let n=Ys("Patches").applyPatches_;return qs(t)?n(t,e):this.produce(t,o=>n(o,e))}};function uA(t,e){let r=hp(t)?Ys("MapSet").proxyMap_(t,e):gp(t)?Ys("MapSet").proxySet_(t,e):u7(t,e);return(e?e.scope_:YU()).drafts_.push(r),r}function m7(t){return qs(t)||Ur(10,t),JU(t)}function JU(t){if(!_a(t)||Hg(t))return t;let e=t[Rn],r;if(e){if(!e.modified_)return e.base_;e.finalized_=!0,r=iA(t,e.scope_.immer_.useStrictShallowCopy_)}else r=iA(t,!0);return dp(r,(n,o)=>{KU(r,n,JU(o))}),e&&(e.finalized_=!1),r}function QU(){let e="replace",r="add",n="remove";function o(p,m,f,h){switch(p.type_){case 0:case 2:return a(p,m,f,h);case 1:return i(p,m,f,h);case 3:return s(p,m,f,h)}}function i(p,m,f,h){let{base_:S,assigned_:g}=p,E=p.copy_;E.length<S.length&&([S,E]=[E,S],[f,h]=[h,f]);for(let y=0;y<S.length;y++)if(g[y]&&E[y]!==S[y]){let b=m.concat([y]);f.push({op:e,path:b,value:d(E[y])}),h.push({op:e,path:b,value:d(S[y])})}for(let y=S.length;y<E.length;y++){let b=m.concat([y]);f.push({op:r,path:b,value:d(E[y])})}for(let y=E.length-1;S.length<=y;--y){let b=m.concat([y]);h.push({op:n,path:b})}}function a(p,m,f,h){let{base_:S,copy_:g}=p;dp(p.assigned_,(E,y)=>{let b=rA(S,E),C=rA(g,E),I=y?pp(S,E)?e:r:n;if(b===C&&I===e)return;let _=m.concat(E);f.push(I===n?{op:I,path:_}:{op:I,path:_,value:C}),h.push(I===r?{op:n,path:_}:I===n?{op:r,path:_,value:d(b)}:{op:e,path:_,value:d(b)})})}function s(p,m,f,h){let{base_:S,copy_:g}=p,E=0;S.forEach(y=>{if(!g.has(y)){let b=m.concat([E]);f.push({op:n,path:b,value:y}),h.unshift({op:r,path:b,value:y})}E++}),E=0,g.forEach(y=>{if(!S.has(y)){let b=m.concat([E]);f.push({op:r,path:b,value:y}),h.unshift({op:n,path:b,value:y})}E++})}function c(p,m,f,h){f.push({op:e,path:[],value:m===dA?void 0:m}),h.push({op:e,path:[],value:p})}function l(p,m){return m.forEach(f=>{let{path:h,op:S}=f,g=p;for(let C=0;C<h.length-1;C++){let I=Ks(g),_=h[C];typeof _!="string"&&typeof _!="number"&&(_=""+_),(I===0||I===1)&&(_==="__proto__"||_==="constructor")&&Ur(19),typeof g=="function"&&_==="prototype"&&Ur(19),g=rA(g,_),typeof g!="object"&&Ur(18,h.join("/"))}let E=Ks(g),y=u(f.value),b=h[h.length-1];switch(S){case e:switch(E){case 2:return g.set(b,y);case 3:Ur(16);default:return g[b]=y}case r:switch(E){case 1:return b==="-"?g.push(y):g.splice(b,0,y);case 2:return g.set(b,y);case 3:return g.add(y);default:return g[b]=y}case n:switch(E){case 1:return g.splice(b,1);case 2:return g.delete(b);case 3:return g.delete(f.value);default:return delete g[b]}default:Ur(17,S)}}),p}function u(p){if(!_a(p))return p;if(Array.isArray(p))return p.map(u);if(hp(p))return new Map(Array.from(p.entries()).map(([f,h])=>[f,u(h)]));if(gp(p))return new Set(Array.from(p).map(u));let m=Object.create($s(p));for(let f in p)m[f]=u(p[f]);return pp(p,up)&&(m[up]=p[up]),m}function d(p){return qs(p)?u(p):p}s7("Patches",{applyPatches_:l,generatePatches_:o,generateReplacementPatches_:c})}var wn=new p7,Wpt=wn.produce,ZU=wn.produceWithPatches.bind(wn),$pt=wn.setAutoFreeze.bind(wn),qpt=wn.setUseStrictShallowCopy.bind(wn),Kpt=wn.applyPatches.bind(wn),Ypt=wn.createDraft.bind(wn),Xpt=wn.finishDraft.bind(wn);import{v4 as f7}from"uuid";QU();function Gg({logger:t,socket:e,baseState:r,recipe:n,description:o}){let[i,a,s]=ZU(r,n),c={id:f7(),patches:a,inversePatches:s,description:o,timestamp:Date.now()};return e?.emit("copilotPatch",c),t.info({patchJson:JSON.stringify(c)},"Immer patch representation of tool's effect on test"),{patch:c,newState:i}}var eB=({steps:t,fromStep:e,toStep:r})=>{let n={total:0,fastForwardingToStep:!0},o=(i,a)=>{if(i.skipped)return!1;let s=a.map(l=>l.id),c=ip(i.id,s,e.fromStepId,e.parentStepIdChain);if(n.fastForwardingToStep){if(!c)return!1;n.fastForwardingToStep=!1}return n.total+=1,!!(r&&ip(i.id,s,r.toStepId,r.parentStepIdChain))};return ln({steps:t,earlyStop:!0,onPresetAction:(i,a)=>o(i,a.parentChain),onConditional:(i,a)=>{if(i.skipped)return!1;let s=a.parentChain.map(l=>l.id),c=ip(i.id,s,e.fromStepId,e.parentStepIdChain);if(n.fastForwardingToStep){if(!c)return!1;n.fastForwardingToStep=!1}return!!(r&&ip(i.id,s,r.toStepId,r.parentStepIdChain))},onSimpleStepContainer:(i,a)=>o(i,a.parentChain)}),n.total};var g7=t=>{throw new Error(`Unknown test section: ${t}`)};function hA(t,e){switch(e){case"setup":return t.beforeSteps??[];case"teardown":return t.afterSteps??[];case"main":return t.steps;default:return g7(e)}}function fA(t,e,r){let n=hA(t,e);if(!r?.length)return n;let o=yL(n,r);if(!o)throw new Error(`No step found with parent chain [${r.join(", ")}] in ${e} section, or parent does not support nested steps`);return o}function S7({sectionLength:t,startIndex:e,insertedCount:r}){let n=Math.max(0,e-1),o=Math.min(t,e+r+1);return{windowStart:n,windowEndExclusive:o}}function y7({steps:t,sectionLabel:e,startIndexOffset:r}){if(t.length===0)return`${e}: (no steps)`;let n=tb(t,{includeCache:!1});n.forEach((i,a)=>{i.index=r+a});let o=["```json",JSON.stringify(n,null,2),"```"].join(`
|
|
5268
|
+
`);r.addPartFromText(a)}});import{z as Fg}from"zod";var UU=Zt({schema:{name:RI,description:"Get the current browser state for a granular session. Defaults: screenshot on, browser snapshot off. The browser snapshot includes the URL, accessibility tree, and other context. Ask for it (returnBrowserState: true) when you need it for locator resolution or richer page structure\u2014e.g. when screenshot-only output is insufficient.",inputSchema:{sessionId:Fg.string().describe("The session id to query."),returnBrowserState:Fg.boolean().default(!1).describe("Include the serialized browser snapshot. Default false. Set to true when you need the browser snapshot for element targeting or page structure."),returnScreenshot:Fg.boolean().default(!0).describe("Include a screenshot. Default true. Set to false if you already have a screenshot of the present state and don't need a new one. EX: you just previewed a step and see that the page is too complicated and need the browser snapshot.")}},handle:async(t,e,r)=>{let n=Vs(r,e.sessionId);if(!n)return;n.controller.setOpen();let o=await Jv({browser:n.controller.browser,supportsFileOutput:t.supportsFileOutput,returnBrowserState:e.returnBrowserState,returnScreenshot:e.returnScreenshot});r.addContentParts(o)}}),BU=Zt({schema:{name:wI,description:"Get the current environment variables for a session.",inputSchema:{sessionId:Fg.string()}},handle:async(t,e,r)=>{let n=Vs(r,e.sessionId);if(!n)return;let o=await io({testContext:n.context,supportsFileOutput:t.supportsFileOutput});r.addContentParts(o)}});import{z as Fc}from"zod";var zU=Zt({schema:{name:AI,description:"Start a granular browser session for a specific test. Requires a testId. Returns session metadata (sessionId, testId, testFileAbsolutePath, viewport, etc.). Use testFileAbsolutePath to read the test file for step IDs when calling tools that require step IDs.",inputSchema:{testId:Fc.string().describe("The test id to target when starting a session."),envName:Fc.string().optional().describe("Optional environment override (matches CLI --env behavior). Defaults to the test's default env when omitted."),projectConfigPath:Fc.string().optional().describe("Optional path to a momentic.config.yaml file (matches CLI --config)."),projectNameFilter:Fc.string().optional().describe("Optional project name filter for workspace configs (matches CLI --filter)."),headfulBrowser:Fc.boolean().optional().describe("Whether to launch a headful browser for the session. When omitted, uses the MCP server default if configured.")}},handle:async(t,e,r)=>{let{logger:n}=t,o;try{o=await oi.startSession({logger:n,testId:e.testId,idleTimeoutMs:t.sessionIdleTimeoutMs,envName:e.envName,projectConfigPath:e.projectConfigPath??t.project.configFilePath,projectNameFilter:e.projectNameFilter,headfulOverride:e.headfulBrowser??t.headfulBrowserDefault??!0,customHeaders:t.customHeaders,devicePixelRatio:t.devicePixelRatio,skipExitOnError:!0})}catch(l){r.addError(Yt(l));return}let{session:i,baseUrl:a,envName:s}=o,c=i.controller.browser.getViewport();r.addPartFromText(JSON.stringify({sessionId:i.sessionId,testId:i.testId,testFileAbsolutePath:i.testFileAbsolutePath,createdAt:i.createdAt,expiresAt:i.lastAccessedAt+i.idleTimeoutMs,idleTimeoutMinutes:i.idleTimeoutMs/(60*1e3),envName:s,baseUrl:a,viewport:c},null,2));try{r.addContentParts(await Fr({browser:i.controller.browser,supportsFileOutput:t.supportsFileOutput}))}catch(l){n.warn({sessionId:i.sessionId,err:l},"Session started but initial screenshot capture failed"),r.addPartFromText(JSON.stringify({warning:"Session started successfully, but initial screenshot capture failed.",screenshotError:Yt(l)},null,2))}}}),HU=Zt({schema:{name:CI,description:"Kill a granular browser session by sessionId. Returns available session ids if the target is missing.",inputSchema:{sessionId:Fc.string().describe("The session id to terminate.")}},handle:async(t,e,r)=>{try{if(!await oi.killSession(e.sessionId,"explicit kill")){r.addError(JSON.stringify({message:`No active session found for id '${e.sessionId}'.`,availableSessionIds:oi.listSessionIds()},null,2));return}r.addPartFromText(JSON.stringify({sessionId:e.sessionId,killed:!0},null,2))}catch(n){r.addError(String(n))}}});import{z as ao}from"zod";import GU from"path";import{v4 as XZ}from"uuid";async function cp({project:t,input:e}){try{go(e.name)}catch(l){throw new or(`${l} when validating the test entity name`)}if(!e.baseUrl&&!e.environment)throw new or("Either 'baseUrl' or 'environment' must be provided when creating a test.");let r=await fe(t);if(Object.values(r.tests).find(l=>l.name===e.name))throw new or(`A test with the name "${e.name}" already exists. Please use a different name.`);let i={id:XZ(),name:e.name,description:e.description,baseUrl:e.baseUrl,schemaVersion:De,advanced:{browserType:e.browserType??"Chromium",viewport:e.viewport??Ir},retries:1,steps:[]};e.environment&&(i.envs=[{name:e.environment,default:!0}]);let a=GU.join(t.rootDir,...e.pathSegments||[]),s=await LN({test:i,name:e.name,folder:a});return{...i,relativeFilePath:GU.relative(t.rootDir,s)}}import{randomUUID as QZ}from"crypto";import{cloneDeep as ZZ}from"lodash-es";import{randomUUID as JZ}from"crypto";var Uc=async({step:t,controller:e,executionOptions:r,storage:n,codeEvalTools:o,logger:i,socket:a,testContext:s,orgId:c})=>{let{results:l}=await tA({steps:[t],controller:e,executionOptions:r,storage:n,codeEvalTools:o,logger:i,socket:a,testContext:s,orgId:c});return l[0]},tA=async({steps:t,fromStep:e,toStep:r,tracer:n,controller:o,executionOptions:i,storage:a,codeEvalTools:s,logger:c,socket:l,testContext:u,orgId:d})=>{let p={controller:o,storage:a,codeEvalTools:s,logger:c,context:u,usageTracker:new Dl},m=n??(l?new Oi({orgId:d,parentStep:null,parentTracer:null,socket:l}):new sd);o.setOpen();let f={results:[],asyncTasks:[],state:{autoHealingDisabled:!0,failureRecoveryDisabled:!0,failureRecoveryAttempts:0},...e&&{fastForwardingToStep:!0}},h=()=>Io({listParams:{containerName:"copilot-steps",steps:t,tracer:m},fixtures:p,options:{collectDebugData:!1,reinitializeBrowser:!1,disableHealing:!0},inputs:{orgId:d,runId:JZ(),steps:t,testMetadata:null,orgSettings:{},fromStep:e,toStep:r},callbacks:{test:{},step:{}},work:f});return i?o.withExecutionOptions(i,h):h()};async function Ug({step:t,project:e,logger:r,storage:n,controller:o,codeEvalTools:i,socket:a,orgId:s,testContext:c,supportsFileOutput:l,tempCaches:u}){let d=await Pg(t,{project:e,logger:r,tempCaches:u});switch(d.type){case"PRESET_ACTION":return e7({step:d,logger:r,storage:n,controller:o,codeEvalTools:i,socket:a,orgId:s,testContext:c,supportsFileOutput:l,tempCaches:u});case"AI_ACTION_DYNAMIC":return t7({step:d,logger:r,storage:n,controller:o,codeEvalTools:i,socket:a,orgId:s,testContext:c,supportsFileOutput:l});case"RESOLVED_MODULE":return r7({step:d,logger:r,storage:n,controller:o,codeEvalTools:i,socket:a,orgId:s,testContext:c,supportsFileOutput:l});default:{let[p,m]=await Promise.all([Fr({browser:o.browser,supportsFileOutput:l}),io({testContext:c,supportsFileOutput:l})]);return[...me({text:`Preview for step type ${d.type} is not supported. Only PRESET_ACTION, RESOLVED_MODULE, and AI_ACTION_DYNAMIC are supported.`,section:"Error"}),...p,...m]}}}async function e7({step:t,logger:e,storage:r,controller:n,codeEvalTools:o,socket:i,orgId:a,testContext:s,supportsFileOutput:c,tempCaches:l}){let u=await Uc({step:t,logger:e,storage:r,controller:n,executionOptions:{skipAISmartWaiting:!0},codeEvalTools:o,socket:i,orgId:a,testContext:s}),d=[];u?u.status==="SUCCESS"?(n7({logger:e,tempCaches:l,command:t.command,parts:d}),d.push(...me({text:`Step Execution successful: ${u.message}`,section:"Successful Result"}))):d.push(...me({text:`Step Execution failed: ${u.message}`,section:"Error"})):d.push(...me({text:"Step Execution errored for an unknown reason.",section:"Error"}));let[p,m]=await Promise.all([Fr({browser:n.browser,supportsFileOutput:c}),io({testContext:s,supportsFileOutput:c})]);return d.push(...p,...m),d}async function t7({step:t,logger:e,storage:r,controller:n,codeEvalTools:o,socket:i,orgId:a,testContext:s,supportsFileOutput:c}){let l=await Uc({step:t,logger:e,storage:r,controller:n,executionOptions:{skipAISmartWaiting:!0},codeEvalTools:o,socket:i,orgId:a,testContext:s}),u=[];l?l.status==="SUCCESS"?u.push(...me({text:`AI action completed successfully: ${l.message??"Goal achieved"}`,section:"Successful Result"})):u.push(...me({text:`AI action failed: ${l.message??"Unknown error while previewing AI action"}`,section:"Error"})):u.push(...me({text:"AI action executed with unknown result.",section:"Error"}));let[d,p]=await Promise.all([Fr({browser:n.browser,supportsFileOutput:c}),io({testContext:s,supportsFileOutput:c})]);return u.push(...d,...p),u}async function r7({step:t,logger:e,storage:r,controller:n,codeEvalTools:o,socket:i,orgId:a,testContext:s,supportsFileOutput:c}){let l=await Uc({step:t,logger:e,storage:r,controller:n,executionOptions:{skipAISmartWaiting:!0},codeEvalTools:o,socket:i,orgId:a,testContext:s}),u=[];l?l.status==="SUCCESS"?u.push(...me({text:`Module executed successfully: ${l.message}`,section:"Successful Result"})):u.push(...me({text:`Module execution failed: ${l.message}`,section:"Error"})):u.push(...me({text:"Module execution errored for an unknown reason.",section:"Error"}));let[d,p]=await Promise.all([Fr({browser:n.browser,supportsFileOutput:c}),io({testContext:s,supportsFileOutput:c})]);return u.push(...d,...p),u}function n7({logger:t,tempCaches:e,command:r,parts:n}){if(e&&Hi(r)&&r.cache)try{let o=QZ();e[o]=po.parse(ZZ({type:r.type,cache:r.cache})),n.push(...me({text:o,section:"CacheId"}))}catch(o){t.warn({err:o},"Failed to save temp cache for step. Continuing...")}}import{cloneDeep as h7}from"lodash-es";import rB from"path";var dA=Symbol.for("immer-nothing"),up=Symbol.for("immer-draftable"),Rn=Symbol.for("immer-state");function Ur(t,...e){throw new Error(`[Immer] minified error nr: ${t}. Full error at: https://bit.ly/3cXEKWf`)}var $s=Object.getPrototypeOf;function qs(t){return!!t&&!!t[Rn]}function _a(t){return t?qU(t)||Array.isArray(t)||!!t[up]||!!t.constructor?.[up]||hp(t)||gp(t):!1}var o7=Object.prototype.constructor.toString();function qU(t){if(!t||typeof t!="object")return!1;let e=$s(t);if(e===null)return!0;let r=Object.hasOwnProperty.call(e,"constructor")&&e.constructor;return r===Object?!0:typeof r=="function"&&Function.toString.call(r)===o7}function dp(t,e){Ks(t)===0?Reflect.ownKeys(t).forEach(r=>{e(r,t[r],t)}):t.forEach((r,n)=>e(n,r,t))}function Ks(t){let e=t[Rn];return e?e.type_:Array.isArray(t)?1:hp(t)?2:gp(t)?3:0}function pp(t,e){return Ks(t)===2?t.has(e):Object.prototype.hasOwnProperty.call(t,e)}function rA(t,e){return Ks(t)===2?t.get(e):t[e]}function KU(t,e,r){let n=Ks(t);n===2?t.set(e,r):n===3?t.add(r):t[e]=r}function i7(t,e){return t===e?t!==0||1/t===1/e:t!==t&&e!==e}function hp(t){return t instanceof Map}function gp(t){return t instanceof Set}function Ws(t){return t.copy_||t.base_}function iA(t,e){if(hp(t))return new Map(t);if(gp(t))return new Set(t);if(Array.isArray(t))return Array.prototype.slice.call(t);let r=qU(t);if(e===!0||e==="class_only"&&!r){let n=Object.getOwnPropertyDescriptors(t);delete n[Rn];let o=Reflect.ownKeys(n);for(let i=0;i<o.length;i++){let a=o[i],s=n[a];s.writable===!1&&(s.writable=!0,s.configurable=!0),(s.get||s.set)&&(n[a]={configurable:!0,writable:!0,enumerable:s.enumerable,value:t[a]})}return Object.create($s(t),n)}else{let n=$s(t);if(n!==null&&r)return{...t};let o=Object.create(n);return Object.assign(o,t)}}function pA(t,e=!1){return Hg(t)||qs(t)||!_a(t)||(Ks(t)>1&&(t.set=t.add=t.clear=t.delete=a7),Object.freeze(t),e&&Object.entries(t).forEach(([r,n])=>pA(n,!0))),t}function a7(){Ur(2)}function Hg(t){return Object.isFrozen(t)}var aA={};function Ys(t){let e=aA[t];return e||Ur(0,t),e}function s7(t,e){aA[t]||(aA[t]=e)}var mp;function YU(){return mp}function l7(t,e){return{drafts_:[],parent_:t,immer_:e,canAutoFreeze_:!0,unfinalizedDrafts_:0}}function jU(t,e){e&&(Ys("Patches"),t.patches_=[],t.inversePatches_=[],t.patchListener_=e)}function sA(t){lA(t),t.drafts_.forEach(c7),t.drafts_=null}function lA(t){t===mp&&(mp=t.parent_)}function VU(t){return mp=l7(mp,t)}function c7(t){let e=t[Rn];e.type_===0||e.type_===1?e.revoke_():e.revoked_=!0}function WU(t,e){e.unfinalizedDrafts_=e.drafts_.length;let r=e.drafts_[0];return t!==void 0&&t!==r?(r[Rn].modified_&&(sA(e),Ur(4)),_a(t)&&(t=Bg(e,t),e.parent_||zg(e,t)),e.patches_&&Ys("Patches").generateReplacementPatches_(r[Rn].base_,t,e.patches_,e.inversePatches_)):t=Bg(e,r,[]),sA(e),e.patches_&&e.patchListener_(e.patches_,e.inversePatches_),t!==dA?t:void 0}function Bg(t,e,r){if(Hg(e))return e;let n=e[Rn];if(!n)return dp(e,(o,i)=>$U(t,n,e,o,i,r)),e;if(n.scope_!==t)return e;if(!n.modified_)return zg(t,n.base_,!0),n.base_;if(!n.finalized_){n.finalized_=!0,n.scope_.unfinalizedDrafts_--;let o=n.copy_,i=o,a=!1;n.type_===3&&(i=new Set(o),o.clear(),a=!0),dp(i,(s,c)=>$U(t,n,o,s,c,r,a)),zg(t,o,!1),r&&t.patches_&&Ys("Patches").generatePatches_(n,r,t.patches_,t.inversePatches_)}return n.copy_}function $U(t,e,r,n,o,i,a){if(qs(o)){let s=i&&e&&e.type_!==3&&!pp(e.assigned_,n)?i.concat(n):void 0,c=Bg(t,o,s);if(KU(r,n,c),qs(c))t.canAutoFreeze_=!1;else return}else a&&r.add(o);if(_a(o)&&!Hg(o)){if(!t.immer_.autoFreeze_&&t.unfinalizedDrafts_<1)return;Bg(t,o),(!e||!e.scope_.parent_)&&typeof n!="symbol"&&Object.prototype.propertyIsEnumerable.call(r,n)&&zg(t,o)}}function zg(t,e,r=!1){!t.parent_&&t.immer_.autoFreeze_&&t.canAutoFreeze_&&pA(e,r)}function u7(t,e){let r=Array.isArray(t),n={type_:r?1:0,scope_:e?e.scope_:YU(),modified_:!1,finalized_:!1,assigned_:{},parent_:e,base_:t,draft_:null,copy_:null,revoke_:null,isManual_:!1},o=n,i=mA;r&&(o=[n],i=fp);let{revoke:a,proxy:s}=Proxy.revocable(o,i);return n.draft_=s,n.revoke_=a,s}var mA={get(t,e){if(e===Rn)return t;let r=Ws(t);if(!pp(r,e))return d7(t,r,e);let n=r[e];return t.finalized_||!_a(n)?n:n===nA(t.base_,e)?(oA(t),t.copy_[e]=uA(n,t)):n},has(t,e){return e in Ws(t)},ownKeys(t){return Reflect.ownKeys(Ws(t))},set(t,e,r){let n=XU(Ws(t),e);if(n?.set)return n.set.call(t.draft_,r),!0;if(!t.modified_){let o=nA(Ws(t),e),i=o?.[Rn];if(i&&i.base_===r)return t.copy_[e]=r,t.assigned_[e]=!1,!0;if(i7(r,o)&&(r!==void 0||pp(t.base_,e)))return!0;oA(t),cA(t)}return t.copy_[e]===r&&(r!==void 0||e in t.copy_)||Number.isNaN(r)&&Number.isNaN(t.copy_[e])||(t.copy_[e]=r,t.assigned_[e]=!0),!0},deleteProperty(t,e){return nA(t.base_,e)!==void 0||e in t.base_?(t.assigned_[e]=!1,oA(t),cA(t)):delete t.assigned_[e],t.copy_&&delete t.copy_[e],!0},getOwnPropertyDescriptor(t,e){let r=Ws(t),n=Reflect.getOwnPropertyDescriptor(r,e);return n&&{writable:!0,configurable:t.type_!==1||e!=="length",enumerable:n.enumerable,value:r[e]}},defineProperty(){Ur(11)},getPrototypeOf(t){return $s(t.base_)},setPrototypeOf(){Ur(12)}},fp={};dp(mA,(t,e)=>{fp[t]=function(){return arguments[0]=arguments[0][0],e.apply(this,arguments)}});fp.deleteProperty=function(t,e){return fp.set.call(this,t,e,void 0)};fp.set=function(t,e,r){return mA.set.call(this,t[0],e,r,t[0])};function nA(t,e){let r=t[Rn];return(r?Ws(r):t)[e]}function d7(t,e,r){let n=XU(e,r);return n?"value"in n?n.value:n.get?.call(t.draft_):void 0}function XU(t,e){if(!(e in t))return;let r=$s(t);for(;r;){let n=Object.getOwnPropertyDescriptor(r,e);if(n)return n;r=$s(r)}}function cA(t){t.modified_||(t.modified_=!0,t.parent_&&cA(t.parent_))}function oA(t){t.copy_||(t.copy_=iA(t.base_,t.scope_.immer_.useStrictShallowCopy_))}var p7=class{constructor(t){this.autoFreeze_=!0,this.useStrictShallowCopy_=!1,this.produce=(e,r,n)=>{if(typeof e=="function"&&typeof r!="function"){let i=r;r=e;let a=this;return function(c=i,...l){return a.produce(c,u=>r.call(this,u,...l))}}typeof r!="function"&&Ur(6),n!==void 0&&typeof n!="function"&&Ur(7);let o;if(_a(e)){let i=VU(this),a=uA(e,void 0),s=!0;try{o=r(a),s=!1}finally{s?sA(i):lA(i)}return jU(i,n),WU(o,i)}else if(!e||typeof e!="object"){if(o=r(e),o===void 0&&(o=e),o===dA&&(o=void 0),this.autoFreeze_&&pA(o,!0),n){let i=[],a=[];Ys("Patches").generateReplacementPatches_(e,o,i,a),n(i,a)}return o}else Ur(1,e)},this.produceWithPatches=(e,r)=>{if(typeof e=="function")return(a,...s)=>this.produceWithPatches(a,c=>e(c,...s));let n,o;return[this.produce(e,r,(a,s)=>{n=a,o=s}),n,o]},typeof t?.autoFreeze=="boolean"&&this.setAutoFreeze(t.autoFreeze),typeof t?.useStrictShallowCopy=="boolean"&&this.setUseStrictShallowCopy(t.useStrictShallowCopy)}createDraft(t){_a(t)||Ur(8),qs(t)&&(t=m7(t));let e=VU(this),r=uA(t,void 0);return r[Rn].isManual_=!0,lA(e),r}finishDraft(t,e){let r=t&&t[Rn];(!r||!r.isManual_)&&Ur(9);let{scope_:n}=r;return jU(n,e),WU(void 0,n)}setAutoFreeze(t){this.autoFreeze_=t}setUseStrictShallowCopy(t){this.useStrictShallowCopy_=t}applyPatches(t,e){let r;for(r=e.length-1;r>=0;r--){let o=e[r];if(o.path.length===0&&o.op==="replace"){t=o.value;break}}r>-1&&(e=e.slice(r+1));let n=Ys("Patches").applyPatches_;return qs(t)?n(t,e):this.produce(t,o=>n(o,e))}};function uA(t,e){let r=hp(t)?Ys("MapSet").proxyMap_(t,e):gp(t)?Ys("MapSet").proxySet_(t,e):u7(t,e);return(e?e.scope_:YU()).drafts_.push(r),r}function m7(t){return qs(t)||Ur(10,t),JU(t)}function JU(t){if(!_a(t)||Hg(t))return t;let e=t[Rn],r;if(e){if(!e.modified_)return e.base_;e.finalized_=!0,r=iA(t,e.scope_.immer_.useStrictShallowCopy_)}else r=iA(t,!0);return dp(r,(n,o)=>{KU(r,n,JU(o))}),e&&(e.finalized_=!1),r}function QU(){let e="replace",r="add",n="remove";function o(p,m,f,h){switch(p.type_){case 0:case 2:return a(p,m,f,h);case 1:return i(p,m,f,h);case 3:return s(p,m,f,h)}}function i(p,m,f,h){let{base_:S,assigned_:g}=p,E=p.copy_;E.length<S.length&&([S,E]=[E,S],[f,h]=[h,f]);for(let y=0;y<S.length;y++)if(g[y]&&E[y]!==S[y]){let b=m.concat([y]);f.push({op:e,path:b,value:d(E[y])}),h.push({op:e,path:b,value:d(S[y])})}for(let y=S.length;y<E.length;y++){let b=m.concat([y]);f.push({op:r,path:b,value:d(E[y])})}for(let y=E.length-1;S.length<=y;--y){let b=m.concat([y]);h.push({op:n,path:b})}}function a(p,m,f,h){let{base_:S,copy_:g}=p;dp(p.assigned_,(E,y)=>{let b=rA(S,E),C=rA(g,E),I=y?pp(S,E)?e:r:n;if(b===C&&I===e)return;let _=m.concat(E);f.push(I===n?{op:I,path:_}:{op:I,path:_,value:C}),h.push(I===r?{op:n,path:_}:I===n?{op:r,path:_,value:d(b)}:{op:e,path:_,value:d(b)})})}function s(p,m,f,h){let{base_:S,copy_:g}=p,E=0;S.forEach(y=>{if(!g.has(y)){let b=m.concat([E]);f.push({op:n,path:b,value:y}),h.unshift({op:r,path:b,value:y})}E++}),E=0,g.forEach(y=>{if(!S.has(y)){let b=m.concat([E]);f.push({op:r,path:b,value:y}),h.unshift({op:n,path:b,value:y})}E++})}function c(p,m,f,h){f.push({op:e,path:[],value:m===dA?void 0:m}),h.push({op:e,path:[],value:p})}function l(p,m){return m.forEach(f=>{let{path:h,op:S}=f,g=p;for(let C=0;C<h.length-1;C++){let I=Ks(g),_=h[C];typeof _!="string"&&typeof _!="number"&&(_=""+_),(I===0||I===1)&&(_==="__proto__"||_==="constructor")&&Ur(19),typeof g=="function"&&_==="prototype"&&Ur(19),g=rA(g,_),typeof g!="object"&&Ur(18,h.join("/"))}let E=Ks(g),y=u(f.value),b=h[h.length-1];switch(S){case e:switch(E){case 2:return g.set(b,y);case 3:Ur(16);default:return g[b]=y}case r:switch(E){case 1:return b==="-"?g.push(y):g.splice(b,0,y);case 2:return g.set(b,y);case 3:return g.add(y);default:return g[b]=y}case n:switch(E){case 1:return g.splice(b,1);case 2:return g.delete(b);case 3:return g.delete(f.value);default:return delete g[b]}default:Ur(17,S)}}),p}function u(p){if(!_a(p))return p;if(Array.isArray(p))return p.map(u);if(hp(p))return new Map(Array.from(p.entries()).map(([f,h])=>[f,u(h)]));if(gp(p))return new Set(Array.from(p).map(u));let m=Object.create($s(p));for(let f in p)m[f]=u(p[f]);return pp(p,up)&&(m[up]=p[up]),m}function d(p){return qs(p)?u(p):p}s7("Patches",{applyPatches_:l,generatePatches_:o,generateReplacementPatches_:c})}var wn=new p7,qpt=wn.produce,ZU=wn.produceWithPatches.bind(wn),Kpt=wn.setAutoFreeze.bind(wn),Ypt=wn.setUseStrictShallowCopy.bind(wn),Xpt=wn.applyPatches.bind(wn),Jpt=wn.createDraft.bind(wn),Qpt=wn.finishDraft.bind(wn);import{v4 as f7}from"uuid";QU();function Gg({logger:t,socket:e,baseState:r,recipe:n,description:o}){let[i,a,s]=ZU(r,n),c={id:f7(),patches:a,inversePatches:s,description:o,timestamp:Date.now()};return e?.emit("copilotPatch",c),t.info({patchJson:JSON.stringify(c)},"Immer patch representation of tool's effect on test"),{patch:c,newState:i}}var eB=({steps:t,fromStep:e,toStep:r})=>{let n={total:0,fastForwardingToStep:!0},o=(i,a)=>{if(i.skipped)return!1;let s=a.map(l=>l.id),c=ip(i.id,s,e.fromStepId,e.parentStepIdChain);if(n.fastForwardingToStep){if(!c)return!1;n.fastForwardingToStep=!1}return n.total+=1,!!(r&&ip(i.id,s,r.toStepId,r.parentStepIdChain))};return ln({steps:t,earlyStop:!0,onPresetAction:(i,a)=>o(i,a.parentChain),onConditional:(i,a)=>{if(i.skipped)return!1;let s=a.parentChain.map(l=>l.id),c=ip(i.id,s,e.fromStepId,e.parentStepIdChain);if(n.fastForwardingToStep){if(!c)return!1;n.fastForwardingToStep=!1}return!!(r&&ip(i.id,s,r.toStepId,r.parentStepIdChain))},onSimpleStepContainer:(i,a)=>o(i,a.parentChain)}),n.total};var g7=t=>{throw new Error(`Unknown test section: ${t}`)};function hA(t,e){switch(e){case"setup":return t.beforeSteps??[];case"teardown":return t.afterSteps??[];case"main":return t.steps;default:return g7(e)}}function fA(t,e,r){let n=hA(t,e);if(!r?.length)return n;let o=yL(n,r);if(!o)throw new Error(`No step found with parent chain [${r.join(", ")}] in ${e} section, or parent does not support nested steps`);return o}function S7({sectionLength:t,startIndex:e,insertedCount:r}){let n=Math.max(0,e-1),o=Math.min(t,e+r+1);return{windowStart:n,windowEndExclusive:o}}function y7({steps:t,sectionLabel:e,startIndexOffset:r}){if(t.length===0)return`${e}: (no steps)`;let n=tb(t,{includeCache:!1});n.forEach((i,a)=>{i.index=r+a});let o=["```json",JSON.stringify(n,null,2),"```"].join(`
|
|
5268
5269
|
`);return`${e}:
|
|
5269
5270
|
${o}`}function tB(t,e){let r=e.moduleId,n=o=>{o.type!=="RESOLVED_MODULE"||o.moduleId!==r||(e.parameters!==void 0&&(o.parameters=e.parameters),e.parameterEnums!==void 0&&(o.parameterEnums=e.parameterEnums),e.defaultParameters!==void 0&&(o.defaultParameters=e.defaultParameters),e.name!==void 0&&(o.name=e.name),e.description!==void 0&&(o.description=e.description),e.enabled!==void 0&&(o.enabled=e.enabled),e.steps!==void 0&&(o.steps=e.steps))};for(let o of[t.steps,t.beforeSteps??[],t.afterSteps??[]])ln({steps:o,onPresetAction:n,onConditional:n,onSimpleStepContainer:n})}async function jg({project:t,orgId:e,logger:r,testPath:n,socket:o,saveChangesToDisk:i,tempCaches:a,params:s,envName:c}){let l=await fe(t),u=await Ut(rB.join(t.rootDir,n),r,l),d={steps:u.steps??[],beforeSteps:u.beforeSteps??[],afterSteps:u.afterSteps??[]},p=await Promise.all(s.steps.map(b=>Pg(b,{project:t,logger:r,tempCaches:a}))),m=s.parentStepIdChain,f;try{f=fA(d,s.targetSection,m)}catch(b){return Pt(me({text:`Error: ${b.message}`,section:"Error"}))}if(s.startIndex<0||s.startIndex>f.length)return Pt(me({text:`Error: Invalid startIndex ${s.startIndex} for splicing ${s.targetSection} section with ${f.length} steps (must be 0-${f.length})`,section:"Error"}));let h=s.steps.length,S=s.deleteCount,g="Cannot add a module step inside another module. Modules cannot be nested.",E;try{E=Gg({logger:r,socket:o,baseState:d,recipe:I=>{let _;if(m?.length&&(_=EL(hA(I,s.targetSection),m,s.targetSection),_.some(P=>P.type==="RESOLVED_MODULE")&&p.some(P=>P.type==="RESOLVED_MODULE")))throw new Error(g);fA(I,s.targetSection,m).splice(s.startIndex,s.deleteCount,...p);for(let M of p)M.type==="RESOLVED_MODULE"&&tB(I,M);if(_)for(let M of _)M.type==="RESOLVED_MODULE"&&tB(I,M)},description:`Splice ${h} step(s) at index ${s.startIndex} in ${s.targetSection}, removing ${S}`}).newState}catch(b){if(b instanceof Error&&b.message===g)return Pt(me({text:`Error: ${b.message}`,section:"Error"}));throw b}if(i){let{stepsToSave:b,moduleUpdates:C}=await Ft({stepLists:E});C.forEach(I=>{Yn({content:I,schemaVersion:De,momenticFiles:l,project:t})}),Tn({relativeTestPath:n,steps:b,schemaVersion:De,project:t})}await E7({logger:r,project:t,orgId:e,testId:u.id,environment:c,originalSteps:d,updatedSteps:E});let y=[...me({text:`Successfully spliced ${h} step(s) at index ${s.startIndex} in the ${s.targetSection} section, removing ${S} step(s).`,section:"Result"})];if(s.returnTest)y.push(...me({text:JSON.stringify(await Lg({project:t,testPath:n,envName:c,logger:r}),null,2),section:"Test Content"}));else{let b=fA(E,s.targetSection,m),{windowStart:C,windowEndExclusive:I}=S7({sectionLength:b.length,startIndex:s.startIndex,insertedCount:h}),_=b.slice(C,I),M=_.length>0?`${C}-${I-1}`:"(no steps in window)";y.push(...me({text:[`Updated ${s.targetSection} section splice window (includes one step of context before/after when available).`,`Window index range in updated section: ${M}`,"",y7({steps:_,sectionLabel:"Changed Step Window",startIndexOffset:C})].join(`
|
|
5270
|
-
`),section:"Changed Steps"}))}return Pt(y)}async function Vg({project:t,logger:e,testPath:r,storage:n,controller:o,codeEvalTools:i,socket:a,orgId:s,envName:c,testContext:l,tracer:u,params:d,tokenLimit:p,supportsFileOutput:m}){let{fromStep:f,toStep:h,targetSection:S}=d,g=await fe(t),E=await Ut(rB.join(t.rootDir,r),e,g),y=new pt({baseUrl:qt(),apiKey:Cr(),logger:e}),b=await Er(e,y,t),{alwaysSaveCache:C,noCache:I}=Ns(),_=xo({logger:e,orgId:s,client:y,gitMetadata:b,regenerateCache:!1,alwaysSaveCache:C,noCache:I,isolateCachesByEnvironment:t.config?.advanced?.isolateCachesByEnvironment,bustOldestCachePercentage:void 0});try{await _.resolveStepCacheEntries({logger:e,schemaVersion:E.schemaVersion,stepLists:{beforeSteps:E.beforeSteps??[],afterSteps:E.afterSteps??[],steps:E.steps},testId:E.id,environment:c})}catch(te){e.warn({err:te},"Failed to resolve step cache entries, continuing without cache")}let R=hA(E,S),M=h7({steps:E.steps,beforeSteps:E.beforeSteps,afterSteps:E.afterSteps}),{result:P}=Ts(R,f.fromStepId,f.parentStepIdChain);if(!P)return Pt(me({text:`Error: No step found with id "${f.fromStepId}" and parent chain [${f.parentStepIdChain.join(", ")}] in ${S} section.`,section:"Error"}));if(h){let{result:te}=Ts(R,h.toStepId,h.parentStepIdChain);if(!te)return Pt(me({text:`Error: No step found with id "${h.toStepId}" and parent chain [${h.parentStepIdChain.join(", ")}] in ${S} section.`,section:"Error"}))}if(u?.setProgressTotal){let te=eB({steps:R,fromStep:f,toStep:h});u.setProgressTotal(te)}o.setOpen();let{results:B}=await tA({steps:R,controller:o,storage:n,codeEvalTools:i,logger:e,socket:a,orgId:s,testContext:l,fromStep:f,toStep:h,tracer:u});if(!B||B.length===0)return Pt(me({text:"Error: No steps were executed.",section:"Error"}));let F=B.at(-1);if(!F)return Pt(me({text:"Error: No steps were executed.",section:"Error"}));let G={logger:e,cacheStorage:_,orgId:s,testId:E.id,environment:c,originalStepsWithCaches:M,updatedStepsWithCaches:{steps:E.steps,beforeSteps:E.beforeSteps??[],afterSteps:E.afterSteps??[]}},z=F.status!=="SUCCESS";if(z)F.status==="FAILED"&&await Sc(G);else try{await vs(G)}catch(te){e.warn({err:te},"Failed to save step cache after execution, future runs may be slower")}let ae=S==="main"?"":` in ${S}`,W=te=>{let be="fromStepId"in te?te.fromStepId:te.toStepId;return te.parentStepIdChain.length>0?`id "${be}" (parent chain [${te.parentStepIdChain.join(", ")}])`:`id "${be}"`},q=f?W(f):"beginning",X=h?`Steps from ${q} through ${W(h)}${ae}`:`Steps from ${q} to end${ae}`,ne=[];if(z)ne.push(...me({text:`Error: step with id ${F.id} failed: ${F.message}`,section:"Error"}));else{o.setOpen();let te=`${X} executed successfully.`;ne.push(...me({text:te,section:"Result"})),F.data&&ne.push(...me({text:`Data: ${JSON.stringify(F.data,null,2)}`,section:"Result Data"}))}let[de,Te]=await Promise.all([Fr({browser:o.browser,supportsFileOutput:m}),io({testContext:l,supportsFileOutput:m,limits:{tokenLimit:p}})]);return Pt([...ne,...de,...Te])}async function E7({logger:t,project:e,orgId:r,testId:n,environment:o,originalSteps:i,updatedSteps:a}){try{let s=new pt({baseUrl:qt(),apiKey:Cr(),logger:t}),c=await Er(t,s,e),{alwaysSaveCache:l,noCache:u}=Ns(),d=xo({logger:t,orgId:r,client:s,gitMetadata:c,regenerateCache:!1,alwaysSaveCache:l,noCache:u,isolateCachesByEnvironment:e.config?.advanced?.isolateCachesByEnvironment,bustOldestCachePercentage:void 0});await vs({logger:t,cacheStorage:d,orgId:r,testId:n,environment:o,originalStepsWithCaches:i,updatedStepsWithCaches:a})}catch(s){t.warn({err:s},"Failed to save step caches after execution, future runs may be slower")}}var gA=class{constructor(e,r,n,o){this.reporter=e;this.step=r;this.parentStepIdChain=n;this.setTotal=o}loggerBindings;attachBeforeScreenshot(e){}attachAfterScreenshot(e){}attachBeforeHtmlSnapshot(e){}attachAfterHtmlSnapshot(e){}recordTargetAutoHeal(e){}recordStepDuration(e){}storeTraceAsset(){}async finish(e){this.reporter.onStepComplete(this.step)}async startSubSteps(){return new Wg(this.reporter,this.parentStepIdChain.concat(this.step.id),this.setTotal)}},Wg=class{constructor(e,r=[],n){this.reporter=e;this.parentStepIdChain=r;this.setTotal=n}loggerBindings;setProgressTotal(e){this.setTotal(e)}async getScreenshot(e,r){}async getHtmlSnapshot(e,r){}async startStep(e){return this.reporter.onStepStart(e.step),new gA(this.reporter,e.step,this.parentStepIdChain,this.setTotal)}};function nB(t,e,r,n){let o=jv(t),i={completed:0,total:0},a=new AbortController,s=!1,c=p=>{o&&bU(t,i,p,e,a,r)},l=()=>{o&&(s||(s=!0,c("Starting step execution...")))},u=p=>{!Number.isFinite(p)||p<0||(i.total=p)},d={onStepStart:p=>{l(),i.total===i.completed&&(i.total+=1),c(`Starting: ${Kn(p)}`)},onStepComplete:p=>{n(),l(),i.completed+=1,i.total<i.completed&&(i.total=i.completed),c(`Completed: ${Kn(p)}`)}};return new Wg(d,[],u)}var T7=Zt({schema:{name:TI,description:"Create a test. The name must satisfy Momentic entity naming rules, and you must provide either a baseUrl or environment or the tool will fail.",inputSchema:lE},handle:async(t,e,r,n)=>{let{project:o}=t;try{let i=await cp({project:o,input:e});r.addPartFromText(JSON.stringify(i,null,2))}catch(i){r.addError(Yt(i));return}}}),b7=Zt({schema:{name:EI,description:"List local test attributes. Prints tests and environments as inline JSON with { tests: [...], environments: [...] }, or writes separate Tests and Environments JSON artifacts when file output is enabled.",inputSchema:{}},handle:async(t,e,r,n)=>{let{project:o,logger:i}=t,a=await fe(o),s=Object.values(a.tests).map(u=>({id:u.id,name:u.name,description:u.description,testFileAbsolutePath:u.fullFilePath,labels:u.labels||[]})),c=xh(o,i),l=await hU({artifacts:[{title:"Tests",entity:"test-list",payload:{tests:s}},{title:"Environments",entity:"environment-list",payload:{environments:c}}],rootDir:o.rootDir,supportsFileOutput:t.supportsFileOutput});r.addContentParts(l)}}),oB=Zt({schema:{name:xI,description:"Execute a step without adding it to the test.",inputSchema:{sessionId:ao.string(),step:ao.string().describe(`CLI-style step definition. Use data returned from the ${ls} tool to get the full step schema.`)}},handle:async(t,e,r,n)=>{let{sessionId:o,step:i}=e,a=Vs(r,o);if(!a)return;a.controller.setOpen();let s=await Ug({project:t.project,step:i,logger:t.logger,storage:a.storage,controller:a.controller,codeEvalTools:a.codeEvalTools,orgId:a.orgId,testContext:a.context,supportsFileOutput:t.supportsFileOutput,tempCaches:a.tempCaches});r.addContentParts(s)}}),iB=Zt({schema:{name:bI,description:"Insert, delete, or replace steps in the test by index. Use parentStepIdChain to splice into nested steps (e.g. inside a conditional or module).",inputSchema:{sessionId:ao.string(),startIndex:ao.number(),deleteCount:ao.number().describe("Number of steps to remove. Use 0 to insert without deleting, 1 to replace a single step, or N to delete N steps."),steps:ao.array(ao.string()).describe(`CLI-style definition of steps to insert. Use data returned from the ${ls} tool to get the full step schema.`),targetSection:$a.default("main"),parentStepIdChain:ao.array(ao.string()).optional().describe("When splicing into a nested step (e.g. conditional or module), the chain of parent step ids from root to the container. Empty or omit for top-level."),returnTest:ao.boolean().default(!1).describe("Whether or not you want to see the full test after the splice is complete")}},handle:async(t,e,r,n)=>{let o=Vs(r,e.sessionId);if(!o)return;let a=(await jg({project:t.project,orgId:o.orgId,logger:t.logger,testPath:o.relativeTestPath,envName:o.envName,saveChangesToDisk:t.saveChangesToDisk,tempCaches:o.tempCaches,params:{startIndex:e.startIndex,deleteCount:e.deleteCount,steps:e.steps,targetSection:e.targetSection,parentStepIdChain:e.parentStepIdChain,returnTest:e.returnTest}})).value.map(s=>s.type==="media"?{type:"media",data:s.data,mediaType:"image/jpeg"}:s);r.addContentParts(a)}}),aB=Zt({schema:{name:vI,description:"Run one or more steps from the test bound to an active session.",inputSchema:{sessionId:ao.string(),fromStep:cm,toStep:um.optional(),targetSection:$a.default("main"),resetSession:ao.boolean().default(!1).describe("Whether to reset the browser session before running the steps.")}},handle:async(t,e,r,n)=>{let o=Vs(r,e.sessionId);if(!o)return;o.controller.setOpen(),e.resetSession&&await Ng({project:t.project,logger:t.logger,testPath:o.relativeTestPath,orgId:o.orgId,storage:o.storage,apiKey:Cr(),baseUrl:qt(),controller:o.controller,testContext:o.context,supportsFileOutput:t.supportsFileOutput});let i=nB(n,t.logger,r,()=>{oi.touchSession(o.sessionId)}),s=(await Vg({project:t.project,logger:t.logger,testPath:o.relativeTestPath,storage:o.storage,controller:o.controller,codeEvalTools:o.codeEvalTools,orgId:o.orgId,testContext:o.context,tracer:i,params:{fromStep:e.fromStep,toStep:e.toStep,targetSection:e.targetSection},supportsFileOutput:t.supportsFileOutput,envName:o.envName})).value.map(c=>c.type==="media"?{type:"media",data:c.data,mediaType:"image/jpeg"}:c);r.addContentParts(s)}}),sB=[b7,T7];var lB=[FU,UU,BU,zU,HU,oB,aB,iB];import{z as Rr}from"zod";import A7 from"fs";import Sp from"path";import v7 from"fs";import Bc from"path";function cB(t){let e=t.subDir?Bc.join(t.project.rootDir,t.subDir):t.project.rootDir,r=`${dt(t.name)}.module.yaml`,n=Bc.join(e,r),o=Bc.relative(t.project.rootDir,n),i=v7.statSync(n);return{type:ye.MODULE,name:t.name,id:t.moduleId,description:t.description??void 0,relativePath:o,fullFilePath:n,platformSep:Bc.sep,fullPathSegments:n.split(Bc.sep),relativePathSegments:o.split(Bc.sep),fileName:r,lastModified:i.mtime,createdAt:i.birthtime}}async function C7({moduleMetadata:t,steps:e,momenticFiles:r,project:n}){let{stepsToSave:o}=await Ft({stepLists:{steps:e}});Yn({content:{...t,steps:o.steps},schemaVersion:De,momenticFiles:r,project:n})}async function $g({project:t,logger:e,testPath:r,socket:n,saveChangesToDisk:o,params:i}){go(i.name);let a=await fe(t),s;if(i.startIndex!==void 0&&r!==void 0){let f=Sp.isAbsolute(r)?r:Sp.join(t.rootDir,r);s=(await Ut(f,e,a)).steps}let{stepsToExtract:c,startIndex:l,endIndex:u}=CU({moduleName:i.name,existingModuleNames:Object.values(a.modules).map(f=>f.name),parameterNames:i.parameters,defaultParameters:i.defaultParameters,parameterEnums:i.parameterEnums,moduleInputs:i.moduleInputs,testPath:r,startIndex:i.startIndex,endIndex:i.endIndex,availableSteps:s,containsNestedModuleStep:SL}),d=i.subDir?Sp.join(t.rootDir,i.subDir):t.rootDir;i.subDir&&A7.mkdirSync(d,{recursive:!0});let p=await Rh({name:i.name,description:i.description??"",enabled:i.enabled??!0,steps:c,folder:d,project:t}),m=cB({project:t,name:i.name,moduleId:p.moduleId,subDir:i.subDir,description:p.description??void 0});if(a.modules[p.moduleId]=m,i.parameters!==void 0||i.defaultParameters!==void 0||i.parameterEnums!==void 0){let f={moduleId:p.moduleId,name:i.name,description:i.description??p.description,enabled:i.enabled??p.enabled,parameters:i.parameters??[],defaultParameters:i.defaultParameters,parameterEnums:i.parameterEnums};await C7({moduleMetadata:f,steps:c,momenticFiles:a,project:t}),p={...p,name:i.name,description:i.description??p.description,enabled:i.enabled??p.enabled,parameters:i.parameters??[],defaultParameters:i.defaultParameters,parameterEnums:i.parameterEnums}}if(i.startIndex!==void 0&&r!==void 0){let f=Sp.isAbsolute(r)?r:Sp.join(t.rootDir,r),h=await Ut(f,e,a),S={steps:h.steps??[],beforeSteps:h.beforeSteps??[],afterSteps:h.afterSteps??[]},g=await ap({stepType:"MODULE",moduleId:p.moduleId,inputs:Object.entries(i.moduleInputs??{}).map(([b,C])=>`${b}=${C}`)},{project:t,logger:e}),E=b=>{b.steps.splice(l,u-l,g)},{newState:y}=Gg({logger:e,socket:n,baseState:S,recipe:E,description:`Create module "${i.name}" from steps ${l}-${u-1}`});if(o){let{stepsToSave:b,moduleUpdates:C}=await Ft({stepLists:y});C.forEach(I=>{Yn({content:I,schemaVersion:De,momenticFiles:a,project:t})}),Tn({relativeTestPath:r,steps:b,schemaVersion:De,project:t})}}return{module:p}}var uB=Zt({schema:{name:yI,description:"Create a module. The name must satisfy Momentic entity naming rules or the tool will fail. If startIndex is provided, testPath is required and the specified test range is extracted into the module, then replaced with a module invocation in that test. endIndex may only be provided when startIndex is set.",inputSchema:{name:Rr.string().describe(ea),description:Rr.string(),enabled:Rr.boolean().default(!0),parameters:Rr.string().array().optional().describe("Array of parameter names for the module, e.g., ['apiKey', 'userId']."),defaultParameters:Rr.record(Rr.string(),Rr.string()).optional().describe("Default values for parameters, e.g., { 'apiKey': 'default123' }. Keys must match parameters."),parameterEnums:Rr.record(Rr.string(),Rr.string().array()).optional().describe("Enum options for parameters, e.g., { 'role': ['admin', 'user'] }. Keys must match parameters."),moduleInputs:Rr.record(Rr.string(),Rr.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 when extracting from a test."),subDir:Rr.string().optional().describe("Subdirectory to create the module in. If not provided, the module is created in the project root."),testPath:Rr.string().optional().describe("Relative path to the test to extract steps from. Required when startIndex is provided."),startIndex:Rr.number().optional().describe("Start index of steps to extract from the target test (0-based)."),endIndex:Rr.number().optional().describe("End index of steps to extract from the target test (exclusive). Only valid when startIndex is provided. If not provided, extracts just startIndex.")}},handle:async(t,e,r,n)=>{let{testPath:o,...i}=e;try{let a=lU({projectRoot:t.project.rootDir,filePath:o,pathLabel:"testPath"}),s=await $g({project:t.project,logger:t.logger,testPath:a,saveChangesToDisk:t.saveChangesToDisk,params:i});r.addPartFromText(JSON.stringify(s.module,null,2))}catch(a){r.addError(Yt(a))}}});var qg=[...sB,...kg,...lB,uB];var SA=async(t,e)=>{try{let{killed:r,failed:n}=await oi.killAllSessions(t);n.length>0?e.warn({failed:n,reason:t},"Some browser sessions failed to terminate on shutdown"):r.length>0&&e.info({killedCount:r.length,reason:t},"Terminated browser sessions on shutdown")}catch(r){e.warn({err:r,reason:t},"Failed to terminate browser sessions on shutdown")}};async function yA({project:t,logger:e,apiKey:r,serverUrl:n,cliVersion:o,applicationName:i="momentic-mcp-stdio-server",supportsFileOutput:a=!0,alwaysSaveCache:s=!1,noCache:c=!1,headfulBrowserDefault:l=!0,customHeaders:u,devicePixelRatio:d,sessionIdleTimeoutMinutes:p}){dc(e,!0),Zh(n),eg({alwaysSaveCache:s,noCache:c}),await tg(r),Pc(t,g=>Ct({configFilePath:g}));let m={serverId:R7(),applicationName:i,cliVersion:o},f=e.child({orgId:Kt(),userId:Jo(),...m}),h=new cn(t.config.ai?.agentConfig,{baseUrl:n,apiKey:r,logger:f,mode:"interactive"}),S={project:t,orgId:Kt(),logger:f,generator:h,serverId:m.serverId,saveChangesToDisk:!0,supportsFileOutput:a,headfulBrowserDefault:l,sessionIdleTimeoutMs:(p&&p>=1?p:wa)*60*1e3,customHeaders:u,devicePixelRatio:d};return AU({context:S,info:m,tools:qg,shutdownHandlers:[SA]})}import{Router as P7}from"express";import{Router as x7}from"express";import Tp from"fs";import Ep from"path";import{v4 as _7}from"uuid";import I7 from"yaml";import{hostname as w7}from"os";var yp="2.71.1",ut=ql({app:"desktop-server",hostname:w7(),disableConsoleLogs:!0,captureExceptions:!0}).child({cliVersion:yp});(async()=>{try{let t=await _i(ut);t.gitBranchName&&ut.addBinding("branch",t.gitBranchName)}catch{}})();var Xs=x7();async function Kg(t){return(await wh(t,ut)).map(n=>{let o=t.modules[n.moduleId];if(!o){v.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)}Xs.get("/",je(async(t,e)=>{let r=Re(),n=await fe(r),o=await Kg(n);e.status(200).json(o)}));Xs.get("/tests-join",je(async(t,e)=>{let r=Re(),n=await fe(r),o=await Kg(n),i={};for(let s of o)i[s.id]={...s,tests:[]};let a=await Promise.all(Object.values(n.tests).map(async s=>({id:s.id,name:s.name,relativePath:s.relativePath,test:await Ut(s.fullFilePath,ut,n)})));for(let{id:s,name:c,relativePath:l,test:u}of a){let d=new Set,p=[u.steps,u.beforeSteps,u.afterSteps];for(let m of p)ln({steps:m??[],onPresetAction:()=>{},onConditional:()=>{},onSimpleStepContainer:f=>{qS(f)&&d.add(f.moduleId)}});for(let m of d){let f=i[m];f&&f.tests.push({id:s,name:c,relativePath:l})}}e.status(200).json(i)}));Xs.post("/",je(async(t,e)=>{let r;try{r=o_.parse(t.body)}catch(s){e.status(400).json({error:`Invalid request body: ${s}`});return}try{go(r.name)}catch(s){e.status(400).json({error:`Invalid module name: ${s}`});return}let n=Re(),o=(await fe(n)).modules;if(Object.values(o).find(s=>s.name===r.name)){e.status(400).send(`A module with the name "${r.name}" already exists. Please choose a different name.`);return}let i=Ep.join(n.rootDir,r.folderPath??"");if(!Tp.existsSync(i)||!Tp.statSync(i).isDirectory()){e.status(400).json({error:`The folder configured for module creation '${i}' does not exist.`});return}let a=await Rh({...r,folder:i,project:n});e.status(201).json(a)}));Xs.get("/:moduleId",je(async(t,e)=>{if(!t.params.moduleId){e.status(400).json({error:"Missing moduleId in url path."});return}let r=await fe(Re()),n=r.modules[t.params.moduleId];if(!n){e.status(404).json({error:"Module not found."});return}try{let o=await wi(n,r,v);e.json(o)}catch(o){e.status(400).json({err:o})}}));Xs.post("/:moduleId/duplicate",je(async(t,e)=>{if(!t.params.moduleId){e.status(400).json({error:"Missing moduleId in url path."});return}let r;try{r=n_.parse(t.body)}catch(h){e.status(400).json({error:`Invalid request body: ${h}`});return}try{go(r.name)}catch(h){e.status(400).json({error:h.message});return}let n=Re(),o=await fe(n),i=o.modules[t.params.moduleId];if(!i){e.status(404).json({error:"Module not found."});return}if(Object.values(o.modules).find(h=>h.name===r.name)){e.status(400).send(`A module with the name "${r.name}" already exists. Please choose a different name.`);return}let a=await wi(i,o,v),s=Ep.join(n.rootDir,Ep.dirname(i.relativePath));if(!Tp.existsSync(s)||!Tp.statSync(s).isDirectory()){e.status(400).json({error:`The folder configured for module creation '${s}' does not exist.`});return}let c=dt(r.name),l=Ep.join(s,`${c}.module.yaml`),u=_7(),{stepsToSave:d}=await Ft({stepLists:{steps:a.steps},createNewCacheIds:!0}),p={fileType:ye.MODULE,schemaVersion:De,moduleId:u,name:r.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=I7.stringify(p);Tp.writeFileSync(l,m,"utf-8");let f={relativeFilePath:Ep.relative(n.rootDir,l)};e.status(201).json(f)}));Xs.patch("/:moduleId/metadata",je(async(t,e)=>{if(!t.params.moduleId){e.status(400).json({error:"Missing moduleId in url path."});return}let r;try{r=i_.parse(t.body)}catch(i){e.status(400).json({error:`Invalid request body: ${i}`});return}let n=Re(),o=await fe(n);PN({moduleId:t.params.moduleId,content:r,momenticFiles:o,logger:v,project:n}),e.status(201).json({message:"ok"})}));var dB=Xs;var pB=P7();pB.get("/",je(async(t,e)=>{let r=Re(),n=await fe(r),o=new Set;n?.tests&&Object.values(n.tests).forEach(l=>{l.labels?.forEach(u=>o.add(u))});let i=Array.from(o).sort(),a=Object.values(n.tests),s=await Kg(n),c={labels:i,tests:a,modules:s};e.status(200).json(c)}));var mB=pB;import{Router as M7}from"express";var EA=M7();EA.get("/",je((t,e)=>{let r=xh(Re(),ut);e.status(200).json(r)}));EA.get("/names",je((t,e)=>{let n=Re().config.environments?.map(o=>o.name)??[];e.status(200).json(n)}));var fB=EA;import{Router as O7}from"express";var hB=O7();hB.get("/",je((t,e)=>{let r={userId:Jo(),orgId:Kt(),cliVersion:yp??"0.0.0"};e.status(200).json(r)}));var gB=hB;import{StreamableHTTPServerTransport as L7}from"@modelcontextprotocol/sdk/server/streamableHttp.js";import{isInitializeRequest as N7}from"@modelcontextprotocol/sdk/types.js";import{randomUUID as yB}from"crypto";import{Router as D7}from"express";var TA="mcp-session-id",SB="MOMENTIC_SESSION_IDLE_TIMEOUT_MINUTES",Yg=D7();function k7(){let t=process.env[SB];if(!t)return wa*60*1e3;let e=Number.parseInt(t,10);return Number.isNaN(e)||e<1?(ut.warn({envVar:SB,rawValue:t,fallback:wa},"Invalid MCP session idle timeout env var; falling back to default"),wa*60*1e3):e*60*1e3}function F7(t,e){let r={serverId:yB(),applicationName:"momentic-mcp-desktop-server",cliVersion:yp??"0.0.0"},n=Re(),o=Cr(),i=qt(),a=ut.child({orgId:Kt(),userId:Jo(),...r}),s=zl(process.env.MOMENTIC_HEADFUL_BROWSER),c=new cn(n.config.ai?.agentConfig,{baseUrl:i,apiKey:o,logger:a,mode:"interactive"});return{context:{project:n,orgId:Kt(),logger:a,generator:c,serverId:r.serverId,saveChangesToDisk:!0,supportsFileOutput:e??!0,sessionIdleTimeoutMs:k7(),headfulBrowserDefault:t??s??!0},info:r}}var Li={};Yg.post("/",async(t,e)=>{let r=String(t.headers[TA]??"");try{if(r&&Li[r]){await Li[r].handleRequest(t,e,t.body);return}if(!r&&N7(t.body)){let{context:n,info:o}=F7(),i=Vv(n,o,qg),a=new L7({sessionIdGenerator:()=>yB(),enableDnsRebindingProtection:!1,onsessioninitialized:s=>{Li[s]=a}});a.onclose=()=>{let s=a.sessionId;s&&Li[s]&&delete Li[s],i.close().catch(()=>{})},await i.connect(a),await a.handleRequest(t,e,t.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})}});Yg.get("/",async(t,e)=>{let r=String(t.headers[TA]??"");if(!r||!Li[r]){e.status(400).send("Invalid or missing session ID");return}await Li[r].handleRequest(t,e)});Yg.delete("/",async(t,e)=>{let r=String(t.headers[TA]??"");if(!r||!Li[r]){e.status(400).send("Invalid or missing session ID");return}let n=Li[r];try{await n.handleRequest(t,e)}catch{e.headersSent||e.status(500).send("Error processing session termination")}});var EB=Yg;import{Router as U7}from"express";var TB=U7();TB.get("/:id",je(async(t,e)=>{let{id:r}=t.params;if(!r){e.status(400).json({error:"Missing ID"});return}let n=Ic();if(!n){e.status(500).json({error:"API client not initialized"});return}try{let{data:o,contentType:i}=await n.fetchOnDemandScreenshot(r);e.setHeader("Content-Type",i),e.status(200).send(o)}catch(o){ut.error({err:o,screenshotId:r},"Failed to proxy on-demand screenshot"),e.status(404).json({error:"Screenshot not found"})}}));var bB=TB;import{Router as B7}from"express";var Xg=B7();Xg.get("/",je(async(t,e)=>{let r=(await sb()).map(n=>({name:n.config.name,configFilePath:n.configFilePath}));e.status(200).json(r)}));Xg.get("/current",je((t,e)=>{let r=Re();if(!r){e.status(404).json({error:"No project found."});return}let n={name:r.config.name,configFilePath:r.configFilePath};e.status(200).json(n)}));Xg.post("/set",je(async(t,e)=>{let r;try{r=s_.parse(t.body)}catch(n){e.status(400).json({error:`Invalid request body: ${n}`});return}ut.info("Setting local project");try{let n=await Ct({configFilePath:r.configFilePath});Pc(n,o=>Ct({configFilePath:o}))}catch(n){e.status(400).json({error:`Error setting project: ${n}`});return}e.sendStatus(204)}));var vB=Xg;import{Router as z7}from"express";var AB=z7();AB.get("/",je((t,e)=>{let r=Re(),n={ai:r.config.ai,browser:r.config.browser,displayRoot:r.config.displayRoot};e.status(200).json(n)}));var CB=AB;import{streamText as uee}from"ai";import{Router as dee}from"express";import Qg from"fs";import Gc from"path";import{v4 as pee}from"uuid";import mee from"yaml";import{convertToModelMessages as X7,pruneMessages as J7,stepCountIs as Q7}from"ai";import Jg from"dedent";var zc="3",H7=Jg`
|
|
5271
|
+
`),section:"Changed Steps"}))}return Pt(y)}async function Vg({project:t,logger:e,testPath:r,storage:n,controller:o,codeEvalTools:i,socket:a,orgId:s,envName:c,testContext:l,tracer:u,params:d,tokenLimit:p,supportsFileOutput:m}){let{fromStep:f,toStep:h,targetSection:S}=d,g=await fe(t),E=await Ut(rB.join(t.rootDir,r),e,g),y=new pt({baseUrl:qt(),apiKey:Cr(),logger:e}),b=await Er(e,y,t),{alwaysSaveCache:C,noCache:I}=Ns(),_=xo({logger:e,orgId:s,client:y,gitMetadata:b,regenerateCache:!1,alwaysSaveCache:C,noCache:I,isolateCachesByEnvironment:t.config?.advanced?.isolateCachesByEnvironment,bustOldestCachePercentage:void 0});try{await _.resolveStepCacheEntries({logger:e,schemaVersion:E.schemaVersion,stepLists:{beforeSteps:E.beforeSteps??[],afterSteps:E.afterSteps??[],steps:E.steps},testId:E.id,environment:c})}catch(te){e.warn({err:te},"Failed to resolve step cache entries, continuing without cache")}let R=hA(E,S),M=h7({steps:E.steps,beforeSteps:E.beforeSteps,afterSteps:E.afterSteps}),{result:P}=Ts(R,f.fromStepId,f.parentStepIdChain);if(!P)return Pt(me({text:`Error: No step found with id "${f.fromStepId}" and parent chain [${f.parentStepIdChain.join(", ")}] in ${S} section.`,section:"Error"}));if(h){let{result:te}=Ts(R,h.toStepId,h.parentStepIdChain);if(!te)return Pt(me({text:`Error: No step found with id "${h.toStepId}" and parent chain [${h.parentStepIdChain.join(", ")}] in ${S} section.`,section:"Error"}))}if(u?.setProgressTotal){let te=eB({steps:R,fromStep:f,toStep:h});u.setProgressTotal(te)}o.setOpen();let{results:B}=await tA({steps:R,controller:o,storage:n,codeEvalTools:i,logger:e,socket:a,orgId:s,testContext:l,fromStep:f,toStep:h,tracer:u});if(!B||B.length===0)return Pt(me({text:"Error: No steps were executed.",section:"Error"}));let F=B.at(-1);if(!F)return Pt(me({text:"Error: No steps were executed.",section:"Error"}));let G={logger:e,cacheStorage:_,orgId:s,testId:E.id,environment:c,originalStepsWithCaches:M,updatedStepsWithCaches:{steps:E.steps,beforeSteps:E.beforeSteps??[],afterSteps:E.afterSteps??[]}},z=F.status!=="SUCCESS";if(z)F.status==="FAILED"&&await Sc(G);else try{await vs(G)}catch(te){e.warn({err:te},"Failed to save step cache after execution, future runs may be slower")}let ae=S==="main"?"":` in ${S}`,W=te=>{let be="fromStepId"in te?te.fromStepId:te.toStepId;return te.parentStepIdChain.length>0?`id "${be}" (parent chain [${te.parentStepIdChain.join(", ")}])`:`id "${be}"`},q=f?W(f):"beginning",X=h?`Steps from ${q} through ${W(h)}${ae}`:`Steps from ${q} to end${ae}`,ne=[];if(z)ne.push(...me({text:`Error: step with id ${F.id} failed: ${F.message}`,section:"Error"}));else{o.setOpen();let te=`${X} executed successfully.`;ne.push(...me({text:te,section:"Result"})),F.data&&ne.push(...me({text:`Data: ${JSON.stringify(F.data,null,2)}`,section:"Result Data"}))}let[de,Te]=await Promise.all([Fr({browser:o.browser,supportsFileOutput:m}),io({testContext:l,supportsFileOutput:m,limits:{tokenLimit:p}})]);return Pt([...ne,...de,...Te])}async function E7({logger:t,project:e,orgId:r,testId:n,environment:o,originalSteps:i,updatedSteps:a}){try{let s=new pt({baseUrl:qt(),apiKey:Cr(),logger:t}),c=await Er(t,s,e),{alwaysSaveCache:l,noCache:u}=Ns(),d=xo({logger:t,orgId:r,client:s,gitMetadata:c,regenerateCache:!1,alwaysSaveCache:l,noCache:u,isolateCachesByEnvironment:e.config?.advanced?.isolateCachesByEnvironment,bustOldestCachePercentage:void 0});await vs({logger:t,cacheStorage:d,orgId:r,testId:n,environment:o,originalStepsWithCaches:i,updatedStepsWithCaches:a})}catch(s){t.warn({err:s},"Failed to save step caches after execution, future runs may be slower")}}var gA=class{constructor(e,r,n,o){this.reporter=e;this.step=r;this.parentStepIdChain=n;this.setTotal=o}loggerBindings;attachBeforeScreenshot(e){}attachAfterScreenshot(e){}attachBeforeHtmlSnapshot(e){}attachAfterHtmlSnapshot(e){}recordTargetAutoHeal(e){}recordStepDuration(e){}storeTraceAsset(){}async finish(e){this.reporter.onStepComplete(this.step)}async startSubSteps(){return new Wg(this.reporter,this.parentStepIdChain.concat(this.step.id),this.setTotal)}},Wg=class{constructor(e,r=[],n){this.reporter=e;this.parentStepIdChain=r;this.setTotal=n}loggerBindings;setProgressTotal(e){this.setTotal(e)}async getScreenshot(e,r){}async getHtmlSnapshot(e,r){}async startStep(e){return this.reporter.onStepStart(e.step),new gA(this.reporter,e.step,this.parentStepIdChain,this.setTotal)}};function nB(t,e,r,n){let o=jv(t),i={completed:0,total:0},a=new AbortController,s=!1,c=p=>{o&&bU(t,i,p,e,a,r)},l=()=>{o&&(s||(s=!0,c("Starting step execution...")))},u=p=>{!Number.isFinite(p)||p<0||(i.total=p)},d={onStepStart:p=>{l(),i.total===i.completed&&(i.total+=1),c(`Starting: ${Kn(p)}`)},onStepComplete:p=>{n(),l(),i.completed+=1,i.total<i.completed&&(i.total=i.completed),c(`Completed: ${Kn(p)}`)}};return new Wg(d,[],u)}var T7=Zt({schema:{name:TI,description:"Create a test. The name must satisfy Momentic entity naming rules, and you must provide either a baseUrl or environment or the tool will fail.",inputSchema:lE},handle:async(t,e,r,n)=>{let{project:o}=t;try{let i=await cp({project:o,input:e});r.addPartFromText(JSON.stringify(i,null,2))}catch(i){r.addError(Yt(i));return}}}),b7=Zt({schema:{name:EI,description:"List local test attributes. Prints tests and environments as inline JSON with { tests: [...], environments: [...] }, or writes separate Tests and Environments JSON artifacts when file output is enabled.",inputSchema:{}},handle:async(t,e,r,n)=>{let{project:o,logger:i}=t,a=await fe(o),s=Object.values(a.tests).map(u=>({id:u.id,name:u.name,description:u.description,testFileAbsolutePath:u.fullFilePath,labels:u.labels||[]})),c=xh(o,i),l=await hU({artifacts:[{title:"Tests",entity:"test-list",payload:{tests:s}},{title:"Environments",entity:"environment-list",payload:{environments:c}}],rootDir:o.rootDir,supportsFileOutput:t.supportsFileOutput});r.addContentParts(l)}}),oB=Zt({schema:{name:xI,description:"Execute a step without adding it to the test.",inputSchema:{sessionId:ao.string(),step:ao.string().describe(`CLI-style step definition. Use data returned from the ${ls} tool to get the full step schema.`)}},handle:async(t,e,r,n)=>{let{sessionId:o,step:i}=e,a=Vs(r,o);if(!a)return;a.controller.setOpen();let s=await Ug({project:t.project,step:i,logger:t.logger,storage:a.storage,controller:a.controller,codeEvalTools:a.codeEvalTools,orgId:a.orgId,testContext:a.context,supportsFileOutput:t.supportsFileOutput,tempCaches:a.tempCaches});r.addContentParts(s)}}),iB=Zt({schema:{name:bI,description:"Insert, delete, or replace steps in the test by index. Use parentStepIdChain to splice into nested steps (e.g. inside a conditional or module).",inputSchema:{sessionId:ao.string(),startIndex:ao.number(),deleteCount:ao.number().describe("Number of steps to remove. Use 0 to insert without deleting, 1 to replace a single step, or N to delete N steps."),steps:ao.array(ao.string()).describe(`CLI-style definition of steps to insert. Use data returned from the ${ls} tool to get the full step schema.`),targetSection:$a.default("main"),parentStepIdChain:ao.array(ao.string()).optional().describe("When splicing into a nested step (e.g. conditional or module), the chain of parent step ids from root to the container. Empty or omit for top-level."),returnTest:ao.boolean().default(!1).describe("Whether or not you want to see the full test after the splice is complete")}},handle:async(t,e,r,n)=>{let o=Vs(r,e.sessionId);if(!o)return;let a=(await jg({project:t.project,orgId:o.orgId,logger:t.logger,testPath:o.relativeTestPath,envName:o.envName,saveChangesToDisk:t.saveChangesToDisk,tempCaches:o.tempCaches,params:{startIndex:e.startIndex,deleteCount:e.deleteCount,steps:e.steps,targetSection:e.targetSection,parentStepIdChain:e.parentStepIdChain,returnTest:e.returnTest}})).value.map(s=>s.type==="media"?{type:"media",data:s.data,mediaType:"image/jpeg"}:s);r.addContentParts(a)}}),aB=Zt({schema:{name:vI,description:"Run one or more steps from the test bound to an active session.",inputSchema:{sessionId:ao.string(),fromStep:cm,toStep:um.optional(),targetSection:$a.default("main"),resetSession:ao.boolean().default(!1).describe("Whether to reset the browser session before running the steps.")}},handle:async(t,e,r,n)=>{let o=Vs(r,e.sessionId);if(!o)return;o.controller.setOpen(),e.resetSession&&await Ng({project:t.project,logger:t.logger,testPath:o.relativeTestPath,orgId:o.orgId,storage:o.storage,apiKey:Cr(),baseUrl:qt(),controller:o.controller,testContext:o.context,supportsFileOutput:t.supportsFileOutput});let i=nB(n,t.logger,r,()=>{oi.touchSession(o.sessionId)}),s=(await Vg({project:t.project,logger:t.logger,testPath:o.relativeTestPath,storage:o.storage,controller:o.controller,codeEvalTools:o.codeEvalTools,orgId:o.orgId,testContext:o.context,tracer:i,params:{fromStep:e.fromStep,toStep:e.toStep,targetSection:e.targetSection},supportsFileOutput:t.supportsFileOutput,envName:o.envName})).value.map(c=>c.type==="media"?{type:"media",data:c.data,mediaType:"image/jpeg"}:c);r.addContentParts(s)}}),sB=[b7,T7];var lB=[FU,UU,BU,zU,HU,oB,aB,iB];import{z as Rr}from"zod";import A7 from"fs";import Sp from"path";import v7 from"fs";import Bc from"path";function cB(t){let e=t.subDir?Bc.join(t.project.rootDir,t.subDir):t.project.rootDir,r=`${dt(t.name)}.module.yaml`,n=Bc.join(e,r),o=Bc.relative(t.project.rootDir,n),i=v7.statSync(n);return{type:ye.MODULE,name:t.name,id:t.moduleId,description:t.description??void 0,relativePath:o,fullFilePath:n,platformSep:Bc.sep,fullPathSegments:n.split(Bc.sep),relativePathSegments:o.split(Bc.sep),fileName:r,lastModified:i.mtime,createdAt:i.birthtime}}async function C7({moduleMetadata:t,steps:e,momenticFiles:r,project:n}){let{stepsToSave:o}=await Ft({stepLists:{steps:e}});Yn({content:{...t,steps:o.steps},schemaVersion:De,momenticFiles:r,project:n})}async function $g({project:t,logger:e,testPath:r,socket:n,saveChangesToDisk:o,params:i}){go(i.name);let a=await fe(t),s;if(i.startIndex!==void 0&&r!==void 0){let f=Sp.isAbsolute(r)?r:Sp.join(t.rootDir,r);s=(await Ut(f,e,a)).steps}let{stepsToExtract:c,startIndex:l,endIndex:u}=CU({moduleName:i.name,existingModuleNames:Object.values(a.modules).map(f=>f.name),parameterNames:i.parameters,defaultParameters:i.defaultParameters,parameterEnums:i.parameterEnums,moduleInputs:i.moduleInputs,testPath:r,startIndex:i.startIndex,endIndex:i.endIndex,availableSteps:s,containsNestedModuleStep:SL}),d=i.subDir?Sp.join(t.rootDir,i.subDir):t.rootDir;i.subDir&&A7.mkdirSync(d,{recursive:!0});let p=await Rh({name:i.name,description:i.description??"",enabled:i.enabled??!0,steps:c,folder:d,project:t}),m=cB({project:t,name:i.name,moduleId:p.moduleId,subDir:i.subDir,description:p.description??void 0});if(a.modules[p.moduleId]=m,i.parameters!==void 0||i.defaultParameters!==void 0||i.parameterEnums!==void 0){let f={moduleId:p.moduleId,name:i.name,description:i.description??p.description,enabled:i.enabled??p.enabled,parameters:i.parameters??[],defaultParameters:i.defaultParameters,parameterEnums:i.parameterEnums};await C7({moduleMetadata:f,steps:c,momenticFiles:a,project:t}),p={...p,name:i.name,description:i.description??p.description,enabled:i.enabled??p.enabled,parameters:i.parameters??[],defaultParameters:i.defaultParameters,parameterEnums:i.parameterEnums}}if(i.startIndex!==void 0&&r!==void 0){let f=Sp.isAbsolute(r)?r:Sp.join(t.rootDir,r),h=await Ut(f,e,a),S={steps:h.steps??[],beforeSteps:h.beforeSteps??[],afterSteps:h.afterSteps??[]},g=await ap({stepType:"MODULE",moduleId:p.moduleId,inputs:Object.entries(i.moduleInputs??{}).map(([b,C])=>`${b}=${C}`)},{project:t,logger:e}),E=b=>{b.steps.splice(l,u-l,g)},{newState:y}=Gg({logger:e,socket:n,baseState:S,recipe:E,description:`Create module "${i.name}" from steps ${l}-${u-1}`});if(o){let{stepsToSave:b,moduleUpdates:C}=await Ft({stepLists:y});C.forEach(I=>{Yn({content:I,schemaVersion:De,momenticFiles:a,project:t})}),Tn({relativeTestPath:r,steps:b,schemaVersion:De,project:t})}}return{module:p}}var uB=Zt({schema:{name:yI,description:"Create a module. The name must satisfy Momentic entity naming rules or the tool will fail. If startIndex is provided, testPath is required and the specified test range is extracted into the module, then replaced with a module invocation in that test. endIndex may only be provided when startIndex is set.",inputSchema:{name:Rr.string().describe(ea),description:Rr.string(),enabled:Rr.boolean().default(!0),parameters:Rr.string().array().optional().describe("Array of parameter names for the module, e.g., ['apiKey', 'userId']."),defaultParameters:Rr.record(Rr.string(),Rr.string()).optional().describe("Default values for parameters, e.g., { 'apiKey': 'default123' }. Keys must match parameters."),parameterEnums:Rr.record(Rr.string(),Rr.string().array()).optional().describe("Enum options for parameters, e.g., { 'role': ['admin', 'user'] }. Keys must match parameters."),moduleInputs:Rr.record(Rr.string(),Rr.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 when extracting from a test."),subDir:Rr.string().optional().describe("Subdirectory to create the module in. If not provided, the module is created in the project root."),testPath:Rr.string().optional().describe("Relative path to the test to extract steps from. Required when startIndex is provided."),startIndex:Rr.number().optional().describe("Start index of steps to extract from the target test (0-based)."),endIndex:Rr.number().optional().describe("End index of steps to extract from the target test (exclusive). Only valid when startIndex is provided. If not provided, extracts just startIndex.")}},handle:async(t,e,r,n)=>{let{testPath:o,...i}=e;try{let a=lU({projectRoot:t.project.rootDir,filePath:o,pathLabel:"testPath"}),s=await $g({project:t.project,logger:t.logger,testPath:a,saveChangesToDisk:t.saveChangesToDisk,params:i});r.addPartFromText(JSON.stringify(s.module,null,2))}catch(a){r.addError(Yt(a))}}});var qg=[...sB,...kg,...lB,uB];var SA=async(t,e)=>{try{let{killed:r,failed:n}=await oi.killAllSessions(t);n.length>0?e.warn({failed:n,reason:t},"Some browser sessions failed to terminate on shutdown"):r.length>0&&e.info({killedCount:r.length,reason:t},"Terminated browser sessions on shutdown")}catch(r){e.warn({err:r,reason:t},"Failed to terminate browser sessions on shutdown")}};async function yA({project:t,logger:e,apiKey:r,serverUrl:n,cliVersion:o,applicationName:i="momentic-mcp-stdio-server",supportsFileOutput:a=!0,alwaysSaveCache:s=!1,noCache:c=!1,headfulBrowserDefault:l=!0,customHeaders:u,devicePixelRatio:d,sessionIdleTimeoutMinutes:p}){dc(e,!0),Zh(n),eg({alwaysSaveCache:s,noCache:c}),await tg(r),Pc(t,g=>Ct({configFilePath:g}));let m={serverId:R7(),applicationName:i,cliVersion:o},f=e.child({orgId:Kt(),userId:Jo(),...m}),h=new cn(t.config.ai?.agentConfig,{baseUrl:n,apiKey:r,logger:f,mode:"interactive"}),S={project:t,orgId:Kt(),logger:f,generator:h,serverId:m.serverId,saveChangesToDisk:!0,supportsFileOutput:a,headfulBrowserDefault:l,sessionIdleTimeoutMs:(p&&p>=1?p:wa)*60*1e3,customHeaders:u,devicePixelRatio:d};return AU({context:S,info:m,tools:qg,shutdownHandlers:[SA]})}import{Router as P7}from"express";import{Router as x7}from"express";import Tp from"fs";import Ep from"path";import{v4 as _7}from"uuid";import I7 from"yaml";import{hostname as w7}from"os";var yp="2.71.2",ut=ql({app:"desktop-server",hostname:w7(),disableConsoleLogs:!0,captureExceptions:!0}).child({cliVersion:yp});(async()=>{try{let t=await _i(ut);t.gitBranchName&&ut.addBinding("branch",t.gitBranchName)}catch{}})();var Xs=x7();async function Kg(t){return(await wh(t,ut)).map(n=>{let o=t.modules[n.moduleId];if(!o){v.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)}Xs.get("/",je(async(t,e)=>{let r=Re(),n=await fe(r),o=await Kg(n);e.status(200).json(o)}));Xs.get("/tests-join",je(async(t,e)=>{let r=Re(),n=await fe(r),o=await Kg(n),i={};for(let s of o)i[s.id]={...s,tests:[]};let a=await Promise.all(Object.values(n.tests).map(async s=>({id:s.id,name:s.name,relativePath:s.relativePath,test:await Ut(s.fullFilePath,ut,n)})));for(let{id:s,name:c,relativePath:l,test:u}of a){let d=new Set,p=[u.steps,u.beforeSteps,u.afterSteps];for(let m of p)ln({steps:m??[],onPresetAction:()=>{},onConditional:()=>{},onSimpleStepContainer:f=>{qS(f)&&d.add(f.moduleId)}});for(let m of d){let f=i[m];f&&f.tests.push({id:s,name:c,relativePath:l})}}e.status(200).json(i)}));Xs.post("/",je(async(t,e)=>{let r;try{r=o_.parse(t.body)}catch(s){e.status(400).json({error:`Invalid request body: ${s}`});return}try{go(r.name)}catch(s){e.status(400).json({error:`Invalid module name: ${s}`});return}let n=Re(),o=(await fe(n)).modules;if(Object.values(o).find(s=>s.name===r.name)){e.status(400).send(`A module with the name "${r.name}" already exists. Please choose a different name.`);return}let i=Ep.join(n.rootDir,r.folderPath??"");if(!Tp.existsSync(i)||!Tp.statSync(i).isDirectory()){e.status(400).json({error:`The folder configured for module creation '${i}' does not exist.`});return}let a=await Rh({...r,folder:i,project:n});e.status(201).json(a)}));Xs.get("/:moduleId",je(async(t,e)=>{if(!t.params.moduleId){e.status(400).json({error:"Missing moduleId in url path."});return}let r=await fe(Re()),n=r.modules[t.params.moduleId];if(!n){e.status(404).json({error:"Module not found."});return}try{let o=await wi(n,r,v);e.json(o)}catch(o){e.status(400).json({err:o})}}));Xs.post("/:moduleId/duplicate",je(async(t,e)=>{if(!t.params.moduleId){e.status(400).json({error:"Missing moduleId in url path."});return}let r;try{r=n_.parse(t.body)}catch(h){e.status(400).json({error:`Invalid request body: ${h}`});return}try{go(r.name)}catch(h){e.status(400).json({error:h.message});return}let n=Re(),o=await fe(n),i=o.modules[t.params.moduleId];if(!i){e.status(404).json({error:"Module not found."});return}if(Object.values(o.modules).find(h=>h.name===r.name)){e.status(400).send(`A module with the name "${r.name}" already exists. Please choose a different name.`);return}let a=await wi(i,o,v),s=Ep.join(n.rootDir,Ep.dirname(i.relativePath));if(!Tp.existsSync(s)||!Tp.statSync(s).isDirectory()){e.status(400).json({error:`The folder configured for module creation '${s}' does not exist.`});return}let c=dt(r.name),l=Ep.join(s,`${c}.module.yaml`),u=_7(),{stepsToSave:d}=await Ft({stepLists:{steps:a.steps},createNewCacheIds:!0}),p={fileType:ye.MODULE,schemaVersion:De,moduleId:u,name:r.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=I7.stringify(p);Tp.writeFileSync(l,m,"utf-8");let f={relativeFilePath:Ep.relative(n.rootDir,l)};e.status(201).json(f)}));Xs.patch("/:moduleId/metadata",je(async(t,e)=>{if(!t.params.moduleId){e.status(400).json({error:"Missing moduleId in url path."});return}let r;try{r=i_.parse(t.body)}catch(i){e.status(400).json({error:`Invalid request body: ${i}`});return}let n=Re(),o=await fe(n);PN({moduleId:t.params.moduleId,content:r,momenticFiles:o,logger:v,project:n}),e.status(201).json({message:"ok"})}));var dB=Xs;var pB=P7();pB.get("/",je(async(t,e)=>{let r=Re(),n=await fe(r),o=new Set;n?.tests&&Object.values(n.tests).forEach(l=>{l.labels?.forEach(u=>o.add(u))});let i=Array.from(o).sort(),a=Object.values(n.tests),s=await Kg(n),c={labels:i,tests:a,modules:s};e.status(200).json(c)}));var mB=pB;import{Router as M7}from"express";var EA=M7();EA.get("/",je((t,e)=>{let r=xh(Re(),ut);e.status(200).json(r)}));EA.get("/names",je((t,e)=>{let n=Re().config.environments?.map(o=>o.name)??[];e.status(200).json(n)}));var fB=EA;import{Router as O7}from"express";var hB=O7();hB.get("/",je((t,e)=>{let r={userId:Jo(),orgId:Kt(),cliVersion:yp??"0.0.0"};e.status(200).json(r)}));var gB=hB;import{StreamableHTTPServerTransport as L7}from"@modelcontextprotocol/sdk/server/streamableHttp.js";import{isInitializeRequest as N7}from"@modelcontextprotocol/sdk/types.js";import{randomUUID as yB}from"crypto";import{Router as D7}from"express";var TA="mcp-session-id",SB="MOMENTIC_SESSION_IDLE_TIMEOUT_MINUTES",Yg=D7();function k7(){let t=process.env[SB];if(!t)return wa*60*1e3;let e=Number.parseInt(t,10);return Number.isNaN(e)||e<1?(ut.warn({envVar:SB,rawValue:t,fallback:wa},"Invalid MCP session idle timeout env var; falling back to default"),wa*60*1e3):e*60*1e3}function F7(t,e){let r={serverId:yB(),applicationName:"momentic-mcp-desktop-server",cliVersion:yp??"0.0.0"},n=Re(),o=Cr(),i=qt(),a=ut.child({orgId:Kt(),userId:Jo(),...r}),s=zl(process.env.MOMENTIC_HEADFUL_BROWSER),c=new cn(n.config.ai?.agentConfig,{baseUrl:i,apiKey:o,logger:a,mode:"interactive"});return{context:{project:n,orgId:Kt(),logger:a,generator:c,serverId:r.serverId,saveChangesToDisk:!0,supportsFileOutput:e??!0,sessionIdleTimeoutMs:k7(),headfulBrowserDefault:t??s??!0},info:r}}var Li={};Yg.post("/",async(t,e)=>{let r=String(t.headers[TA]??"");try{if(r&&Li[r]){await Li[r].handleRequest(t,e,t.body);return}if(!r&&N7(t.body)){let{context:n,info:o}=F7(),i=Vv(n,o,qg),a=new L7({sessionIdGenerator:()=>yB(),enableDnsRebindingProtection:!1,onsessioninitialized:s=>{Li[s]=a}});a.onclose=()=>{let s=a.sessionId;s&&Li[s]&&delete Li[s],i.close().catch(()=>{})},await i.connect(a),await a.handleRequest(t,e,t.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})}});Yg.get("/",async(t,e)=>{let r=String(t.headers[TA]??"");if(!r||!Li[r]){e.status(400).send("Invalid or missing session ID");return}await Li[r].handleRequest(t,e)});Yg.delete("/",async(t,e)=>{let r=String(t.headers[TA]??"");if(!r||!Li[r]){e.status(400).send("Invalid or missing session ID");return}let n=Li[r];try{await n.handleRequest(t,e)}catch{e.headersSent||e.status(500).send("Error processing session termination")}});var EB=Yg;import{Router as U7}from"express";var TB=U7();TB.get("/:id",je(async(t,e)=>{let{id:r}=t.params;if(!r){e.status(400).json({error:"Missing ID"});return}let n=Ic();if(!n){e.status(500).json({error:"API client not initialized"});return}try{let{data:o,contentType:i}=await n.fetchOnDemandScreenshot(r);e.setHeader("Content-Type",i),e.status(200).send(o)}catch(o){ut.error({err:o,screenshotId:r},"Failed to proxy on-demand screenshot"),e.status(404).json({error:"Screenshot not found"})}}));var bB=TB;import{Router as B7}from"express";var Xg=B7();Xg.get("/",je(async(t,e)=>{let r=(await sb()).map(n=>({name:n.config.name,configFilePath:n.configFilePath}));e.status(200).json(r)}));Xg.get("/current",je((t,e)=>{let r=Re();if(!r){e.status(404).json({error:"No project found."});return}let n={name:r.config.name,configFilePath:r.configFilePath};e.status(200).json(n)}));Xg.post("/set",je(async(t,e)=>{let r;try{r=s_.parse(t.body)}catch(n){e.status(400).json({error:`Invalid request body: ${n}`});return}ut.info("Setting local project");try{let n=await Ct({configFilePath:r.configFilePath});Pc(n,o=>Ct({configFilePath:o}))}catch(n){e.status(400).json({error:`Error setting project: ${n}`});return}e.sendStatus(204)}));var vB=Xg;import{Router as z7}from"express";var AB=z7();AB.get("/",je((t,e)=>{let r=Re(),n={ai:r.config.ai,browser:r.config.browser,displayRoot:r.config.displayRoot};e.status(200).json(n)}));var CB=AB;import{streamText as uee}from"ai";import{Router as dee}from"express";import Qg from"fs";import Gc from"path";import{v4 as pee}from"uuid";import mee from"yaml";import{convertToModelMessages as X7,pruneMessages as J7,stepCountIs as Q7}from"ai";import Jg from"dedent";var zc="3",H7=Jg`
|
|
5271
5272
|
<ai-actions>
|
|
5272
5273
|
AI actions (--step-type AI_ACTION) are special steps that dynamically generate up to 15 sub-steps to achieve a complex goal. They are useful for:
|
|
5273
5274
|
- Multi-step workflows that require decision-making (e.g., "Find and click the first available appointment slot")
|
|
@@ -5569,7 +5570,7 @@ ${t.map(p=>`${It}- ${p}`).join(`
|
|
|
5569
5570
|
`))}async function kz({test:t,reason:e,apiClient:r,project:n,identity:o}){let i=(await fe(n)).tests,a=Object.values(i),s=(await r.getQuarantinedTests()).quarantined,c=new Set(s.map(p=>p.testId)),l=a.filter(p=>c.has(p.id)),u=await lS({prompt:"Select a test to unquarantine.",inputtedTest:t,testOptions:l}),d=await cS({prompt:"Enter a reason for unquarantining the test.",inputtedReason:e});await r.unquarantineTest(u,d,o),v.success(`Test ${u.name} has been successfully removed from quarantine.`)}function Fz(t){return t?dt(t):"Unknown suite"}async function Uz({client:t,orgId:e,suitePaths:r,wait:n,waitTimeout:o,...i}){let{suiteRunIds:a,runGroupIds:s}=await t.queueSuiteRuns({paths:r,...i});le.info({orgId:e,suiteRunIds:a,runGroupIds:s,suitePaths:r},"Queued suites remotely"),v.dimmed(`Queued ${r.length} suites.`),n||process.exit(0);let c=Date.now();v.dimmed(`Waiting for ${r.length} suites to finish. You can view results upon completion at:`);for(let S of s)v.dimmed(`${It}- ${t.getAppUrl()}/run-groups/${S}`);let l=new Set,u=[],d=S=>(S.status==="FAILED"||S.status==="PASSED"||S.status==="CANCELLED")&&S.runs.every(E=>E.status==="FAILED"&&(E.failureReason||E.finishedAt&&Date.now()-E.finishedAt.getTime()>30*1e3)||E.status==="PASSED"||E.status==="CANCELLED"),p=await Zf({name:"suites",getResults:async()=>{let S=s.filter(y=>!u.some(b=>b.id===y)),g=await t.bulkGetRunGroupStatus(S),E=[];for(let y of g)d(y)?u.push(y):E.push(y);return[...u,...E]},timeoutMs:o?o*1e3:void 0,checkDone:S=>(S.forEach(g=>{g.status==="RUNNING"&&(l.has(g.id)||(l.add(g.id),v.log(`${l.size}/${s.length} ${Fz(g.suite?.name)}`)))}),S.every(d))}),m=t.getAppUrl(),h=cc({results:p,startTime:c,onFailed:S=>{let g=Fz(S.suite?.name),E=S.runs.filter(b=>b.status==="FAILED").length,y=S.runs.length;v.error(`${g} (${E}/${y} tests failed):`);for(let b of S.runs)if(b.status==="FAILED"){let C=b.testName||b.test?.name;v.error(` ${C?dt(C):"Unknown test"} (${m}/runs/${b.id})`)}},entity:"suite",getDisplayLine:S=>` ${S.suite?.name?dt(S.suite.name):"Unknown suite name"} (${m}/run-groups/${S.id})`});process.exit(h.failed>0?1:0)}async function Bz({tests:t,client:e,orgId:r,...n}){!n.yes&&!await yr(`This command will queue ${t.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:t,...n});if(le.info({queuedTests:o,runIds:i,orgId:r},"Queued tests remotely"),v.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;v.dimmed(`Waiting for ${o.length} tests to complete.`);let a=new Set,s=[],c=m=>m.status==="FAILED"&&m.failureReason||m.status==="PASSED"||m.status==="CANCELLED",l=e.getAppUrl(),u=Date.now(),d=await Zf({name:"runs",getResults:async()=>{let m=i.filter(S=>!s.some(g=>g.id===S)),f=await e.bulkGetRunStatus(m),h=[];for(let S of f)c(S)?s.push(S):h.push(S);return[...s,...h]},timeoutMs:n.waitTimeout?n.waitTimeout*1e3:void 0,checkDone:m=>(m.forEach(f=>{if(f.status==="RUNNING"&&!a.has(f.id)){a.add(f.id);let h=f.testName||f.test?.name;h&&v.log(`${a.size}/${o.length} ${dt(h)}`)}}),m.every(c))}),p=cc({results:d,startTime:u,onFailed:m=>{let f=m.testName||m.test?.name;eh(m,f?dt(f):"Unknown test")},getDisplayLine:m=>{let f=m.testName||m.test?.name,h=` ${f?dt(f):"Unknown test"}`;return m.id&&(h+=` (${l}/runs/${m.id})`),h},entity:"test"});process.exit(p.failed>0?1:0)}import{randomUUID as Nte}from"crypto";import Dte from"fs";import{existsSync as cte,mkdirSync as ute,statSync as dte}from"fs";import{randomUUID as Qs}from"crypto";import $c,{writeFileSync as zz}from"fs";import{hostname as Gee}from"os";import ii from"path";import{z as uS}from"zod";async function pS(t,e,r,n){if(n){let o=await e.getScreenshot(t,n);if(o){let i=`screenshot-${n}.jpeg`,a=ii.join(r,i);return $c.writeFileSync(a,o),i}}}async function jee(t,e,r,n){let o=r.folder,i={uuid:n.runAttemptId??Qs(),historyId:n.runId??Qs(),testCaseId:n.test.id,fullName:n.test.name,name:dt(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:r.suiteName},{name:"host",value:Gee()},{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}`}),n.quarantined&&i.labels.push({name:"quarantined",value:"true"}),n.quarantinedMetadata?.quarantinedReason&&i.labels.push({name:"quarantinedReason",value:n.quarantinedMetadata.quarantinedReason}),n.quarantinedMetadata?.quarantinedAt&&i.labels.push({name:"quarantinedAt",value:n.quarantinedMetadata.quarantinedAt.toISOString()});for(let[c,l]of Object.entries(n.parameters))l!=null&&i.parameters.push({name:c,value:JSON.stringify(l)});n.results&&await VA(t,e,r.folder,i.steps,n.results);let a=Vee(e,o,i.uuid);a.length>0&&(i.attachments=a);let s=`${n.runAttemptId}-result.json`;$c.writeFileSync(ii.join(o,s),JSON.stringify(i,void 0,2))}async function dS(t,e,r,n){let o={name:iN(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 pS(t,e,r,n.beforeSnapshot);i&&o.attachments.push({name:"Screenshot before step",source:i,type:"image/jpeg"});let a=await pS(t,e,r,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)if(su.safeParse(n.data).success){let s=su.parse(n.data),c=s.request,l={...s,request:void 0},u=`output-attachment-api-request-${Qs()}.json`,d=`output-attachment-api-response-${Qs()}.json`,p=ii.join(r,u),m=ii.join(r,d);$c.writeFileSync(p,JSON.stringify(c,null,2)),$c.writeFileSync(m,JSON.stringify(l,null,2)),o.attachments.push({name:"API request details",source:u,type:"application/json"}),o.attachments.push({name:"API response details",source:d,type:"application/json"})}else{let s=uS.union([uS.object({}).passthrough(),uS.array(uS.any())]).safeParse(n.data).success,c=`output-attachment-${Qs()}.json`,l=ii.join(r,c);$c.writeFileSync(l,JSON.stringify(n.data,null,2)),o.attachments.push({name:"Step output data",source:c,type:s?"application/json":"text/plain"})}return o}async function VA(t,e,r,n,o){for(let i of o){let a;switch(i.type){case"PRESET_ACTION":{a=await dS(t,e,r,i);break}case"CONDITIONAL":{a=await dS(t,e,r,i),a.steps=[],i.assertionResult&&a.steps.push(await dS(t,e,r,i.assertionResult)),await VA(t,e,r,a.steps,i.results);break}case"AI_ACTION_DYNAMIC":case"AI_ACTION":case"SECTION":case"MODULE":{if(a=await dS(t,e,r,i),await VA(t,e,r,a.steps,i.results),i.type==="MODULE"&&i.inputs){a.parameters=[];for(let[s,c]of Object.entries(i.inputs))a.parameters.push({name:s,value:c})}break}default:{let s=i}}if(!a){t.warn({result:i},"Failed to convert Momentic result to Allure step");continue}if(a.attachments||(a.attachments=[]),i.beforeTestContext){let s=`before-context-${Qs()}.json`,c=ii.join(r,s);zz(c,Hz(i.beforeTestContext.env)),a.attachments.push({name:"Test context before step",source:s,type:"application/json"})}if(i.afterTestContext){let s=`after-context-${Qs()}.json`,c=ii.join(r,s);zz(c,Hz(i.afterTestContext.env)),a.attachments.push({name:"Test context after step",source:s,type:"application/json"})}n.push(a)}}async function Gz(t,e,r,n,o){for(let i of o){if(!i.runId||!i.runAttemptId)throw new Error(`Missing runId/runAttemptId for Allure report generation for test '${i.test.name}'`);let a=e.createDebugDataReaderForRunAttempt(i.runId,i.runAttemptId);try{await jee(t,a,{folder:r,suiteName:n.suiteName},i)}finally{a.close()}}}function Hz(t){try{return JSON.stringify(t,void 0,2)??JSON.stringify({value:null},void 0,2)}catch(e){let r=e instanceof Error?e.message:"unknown error";return JSON.stringify({error:r},void 0,2)}}function Vee(t,e,r){let n=t.listVideoAssetPaths();if(n.length===0)return[];let o=[];for(let i of n){let a=ii.basename(i),s=a,c=ii.join(e,s);try{$c.copyFileSync(i,c)}catch{continue}let l,u=ii.extname(i).toLowerCase();u===".webm"?l="video/webm":u===".mp4"?l="video/mp4":l="application/octet-stream",o.push({name:a,source:s,type:l})}return o}import{randomUUID as Wz}from"crypto";import Wee from"fs";import fS from"path";function mS(t){if(t.status!=="FAILED")return"none";switch(t.failureReason){case"SetupFailureError":return"setup";case"TeardownFailureError":return"teardown";default:return"main"}}function $ee(t){switch(t){case"PASSED":return"passed";case"FAILED":return"failed";case"CANCELLED":return"skipped";case"RETRYING":case"WAITING_FOR_USER":case"PENDING":case"RUNNING":return"unknown";default:return Xx(t)}}function $z(t){let e=fS.relative(".",t);return e===""?t:e}function jz(t,e){return Math.max(0,(t.getTime()-e.getTime())/1e3)}function qee(t,e,r){let n=jz(e,t),o=jz(r,t);return{start_at:n,end_at:o,duration:Math.max(0,o-n)}}function qz(t){let e=t.reduce((r,[n,o])=>(!o||Object.keys(r).length>=10||(r[n]=o),r),{});return Object.keys(e).length>0?e:void 0}function Kee(t){if(t.status!=="FAILED"||!t.failureReason)return;let e=t.failureDetails?.classification,r=gl[e?.reason||t.failureReason],n=e?.summary||t.failureDetails?.errorMessage||Gi[t.failureReason];return`${r}: ${n}`}function Yee(t){if(t.status!=="FAILED")return;let e=[t.failureDetails?.classification?.summary,t.failureDetails?.classification?.rootCause,t.failureDetails?.errorMessage].filter(n=>!!n),r=t.failureDetails?.errorStack?.split(`
|
|
5570
5571
|
`).map(n=>n.trim()).filter(Boolean)||[];if(!(e.length===0&&r.length===0))return[{expanded:e,backtrace:r}]}function Xee(t){let e=t.status==="FAILED"?mS(t):void 0;return qz([["failure_section",e],["quarantined",t.quarantined?"true":"false"],["failure_recovery",t.failureRecoveryDetails?.attempts?"true":"false"]])}function Jee(t,e,r){let n=$z(r.filePath);return{id:r.runId||Wz(),scope:t,name:r.testName,location:n,file_name:fS.basename(n),result:$ee(r.status),failure_reason:Kee(r),failure_expanded:Yee(r),history:qee(e,r.lastAttemptStartedAt,r.finishedAt),tags:Xee(r)}}function Vz(t,e,r,n,o){let i=$z(e);return{id:Wz(),scope:t,name:r,location:i,file_name:fS.basename(i),result:"skipped",history:{start_at:0,end_at:0,duration:0},tags:qz([["quarantined",o?.quarantined||"false"],["failure_recovery","false"]])}}function Qee(t,e){let r=e.map(i=>Jee(t.suiteName,t.startedAt,i)),n=t.testsToSkip.map(i=>Vz(t.suiteName,i.relativeFilePath,i.name,i.id,void 0)),o=t.quarantinedTestsToSkip.map(i=>Vz(t.suiteName,i.relativeFilePath,i.name,i.id,{quarantined:"true"}));return[...r,...n,...o]}function Kz(t,e,r){let n=Qee(e,r);Wee.writeFileSync(fS.join(t,`${e.suiteName}.buildkite.json`),JSON.stringify(n,null,2))}import Zee from"junit-report-builder";import hS from"path";function Yz(t,e){t.property("quarantined","true"),t.property("dd_tags[quarantined]","true"),e.quarantinedReason&&(t.property("quarantined_reason",e.quarantinedReason),t.property("dd_tags[quarantined_reason]",e.quarantinedReason)),e.quarantinedAt&&(t.property("quarantined_at",e.quarantinedAt.toISOString()),t.property("dd_tags[quarantined_at]",e.quarantinedAt.toISOString()))}function ete(t,e){let r=mS(t);if(e.name(t.testName).className(t.testName).file(hS.relative(".",t.filePath)).property("id",t.testId).property("dd_tags[id]",t.testId),t.labels&&(e.property("labels",t.labels.join(",")),t.labels.forEach(n=>{e.property("dd_tags[label]",n)})),t.baseUrl&&(e.property("base_url",t.baseUrl),e.property("dd_tags[base_url]",t.baseUrl)),t.runId&&(e.property("run_url",`https://app.momentic.ai/runs/${t.runId}`),e.property("dd_tags[run_url]",`https://app.momentic.ai/runs/${t.runId}`)),t.quarantinedMetadata&&Yz(e,t.quarantinedMetadata),r==="setup"&&(e.property("setup_failed","true"),e.property("dd_tags[setup_failed]","true")),r==="main"&&(e.property("main_failed","true"),e.property("dd_tags[main_failed]","true")),r==="teardown"&&(e.property("teardown_failed","true"),e.property("dd_tags[teardown_failed]","true")),t.status==="FAILED"){if(t.failureReason){let n=gl[t.failureDetails?.classification?.reason||t.failureReason],o=t.failureDetails?.classification?.summary||Gi[t.failureReason];t.runId&&(o+=` Visit https://app.momentic.ai/runs/${t.runId} for more details.`),e.failure(o,n)}t.failureDetails?.errorStack&&e.stacktrace(t.failureDetails.errorStack)}else t.status==="CANCELLED"&&e.skipped();return e.time((t.finishedAt.getTime()-t.lastAttemptStartedAt.getTime())/1e3).property("started_at",t.lastAttemptStartedAt.toISOString()).property("dd_tags[started_at]",t.lastAttemptStartedAt.toISOString()).property("finished_at",t.finishedAt.toISOString()).property("dd_tags[finished_at]",t.finishedAt.toISOString()),e.property("attempts",t.attempts.toString()).property("dd_tags[attempts]",t.attempts.toString()),t.parameters?.envName&&(e.property("environment",t.parameters.envName),e.property("dd_tags[environment]",t.parameters.envName)),t.parameters?.urlOverride&&e.property("url_override",t.parameters.urlOverride),e}function tte(t,e,r){let{suiteId:n,suiteName:o,startedAt:i,finishedAt:a,testsToSkip:s,quarantinedTestsToSkip:c,quarantinedTestsMetadata:l}=e,u=t.testSuite().name(o);n&&u.property("id",n),u.timestamp(i).property("startedAt",i.toISOString()).property("finishedAt",a.toISOString()).time((a.getTime()-i.getTime())/1e3);for(let d of r){let p=u.testCase();ete(d,p)}for(let d of s){let p=u.testCase();p.name(d.name).className(d.name).file(hS.relative(".",d.relativeFilePath)).property("id",d.id),d.baseUrl&&p.property("baseUrl",d.baseUrl),d.labels&&(p.property("labels",d.labels.join(",")),d.labels.forEach(m=>{p.property("dd_tags[label]",m)})),p.skipped()}for(let d of c){let p=u.testCase();p.name(d.name).className(d.name).file(hS.relative(".",d.relativeFilePath)).property("id",d.id);let m=l[d.id];m&&Yz(p,m),d.baseUrl&&p.property("baseUrl",d.baseUrl),d.labels&&(p.property("labels",d.labels.join(",")),d.labels.forEach(f=>{p.property("dd_tags[label]",f)})),p.skipped()}return u}function Xz(t,e,r){let n=Zee.newBuilder();tte(n,e,r),n.writeTo(hS.join(t,`${e.suiteName}.xml`))}import rte from"fs";import nte from"path";function Jz(t){return{title:Kn(t),duration:t.finishedAt.getTime()-t.startedAt.getTime(),error:t.status==="FAILED"?{value:t.failureReason}:void 0,steps:t.results&&t.type!=="PRESET_ACTION"?t.results.map(Jz):[]}}async function ote(t,e,r,n){if(n.results?.length){let o=await pS(t,e,r,n.results[n.results.length-1].afterSnapshot);return o?[{name:"Final state screenshot",path:o,contentType:"image/jpeg"}]:[]}return[]}async function ite(t,e,r,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||Gi[n.failureReason]}:void 0,retry:n.attempts-1,steps:n.results?.map(Jz)||[],startTime:n.lastAttemptStartedAt.toISOString(),attachments:await ote(t,e,r,n)}}async function ate(t,e,r,n){return{expectedStatus:"passed",status:n.status==="PASSED"?"expected":"unexpected",results:[await ite(t,e,r,n)]}}async function ste(t,e,r,n){return{tags:[],title:n.test.name,ok:n.status==="PASSED",tests:[await ate(t,e,r,n)],id:n.runId,file:n.filePath}}function WA(t,e){return t.reduce((r,n)=>e(n)?r+1:r,0)}async function lte(t,e,r,n,o){return{suites:[{title:n.suiteName,file:n.projectConfigPath,specs:await Promise.all(o.map(async i=>{let a=i.runId&&i.runAttemptId?e.createDebugDataReaderForRunAttempt(i.runId,i.runAttemptId):new ed;try{return await ste(t,a,r,i)}finally{a.close()}}))}],errors:[],stats:{startTime:n.startedAt.toISOString(),duration:n.finishedAt.getTime()-n.startedAt.getTime(),expected:WA(o,i=>i.status==="PASSED"),unexpected:WA(o,i=>i.status!=="PASSED"),flaky:WA(o,i=>!!i.isFlake),skipped:0}}}async function Qz(t,e,r,n,o){let i=await lte(t,e,r,n,o);rte.writeFileSync(nte.join(r,`${n.suiteName}.json`),JSON.stringify(i,null,2))}function Zz(t){return{testName:t.test.name,testId:t.test.id,filePath:t.filePath,labels:t.test.labels,baseUrl:t.baseUrl,runId:t.runId,quarantined:t.quarantined,quarantinedMetadata:t.quarantinedMetadata,status:t.status,failureRecoveryDetails:t.failureRecoveryDetails,failureDetails:t.failureDetails,failureReason:t.failureReason,finishedAt:t.finishedAt,lastAttemptStartedAt:t.lastAttemptStartedAt,attempts:t.attempts,parameters:t.parameters}}async function e1({logger:t,callbacks:e,format:r,params:n,runs:o,folder:i}){switch(cte(i)?dte(i).isDirectory()||(v.error(`The specified reporter output directory '${i}' exists on disk but is not a folder. Please move or delete the existing object or specify a different reporter path.`),process.exit(1)):(v.info(`Reporter output directory '${i}' does not exist on disk, creating it now...`),ute(i,{recursive:!0})),r){case"junit":{let a=o.map(Zz);Xz(i,n,a);return}case"buildkite-json":{let a=o.map(Zz);Kz(i,n,a);return}case"allure":case"allure-json":await Gz(t,e,i,n,o);return;case"playwright-json":await Qz(t,e,i,n,o);return;default:throw new Error(`Unknown reporter format requested: '${r}'`)}}import kte from"wait-on";import{execSync as pte}from"child_process";import{platform as mte}from"os";function gS(){return t1()?(v.dimmed("Setting device pixel ratio to 2 automatically since a Mac OS Retina screen was detected."),v.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.
|
|
5571
5572
|
`),2):(v.dimmed("Setting device pixel ratio to 1."),v.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.
|
|
5572
|
-
`),1)}function t1(){return mte()==="darwin"&&pte("system_profiler SPDisplaysDataType").toString().includes("Retina")}function SS(t){t1()&&t===1&&(v.warn("If you are using Momentic on a Retina screen, relaunch with the --pixel-ratio option to avoid incorrect viewport calculations."),v.warn("Confirm your device's pixel-ratio at https://www.mydevice.io."))}import fte from"@actions/exec";import hte from"@actions/io";import gte from"quote";import Ste from"string-argv";async function r1(t,e=!0){let r=Ste(t),n=await hte.which(r[0],!0),o=r.slice(1),i=fte.exec(gte(n),o,{delay:100});if(e)return i}import yte from"csv-parser";import{createReadStream as Ete}from"fs";function $A(t){return new Promise((e,r)=>{let n=[];Ete(t).pipe(yte()).on("data",o=>n.push(o)).on("end",()=>e(n)).on("error",o=>r(o))})}import qc from"semver";import{z as yS}from"zod";var Zr="2.71.1",Tte="https://registry.npmjs.org/momentic",bte=yS.object({versions:yS.record(yS.string(),yS.unknown()).optional()});async function Po(t){try{await vte(t)}catch(e){v.warn({err:e},"Failed to check CLI version against NPM servers")}}async function qA(){let t=await J(fetch(Tte),{milliseconds:5e3});if(!t.ok)throw new Error(`Got error status code ${t.statusText}`);let e=await t.json(),r=bte.parse(e).versions;if(!r)throw new Error("Failed to fetch npm registry data. Skipping version check.");let n=Zr;for(let o of Object.keys(r))qc.valid(o)&&qc.major(o)===qc.major(Zr)&&qc.gt(o,n)&&qc.prerelease(o)===null&&(n=o);return n}async function vte(t){let e;for(let r=0;r<2;r++)try{e=await qA()}catch(n){t.warn({err:n},"Failed to fetch latest version from npm registry")}if(!e){t.warn("Failed to fetch npm registry data. Skipping version check.");return}qc.eq(Zr,e)||(v.warn(`Update available: v${Zr} -> v${e}`),v.warn("This version may be missing critical fixes, features, and security updates."),v.warn('Run "npx momentic@latest upgrade" to update'))}async function ki(){try{await J(Promise.all([Zm(),Wt.flush()]),{milliseconds:5e3})}catch{}}import{partition as Ate}from"lodash-es";function ES(t){return t.length===1?"test":"tests"}function n1(t){return t===1?"1 worker":`${t} workers`}function o1(t){t.length!==0&&(v.info(`Skipping ${t.length} disabled ${ES(t)}:`),t.forEach(e=>{v.info(`${It}- ${[e.relativeFilePath]}`)}),v.log(""))}function i1(t,e){t.length!==0&&(v.info(`Skipping ${t.length} quarantined ${ES(t)}:`),t.forEach(r=>{v.info(`${It}- ${[r.relativeFilePath]}: ${e[r.id]?.quarantinedReason}`)}),v.log(""))}function Cte(t,e){t.length!==0&&(v.info(`Running ${t.length} quarantined ${ES(t)} with ${n1(e)}:`),t.forEach(r=>{v.info(`${It}- ${[r.testDefinition.relativeFilePath]}${typeof r.inputIndex=="number"?` with input set ${r.inputIndex}`:""}`)}),v.log(""))}function Rte(t,e,r){e.length===0&&t.length>0||(v.info(`Running ${e.length} ${ES(e)} with ${n1(r)}:`),e.forEach(n=>{v.info(`${It}- ${[n.testDefinition.relativeFilePath]}${typeof n.inputIndex=="number"?` with input set ${n.inputIndex}`:""}`)}),v.log(""))}function a1({logger:t,localTestsToRunWithInputs:e,parallel:r,shardCount:n,shardIndex:o}){t.info({tests:e.length,shardCount:n,shardIndex:o,parallel:r},"Running local tests");let[i,a]=Ate(e,s=>s.quarantined);Cte(i,r),Rte(i,a,r)}import{randomUUID as wte}from"crypto";import{cloneDeep as Kc}from"lodash-es";import{dirname as xte}from"path";async function s1({orgId:t,codeEvalTools:e,logger:r,outputDefinitions:n,testContext:o}){let i={};for(let a of n){let{name:s,value:c}=a;i[s]=await Jr({orgId:t,s:c,localTools:e,logger:r,context:o})}return i}async function l1({baseUrl:t,envName:e,testName:r,devicePixelRatio:n,apiClient:o,test:i,storageClient:a,codeEvalTools:s,generator:c,orgId:l,variables:u,logger:d,customHeaders:p,testInputs:m,localBrowserConfig:f,aiSettings:h,visualDiffScreenshotStorage:S,tracer:g,browserTypeOverride:E}){let y=await Nc({settings:f,customHeaders:p,envVariables:u,envName:e,testName:r,baseUrl:t,logger:d,localTools:s,orgId:l}),b={baseUrl:o.baseUrl,apiKey:o.apiKey,logger:le,mode:"runner"},C=rm({browserTypeOverride:E,configuredBrowserType:y.browserType,orgDefaultBrowserType:f.defaultBrowserType});if(y.browserType=C,!aL(C)){let M=`Browser ${C} 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...`;v.warn(M),le.warn(M)}let I=await no.init({baseUrl:t,logger:d,userBrowserSettings:y,storage:a,enricher:new ga(b,c),contextArgs:{viewport:i.advanced.viewport??Ir,locale:i.advanced.locale??$i,geolocation:i.advanced.geolocation??Ki,timezoneId:i.advanced.timezone??qi,colorScheme:i.advanced.colorScheme,deviceScaleFactor:n},callbacks:{onNetworkPage:M=>g.onNetworkPage(M),onNetworkLogs:M=>g.onNetworkLogs(M)},iconKnowledgeBase:null,videoOptions:g.videoOutputPath?{videoOutputPath:g.videoOutputPath,onVideoPageChange:({videoName:M,timestamp:P})=>{g.setActiveVideo(M,P)}}:void 0}),_=new Aa({browser:I,generator:c,logger:d,orgId:l,options:{scratchPadId:void 0,slowMoMs:y.slowMoMs,autoFollowNewTabs:y.autoFollowNewTabs,useMemory:h.useMemory,aiPageFiltering:h.aiPageFiltering},storage:a,localCodeEvalTools:s,visualDiffScreenshotStorage:S}),R=new $r({baseUrl:t,currentUrl:_.browser.url(),variablesFromEnvironment:u,envName:e,testName:r});return i.parameters&&await Promise.all(i.parameters.map(async M=>{let{name:P,defaultValue:B,required:F}=M,G=m?.[P];F&&G===void 0&&(v.error(`Required parameter '${P}' is required by test '${i.name}' but not provided`),process.exit(1));let z=await Jr({orgId:l,s:G??B,localTools:s,logger:d,context:$r.dummyContext(R.getEnvName())});R.setMomenticSystemVariable(P,z)})),{controller:_,context:R}}async function c1({testAdvancedSettings:t,orgSettings:e,logger:r}){if(t.failureRecovery===!1||t.failureRecovery===void 0&&!e?.failureRecovery)return!1;if(!cs){let n="This test is ineligible for failure recovery since this does not appear to be a CI environment";return r.warn(n),v.warn(n),!1}return!0}async function u1({attemptInputs:t,attemptFixtures:e,attemptMetadata:r}){let{orgId:n,runId:o}=r,{controller:i,context:a,codeEvalTools:s,storageClient:c,logger:l,usageTracker:u,tracer:d}=e,{test:p,orgSettings:m}=t;l.info(`Running test '${p.name}' locally (run link: https://app.momentic.ai/runs/${o})`);let f={controller:i,storage:c,usageTracker:u,context:a,logger:l,codeEvalTools:s},h={orgId:n,runId:o,testMetadata:p,steps:p.steps,beforeSteps:p.beforeSteps,afterSteps:p.afterSteps,orgSettings:m},S={collectDebugData:!0,reinitializeBrowser:!0,disableHealing:!await c1({testAdvancedSettings:p.advanced,orgSettings:m.ai,logger:l})};return await wg({fixtures:f,inputs:h,options:S,callbacks:{step:{},test:{onTestComplete:async()=>{await i.browser.cleanup()}}},testParams:{tracer:d}})}async function d1(t){let{testDefinition:e,logger:r}=t,n=new Date;try{return await _te(t)}catch(o){let i="Fatal error running test";return v.error(`${i}: ${o.message}`),r.error({err:o},i),{results:[],parameters:t,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:{},quarantined:t.quarantined,quarantinedMetadata:t.quarantinedMetadata}}}async function _te(t){let{testDefinition:e,project:r,apiClient:n,orgId:o,urlOverride:i,runGroupTracer:a,logger:s,gitMetadata:c,cacheOptions:l,runId:u,testInputs:d,quarantined:p,quarantinedMetadata:m,usageTracker:f}=t,h=new wc(n,o),S=xo({logger:s,orgId:o,client:n,gitMetadata:c,regenerateCache:l.regenerateCache,alwaysSaveCache:l.alwaysSaveCache,noCache:l.noCache,isolateCachesByEnvironment:r.config?.advanced?.isolateCachesByEnvironment,bustOldestCachePercentage:l.bustOldestCachePercentage}),{envName:g,resolvedEnv:E,environmentVariables:y,baseUrl:b}=Kh({test:e,envNameOverride:t.envName,urlOverride:i,resolveEnv:F=>_s(F,r,s)}),C=await dh({cacheStorage:S,logger:s,schemaVersion:e.schemaVersion,stepLists:{steps:e.steps,beforeSteps:e.beforeSteps,afterSteps:e.afterSteps},testId:e.id,environment:g}),I=C.steps,_=C.beforeSteps??void 0,R=C.afterSteps??void 0,M=await a.startRun({logger:s,runId:u,originalSteps:{beforeSteps:e.beforeSteps,steps:e.steps,afterSteps:e.afterSteps},testId:e.id,testName:e.name,directory:xte(e.relativeFilePath),testDescription:e.description??void 0,testLabels:e.labels,baseUrl:b,environmentName:g,schemaVersion:e.schemaVersion,resolvedInputs:d,quarantined:p,quarantinedReason:m?.quarantinedReason,aiSettings:t.project.config.ai}),P=s.child(M.loggerBindings||{});Object.entries(M.envVarBindings||{}).forEach(([F,G])=>{y[F]=G});let B=await Ite({...t,variables:y,envName:g,resolvedEnv:E,baseUrl:b,storageClient:h,tracer:M,logger:P,cacheStorage:S,stepsWithCaches:I,beforeStepsWithCaches:_,afterStepsWithCaches:R,usageTracker:f});return await M.finish({logger:s,status:B.status,finishedAt:B.finishedAt,failureDetails:B.failureDetails,failureReason:B.failureReason,isFlake:B.isFlake,failureRecoveryDetails:B.failureRecoveryDetails}),{runId:M.runId,...B}}async function Ite(t){let{testDefinition:e,stepsWithCaches:r,beforeStepsWithCaches:n,afterStepsWithCaches:o,project:i,regenerateGoldenFiles:a,apiClient:s,generator:c,baseUrl:l,storageClient:u,orgId:d,envName:p,urlOverride:m,customHeaders:f,testInputs:h,variables:S,resolvedEnv:g,retriesOverride:E,devicePixelRatio:y,logUpdate:b,tracer:C,logger:I,cacheStorage:_,gitMetadata:R,quarantined:M,quarantinedMetadata:P,usageTracker:B}=t,F=i.config.ai?.aiFailureAnalysis??!1,G=new Date,z=new vc(i,s,a),ae={...i.config},W={envName:p,urlOverride:m,customHeaders:f,testInputs:h},q,X=Math.abs(E??e.retries??i.config.retries??0),ne=[];I.info({...R,labels:e.labels,name:e.name,cwd:process.cwd()},"Starting test run using CLI");for(let de=0;de<=X;de++){let Te=wte(),te=await C.startAttempt(Te),be=I.child(te.loggerBindings||{}),Pe={...e,steps:Kc(r),beforeSteps:Kc(n),afterSteps:Kc(o)};de!==0&&b("RETRY",`attempt ${de+1}/${X+1}`);let ve=new Date,x=ae.advanced?.fakerConstantSeed,se=new Xo({httpClient:new Tr({baseUrl:s.baseUrl,apiKey:s.apiKey,logger:be,mode:"runner"}),fakerSeed:x?Hl:void 0}),Ae=te;try{let{controller:dn,context:Mo}=await l1({tracer:te,baseUrl:l,envName:p,testName:Pe.name,apiClient:s,devicePixelRatio:y,logger:be,storageClient:u,codeEvalTools:se,test:Pe,generator:c,orgId:d,variables:S,customHeaders:f,testInputs:h,localBrowserConfig:{...i.config.browser||{},...g?.browser||{},...Pe.advanced},browserTypeOverride:t.browserTypeOverride,aiSettings:{...i.config.ai||{},...Pe.advanced||{}},visualDiffScreenshotStorage:z});q=await u1({attemptMetadata:{attemptNumber:de+1,orgId:d,runId:C.runId},attemptFixtures:{logger:be,storageClient:u,usageTracker:B,codeEvalTools:se,apiClient:s,context:Mo,controller:dn,tracer:te},attemptInputs:{test:Pe,orgSettings:ae}});let Mn=new Date,Oo={logger:I,cacheStorage:_,orgId:d,testId:e.id,environment:p,originalStepsWithCaches:{steps:Kc(r),beforeSteps:Kc(n),afterSteps:Kc(o)},updatedStepsWithCaches:{steps:Pe.steps,beforeSteps:Pe.beforeSteps,afterSteps:Pe.afterSteps}};q?.status==="PASSED"?await vs(Oo):q?.status==="FAILED"&&de===X&&await Sc(Oo),await te.finish({logger:be,result:q}),ne.unshift(q.status);let ce=await s1({orgId:d,codeEvalTools:se,logger:be,outputDefinitions:e.outputs??[],testContext:Mo}),ai=pw(ne),Pp=de+1;if(q.status!=="FAILED")return{...q,runAttemptId:Te,parameters:W,test:Pe,filePath:Pe.relativeFilePath,startedAt:G,lastAttemptStartedAt:ve,finishedAt:Mn,attempts:Pp,baseUrl:l,outputs:ce,isFlake:ai,quarantined:M,quarantinedMetadata:P};let Ma=q.failedStepResult,so=Ma?.message||"Unknown failure",Ui=Ma?.failureReason??hR(so)??"UnknownError",el=be.child({failureReason:Ui,errorMessage:so,numAttempts:(X+1).toString(),name:Pe.name});if(de<X){el.warn(`Retrying failed execution attempt for run: ${so}`);continue}el.error(`Test failed after all exhausting attempts: ${so}`);let Yc=new Error(so),tl={errorMessage:so,errorStack:Yc.stack},Bi;if(F){let Mp;try{if(q.results&&q.results.length>0){let{classification:Xc,aiFailureReason:tt}=await RN({logger:be,browserStateStorage:Ae,generator:c,fullResults:q,failureReason:Ui,error:Yc,maxItemsFromEnd:void 0,numStepsWithScreenshots:void 0,disableCache:!1});Mp=Xc,Bi=tt}}catch(Xc){be.warn({err:Xc},"Failed to classify test results")}Mp&&(tl.classification=Mp,Ui=Bi??Ui)}return{...q,runAttemptId:Te,parameters:W,failureDetails:tl,failureReason:Ui,test:Pe,filePath:Pe.relativeFilePath,startedAt:G,lastAttemptStartedAt:ve,finishedAt:Mn,attempts:de+1,baseUrl:l,outputs:ce,quarantined:M,quarantinedMetadata:P}}catch(dn){let Mo=`Encountered fatal platform error while running test '${Pe.name}': ${dn}`,Mn=new Date,Oo=de+1;be.error({err:dn},Mo),v.error(Mo);let ce={errorMessage:dn.message,errStack:dn.stack},ai={status:"FAILED",failureDetails:ce,failureReason:"InternalPlatformError",finishedAt:Mn};return await te.finish({logger:be,result:{status:"FAILED",results:[]}}),{...ai,runAttemptId:Te,results:[],parameters:W,test:Pe,filePath:Pe.relativeFilePath,startedAt:G,lastAttemptStartedAt:ve,finishedAt:new Date,attempts:Oo,baseUrl:l,outputs:{},quarantined:M,quarantinedMetadata:P}}}throw new Error("This code should not be reachable")}import Ote from"adm-zip";import Lte from"path";function Pte(t){switch(t){case"PASSED":return"SUCCESS";case"FAILED":return"FAILED";case"CANCELLED":return"CANCELLED";case"RUNNING":case"PENDING":case"RETRYING":case"WAITING_FOR_USER":return"RUNNING"}}var Zs=class{constructor(e,r,n,o){this.orgId=e;this.testId=r;this.testName=n;this.diskStorage=o}children=[];finished=!1;stepFrequenciesByType={};async getScreenshot(e,r){return this.diskStorage.readFile(`${gr}/${r}.jpeg`)}async getHtmlSnapshot(e,r){return this.diskStorage.readFile(`${gr}/${r}.html`)?.toString()}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,r]of Object.entries(this.stepFrequenciesByType))Wt.increment("test_step_execution",r,[`type:${e}`,"platform:browser","executor:cli",`orgId:${this.orgId}`])}async startStep(e){let{step:r}=e;this.recordStepStat(r);let n={step:r,status:"RUNNING",startedAt:new Date},o=new KA(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(r=>r.finishInternal({status:Pte(e.status),finishedAt:e.finishedAt}))),this.sendFinalizedStepStats())}};function Mte(t){switch(t){case"SUCCESS":return"PASSED";case"FAILED":return"FAILED";case"CANCELLED":return"CANCELLED";case"RUNNING":return"RUNNING";case"IDLE":return"PENDING"}}var KA=class{constructor(e,r,n,o,i){this.orgId=e;this.testId=r;this.testName=n;this.metadata=o;this.diskStorage=i;this.interactionTracer=new Mi(void 0,a=>this.storeTraceAsset(a)),Pi.initializeRootTracerContext(this.interactionTracer)}children=[];finished=!1;interactionTracer;attachBeforeScreenshot(e){let{snapshotId:r,screenshot:n}=e;this.metadata.beforeSnapshotId=r,this.diskStorage.storeFile({name:`${gr}/${r}.jpeg`,contents:n})}attachAfterScreenshot(e){let{snapshotId:r,screenshot:n}=e;this.metadata.afterSnapshotId=r,this.diskStorage.storeFile({name:`${gr}/${r}.jpeg`,contents:n})}attachBeforeHtmlSnapshot(e){let{snapshotId:r,html:n}=e;this.metadata.beforeSnapshotId=r,this.diskStorage.storeFile({name:`${gr}/${r}.html`,contents:n})}attachAfterHtmlSnapshot(e){let{snapshotId:r,html:n}=e;this.metadata.afterSnapshotId=r,this.diskStorage.storeFile({name:`${gr}/${r}.html`,contents:n})}recordTargetAutoHeal(e){let{healType:r}=e,n=r==="AI"?"ai-target-heal":"cache-heal";Wt.increment("test_event",1,[`name:${n}`,`orgId:${this.orgId}`]),this.metadata.healMetadata={healType:r,healedAt:new Date}}recordStepDuration(e){if(!Qm(e.step))return;let r=Jm(e.step);Wt.distribution("test_step_duration",e.durationMs,[`type:${r}`,"platform:browser","executor:cli",`orgId:${this.orgId}`])}storeTraceAsset(e){this.diskStorage.storeFile({name:`${gr}/${e.snapshotId}.jpeg`,contents:e.data})}async finishInternal(e){this.finished||(this.finished=!0,this.interactionTracer.finish(),await Promise.all(this.children.map(r=>r.finish({status:Mte(e.status),finishedAt:e.finishedAt}))))}async finish(e){await this.finishInternal(e.step),e.step.trace=this.interactionTracer.getRootSpan()}async startSubSteps(){let e=new Zs(this.orgId,this.testId,this.testName,this.diskStorage);return this.children.push(e),e}};var xp=class{constructor(e,r,n,o,i,a,s){this.orgId=e;this.testId=r;this.testName=n;this.runAttemptId=o;this.metadata=i;this.diskStorage=a;this.recordVideo=s;this.diskStorage.mkdir(gr),this.harPagesStream=this.diskStorage.createFileStream(`${gr}/har-pages.log`),this.inProgressHarEntries={},this.harEntriesStream=this.diskStorage.createFileStream(`${gr}/har-entries.log`),this.resourceUsageStream=this.diskStorage.createFileStream(`${gr}/resource-usage.ndjson`),this.resourceUsageSampler=jI({keepSamples:!1,onSample:c=>{this.resourceUsageStream.write(`${JSON.stringify(c)}
|
|
5573
|
+
`),1)}function t1(){return mte()==="darwin"&&pte("system_profiler SPDisplaysDataType").toString().includes("Retina")}function SS(t){t1()&&t===1&&(v.warn("If you are using Momentic on a Retina screen, relaunch with the --pixel-ratio option to avoid incorrect viewport calculations."),v.warn("Confirm your device's pixel-ratio at https://www.mydevice.io."))}import fte from"@actions/exec";import hte from"@actions/io";import gte from"quote";import Ste from"string-argv";async function r1(t,e=!0){let r=Ste(t),n=await hte.which(r[0],!0),o=r.slice(1),i=fte.exec(gte(n),o,{delay:100});if(e)return i}import yte from"csv-parser";import{createReadStream as Ete}from"fs";function $A(t){return new Promise((e,r)=>{let n=[];Ete(t).pipe(yte()).on("data",o=>n.push(o)).on("end",()=>e(n)).on("error",o=>r(o))})}import qc from"semver";import{z as yS}from"zod";var Zr="2.71.2",Tte="https://registry.npmjs.org/momentic",bte=yS.object({versions:yS.record(yS.string(),yS.unknown()).optional()});async function Po(t){try{await vte(t)}catch(e){v.warn({err:e},"Failed to check CLI version against NPM servers")}}async function qA(){let t=await J(fetch(Tte),{milliseconds:5e3});if(!t.ok)throw new Error(`Got error status code ${t.statusText}`);let e=await t.json(),r=bte.parse(e).versions;if(!r)throw new Error("Failed to fetch npm registry data. Skipping version check.");let n=Zr;for(let o of Object.keys(r))qc.valid(o)&&qc.major(o)===qc.major(Zr)&&qc.gt(o,n)&&qc.prerelease(o)===null&&(n=o);return n}async function vte(t){let e;for(let r=0;r<2;r++)try{e=await qA()}catch(n){t.warn({err:n},"Failed to fetch latest version from npm registry")}if(!e){t.warn("Failed to fetch npm registry data. Skipping version check.");return}qc.eq(Zr,e)||(v.warn(`Update available: v${Zr} -> v${e}`),v.warn("This version may be missing critical fixes, features, and security updates."),v.warn('Run "npx momentic@latest upgrade" to update'))}async function ki(){try{await J(Promise.all([Zm(),Wt.flush()]),{milliseconds:5e3})}catch{}}import{partition as Ate}from"lodash-es";function ES(t){return t.length===1?"test":"tests"}function n1(t){return t===1?"1 worker":`${t} workers`}function o1(t){t.length!==0&&(v.info(`Skipping ${t.length} disabled ${ES(t)}:`),t.forEach(e=>{v.info(`${It}- ${[e.relativeFilePath]}`)}),v.log(""))}function i1(t,e){t.length!==0&&(v.info(`Skipping ${t.length} quarantined ${ES(t)}:`),t.forEach(r=>{v.info(`${It}- ${[r.relativeFilePath]}: ${e[r.id]?.quarantinedReason}`)}),v.log(""))}function Cte(t,e){t.length!==0&&(v.info(`Running ${t.length} quarantined ${ES(t)} with ${n1(e)}:`),t.forEach(r=>{v.info(`${It}- ${[r.testDefinition.relativeFilePath]}${typeof r.inputIndex=="number"?` with input set ${r.inputIndex}`:""}`)}),v.log(""))}function Rte(t,e,r){e.length===0&&t.length>0||(v.info(`Running ${e.length} ${ES(e)} with ${n1(r)}:`),e.forEach(n=>{v.info(`${It}- ${[n.testDefinition.relativeFilePath]}${typeof n.inputIndex=="number"?` with input set ${n.inputIndex}`:""}`)}),v.log(""))}function a1({logger:t,localTestsToRunWithInputs:e,parallel:r,shardCount:n,shardIndex:o}){t.info({tests:e.length,shardCount:n,shardIndex:o,parallel:r},"Running local tests");let[i,a]=Ate(e,s=>s.quarantined);Cte(i,r),Rte(i,a,r)}import{randomUUID as wte}from"crypto";import{cloneDeep as Kc}from"lodash-es";import{dirname as xte}from"path";async function s1({orgId:t,codeEvalTools:e,logger:r,outputDefinitions:n,testContext:o}){let i={};for(let a of n){let{name:s,value:c}=a;i[s]=await Jr({orgId:t,s:c,localTools:e,logger:r,context:o})}return i}async function l1({baseUrl:t,envName:e,testName:r,devicePixelRatio:n,apiClient:o,test:i,storageClient:a,codeEvalTools:s,generator:c,orgId:l,variables:u,logger:d,customHeaders:p,testInputs:m,localBrowserConfig:f,aiSettings:h,visualDiffScreenshotStorage:S,tracer:g,browserTypeOverride:E}){let y=await Nc({settings:f,customHeaders:p,envVariables:u,envName:e,testName:r,baseUrl:t,logger:d,localTools:s,orgId:l}),b={baseUrl:o.baseUrl,apiKey:o.apiKey,logger:le,mode:"runner"},C=rm({browserTypeOverride:E,configuredBrowserType:y.browserType,orgDefaultBrowserType:f.defaultBrowserType});if(y.browserType=C,!aL(C)){let M=`Browser ${C} 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...`;v.warn(M),le.warn(M)}let I=await no.init({baseUrl:t,logger:d,userBrowserSettings:y,storage:a,enricher:new ga(b,c),contextArgs:{viewport:i.advanced.viewport??Ir,locale:i.advanced.locale??$i,geolocation:i.advanced.geolocation??Ki,timezoneId:i.advanced.timezone??qi,colorScheme:i.advanced.colorScheme,deviceScaleFactor:n},callbacks:{onNetworkPage:M=>g.onNetworkPage(M),onNetworkLogs:M=>g.onNetworkLogs(M)},iconKnowledgeBase:null,videoOptions:g.videoOutputPath?{videoOutputPath:g.videoOutputPath,onVideoPageChange:({videoName:M,timestamp:P})=>{g.setActiveVideo(M,P)}}:void 0}),_=new Aa({browser:I,generator:c,logger:d,orgId:l,options:{scratchPadId:void 0,slowMoMs:y.slowMoMs,autoFollowNewTabs:y.autoFollowNewTabs,useMemory:h.useMemory,aiPageFiltering:h.aiPageFiltering},storage:a,localCodeEvalTools:s,visualDiffScreenshotStorage:S}),R=new $r({baseUrl:t,currentUrl:_.browser.url(),variablesFromEnvironment:u,envName:e,testName:r});return i.parameters&&await Promise.all(i.parameters.map(async M=>{let{name:P,defaultValue:B,required:F}=M,G=m?.[P];F&&G===void 0&&(v.error(`Required parameter '${P}' is required by test '${i.name}' but not provided`),process.exit(1));let z=await Jr({orgId:l,s:G??B,localTools:s,logger:d,context:$r.dummyContext(R.getEnvName())});R.setMomenticSystemVariable(P,z)})),{controller:_,context:R}}async function c1({testAdvancedSettings:t,orgSettings:e,logger:r}){if(t.failureRecovery===!1||t.failureRecovery===void 0&&!e?.failureRecovery)return!1;if(!cs){let n="This test is ineligible for failure recovery since this does not appear to be a CI environment";return r.warn(n),v.warn(n),!1}return!0}async function u1({attemptInputs:t,attemptFixtures:e,attemptMetadata:r}){let{orgId:n,runId:o}=r,{controller:i,context:a,codeEvalTools:s,storageClient:c,logger:l,usageTracker:u,tracer:d}=e,{test:p,orgSettings:m}=t;l.info(`Running test '${p.name}' locally (run link: https://app.momentic.ai/runs/${o})`);let f={controller:i,storage:c,usageTracker:u,context:a,logger:l,codeEvalTools:s},h={orgId:n,runId:o,testMetadata:p,steps:p.steps,beforeSteps:p.beforeSteps,afterSteps:p.afterSteps,orgSettings:m},S={collectDebugData:!0,reinitializeBrowser:!0,disableHealing:!await c1({testAdvancedSettings:p.advanced,orgSettings:m.ai,logger:l})};return await wg({fixtures:f,inputs:h,options:S,callbacks:{step:{},test:{onTestComplete:async()=>{await i.browser.cleanup()}}},testParams:{tracer:d}})}async function d1(t){let{testDefinition:e,logger:r}=t,n=new Date;try{return await _te(t)}catch(o){let i="Fatal error running test";return v.error(`${i}: ${o.message}`),r.error({err:o},i),{results:[],parameters:t,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:{},quarantined:t.quarantined,quarantinedMetadata:t.quarantinedMetadata}}}async function _te(t){let{testDefinition:e,project:r,apiClient:n,orgId:o,urlOverride:i,runGroupTracer:a,logger:s,gitMetadata:c,cacheOptions:l,runId:u,testInputs:d,quarantined:p,quarantinedMetadata:m,usageTracker:f}=t,h=new wc(n,o),S=xo({logger:s,orgId:o,client:n,gitMetadata:c,regenerateCache:l.regenerateCache,alwaysSaveCache:l.alwaysSaveCache,noCache:l.noCache,isolateCachesByEnvironment:r.config?.advanced?.isolateCachesByEnvironment,bustOldestCachePercentage:l.bustOldestCachePercentage}),{envName:g,resolvedEnv:E,environmentVariables:y,baseUrl:b}=Kh({test:e,envNameOverride:t.envName,urlOverride:i,resolveEnv:F=>_s(F,r,s)}),C=await dh({cacheStorage:S,logger:s,schemaVersion:e.schemaVersion,stepLists:{steps:e.steps,beforeSteps:e.beforeSteps,afterSteps:e.afterSteps},testId:e.id,environment:g}),I=C.steps,_=C.beforeSteps??void 0,R=C.afterSteps??void 0,M=await a.startRun({logger:s,runId:u,originalSteps:{beforeSteps:e.beforeSteps,steps:e.steps,afterSteps:e.afterSteps},testId:e.id,testName:e.name,directory:xte(e.relativeFilePath),testDescription:e.description??void 0,testLabels:e.labels,baseUrl:b,environmentName:g,schemaVersion:e.schemaVersion,resolvedInputs:d,quarantined:p,quarantinedReason:m?.quarantinedReason,aiSettings:t.project.config.ai}),P=s.child(M.loggerBindings||{});Object.entries(M.envVarBindings||{}).forEach(([F,G])=>{y[F]=G});let B=await Ite({...t,variables:y,envName:g,resolvedEnv:E,baseUrl:b,storageClient:h,tracer:M,logger:P,cacheStorage:S,stepsWithCaches:I,beforeStepsWithCaches:_,afterStepsWithCaches:R,usageTracker:f});return await M.finish({logger:s,status:B.status,finishedAt:B.finishedAt,failureDetails:B.failureDetails,failureReason:B.failureReason,isFlake:B.isFlake,failureRecoveryDetails:B.failureRecoveryDetails}),{runId:M.runId,...B}}async function Ite(t){let{testDefinition:e,stepsWithCaches:r,beforeStepsWithCaches:n,afterStepsWithCaches:o,project:i,regenerateGoldenFiles:a,apiClient:s,generator:c,baseUrl:l,storageClient:u,orgId:d,envName:p,urlOverride:m,customHeaders:f,testInputs:h,variables:S,resolvedEnv:g,retriesOverride:E,devicePixelRatio:y,logUpdate:b,tracer:C,logger:I,cacheStorage:_,gitMetadata:R,quarantined:M,quarantinedMetadata:P,usageTracker:B}=t,F=i.config.ai?.aiFailureAnalysis??!1,G=new Date,z=new vc(i,s,a),ae={...i.config},W={envName:p,urlOverride:m,customHeaders:f,testInputs:h},q,X=Math.abs(E??e.retries??i.config.retries??0),ne=[];I.info({...R,labels:e.labels,name:e.name,cwd:process.cwd()},"Starting test run using CLI");for(let de=0;de<=X;de++){let Te=wte(),te=await C.startAttempt(Te),be=I.child(te.loggerBindings||{}),Pe={...e,steps:Kc(r),beforeSteps:Kc(n),afterSteps:Kc(o)};de!==0&&b("RETRY",`attempt ${de+1}/${X+1}`);let ve=new Date,x=ae.advanced?.fakerConstantSeed,se=new Xo({httpClient:new Tr({baseUrl:s.baseUrl,apiKey:s.apiKey,logger:be,mode:"runner"}),fakerSeed:x?Hl:void 0}),Ae=te;try{let{controller:dn,context:Mo}=await l1({tracer:te,baseUrl:l,envName:p,testName:Pe.name,apiClient:s,devicePixelRatio:y,logger:be,storageClient:u,codeEvalTools:se,test:Pe,generator:c,orgId:d,variables:S,customHeaders:f,testInputs:h,localBrowserConfig:{...i.config.browser||{},...g?.browser||{},...Pe.advanced},browserTypeOverride:t.browserTypeOverride,aiSettings:{...i.config.ai||{},...Pe.advanced||{}},visualDiffScreenshotStorage:z});q=await u1({attemptMetadata:{attemptNumber:de+1,orgId:d,runId:C.runId},attemptFixtures:{logger:be,storageClient:u,usageTracker:B,codeEvalTools:se,apiClient:s,context:Mo,controller:dn,tracer:te},attemptInputs:{test:Pe,orgSettings:ae}});let Mn=new Date,Oo={logger:I,cacheStorage:_,orgId:d,testId:e.id,environment:p,originalStepsWithCaches:{steps:Kc(r),beforeSteps:Kc(n),afterSteps:Kc(o)},updatedStepsWithCaches:{steps:Pe.steps,beforeSteps:Pe.beforeSteps,afterSteps:Pe.afterSteps}};q?.status==="PASSED"?await vs(Oo):q?.status==="FAILED"&&de===X&&await Sc(Oo),await te.finish({logger:be,result:q}),ne.unshift(q.status);let ce=await s1({orgId:d,codeEvalTools:se,logger:be,outputDefinitions:e.outputs??[],testContext:Mo}),ai=pw(ne),Pp=de+1;if(q.status!=="FAILED")return{...q,runAttemptId:Te,parameters:W,test:Pe,filePath:Pe.relativeFilePath,startedAt:G,lastAttemptStartedAt:ve,finishedAt:Mn,attempts:Pp,baseUrl:l,outputs:ce,isFlake:ai,quarantined:M,quarantinedMetadata:P};let Ma=q.failedStepResult,so=Ma?.message||"Unknown failure",Ui=Ma?.failureReason??hR(so)??"UnknownError",el=be.child({failureReason:Ui,errorMessage:so,numAttempts:(X+1).toString(),name:Pe.name});if(de<X){el.warn(`Retrying failed execution attempt for run: ${so}`);continue}el.error(`Test failed after all exhausting attempts: ${so}`);let Yc=new Error(so),tl={errorMessage:so,errorStack:Yc.stack},Bi;if(F){let Mp;try{if(q.results&&q.results.length>0){let{classification:Xc,aiFailureReason:tt}=await RN({logger:be,browserStateStorage:Ae,generator:c,fullResults:q,failureReason:Ui,error:Yc,maxItemsFromEnd:void 0,numStepsWithScreenshots:void 0,disableCache:!1});Mp=Xc,Bi=tt}}catch(Xc){be.warn({err:Xc},"Failed to classify test results")}Mp&&(tl.classification=Mp,Ui=Bi??Ui)}return{...q,runAttemptId:Te,parameters:W,failureDetails:tl,failureReason:Ui,test:Pe,filePath:Pe.relativeFilePath,startedAt:G,lastAttemptStartedAt:ve,finishedAt:Mn,attempts:de+1,baseUrl:l,outputs:ce,quarantined:M,quarantinedMetadata:P}}catch(dn){let Mo=`Encountered fatal platform error while running test '${Pe.name}': ${dn}`,Mn=new Date,Oo=de+1;be.error({err:dn},Mo),v.error(Mo);let ce={errorMessage:dn.message,errStack:dn.stack},ai={status:"FAILED",failureDetails:ce,failureReason:"InternalPlatformError",finishedAt:Mn};return await te.finish({logger:be,result:{status:"FAILED",results:[]}}),{...ai,runAttemptId:Te,results:[],parameters:W,test:Pe,filePath:Pe.relativeFilePath,startedAt:G,lastAttemptStartedAt:ve,finishedAt:new Date,attempts:Oo,baseUrl:l,outputs:{},quarantined:M,quarantinedMetadata:P}}}throw new Error("This code should not be reachable")}import Ote from"adm-zip";import Lte from"path";function Pte(t){switch(t){case"PASSED":return"SUCCESS";case"FAILED":return"FAILED";case"CANCELLED":return"CANCELLED";case"RUNNING":case"PENDING":case"RETRYING":case"WAITING_FOR_USER":return"RUNNING"}}var Zs=class{constructor(e,r,n,o){this.orgId=e;this.testId=r;this.testName=n;this.diskStorage=o}children=[];finished=!1;stepFrequenciesByType={};async getScreenshot(e,r){return this.diskStorage.readFile(`${gr}/${r}.jpeg`)}async getHtmlSnapshot(e,r){return this.diskStorage.readFile(`${gr}/${r}.html`)?.toString()}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,r]of Object.entries(this.stepFrequenciesByType))Wt.increment("test_step_execution",r,[`type:${e}`,"platform:browser","executor:cli",`orgId:${this.orgId}`])}async startStep(e){let{step:r}=e;this.recordStepStat(r);let n={step:r,status:"RUNNING",startedAt:new Date},o=new KA(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(r=>r.finishInternal({status:Pte(e.status),finishedAt:e.finishedAt}))),this.sendFinalizedStepStats())}};function Mte(t){switch(t){case"SUCCESS":return"PASSED";case"FAILED":return"FAILED";case"CANCELLED":return"CANCELLED";case"RUNNING":return"RUNNING";case"IDLE":return"PENDING"}}var KA=class{constructor(e,r,n,o,i){this.orgId=e;this.testId=r;this.testName=n;this.metadata=o;this.diskStorage=i;this.interactionTracer=new Mi(void 0,a=>this.storeTraceAsset(a)),Pi.initializeRootTracerContext(this.interactionTracer)}children=[];finished=!1;interactionTracer;attachBeforeScreenshot(e){let{snapshotId:r,screenshot:n}=e;this.metadata.beforeSnapshotId=r,this.diskStorage.storeFile({name:`${gr}/${r}.jpeg`,contents:n})}attachAfterScreenshot(e){let{snapshotId:r,screenshot:n}=e;this.metadata.afterSnapshotId=r,this.diskStorage.storeFile({name:`${gr}/${r}.jpeg`,contents:n})}attachBeforeHtmlSnapshot(e){let{snapshotId:r,html:n}=e;this.metadata.beforeSnapshotId=r,this.diskStorage.storeFile({name:`${gr}/${r}.html`,contents:n})}attachAfterHtmlSnapshot(e){let{snapshotId:r,html:n}=e;this.metadata.afterSnapshotId=r,this.diskStorage.storeFile({name:`${gr}/${r}.html`,contents:n})}recordTargetAutoHeal(e){let{healType:r}=e,n=r==="AI"?"ai-target-heal":"cache-heal";Wt.increment("test_event",1,[`name:${n}`,`orgId:${this.orgId}`]),this.metadata.healMetadata={healType:r,healedAt:new Date}}recordStepDuration(e){if(!Qm(e.step))return;let r=Jm(e.step);Wt.distribution("test_step_duration",e.durationMs,[`type:${r}`,"platform:browser","executor:cli",`orgId:${this.orgId}`])}storeTraceAsset(e){this.diskStorage.storeFile({name:`${gr}/${e.snapshotId}.jpeg`,contents:e.data})}async finishInternal(e){this.finished||(this.finished=!0,this.interactionTracer.finish(),await Promise.all(this.children.map(r=>r.finish({status:Mte(e.status),finishedAt:e.finishedAt}))))}async finish(e){await this.finishInternal(e.step),e.step.trace=this.interactionTracer.getRootSpan()}async startSubSteps(){let e=new Zs(this.orgId,this.testId,this.testName,this.diskStorage);return this.children.push(e),e}};var xp=class{constructor(e,r,n,o,i,a,s){this.orgId=e;this.testId=r;this.testName=n;this.runAttemptId=o;this.metadata=i;this.diskStorage=a;this.recordVideo=s;this.diskStorage.mkdir(gr),this.harPagesStream=this.diskStorage.createFileStream(`${gr}/har-pages.log`),this.inProgressHarEntries={},this.harEntriesStream=this.diskStorage.createFileStream(`${gr}/har-entries.log`),this.resourceUsageStream=this.diskStorage.createFileStream(`${gr}/resource-usage.ndjson`),this.resourceUsageSampler=jI({keepSamples:!1,onSample:c=>{this.resourceUsageStream.write(`${JSON.stringify(c)}
|
|
5573
5574
|
`),c.system.cpu&&(this.cpuUsageSum+=c.system.cpu.total,this.cpuSampleCount++);let l=c.system.memory.total-c.system.memory.free;this.memoryUsageSum+=l,this.memorySampleCount++}})}finished=!1;children=[];harPagesStream;inProgressHarEntries;harEntriesStream;resourceUsageStream;resourceUsageSampler;cpuUsageSum=0;cpuSampleCount=0;memoryUsageSum=0;memorySampleCount=0;get loggerBindings(){return{runAttemptId:this.runAttemptId}}getResourceUsageAverages(){return{avgCpuUsage:this.cpuSampleCount>0?this.cpuUsageSum/this.cpuSampleCount:0,avgMemoryUsage:this.memorySampleCount>0?this.memoryUsageSum/this.memorySampleCount:0}}get videoOutputPath(){if(this.recordVideo)return Lte.resolve(this.diskStorage.cwd(),gr)}setActiveVideo(e,r){this.recordVideo&&(this.metadata.activeVideos=this.metadata.activeVideos||[],this.metadata.activeVideos.push({videoName:e,timestamp:r}))}onNetworkPage(e){this.finished||this.harPagesStream.write(`${JSON.stringify(e)}
|
|
5574
5575
|
`)}onNetworkLogs(e){if(!this.finished)for(let[r,n]of Object.entries(e))n.response?(delete this.inProgressHarEntries[r],this.harEntriesStream.write(`${JSON.stringify(n)}
|
|
5575
5576
|
`)):this.inProgressHarEntries[r]=n}attachConsoleLogs(e){let{logs:r}=e;this.diskStorage.storeFile({name:"console.json",contents:JSON.stringify(r,null,2)})}attachBrowserCrashDump(e){let{crashReportDirFetcher:r,logger:n}=e,o=r();if(!o)return;let i=new Ote;i.addLocalFolder(o,void 0,a=>a!==".DS_Store"),this.diskStorage.storeFile({name:`${gr}/${vE}`,contents:i.toBuffer()}),n.info({browserCrashZipName:vE},"Attached browser crash ZIP")}async finish(e){if(this.finished)return;this.finished=!0;let{logger:r,result:n}=e,o={...this.metadata,status:n.status,finishedAt:new Date,results:Sh(n.results,r),beforeResults:n.beforeResults?Sh(n.beforeResults,r):void 0,afterResults:n.afterResults?Sh(n.afterResults,r):void 0};await Promise.all(this.children.map(i=>i.finish({status:o.status,finishedAt:o.finishedAt})));for(let i of Object.values(this.inProgressHarEntries))this.harEntriesStream.write(`${JSON.stringify(i)}
|
|
@@ -5579,4 +5580,4 @@ ${t.map(p=>`${It}- ${p}`).join(`
|
|
|
5579
5580
|
${o}`),v.success(`Initialized Momentic project file at ${pr.resolve(ua)}`);let i=pr.join("swag-labs");Fi.mkdirSync(i,{recursive:!0});let a=Q(),s=Q(),c=Q(),l=[{fileName:"log-in-username-password.module.yaml",data:{fileType:ye.MODULE,moduleId:a,name:"log-in-username-password",description:"log in using username and password",enabled:!0,parameters:[],defaultCacheKey:null,defaultCacheTtl:null,defaultCacheAllInvocations:null,autoAuth:null,schemaVersion:De,steps:[{id:Q(),type:"PRESET_ACTION",command:{id:Q(),clearContent:!0,delay:50,type:"TYPE",target:{type:"description",elementDescriptor:"username input"},value:"{{env.USERNAME}}"}},{id:Q(),type:"PRESET_ACTION",command:{id:Q(),clearContent:!0,type:"TYPE",target:{type:"description",elementDescriptor:"password input"},value:"{{env.PASSWORD}}"}},{id:Q(),type:"PRESET_ACTION",command:{id:Q(),type:"CLICK",target:{type:"description",elementDescriptor:"login button"}}}]}},{fileName:"add-item-to-cart.module.yaml",data:{fileType:ye.MODULE,moduleId:s,name:"add-item-to-cart",description:"Add the specified item to cart",enabled:!0,parameters:["ITEM"],defaultCacheKey:null,defaultCacheTtl:null,defaultCacheAllInvocations:null,autoAuth:null,schemaVersion:De,steps:[{id:Q(),type:"PRESET_ACTION",command:{id:Q(),type:"CLICK",target:{type:"description",elementDescriptor:"add to cart for the {{env.ITEM}} item"}}}]}},{fileName:"fill-out-personal-info.module.yaml",data:{fileType:ye.MODULE,moduleId:c,name:"fill-out-personal-info",description:"Fill out name and zip code",enabled:!0,parameters:[],defaultCacheKey:null,defaultCacheTtl:null,defaultCacheAllInvocations:null,autoAuth:null,schemaVersion:De,steps:[{id:Q(),type:"PRESET_ACTION",command:{id:Q(),clearContent:!0,type:"TYPE",target:{type:"description",elementDescriptor:"first name input"},value:"{{faker.person.firstName()}}"}},{id:Q(),type:"PRESET_ACTION",command:{id:Q(),clearContent:!0,type:"TYPE",target:{type:"description",elementDescriptor:"last name input"},value:"{{faker.person.lastName()}}"}},{id:Q(),type:"PRESET_ACTION",command:{id:Q(),clearContent:!0,type:"TYPE",target:{type:"description",elementDescriptor:"zip code input"},value:"{{faker.location.zipCode()}}"}}]}}],u=[{fileName:"standard-user-purchases.test.yaml",data:{fileType:ye.TEST,id:Q(),name:"standard-user-purchases",baseUrl:"",description:"End-to-end checkout flow",schemaVersion:De,advanced:{viewport:{width:1920,height:1080},browserType:"Chromium"},retries:1,envs:[{name:"swag-labs",default:!0}],disabled:!1,labels:[],steps:[{id:Q(),type:"MODULE",moduleId:a},{id:Q(),inputs:{ITEM:'"sauce labs backpack"'},type:"MODULE",moduleId:s},{id:Q(),inputs:{ITEM:'"sauce labs onesie"'},type:"MODULE",moduleId:s},{id:Q(),type:"PRESET_ACTION",command:{id:Q(),type:"CLICK",target:{type:"description",elementDescriptor:"Cart icon on the top right of the page"}}},{id:Q(),type:"PRESET_ACTION",command:{id:Q(),type:"AI_ASSERTION",assertion:"Verify that both the backpack and the onesie is in the cart"}},{id:Q(),type:"PRESET_ACTION",command:{id:Q(),type:"CLICK",target:{type:"description",elementDescriptor:"Checkout button"}}},{id:Q(),type:"MODULE",moduleId:c},{id:Q(),type:"PRESET_ACTION",command:{id:Q(),type:"CLICK",target:{type:"description",elementDescriptor:"Continue button"}}},{id:Q(),type:"PRESET_ACTION",command:{id:Q(),type:"AI_ASSERTION",assertion:"Verify the item total matches the amount listed for each item"}},{id:Q(),type:"PRESET_ACTION",command:{id:Q(),type:"AI_ASSERTION",assertion:"Verify the total matches item total + tax"}},{id:Q(),type:"PRESET_ACTION",command:{id:Q(),type:"CLICK",target:{type:"description",elementDescriptor:"Finish button"}}},{id:Q(),type:"PRESET_ACTION",command:{id:Q(),type:"AI_ASSERTION",assertion:"Verify there is a thank you message"}}]}},{fileName:"problem-user-adds-tshirt.test.yaml",data:{fileType:ye.TEST,id:Q(),name:"problem-user-adds-tshirt",baseUrl:"https://saucedemo.com",description:"Test that problem_user can add a t-shirt to cart",schemaVersion:De,advanced:{viewport:{width:1920,height:1080},browserType:"Chromium"},retries:1,steps:[{id:Q(),type:"PRESET_ACTION",command:{id:Q(),clearContent:!0,type:"TYPE",target:{type:"description",elementDescriptor:"username input"},value:"problem_user"}},{id:Q(),type:"PRESET_ACTION",command:{id:Q(),clearContent:!0,type:"TYPE",target:{type:"description",elementDescriptor:"password input"},value:"secret_sauce"}},{id:Q(),type:"PRESET_ACTION",command:{id:Q(),type:"CLICK",target:{type:"description",elementDescriptor:"Login button"}}},{id:Q(),inputs:{ITEM:"'Sauce Labs Bolt T-Shirt'"},type:"MODULE",moduleId:s},{id:Q(),type:"PRESET_ACTION",command:{id:Q(),type:"CLICK",target:{type:"description",elementDescriptor:"shopping cart icon in the top right"}}},{id:Q(),type:"PRESET_ACTION",command:{id:Q(),type:"AI_ASSERTION",assertion:"The Sauce Labs Bolt T-Shirt should be listed as an item in the cart",timeout:5}}]}},{fileName:"cart-and-sorting-behavior.test.yaml",data:{fileType:ye.TEST,id:Q(),name:"cart-and-sorting-behavior",baseUrl:"",description:"Sorting changes view, not state; cart remains consistent",schemaVersion:De,advanced:{viewport:{width:1920,height:1080},browserType:"Chromium"},retries:1,envs:[{name:"swag-labs",default:!0}],disabled:!1,labels:[],steps:[{id:Q(),type:"MODULE",moduleId:a},{id:Q(),type:"PRESET_ACTION",command:{id:Q(),type:"SELECT_OPTION",target:{type:"description",elementDescriptor:"sort dropdown"},choice:{type:"LABEL",label:"Price (low to high)"}}},{id:Q(),type:"PRESET_ACTION",command:{id:Q(),type:"AI_ASSERTION",assertion:"Verify the first item is the cheapest one on the page"}},{id:Q(),type:"PRESET_ACTION",command:{id:Q(),type:"AI_ASSERTION",assertion:"Verify the last item on the page is the most expensive one",timeout:5}},{id:Q(),inputs:{ITEM:'"cheapest item"'},type:"MODULE",moduleId:s},{id:Q(),type:"PRESET_ACTION",command:{id:Q(),type:"CLICK",target:{type:"description",elementDescriptor:"Cart icon on the top right"}}},{id:Q(),type:"PRESET_ACTION",command:{id:Q(),type:"CLICK",target:{type:"description",elementDescriptor:"Checkout button"}}},{id:Q(),type:"MODULE",moduleId:c},{id:Q(),type:"PRESET_ACTION",command:{id:Q(),type:"CLICK",target:{type:"description",elementDescriptor:"Continue button"}}},{id:Q(),type:"PRESET_ACTION",command:{id:Q(),type:"CLICK",target:{type:"description",elementDescriptor:"Finish button"}}},{id:Q(),type:"PRESET_ACTION",command:{id:Q(),type:"ELEMENT_CHECK",target:{type:"description",elementDescriptor:"Back home button"},assertion:{type:"ELEMENT_EXISTENCE",condition:"EXISTS"}}}]}}];for(let{fileName:d,data:p}of l)IN(p,pr.join(i,d));for(let{fileName:d,data:p}of u)ON(p,pr.join(i,d));v.success(`Created sample Swag Labs tests and modules in ${pr.resolve(i)}/`)});nr.command("app").addOption(In).addOption(Pn).addOption(Ia).addOption(nS).addOption(Br).addOption(lz).addOption(FA).addOption(aS).addOption(sS).action(async t=>{await Po(le),le.setApp("desktop-server");let{apiKey:e,yes:r,server:n,pixelRatio:o,port:i,disableCache:a,saveCache:s,regenerateCache:c}=t;rh({disableCache:a,saveCache:s,regenerateCache:c});let l=await Ct({configFilePath:t.config,nameFilter:void 0}),{errors:u,parsingErrors:d,failedTestFilePaths:p,failedModuleFilePaths:m,parsingErrorDetails:f}=await Rp({project:l,fix:!1});d>0?(uc({parsingErrors:d,parsingErrorDetails:f,failedTestFilePaths:p,failedModuleFilePaths:m}),process.exit(1)):u>0&&(v.error(`Found ${u} errors`),v.warn("To fix these errors automatically, run the duplicate-ids check with the --fix flag and then commit the resulting changes"),process.exit(1)),VI(le);let h=new pt({baseUrl:n,apiKey:e,logger:le});await Gh({client:h,skipPrompts:r});let S=S1(import.meta.url),g=pr.dirname(S),E=pr.resolve(g,"..","static"),y=pr.resolve(g,"..","assets"),b=o??gS();SS(b),await jB({momenticServerUrl:n,apiKey:e,serverPort:i,appPort:i,staticDir:E,assetsDir:y,devicePixelRatio:b,regenerateCache:c??!1,noCache:a??!1,alwaysSaveCache:s??!1,initialProject:l});let C=`http://localhost:${i}`;await Wte(C)});nr.command("mcp").description("Start the MCP server over stdio.").addOption(In).addOption(Pn).addOption(Br).addOption(aS).addOption(sS).addOption(cz).addOption(nS).addOption(xz).action(async t=>{le.setApp("mcp"),v.setMinLevel(Number.POSITIVE_INFINITY);let{apiKey:e,server:r,saveCache:n,disableCache:o,headfulBrowser:i,pixelRatio:a,sessionIdleTimeoutMinutes:s}=t;rh({disableCache:o,saveCache:n});let c=i!==void 0?i:zl(process.env.MOMENTIC_HEADFUL_BROWSER)??!0,l=a??gS();SS(l);let u=await Ct({configFilePath:t.config,nameFilter:void 0}),{errors:d,parsingErrors:p,failedTestFilePaths:m,failedModuleFilePaths:f,parsingErrorDetails:h}=await Rp({project:u,fix:!1});p>0?(uc({parsingErrors:p,parsingErrorDetails:h,failedTestFilePaths:m,failedModuleFilePaths:f}),process.exit(1)):d>0&&(v.error(`Found ${d} errors`),v.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 S=new pt({baseUrl:r,apiKey:e,logger:le});if(await Gh({client:S,skipPrompts:!0}),!Zr)throw new Error("CLI_VERSION is not set");await yA({project:u,logger:le,apiKey:e,serverUrl:r,cliVersion:Zr,supportsFileOutput:!0,alwaysSaveCache:n??!1,noCache:o??!1,headfulBrowserDefault:c,devicePixelRatio:l,sessionIdleTimeoutMinutes:s})});var b1=nr.command("queue").description("Queue tests or suites to run on Momentic Cloud");b1.command("suites").description("Run one or more suites on Momentic Cloud").addOption(In).addOption(Pn).addOption(MA).addOption(OA).addOption(Ia).addArgument(Az).addOption(iS).addOption(oS).addOption(rS).action(async(t,e)=>{await Po(le);let{apiKey:r,server:n,wait:o,waitTimeout:i,env:a,urlOverride:s}=e,c=tS(e.customHeaders),l=new pt({baseUrl:n,apiKey:r,logger:le});(!t||!Array.isArray(t)||!t.length)&&(v.error("Must pass at least one suite to run."),process.exit(1));let{orgId:u}=await l.getAuthInfo();await Uz({client:l,orgId:u,wait:o,suitePaths:t,waitTimeout:i,env:a,urlOverride:s,customHeaders:c}),await ki()});b1.command("tests").description("Run one or more tests on Momentic Cloud").addOption(In).addOption(Pn).addOption(Ia).addOption(rS).addOption(kA).addOption(iS).addOption(oS).addOption(new zr("--all","Run all tests.").default(!1)).addOption(MA).addOption(OA).addArgument(bz).action(async(t,e)=>{await Po(le);let{all:r,apiKey:n,env:o,server:i,inputCsv:a,urlOverride:s,wait:c,waitTimeout:l,yes:u}=e,d=tS(e.customHeaders);for(let h of t)(h.endsWith(".yaml")||Fi.existsSync(h))&&v.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 pt({baseUrl:i,apiKey:n,logger:le}),{orgId:m}=await p.getAuthInfo(),f;a&&(f=await $A(a)),await Bz({client:p,orgId:m,tests:t,all:r,customHeaders:d,env:o,urlOverride:s,wait:c,waitTimeout:l,testInputMatrix:f,yes:u}),await ki(),process.exit(0)});var qte=nr.command("list").description("List test paths");qte.addOption(Br).addOption(Pa).addOption(NA).addOption(DA).addOption(new zr("--labels <labels...>","Only run tests with the specified label(s).")).addArgument(UA).action(async(t,e)=>{let r=await Ct({configFilePath:e.config,nameFilter:e.filter}),n=await fe(r),o=await Wc({tests:t,momenticFiles:n,yes:!0,project:r,include:e.include,exclude:e.exclude,labels:e.labels,logger:new ss(40,{})});v.info(o.map(i=>i.relativeFilePath).join(`
|
|
5580
5581
|
`)),process.exit(0)});var Kte=nr.command("run").alias("test").description("Run tests on the local machine");Kte.addOption(In).addOption(Pn).addOption(Br).addOption(Pa).addOption(Ia).addOption(rS).addOption(kA).addOption(FA).addOption(aS).addOption(sS).addOption(gz).addOption(Tz).addOption(Sz).addOption(yz).addOption(Ez).addOption(oS).addOption(iS).addOption(nS).addOption(new zr("--start <start>","Arbitrary setup command that will run before Momentic steps begin.")).addOption(new zr("--wait-on <waitOn>","URL to wait to become accessible before Momentic tests begin.")).addOption(new zr("--wait-on-proxy <waitOnProxy>","HTTP proxy to use with the --wait-on command. Specify as https://username:pass@domain.com:2345")).addOption(new zr("--wait-on-timeout <waitOnTimeout>","Max time in seconds to wait for the --wait-on URL to become accessible.").default(60).argParser(_n)).addOption(new zr("--retries <retries>","Number of retries to attempt when running tests locally. Defaults to each test's own retry configuration.").argParser(_n)).addOption(new zr("-p, --parallel <parallel>","The number of tests to run in parallel. Defaults to 1.").argParser(_n)).addOption(new zr("--labels <labels...>","Only run tests with the specified label(s).")).addOption(wz).addOption(new zr("--update-golden-files","Update locally stored golden files for steps that this is enabled for.").default(!1)).addOption(uz).addOption(dz).addOption(LA).addOption(pz).addOption(fz).addOption(mz).addOption(NA).addOption(DA).addOption(Rz).addOption(_z).addArgument(UA).action(async(t,e)=>{await Po(le);let{disableCache:r,saveCache:n,regenerateCache:o,name:i}=e;rh({disableCache:r,saveCache:n,regenerateCache:o}),uL({shardIndex:e.shardIndex,shardCount:e.shardCount});let a=tS(e.customHeaders),s=await Ct({configFilePath:e.config,nameFilter:e.filter}),c=e.parallel??s.config.parallel??1;g1().length<c*2&&v.warn(`You requested to run tests in parallel ${c} at a time on a machine with ${g1().length} cores. This may cause performance issues and test failures as Chrome requires at least 2 cores per browser instance.`),v.debug({projectName:s.config.name},"Identified project config");let{errors:l,parsingErrors:u,parsingErrorDetails:d,failedTestFilePaths:p,failedModuleFilePaths:m}=await Rp({project:s,fix:!1});u>0?(uc({parsingErrors:u,parsingErrorDetails:d,failedTestFilePaths:p,failedModuleFilePaths:m}),process.exit(1)):l>0&&(v.error(`Found ${l} errors`),v.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 f=new pt({baseUrl:e.server,apiKey:e.apiKey,logger:le});v.debug("Checking API key and dependencies");let{orgId:h,userId:S}=await Gh({client:f,skipPrompts:e.yes});v.debug("API key check and browser installation complete");let g=e.outputDir??s.config.outputDir,E=e.reporterDir??s.config.reporterDir,y=jte(),b=le.child({cliVersion:Zr,orgId:h,userId:S,runGroupId:y}),C=await Er(le,f,s);b.info({gitMetadata:C,config:s.config,nodeVersion:process.versions.node},"Got local metadata");let I;e.inputCsv&&(I=await $A(e.inputCsv));let _=e.pixelRatio??gS();SS(_);try{let R=await m1({...e,suiteName:i,parallel:c,retriesOverride:e.retries,devicePixelRatio:_,tests:t,project:s,client:f,outputDir:g,uploadResults:e.uploadResults,reporterDir:E,customHeaders:a,envName:e.env,orgId:h,testInputMatrix:I,logger:b,regenerateGoldenFiles:e.updateGoldenFiles,gitMetadata:C,cacheOptions:{regenerateCache:o??!1,alwaysSaveCache:n??!1,noCache:r??!1,bustOldestCachePercentage:e.bustOldestCachePercentage},recordVideo:e.recordVideo??s.config.recordVideo,runGroupId:y,timeoutMinutes:e.timeoutMinutes,browserTypeOverride:e.browser});await ki(),R.failed>0?process.exit(1):process.exit(0)}catch(R){v.error("Failed to run tests locally. Please check the error message below or run with the --verbose flag."),v.error(R),await ki(),process.exit(1)}});var Yte=nr.command("apply").description("Apply an operation to local resources");Yte.command("patch").addOption(In).addOption(Pn).addOption(Br).addOption(Pa).addOption(Ia).addOption(new zr("--from <from>","Name or ID of the patch to apply").makeOptionMandatory()).addOption(new zr("--to <to>","Name or ID of the test to apply the patch to").makeOptionMandatory()).action(async t=>{let{apiKey:e,server:r,config:n,yes:o}=t,i=await Ct({configFilePath:n}),a=le,s=new pt({baseUrl:r,apiKey:e,logger:a}),c=await fe(i),l=c.tests[t.to]??Object.values(c.tests).find(d=>dt(d.name)===t.to.trim());l||(v.error(`No test matching '${t.to}' could be found in the current project.`),process.exit(1));let u=await s.fetchTestFragment(t.from);await XB({client:s,test:l,fragment:u,yes:o,entities:c,logger:le}),process.exit(0)});var XA=nr.command("results").description("Merge and upload test results.");XA.command("merge").description("Merge test results files.").addOption(LA).addArgument(Cz).action(async(t,e)=>{let{outputDir:r}=e;r||(v.error("Output directory is required."),process.exit(1)),Fi.existsSync(t)||(v.warn("Results path does not exist, skipping merge."),process.exit(0)),Fi.existsSync(r)&&v.warn(`Output directory ${r} already exists, removing before merging...`),QN(le,r,t)});XA.command("upload").description("Upload test results to Momentic cloud.").addOption(In).addOption(Pn).addArgument(BA).action(async(t,e)=>{let{apiKey:r,server:n}=e,o=le,i=new pt({baseUrl:n,apiKey:r,logger:o});await $h({consoleLogger:v,resultsPath:t,client:i}),process.exit(0)});XA.command("view").description("Launch the run viewer to view test results in your current directory.").addOption(new zr("--port <port>",`Port to run the backend server on. Defaults to ${Bm}.`).argParser(_n)).addArgument(BA).addArgument(new zte("<runId>","Run ID to open in the viewer.").argOptional()).action(async(t,e,r)=>{await Po(le),le.setApp("local-run-viewer");let n=S1(import.meta.url),o=pr.dirname(n),i=pr.resolve(o,"..","run-viewer-static");await IA({logger:le,staticDir:i,resultsPath:t,runId:e,port:r.port})});var JA=nr.command("quarantine").description("Manage test quarantines");JA.command("add").description("Add a test to the quarantine. This will prevent it from running.").addOption(In).addOption(Pn).addOption(Br).addOption(Pa).addOption(zA).addArgument(HA).action(async(t,e)=>{let{apiKey:r,server:n,config:o,reason:i}=e,a=le,s=await Ct({configFilePath:o}),c=new pt({baseUrl:n,apiKey:r,logger:a}),l=await Er(le,c,s);await Mz({test:t,reason:i,apiClient:c,project:s,logger:a,identity:l})});JA.command("list").description("List quarantined tests.").addOption(In).addOption(Pn).addOption(Br).addOption(Pa).action(async t=>{let{apiKey:e,server:r,config:n}=t,o=le,i=await Ct({configFilePath:n}),a=new pt({baseUrl:r,apiKey:e,logger:o});await Dz({apiClient:a,project:i})});JA.command("remove").description("Remove a test from the quarantine. This will allow it to run again.").addOption(In).addOption(Pn).addOption(Br).addOption(Pa).addOption(zA).addArgument(HA).action(async(t,e)=>{let{apiKey:r,server:n,config:o,reason:i}=e,a=le,s=await Ct({configFilePath:o}),c=new pt({baseUrl:n,apiKey:r,logger:a}),l=await Er(le,c,s);await kz({test:t,reason:i,apiClient:c,project:s,identity:l})});nr.command("upgrade").description("Upgrade your configuration to the latest recommended settings").addOption(Br).addOption(Pa).action(async t=>{let e=await Ct({configFilePath:t.config,nameFilter:t.filter});v.info("Updating Momentic version in package.json..."),await f1(),v.info("Updating project configuration..."),h1(e),v.success("Your project configuration was successfully updated to the latest recommended settings."),v.info("You can optionally run tests with the `--regenerate-cache` flag to entirely rebuild caches with the newer configuration. Warning: using this option will cause all steps to run without any cached data, resulting in significantly longer execution times.")});async function Xte(){E1("Main program started");try{await nr.parseAsync(process.argv),await ki()}catch(t){let e={};try{e.playwrightVersion=Gte("npx playwright --version").toString()}catch(r){le.error({err:r},"Error fetching debug information")}le.error({err:t,debugInfo:e},"Uncaught error in CLI"),v.error(t),await ki(),process.exit(1)}}Vte.setMaxListeners(25);process.on("warning",t=>{le.warn({err:t},`Node warning received on CLI: ${t.message}`)});E1("CLI parsing setup complete");Xte();
|
|
5581
5582
|
//# sourceMappingURL=cli.js.map
|
|
5582
|
-
//# debugId=
|
|
5583
|
+
//# debugId=58b67399-a7d2-5cb5-8cb3-2de3e5b859f3
|