momentic 2.72.0 → 2.72.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/bin/cli.js
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
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 PH=Object.create;var wS=Object.defineProperty;var MH=Object.getOwnPropertyDescriptor;var OH=Object.getOwnPropertyNames;var LH=Object.getPrototypeOf,NH=Object.prototype.hasOwnProperty;var Mt=(t,e)=>()=>(t&&(e=t(t=0)),e);var DH=(t,e)=>()=>(e||t((e={exports:{}}).exports,e),e.exports),kH=(t,e)=>{for(var r in e)wS(t,r,{get:e[r],enumerable:!0})},UH=(t,e,r,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of OH(e))!NH.call(t,o)&&o!==r&&wS(t,o,{get:()=>e[o],enumerable:!(n=MH(e,o))||n.enumerable});return t};var iC=(t,e,r)=>(r=t!=null?PH(LH(t)):{},UH(e||!t||!t.__esModule?wS(r,"default",{value:t,enumerable:!0}):r,t));var ZI,eP=Mt(()=>{"use strict";ZI=typeof globalThis=="object"?globalThis:global});var tP=Mt(()=>{"use strict";eP()});var rP=Mt(()=>{"use strict";tP()});var yi,DE=Mt(()=>{"use strict";yi="1.9.0"});function tq(t){var e=new Set([t]),r=new Set,n=t.match(nP);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(nP);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 nP,oP,iP=Mt(()=>{"use strict";DE();nP=/^(\d+)\.(\d+)\.(\d+)(-(.+))?$/;oP=tq(yi)});function Jl(t,e,r,n){var o;n===void 0&&(n=!1);var i=md[pd]=(o=md[pd])!==null&&o!==void 0?o:{version:yi};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!==yi){var a=new Error("@opentelemetry/api: Registration of version v"+i.version+" for "+t+" does not match previously registered API v"+yi);return r.error(a.stack||a.message),!1}return i[t]=e,r.debug("@opentelemetry/api: Registered a global for "+t+" v"+yi+"."),!0}function Ei(t){var e,r,n=(e=md[pd])===null||e===void 0?void 0:e.version;if(!(!n||!oP(n)))return(r=md[pd])===null||r===void 0?void 0:r[t]}function Ql(t,e){e.debug("@opentelemetry/api: Unregistering a global for "+t+" v"+yi+".");var r=md[pd];r&&delete r[t]}var rq,pd,md,fd=Mt(()=>{"use strict";rP();DE();iP();rq=yi.split(".")[0],pd=Symbol.for("opentelemetry.js.api."+rq),md=ZI});function hd(t,e,r){var n=Ei("diag");if(n)return r.unshift(e),n[t].apply(n,oq([],nq(r),!1))}var nq,oq,aP,sP=Mt(()=>{"use strict";fd();nq=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},oq=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))},aP=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 hd("debug",this._namespace,e)},t.prototype.error=function(){for(var e=[],r=0;r<arguments.length;r++)e[r]=arguments[r];return hd("error",this._namespace,e)},t.prototype.info=function(){for(var e=[],r=0;r<arguments.length;r++)e[r]=arguments[r];return hd("info",this._namespace,e)},t.prototype.warn=function(){for(var e=[],r=0;r<arguments.length;r++)e[r]=arguments[r];return hd("warn",this._namespace,e)},t.prototype.verbose=function(){for(var e=[],r=0;r<arguments.length;r++)e[r]=arguments[r];return hd("verbose",this._namespace,e)},t}()});var At,df=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 lP(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 cP=Mt(()=>{"use strict";df()});var iq,aq,sq,jo,gd=Mt(()=>{"use strict";sP();cP();df();fd();iq=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},aq=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))},sq="diag",jo=function(){function t(){function e(o){return function(){for(var i=[],a=0;a<arguments.length;a++)i[a]=arguments[a];var s=Ei("diag");if(s)return s[o].apply(s,aq([],iq(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=Ei("diag"),d=lP((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 Jl("diag",d,r,!0)};r.setLogger=n,r.disable=function(){Ql(sq,r)},r.createComponentLogger=function(o){return new aP(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 uP,dP=Mt(()=>{"use strict";uP=Symbol("BaggageEntryMetadata")});function kE(t){return typeof t!="string"&&(lq.error("Cannot create baggage metadata from unknown type: "+typeof t),t=""),{__TYPE__:uP,toString:function(){return t}}}var lq,pP=Mt(()=>{"use strict";gd();dP();lq=jo.instance()});function UE(t){return Symbol.for(t)}var cq,FE,BE=Mt(()=>{"use strict";cq=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}(),FE=new cq});function GE(){return HE}var ms,uq,pf,dq,pq,mq,fq,zE,hq,gq,Sq,HE,yq,Eq,Tq,bq,vq,Aq,Cq,jE=Mt(()=>{"use strict";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)}}(),uq=function(){function t(){}return t.prototype.createGauge=function(e,r){return Eq},t.prototype.createHistogram=function(e,r){return Tq},t.prototype.createCounter=function(e,r){return yq},t.prototype.createUpDownCounter=function(e,r){return bq},t.prototype.createObservableGauge=function(e,r){return Aq},t.prototype.createObservableCounter=function(e,r){return vq},t.prototype.createObservableUpDownCounter=function(e,r){return Cq},t.prototype.addBatchObservableCallback=function(e,r){},t.prototype.removeBatchObservableCallback=function(e){},t}(),pf=function(){function t(){}return t}(),dq=function(t){ms(e,t);function e(){return t!==null&&t.apply(this,arguments)||this}return e.prototype.add=function(r,n){},e}(pf),pq=function(t){ms(e,t);function e(){return t!==null&&t.apply(this,arguments)||this}return e.prototype.add=function(r,n){},e}(pf),mq=function(t){ms(e,t);function e(){return t!==null&&t.apply(this,arguments)||this}return e.prototype.record=function(r,n){},e}(pf),fq=function(t){ms(e,t);function e(){return t!==null&&t.apply(this,arguments)||this}return e.prototype.record=function(r,n){},e}(pf),zE=function(){function t(){}return t.prototype.addCallback=function(e){},t.prototype.removeCallback=function(e){},t}(),hq=function(t){ms(e,t);function e(){return t!==null&&t.apply(this,arguments)||this}return e}(zE),gq=function(t){ms(e,t);function e(){return t!==null&&t.apply(this,arguments)||this}return e}(zE),Sq=function(t){ms(e,t);function e(){return t!==null&&t.apply(this,arguments)||this}return e}(zE),HE=new uq,yq=new dq,Eq=new mq,Tq=new fq,bq=new pq,vq=new hq,Aq=new gq,Cq=new Sq});var Tn,mP=Mt(()=>{"use strict";(function(t){t[t.INT=0]="INT",t[t.DOUBLE=1]="DOUBLE"})(Tn||(Tn={}))});var Rq,wq,fP,hP=Mt(()=>{"use strict";BE();Rq=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},wq=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))},fP=function(){function t(){}return t.prototype.active=function(){return FE},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,wq([n],Rq(o),!1))},t.prototype.bind=function(e,r){return r},t.prototype.enable=function(){return this},t.prototype.disable=function(){return this},t}()});var xq,_q,VE,Iq,gP,SP=Mt(()=>{"use strict";hP();fd();gd();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},_q=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))},VE="context",Iq=new fP,gP=function(){function t(){}return t.getInstance=function(){return this._instance||(this._instance=new t),this._instance},t.prototype.setGlobalContextManager=function(e){return Jl(VE,e,jo.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,_q([e,r,n],xq(i),!1))},t.prototype.bind=function(e,r){return this._getContextManager().bind(e,r)},t.prototype._getContextManager=function(){return Ei(VE)||Iq},t.prototype.disable=function(){this._getContextManager().disable(),Ql(VE,jo.instance())},t}()});var Zl,yP=Mt(()=>{"use strict";SP();Zl=gP.getInstance()});var ie,EP=Mt(()=>{"use strict";gd();ie=jo.instance()});var Pq,TP,bP=Mt(()=>{"use strict";jE();Pq=function(){function t(){}return t.prototype.getMeter=function(e,r,n){return HE},t}(),TP=new Pq});var WE,vP,AP=Mt(()=>{"use strict";bP();fd();gd();WE="metrics",vP=function(){function t(){}return t.getInstance=function(){return this._instance||(this._instance=new t),this._instance},t.prototype.setGlobalMeterProvider=function(e){return Jl(WE,e,jo.instance())},t.prototype.getMeterProvider=function(){return Ei(WE)||TP},t.prototype.getMeter=function(e,r,n){return this.getMeterProvider().getMeter(e,r,n)},t.prototype.disable=function(){Ql(WE,jo.instance())},t}()});var mf,CP=Mt(()=>{"use strict";AP();mf=vP.getInstance()});var yt=Mt(()=>{"use strict";pP();BE();df();jE();mP();yP();EP();CP()});var Qv=DH((dp,Jv)=>{"use strict";(function(t,e){if(typeof dp=="object"&&typeof Jv=="object")Jv.exports=e();else if(typeof define=="function"&&define.amd)define([],e);else{var r=e();for(var n in r)(typeof dp=="object"?dp:t)[n]=r[n]}})(typeof self<"u"?self:dp,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 ARe,{multistream as RRe}from"pino";import xRe from"pino-pretty";import{z as xS}from"zod";var sre=xS.object({input:xS.string(),agentConfigVersion:xS.string().optional()}),Bp="finish";import{z as er}from"zod";var ure=er.object({srcs:er.array(er.string()),urls:er.array(er.string()),desiredSrc:er.string().optional(),desiredUrl:er.string().optional()}),aC=er.object({srcRegex:er.string().optional(),urlRegex:er.string().optional()}),sC=er.object({x:er.number(),y:er.number(),correlation:er.number()}),dre=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 FH}from"zod-openapi";import eu from"zod";var tu=eu.object({updatedAt:eu.coerce.date().optional()}),Fa=eu.object({contentType:eu.enum(["image/jpeg","image/png"]),id:eu.string()});FH(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||{}),BH=j.object({mPathSelectorTokens:j.string().array(),frameSrcRegex:j.string().optional(),frameUrlRegex:j.string().optional(),indices:j.number().array()}),ru=j.object({result:j.number(),traceId:j.string()}).array(),uo=j.object({type:j.literal("GCS_TRACES"),traces:ru}),tn=(o=>(o.PRECISE="precise",o.NARROW="narrow",o.BROAD="broad",o.IRRELEVANT="irrelevant",o))(tn||{}),lC=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(tn)}).optional(),shape:j.object({width:j.number(),height:j.number(),tolerance:j.nativeEnum(tn)}).optional(),boundingBox:j.object({x:j.number(),y:j.number(),width:j.number(),height:j.number()}).optional()}),zH=j.object({selectors:j.string().array(),requirements:lC.optional(),relativeAngleRadians:j.number().min(0).max(2*Math.PI).optional(),relativeDistance:j.number().optional()}),ci=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:lC.optional(),additionalElements:zH.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(Fa.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:BH.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:uo.optional()}).openapi({ref:"ElementTargetCache"});function nl(t){return!!(t.serializedHtml||t.screenshotUrl||t.generatedSelectors||t.hybridSelector)}var HH=j.object({type:j.literal("description"),elementDescriptor:j.string().describe("Description of the element.")}).openapi({ref:"DescriptionTarget"}),GH=j.object({x:j.number(),y:j.number()}),jH=j.object({type:j.literal("coordinates"),pixels:GH}).openapi({ref:"CoordinatesTarget"});function Gi(t){return t.type==="description"}function No(t){return t.type==="coordinates"}var xr=j.discriminatedUnion("type",[HH,jH]).openapi({ref:"ElementTarget"});function _S(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 zp(t){return uo.safeParse(t).success}import{v4 as lt}from"uuid";import*as w from"zod";import{extendZodWithOpenApi as t1}from"zod-openapi";import{z as ze}from"zod";import{extendZodWithOpenApi as VH}from"zod-openapi";import{z as nu}from"zod";var ou=nu.object({result:nu.boolean(),traceId:nu.string()}).array(),Ba=nu.object({type:nu.literal("GCS_TRACES"),traces:ou}),IS=tu.extend({memory:Ba.optional()});var ol=(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))(ol||{});VH(ze);var cC=ze.object({thoughts:ze.string(),result:ze.boolean(),relevantElements:ze.array(ze.number()).optional(),updatedMemory:ou.optional()}),fn=(o=>(o.CONTAINS="CONTAINS",o.STARTS_WITH="STARTS_WITH",o.EQUALS="EQUALS",o.EXISTS="EXISTS",o))(fn||{});var PS=["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"],WH=ze.object({type:ze.literal("ELEMENT_NAME"),negated:ze.boolean().optional(),operation:ze.nativeEnum(fn),value:ze.string()}).openapi({ref:"ElementNameAssertion"}),$H=ze.object({type:ze.literal("ELEMENT_STYLE"),negated:ze.boolean().optional(),operation:ze.nativeEnum(fn),property:ze.string(),value:ze.string()}).openapi({ref:"ElementStyleAssertion"}),qH=ze.object({type:ze.literal("ELEMENT_CONTENT"),negated:ze.boolean().optional(),operation:ze.nativeEnum(fn),value:ze.string()}).openapi({ref:"ElementContentAssertion"}),KH=ze.object({type:ze.literal("ELEMENT_ATTRIBUTE"),negated:ze.boolean().optional(),operation:ze.nativeEnum(fn),attr:ze.string(),value:ze.string()}).openapi({ref:"ElementAttributeValueAssertion"}),Ln=(i=>(i.EXISTS="EXISTS",i.VISIBLE="VISIBLE",i.ENABLED="ENABLED",i.EDITABLE="EDITABLE",i.FOCUSED="FOCUSED",i))(Ln||{});var YH=ze.object({type:ze.literal("ELEMENT_EXISTENCE"),negated:ze.boolean().optional(),condition:ze.nativeEnum(Ln).describe("Treated as the element exists AND is also ...")}).openapi({ref:"ElementExistenceAssertion"}),Hp=ze.discriminatedUnion("type",[qH,KH,YH,WH,$H]).openapi({ref:"ManualElementAssertion"});var XH=ze.object({type:ze.literal("CONTENT"),negated:ze.boolean().optional(),value:ze.string()}).openapi({ref:"PageContentAssertion"}),uC=ze.discriminatedUnion("type",[XH]).openapi({ref:"ManualPageAssertion"});import Gr from"zod";var MS=Gr.discriminatedUnion("type",[Gr.object({type:Gr.literal("SUBSTRING"),url:Gr.string()}),Gr.object({type:Gr.literal("GLOB"),glob:Gr.string()}),Gr.object({type:Gr.literal("REGEX"),regex:Gr.string()}),Gr.object({type:Gr.literal("DOMAIN"),domain:Gr.string()})]),Do=Gr.object({urlMatcher:MS,method:Gr.string().optional()});import{z as Qe}from"zod";var JH=Qe.object({type:Qe.literal("json"),content:Qe.string().describe("The JSON content to send in the request body")}),QH=Qe.object({type:Qe.literal("form-urlencoded"),content:Qe.record(Qe.string(),Qe.string()).describe("The form fields to send in the request body")}),ZH=Qe.discriminatedUnion("type",[JH,QH]),e1=["GET","POST","PUT","DELETE","PATCH"],iu=Qe.enum(e1),za=Qe.object({url:Qe.string(),method:iu,headers:Qe.record(Qe.string(),Qe.string()).optional(),params:Qe.record(Qe.string(),Qe.string()).optional(),body:ZH.optional(),timeout:Qe.number().int().optional().describe("Max seconds to wait for the request to complete")}),dC=Qe.object({url:Qe.string(),headers:Qe.record(Qe.string(),Qe.string()).optional(),query:Qe.string(),variables:Qe.string().optional(),timeout:Qe.number().int().optional().describe("Max seconds to wait for the request to complete")}),Gp=Qe.object({code:Qe.string(),fragment:Qe.boolean().optional().describe("Agents should not touch this unless explicitly told to"),environment:Qe.union([Qe.literal("NODE"),Qe.literal("BROWSER")]).optional().describe("default NODE, Agents default to using node unless it is necessary to use browser"),timeout:Qe.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||{});t1(w);var he=w.object({thoughts:w.string().optional(),id:w.string().uuid().describe("unique identifier to this step, used for step cache")}),Dn=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"}),hn=tu.extend({target:ci}).optional().openapi({ref:"SingleTargetCache"});function jp(t){return!!t&&hn.safeParse(t).success}var Vp=w.object({loadTimeout:w.number().int().max(60).optional().describe("Max seconds for the page to load")}),pC=he.merge(Vp).merge(w.object({type:w.literal("NAVIGATE"),url:w.string()})).openapi({ref:"NavigateCommand"}),Wp=Dn.merge(w.object({cache:hn})),Ha=he.merge(Wp.merge(w.object({target:xr.optional(),type:w.literal("SCROLL_UP"),deltaY:w.number().optional()}))).openapi({ref:"ScrollUpCommand"}),Ga=he.merge(Wp.merge(w.object({target:xr.optional(),type:w.literal("SCROLL_DOWN"),deltaY:w.number().optional()}))).openapi({ref:"ScrollDownCommand"}),il=he.merge(Wp.merge(w.object({target:xr.optional(),type:w.literal("SCROLL_LEFT"),deltaX:w.number().optional()}))).openapi({ref:"ScrollLeftCommand"}),al=he.merge(Wp.merge(w.object({target:xr.optional(),type:w.literal("SCROLL_RIGHT"),deltaX:w.number().optional()}))).openapi({ref:"ScrollRightCommand"}),$re=w.discriminatedUnion("type",[Ha,Ga,il,al]).openapi({ref:"AllScrollCommands"}),r1=he.merge(w.object({type:w.literal("DIALOG"),action:w.union([w.literal("ACCEPT"),w.literal("DISMISS")])})).openapi({ref:"DialogCommand"}),mC=he.merge(w.object({type:w.literal("WAIT"),delay:w.number()})).openapi({ref:"WaitCommand"}),n1=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")}),fC=he.extend({type:w.literal("WAIT_FOR_URL"),matcher:MS}).merge(n1).openapi({ref:"WaitUrlCommand"}),hC=he.merge(Vp).merge(w.object({type:w.literal("REFRESH")})).openapi({ref:"RefreshCommand"}),gC=he.merge(w.object({type:w.literal("GO_BACK")})).openapi({ref:"GoBackCommand"}),SC=he.merge(w.object({type:w.literal("GO_FORWARD")})).openapi({ref:"GoForwardCommand"}),o1=he.extend({type:w.literal("AUTH_SAVE")}).openapi({ref:"AuthSaveCommand"}),i1=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"}),OS=he.merge(Dn).extend({type:w.literal("CAPTCHA")}).openapi({ref:"CaptchaCommand"}),yC=he.extend({type:w.literal("COPY"),value:w.string()}).openapi({ref:"CopyCommand"}),EC=he.extend({type:w.literal("PASTE")}).openapi({ref:"PasteCommand"}),TC=he.merge(Gp).extend({type:w.literal("JAVASCRIPT")}).openapi({ref:"JavaScriptCommand"}),sl=he.merge(Dn).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:hn,relativePosition:w.object({x:w.number(),y:w.number()}).optional()}).openapi({ref:"ClickCommand"}),LS=tu.extend({fromTarget:ci.optional(),toTarget:ci.optional()}),ll=he.merge(Dn).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:LS.optional()})).openapi({ref:"DragCommand"}),cl=he.merge(Dn).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:hn})).openapi({ref:"MouseDragCommand"}),ul=he.merge(Dn).merge(w.object({type:w.literal("HOVER"),target:xr,cache:hn})).openapi({ref:"HoverCommand"}),su=he.merge(Dn).merge(w.object({type:w.literal("FOCUS"),target:xr,cache:hn})).openapi({ref:"FocusCommand"}),lu=he.merge(Dn).extend({type:w.literal("BLUR"),target:xr.optional(),cache:hn}).openapi({ref:"BlurCommand"}),a1=w.object({type:w.literal("URL"),url:w.string()}).describe("Accessible link to the file, either public http or local file://").openapi({ref:"UrlSource"}),s1=w.object({type:w.literal("USER_FILE"),name:w.string()}).describe("Accessible link to the file, references the google cloud file").openapi({ref:"UploadedFileSource"}),l1=he.extend({type:w.literal("FILE_UPLOAD"),fileSource:w.discriminatedUnion("type",[a1,s1]),filename:w.string().optional()}).openapi({ref:"FileUploadCommand"}),NS=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()})]),dl=he.merge(Dn).extend({type:w.literal("SELECT_OPTION"),target:xr,cache:hn,choice:NS.describe("new field for selecting options, optional for backcompat")}).openapi({ref:"SelectOptionCommand"}),DS=w.union([w.literal("MULTIMODAL"),w.literal("VISION_ONLY")]),cu=he.merge(w.object({type:w.literal("AI_ASSERTION"),assertion:w.string(),disableCache:w.boolean().optional(),iframeUrl:w.string().optional(),contextChoice:DS.optional(),timeout:w.number().int().optional().describe("Max seconds to wait for assertion to be true"),cache:IS.optional(),source:w.string().optional()})).openapi({ref:"AIAssertionCommand"}),kn=5,ja=600,pl=he.merge(Dn).extend({type:w.literal("ELEMENT_CHECK"),target:xr,assertion:Hp,cache:hn.or(IS).optional(),timeout:w.number().int().min(0).max(ja).optional().describe("max seconds to wait for the assertion to be true")}).openapi({ref:"ElementAssertionCommand"}),bC=he.extend({type:w.literal("PAGE_CHECK"),assertion:uC,iframeUrl:w.string().optional().describe("url or url regex for the iframe"),timeout:w.number().int().min(0).max(ja).optional().describe("max seconds to wait for the assertion to be true")}).openapi({ref:"PageAssertionCommand"}),vC=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"}),c1=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()}),AC=25,ml=he.merge(Dn).merge(c1).extend({type:w.literal("TYPE"),target:xr.optional(),value:w.string(),cache:hn}).openapi({ref:"TypeCommand"}),CC=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"}),RC=he.merge(w.object({type:w.literal("KEY_DOWN"),value:w.string(),convertMeta:w.boolean().optional()})).openapi({ref:"KeyDownCommand"}),wC=he.merge(w.object({type:w.literal("KEY_UP"),value:w.string(),convertMeta:w.boolean().optional()})).openapi({ref:"KeyUpCommand"}),u1=w.object({type:w.literal("SUBSTRING"),substring:w.string()}),d1=w.object({type:w.literal("REGEX"),pattern:w.string()}),p1=w.object({type:w.literal("INDEX"),index:w.coerce.string()}),m1=w.discriminatedUnion("type",[u1,d1,p1]),f1=he.merge(Vp).merge(w.object({type:w.literal("TAB"),action:m1})).openapi({ref:"TabCommand"}),xC=he.merge(Vp).merge(w.object({type:w.literal("NEW_TAB"),url:w.string()})).openapi({ref:"NewTabCommand"}),h1=he.merge(w.object({type:w.literal("COOKIE"),value:w.string()})).openapi({ref:"CookieCommand"}),_C=he.merge(w.object({type:w.literal("LOCAL_STORAGE"),key:w.string(),value:w.string()})).openapi({ref:"LocalStorageCommand"}),IC=he.extend({type:w.literal("REQUEST")}).merge(za).openapi({ref:"RequestCommand"}),uu=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()})}),PC=he.extend({type:w.literal("GRAPHQL_REQUEST")}).merge(dC).openapi({ref:"GraphQLRequestCommand"}),MC=he.merge(w.object({type:w.literal("SUCCESS"),condition:cu.optional()})).openapi({ref:"SuccessCommand"}),OC=he.merge(w.object({type:w.literal("FAILURE")})).openapi({ref:"FailureCommand"}),g1=w.object({data:w.union([w.string().describe("location at which to find a jpg - public URL or local"),Fa]),width:w.number(),height:w.number()});function LC(t){return t?Fa.safeParse(t).success:!1}var du=he.merge(Dn).merge(w.object({type:w.literal("VISUAL_DIFF"),threshold:w.number().optional().describe("default 0.1"),target:xr.optional(),screenshot:g1.optional(),cache:hn})).openapi({ref:"VisualDiffCommand"}),NC=he.merge(w.object({type:w.literal("REGISTER_REQUEST_LISTENER"),requestMatcher:Do,key:w.string()})).openapi({ref:"RegisterRequestListenerCommand"}),S1=he.merge(w.object({type:w.literal("AWAIT_LISTENER"),key:w.string(),timeout:w.number().optional().describe("timeout")})).openapi({ref:"WaitForListenerCommand"}),DC=he.merge(w.object({type:w.literal("RECORD_REQUESTS"),requestMatcher:Do,key:w.string()})).openapi({ref:"RecordRequestsCommand"}),y1=he.merge(w.object({type:w.literal("GET_RECORDED_REQUESTS"),key:w.string()})).openapi({ref:"GetRecordedRequestsCommand"}),kC=he.merge(w.object({type:w.literal("SET_HEADER"),name:w.string(),value:w.string(),requestMatcher:Do.optional()})).openapi({ref:"SetHeaderCommand"}),UC=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"})),E1=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"})),T1=he.merge(w.object({type:w.literal("OFFLINE_MODE"),enable:w.boolean()})).openapi({ref:"OfflineModeCommand"}),b1=["CLICK","TYPE","PRESS","KEY_DOWN","KEY_UP","SELECT_OPTION","NAVIGATE","SCROLL_DOWN","SCROLL_UP","AI_ASSERTION","GO_BACK","HOVER","WAIT"],qre=[...b1,"DRAG"],v1=w.discriminatedUnion("type",[sl,ml,CC,RC,wC,dl,pC,Ga,Ha,cu,gC,ul,mC]),A1=w.discriminatedUnion("type",[...v1.options,ll]),C1=w.discriminatedUnion("type",[...A1.options]),FC=w.discriminatedUnion("type",[...C1.options,MC]),kS=w.discriminatedUnion("type",[MC,sl,ml,CC,RC,wC,dl,pC,Ga,Ha,cu,gC,ul,mC,TC,pl,bC,xC,fC,vC,yC,SC,_C,ll,cl,EC,hC,IC,PC,kC,NC,DC,UC]),R1=w.discriminatedUnion("type",[vC,i1,o1,OS,h1,yC,r1,pl,l1,SC,TC,_C,cl,xC,bC,EC,hC,IC,PC,il,al,f1,du,su,lu,fC,NC,S1,DC,y1,kC,UC,E1,T1]),fl=w.discriminatedUnion("type",[...FC.options,...R1.options]).openapi({ref:"Command"}),$p=w.discriminatedUnion("type",[...FC.options,OC]),Kre=w.discriminatedUnion("type",[...kS.options,OC]);function ui(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 Qre={AI_ASSERTION:"AI check",ELEMENT_CHECK:"Element check",JAVASCRIPT:"JavaScript",PAGE_CHECK:"Page check"};import{z as w1}from"zod";var nne=w1.discriminatedUnion("type",[lu,OS,sl,ll,su,ul,cl,Ha,Ga,il,al,dl,ml,du,pl]);function BC(t){return["AI_ASSERTION","ELEMENT_CHECK","PAGE_CHECK"].includes(t)}import{z as x1}from"zod";import{z as jr}from"zod";function hl(t){return jr.object({key:jr.string(),testId:jr.string().optional(),environment:jr.string().optional(),moduleId:jr.string().optional(),organizationId:jr.string(),value:t})}function Va(t){return jr.object({key:jr.string(),testId:jr.string().optional(),environment:jr.string().optional(),moduleId:jr.string().optional(),organizationId:jr.string(),value:t,uniqueKey:jr.string()})}function zC(t){return jr.record(jr.string(),Va(t))}var Vr={type:!0,cache:!0},po=x1.discriminatedUnion("type",[cu.pick(Vr),lu.pick(Vr),sl.pick(Vr),ll.pick(Vr),pl.pick(Vr),su.pick(Vr),ul.pick(Vr),cl.pick(Vr),Ha.pick(Vr),Ga.pick(Vr),il.pick(Vr),al.pick(Vr),dl.pick(Vr),ml.pick(Vr),du.pick(Vr)]),qp=Object.values(rt).filter(t=>po.options.some(e=>e.shape.type.safeParse(t).success));fl.options.forEach(t=>{if("target"in t.shape&&!qp.includes(t.shape.type.value))throw new Error(`Command ${t.shape.type.value} has a target but no cache`)});function ji(t){return qp.includes(t.type)}var HC=hl(po),GC=Va(po),dne=zC(po);import{v4 as ct}from"uuid";import{z as O}from"zod";var VC=Symbol("Let zodToJsonSchema decide on which parser to use");var jC={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"},WC=t=>typeof t=="string"?{...jC,name:t}:{...jC,...t};var $C=t=>{let e=WC(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 US(t,e,r,n){n?.errorMessages&&r&&(t.errorMessage={...t.errorMessage,[e]:r})}function qe(t,e,r,n,o){t[e]=r,US(t,e,n,o)}var Kp=(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 je}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"?Kp(e,t.currentPath):e.join("/")}}import{ZodFirstPartyTypeKind as _1}from"zod";function qC(t,e){let r={type:"array"};return t.type?._def&&t.type?._def?.typeName!==_1.ZodAny&&(r.items=Se(t.type._def,{...e,currentPath:[...e.currentPath,"items"]})),t.minLength&&qe(r,"minItems",t.minLength.value,t.minLength.message,e),t.maxLength&&qe(r,"maxItems",t.maxLength.value,t.maxLength.message,e),t.exactLength&&(qe(r,"minItems",t.exactLength.value,t.exactLength.message,e),qe(r,"maxItems",t.exactLength.value,t.exactLength.message,e)),r}function KC(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?qe(r,"minimum",n.value,n.message,e):qe(r,"exclusiveMinimum",n.value,n.message,e):(n.inclusive||(r.exclusiveMinimum=!0),qe(r,"minimum",n.value,n.message,e));break;case"max":e.target==="jsonSchema7"?n.inclusive?qe(r,"maximum",n.value,n.message,e):qe(r,"exclusiveMaximum",n.value,n.message,e):(n.inclusive||(r.exclusiveMaximum=!0),qe(r,"maximum",n.value,n.message,e));break;case"multipleOf":qe(r,"multipleOf",n.value,n.message,e);break}return r}function YC(){return{type:"boolean"}}function Yp(t,e){return Se(t.type._def,e)}var XC=(t,e)=>Se(t.innerType._def,e);function FS(t,e,r){let n=r??e.dateStrategy;if(Array.isArray(n))return{anyOf:n.map((o,i)=>FS(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 I1(t,e)}}var I1=(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":qe(r,"minimum",n.value,n.message,e);break;case"max":qe(r,"maximum",n.value,n.message,e);break}return r};function JC(t,e){return{...Se(t.innerType._def,e),default:t.defaultValue()}}function QC(t,e){return e.effectStrategy==="input"?Se(t.schema._def,e):wt(e)}function ZC(t){return{type:"string",enum:Array.from(t.values)}}var P1=t=>"type"in t&&t.type==="string"?!1:"allOf"in t;function eR(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(P1(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 tR(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 pu}from"zod";var BS,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:()=>(BS===void 0&&(BS=RegExp("^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$","u")),BS),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 Xp(t,e){let r={type:"string"};if(t.checks)for(let n of t.checks)switch(n.kind){case"min":qe(r,"minLength",typeof r.minLength=="number"?Math.max(r.minLength,n.value):n.value,n.message,e);break;case"max":qe(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":Wr(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":Wr(r,n.regex,n.message,e);break;case"cuid":Wr(r,mo.cuid,n.message,e);break;case"cuid2":Wr(r,mo.cuid2,n.message,e);break;case"startsWith":Wr(r,RegExp(`^${zS(n.value,e)}`),n.message,e);break;case"endsWith":Wr(r,RegExp(`${zS(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":qe(r,"minLength",typeof r.minLength=="number"?Math.max(r.minLength,n.value):n.value,n.message,e),qe(r,"maxLength",typeof r.maxLength=="number"?Math.min(r.maxLength,n.value):n.value,n.message,e);break;case"includes":{Wr(r,RegExp(zS(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":Wr(r,mo.base64url,n.message,e);break;case"jwt":Wr(r,mo.jwt,n.message,e);break;case"cidr":{n.version!=="v6"&&Wr(r,mo.ipv4Cidr,n.message,e),n.version!=="v4"&&Wr(r,mo.ipv6Cidr,n.message,e);break}case"emoji":Wr(r,mo.emoji(),n.message,e);break;case"ulid":{Wr(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":{qe(r,"contentEncoding","base64",n.message,e);break}case"pattern:zod":{Wr(r,mo.base64,n.message,e);break}}break}case"nanoid":Wr(r,mo.nanoid,n.message,e);case"toLowerCase":case"toUpperCase":case"trim":break;default:}return r}function zS(t,e){return e.patternStrategy==="escape"?O1(t):t}var M1=new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789");function O1(t){let e="";for(let r=0;r<t.length;r++)M1.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}}})):qe(t,"format",e,r,n)}function Wr(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:rR(e,n),...r&&n.errorMessages&&{errorMessage:{pattern:r}}})):qe(t,"pattern",rR(e,n),r,n)}function rR(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]="e8f17de5-e335-58a2-b652-fad7f23ed7c0")}catch(e){}}();
|
|
4
|
+
var PH=Object.create;var wS=Object.defineProperty;var MH=Object.getOwnPropertyDescriptor;var OH=Object.getOwnPropertyNames;var LH=Object.getPrototypeOf,NH=Object.prototype.hasOwnProperty;var Mt=(t,e)=>()=>(t&&(e=t(t=0)),e);var DH=(t,e)=>()=>(e||t((e={exports:{}}).exports,e),e.exports),kH=(t,e)=>{for(var r in e)wS(t,r,{get:e[r],enumerable:!0})},UH=(t,e,r,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of OH(e))!NH.call(t,o)&&o!==r&&wS(t,o,{get:()=>e[o],enumerable:!(n=MH(e,o))||n.enumerable});return t};var iC=(t,e,r)=>(r=t!=null?PH(LH(t)):{},UH(e||!t||!t.__esModule?wS(r,"default",{value:t,enumerable:!0}):r,t));var ZI,eP=Mt(()=>{"use strict";ZI=typeof globalThis=="object"?globalThis:global});var tP=Mt(()=>{"use strict";eP()});var rP=Mt(()=>{"use strict";tP()});var yi,DE=Mt(()=>{"use strict";yi="1.9.0"});function tq(t){var e=new Set([t]),r=new Set,n=t.match(nP);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(nP);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 nP,oP,iP=Mt(()=>{"use strict";DE();nP=/^(\d+)\.(\d+)\.(\d+)(-(.+))?$/;oP=tq(yi)});function Jl(t,e,r,n){var o;n===void 0&&(n=!1);var i=md[pd]=(o=md[pd])!==null&&o!==void 0?o:{version:yi};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!==yi){var a=new Error("@opentelemetry/api: Registration of version v"+i.version+" for "+t+" does not match previously registered API v"+yi);return r.error(a.stack||a.message),!1}return i[t]=e,r.debug("@opentelemetry/api: Registered a global for "+t+" v"+yi+"."),!0}function Ei(t){var e,r,n=(e=md[pd])===null||e===void 0?void 0:e.version;if(!(!n||!oP(n)))return(r=md[pd])===null||r===void 0?void 0:r[t]}function Ql(t,e){e.debug("@opentelemetry/api: Unregistering a global for "+t+" v"+yi+".");var r=md[pd];r&&delete r[t]}var rq,pd,md,fd=Mt(()=>{"use strict";rP();DE();iP();rq=yi.split(".")[0],pd=Symbol.for("opentelemetry.js.api."+rq),md=ZI});function hd(t,e,r){var n=Ei("diag");if(n)return r.unshift(e),n[t].apply(n,oq([],nq(r),!1))}var nq,oq,aP,sP=Mt(()=>{"use strict";fd();nq=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},oq=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))},aP=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 hd("debug",this._namespace,e)},t.prototype.error=function(){for(var e=[],r=0;r<arguments.length;r++)e[r]=arguments[r];return hd("error",this._namespace,e)},t.prototype.info=function(){for(var e=[],r=0;r<arguments.length;r++)e[r]=arguments[r];return hd("info",this._namespace,e)},t.prototype.warn=function(){for(var e=[],r=0;r<arguments.length;r++)e[r]=arguments[r];return hd("warn",this._namespace,e)},t.prototype.verbose=function(){for(var e=[],r=0;r<arguments.length;r++)e[r]=arguments[r];return hd("verbose",this._namespace,e)},t}()});var At,df=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 lP(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 cP=Mt(()=>{"use strict";df()});var iq,aq,sq,jo,gd=Mt(()=>{"use strict";sP();cP();df();fd();iq=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},aq=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))},sq="diag",jo=function(){function t(){function e(o){return function(){for(var i=[],a=0;a<arguments.length;a++)i[a]=arguments[a];var s=Ei("diag");if(s)return s[o].apply(s,aq([],iq(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=Ei("diag"),d=lP((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 Jl("diag",d,r,!0)};r.setLogger=n,r.disable=function(){Ql(sq,r)},r.createComponentLogger=function(o){return new aP(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 uP,dP=Mt(()=>{"use strict";uP=Symbol("BaggageEntryMetadata")});function kE(t){return typeof t!="string"&&(lq.error("Cannot create baggage metadata from unknown type: "+typeof t),t=""),{__TYPE__:uP,toString:function(){return t}}}var lq,pP=Mt(()=>{"use strict";gd();dP();lq=jo.instance()});function UE(t){return Symbol.for(t)}var cq,FE,BE=Mt(()=>{"use strict";cq=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}(),FE=new cq});function GE(){return HE}var ms,uq,pf,dq,pq,mq,fq,zE,hq,gq,Sq,HE,yq,Eq,Tq,bq,vq,Aq,Cq,jE=Mt(()=>{"use strict";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)}}(),uq=function(){function t(){}return t.prototype.createGauge=function(e,r){return Eq},t.prototype.createHistogram=function(e,r){return Tq},t.prototype.createCounter=function(e,r){return yq},t.prototype.createUpDownCounter=function(e,r){return bq},t.prototype.createObservableGauge=function(e,r){return Aq},t.prototype.createObservableCounter=function(e,r){return vq},t.prototype.createObservableUpDownCounter=function(e,r){return Cq},t.prototype.addBatchObservableCallback=function(e,r){},t.prototype.removeBatchObservableCallback=function(e){},t}(),pf=function(){function t(){}return t}(),dq=function(t){ms(e,t);function e(){return t!==null&&t.apply(this,arguments)||this}return e.prototype.add=function(r,n){},e}(pf),pq=function(t){ms(e,t);function e(){return t!==null&&t.apply(this,arguments)||this}return e.prototype.add=function(r,n){},e}(pf),mq=function(t){ms(e,t);function e(){return t!==null&&t.apply(this,arguments)||this}return e.prototype.record=function(r,n){},e}(pf),fq=function(t){ms(e,t);function e(){return t!==null&&t.apply(this,arguments)||this}return e.prototype.record=function(r,n){},e}(pf),zE=function(){function t(){}return t.prototype.addCallback=function(e){},t.prototype.removeCallback=function(e){},t}(),hq=function(t){ms(e,t);function e(){return t!==null&&t.apply(this,arguments)||this}return e}(zE),gq=function(t){ms(e,t);function e(){return t!==null&&t.apply(this,arguments)||this}return e}(zE),Sq=function(t){ms(e,t);function e(){return t!==null&&t.apply(this,arguments)||this}return e}(zE),HE=new uq,yq=new dq,Eq=new mq,Tq=new fq,bq=new pq,vq=new hq,Aq=new gq,Cq=new Sq});var Tn,mP=Mt(()=>{"use strict";(function(t){t[t.INT=0]="INT",t[t.DOUBLE=1]="DOUBLE"})(Tn||(Tn={}))});var Rq,wq,fP,hP=Mt(()=>{"use strict";BE();Rq=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},wq=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))},fP=function(){function t(){}return t.prototype.active=function(){return FE},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,wq([n],Rq(o),!1))},t.prototype.bind=function(e,r){return r},t.prototype.enable=function(){return this},t.prototype.disable=function(){return this},t}()});var xq,_q,VE,Iq,gP,SP=Mt(()=>{"use strict";hP();fd();gd();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},_q=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))},VE="context",Iq=new fP,gP=function(){function t(){}return t.getInstance=function(){return this._instance||(this._instance=new t),this._instance},t.prototype.setGlobalContextManager=function(e){return Jl(VE,e,jo.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,_q([e,r,n],xq(i),!1))},t.prototype.bind=function(e,r){return this._getContextManager().bind(e,r)},t.prototype._getContextManager=function(){return Ei(VE)||Iq},t.prototype.disable=function(){this._getContextManager().disable(),Ql(VE,jo.instance())},t}()});var Zl,yP=Mt(()=>{"use strict";SP();Zl=gP.getInstance()});var ie,EP=Mt(()=>{"use strict";gd();ie=jo.instance()});var Pq,TP,bP=Mt(()=>{"use strict";jE();Pq=function(){function t(){}return t.prototype.getMeter=function(e,r,n){return HE},t}(),TP=new Pq});var WE,vP,AP=Mt(()=>{"use strict";bP();fd();gd();WE="metrics",vP=function(){function t(){}return t.getInstance=function(){return this._instance||(this._instance=new t),this._instance},t.prototype.setGlobalMeterProvider=function(e){return Jl(WE,e,jo.instance())},t.prototype.getMeterProvider=function(){return Ei(WE)||TP},t.prototype.getMeter=function(e,r,n){return this.getMeterProvider().getMeter(e,r,n)},t.prototype.disable=function(){Ql(WE,jo.instance())},t}()});var mf,CP=Mt(()=>{"use strict";AP();mf=vP.getInstance()});var yt=Mt(()=>{"use strict";pP();BE();df();jE();mP();yP();EP();CP()});var Qv=DH((dp,Jv)=>{"use strict";(function(t,e){if(typeof dp=="object"&&typeof Jv=="object")Jv.exports=e();else if(typeof define=="function"&&define.amd)define([],e);else{var r=e();for(var n in r)(typeof dp=="object"?dp:t)[n]=r[n]}})(typeof self<"u"?self:dp,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 CRe,{multistream as wRe}from"pino";import _Re from"pino-pretty";import{z as xS}from"zod";var sre=xS.object({input:xS.string(),agentConfigVersion:xS.string().optional()}),Bp="finish";import{z as er}from"zod";var ure=er.object({srcs:er.array(er.string()),urls:er.array(er.string()),desiredSrc:er.string().optional(),desiredUrl:er.string().optional()}),aC=er.object({srcRegex:er.string().optional(),urlRegex:er.string().optional()}),sC=er.object({x:er.number(),y:er.number(),correlation:er.number()}),dre=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 FH}from"zod-openapi";import eu from"zod";var tu=eu.object({updatedAt:eu.coerce.date().optional()}),Fa=eu.object({contentType:eu.enum(["image/jpeg","image/png"]),id:eu.string()});FH(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||{}),BH=j.object({mPathSelectorTokens:j.string().array(),frameSrcRegex:j.string().optional(),frameUrlRegex:j.string().optional(),indices:j.number().array()}),ru=j.object({result:j.number(),traceId:j.string()}).array(),uo=j.object({type:j.literal("GCS_TRACES"),traces:ru}),tn=(o=>(o.PRECISE="precise",o.NARROW="narrow",o.BROAD="broad",o.IRRELEVANT="irrelevant",o))(tn||{}),lC=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(tn)}).optional(),shape:j.object({width:j.number(),height:j.number(),tolerance:j.nativeEnum(tn)}).optional(),boundingBox:j.object({x:j.number(),y:j.number(),width:j.number(),height:j.number()}).optional()}),zH=j.object({selectors:j.string().array(),requirements:lC.optional(),relativeAngleRadians:j.number().min(0).max(2*Math.PI).optional(),relativeDistance:j.number().optional()}),ci=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:lC.optional(),additionalElements:zH.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(Fa.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:BH.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:uo.optional()}).openapi({ref:"ElementTargetCache"});function nl(t){return!!(t.serializedHtml||t.screenshotUrl||t.generatedSelectors||t.hybridSelector)}var HH=j.object({type:j.literal("description"),elementDescriptor:j.string().describe("Description of the element.")}).openapi({ref:"DescriptionTarget"}),GH=j.object({x:j.number(),y:j.number()}),jH=j.object({type:j.literal("coordinates"),pixels:GH}).openapi({ref:"CoordinatesTarget"});function Gi(t){return t.type==="description"}function No(t){return t.type==="coordinates"}var xr=j.discriminatedUnion("type",[HH,jH]).openapi({ref:"ElementTarget"});function _S(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 zp(t){return uo.safeParse(t).success}import{v4 as lt}from"uuid";import*as w from"zod";import{extendZodWithOpenApi as t1}from"zod-openapi";import{z as ze}from"zod";import{extendZodWithOpenApi as VH}from"zod-openapi";import{z as nu}from"zod";var ou=nu.object({result:nu.boolean(),traceId:nu.string()}).array(),Ba=nu.object({type:nu.literal("GCS_TRACES"),traces:ou}),IS=tu.extend({memory:Ba.optional()});var ol=(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))(ol||{});VH(ze);var cC=ze.object({thoughts:ze.string(),result:ze.boolean(),relevantElements:ze.array(ze.number()).optional(),updatedMemory:ou.optional()}),fn=(o=>(o.CONTAINS="CONTAINS",o.STARTS_WITH="STARTS_WITH",o.EQUALS="EQUALS",o.EXISTS="EXISTS",o))(fn||{});var PS=["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"],WH=ze.object({type:ze.literal("ELEMENT_NAME"),negated:ze.boolean().optional(),operation:ze.nativeEnum(fn),value:ze.string()}).openapi({ref:"ElementNameAssertion"}),$H=ze.object({type:ze.literal("ELEMENT_STYLE"),negated:ze.boolean().optional(),operation:ze.nativeEnum(fn),property:ze.string(),value:ze.string()}).openapi({ref:"ElementStyleAssertion"}),qH=ze.object({type:ze.literal("ELEMENT_CONTENT"),negated:ze.boolean().optional(),operation:ze.nativeEnum(fn),value:ze.string()}).openapi({ref:"ElementContentAssertion"}),KH=ze.object({type:ze.literal("ELEMENT_ATTRIBUTE"),negated:ze.boolean().optional(),operation:ze.nativeEnum(fn),attr:ze.string(),value:ze.string()}).openapi({ref:"ElementAttributeValueAssertion"}),Ln=(i=>(i.EXISTS="EXISTS",i.VISIBLE="VISIBLE",i.ENABLED="ENABLED",i.EDITABLE="EDITABLE",i.FOCUSED="FOCUSED",i))(Ln||{});var YH=ze.object({type:ze.literal("ELEMENT_EXISTENCE"),negated:ze.boolean().optional(),condition:ze.nativeEnum(Ln).describe("Treated as the element exists AND is also ...")}).openapi({ref:"ElementExistenceAssertion"}),Hp=ze.discriminatedUnion("type",[qH,KH,YH,WH,$H]).openapi({ref:"ManualElementAssertion"});var XH=ze.object({type:ze.literal("CONTENT"),negated:ze.boolean().optional(),value:ze.string()}).openapi({ref:"PageContentAssertion"}),uC=ze.discriminatedUnion("type",[XH]).openapi({ref:"ManualPageAssertion"});import Gr from"zod";var MS=Gr.discriminatedUnion("type",[Gr.object({type:Gr.literal("SUBSTRING"),url:Gr.string()}),Gr.object({type:Gr.literal("GLOB"),glob:Gr.string()}),Gr.object({type:Gr.literal("REGEX"),regex:Gr.string()}),Gr.object({type:Gr.literal("DOMAIN"),domain:Gr.string()})]),Do=Gr.object({urlMatcher:MS,method:Gr.string().optional()});import{z as Qe}from"zod";var JH=Qe.object({type:Qe.literal("json"),content:Qe.string().describe("The JSON content to send in the request body")}),QH=Qe.object({type:Qe.literal("form-urlencoded"),content:Qe.record(Qe.string(),Qe.string()).describe("The form fields to send in the request body")}),ZH=Qe.discriminatedUnion("type",[JH,QH]),e1=["GET","POST","PUT","DELETE","PATCH"],iu=Qe.enum(e1),za=Qe.object({url:Qe.string(),method:iu,headers:Qe.record(Qe.string(),Qe.string()).optional(),params:Qe.record(Qe.string(),Qe.string()).optional(),body:ZH.optional(),timeout:Qe.number().int().optional().describe("Max seconds to wait for the request to complete")}),dC=Qe.object({url:Qe.string(),headers:Qe.record(Qe.string(),Qe.string()).optional(),query:Qe.string(),variables:Qe.string().optional(),timeout:Qe.number().int().optional().describe("Max seconds to wait for the request to complete")}),Gp=Qe.object({code:Qe.string(),fragment:Qe.boolean().optional().describe("Agents should not touch this unless explicitly told to"),environment:Qe.union([Qe.literal("NODE"),Qe.literal("BROWSER")]).optional().describe("default NODE, Agents default to using node unless it is necessary to use browser"),timeout:Qe.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||{});t1(w);var he=w.object({thoughts:w.string().optional(),id:w.string().uuid().describe("unique identifier to this step, used for step cache")}),Dn=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"}),hn=tu.extend({target:ci}).optional().openapi({ref:"SingleTargetCache"});function jp(t){return!!t&&hn.safeParse(t).success}var Vp=w.object({loadTimeout:w.number().int().max(60).optional().describe("Max seconds for the page to load")}),pC=he.merge(Vp).merge(w.object({type:w.literal("NAVIGATE"),url:w.string()})).openapi({ref:"NavigateCommand"}),Wp=Dn.merge(w.object({cache:hn})),Ha=he.merge(Wp.merge(w.object({target:xr.optional(),type:w.literal("SCROLL_UP"),deltaY:w.number().optional()}))).openapi({ref:"ScrollUpCommand"}),Ga=he.merge(Wp.merge(w.object({target:xr.optional(),type:w.literal("SCROLL_DOWN"),deltaY:w.number().optional()}))).openapi({ref:"ScrollDownCommand"}),il=he.merge(Wp.merge(w.object({target:xr.optional(),type:w.literal("SCROLL_LEFT"),deltaX:w.number().optional()}))).openapi({ref:"ScrollLeftCommand"}),al=he.merge(Wp.merge(w.object({target:xr.optional(),type:w.literal("SCROLL_RIGHT"),deltaX:w.number().optional()}))).openapi({ref:"ScrollRightCommand"}),$re=w.discriminatedUnion("type",[Ha,Ga,il,al]).openapi({ref:"AllScrollCommands"}),r1=he.merge(w.object({type:w.literal("DIALOG"),action:w.union([w.literal("ACCEPT"),w.literal("DISMISS")])})).openapi({ref:"DialogCommand"}),mC=he.merge(w.object({type:w.literal("WAIT"),delay:w.number()})).openapi({ref:"WaitCommand"}),n1=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")}),fC=he.extend({type:w.literal("WAIT_FOR_URL"),matcher:MS}).merge(n1).openapi({ref:"WaitUrlCommand"}),hC=he.merge(Vp).merge(w.object({type:w.literal("REFRESH")})).openapi({ref:"RefreshCommand"}),gC=he.merge(w.object({type:w.literal("GO_BACK")})).openapi({ref:"GoBackCommand"}),SC=he.merge(w.object({type:w.literal("GO_FORWARD")})).openapi({ref:"GoForwardCommand"}),o1=he.extend({type:w.literal("AUTH_SAVE")}).openapi({ref:"AuthSaveCommand"}),i1=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"}),OS=he.merge(Dn).extend({type:w.literal("CAPTCHA")}).openapi({ref:"CaptchaCommand"}),yC=he.extend({type:w.literal("COPY"),value:w.string()}).openapi({ref:"CopyCommand"}),EC=he.extend({type:w.literal("PASTE")}).openapi({ref:"PasteCommand"}),TC=he.merge(Gp).extend({type:w.literal("JAVASCRIPT")}).openapi({ref:"JavaScriptCommand"}),sl=he.merge(Dn).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:hn,relativePosition:w.object({x:w.number(),y:w.number()}).optional()}).openapi({ref:"ClickCommand"}),LS=tu.extend({fromTarget:ci.optional(),toTarget:ci.optional()}),ll=he.merge(Dn).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:LS.optional()})).openapi({ref:"DragCommand"}),cl=he.merge(Dn).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:hn})).openapi({ref:"MouseDragCommand"}),ul=he.merge(Dn).merge(w.object({type:w.literal("HOVER"),target:xr,cache:hn})).openapi({ref:"HoverCommand"}),su=he.merge(Dn).merge(w.object({type:w.literal("FOCUS"),target:xr,cache:hn})).openapi({ref:"FocusCommand"}),lu=he.merge(Dn).extend({type:w.literal("BLUR"),target:xr.optional(),cache:hn}).openapi({ref:"BlurCommand"}),a1=w.object({type:w.literal("URL"),url:w.string()}).describe("Accessible link to the file, either public http or local file://").openapi({ref:"UrlSource"}),s1=w.object({type:w.literal("USER_FILE"),name:w.string()}).describe("Accessible link to the file, references the google cloud file").openapi({ref:"UploadedFileSource"}),l1=he.extend({type:w.literal("FILE_UPLOAD"),fileSource:w.discriminatedUnion("type",[a1,s1]),filename:w.string().optional()}).openapi({ref:"FileUploadCommand"}),NS=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()})]),dl=he.merge(Dn).extend({type:w.literal("SELECT_OPTION"),target:xr,cache:hn,choice:NS.describe("new field for selecting options, optional for backcompat")}).openapi({ref:"SelectOptionCommand"}),DS=w.union([w.literal("MULTIMODAL"),w.literal("VISION_ONLY")]),cu=he.merge(w.object({type:w.literal("AI_ASSERTION"),assertion:w.string(),disableCache:w.boolean().optional(),iframeUrl:w.string().optional(),contextChoice:DS.optional(),timeout:w.number().int().optional().describe("Max seconds to wait for assertion to be true"),cache:IS.optional(),source:w.string().optional()})).openapi({ref:"AIAssertionCommand"}),kn=5,ja=600,pl=he.merge(Dn).extend({type:w.literal("ELEMENT_CHECK"),target:xr,assertion:Hp,cache:hn.or(IS).optional(),timeout:w.number().int().min(0).max(ja).optional().describe("max seconds to wait for the assertion to be true")}).openapi({ref:"ElementAssertionCommand"}),bC=he.extend({type:w.literal("PAGE_CHECK"),assertion:uC,iframeUrl:w.string().optional().describe("url or url regex for the iframe"),timeout:w.number().int().min(0).max(ja).optional().describe("max seconds to wait for the assertion to be true")}).openapi({ref:"PageAssertionCommand"}),vC=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"}),c1=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()}),AC=25,ml=he.merge(Dn).merge(c1).extend({type:w.literal("TYPE"),target:xr.optional(),value:w.string(),cache:hn}).openapi({ref:"TypeCommand"}),CC=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"}),RC=he.merge(w.object({type:w.literal("KEY_DOWN"),value:w.string(),convertMeta:w.boolean().optional()})).openapi({ref:"KeyDownCommand"}),wC=he.merge(w.object({type:w.literal("KEY_UP"),value:w.string(),convertMeta:w.boolean().optional()})).openapi({ref:"KeyUpCommand"}),u1=w.object({type:w.literal("SUBSTRING"),substring:w.string()}),d1=w.object({type:w.literal("REGEX"),pattern:w.string()}),p1=w.object({type:w.literal("INDEX"),index:w.coerce.string()}),m1=w.discriminatedUnion("type",[u1,d1,p1]),f1=he.merge(Vp).merge(w.object({type:w.literal("TAB"),action:m1})).openapi({ref:"TabCommand"}),xC=he.merge(Vp).merge(w.object({type:w.literal("NEW_TAB"),url:w.string()})).openapi({ref:"NewTabCommand"}),h1=he.merge(w.object({type:w.literal("COOKIE"),value:w.string()})).openapi({ref:"CookieCommand"}),_C=he.merge(w.object({type:w.literal("LOCAL_STORAGE"),key:w.string(),value:w.string()})).openapi({ref:"LocalStorageCommand"}),IC=he.extend({type:w.literal("REQUEST")}).merge(za).openapi({ref:"RequestCommand"}),uu=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()})}),PC=he.extend({type:w.literal("GRAPHQL_REQUEST")}).merge(dC).openapi({ref:"GraphQLRequestCommand"}),MC=he.merge(w.object({type:w.literal("SUCCESS"),condition:cu.optional()})).openapi({ref:"SuccessCommand"}),OC=he.merge(w.object({type:w.literal("FAILURE")})).openapi({ref:"FailureCommand"}),g1=w.object({data:w.union([w.string().describe("location at which to find a jpg - public URL or local"),Fa]),width:w.number(),height:w.number()});function LC(t){return t?Fa.safeParse(t).success:!1}var du=he.merge(Dn).merge(w.object({type:w.literal("VISUAL_DIFF"),threshold:w.number().optional().describe("default 0.1"),target:xr.optional(),screenshot:g1.optional(),cache:hn})).openapi({ref:"VisualDiffCommand"}),NC=he.merge(w.object({type:w.literal("REGISTER_REQUEST_LISTENER"),requestMatcher:Do,key:w.string()})).openapi({ref:"RegisterRequestListenerCommand"}),S1=he.merge(w.object({type:w.literal("AWAIT_LISTENER"),key:w.string(),timeout:w.number().optional().describe("timeout")})).openapi({ref:"WaitForListenerCommand"}),DC=he.merge(w.object({type:w.literal("RECORD_REQUESTS"),requestMatcher:Do,key:w.string()})).openapi({ref:"RecordRequestsCommand"}),y1=he.merge(w.object({type:w.literal("GET_RECORDED_REQUESTS"),key:w.string()})).openapi({ref:"GetRecordedRequestsCommand"}),kC=he.merge(w.object({type:w.literal("SET_HEADER"),name:w.string(),value:w.string(),requestMatcher:Do.optional()})).openapi({ref:"SetHeaderCommand"}),UC=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"})),E1=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"})),T1=he.merge(w.object({type:w.literal("OFFLINE_MODE"),enable:w.boolean()})).openapi({ref:"OfflineModeCommand"}),b1=["CLICK","TYPE","PRESS","KEY_DOWN","KEY_UP","SELECT_OPTION","NAVIGATE","SCROLL_DOWN","SCROLL_UP","AI_ASSERTION","GO_BACK","HOVER","WAIT"],qre=[...b1,"DRAG"],v1=w.discriminatedUnion("type",[sl,ml,CC,RC,wC,dl,pC,Ga,Ha,cu,gC,ul,mC]),A1=w.discriminatedUnion("type",[...v1.options,ll]),C1=w.discriminatedUnion("type",[...A1.options]),FC=w.discriminatedUnion("type",[...C1.options,MC]),kS=w.discriminatedUnion("type",[MC,sl,ml,CC,RC,wC,dl,pC,Ga,Ha,cu,gC,ul,mC,TC,pl,bC,xC,fC,vC,yC,SC,_C,ll,cl,EC,hC,IC,PC,kC,NC,DC,UC]),R1=w.discriminatedUnion("type",[vC,i1,o1,OS,h1,yC,r1,pl,l1,SC,TC,_C,cl,xC,bC,EC,hC,IC,PC,il,al,f1,du,su,lu,fC,NC,S1,DC,y1,kC,UC,E1,T1]),fl=w.discriminatedUnion("type",[...FC.options,...R1.options]).openapi({ref:"Command"}),$p=w.discriminatedUnion("type",[...FC.options,OC]),Kre=w.discriminatedUnion("type",[...kS.options,OC]);function ui(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 Qre={AI_ASSERTION:"AI check",ELEMENT_CHECK:"Element check",JAVASCRIPT:"JavaScript",PAGE_CHECK:"Page check"};import{z as w1}from"zod";var nne=w1.discriminatedUnion("type",[lu,OS,sl,ll,su,ul,cl,Ha,Ga,il,al,dl,ml,du,pl]);function BC(t){return["AI_ASSERTION","ELEMENT_CHECK","PAGE_CHECK"].includes(t)}import{z as x1}from"zod";import{z as jr}from"zod";function hl(t){return jr.object({key:jr.string(),testId:jr.string().optional(),environment:jr.string().optional(),moduleId:jr.string().optional(),organizationId:jr.string(),value:t})}function Va(t){return jr.object({key:jr.string(),testId:jr.string().optional(),environment:jr.string().optional(),moduleId:jr.string().optional(),organizationId:jr.string(),value:t,uniqueKey:jr.string()})}function zC(t){return jr.record(jr.string(),Va(t))}var Vr={type:!0,cache:!0},po=x1.discriminatedUnion("type",[cu.pick(Vr),lu.pick(Vr),sl.pick(Vr),ll.pick(Vr),pl.pick(Vr),su.pick(Vr),ul.pick(Vr),cl.pick(Vr),Ha.pick(Vr),Ga.pick(Vr),il.pick(Vr),al.pick(Vr),dl.pick(Vr),ml.pick(Vr),du.pick(Vr)]),qp=Object.values(rt).filter(t=>po.options.some(e=>e.shape.type.safeParse(t).success));fl.options.forEach(t=>{if("target"in t.shape&&!qp.includes(t.shape.type.value))throw new Error(`Command ${t.shape.type.value} has a target but no cache`)});function ji(t){return qp.includes(t.type)}var HC=hl(po),GC=Va(po),dne=zC(po);import{v4 as ct}from"uuid";import{z as O}from"zod";var VC=Symbol("Let zodToJsonSchema decide on which parser to use");var jC={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"},WC=t=>typeof t=="string"?{...jC,name:t}:{...jC,...t};var $C=t=>{let e=WC(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 US(t,e,r,n){n?.errorMessages&&r&&(t.errorMessage={...t.errorMessage,[e]:r})}function qe(t,e,r,n,o){t[e]=r,US(t,e,n,o)}var Kp=(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 je}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"?Kp(e,t.currentPath):e.join("/")}}import{ZodFirstPartyTypeKind as _1}from"zod";function qC(t,e){let r={type:"array"};return t.type?._def&&t.type?._def?.typeName!==_1.ZodAny&&(r.items=Se(t.type._def,{...e,currentPath:[...e.currentPath,"items"]})),t.minLength&&qe(r,"minItems",t.minLength.value,t.minLength.message,e),t.maxLength&&qe(r,"maxItems",t.maxLength.value,t.maxLength.message,e),t.exactLength&&(qe(r,"minItems",t.exactLength.value,t.exactLength.message,e),qe(r,"maxItems",t.exactLength.value,t.exactLength.message,e)),r}function KC(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?qe(r,"minimum",n.value,n.message,e):qe(r,"exclusiveMinimum",n.value,n.message,e):(n.inclusive||(r.exclusiveMinimum=!0),qe(r,"minimum",n.value,n.message,e));break;case"max":e.target==="jsonSchema7"?n.inclusive?qe(r,"maximum",n.value,n.message,e):qe(r,"exclusiveMaximum",n.value,n.message,e):(n.inclusive||(r.exclusiveMaximum=!0),qe(r,"maximum",n.value,n.message,e));break;case"multipleOf":qe(r,"multipleOf",n.value,n.message,e);break}return r}function YC(){return{type:"boolean"}}function Yp(t,e){return Se(t.type._def,e)}var XC=(t,e)=>Se(t.innerType._def,e);function FS(t,e,r){let n=r??e.dateStrategy;if(Array.isArray(n))return{anyOf:n.map((o,i)=>FS(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 I1(t,e)}}var I1=(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":qe(r,"minimum",n.value,n.message,e);break;case"max":qe(r,"maximum",n.value,n.message,e);break}return r};function JC(t,e){return{...Se(t.innerType._def,e),default:t.defaultValue()}}function QC(t,e){return e.effectStrategy==="input"?Se(t.schema._def,e):wt(e)}function ZC(t){return{type:"string",enum:Array.from(t.values)}}var P1=t=>"type"in t&&t.type==="string"?!1:"allOf"in t;function eR(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(P1(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 tR(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 pu}from"zod";var BS,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:()=>(BS===void 0&&(BS=RegExp("^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$","u")),BS),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 Xp(t,e){let r={type:"string"};if(t.checks)for(let n of t.checks)switch(n.kind){case"min":qe(r,"minLength",typeof r.minLength=="number"?Math.max(r.minLength,n.value):n.value,n.message,e);break;case"max":qe(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":Wr(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":Wr(r,n.regex,n.message,e);break;case"cuid":Wr(r,mo.cuid,n.message,e);break;case"cuid2":Wr(r,mo.cuid2,n.message,e);break;case"startsWith":Wr(r,RegExp(`^${zS(n.value,e)}`),n.message,e);break;case"endsWith":Wr(r,RegExp(`${zS(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":qe(r,"minLength",typeof r.minLength=="number"?Math.max(r.minLength,n.value):n.value,n.message,e),qe(r,"maxLength",typeof r.maxLength=="number"?Math.min(r.maxLength,n.value):n.value,n.message,e);break;case"includes":{Wr(r,RegExp(zS(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":Wr(r,mo.base64url,n.message,e);break;case"jwt":Wr(r,mo.jwt,n.message,e);break;case"cidr":{n.version!=="v6"&&Wr(r,mo.ipv4Cidr,n.message,e),n.version!=="v4"&&Wr(r,mo.ipv6Cidr,n.message,e);break}case"emoji":Wr(r,mo.emoji(),n.message,e);break;case"ulid":{Wr(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":{qe(r,"contentEncoding","base64",n.message,e);break}case"pattern:zod":{Wr(r,mo.base64,n.message,e);break}}break}case"nanoid":Wr(r,mo.nanoid,n.message,e);case"toLowerCase":case"toUpperCase":case"trim":break;default:}return r}function zS(t,e){return e.patternStrategy==="escape"?O1(t):t}var M1=new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789");function O1(t){let e="";for(let r=0;r<t.length;r++)M1.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}}})):qe(t,"format",e,r,n)}function Wr(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:rR(e,n),...r&&n.errorMessages&&{errorMessage:{pattern:r}}})):qe(t,"pattern",rR(e,n),r,n)}function rR(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
|
|
@@ -21,7 +21,7 @@ Parse error: ${e.error.message}`}throw new Zp(n,{cause:e.error})}var DR=t=>{let
|
|
|
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(cs(m,void 0,2)," ");console.log(r(` ${s}.${p}:`,f));continue}console.log(r(` ${s}.${p}:`,m))}}else typeof c=="object"?(l=cs(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=cs(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=ld[e]:this.minLogLevel=e}log(...e){this.logWithLevel(30,zo.reset,...e)}info(...e){this.logWithLevel(30,zo.white,...e)}debug(...e){this.logWithLevel(20,zo.dim,...e)}warn(...e){this.logWithLevel(40,zo.yellow,...e)}error(...e){this.logWithLevel(50,zo.red,...e)}success(...e){this.logWithLevel(1/0,zo.green,...e)}dimmed(...e){this.logWithLevel(30,zo.dim,...e)}underline(...e){this.logWithLevel(40,zo.underline,...e)}bold(...e){this.logWithLevel(40,zo.bold,...e)}grey(...e){this.logWithLevel(20,zo.grey,...e)}child(e){return new t(this.minLogLevel,{...this.logBindings,...e})}async flush(){}bindings(){return this.logBindings}},hE=class{debug(){}info(){}warn(){}error(){}success(){}dimmed(){}underline(){}bold(){}grey(){}child(){return this}async flush(){}bindings(){return{}}},STe=new hE,zW=typeof window>"u"&&typeof process<"u"&&fE.safeParse(process?.env?.MOMENTIC_DEV_LOG_LEVEL).success?fE.parse(process.env.MOMENTIC_DEV_LOG_LEVEL):30,v=new us(zW,{}),Ho={info:()=>{},error:()=>{},debug:()=>{},warn:()=>{},child:()=>Ho,flush:async()=>{},bindings:()=>({})},jm={},Vm=({logger:t,logKey:e,maxCount:r,intervalMs:n},o,i,...a)=>{let s=jm[e];s?clearTimeout(s.timer):(s={count:0,totalCount:0},jm[e]=s),s.totalCount++,s.count<r&&(s.count++,t.debug(o,i,...a)),s.timer=setTimeout(()=>{let c=jm[e];c?.totalCount!==c?.count&&t.debug({logKey:e,totalCount:c?.totalCount,count:c?.count},`Debug logs were rate-limited for ${e}`),delete jm[e]},n)};import{z as K}from"zod";var HW=K.array(Vl.extend({id:K.string(),name:K.string(),description:K.string().optional(),labels:K.string().array().optional()})),GW=K.array(Vl.extend({id:K.string(),name:K.string(),description:K.string().optional(),content:oE})),v_={name:K.string().min(1).max(255).describe(oa),description:K.string().optional(),settings:zl.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:pw.optional().default("ANDROID").describe("For LLM: Never assign this unless the user explicitly asks for iOS. Defaults to Android.")},{defaultEnv:wTe,...xTe}=v_;var _Te=K.object(v_),ITe=K.object({id:K.string(),fileName:K.string(),fullPath:K.string(),relativeFilePath:K.string().describe("relative to project root")});var PTe=K.object({steps:ls.array().optional(),settings:zl.optional(),labels:K.array(K.string()).optional()}),MTe=K.object({message:K.literal("ok")}),OTe=K.object({name:di.optional(),description:K.string().min(1).optional(),settings:zl.optional(),disabled:K.boolean().optional(),labels:K.array(K.string()).optional()}),LTe=K.object({message:K.string(),newRelativeTestPath:K.string().optional()}),NTe=K.object({tag:K.string(),channel:K.string(),filePath:K.string()}),DTe=K.object({name:di}),kTe=K.object({tests:HW,modules:GW,labels:K.string().array()}),UTe=K.object({name:K.string(),description:K.string(),enabled:K.boolean()}).partial(),FTe=K.object({name:K.string(),description:K.string(),enabled:K.boolean(),steps:ls.array(),testFilePath:K.string().describe("relative to the project root"),folderPath:K.string().optional().describe("user selected folder path")}),BTe=K.object({name:K.string().describe(oa),description:K.string().optional(),enabled:K.boolean().default(!0),parameters:td.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()}),zTe=K.object({packages:K.string().array()}),HTe=K.object({name:K.string()}),GTe=K.object({relativeFilePath:K.string()}),A_=K.object({stepId:K.string(),testId:K.string(),environment:K.string().optional(),parentStepIdChain:K.array(K.string()),value:Fl}),jW=A_.extend({platform:K.literal("ANDROID"),steps:ls.array()}),VW=A_.extend({platform:K.literal("IOS"),steps:rd.array()}),jTe=K.discriminatedUnion("platform",[jW,VW]),VTe=K.object({platform:K.nativeEnum(yn),completionType:K.string(),traceIds:K.string().array()}),WTe=K.object({completionType:K.string(),traceIds:K.string().array()});import{v4 as WW}from"uuid";var Wm=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=WW();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 C_=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:XS.nullish()}),rbe=C_.extend({steps:jt.lazy(()=>bt.array())}),R_=5*60*1e3,gE=rn.merge(C_.omit({id:!0,createdAt:!0,createdBy:!0,organizationId:!0,enabled:!0}));import{formatInTimeZone as ibe}from"date-fns-tz";import*as A from"zod";import{z as kt}from"zod";var SE=(e=>(e.TEST_REVIEW="TEST_REVIEW",e))(SE||{});var $W=kt.object({type:kt.literal("DESCRIPTION_UPDATE"),thoughts:kt.string()}),$m=kt.discriminatedUnion("type",[$W]),qW=kt.object({testId:kt.string(),name:kt.string(),orgId:kt.string(),runId:kt.string(),steps:Nt.array(),purpose:kt.nativeEnum(SE),details:$m.or($m.array()).optional()});var ube=qW.pick({name:!0,orgId:!0}),KW=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(SE),details:$m.or($m.array()).optional(),applied:kt.boolean().nullish(),appliedAt:kt.coerce.date().nullish()}),w_=KW.extend({steps:Nt.array()});var qm="x-momentic-cli-version",x_="x-momentic-client-mode",__="x-momentic-cli-type",I_="x-momentic-logger-tags",YW="x-momentic-main-branch-name",XW="x-momentic-branch-name",JW="x-momentic-commit-timestamp",QW="x-momentic-last-commit-on-main",ZW="x-momentic-last-commit-on-main-timestamp",e$="x-momentic-merged-branch-name",P_="x-momentic-session-id",Lbe=A.object({error:A.boolean(),reason:A.string(),message:A.string()}),Nbe=Gt.merge(gy),M_=$p,Dbe=Gt.merge(gy);var kbe=Gt.merge(Mw).extend({useConsensus:A.boolean().optional(),attemptNumber:A.number().optional()}),yE=cC,Ube=Gt.merge(Lw),O_=qR,Fbe=Gt.merge(Nw),L_=KR,Bbe=Gt.merge(Dw),N_=YR,zbe=Gt.merge(Ow),D_=$R,Hbe=Gt.merge(xw),k_=om,Gbe=Gt.merge(_w),U_=GR,jbe=Gt.merge(Iw);var Vbe=Gt.merge(Pw),Wbe=Gt.merge(Bw),$be=Gt.merge(zw),qbe=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()}),F_=A.object({queuedTests:A.unknown().array(),runIds:A.string().uuid().array(),runGroupId:A.string().optional()});var Kbe=A.string().array(),Ybe=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")})]),B_=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"))}),t$=A.object({test:A.string().describe("test YAML"),modules:A.record(A.string().describe("moduleId"),A.string().describe("module YAML"))}),Xbe=t$.array(),Jbe=A.object({testId:A.string(),schemaVersion:A.string()}).merge(Ka);function EE(t){let{gitMainBranch:e,gitBranchName:r,gitCommitTimestamp:n,lastCommitOnMainSha:o,lastCommitOnMainTimestamp:i}=t,a={};return e&&(a[YW]=encodeURIComponent(e)),r&&(a[XW]=encodeURIComponent(r)),n&&(a[JW]=n.toISOString()),o&&(a[QW]=encodeURIComponent(o)),i&&(a[ZW]=i.toISOString()),t.mergedGitBranchName&&(a[e$]=encodeURIComponent(t.mergedGitBranchName)),a}var Qbe=A.object({entries:A.array(HC)});var Zbe=A.object({testId:A.string(),environment:A.string().optional()});function z_(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 H_=z_(GC);function G_(t){return z_(Va(t))}var r$=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()}),n$=A.object({id:A.string(),assertion:A.string().optional(),result:A.string(),thoughts:A.string(),sessionType:A.string(),timeCreated:A.string().optional()}),eve=A.object({completionType:A.string(),traceIds:A.string().array()}),TE=A.union([r$,n$]).array(),j_=A.object({trigger:A.nativeEnum(nn),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()}),tve=A.object({id:A.string()}),V_=A.object({status:A.nativeEnum(nt),updatedAt:A.coerce.date().optional(),finishedAt:A.coerce.date().optional()}),W_=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(nn),schemaVersion:A.string().optional(),section:A.nativeEnum(Sm).optional(),resolvedInputs:A.record(A.string(),A.string()).optional(),quarantined:A.boolean().optional().default(!1),quarantinedReason:A.string().optional(),aiSettings:mi.optional()}),rve=A.object({id:A.string()}),o$=my.pick({id:!0,status:!0,testName:!0,testId:!0,test:!0,failureReason:!0,failureDetails:!0}),$_=o$.array(),q_=my.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(),nve=A.object({id:A.string()}),K_=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()}),ove=A.object({screenshot:A.string(),contentType:A.enum(["image/jpeg","image/png"]).optional()}),ive=A.object({id:A.string(),screenshot:A.string(),contentType:A.enum(["image/jpeg","image/png"])}),Y_=A.object({key:A.string()}),X_=A.object({orgId:A.string(),userId:A.string()}),J_=A.array(lw),ave=A.record(A.string(),A.union([A.string(),A.boolean()])),sve=A.object({paths:A.string().array(),env:A.string().optional(),urlOverride:A.string().optional(),customHeaders:A.record(A.string(),A.string()).optional()}),Q_=A.object({suiteRunIds:A.string().array(),runGroupIds:A.string().array()}),lve=A.object({suiteRunIds:A.string().array()}),cve=Cw.array(),uve=A.object({runGroupIds:A.string().array()}),i$=A.object({uploadUrl:A.string()}),dve=Gt.merge(kw),pve=Gt.merge(Fw),mve=Gt.merge(Uw),a$=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()}),s$=A.object({transactionId:A.string(),timestamp:A.string(),event:A.nativeEnum(Qu),properties:a$}),fve=s$.array(),Z_=w_.omit({steps:!0}).extend({steps:A.array(A.record(A.string(),A.unknown())).describe("unparsed ResolvedStep[]")}),hve=A.object({limit:A.number().max(10).optional(),afterTime:A.number().optional()}),eI=yw.array(),gve=A.object({applied:A.boolean().optional(),appliedAt:A.coerce.date().optional()}),tI=i$.extend({id:A.string()}),Sve=A.object({runGroupId:A.string().uuid().optional()}),rI=A.object({runGroupId:A.string().uuid()}),nI=A.object({quarantined:A.object({testId:A.string().uuid(),quarantinedAt:A.coerce.date(),quarantinedBy:A.string().optional(),quarantinedReason:A.string()}).array()}),yve=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()}),Eve=A.object({testName:A.string().optional(),reason:A.string().optional(),gitLocalUsername:A.string().optional(),gitLocalEmail:A.string().optional(),gitLocalName:A.string().optional()}),Tve=Gt.merge(dx),bve=Gt.merge(px),vve=Gt.merge(mx),Ave=A.object({apkToInstall:A.object({channel:A.string(),tag:A.string().optional()}).optional(),hostname:A.string().optional(),region:A.nativeEnum(Zu).optional(),osVersion:A.nativeEnum(ed).optional(),sessionId:A.string().optional()}),oI=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()}),Cve=A.object({appToInstall:A.object({channel:A.string(),tag:A.string().optional()}).optional(),hostname:A.string().optional(),region:A.nativeEnum(Zu).optional(),osVersion:A.nativeEnum(tE).optional(),sessionId:A.string().optional()}),iI=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()}),Rve=A.object({channel:A.string(),tag:A.string(),md5:A.string()}),aI=A.object({id:A.string(),uploadUrl:A.string().optional(),downloadUrl:A.string(),md5:A.string().optional()}),sI=A.object({assets:A.array(A.object({channel:A.string(),tag:A.string(),md5:A.string(),platform:A.nativeEnum(yn).default("ANDROID"),createdAt:A.number().describe("Unix timestamp in milliseconds")}))}),lI=A.object({downloadUrl:A.string()});import{z as Le}from"zod";var uI=7,l$=3,cI=Le.object({quarantinedAt:Le.date(),quarantinedReason:Le.string(),quarantinedBy:Le.string().optional(),quarantinedByGitEmail:Le.string().optional(),quarantinedByGitName:Le.string().optional(),quarantinedByGitUsername:Le.string().optional()}),_ve=Le.object({localTestId:Le.string()}).merge(cI).or(Le.object({cloudTestId:Le.string()}).merge(cI)),dI=(r=>(r.QUARANTINE="QUARANTINE",r.UNQUARANTINE="UNQUARANTINE",r))(dI||{});var bE=Le.object({name:Le.string(),description:Le.string().nullish(),effect:Le.nativeEnum(dI),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()}),c$=Le.object({type:Le.literal("LAST_N_RUNS"),lastN:Le.number().min(l$)}),u$=Le.object({type:Le.literal("LAST_N_HOURS"),lastN:Le.number().min(1).max(uI*24)}),d$=Le.object({type:Le.literal("LAST_N_DAYS"),lastN:Le.number().min(1).max(uI)}),vE=Le.discriminatedUnion("type",[c$,u$,d$]),p$=Le.object({flakeRateThreshold:Le.number().min(1).max(100),evaluationWindow:vE}),m$=bE.extend({type:Le.literal("FLAKE_RATE"),config:p$}),f$=Le.object({passRateThreshold:Le.number().min(1).max(100),evaluationWindow:vE}),h$=bE.extend({type:Le.literal("PASS_RATE"),config:f$}),g$=Le.object({failureCountThreshold:Le.number().min(0),evaluationWindow:vE}),S$=bE.extend({type:Le.literal("FAILURE_COUNT"),config:g$}),Ive=Le.discriminatedUnion("type",[m$,h$,S$]);import{z as Vt}from"zod";var Ove=Vt.object({repositoriesIndexed:Vt.boolean(),indexingInProgress:Vt.boolean(),indexesOutdated:Vt.boolean()}),pI=(a=>(a.Queued="queued",a.InProgress="in_progress",a.Completed="completed",a.Waiting="waiting",a.Requested="requested",a.Pending="pending",a))(pI||{}),mI=(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))(mI||{}),Lve=Vt.object({name:Vt.string(),status:Vt.nativeEnum(pI),conclusion:Vt.nativeEnum(mI).nullable()}),cd=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()})}),AE=Vt.object({mergedBranch:Vt.string().optional()});import{z as _t}from"zod";var fI=_t.object({orgId:_t.string(),cacheKeys:_t.string().array()}),kve=_t.object({keyParams:fI,clientMetadata:_t.string(),lockAcquisitionTimeoutMs:_t.number().optional()}),hI=_t.object({acquired:_t.boolean(),acquiredByMetadata:_t.string(),keyPrefix:_t.string()}),Uve=_t.object({keyPrefix:_t.string(),result:_t.string(),ttlMs:_t.number()}),Fve=_t.union([_t.object({keyPrefix:_t.string()}),fI]),y$=_t.object({remainingTtlMs:_t.number(),value:_t.string().nullish()}),Bve=_t.object({results:_t.record(_t.string(),y$),activeLocks:_t.string().array()}),gI=0,SI=5*60*1e3;var jve=30*24*60*60*1e3,Vve=7*24*60*60*1e3;import{z as yI}from"zod";var qve=yI.object({quarantineNotifications:yI.string().nullish()});function Wl(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 E$=hr.object({version:hr.string(),json:hr.record(hr.unknown()),hash:hr.string()}),EI=hr.record(hr.unknown()),Qve=hr.object({newSvgs:hr.array(E$),metadata:EI.optional()}),T$=hr.object({version:hr.string(),json:hr.record(hr.unknown()).nullish(),hash:hr.string(),description:hr.string().nullish(),metadata:EI.nullish()}),TI=hr.record(hr.string().describe("icon hash"),T$);import{validator as b$}from"@exodus/schemasafe";function bI(t){let e;try{e=JSON.parse(t)}catch(r){return`The schema is not valid JSON. ${r}`}try{b$(e)}catch(r){return`The schema is not a valid JSON schema. ${r}`}}var vI=t=>{t.extraHeaders&&(t.extraHeaders=Object.fromEntries(Object.entries(t.extraHeaders).filter(([e,r])=>e.trim()&&r.trim())))};import{z as hAe}from"zod";var Km=class{async resolveStepCacheEntries(){}async saveStepCacheEntries(){}};function v$(t){return t.map(e=>({...e,environment:void 0}))}function CE(t,e){return e?t:v$(t)}var En="get_browser_state",Ym="get_environment_variables",Xm="reset_session",Go="run_step",Wn="preview_preflight",AI="preview_ensure",sr="preview_step",Jm="test_get",lr="test_splice_steps",Qm="module_create",CI="momentic_module_create",$l="momentic_module_get",Zm="momentic_module_list",ia="momentic_module_recommend",RI="momentic_attributes_list",wI="momentic_test_create",xI="momentic_test_splice_steps",_I="momentic_run_step",II="momentic_session_start",PI="momentic_session_terminate",MI="momentic_get_session_state",OI="momentic_get_environment_variables",gi="momentic_get_initial_data",LI="momentic_preview_step";var wE="browser-crash-dump.zip",RE=class{loggerBindings;attachBeforeScreenshot(){}attachAfterScreenshot(){}attachBeforeHtmlSnapshot(){}attachAfterHtmlSnapshot(){}recordTargetAutoHeal(){}recordStepDuration(){}storeTraceAsset(){}async finish(){}async startSubSteps(){return new ud}},ud=class{async getScreenshot(){}async getHtmlSnapshot(){}async startStep(){return new RE}};import{z as xE}from"zod";var _Ae=xE.object({parentStepIdChain:xE.array(xE.string()),result:Eo});import{z as oe}from"zod";var gr="assets",A$=oe.object({step:Nt,status:oe.nativeEnum(at),startedAt:oe.coerce.date(),finishedAt:oe.coerce.date().optional(),healMetadata:oe.object({healType:oe.nativeEnum(vu).or(oe.literal("AI")),healedAt:oe.coerce.date()}).optional(),beforeSnapshotId:oe.string().uuid().optional(),afterSnapshotId:oe.string().uuid().optional(),message:oe.string().optional()}),C$=A$.extend({finishedAt:oe.coerce.date().optional().transform(t=>t??new Date)}),FAe=C$.extend({step:oe.unknown()}),_E=oe.object({avdId:oe.string().optional(),channel:oe.string().optional(),tag:oe.string().optional()}),NI="1.0.0",IE=K_.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:_E.optional(),activeVideos:oe.array(oe.object({videoName:oe.string(),timestamp:oe.coerce.date()})).optional()}),DI=IE.extend({assetDetails:_E.optional(),finishedAt:oe.coerce.date().optional().transform(t=>t??new Date)}),BAe=IE.merge(Cu),zAe=DI.merge(Cu),kI=oe.object({results:oe.array(Eo),beforeResults:oe.array(Eo).optional(),afterResults:oe.array(Eo).optional()}),HAe=IE.merge(kI),GAe=DI.merge(kI),UI=q_.merge(W_).extend({executionType:oe.nativeEnum(Al).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:mi.optional(),avgCpuUsage:oe.number().optional(),avgMemoryUsage:oe.number().optional()}),R$=UI.merge(_E),FI=UI.extend({finishedAt:oe.coerce.date().optional().transform(t=>t??new Date)}),jAe=R$.extend({finishedAt:oe.coerce.date().optional().transform(t=>t??new Date)}),w$=j_.merge(V_).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()}),ql=w$.extend({updatedAt:oe.coerce.date().optional().transform(t=>t??new Date),finishedAt:oe.coerce.date().optional().transform(t=>t??new Date)});var x$=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"]),_$=new Set(["MODULE","RESOLVED_MODULE"]),XAe=new Set(["MOBILE_MODULE_STEP","RESOLVED_MOBILE_MODULE"]);function ef(t){return t.type!=="PRESET_ACTION"?t.type:t.command.type}function tf(t){return _$.has(t.type)?!1:t.type!=="PRESET_ACTION"?!0:!x$.has(t.command.type)}var PRe=5*1024,I$="...[truncated]",MRe=Buffer.byteLength(I$,"utf8");import M$ from"fetch-retry";import O$ from"os";import zI,{multistream as L$}from"pino";import N$ from"pino-pretty";import D$ from"pino-std-serializers";var dd;function BI(t){dd=t}var P$=new Set(["InternalWebAgentError","InternalPlatformError","UnknownError"]);function PE(t){return t instanceof Error&&t.name==="AbortError"?!1:t instanceof L?P$.has(t.reason):!0}var Kl=new Map,k$=!0,HI="Log throttle exceeded",U$=100,F$=5e3,B$=M$(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}}),ME=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??O$.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=k$?zI(s):zI(s,L$([{stream:N$({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 B$(this.site,{method:"POST",headers:{"Content-Type":"application/json","signoz-access-token":"CumAaTMUcwjt05OddAmefKgshbhfRmWxzxih"},body:cs(e),signal:AbortSignal.timeout(5e3)});if(!r.ok)throw new Error(`Got error status (${r.statusText}) from SigNoz`)}catch{}}shouldAllowLog(e){if(e===HI)return!0;let r=Date.now();return r-this.lastWindowStart>F$&&(this.logsInCurrentWindow=0,this.droppedLogsInWindow&&this.log("error",void 0,HI),this.droppedLogsInWindow=!1,this.lastWindowStart=r),this.logsInCurrentWindow<U$?(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(ld[e]<this.minLevelValue||!this.shouldAllowLog(n))return;e==="error"&&this.captureExceptions&&dd&&(r instanceof Error&&PE(r)?dd(r):typeof r=="object"&&r&&"err"in r&&r.err instanceof Error&&PE(r.err)&&dd(r.err)),typeof r=="string"&&!n&&(r={message:r}),typeof r=="object"&&r&&"err"in r&&r.err instanceof Error&&(r.err=D$.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:T_({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,Kl.set("app",this),Kl.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=b_[e]):(this.minLevelValue=ld[e],this.consoleLogger.level=e)}enableConsoleLogs(){this.disableConsoleLogs=!1}},Yl=({app:t,hostname:e,disableConsoleLogs:r,captureExceptions:n})=>(Kl.has(t)||Kl.set(t,new ME({bindings:{app:t},hostname:e,disableConsoleLogs:r,captureExceptions:n})),Kl.get(t));async function rf(){await Promise.all([...Kl.values()].map(t=>t.flush()))}import{PostHog as z$}from"posthog-node";var aa=class extends Error{constructor(e){super(e),this.name="TimeoutError"}};var jI=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(jI(p));l=()=>c(jI(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 aa(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 VI(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 nf=class t extends ad{constructor(r,n,o,i){super(o,i);this.client=r;this.orgId=n}static async init(r){let n=new z$("phc_WRWd8LYIv6rolgDsyCdrPpxtZhsu6qXAkEwPicl44bI",{host:"https://us.i.posthog.com"}),{flags:o,payloads:i}=await VI(n,r);return new t(n,r,o,i)}async refresh(){let{flags:r,payloads:n}=await VI(this.client,this.orgId);this.flags=r,this.payloads=n}};import{randomUUID as H$}from"node:crypto";import{PostHog as G$}from"posthog-node";var of=class t{identity;bindings;client;options;constructor(e,r={},n){this.bindings=e,this.options=r,this.identity=n,this.client=new G$("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(!hx(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??H$(),event:n,timestamp:r?.timestamp,properties:{...this.bindings,...o,organizationId:this.identity?.orgId}}),this}};import{execSync as j$}from"child_process";import{readFileSync as qI}from"fs";import Si from"os";import V$ from"v8";var ds=!!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 W$=2e3,ps=t=>Number.parseInt(t,10),NE=t=>qI(t,"utf8").trim(),Xl=t=>ps(NE(t)),WI,af,OE=0,lf=Si.platform(),$$=Si.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 LE(t=Date.now()){let e=Si.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 KI(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 q$(){let t=LE();return()=>{let e=LE(),r=KI(t,e);return t=e,r}}function $I(){try{let e=qI("/sys/fs/cgroup/cpu.stat","utf8").match(/^usage_usec\s+(\d+)/m);if(e?.[1])return ps(e[1])}catch{}try{let t=Xl("/sys/fs/cgroup/cpuacct/cpuacct.usage");if(!isNaN(t))return t/1e3}catch{}return null}function K$(){try{let e=NE("/sys/fs/cgroup/cpu.max").split(" "),r=e[0],n=e[1];return!r||!n||r==="max"?null:ps(r)/ps(n)}catch{}try{let t=Xl("/sys/fs/cgroup/cpu/cpu.cfs_quota_us"),e=Xl("/sys/fs/cgroup/cpu/cpu.cfs_period_us");return t===-1||isNaN(e)?null:t/e}catch{return null}}function Y$(){if(lf!=="linux")return null;let t=$I();if(t===null)return null;let e=K$()??Si.cpus().length,r=t,n=Date.now();return()=>{let o=$I();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 X$(){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(Si.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 YI({intervalMs:t=W$,maxSamples:e=1e4,keepSamples:r=!0,onSample:n}={}){let o=[],i=Y$()??q$(),a=X$(),s=()=>{let u=Date.now(),d=QI(),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 sf=t=>{try{let e={},r=!1,n=QI(),o=Q$(),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=V$.getHeapStatistics(),c=s.used_heap_size,l=s.heap_size_limit;c/l>.9&&(r=!0),r?(OE++,t.warn({memory:n,cpu:o,heapStats:s,...e},"Critical resource usage metrics detected"),ds&&OE>=2&&v.warn(`Low machine resources detected (memory: ${i} free, cpu: ${a} free)`)):(OE=0,t.debug({memory:n,cpu:o},"Got machine resource usage metrics"))}catch{}},XI=t=>{sf(t),setTimeout(()=>sf(t),5e3)};function JI(t){if(!Vn)return sf(t),{interval:setInterval(()=>sf(t),2e4),cpuMetadata:$$,platform:lf}}function J$(){if(lf!=="linux")return null;try{let t=NE("/sys/fs/cgroup/memory.max"),e=Xl("/sys/fs/cgroup/memory.current");if(t==="max"||isNaN(e))return null;let r=ps(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=Xl("/sys/fs/cgroup/memory/memory.limit_in_bytes"),e=Xl("/sys/fs/cgroup/memory/memory.usage_in_bytes");if(isNaN(t)||isNaN(e))return null;let r=Si.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 QI(){let t=J$();if(t)return t;let e=Si.totalmem(),r=lf==="darwin"?Z$():(()=>{let o=Si.freemem();return{availableMemory:o,rawFreeMemory:o,cachedMemory:0}})(),n=r.availableMemory/e;return{totalMemory:e,freeMemory:r.availableMemory,freePercentage:n}}function Q$(){let t=LE();if(!af)return af=t,null;let e=KI(af,t);return af=t,e?(WI=e,WI):null}function Z$(){try{let t=j$("/usr/bin/vm_stat",{encoding:"utf8",stdio:["pipe","pipe","ignore"]}),r=t.match(/page size of (\d+) bytes/)?.[1],n=r?ps(r):4096,o=u=>{let p=t.match(new RegExp(`${u}:\\s+(\\d+)\\.`,"i"))?.[1];return p?ps(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=Si.freemem();return{availableMemory:t,rawFreeMemory:t,cachedMemory:0}}}var cf=class{increment(e,r,n){}gauge(e,r){}distribution(e,r,n){}async flush(){}async recordDuration({fn:e}){return await e()}};function eq(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 uf(t,e){let r=eq(t);return!e||Object.keys(e).length===0?r:{...e,...r}}var RP="=",ff=";",$E=",";var wP=8192;var ec={};kH(ec,{getKeyPairs:()=>Lq,parseKeyPairsIntoRecord:()=>Nq,parsePairKeyValue:()=>xP,serializeKeyPairs:()=>Oq});yt();var Mq=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 Oq(t){return t.reduce(function(e,r){var n=""+e+(e!==""?$E:"")+r;return n.length>wP?e:n},"")}function Lq(t){return t.getAllEntries().map(function(e){var r=Mq(e,2),n=r[0],o=r[1],i=encodeURIComponent(n)+"="+encodeURIComponent(o.value);return o.metadata!==void 0&&(i+=ff+o.metadata.toString()),i})}function xP(t){var e=t.split(ff);if(!(e.length<=0)){var r=e.shift();if(r){var n=r.indexOf(RP);if(!(n<=0)){var o=decodeURIComponent(r.substring(0,n).trim()),i=decodeURIComponent(r.substring(n+1).trim()),a;return e.length>0&&(a=kE(e.join(ff))),{key:o,value:i,metadata:a}}}}}function Nq(t){return typeof t!="string"||t.length===0?{}:t.split($E).map(function(e){return xP(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 hf;(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"})(hf||(hf={}));var Dq=",",kq=["OTEL_SDK_DISABLED"];function Uq(t){return kq.indexOf(t)>-1}var Fq=["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 Bq(t){return Fq.indexOf(t)>-1}var zq=["OTEL_NO_PATCH_MODULES","OTEL_PROPAGATORS"];function Hq(t){return zq.indexOf(t)>-1}var qE=1/0,KE=128,Gq=128,jq=128,YE={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:qE,OTEL_ATTRIBUTE_COUNT_LIMIT:KE,OTEL_SPAN_ATTRIBUTE_VALUE_LENGTH_LIMIT:qE,OTEL_SPAN_ATTRIBUTE_COUNT_LIMIT:KE,OTEL_LOGRECORD_ATTRIBUTE_VALUE_LENGTH_LIMIT:qE,OTEL_LOGRECORD_ATTRIBUTE_COUNT_LIMIT:KE,OTEL_SPAN_EVENT_COUNT_LIMIT:128,OTEL_SPAN_LINK_COUNT_LIMIT:128,OTEL_SPAN_ATTRIBUTE_PER_EVENT_COUNT_LIMIT:Gq,OTEL_SPAN_ATTRIBUTE_PER_LINK_COUNT_LIMIT:jq,OTEL_TRACES_EXPORTER:"",OTEL_TRACES_SAMPLER:hf.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 Vq(t,e,r){if(!(typeof r[t]>"u")){var n=String(r[t]);e[t]=n.toLowerCase()==="true"}}function Wq(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 $q(t,e,r,n){n===void 0&&(n=Dq);var o=r[t];typeof o=="string"&&(e[t]=o.split(n).map(function(i){return i.trim()}))}var qq={ALL:At.ALL,VERBOSE:At.VERBOSE,DEBUG:At.DEBUG,INFO:At.INFO,WARN:At.WARN,ERROR:At.ERROR,NONE:At.NONE};function Kq(t,e,r){var n=r[t];if(typeof n=="string"){var o=qq[n.toUpperCase()];o!=null&&(e[t]=o)}}function _P(t){var e={};for(var r in YE){var n=r;switch(n){case"OTEL_LOG_LEVEL":Kq(n,e,t);break;default:if(Uq(n))Vq(n,e,t);else if(Bq(n))Wq(n,e,t);else if(Hq(n))$q(n,e,t);else{var o=t[n];typeof o<"u"&&o!==null&&(e[n]=String(o))}}}return e}function Sr(){var t=_P(process.env);return Object.assign({},YE,t)}function IP(t){return t>=48&&t<=57?t-48:t>=97&&t<=102?t-87:t-55}function gf(t){for(var e=new Uint8Array(t.length/2),r=0,n=0;n<t.length;n+=2){var o=IP(t.charCodeAt(n)),i=IP(t.charCodeAt(n+1));e[r++]=o<<4|i}return e}var PP="1.25.1";var Yq="deployment.environment";var Xq="process.runtime.name";var Jq="service.name";var Qq="service.instance.id";var Zq="telemetry.sdk.name",eK="telemetry.sdk.language",tK="telemetry.sdk.version";var MP=Yq;var OP=Xq;var Sf=Jq;var LP=Qq;var yd=Zq,Ed=eK,Td=tK;var rK="nodejs";var NP=rK;var tc,yf=(tc={},tc[yd]="opentelemetry",tc[OP]="node",tc[Ed]=NP,tc[Td]=PP,tc);var nK=9,oK=6,iK=Math.pow(10,oK),aK=Math.pow(10,nK);function DP(t){var e=t/1e3,r=Math.trunc(e),n=Math.round(t%1e3*iK);return[r,n]}function kP(t){return t[0]*aK+t[1]}function bd(t){return t[0]*1e6+t[1]/1e3}var fs;(function(t){t[t.SUCCESS=0]="SUCCESS",t[t.FAILED=1]="FAILED"})(fs||(fs={}));var UP=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 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},lK=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))},FP=function(){function t(e,r){this._callback=e,this._that=r,this._isCalled=!1,this._deferred=new UP}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,lK([this._that],sK(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 $n;(function(t){t[t.DELTA=0]="DELTA",t[t.CUMULATIVE=1]="CUMULATIVE"})($n||($n={}));var Nr;(function(t){t[t.HISTOGRAM=0]="HISTOGRAM",t[t.EXPONENTIAL_HISTOGRAM=1]="EXPONENTIAL_HISTOGRAM",t[t.GAUGE=2]="GAUGE",t[t.SUM=3]="SUM"})(Nr||(Nr={}));var cK=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 D_e=function(t){cK(e,t);function e(r){var n=t.call(this,r)||this;return Object.setPrototypeOf(n,e.prototype),n}return e}(Error);function BP(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 qn;(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"})(qn||(qn={}));var zP=function(){function t(){this.kind=qn.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 Be;(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"})(Be||(Be={}));var uK=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 dK(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 XE=function(){function t(e,r,n,o){n===void 0&&(n=!0),o===void 0&&(o=dK(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=BP(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 JE=function(){function t(e,r){this._boundaries=e,this._recordMinMax=r,this.kind=qn.HISTOGRAM}return t.prototype.createAccumulation=function(e){return new XE(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 XE(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 XE(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:Nr.HISTOGRAM,dataPoints:n.map(function(i){var a=uK(i,2),s=a[0],c=a[1],l=c.toPointValue(),u=e.type===Be.GAUGE||e.type===Be.UP_DOWN_COUNTER||e.type===Be.OBSERVABLE_GAUGE||e.type===Be.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 QE=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},ZE=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))},eT=function(){function t(e,r,n,o){e===void 0&&(e=new pK),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 pK=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,ZE([n,this._counts.length-r],QE(this._counts.slice(r)),!1)),o.splice.apply(o,ZE([0,r],QE(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(ZE([],QE(this._counts),!1))},t}();var HP=52,mK=2146435072,fK=1048575,tT=1023,Ef=-tT+1,Tf=tT,vd=Math.pow(2,-1022);function bf(t){var e=new DataView(new ArrayBuffer(8));e.setFloat64(0,t);var r=e.getUint32(0),n=(r&mK)>>20;return n-tT}function vf(t){var e=new DataView(new ArrayBuffer(8));e.setFloat64(0,t);var r=e.getUint32(0),n=e.getUint32(4),o=(r&fK)*Math.pow(2,32);return o+n}function Ad(t,e){return t===0||t===Number.POSITIVE_INFINITY||t===Number.NEGATIVE_INFINITY||Number.isNaN(t)?t:t*Math.pow(2,e)}function jP(t){return t--,t|=t>>1,t|=t>>2,t|=t>>4,t|=t>>8,t|=t>>16,t++,t}var hK=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){hK(e,t);function e(){return t!==null&&t.apply(this,arguments)||this}return e}(Error);var WP=function(){function t(e){this._shift=-e}return t.prototype.mapToIndex=function(e){if(e<vd)return this._minNormalLowerBoundaryIndex();var r=bf(e),n=this._rightShift(vf(e)-1,HP);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 Ad(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=Ef>>this._shift;return this._shift<2&&e--,e},t.prototype._maxNormalLowerBoundaryIndex=function(){return Tf>>this._shift},t.prototype._rightShift=function(e,r){return Math.floor(e*Math.pow(2,-r))},t}();var $P=function(){function t(e){this._scale=e,this._scaleFactor=Ad(Math.LOG2E,e),this._inverseFactor=Ad(Math.LN2,-e)}return t.prototype.mapToIndex=function(e){if(e<=vd)return this._minNormalLowerBoundaryIndex()-1;if(vf(e)===0){var r=bf(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 vd;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 Ef<<this._scale},t.prototype._maxNormalLowerBoundaryIndex=function(){return(Tf+1<<this._scale)-1},t}();var qP=-10,KP=20,gK=Array.from({length:31},function(t,e){return e>10?new $P(e-10):new WP(e-10)});function rT(t){if(t>KP||t<qP)throw new sa("expected scale >= "+qP+" && <= "+KP+", got: "+t);return gK[t+10]}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},Af=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}(),yK=20,EK=160,nT=2,TK=function(){function t(e,r,n,o,i,a,s,c,l,u,d){e===void 0&&(e=e),r===void 0&&(r=EK),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 eT),u===void 0&&(u=new eT),d===void 0&&(d=rT(yK)),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<nT&&(ie.warn("Exponential Histogram Max Size set to "+this._maxSize+", changing to the minimum size of: "+nT),this._maxSize=nT)}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=jP(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=rT(r)}},t.prototype._minScale=function(e){var r=Math.min(this.scale,e.scale),n=Af.combine(this._highLowAtScale(this.positive,this.scale,r),this._highLowAtScale(e.positive,e.scale,r)),o=Af.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 Af(0,-1);var o=r-n;return new Af(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 YP=function(){function t(e,r){this._maxSize=e,this._recordMinMax=r,this.kind=qn.EXPONENTIAL_HISTOGRAM}return t.prototype.createAccumulation=function(e){return new TK(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:Nr.EXPONENTIAL_HISTOGRAM,dataPoints:n.map(function(i){var a=SK(i,2),s=a[0],c=a[1],l=c.toPointValue(),u=e.type===Be.GAUGE||e.type===Be.UP_DOWN_COUNTER||e.type===Be.OBSERVABLE_GAUGE||e.type===Be.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 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},oT=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=DP(Date.now())},t.prototype.setStartTime=function(e){this.startTime=e},t.prototype.toPointValue=function(){return this._current},t}();var XP=function(){function t(){this.kind=qn.LAST_VALUE}return t.prototype.createAccumulation=function(e){return new oT(e)},t.prototype.merge=function(e,r){var n=bd(r.sampleTime)>=bd(e.sampleTime)?r:e;return new oT(e.startTime,n.toPointValue(),n.sampleTime)},t.prototype.diff=function(e,r){var n=bd(r.sampleTime)>=bd(e.sampleTime)?r:e;return new oT(r.startTime,n.toPointValue(),n.sampleTime)},t.prototype.toMetricData=function(e,r,n,o){return{descriptor:e,aggregationTemporality:r,dataPointType:Nr.GAUGE,dataPoints:n.map(function(i){var a=bK(i,2),s=a[0],c=a[1];return{attributes:s,startTime:c.startTime,endTime:o,value:c.toPointValue()}})}},t}();var vK=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},Cd=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 iT=function(){function t(e){this.monotonic=e,this.kind=qn.SUM}return t.prototype.createAccumulation=function(e){return new Cd(e,this.monotonic)},t.prototype.merge=function(e,r){var n=e.toPointValue(),o=r.toPointValue();return r.reset?new Cd(r.startTime,this.monotonic,o,r.reset):new Cd(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 Cd(r.startTime,this.monotonic,o,!0):new Cd(r.startTime,this.monotonic,o-n)},t.prototype.toMetricData=function(e,r,n,o){return{descriptor:e,aggregationTemporality:r,dataPointType:Nr.SUM,dataPoints:n.map(function(i){var a=vK(i,2),s=a[0],c=a[1];return{attributes:s,startTime:c.startTime,endTime:o,value:c.toPointValue()}}),isMonotonic:this.monotonic}},t}();var hs=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)}}(),Vo=function(){function t(){}return t.Drop=function(){return oM},t.Sum=function(){return iM},t.LastValue=function(){return aM},t.Histogram=function(){return sM},t.ExponentialHistogram=function(){return AK},t.Default=function(){return CK},t}();var JP=function(t){hs(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 zP,e}(Vo);var QP=function(t){hs(e,t);function e(){return t!==null&&t.apply(this,arguments)||this}return e.prototype.createAggregator=function(r){switch(r.type){case Be.COUNTER:case Be.OBSERVABLE_COUNTER:case Be.HISTOGRAM:return e.MONOTONIC_INSTANCE;default:return e.NON_MONOTONIC_INSTANCE}},e.MONOTONIC_INSTANCE=new iT(!0),e.NON_MONOTONIC_INSTANCE=new iT(!1),e}(Vo);var ZP=function(t){hs(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 XP,e}(Vo);var eM=function(t){hs(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 JE([0,5,10,25,50,75,100,250,500,750,1e3,2500,5e3,7500,1e4],!0),e}(Vo);var tM=function(t){hs(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 JE(this._boundaries,this._recordMinMax)},e}(Vo);var rM=function(t){hs(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 YP(this._maxSize,this._recordMinMax)},e}(Vo);var nM=function(t){hs(e,t);function e(){return t!==null&&t.apply(this,arguments)||this}return e.prototype._resolve=function(r){switch(r.type){case Be.COUNTER:case Be.UP_DOWN_COUNTER:case Be.OBSERVABLE_COUNTER:case Be.OBSERVABLE_UP_DOWN_COUNTER:return iM;case Be.GAUGE:case Be.OBSERVABLE_GAUGE:return aM;case Be.HISTOGRAM:return r.advice.explicitBucketBoundaries?new tM(r.advice.explicitBucketBoundaries):sM}return ie.warn("Unable to recognize instrument type: "+r.type),oM},e.prototype.createAggregator=function(r){return this._resolve(r).createAggregator(r)},e}(Vo);var oM=new JP,iM=new QP,aM=new ZP,sM=new eM,AK=new rM,CK=new nM;yt();function Cf(){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)},RK=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())})},wK=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},aT=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[Sf]=Cf(),e[Ed]=yf[Ed],e[yd]=yf[yd],e[Td]=yf[Td],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 RK(this,void 0,void 0,function(){return wK(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=xK(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 gs;(function(t){t[t.DELTA=0]="DELTA",t[t.CUMULATIVE=1]="CUMULATIVE",t[t.LOWMEMORY=2]="LOWMEMORY"})(gs||(gs={}));yt();var _K=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())})},IK=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}}},sT=function(){return $n.CUMULATIVE},lM=function(t){switch(t){case Be.COUNTER:case Be.OBSERVABLE_COUNTER:case Be.GAUGE:case Be.HISTOGRAM:case Be.OBSERVABLE_GAUGE:return $n.DELTA;case Be.UP_DOWN_COUNTER:case Be.OBSERVABLE_UP_DOWN_COUNTER:return $n.CUMULATIVE}},cM=function(t){switch(t){case Be.COUNTER:case Be.HISTOGRAM:return $n.DELTA;case Be.GAUGE:case Be.UP_DOWN_COUNTER:case Be.OBSERVABLE_UP_DOWN_COUNTER:case Be.OBSERVABLE_COUNTER:case Be.OBSERVABLE_GAUGE:return $n.CUMULATIVE}};function PK(){var t=Sr(),e=t.OTEL_EXPORTER_OTLP_METRICS_TEMPORALITY_PREFERENCE.trim().toLowerCase();return e==="cumulative"?sT:e==="delta"?lM:e==="lowmemory"?cM:(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."),sT)}function MK(t){return t!=null?t===gs.DELTA?lM:t===gs.LOWMEMORY?cM:sT:PK()}function OK(t){return t?.aggregationPreference?t.aggregationPreference:function(e){return Vo.Default()}}var uM=function(){function t(e,r){this._otlpExporter=e,this._aggregationSelector=OK(r),this._aggregationTemporalitySelector=MK(r?.temporalityPreference)}return t.prototype.export=function(e,r){this._otlpExporter.export([e],r)},t.prototype.shutdown=function(){return _K(this,void 0,void 0,function(){return IK(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 LK=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},dM=1e4,pM=5,mM=1e3,fM=5e3,hM=1.5;function Rd(t){t===void 0&&(t={});var e={};return Object.entries(t).forEach(function(r){var n=LK(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 lT(t,e){return t.endsWith("/")||(t=t+"/"),t+e}function cT(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 uT(t){return typeof t=="number"?t<=0?dT(t,dM):t:NK()}function NK(){var t,e=Number((t=Sr().OTEL_EXPORTER_OTLP_TRACES_TIMEOUT)!==null&&t!==void 0?t:Sr().OTEL_EXPORTER_OTLP_TIMEOUT);return e<=0?dT(e,dM):e}function dT(t,e){return ie.warn("Timeout must be greater than 0",t),e}function gM(t){var e=[429,502,503,504];return e.includes(t)}function SM(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 yM=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 FP(this._shutdown,this),this._concurrencyLimit=typeof e.concurrencyLimit=="number"?e.concurrencyLimit:30,this.timeoutMillis=uT(e.timeoutMillis),this.onInit(e)}return t.prototype.export=function(e,r){if(this._shutdownOnce.isCalled){r({code:fs.FAILED,error:new Error("Exporter has been shutdown")});return}if(this._sendingPromises.length>=this._concurrencyLimit){r({code:fs.FAILED,error:new Error("Concurrent export limit reached")});return}this._export(e).then(function(){r({code:fs.SUCCESS})}).catch(function(n){r({code:fs.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 pT from"url";import*as wf from"http";import*as xf from"https";import*as EM from"zlib";import{Readable as kK}from"stream";var ca;(function(t){t.NONE="none",t.GZIP="gzip"})(ca||(ca={}));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)}}(),rc=function(t){DK(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 Rf=function(){return Rf=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},Rf.apply(this,arguments)};function mT(t,e,r,n,o){var i=t.timeoutMillis,a=new pT.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 rc("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:Rf({"Content-Type":r},t.headers),agent:t.agent},m=a.protocol==="http:"?wf.request:xf.request,f=function(h,S){switch(h===void 0&&(h=pM),S===void 0&&(S=mM),l=m(p,function(E){var y="";E.on("data",function(b){return y+=b}),E.on("aborted",function(){if(u){var b=new rc("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&&gM(E.statusCode)&&h>0){var b=void 0;S=hM*S,E.headers["retry-after"]?b=SM(E.headers["retry-after"]):b=Math.round(Math.random()*(fM-S)+S),c=setTimeout(function(){f(h-1,S)},b)}else{var C=new rc(E.statusMessage,E.statusCode,y);o(C),clearTimeout(d),clearTimeout(c)}})}),l.on("error",function(E){if(u){var y=new rc("Request Timeout",E.code);o(y)}else o(E);clearTimeout(d),clearTimeout(c)}),l.on("abort",function(){if(u){var E=new rc("Request Timeout");o(E)}clearTimeout(d),clearTimeout(c)}),t.compression){case ca.GZIP:{l.setHeader("Content-Encoding","gzip");var g=UK(e);g.on("error",o).pipe(EM.createGzip()).on("error",o).pipe(l);break}default:l.end(Buffer.from(e));break}};f()}function UK(t){var e=new kK;return e.push(t),e.push(null),e}function fT(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 pT.URL(t.url),r=e.protocol==="http:"?wf.Agent:xf.Agent;return new r(Rf({keepAlive:!0},t.httpAgentOptions))}catch(n){ie.error("collector exporter failed to create http agent. err: "+n.message);return}}function hT(t){if(t)return t;var e=Sr().OTEL_EXPORTER_OTLP_TRACES_COMPRESSION||Sr().OTEL_EXPORTER_OTLP_COMPRESSION;return e===ca.GZIP?ca.GZIP:ca.NONE}yt();var FK=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)}}(),_f=function(t){FK(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,Rd(r.headers),ec.parseKeyPairsIntoRecord(Sr().OTEL_EXPORTER_OTLP_HEADERS)),i.agent=fT(r),i.compression=hT(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;mT(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}(yM);function bM(t){var e=BigInt(1e9);return BigInt(t[0])*e+BigInt(t[1])}function BK(t){var e=Number(BigInt.asUintN(32,t)),r=Number(BigInt.asUintN(32,t>>BigInt(32)));return{low:e,high:r}}function vM(t){var e=bM(t);return BK(e)}function zK(t){var e=bM(t);return e.toString()}var HK=typeof BigInt<"u"?zK:kP;function TM(t){return t}function AM(t){if(t!==void 0)return gf(t)}var GK={encodeHrTime:vM,encodeSpanContext:gf,encodeOptionalSpanContext:AM};function CM(t){var e,r;if(t===void 0)return GK;var n=(e=t.useLongBits)!==null&&e!==void 0?e:!0,o=(r=t.useHex)!==null&&r!==void 0?r:!1;return{encodeHrTime:n?vM:HK,encodeSpanContext:o?TM:gf,encodeOptionalSpanContext:o?TM:AM}}var jK=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 RM(t){return{name:t.name,version:t.version}}function nc(t){return Object.keys(t).map(function(e){return wM(e,t[e])})}function wM(t,e){return{key:t,value:xM(e)}}function xM(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(xM)}}:e==="object"&&t!=null?{kvlistValue:{values:Object.entries(t).map(function(r){var n=jK(r,2),o=n[0],i=n[1];return wM(o,i)})}}:{}}function _M(t){return{attributes:nc(t.attributes),droppedAttributesCount:0}}yt();function PM(t,e){var r=CM(e);return{resource:_M(t.resource),schemaUrl:void 0,scopeMetrics:VK(t.scopeMetrics,r)}}function VK(t,e){return Array.from(t.map(function(r){return{scope:RM(r.scope),metrics:r.metrics.map(function(n){return WK(n,e)}),schemaUrl:r.scope.schemaUrl}}))}function WK(t,e){var r={name:t.descriptor.name,description:t.descriptor.description,unit:t.descriptor.unit},n=YK(t.aggregationTemporality);switch(t.dataPointType){case Nr.SUM:r.sum={aggregationTemporality:n,isMonotonic:t.isMonotonic,dataPoints:IM(t,e)};break;case Nr.GAUGE:r.gauge={dataPoints:IM(t,e)};break;case Nr.HISTOGRAM:r.histogram={aggregationTemporality:n,dataPoints:qK(t,e)};break;case Nr.EXPONENTIAL_HISTOGRAM:r.exponentialHistogram={aggregationTemporality:n,dataPoints:KK(t,e)};break}return r}function $K(t,e,r){var n={attributes:nc(t.attributes),startTimeUnixNano:r.encodeHrTime(t.startTime),timeUnixNano:r.encodeHrTime(t.endTime)};switch(e){case Tn.INT:n.asInt=t.value;break;case Tn.DOUBLE:n.asDouble=t.value;break}return n}function IM(t,e){return t.dataPoints.map(function(r){return $K(r,t.descriptor.valueType,e)})}function qK(t,e){return t.dataPoints.map(function(r){var n=r.value;return{attributes:nc(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 KK(t,e){return t.dataPoints.map(function(r){var n=r.value;return{attributes:nc(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 YK(t){switch(t){case $n.DELTA:return 1;case $n.CUMULATIVE:return 2}}function MM(t,e){return{resourceMetrics:t.map(function(r){return PM(r,e)})}}var gT={serializeRequest:function(t){var e=MM(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 OM="0.52.1";var LM=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)}}(),oc=function(){return oc=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},oc.apply(this,arguments)},NM="v1/metrics",XK="http://localhost:4318/"+NM,JK={"User-Agent":"OTel-OTLP-Exporter-JavaScript/"+OM},QK=function(t){LM(e,t);function e(r){var n=t.call(this,r,gT,"application/json")||this;return n.headers=oc(oc(oc(oc({},n.headers),JK),ec.parseKeyPairsIntoRecord(Sr().OTEL_EXPORTER_OTLP_METRICS_HEADERS)),Rd(r?.headers)),n}return e.prototype.getDefaultUrl=function(r){return typeof r.url=="string"?r.url:Sr().OTEL_EXPORTER_OTLP_METRICS_ENDPOINT.length>0?cT(Sr().OTEL_EXPORTER_OTLP_METRICS_ENDPOINT):Sr().OTEL_EXPORTER_OTLP_ENDPOINT.length>0?lT(Sr().OTEL_EXPORTER_OTLP_ENDPOINT,NM):XK},e}(_f),DM=function(t){LM(e,t);function e(r){return t.call(this,new QK(r),r)||this}return e}(uM);var ic;(function(t){t[t.DELTA=0]="DELTA",t[t.CUMULATIVE=1]="CUMULATIVE"})(ic||(ic={}));var Wo;(function(t){t[t.HISTOGRAM=0]="HISTOGRAM",t[t.EXPONENTIAL_HISTOGRAM=1]="EXPONENTIAL_HISTOGRAM",t[t.GAUGE=2]="GAUGE",t[t.SUM=3]="SUM"})(Wo||(Wo={}));yt();var ZK=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)}}(),kM=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())})},UM=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}}},e2=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},t2=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))},r2=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 FM(t){return t!=null}function If(t){var e=Object.keys(t);return e.length===0?"":(e=e.sort(),JSON.stringify(e.map(function(r){return[r,t[r]]})))}function BM(t){var e,r;return t.name+":"+((e=t.version)!==null&&e!==void 0?e:"")+":"+((r=t.schemaUrl)!==null&&r!==void 0?r:"")}var ST=function(t){ZK(e,t);function e(r){var n=t.call(this,r)||this;return Object.setPrototypeOf(n,e.prototype),n}return e}(Error);function ua(t,e){var r,n=new Promise(function(i,a){r=setTimeout(function(){a(new ST("Operation timed out."))},e)});return Promise.race([t,n]).then(function(o){return clearTimeout(r),o},function(o){throw clearTimeout(r),o})}function zM(t){return kM(this,void 0,void 0,function(){var e=this;return UM(this,function(r){return[2,Promise.all(t.map(function(n){return kM(e,void 0,void 0,function(){var o,i;return UM(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 HM(t){return t.status==="rejected"}function yT(t,e){var r=[];return t.forEach(function(n){r.push.apply(r,t2([],e2(e(n)),!1))}),r}function GM(t,e){var r,n;if(t.size!==e.size)return!1;try{for(var o=r2(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 jM(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 VM(t,e){return t.toLowerCase()===e.toLowerCase()}yt();var Kn;(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"})(Kn||(Kn={}));var ET=function(){function t(){this.kind=Kn.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 Ye;(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"})(Ye||(Ye={}));function $o(t,e,r){var n,o,i,a;return o2(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:Tn.DOUBLE,advice:(a=r?.advice)!==null&&a!==void 0?a:{}}}function WM(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 $M(t,e){return VM(t.name,e.name)&&t.unit===e.unit&&t.type===e.type&&t.valueType===e.valueType}var n2=/^[a-z][a-z0-9_.\-/]{0,254}$/i;function o2(t){return t.match(n2)!=null}var i2=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 a2(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 Pf=function(){function t(e,r,n,o){n===void 0&&(n=!0),o===void 0&&(o=a2(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=jM(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 Mf=function(){function t(e,r){this._boundaries=e,this._recordMinMax=r,this.kind=Kn.HISTOGRAM}return t.prototype.createAccumulation=function(e){return new Pf(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 Pf(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 Pf(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:Wo.HISTOGRAM,dataPoints:n.map(function(i){var a=i2(i,2),s=a[0],c=a[1],l=c.toPointValue(),u=e.type===Ye.GAUGE||e.type===Ye.UP_DOWN_COUNTER||e.type===Ye.OBSERVABLE_GAUGE||e.type===Ye.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 TT=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},bT=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))},vT=function(){function t(e,r,n,o){e===void 0&&(e=new s2),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 s2=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,bT([n,this._counts.length-r],TT(this._counts.slice(r)),!1)),o.splice.apply(o,bT([0,r],TT(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(bT([],TT(this._counts),!1))},t}();var qM=52,l2=2146435072,c2=1048575,AT=1023,Of=-AT+1,Lf=AT,wd=Math.pow(2,-1022);function Nf(t){var e=new DataView(new ArrayBuffer(8));e.setFloat64(0,t);var r=e.getUint32(0),n=(r&l2)>>20;return n-AT}function Df(t){var e=new DataView(new ArrayBuffer(8));e.setFloat64(0,t);var r=e.getUint32(0),n=e.getUint32(4),o=(r&c2)*Math.pow(2,32);return o+n}function xd(t,e){return t===0||t===Number.POSITIVE_INFINITY||t===Number.NEGATIVE_INFINITY||Number.isNaN(t)?t:t*Math.pow(2,e)}function YM(t){return t--,t|=t>>1,t|=t>>2,t|=t>>4,t|=t>>8,t|=t>>16,t++,t}var u2=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)}}(),da=function(t){u2(e,t);function e(){return t!==null&&t.apply(this,arguments)||this}return e}(Error);var JM=function(){function t(e){this._shift=-e}return t.prototype.mapToIndex=function(e){if(e<wd)return this._minNormalLowerBoundaryIndex();var r=Nf(e),n=this._rightShift(Df(e)-1,qM);return r+n>>this._shift},t.prototype.lowerBoundary=function(e){var r=this._minNormalLowerBoundaryIndex();if(e<r)throw new da("underflow: "+e+" is < minimum lower boundary: "+r);var n=this._maxNormalLowerBoundaryIndex();if(e>n)throw new da("overflow: "+e+" is > maximum lower boundary: "+n);return xd(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=Of>>this._shift;return this._shift<2&&e--,e},t.prototype._maxNormalLowerBoundaryIndex=function(){return Lf>>this._shift},t.prototype._rightShift=function(e,r){return Math.floor(e*Math.pow(2,-r))},t}();var QM=function(){function t(e){this._scale=e,this._scaleFactor=xd(Math.LOG2E,e),this._inverseFactor=xd(Math.LN2,-e)}return t.prototype.mapToIndex=function(e){if(e<=wd)return this._minNormalLowerBoundaryIndex()-1;if(Df(e)===0){var r=Nf(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 da("overflow: "+e+" is > maximum lower boundary: "+r)}var n=this._minNormalLowerBoundaryIndex();if(e<=n){if(e===n)return wd;if(e===n-1)return Math.exp((e+(1<<this._scale))/this._scaleFactor)/2;throw new da("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 Of<<this._scale},t.prototype._maxNormalLowerBoundaryIndex=function(){return(Lf+1<<this._scale)-1},t}();var ZM=-10,eO=20,d2=Array.from({length:31},function(t,e){return e>10?new QM(e-10):new JM(e-10)});function CT(t){if(t>eO||t<ZM)throw new da("expected scale >= "+ZM+" && <= "+eO+", got: "+t);return d2[t+10]}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},kf=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}(),m2=20,f2=160,RT=2,tO=function(){function t(e,r,n,o,i,a,s,c,l,u,d){e===void 0&&(e=e),r===void 0&&(r=f2),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 vT),u===void 0&&(u=new vT),d===void 0&&(d=CT(m2)),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<RT&&(ie.warn("Exponential Histogram Max Size set to "+this._maxSize+", changing to the minimum size of: "+RT),this._maxSize=RT)}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=YM(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=CT(r)}},t.prototype._minScale=function(e){var r=Math.min(this.scale,e.scale),n=kf.combine(this._highLowAtScale(this.positive,this.scale,r),this._highLowAtScale(e.positive,e.scale,r)),o=kf.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 kf(0,-1);var o=r-n;return new kf(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 wT=function(){function t(e,r){this._maxSize=e,this._recordMinMax=r,this.kind=Kn.EXPONENTIAL_HISTOGRAM}return t.prototype.createAccumulation=function(e){return new tO(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:Wo.EXPONENTIAL_HISTOGRAM,dataPoints:n.map(function(i){var a=p2(i,2),s=a[0],c=a[1],l=c.toPointValue(),u=e.type===Ye.GAUGE||e.type===Ye.UP_DOWN_COUNTER||e.type===Ye.OBSERVABLE_GAUGE||e.type===Ye.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 h2=UE("OpenTelemetry SDK Context Key SUPPRESS_TRACING");function rO(t){return t.setValue(h2,!0)}yt();function nO(){return function(t){ie.error(g2(t))}}function g2(t){return typeof t=="string"?t:JSON.stringify(S2(t))}function S2(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 y2=nO();function Uf(t){try{y2(t)}catch{}}var oO="1.30.1";var E2="process.runtime.name";var T2="service.name";var b2="telemetry.sdk.name",v2="telemetry.sdk.language",A2="telemetry.sdk.version";var iO=E2;var aO=T2;var _d=b2,Id=v2,Pd=A2;var C2="nodejs";var sO=C2;var ac,Ss=(ac={},ac[_d]="opentelemetry",ac[iO]="node",ac[Id]=sO,ac[Pd]=oO,ac);function Md(t){t.unref()}var M2=9,O2=6,L2=Math.pow(10,O2),BMe=Math.pow(10,M2);function ys(t){var e=t/1e3,r=Math.trunc(e),n=Math.round(t%1e3*L2);return[r,n]}function sc(t){return t[0]*1e6+t[1]/1e3}var Od;(function(t){t[t.SUCCESS=0]="SUCCESS",t[t.FAILED=1]="FAILED"})(Od||(Od={}));yt();function lO(t,e){return new Promise(function(r){Zl.with(rO(Zl.active()),function(){t.export(e,function(n){r(n)})})})}var cO={_export:lO};var N2=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},Ff=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=ys(Date.now())},t.prototype.setStartTime=function(e){this.startTime=e},t.prototype.toPointValue=function(){return this._current},t}();var xT=function(){function t(){this.kind=Kn.LAST_VALUE}return t.prototype.createAccumulation=function(e){return new Ff(e)},t.prototype.merge=function(e,r){var n=sc(r.sampleTime)>=sc(e.sampleTime)?r:e;return new Ff(e.startTime,n.toPointValue(),n.sampleTime)},t.prototype.diff=function(e,r){var n=sc(r.sampleTime)>=sc(e.sampleTime)?r:e;return new Ff(r.startTime,n.toPointValue(),n.sampleTime)},t.prototype.toMetricData=function(e,r,n,o){return{descriptor:e,aggregationTemporality:r,dataPointType:Wo.GAUGE,dataPoints:n.map(function(i){var a=N2(i,2),s=a[0],c=a[1];return{attributes:s,startTime:c.startTime,endTime:o,value:c.toPointValue()}})}},t}();var D2=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},lc=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 Bf=function(){function t(e){this.monotonic=e,this.kind=Kn.SUM}return t.prototype.createAccumulation=function(e){return new lc(e,this.monotonic)},t.prototype.merge=function(e,r){var n=e.toPointValue(),o=r.toPointValue();return r.reset?new lc(r.startTime,this.monotonic,o,r.reset):new lc(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 lc(r.startTime,this.monotonic,o,!0):new lc(r.startTime,this.monotonic,o-n)},t.prototype.toMetricData=function(e,r,n,o){return{descriptor:e,aggregationTemporality:r,dataPointType:Wo.SUM,dataPoints:n.map(function(i){var a=D2(i,2),s=a[0],c=a[1];return{attributes:s,startTime:c.startTime,endTime:o,value:c.toPointValue()}}),isMonotonic:this.monotonic}},t}();var Es=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)}}(),Yn=function(){function t(){}return t.Drop=function(){return gO},t.Sum=function(){return SO},t.LastValue=function(){return yO},t.Histogram=function(){return EO},t.ExponentialHistogram=function(){return k2},t.Default=function(){return U2},t}();var uO=function(t){Es(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 ET,e}(Yn);var dO=function(t){Es(e,t);function e(){return t!==null&&t.apply(this,arguments)||this}return e.prototype.createAggregator=function(r){switch(r.type){case Ye.COUNTER:case Ye.OBSERVABLE_COUNTER:case Ye.HISTOGRAM:return e.MONOTONIC_INSTANCE;default:return e.NON_MONOTONIC_INSTANCE}},e.MONOTONIC_INSTANCE=new Bf(!0),e.NON_MONOTONIC_INSTANCE=new Bf(!1),e}(Yn);var pO=function(t){Es(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 xT,e}(Yn);var mO=function(t){Es(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 Mf([0,5,10,25,50,75,100,250,500,750,1e3,2500,5e3,7500,1e4],!0),e}(Yn);var Ld=function(t){Es(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 Mf(this._boundaries,this._recordMinMax)},e}(Yn);var fO=function(t){Es(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 wT(this._maxSize,this._recordMinMax)},e}(Yn);var hO=function(t){Es(e,t);function e(){return t!==null&&t.apply(this,arguments)||this}return e.prototype._resolve=function(r){switch(r.type){case Ye.COUNTER:case Ye.UP_DOWN_COUNTER:case Ye.OBSERVABLE_COUNTER:case Ye.OBSERVABLE_UP_DOWN_COUNTER:return SO;case Ye.GAUGE:case Ye.OBSERVABLE_GAUGE:return yO;case Ye.HISTOGRAM:return r.advice.explicitBucketBoundaries?new Ld(r.advice.explicitBucketBoundaries):EO}return ie.warn("Unable to recognize instrument type: "+r.type),gO},e.prototype.createAggregator=function(r){return this._resolve(r).createAggregator(r)},e}(Yn);var gO=new uO,SO=new dO,yO=new pO,EO=new mO,k2=new fO,U2=new hO;var TO=function(t){return Yn.Default()},bO=function(t){return ic.CUMULATIVE};var _T=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())})},IT=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}}},vO=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))},AO=function(){function t(e){var r,n,o;this._shutdown=!1,this._aggregationSelector=(r=e?.aggregationSelector)!==null&&r!==void 0?r:TO,this._aggregationTemporalitySelector=(n=e?.aggregationTemporalitySelector)!==null&&n!==void 0?n:bO,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 _T(this,void 0,void 0,function(){var r,n,o,i,a,s;return IT(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(F2([this._sdkMetricProducer.collect({timeoutMillis:e?.timeoutMillis})],vO(this._metricProducers.map(function(l){return l.collect({timeoutMillis:e?.timeoutMillis})})),!1))];case 1:return r=vO.apply(void 0,[c.sent()]),n=r[0],o=r.slice(1),i=n.errors.concat(yT(o,function(l){return l.errors})),a=n.resourceMetrics.resource,s=n.resourceMetrics.scopeMetrics.concat(yT(o,function(l){return l.resourceMetrics.scopeMetrics})),[2,{resourceMetrics:{resource:a,scopeMetrics:s},errors:i}]}})})},t.prototype.shutdown=function(e){return _T(this,void 0,void 0,function(){return IT(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,ua(this.onShutdown(),e.timeoutMillis)];case 3:r.sent(),r.label=4;case 4:return this._shutdown=!0,[2]}})})},t.prototype.forceFlush=function(e){return _T(this,void 0,void 0,function(){return IT(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,ua(this.onForceFlush(),e.timeoutMillis)];case 3:return r.sent(),[2]}})})},t}();yt();var B2=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)}}(),zf=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())})},Hf=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},H2=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))},PT=function(t){B2(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 zf(this,void 0,void 0,function(){var r;return Hf(this,function(n){switch(n.label){case 0:return n.trys.push([0,2,,3]),[4,ua(this._doRun(),this._exportTimeout)];case 1:return n.sent(),[3,3];case 2:return r=n.sent(),r instanceof ST?(ie.error("Export took longer than %s milliseconds and timed out.",this._exportTimeout),[2]):(Uf(r),[3,3]);case 3:return[2]}})})},e.prototype._doRun=function(){var r,n;return zf(this,void 0,void 0,function(){var o,i,a,s,c,l;return Hf(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,H2(["PeriodicExportingMetricReader: metrics collection errors"],z2(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),Uf(s),[3,5];case 5:return i.scopeMetrics.length===0?[2]:[4,cO._export(this._exporter,i)];case 6:if(c=u.sent(),c.code!==Od.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),Md(this._interval)},e.prototype.onForceFlush=function(){return zf(this,void 0,void 0,function(){return Hf(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 zf(this,void 0,void 0,function(){return Hf(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}(AO);yt();yt();function Gf(){return"unknown_service:"+process.argv0}var pa=function(){return pa=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},pa.apply(this,arguments)},G2=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())})},j2=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}}},V2=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},jf=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[aO]=Gf(),e[Id]=Ss[Id],e[_d]=Ss[_d],e[Pd]=Ss[Pd],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 G2(this,void 0,void 0,function(){return j2(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=pa(pa({},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=V2(a,2),l=c[0],u=c[1];return pa(pa(pa(pa({},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 CO=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 Ts=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)}}(),Vf=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=Zl.active()),typeof e!="number"){ie.warn("non-number value provided to metric "+this._descriptor.name+": "+e);return}this._descriptor.valueType===Tn.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,ys(Date.now()))},t}();var RO=function(t){Ts(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}(Vf);var wO=function(t){Ts(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}(Vf);var xO=function(t){Ts(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}(Vf);var _O=function(t){Ts(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}(Vf);var Wf=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 IO=function(t){Ts(e,t);function e(){return t!==null&&t.apply(this,arguments)||this}return e}(Wf);var PO=function(t){Ts(e,t);function e(){return t!==null&&t.apply(this,arguments)||this}return e}(Wf);var MO=function(t){Ts(e,t);function e(){return t!==null&&t.apply(this,arguments)||this}return e}(Wf);function Nd(t){return t instanceof Wf}var OO=function(){function t(e){this._meterSharedState=e}return t.prototype.createGauge=function(e,r){var n=$o(e,Ye.GAUGE,r),o=this._meterSharedState.registerMetricStorage(n);return new xO(o,n)},t.prototype.createHistogram=function(e,r){var n=$o(e,Ye.HISTOGRAM,r),o=this._meterSharedState.registerMetricStorage(n);return new _O(o,n)},t.prototype.createCounter=function(e,r){var n=$o(e,Ye.COUNTER,r),o=this._meterSharedState.registerMetricStorage(n);return new wO(o,n)},t.prototype.createUpDownCounter=function(e,r){var n=$o(e,Ye.UP_DOWN_COUNTER,r),o=this._meterSharedState.registerMetricStorage(n);return new RO(o,n)},t.prototype.createObservableGauge=function(e,r){var n=$o(e,Ye.OBSERVABLE_GAUGE,r),o=this._meterSharedState.registerAsyncMetricStorage(n);return new PO(n,o,this._meterSharedState.observableRegistry)},t.prototype.createObservableCounter=function(e,r){var n=$o(e,Ye.OBSERVABLE_COUNTER,r),o=this._meterSharedState.registerAsyncMetricStorage(n);return new IO(n,o,this._meterSharedState.observableRegistry)},t.prototype.createObservableUpDownCounter=function(e,r){var n=$o(e,Ye.OBSERVABLE_UP_DOWN_COUNTER,r),o=this._meterSharedState.registerAsyncMetricStorage(n);return new MO(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 $f=function(){function t(e){this._instrumentDescriptor=e}return t.prototype.getInstrumentDescriptor=function(){return this._instrumentDescriptor},t.prototype.updateDescription=function(e){this._instrumentDescriptor=$o(this._instrumentDescriptor.name,this._instrumentDescriptor.type,{description:e,valueType:this._instrumentDescriptor.valueType,unit:this._instrumentDescriptor.unit,advice:this._instrumentDescriptor.advice})},t}();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)}}(),LO=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}}},$2=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 LO(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 LO(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){W2(e,t);function e(){return t.call(this,If)||this}return e}($2);var q2=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},qf=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=If(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=q2(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 MT=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.")},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},Kf=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===ic.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=K2(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=MT(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=MT(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=NO(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=MT(e.keys()),s=a.next();!s.done;s=a.next()){var c=NO(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 K2(t){return Array.from(t.entries())}var Y2=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)}}(),X2=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){Y2(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 qf(n,s._aggregationCardinalityLimit),s._temporalMetricStorage=new Kf(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=X2(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}($f);yt();function OT(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=ld[e]:this.minLogLevel=e}log(...e){this.logWithLevel(30,zo.reset,...e)}info(...e){this.logWithLevel(30,zo.white,...e)}debug(...e){this.logWithLevel(20,zo.dim,...e)}warn(...e){this.logWithLevel(40,zo.yellow,...e)}error(...e){this.logWithLevel(50,zo.red,...e)}success(...e){this.logWithLevel(1/0,zo.green,...e)}dimmed(...e){this.logWithLevel(30,zo.dim,...e)}underline(...e){this.logWithLevel(40,zo.underline,...e)}bold(...e){this.logWithLevel(40,zo.bold,...e)}grey(...e){this.logWithLevel(20,zo.grey,...e)}child(e){return new t(this.minLogLevel,{...this.logBindings,...e})}async flush(){}bindings(){return this.logBindings}},hE=class{debug(){}info(){}warn(){}error(){}success(){}dimmed(){}underline(){}bold(){}grey(){}child(){return this}async flush(){}bindings(){return{}}},STe=new hE,zW=typeof window>"u"&&typeof process<"u"&&fE.safeParse(process?.env?.MOMENTIC_DEV_LOG_LEVEL).success?fE.parse(process.env.MOMENTIC_DEV_LOG_LEVEL):30,v=new us(zW,{}),Ho={info:()=>{},error:()=>{},debug:()=>{},warn:()=>{},child:()=>Ho,flush:async()=>{},bindings:()=>({})},jm={},Vm=({logger:t,logKey:e,maxCount:r,intervalMs:n},o,i,...a)=>{let s=jm[e];s?clearTimeout(s.timer):(s={count:0,totalCount:0},jm[e]=s),s.totalCount++,s.count<r&&(s.count++,t.debug(o,i,...a)),s.timer=setTimeout(()=>{let c=jm[e];c?.totalCount!==c?.count&&t.debug({logKey:e,totalCount:c?.totalCount,count:c?.count},`Debug logs were rate-limited for ${e}`),delete jm[e]},n)};import{z as K}from"zod";var HW=K.array(Vl.extend({id:K.string(),name:K.string(),description:K.string().optional(),labels:K.string().array().optional()})),GW=K.array(Vl.extend({id:K.string(),name:K.string(),description:K.string().optional(),content:oE})),v_={name:K.string().min(1).max(255).describe(oa),description:K.string().optional(),settings:zl.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:pw.optional().default("ANDROID").describe("For LLM: Never assign this unless the user explicitly asks for iOS. Defaults to Android.")},{defaultEnv:wTe,...xTe}=v_;var _Te=K.object(v_),ITe=K.object({id:K.string(),fileName:K.string(),fullPath:K.string(),relativeFilePath:K.string().describe("relative to project root")});var PTe=K.object({steps:ls.array().optional(),settings:zl.optional(),labels:K.array(K.string()).optional()}),MTe=K.object({message:K.literal("ok")}),OTe=K.object({name:di.optional(),description:K.string().min(1).optional(),settings:zl.optional(),disabled:K.boolean().optional(),labels:K.array(K.string()).optional()}),LTe=K.object({message:K.string(),newRelativeTestPath:K.string().optional()}),NTe=K.object({tag:K.string(),channel:K.string(),filePath:K.string()}),DTe=K.object({name:di}),kTe=K.object({tests:HW,modules:GW,labels:K.string().array()}),UTe=K.object({name:K.string(),description:K.string(),enabled:K.boolean()}).partial(),FTe=K.object({name:K.string(),description:K.string(),enabled:K.boolean(),steps:ls.array(),testFilePath:K.string().describe("relative to the project root"),folderPath:K.string().optional().describe("user selected folder path")}),BTe=K.object({name:K.string().describe(oa),description:K.string().optional(),enabled:K.boolean().default(!0),parameters:td.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()}),zTe=K.object({packages:K.string().array()}),HTe=K.object({name:K.string()}),GTe=K.object({relativeFilePath:K.string()}),A_=K.object({stepId:K.string(),testId:K.string(),environment:K.string().optional(),parentStepIdChain:K.array(K.string()),value:Fl}),jW=A_.extend({platform:K.literal("ANDROID"),steps:ls.array()}),VW=A_.extend({platform:K.literal("IOS"),steps:rd.array()}),jTe=K.discriminatedUnion("platform",[jW,VW]),VTe=K.object({platform:K.nativeEnum(yn),completionType:K.string(),traceIds:K.string().array()}),WTe=K.object({completionType:K.string(),traceIds:K.string().array()});import{v4 as WW}from"uuid";var Wm=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=WW();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 C_=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:XS.nullish()}),rbe=C_.extend({steps:jt.lazy(()=>bt.array())}),R_=5*60*1e3,gE=rn.merge(C_.omit({id:!0,createdAt:!0,createdBy:!0,organizationId:!0,enabled:!0}));import{formatInTimeZone as ibe}from"date-fns-tz";import*as A from"zod";import{z as kt}from"zod";var SE=(e=>(e.TEST_REVIEW="TEST_REVIEW",e))(SE||{});var $W=kt.object({type:kt.literal("DESCRIPTION_UPDATE"),thoughts:kt.string()}),$m=kt.discriminatedUnion("type",[$W]),qW=kt.object({testId:kt.string(),name:kt.string(),orgId:kt.string(),runId:kt.string(),steps:Nt.array(),purpose:kt.nativeEnum(SE),details:$m.or($m.array()).optional()});var ube=qW.pick({name:!0,orgId:!0}),KW=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(SE),details:$m.or($m.array()).optional(),applied:kt.boolean().nullish(),appliedAt:kt.coerce.date().nullish()}),w_=KW.extend({steps:Nt.array()});var qm="x-momentic-cli-version",x_="x-momentic-client-mode",__="x-momentic-cli-type",I_="x-momentic-logger-tags",YW="x-momentic-main-branch-name",XW="x-momentic-branch-name",JW="x-momentic-commit-timestamp",QW="x-momentic-last-commit-on-main",ZW="x-momentic-last-commit-on-main-timestamp",e$="x-momentic-merged-branch-name",P_="x-momentic-session-id",Lbe=A.object({error:A.boolean(),reason:A.string(),message:A.string()}),Nbe=Gt.merge(gy),M_=$p,Dbe=Gt.merge(gy);var kbe=Gt.merge(Mw).extend({useConsensus:A.boolean().optional(),attemptNumber:A.number().optional()}),yE=cC,Ube=Gt.merge(Lw),O_=qR,Fbe=Gt.merge(Nw),L_=KR,Bbe=Gt.merge(Dw),N_=YR,zbe=Gt.merge(Ow),D_=$R,Hbe=Gt.merge(xw),k_=om,Gbe=Gt.merge(_w),U_=GR,jbe=Gt.merge(Iw);var Vbe=Gt.merge(Pw),Wbe=Gt.merge(Bw),$be=Gt.merge(zw),qbe=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()}),F_=A.object({queuedTests:A.unknown().array(),runIds:A.string().uuid().array(),runGroupId:A.string().optional()});var Kbe=A.string().array(),Ybe=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")})]),B_=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"))}),t$=A.object({test:A.string().describe("test YAML"),modules:A.record(A.string().describe("moduleId"),A.string().describe("module YAML"))}),Xbe=t$.array(),Jbe=A.object({testId:A.string(),schemaVersion:A.string()}).merge(Ka);function EE(t){let{gitMainBranch:e,gitBranchName:r,gitCommitTimestamp:n,lastCommitOnMainSha:o,lastCommitOnMainTimestamp:i}=t,a={};return e&&(a[YW]=encodeURIComponent(e)),r&&(a[XW]=encodeURIComponent(r)),n&&(a[JW]=n.toISOString()),o&&(a[QW]=encodeURIComponent(o)),i&&(a[ZW]=i.toISOString()),t.mergedGitBranchName&&(a[e$]=encodeURIComponent(t.mergedGitBranchName)),a}var Qbe=A.object({entries:A.array(HC)});var Zbe=A.object({testId:A.string(),environment:A.string().optional()});function z_(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 H_=z_(GC);function G_(t){return z_(Va(t))}var r$=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()}),n$=A.object({id:A.string(),assertion:A.string().optional(),result:A.string(),thoughts:A.string(),sessionType:A.string(),timeCreated:A.string().optional()}),eve=A.object({completionType:A.string(),traceIds:A.string().array()}),TE=A.union([r$,n$]).array(),j_=A.object({trigger:A.nativeEnum(nn),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()}),tve=A.object({id:A.string()}),V_=A.object({status:A.nativeEnum(nt),updatedAt:A.coerce.date().optional(),finishedAt:A.coerce.date().optional()}),W_=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(nn),schemaVersion:A.string().optional(),section:A.nativeEnum(Sm).optional(),resolvedInputs:A.record(A.string(),A.string()).optional(),quarantined:A.boolean().optional().default(!1),quarantinedReason:A.string().optional(),aiSettings:mi.optional()}),rve=A.object({id:A.string()}),o$=my.pick({id:!0,status:!0,testName:!0,testId:!0,test:!0,failureReason:!0,failureDetails:!0}),$_=o$.array(),q_=my.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(),nve=A.object({id:A.string()}),K_=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()}),ove=A.object({screenshot:A.string(),contentType:A.enum(["image/jpeg","image/png"]).optional()}),ive=A.object({id:A.string(),screenshot:A.string(),contentType:A.enum(["image/jpeg","image/png"])}),Y_=A.object({key:A.string()}),X_=A.object({orgId:A.string(),userId:A.string()}),J_=A.array(lw),ave=A.record(A.string(),A.union([A.string(),A.boolean()])),sve=A.object({paths:A.string().array(),env:A.string().optional(),urlOverride:A.string().optional(),customHeaders:A.record(A.string(),A.string()).optional()}),Q_=A.object({suiteRunIds:A.string().array(),runGroupIds:A.string().array()}),lve=A.object({suiteRunIds:A.string().array()}),cve=Cw.array(),uve=A.object({runGroupIds:A.string().array()}),i$=A.object({uploadUrl:A.string()}),dve=Gt.merge(kw),pve=Gt.merge(Fw),mve=Gt.merge(Uw),a$=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()}),s$=A.object({transactionId:A.string(),timestamp:A.string(),event:A.nativeEnum(Qu),properties:a$}),fve=s$.array(),Z_=w_.omit({steps:!0}).extend({steps:A.array(A.record(A.string(),A.unknown())).describe("unparsed ResolvedStep[]")}),hve=A.object({limit:A.number().max(10).optional(),afterTime:A.number().optional()}),eI=yw.array(),gve=A.object({applied:A.boolean().optional(),appliedAt:A.coerce.date().optional()}),tI=i$.extend({id:A.string()}),Sve=A.object({runGroupId:A.string().uuid().optional()}),rI=A.object({runGroupId:A.string().uuid()}),nI=A.object({quarantined:A.object({testId:A.string().uuid(),quarantinedAt:A.coerce.date(),quarantinedBy:A.string().optional(),quarantinedReason:A.string()}).array()}),yve=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()}),Eve=A.object({testName:A.string().optional(),reason:A.string().optional(),gitLocalUsername:A.string().optional(),gitLocalEmail:A.string().optional(),gitLocalName:A.string().optional()}),Tve=Gt.merge(dx),bve=Gt.merge(px),vve=Gt.merge(mx),Ave=A.object({apkToInstall:A.object({channel:A.string(),tag:A.string().optional()}).optional(),hostname:A.string().optional(),region:A.nativeEnum(Zu).optional(),osVersion:A.nativeEnum(ed).optional(),sessionId:A.string().optional()}),oI=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()}),Cve=A.object({appToInstall:A.object({channel:A.string(),tag:A.string().optional()}).optional(),hostname:A.string().optional(),region:A.nativeEnum(Zu).optional(),osVersion:A.nativeEnum(tE).optional(),sessionId:A.string().optional()}),iI=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()}),Rve=A.object({channel:A.string(),tag:A.string(),md5:A.string()}),aI=A.object({id:A.string(),uploadUrl:A.string().optional(),downloadUrl:A.string(),md5:A.string().optional()}),sI=A.object({assets:A.array(A.object({channel:A.string(),tag:A.string(),md5:A.string(),platform:A.nativeEnum(yn).default("ANDROID"),createdAt:A.number().describe("Unix timestamp in milliseconds")}))}),lI=A.object({downloadUrl:A.string()});import{z as Le}from"zod";var uI=7,l$=3,cI=Le.object({quarantinedAt:Le.date(),quarantinedReason:Le.string(),quarantinedBy:Le.string().optional(),quarantinedByGitEmail:Le.string().optional(),quarantinedByGitName:Le.string().optional(),quarantinedByGitUsername:Le.string().optional()}),_ve=Le.object({localTestId:Le.string()}).merge(cI).or(Le.object({cloudTestId:Le.string()}).merge(cI)),dI=(r=>(r.QUARANTINE="QUARANTINE",r.UNQUARANTINE="UNQUARANTINE",r))(dI||{});var bE=Le.object({name:Le.string(),description:Le.string().nullish(),effect:Le.nativeEnum(dI),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()}),c$=Le.object({type:Le.literal("LAST_N_RUNS"),lastN:Le.number().min(l$)}),u$=Le.object({type:Le.literal("LAST_N_HOURS"),lastN:Le.number().min(1).max(uI*24)}),d$=Le.object({type:Le.literal("LAST_N_DAYS"),lastN:Le.number().min(1).max(uI)}),vE=Le.discriminatedUnion("type",[c$,u$,d$]),p$=Le.object({flakeRateThreshold:Le.number().min(1).max(100),evaluationWindow:vE}),m$=bE.extend({type:Le.literal("FLAKE_RATE"),config:p$}),f$=Le.object({passRateThreshold:Le.number().min(1).max(100),evaluationWindow:vE}),h$=bE.extend({type:Le.literal("PASS_RATE"),config:f$}),g$=Le.object({failureCountThreshold:Le.number().min(0),evaluationWindow:vE}),S$=bE.extend({type:Le.literal("FAILURE_COUNT"),config:g$}),Ive=Le.discriminatedUnion("type",[m$,h$,S$]);import{z as Vt}from"zod";var Ove=Vt.object({repositoriesIndexed:Vt.boolean(),indexingInProgress:Vt.boolean(),indexesOutdated:Vt.boolean()}),pI=(a=>(a.Queued="queued",a.InProgress="in_progress",a.Completed="completed",a.Waiting="waiting",a.Requested="requested",a.Pending="pending",a))(pI||{}),mI=(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))(mI||{}),Lve=Vt.object({name:Vt.string(),status:Vt.nativeEnum(pI),conclusion:Vt.nativeEnum(mI).nullable()}),cd=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()})}),AE=Vt.object({mergedBranch:Vt.string().optional()});import{z as _t}from"zod";var fI=_t.object({orgId:_t.string(),cacheKeys:_t.string().array()}),kve=_t.object({keyParams:fI,clientMetadata:_t.string(),lockAcquisitionTimeoutMs:_t.number().optional()}),hI=_t.object({acquired:_t.boolean(),acquiredByMetadata:_t.string(),keyPrefix:_t.string()}),Uve=_t.object({keyPrefix:_t.string(),result:_t.string(),ttlMs:_t.number()}),Fve=_t.union([_t.object({keyPrefix:_t.string()}),fI]),y$=_t.object({remainingTtlMs:_t.number(),value:_t.string().nullish()}),Bve=_t.object({results:_t.record(_t.string(),y$),activeLocks:_t.string().array()}),gI=0,SI=5*60*1e3;var jve=30*24*60*60*1e3,Vve=7*24*60*60*1e3;import{z as yI}from"zod";var qve=yI.object({quarantineNotifications:yI.string().nullish()});function Wl(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 E$=hr.object({version:hr.string(),json:hr.record(hr.unknown()),hash:hr.string()}),EI=hr.record(hr.unknown()),Qve=hr.object({newSvgs:hr.array(E$),metadata:EI.optional()}),T$=hr.object({version:hr.string(),json:hr.record(hr.unknown()).nullish(),hash:hr.string(),description:hr.string().nullish(),metadata:EI.nullish()}),TI=hr.record(hr.string().describe("icon hash"),T$);import{validator as b$}from"@exodus/schemasafe";function bI(t){let e;try{e=JSON.parse(t)}catch(r){return`The schema is not valid JSON. ${r}`}try{b$(e)}catch(r){return`The schema is not a valid JSON schema. ${r}`}}var vI=t=>{t.extraHeaders&&(t.extraHeaders=Object.fromEntries(Object.entries(t.extraHeaders).filter(([e,r])=>e.trim()&&r.trim())))};import{z as hAe}from"zod";var Km=class{async resolveStepCacheEntries(){}async saveStepCacheEntries(){}};function v$(t){return t.map(e=>({...e,environment:void 0}))}function CE(t,e){return e?t:v$(t)}var En="get_browser_state",Ym="get_environment_variables",Xm="reset_session",Go="run_step",Wn="preview_preflight",AI="preview_ensure",sr="preview_step",Jm="test_get",lr="test_splice_steps",Qm="module_create",CI="momentic_module_create",$l="momentic_module_get",Zm="momentic_module_list",ia="momentic_module_recommend",RI="momentic_attributes_list",wI="momentic_test_create",xI="momentic_test_splice_steps",_I="momentic_run_step",II="momentic_session_start",PI="momentic_session_terminate",MI="momentic_get_session_state",OI="momentic_get_environment_variables",gi="momentic_get_initial_data",LI="momentic_preview_step";var wE="browser-crash-dump.zip",RE=class{loggerBindings;attachBeforeScreenshot(){}attachAfterScreenshot(){}attachBeforeHtmlSnapshot(){}attachAfterHtmlSnapshot(){}recordTargetAutoHeal(){}recordStepDuration(){}storeTraceAsset(){}async finish(){}async startSubSteps(){return new ud}},ud=class{async getScreenshot(){}async getHtmlSnapshot(){}async startStep(){return new RE}};import{z as xE}from"zod";var _Ae=xE.object({parentStepIdChain:xE.array(xE.string()),result:Eo});import{z as oe}from"zod";var gr="assets",A$=oe.object({step:Nt,status:oe.nativeEnum(at),startedAt:oe.coerce.date(),finishedAt:oe.coerce.date().optional(),healMetadata:oe.object({healType:oe.nativeEnum(vu).or(oe.literal("AI")),healedAt:oe.coerce.date()}).optional(),beforeSnapshotId:oe.string().uuid().optional(),afterSnapshotId:oe.string().uuid().optional(),message:oe.string().optional()}),C$=A$.extend({finishedAt:oe.coerce.date().optional().transform(t=>t??new Date)}),FAe=C$.extend({step:oe.unknown()}),_E=oe.object({avdId:oe.string().optional(),channel:oe.string().optional(),tag:oe.string().optional()}),NI="1.0.0",IE=K_.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:_E.optional(),activeVideos:oe.array(oe.object({videoName:oe.string(),timestamp:oe.coerce.date()})).optional()}),DI=IE.extend({assetDetails:_E.optional(),finishedAt:oe.coerce.date().optional().transform(t=>t??new Date)}),BAe=IE.merge(Cu),zAe=DI.merge(Cu),kI=oe.object({results:oe.array(Eo),beforeResults:oe.array(Eo).optional(),afterResults:oe.array(Eo).optional()}),HAe=IE.merge(kI),GAe=DI.merge(kI),UI=q_.merge(W_).extend({executionType:oe.nativeEnum(Al).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:mi.optional(),avgCpuUsage:oe.number().optional(),avgMemoryUsage:oe.number().optional()}),R$=UI.merge(_E),FI=UI.extend({finishedAt:oe.coerce.date().optional().transform(t=>t??new Date)}),jAe=R$.extend({finishedAt:oe.coerce.date().optional().transform(t=>t??new Date)}),w$=j_.merge(V_).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()}),ql=w$.extend({updatedAt:oe.coerce.date().optional().transform(t=>t??new Date),finishedAt:oe.coerce.date().optional().transform(t=>t??new Date)});var x$=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"]),_$=new Set(["MODULE","RESOLVED_MODULE"]),JAe=new Set(["MOBILE_MODULE_STEP","RESOLVED_MOBILE_MODULE"]);function ef(t){return t.type!=="PRESET_ACTION"?t.type:t.command.type}function tf(t){return _$.has(t.type)?!1:t.type!=="PRESET_ACTION"?!0:!x$.has(t.command.type)}var MRe=5*1024,I$="...[truncated]",ORe=Buffer.byteLength(I$,"utf8");import M$ from"fetch-retry";import O$ from"os";import zI,{multistream as L$}from"pino";import N$ from"pino-pretty";import D$ from"pino-std-serializers";var dd;function BI(t){dd=t}var P$=new Set(["InternalWebAgentError","InternalPlatformError","UnknownError"]);function PE(t){return t instanceof Error&&t.name==="AbortError"?!1:t instanceof L?P$.has(t.reason):!0}var Kl=new Map,k$=!0,HI="Log throttle exceeded",U$=100,F$=5e3,B$=M$(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}}),ME=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??O$.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=k$?zI(s):zI(s,L$([{stream:N$({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 B$(this.site,{method:"POST",headers:{"Content-Type":"application/json","signoz-access-token":"CumAaTMUcwjt05OddAmefKgshbhfRmWxzxih"},body:cs(e),signal:AbortSignal.timeout(5e3)});if(!r.ok)throw new Error(`Got error status (${r.statusText}) from SigNoz`)}catch{}}shouldAllowLog(e){if(e===HI)return!0;let r=Date.now();return r-this.lastWindowStart>F$&&(this.logsInCurrentWindow=0,this.droppedLogsInWindow&&this.log("error",void 0,HI),this.droppedLogsInWindow=!1,this.lastWindowStart=r),this.logsInCurrentWindow<U$?(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(ld[e]<this.minLevelValue||!this.shouldAllowLog(n))return;e==="error"&&this.captureExceptions&&dd&&(r instanceof Error&&PE(r)?dd(r):typeof r=="object"&&r&&"err"in r&&r.err instanceof Error&&PE(r.err)&&dd(r.err)),typeof r=="string"&&!n&&(r={message:r}),typeof r=="object"&&r&&"err"in r&&r.err instanceof Error&&(r.err=D$.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:T_({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,Kl.set("app",this),Kl.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=b_[e]):(this.minLevelValue=ld[e],this.consoleLogger.level=e)}enableConsoleLogs(){this.disableConsoleLogs=!1}},Yl=({app:t,hostname:e,disableConsoleLogs:r,captureExceptions:n})=>(Kl.has(t)||Kl.set(t,new ME({bindings:{app:t},hostname:e,disableConsoleLogs:r,captureExceptions:n})),Kl.get(t));async function rf(){await Promise.all([...Kl.values()].map(t=>t.flush()))}import{PostHog as z$}from"posthog-node";var aa=class extends Error{constructor(e){super(e),this.name="TimeoutError"}};var jI=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(jI(p));l=()=>c(jI(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 aa(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 VI(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 nf=class t extends ad{constructor(r,n,o,i){super(o,i);this.client=r;this.orgId=n}static async init(r){let n=new z$("phc_WRWd8LYIv6rolgDsyCdrPpxtZhsu6qXAkEwPicl44bI",{host:"https://us.i.posthog.com"}),{flags:o,payloads:i}=await VI(n,r);return new t(n,r,o,i)}async refresh(){let{flags:r,payloads:n}=await VI(this.client,this.orgId);this.flags=r,this.payloads=n}};import{randomUUID as H$}from"node:crypto";import{PostHog as G$}from"posthog-node";var of=class t{identity;bindings;client;options;constructor(e,r={},n){this.bindings=e,this.options=r,this.identity=n,this.client=new G$("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(!hx(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??H$(),event:n,timestamp:r?.timestamp,properties:{...this.bindings,...o,organizationId:this.identity?.orgId}}),this}};import{execSync as j$}from"child_process";import{readFileSync as qI}from"fs";import Si from"os";import V$ from"v8";var ds=!!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 W$=2e3,ps=t=>Number.parseInt(t,10),NE=t=>qI(t,"utf8").trim(),Xl=t=>ps(NE(t)),WI,af,OE=0,lf=Si.platform(),$$=Si.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 LE(t=Date.now()){let e=Si.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 KI(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 q$(){let t=LE();return()=>{let e=LE(),r=KI(t,e);return t=e,r}}function $I(){try{let e=qI("/sys/fs/cgroup/cpu.stat","utf8").match(/^usage_usec\s+(\d+)/m);if(e?.[1])return ps(e[1])}catch{}try{let t=Xl("/sys/fs/cgroup/cpuacct/cpuacct.usage");if(!isNaN(t))return t/1e3}catch{}return null}function K$(){try{let e=NE("/sys/fs/cgroup/cpu.max").split(" "),r=e[0],n=e[1];return!r||!n||r==="max"?null:ps(r)/ps(n)}catch{}try{let t=Xl("/sys/fs/cgroup/cpu/cpu.cfs_quota_us"),e=Xl("/sys/fs/cgroup/cpu/cpu.cfs_period_us");return t===-1||isNaN(e)?null:t/e}catch{return null}}function Y$(){if(lf!=="linux")return null;let t=$I();if(t===null)return null;let e=K$()??Si.cpus().length,r=t,n=Date.now();return()=>{let o=$I();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 X$(){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(Si.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 YI({intervalMs:t=W$,maxSamples:e=1e4,keepSamples:r=!0,onSample:n}={}){let o=[],i=Y$()??q$(),a=X$(),s=()=>{let u=Date.now(),d=QI(),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 sf=t=>{try{let e={},r=!1,n=QI(),o=Q$(),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=V$.getHeapStatistics(),c=s.used_heap_size,l=s.heap_size_limit;c/l>.9&&(r=!0),r?(OE++,t.warn({memory:n,cpu:o,heapStats:s,...e},"Critical resource usage metrics detected"),ds&&OE>=2&&v.warn(`Low machine resources detected (memory: ${i} free, cpu: ${a} free)`)):(OE=0,t.debug({memory:n,cpu:o},"Got machine resource usage metrics"))}catch{}},XI=t=>{sf(t),setTimeout(()=>sf(t),5e3)};function JI(t){if(!Vn)return sf(t),{interval:setInterval(()=>sf(t),2e4),cpuMetadata:$$,platform:lf}}function J$(){if(lf!=="linux")return null;try{let t=NE("/sys/fs/cgroup/memory.max"),e=Xl("/sys/fs/cgroup/memory.current");if(t==="max"||isNaN(e))return null;let r=ps(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=Xl("/sys/fs/cgroup/memory/memory.limit_in_bytes"),e=Xl("/sys/fs/cgroup/memory/memory.usage_in_bytes");if(isNaN(t)||isNaN(e))return null;let r=Si.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 QI(){let t=J$();if(t)return t;let e=Si.totalmem(),r=lf==="darwin"?Z$():(()=>{let o=Si.freemem();return{availableMemory:o,rawFreeMemory:o,cachedMemory:0}})(),n=r.availableMemory/e;return{totalMemory:e,freeMemory:r.availableMemory,freePercentage:n}}function Q$(){let t=LE();if(!af)return af=t,null;let e=KI(af,t);return af=t,e?(WI=e,WI):null}function Z$(){try{let t=j$("/usr/bin/vm_stat",{encoding:"utf8",stdio:["pipe","pipe","ignore"]}),r=t.match(/page size of (\d+) bytes/)?.[1],n=r?ps(r):4096,o=u=>{let p=t.match(new RegExp(`${u}:\\s+(\\d+)\\.`,"i"))?.[1];return p?ps(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=Si.freemem();return{availableMemory:t,rawFreeMemory:t,cachedMemory:0}}}var cf=class{increment(e,r,n){}gauge(e,r){}distribution(e,r,n){}async flush(){}async recordDuration({fn:e}){return await e()}};function eq(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 uf(t,e){let r=eq(t);return!e||Object.keys(e).length===0?r:{...e,...r}}var RP="=",ff=";",$E=",";var wP=8192;var ec={};kH(ec,{getKeyPairs:()=>Lq,parseKeyPairsIntoRecord:()=>Nq,parsePairKeyValue:()=>xP,serializeKeyPairs:()=>Oq});yt();var Mq=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 Oq(t){return t.reduce(function(e,r){var n=""+e+(e!==""?$E:"")+r;return n.length>wP?e:n},"")}function Lq(t){return t.getAllEntries().map(function(e){var r=Mq(e,2),n=r[0],o=r[1],i=encodeURIComponent(n)+"="+encodeURIComponent(o.value);return o.metadata!==void 0&&(i+=ff+o.metadata.toString()),i})}function xP(t){var e=t.split(ff);if(!(e.length<=0)){var r=e.shift();if(r){var n=r.indexOf(RP);if(!(n<=0)){var o=decodeURIComponent(r.substring(0,n).trim()),i=decodeURIComponent(r.substring(n+1).trim()),a;return e.length>0&&(a=kE(e.join(ff))),{key:o,value:i,metadata:a}}}}}function Nq(t){return typeof t!="string"||t.length===0?{}:t.split($E).map(function(e){return xP(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 hf;(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"})(hf||(hf={}));var Dq=",",kq=["OTEL_SDK_DISABLED"];function Uq(t){return kq.indexOf(t)>-1}var Fq=["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 Bq(t){return Fq.indexOf(t)>-1}var zq=["OTEL_NO_PATCH_MODULES","OTEL_PROPAGATORS"];function Hq(t){return zq.indexOf(t)>-1}var qE=1/0,KE=128,Gq=128,jq=128,YE={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:qE,OTEL_ATTRIBUTE_COUNT_LIMIT:KE,OTEL_SPAN_ATTRIBUTE_VALUE_LENGTH_LIMIT:qE,OTEL_SPAN_ATTRIBUTE_COUNT_LIMIT:KE,OTEL_LOGRECORD_ATTRIBUTE_VALUE_LENGTH_LIMIT:qE,OTEL_LOGRECORD_ATTRIBUTE_COUNT_LIMIT:KE,OTEL_SPAN_EVENT_COUNT_LIMIT:128,OTEL_SPAN_LINK_COUNT_LIMIT:128,OTEL_SPAN_ATTRIBUTE_PER_EVENT_COUNT_LIMIT:Gq,OTEL_SPAN_ATTRIBUTE_PER_LINK_COUNT_LIMIT:jq,OTEL_TRACES_EXPORTER:"",OTEL_TRACES_SAMPLER:hf.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 Vq(t,e,r){if(!(typeof r[t]>"u")){var n=String(r[t]);e[t]=n.toLowerCase()==="true"}}function Wq(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 $q(t,e,r,n){n===void 0&&(n=Dq);var o=r[t];typeof o=="string"&&(e[t]=o.split(n).map(function(i){return i.trim()}))}var qq={ALL:At.ALL,VERBOSE:At.VERBOSE,DEBUG:At.DEBUG,INFO:At.INFO,WARN:At.WARN,ERROR:At.ERROR,NONE:At.NONE};function Kq(t,e,r){var n=r[t];if(typeof n=="string"){var o=qq[n.toUpperCase()];o!=null&&(e[t]=o)}}function _P(t){var e={};for(var r in YE){var n=r;switch(n){case"OTEL_LOG_LEVEL":Kq(n,e,t);break;default:if(Uq(n))Vq(n,e,t);else if(Bq(n))Wq(n,e,t);else if(Hq(n))$q(n,e,t);else{var o=t[n];typeof o<"u"&&o!==null&&(e[n]=String(o))}}}return e}function Sr(){var t=_P(process.env);return Object.assign({},YE,t)}function IP(t){return t>=48&&t<=57?t-48:t>=97&&t<=102?t-87:t-55}function gf(t){for(var e=new Uint8Array(t.length/2),r=0,n=0;n<t.length;n+=2){var o=IP(t.charCodeAt(n)),i=IP(t.charCodeAt(n+1));e[r++]=o<<4|i}return e}var PP="1.25.1";var Yq="deployment.environment";var Xq="process.runtime.name";var Jq="service.name";var Qq="service.instance.id";var Zq="telemetry.sdk.name",eK="telemetry.sdk.language",tK="telemetry.sdk.version";var MP=Yq;var OP=Xq;var Sf=Jq;var LP=Qq;var yd=Zq,Ed=eK,Td=tK;var rK="nodejs";var NP=rK;var tc,yf=(tc={},tc[yd]="opentelemetry",tc[OP]="node",tc[Ed]=NP,tc[Td]=PP,tc);var nK=9,oK=6,iK=Math.pow(10,oK),aK=Math.pow(10,nK);function DP(t){var e=t/1e3,r=Math.trunc(e),n=Math.round(t%1e3*iK);return[r,n]}function kP(t){return t[0]*aK+t[1]}function bd(t){return t[0]*1e6+t[1]/1e3}var fs;(function(t){t[t.SUCCESS=0]="SUCCESS",t[t.FAILED=1]="FAILED"})(fs||(fs={}));var UP=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 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},lK=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))},FP=function(){function t(e,r){this._callback=e,this._that=r,this._isCalled=!1,this._deferred=new UP}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,lK([this._that],sK(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 $n;(function(t){t[t.DELTA=0]="DELTA",t[t.CUMULATIVE=1]="CUMULATIVE"})($n||($n={}));var Nr;(function(t){t[t.HISTOGRAM=0]="HISTOGRAM",t[t.EXPONENTIAL_HISTOGRAM=1]="EXPONENTIAL_HISTOGRAM",t[t.GAUGE=2]="GAUGE",t[t.SUM=3]="SUM"})(Nr||(Nr={}));var cK=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 k_e=function(t){cK(e,t);function e(r){var n=t.call(this,r)||this;return Object.setPrototypeOf(n,e.prototype),n}return e}(Error);function BP(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 qn;(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"})(qn||(qn={}));var zP=function(){function t(){this.kind=qn.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 Be;(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"})(Be||(Be={}));var uK=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 dK(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 XE=function(){function t(e,r,n,o){n===void 0&&(n=!0),o===void 0&&(o=dK(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=BP(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 JE=function(){function t(e,r){this._boundaries=e,this._recordMinMax=r,this.kind=qn.HISTOGRAM}return t.prototype.createAccumulation=function(e){return new XE(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 XE(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 XE(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:Nr.HISTOGRAM,dataPoints:n.map(function(i){var a=uK(i,2),s=a[0],c=a[1],l=c.toPointValue(),u=e.type===Be.GAUGE||e.type===Be.UP_DOWN_COUNTER||e.type===Be.OBSERVABLE_GAUGE||e.type===Be.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 QE=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},ZE=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))},eT=function(){function t(e,r,n,o){e===void 0&&(e=new pK),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 pK=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,ZE([n,this._counts.length-r],QE(this._counts.slice(r)),!1)),o.splice.apply(o,ZE([0,r],QE(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(ZE([],QE(this._counts),!1))},t}();var HP=52,mK=2146435072,fK=1048575,tT=1023,Ef=-tT+1,Tf=tT,vd=Math.pow(2,-1022);function bf(t){var e=new DataView(new ArrayBuffer(8));e.setFloat64(0,t);var r=e.getUint32(0),n=(r&mK)>>20;return n-tT}function vf(t){var e=new DataView(new ArrayBuffer(8));e.setFloat64(0,t);var r=e.getUint32(0),n=e.getUint32(4),o=(r&fK)*Math.pow(2,32);return o+n}function Ad(t,e){return t===0||t===Number.POSITIVE_INFINITY||t===Number.NEGATIVE_INFINITY||Number.isNaN(t)?t:t*Math.pow(2,e)}function jP(t){return t--,t|=t>>1,t|=t>>2,t|=t>>4,t|=t>>8,t|=t>>16,t++,t}var hK=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){hK(e,t);function e(){return t!==null&&t.apply(this,arguments)||this}return e}(Error);var WP=function(){function t(e){this._shift=-e}return t.prototype.mapToIndex=function(e){if(e<vd)return this._minNormalLowerBoundaryIndex();var r=bf(e),n=this._rightShift(vf(e)-1,HP);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 Ad(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=Ef>>this._shift;return this._shift<2&&e--,e},t.prototype._maxNormalLowerBoundaryIndex=function(){return Tf>>this._shift},t.prototype._rightShift=function(e,r){return Math.floor(e*Math.pow(2,-r))},t}();var $P=function(){function t(e){this._scale=e,this._scaleFactor=Ad(Math.LOG2E,e),this._inverseFactor=Ad(Math.LN2,-e)}return t.prototype.mapToIndex=function(e){if(e<=vd)return this._minNormalLowerBoundaryIndex()-1;if(vf(e)===0){var r=bf(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 vd;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 Ef<<this._scale},t.prototype._maxNormalLowerBoundaryIndex=function(){return(Tf+1<<this._scale)-1},t}();var qP=-10,KP=20,gK=Array.from({length:31},function(t,e){return e>10?new $P(e-10):new WP(e-10)});function rT(t){if(t>KP||t<qP)throw new sa("expected scale >= "+qP+" && <= "+KP+", got: "+t);return gK[t+10]}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},Af=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}(),yK=20,EK=160,nT=2,TK=function(){function t(e,r,n,o,i,a,s,c,l,u,d){e===void 0&&(e=e),r===void 0&&(r=EK),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 eT),u===void 0&&(u=new eT),d===void 0&&(d=rT(yK)),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<nT&&(ie.warn("Exponential Histogram Max Size set to "+this._maxSize+", changing to the minimum size of: "+nT),this._maxSize=nT)}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=jP(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=rT(r)}},t.prototype._minScale=function(e){var r=Math.min(this.scale,e.scale),n=Af.combine(this._highLowAtScale(this.positive,this.scale,r),this._highLowAtScale(e.positive,e.scale,r)),o=Af.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 Af(0,-1);var o=r-n;return new Af(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 YP=function(){function t(e,r){this._maxSize=e,this._recordMinMax=r,this.kind=qn.EXPONENTIAL_HISTOGRAM}return t.prototype.createAccumulation=function(e){return new TK(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:Nr.EXPONENTIAL_HISTOGRAM,dataPoints:n.map(function(i){var a=SK(i,2),s=a[0],c=a[1],l=c.toPointValue(),u=e.type===Be.GAUGE||e.type===Be.UP_DOWN_COUNTER||e.type===Be.OBSERVABLE_GAUGE||e.type===Be.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 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},oT=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=DP(Date.now())},t.prototype.setStartTime=function(e){this.startTime=e},t.prototype.toPointValue=function(){return this._current},t}();var XP=function(){function t(){this.kind=qn.LAST_VALUE}return t.prototype.createAccumulation=function(e){return new oT(e)},t.prototype.merge=function(e,r){var n=bd(r.sampleTime)>=bd(e.sampleTime)?r:e;return new oT(e.startTime,n.toPointValue(),n.sampleTime)},t.prototype.diff=function(e,r){var n=bd(r.sampleTime)>=bd(e.sampleTime)?r:e;return new oT(r.startTime,n.toPointValue(),n.sampleTime)},t.prototype.toMetricData=function(e,r,n,o){return{descriptor:e,aggregationTemporality:r,dataPointType:Nr.GAUGE,dataPoints:n.map(function(i){var a=bK(i,2),s=a[0],c=a[1];return{attributes:s,startTime:c.startTime,endTime:o,value:c.toPointValue()}})}},t}();var vK=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},Cd=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 iT=function(){function t(e){this.monotonic=e,this.kind=qn.SUM}return t.prototype.createAccumulation=function(e){return new Cd(e,this.monotonic)},t.prototype.merge=function(e,r){var n=e.toPointValue(),o=r.toPointValue();return r.reset?new Cd(r.startTime,this.monotonic,o,r.reset):new Cd(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 Cd(r.startTime,this.monotonic,o,!0):new Cd(r.startTime,this.monotonic,o-n)},t.prototype.toMetricData=function(e,r,n,o){return{descriptor:e,aggregationTemporality:r,dataPointType:Nr.SUM,dataPoints:n.map(function(i){var a=vK(i,2),s=a[0],c=a[1];return{attributes:s,startTime:c.startTime,endTime:o,value:c.toPointValue()}}),isMonotonic:this.monotonic}},t}();var hs=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)}}(),Vo=function(){function t(){}return t.Drop=function(){return oM},t.Sum=function(){return iM},t.LastValue=function(){return aM},t.Histogram=function(){return sM},t.ExponentialHistogram=function(){return AK},t.Default=function(){return CK},t}();var JP=function(t){hs(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 zP,e}(Vo);var QP=function(t){hs(e,t);function e(){return t!==null&&t.apply(this,arguments)||this}return e.prototype.createAggregator=function(r){switch(r.type){case Be.COUNTER:case Be.OBSERVABLE_COUNTER:case Be.HISTOGRAM:return e.MONOTONIC_INSTANCE;default:return e.NON_MONOTONIC_INSTANCE}},e.MONOTONIC_INSTANCE=new iT(!0),e.NON_MONOTONIC_INSTANCE=new iT(!1),e}(Vo);var ZP=function(t){hs(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 XP,e}(Vo);var eM=function(t){hs(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 JE([0,5,10,25,50,75,100,250,500,750,1e3,2500,5e3,7500,1e4],!0),e}(Vo);var tM=function(t){hs(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 JE(this._boundaries,this._recordMinMax)},e}(Vo);var rM=function(t){hs(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 YP(this._maxSize,this._recordMinMax)},e}(Vo);var nM=function(t){hs(e,t);function e(){return t!==null&&t.apply(this,arguments)||this}return e.prototype._resolve=function(r){switch(r.type){case Be.COUNTER:case Be.UP_DOWN_COUNTER:case Be.OBSERVABLE_COUNTER:case Be.OBSERVABLE_UP_DOWN_COUNTER:return iM;case Be.GAUGE:case Be.OBSERVABLE_GAUGE:return aM;case Be.HISTOGRAM:return r.advice.explicitBucketBoundaries?new tM(r.advice.explicitBucketBoundaries):sM}return ie.warn("Unable to recognize instrument type: "+r.type),oM},e.prototype.createAggregator=function(r){return this._resolve(r).createAggregator(r)},e}(Vo);var oM=new JP,iM=new QP,aM=new ZP,sM=new eM,AK=new rM,CK=new nM;yt();function Cf(){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)},RK=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())})},wK=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},aT=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[Sf]=Cf(),e[Ed]=yf[Ed],e[yd]=yf[yd],e[Td]=yf[Td],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 RK(this,void 0,void 0,function(){return wK(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=xK(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 gs;(function(t){t[t.DELTA=0]="DELTA",t[t.CUMULATIVE=1]="CUMULATIVE",t[t.LOWMEMORY=2]="LOWMEMORY"})(gs||(gs={}));yt();var _K=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())})},IK=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}}},sT=function(){return $n.CUMULATIVE},lM=function(t){switch(t){case Be.COUNTER:case Be.OBSERVABLE_COUNTER:case Be.GAUGE:case Be.HISTOGRAM:case Be.OBSERVABLE_GAUGE:return $n.DELTA;case Be.UP_DOWN_COUNTER:case Be.OBSERVABLE_UP_DOWN_COUNTER:return $n.CUMULATIVE}},cM=function(t){switch(t){case Be.COUNTER:case Be.HISTOGRAM:return $n.DELTA;case Be.GAUGE:case Be.UP_DOWN_COUNTER:case Be.OBSERVABLE_UP_DOWN_COUNTER:case Be.OBSERVABLE_COUNTER:case Be.OBSERVABLE_GAUGE:return $n.CUMULATIVE}};function PK(){var t=Sr(),e=t.OTEL_EXPORTER_OTLP_METRICS_TEMPORALITY_PREFERENCE.trim().toLowerCase();return e==="cumulative"?sT:e==="delta"?lM:e==="lowmemory"?cM:(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."),sT)}function MK(t){return t!=null?t===gs.DELTA?lM:t===gs.LOWMEMORY?cM:sT:PK()}function OK(t){return t?.aggregationPreference?t.aggregationPreference:function(e){return Vo.Default()}}var uM=function(){function t(e,r){this._otlpExporter=e,this._aggregationSelector=OK(r),this._aggregationTemporalitySelector=MK(r?.temporalityPreference)}return t.prototype.export=function(e,r){this._otlpExporter.export([e],r)},t.prototype.shutdown=function(){return _K(this,void 0,void 0,function(){return IK(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 LK=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},dM=1e4,pM=5,mM=1e3,fM=5e3,hM=1.5;function Rd(t){t===void 0&&(t={});var e={};return Object.entries(t).forEach(function(r){var n=LK(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 lT(t,e){return t.endsWith("/")||(t=t+"/"),t+e}function cT(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 uT(t){return typeof t=="number"?t<=0?dT(t,dM):t:NK()}function NK(){var t,e=Number((t=Sr().OTEL_EXPORTER_OTLP_TRACES_TIMEOUT)!==null&&t!==void 0?t:Sr().OTEL_EXPORTER_OTLP_TIMEOUT);return e<=0?dT(e,dM):e}function dT(t,e){return ie.warn("Timeout must be greater than 0",t),e}function gM(t){var e=[429,502,503,504];return e.includes(t)}function SM(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 yM=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 FP(this._shutdown,this),this._concurrencyLimit=typeof e.concurrencyLimit=="number"?e.concurrencyLimit:30,this.timeoutMillis=uT(e.timeoutMillis),this.onInit(e)}return t.prototype.export=function(e,r){if(this._shutdownOnce.isCalled){r({code:fs.FAILED,error:new Error("Exporter has been shutdown")});return}if(this._sendingPromises.length>=this._concurrencyLimit){r({code:fs.FAILED,error:new Error("Concurrent export limit reached")});return}this._export(e).then(function(){r({code:fs.SUCCESS})}).catch(function(n){r({code:fs.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 pT from"url";import*as wf from"http";import*as xf from"https";import*as EM from"zlib";import{Readable as kK}from"stream";var ca;(function(t){t.NONE="none",t.GZIP="gzip"})(ca||(ca={}));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)}}(),rc=function(t){DK(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 Rf=function(){return Rf=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},Rf.apply(this,arguments)};function mT(t,e,r,n,o){var i=t.timeoutMillis,a=new pT.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 rc("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:Rf({"Content-Type":r},t.headers),agent:t.agent},m=a.protocol==="http:"?wf.request:xf.request,f=function(h,S){switch(h===void 0&&(h=pM),S===void 0&&(S=mM),l=m(p,function(E){var y="";E.on("data",function(b){return y+=b}),E.on("aborted",function(){if(u){var b=new rc("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&&gM(E.statusCode)&&h>0){var b=void 0;S=hM*S,E.headers["retry-after"]?b=SM(E.headers["retry-after"]):b=Math.round(Math.random()*(fM-S)+S),c=setTimeout(function(){f(h-1,S)},b)}else{var C=new rc(E.statusMessage,E.statusCode,y);o(C),clearTimeout(d),clearTimeout(c)}})}),l.on("error",function(E){if(u){var y=new rc("Request Timeout",E.code);o(y)}else o(E);clearTimeout(d),clearTimeout(c)}),l.on("abort",function(){if(u){var E=new rc("Request Timeout");o(E)}clearTimeout(d),clearTimeout(c)}),t.compression){case ca.GZIP:{l.setHeader("Content-Encoding","gzip");var g=UK(e);g.on("error",o).pipe(EM.createGzip()).on("error",o).pipe(l);break}default:l.end(Buffer.from(e));break}};f()}function UK(t){var e=new kK;return e.push(t),e.push(null),e}function fT(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 pT.URL(t.url),r=e.protocol==="http:"?wf.Agent:xf.Agent;return new r(Rf({keepAlive:!0},t.httpAgentOptions))}catch(n){ie.error("collector exporter failed to create http agent. err: "+n.message);return}}function hT(t){if(t)return t;var e=Sr().OTEL_EXPORTER_OTLP_TRACES_COMPRESSION||Sr().OTEL_EXPORTER_OTLP_COMPRESSION;return e===ca.GZIP?ca.GZIP:ca.NONE}yt();var FK=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)}}(),_f=function(t){FK(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,Rd(r.headers),ec.parseKeyPairsIntoRecord(Sr().OTEL_EXPORTER_OTLP_HEADERS)),i.agent=fT(r),i.compression=hT(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;mT(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}(yM);function bM(t){var e=BigInt(1e9);return BigInt(t[0])*e+BigInt(t[1])}function BK(t){var e=Number(BigInt.asUintN(32,t)),r=Number(BigInt.asUintN(32,t>>BigInt(32)));return{low:e,high:r}}function vM(t){var e=bM(t);return BK(e)}function zK(t){var e=bM(t);return e.toString()}var HK=typeof BigInt<"u"?zK:kP;function TM(t){return t}function AM(t){if(t!==void 0)return gf(t)}var GK={encodeHrTime:vM,encodeSpanContext:gf,encodeOptionalSpanContext:AM};function CM(t){var e,r;if(t===void 0)return GK;var n=(e=t.useLongBits)!==null&&e!==void 0?e:!0,o=(r=t.useHex)!==null&&r!==void 0?r:!1;return{encodeHrTime:n?vM:HK,encodeSpanContext:o?TM:gf,encodeOptionalSpanContext:o?TM:AM}}var jK=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 RM(t){return{name:t.name,version:t.version}}function nc(t){return Object.keys(t).map(function(e){return wM(e,t[e])})}function wM(t,e){return{key:t,value:xM(e)}}function xM(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(xM)}}:e==="object"&&t!=null?{kvlistValue:{values:Object.entries(t).map(function(r){var n=jK(r,2),o=n[0],i=n[1];return wM(o,i)})}}:{}}function _M(t){return{attributes:nc(t.attributes),droppedAttributesCount:0}}yt();function PM(t,e){var r=CM(e);return{resource:_M(t.resource),schemaUrl:void 0,scopeMetrics:VK(t.scopeMetrics,r)}}function VK(t,e){return Array.from(t.map(function(r){return{scope:RM(r.scope),metrics:r.metrics.map(function(n){return WK(n,e)}),schemaUrl:r.scope.schemaUrl}}))}function WK(t,e){var r={name:t.descriptor.name,description:t.descriptor.description,unit:t.descriptor.unit},n=YK(t.aggregationTemporality);switch(t.dataPointType){case Nr.SUM:r.sum={aggregationTemporality:n,isMonotonic:t.isMonotonic,dataPoints:IM(t,e)};break;case Nr.GAUGE:r.gauge={dataPoints:IM(t,e)};break;case Nr.HISTOGRAM:r.histogram={aggregationTemporality:n,dataPoints:qK(t,e)};break;case Nr.EXPONENTIAL_HISTOGRAM:r.exponentialHistogram={aggregationTemporality:n,dataPoints:KK(t,e)};break}return r}function $K(t,e,r){var n={attributes:nc(t.attributes),startTimeUnixNano:r.encodeHrTime(t.startTime),timeUnixNano:r.encodeHrTime(t.endTime)};switch(e){case Tn.INT:n.asInt=t.value;break;case Tn.DOUBLE:n.asDouble=t.value;break}return n}function IM(t,e){return t.dataPoints.map(function(r){return $K(r,t.descriptor.valueType,e)})}function qK(t,e){return t.dataPoints.map(function(r){var n=r.value;return{attributes:nc(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 KK(t,e){return t.dataPoints.map(function(r){var n=r.value;return{attributes:nc(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 YK(t){switch(t){case $n.DELTA:return 1;case $n.CUMULATIVE:return 2}}function MM(t,e){return{resourceMetrics:t.map(function(r){return PM(r,e)})}}var gT={serializeRequest:function(t){var e=MM(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 OM="0.52.1";var LM=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)}}(),oc=function(){return oc=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},oc.apply(this,arguments)},NM="v1/metrics",XK="http://localhost:4318/"+NM,JK={"User-Agent":"OTel-OTLP-Exporter-JavaScript/"+OM},QK=function(t){LM(e,t);function e(r){var n=t.call(this,r,gT,"application/json")||this;return n.headers=oc(oc(oc(oc({},n.headers),JK),ec.parseKeyPairsIntoRecord(Sr().OTEL_EXPORTER_OTLP_METRICS_HEADERS)),Rd(r?.headers)),n}return e.prototype.getDefaultUrl=function(r){return typeof r.url=="string"?r.url:Sr().OTEL_EXPORTER_OTLP_METRICS_ENDPOINT.length>0?cT(Sr().OTEL_EXPORTER_OTLP_METRICS_ENDPOINT):Sr().OTEL_EXPORTER_OTLP_ENDPOINT.length>0?lT(Sr().OTEL_EXPORTER_OTLP_ENDPOINT,NM):XK},e}(_f),DM=function(t){LM(e,t);function e(r){return t.call(this,new QK(r),r)||this}return e}(uM);var ic;(function(t){t[t.DELTA=0]="DELTA",t[t.CUMULATIVE=1]="CUMULATIVE"})(ic||(ic={}));var Wo;(function(t){t[t.HISTOGRAM=0]="HISTOGRAM",t[t.EXPONENTIAL_HISTOGRAM=1]="EXPONENTIAL_HISTOGRAM",t[t.GAUGE=2]="GAUGE",t[t.SUM=3]="SUM"})(Wo||(Wo={}));yt();var ZK=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)}}(),kM=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())})},UM=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}}},e2=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},t2=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))},r2=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 FM(t){return t!=null}function If(t){var e=Object.keys(t);return e.length===0?"":(e=e.sort(),JSON.stringify(e.map(function(r){return[r,t[r]]})))}function BM(t){var e,r;return t.name+":"+((e=t.version)!==null&&e!==void 0?e:"")+":"+((r=t.schemaUrl)!==null&&r!==void 0?r:"")}var ST=function(t){ZK(e,t);function e(r){var n=t.call(this,r)||this;return Object.setPrototypeOf(n,e.prototype),n}return e}(Error);function ua(t,e){var r,n=new Promise(function(i,a){r=setTimeout(function(){a(new ST("Operation timed out."))},e)});return Promise.race([t,n]).then(function(o){return clearTimeout(r),o},function(o){throw clearTimeout(r),o})}function zM(t){return kM(this,void 0,void 0,function(){var e=this;return UM(this,function(r){return[2,Promise.all(t.map(function(n){return kM(e,void 0,void 0,function(){var o,i;return UM(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 HM(t){return t.status==="rejected"}function yT(t,e){var r=[];return t.forEach(function(n){r.push.apply(r,t2([],e2(e(n)),!1))}),r}function GM(t,e){var r,n;if(t.size!==e.size)return!1;try{for(var o=r2(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 jM(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 VM(t,e){return t.toLowerCase()===e.toLowerCase()}yt();var Kn;(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"})(Kn||(Kn={}));var ET=function(){function t(){this.kind=Kn.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 Ye;(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"})(Ye||(Ye={}));function $o(t,e,r){var n,o,i,a;return o2(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:Tn.DOUBLE,advice:(a=r?.advice)!==null&&a!==void 0?a:{}}}function WM(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 $M(t,e){return VM(t.name,e.name)&&t.unit===e.unit&&t.type===e.type&&t.valueType===e.valueType}var n2=/^[a-z][a-z0-9_.\-/]{0,254}$/i;function o2(t){return t.match(n2)!=null}var i2=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 a2(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 Pf=function(){function t(e,r,n,o){n===void 0&&(n=!0),o===void 0&&(o=a2(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=jM(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 Mf=function(){function t(e,r){this._boundaries=e,this._recordMinMax=r,this.kind=Kn.HISTOGRAM}return t.prototype.createAccumulation=function(e){return new Pf(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 Pf(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 Pf(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:Wo.HISTOGRAM,dataPoints:n.map(function(i){var a=i2(i,2),s=a[0],c=a[1],l=c.toPointValue(),u=e.type===Ye.GAUGE||e.type===Ye.UP_DOWN_COUNTER||e.type===Ye.OBSERVABLE_GAUGE||e.type===Ye.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 TT=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},bT=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))},vT=function(){function t(e,r,n,o){e===void 0&&(e=new s2),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 s2=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,bT([n,this._counts.length-r],TT(this._counts.slice(r)),!1)),o.splice.apply(o,bT([0,r],TT(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(bT([],TT(this._counts),!1))},t}();var qM=52,l2=2146435072,c2=1048575,AT=1023,Of=-AT+1,Lf=AT,wd=Math.pow(2,-1022);function Nf(t){var e=new DataView(new ArrayBuffer(8));e.setFloat64(0,t);var r=e.getUint32(0),n=(r&l2)>>20;return n-AT}function Df(t){var e=new DataView(new ArrayBuffer(8));e.setFloat64(0,t);var r=e.getUint32(0),n=e.getUint32(4),o=(r&c2)*Math.pow(2,32);return o+n}function xd(t,e){return t===0||t===Number.POSITIVE_INFINITY||t===Number.NEGATIVE_INFINITY||Number.isNaN(t)?t:t*Math.pow(2,e)}function YM(t){return t--,t|=t>>1,t|=t>>2,t|=t>>4,t|=t>>8,t|=t>>16,t++,t}var u2=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)}}(),da=function(t){u2(e,t);function e(){return t!==null&&t.apply(this,arguments)||this}return e}(Error);var JM=function(){function t(e){this._shift=-e}return t.prototype.mapToIndex=function(e){if(e<wd)return this._minNormalLowerBoundaryIndex();var r=Nf(e),n=this._rightShift(Df(e)-1,qM);return r+n>>this._shift},t.prototype.lowerBoundary=function(e){var r=this._minNormalLowerBoundaryIndex();if(e<r)throw new da("underflow: "+e+" is < minimum lower boundary: "+r);var n=this._maxNormalLowerBoundaryIndex();if(e>n)throw new da("overflow: "+e+" is > maximum lower boundary: "+n);return xd(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=Of>>this._shift;return this._shift<2&&e--,e},t.prototype._maxNormalLowerBoundaryIndex=function(){return Lf>>this._shift},t.prototype._rightShift=function(e,r){return Math.floor(e*Math.pow(2,-r))},t}();var QM=function(){function t(e){this._scale=e,this._scaleFactor=xd(Math.LOG2E,e),this._inverseFactor=xd(Math.LN2,-e)}return t.prototype.mapToIndex=function(e){if(e<=wd)return this._minNormalLowerBoundaryIndex()-1;if(Df(e)===0){var r=Nf(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 da("overflow: "+e+" is > maximum lower boundary: "+r)}var n=this._minNormalLowerBoundaryIndex();if(e<=n){if(e===n)return wd;if(e===n-1)return Math.exp((e+(1<<this._scale))/this._scaleFactor)/2;throw new da("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 Of<<this._scale},t.prototype._maxNormalLowerBoundaryIndex=function(){return(Lf+1<<this._scale)-1},t}();var ZM=-10,eO=20,d2=Array.from({length:31},function(t,e){return e>10?new QM(e-10):new JM(e-10)});function CT(t){if(t>eO||t<ZM)throw new da("expected scale >= "+ZM+" && <= "+eO+", got: "+t);return d2[t+10]}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},kf=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}(),m2=20,f2=160,RT=2,tO=function(){function t(e,r,n,o,i,a,s,c,l,u,d){e===void 0&&(e=e),r===void 0&&(r=f2),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 vT),u===void 0&&(u=new vT),d===void 0&&(d=CT(m2)),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<RT&&(ie.warn("Exponential Histogram Max Size set to "+this._maxSize+", changing to the minimum size of: "+RT),this._maxSize=RT)}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=YM(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=CT(r)}},t.prototype._minScale=function(e){var r=Math.min(this.scale,e.scale),n=kf.combine(this._highLowAtScale(this.positive,this.scale,r),this._highLowAtScale(e.positive,e.scale,r)),o=kf.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 kf(0,-1);var o=r-n;return new kf(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 wT=function(){function t(e,r){this._maxSize=e,this._recordMinMax=r,this.kind=Kn.EXPONENTIAL_HISTOGRAM}return t.prototype.createAccumulation=function(e){return new tO(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:Wo.EXPONENTIAL_HISTOGRAM,dataPoints:n.map(function(i){var a=p2(i,2),s=a[0],c=a[1],l=c.toPointValue(),u=e.type===Ye.GAUGE||e.type===Ye.UP_DOWN_COUNTER||e.type===Ye.OBSERVABLE_GAUGE||e.type===Ye.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 h2=UE("OpenTelemetry SDK Context Key SUPPRESS_TRACING");function rO(t){return t.setValue(h2,!0)}yt();function nO(){return function(t){ie.error(g2(t))}}function g2(t){return typeof t=="string"?t:JSON.stringify(S2(t))}function S2(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 y2=nO();function Uf(t){try{y2(t)}catch{}}var oO="1.30.1";var E2="process.runtime.name";var T2="service.name";var b2="telemetry.sdk.name",v2="telemetry.sdk.language",A2="telemetry.sdk.version";var iO=E2;var aO=T2;var _d=b2,Id=v2,Pd=A2;var C2="nodejs";var sO=C2;var ac,Ss=(ac={},ac[_d]="opentelemetry",ac[iO]="node",ac[Id]=sO,ac[Pd]=oO,ac);function Md(t){t.unref()}var M2=9,O2=6,L2=Math.pow(10,O2),zMe=Math.pow(10,M2);function ys(t){var e=t/1e3,r=Math.trunc(e),n=Math.round(t%1e3*L2);return[r,n]}function sc(t){return t[0]*1e6+t[1]/1e3}var Od;(function(t){t[t.SUCCESS=0]="SUCCESS",t[t.FAILED=1]="FAILED"})(Od||(Od={}));yt();function lO(t,e){return new Promise(function(r){Zl.with(rO(Zl.active()),function(){t.export(e,function(n){r(n)})})})}var cO={_export:lO};var N2=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},Ff=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=ys(Date.now())},t.prototype.setStartTime=function(e){this.startTime=e},t.prototype.toPointValue=function(){return this._current},t}();var xT=function(){function t(){this.kind=Kn.LAST_VALUE}return t.prototype.createAccumulation=function(e){return new Ff(e)},t.prototype.merge=function(e,r){var n=sc(r.sampleTime)>=sc(e.sampleTime)?r:e;return new Ff(e.startTime,n.toPointValue(),n.sampleTime)},t.prototype.diff=function(e,r){var n=sc(r.sampleTime)>=sc(e.sampleTime)?r:e;return new Ff(r.startTime,n.toPointValue(),n.sampleTime)},t.prototype.toMetricData=function(e,r,n,o){return{descriptor:e,aggregationTemporality:r,dataPointType:Wo.GAUGE,dataPoints:n.map(function(i){var a=N2(i,2),s=a[0],c=a[1];return{attributes:s,startTime:c.startTime,endTime:o,value:c.toPointValue()}})}},t}();var D2=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},lc=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 Bf=function(){function t(e){this.monotonic=e,this.kind=Kn.SUM}return t.prototype.createAccumulation=function(e){return new lc(e,this.monotonic)},t.prototype.merge=function(e,r){var n=e.toPointValue(),o=r.toPointValue();return r.reset?new lc(r.startTime,this.monotonic,o,r.reset):new lc(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 lc(r.startTime,this.monotonic,o,!0):new lc(r.startTime,this.monotonic,o-n)},t.prototype.toMetricData=function(e,r,n,o){return{descriptor:e,aggregationTemporality:r,dataPointType:Wo.SUM,dataPoints:n.map(function(i){var a=D2(i,2),s=a[0],c=a[1];return{attributes:s,startTime:c.startTime,endTime:o,value:c.toPointValue()}}),isMonotonic:this.monotonic}},t}();var Es=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)}}(),Yn=function(){function t(){}return t.Drop=function(){return gO},t.Sum=function(){return SO},t.LastValue=function(){return yO},t.Histogram=function(){return EO},t.ExponentialHistogram=function(){return k2},t.Default=function(){return U2},t}();var uO=function(t){Es(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 ET,e}(Yn);var dO=function(t){Es(e,t);function e(){return t!==null&&t.apply(this,arguments)||this}return e.prototype.createAggregator=function(r){switch(r.type){case Ye.COUNTER:case Ye.OBSERVABLE_COUNTER:case Ye.HISTOGRAM:return e.MONOTONIC_INSTANCE;default:return e.NON_MONOTONIC_INSTANCE}},e.MONOTONIC_INSTANCE=new Bf(!0),e.NON_MONOTONIC_INSTANCE=new Bf(!1),e}(Yn);var pO=function(t){Es(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 xT,e}(Yn);var mO=function(t){Es(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 Mf([0,5,10,25,50,75,100,250,500,750,1e3,2500,5e3,7500,1e4],!0),e}(Yn);var Ld=function(t){Es(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 Mf(this._boundaries,this._recordMinMax)},e}(Yn);var fO=function(t){Es(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 wT(this._maxSize,this._recordMinMax)},e}(Yn);var hO=function(t){Es(e,t);function e(){return t!==null&&t.apply(this,arguments)||this}return e.prototype._resolve=function(r){switch(r.type){case Ye.COUNTER:case Ye.UP_DOWN_COUNTER:case Ye.OBSERVABLE_COUNTER:case Ye.OBSERVABLE_UP_DOWN_COUNTER:return SO;case Ye.GAUGE:case Ye.OBSERVABLE_GAUGE:return yO;case Ye.HISTOGRAM:return r.advice.explicitBucketBoundaries?new Ld(r.advice.explicitBucketBoundaries):EO}return ie.warn("Unable to recognize instrument type: "+r.type),gO},e.prototype.createAggregator=function(r){return this._resolve(r).createAggregator(r)},e}(Yn);var gO=new uO,SO=new dO,yO=new pO,EO=new mO,k2=new fO,U2=new hO;var TO=function(t){return Yn.Default()},bO=function(t){return ic.CUMULATIVE};var _T=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())})},IT=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}}},vO=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))},AO=function(){function t(e){var r,n,o;this._shutdown=!1,this._aggregationSelector=(r=e?.aggregationSelector)!==null&&r!==void 0?r:TO,this._aggregationTemporalitySelector=(n=e?.aggregationTemporalitySelector)!==null&&n!==void 0?n:bO,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 _T(this,void 0,void 0,function(){var r,n,o,i,a,s;return IT(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(F2([this._sdkMetricProducer.collect({timeoutMillis:e?.timeoutMillis})],vO(this._metricProducers.map(function(l){return l.collect({timeoutMillis:e?.timeoutMillis})})),!1))];case 1:return r=vO.apply(void 0,[c.sent()]),n=r[0],o=r.slice(1),i=n.errors.concat(yT(o,function(l){return l.errors})),a=n.resourceMetrics.resource,s=n.resourceMetrics.scopeMetrics.concat(yT(o,function(l){return l.resourceMetrics.scopeMetrics})),[2,{resourceMetrics:{resource:a,scopeMetrics:s},errors:i}]}})})},t.prototype.shutdown=function(e){return _T(this,void 0,void 0,function(){return IT(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,ua(this.onShutdown(),e.timeoutMillis)];case 3:r.sent(),r.label=4;case 4:return this._shutdown=!0,[2]}})})},t.prototype.forceFlush=function(e){return _T(this,void 0,void 0,function(){return IT(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,ua(this.onForceFlush(),e.timeoutMillis)];case 3:return r.sent(),[2]}})})},t}();yt();var B2=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)}}(),zf=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())})},Hf=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},H2=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))},PT=function(t){B2(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 zf(this,void 0,void 0,function(){var r;return Hf(this,function(n){switch(n.label){case 0:return n.trys.push([0,2,,3]),[4,ua(this._doRun(),this._exportTimeout)];case 1:return n.sent(),[3,3];case 2:return r=n.sent(),r instanceof ST?(ie.error("Export took longer than %s milliseconds and timed out.",this._exportTimeout),[2]):(Uf(r),[3,3]);case 3:return[2]}})})},e.prototype._doRun=function(){var r,n;return zf(this,void 0,void 0,function(){var o,i,a,s,c,l;return Hf(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,H2(["PeriodicExportingMetricReader: metrics collection errors"],z2(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),Uf(s),[3,5];case 5:return i.scopeMetrics.length===0?[2]:[4,cO._export(this._exporter,i)];case 6:if(c=u.sent(),c.code!==Od.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),Md(this._interval)},e.prototype.onForceFlush=function(){return zf(this,void 0,void 0,function(){return Hf(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 zf(this,void 0,void 0,function(){return Hf(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}(AO);yt();yt();function Gf(){return"unknown_service:"+process.argv0}var pa=function(){return pa=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},pa.apply(this,arguments)},G2=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())})},j2=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}}},V2=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},jf=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[aO]=Gf(),e[Id]=Ss[Id],e[_d]=Ss[_d],e[Pd]=Ss[Pd],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 G2(this,void 0,void 0,function(){return j2(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=pa(pa({},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=V2(a,2),l=c[0],u=c[1];return pa(pa(pa(pa({},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 CO=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 Ts=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)}}(),Vf=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=Zl.active()),typeof e!="number"){ie.warn("non-number value provided to metric "+this._descriptor.name+": "+e);return}this._descriptor.valueType===Tn.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,ys(Date.now()))},t}();var RO=function(t){Ts(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}(Vf);var wO=function(t){Ts(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}(Vf);var xO=function(t){Ts(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}(Vf);var _O=function(t){Ts(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}(Vf);var Wf=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 IO=function(t){Ts(e,t);function e(){return t!==null&&t.apply(this,arguments)||this}return e}(Wf);var PO=function(t){Ts(e,t);function e(){return t!==null&&t.apply(this,arguments)||this}return e}(Wf);var MO=function(t){Ts(e,t);function e(){return t!==null&&t.apply(this,arguments)||this}return e}(Wf);function Nd(t){return t instanceof Wf}var OO=function(){function t(e){this._meterSharedState=e}return t.prototype.createGauge=function(e,r){var n=$o(e,Ye.GAUGE,r),o=this._meterSharedState.registerMetricStorage(n);return new xO(o,n)},t.prototype.createHistogram=function(e,r){var n=$o(e,Ye.HISTOGRAM,r),o=this._meterSharedState.registerMetricStorage(n);return new _O(o,n)},t.prototype.createCounter=function(e,r){var n=$o(e,Ye.COUNTER,r),o=this._meterSharedState.registerMetricStorage(n);return new wO(o,n)},t.prototype.createUpDownCounter=function(e,r){var n=$o(e,Ye.UP_DOWN_COUNTER,r),o=this._meterSharedState.registerMetricStorage(n);return new RO(o,n)},t.prototype.createObservableGauge=function(e,r){var n=$o(e,Ye.OBSERVABLE_GAUGE,r),o=this._meterSharedState.registerAsyncMetricStorage(n);return new PO(n,o,this._meterSharedState.observableRegistry)},t.prototype.createObservableCounter=function(e,r){var n=$o(e,Ye.OBSERVABLE_COUNTER,r),o=this._meterSharedState.registerAsyncMetricStorage(n);return new IO(n,o,this._meterSharedState.observableRegistry)},t.prototype.createObservableUpDownCounter=function(e,r){var n=$o(e,Ye.OBSERVABLE_UP_DOWN_COUNTER,r),o=this._meterSharedState.registerAsyncMetricStorage(n);return new MO(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 $f=function(){function t(e){this._instrumentDescriptor=e}return t.prototype.getInstrumentDescriptor=function(){return this._instrumentDescriptor},t.prototype.updateDescription=function(e){this._instrumentDescriptor=$o(this._instrumentDescriptor.name,this._instrumentDescriptor.type,{description:e,valueType:this._instrumentDescriptor.valueType,unit:this._instrumentDescriptor.unit,advice:this._instrumentDescriptor.advice})},t}();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)}}(),LO=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}}},$2=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 LO(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 LO(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){W2(e,t);function e(){return t.call(this,If)||this}return e}($2);var q2=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},qf=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=If(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=q2(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 MT=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.")},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},Kf=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===ic.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=K2(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=MT(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=MT(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=NO(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=MT(e.keys()),s=a.next();!s.done;s=a.next()){var c=NO(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 K2(t){return Array.from(t.entries())}var Y2=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)}}(),X2=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){Y2(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 qf(n,s._aggregationCardinalityLimit),s._temporalMetricStorage=new Kf(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=X2(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}($f);yt();function OT(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 Zp(n,{cause:e.error})}var DR=t=>{let
|
|
|
33
33
|
To resolve the conflict:`,LT(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
|
`,OT(l,e),`To resolve the conflict:
|
|
36
|
-
`,LT(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 UO=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 FO=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===Tn.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 BO=function(){function t(){this._buffer=new Map}return t.prototype.observe=function(e,r,n){if(n===void 0&&(n={}),!!Nd(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===Tn.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 DT=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())})},kT=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}}},zO=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},HO=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(){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(Nd));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(Nd)),o=this._findBatchCallback(e,n);o<0||this._batchCallbacks.splice(o,1)},t.prototype.observe=function(e,r){return DT(this,void 0,void 0,function(){var n,o,i,a;return kT(this,function(s){switch(s.label){case 0:return n=this._observeCallbacks(e,r),o=this._observeBatchCallbacks(e,r),[4,zM(HO(HO([],zO(n),!1),zO(o),!1))];case 1:return i=s.sent(),a=i.filter(HM).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 DT(n,void 0,void 0,function(){var s,c;return kT(this,function(l){switch(l.label){case 0:return s=new FO(a._descriptor.name,a._descriptor.valueType),c=Promise.resolve(i(s)),r!=null&&(c=ua(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 DT(n,void 0,void 0,function(){var s,c;return kT(this,function(l){switch(l.label){case 0:return s=new BO,c=Promise.resolve(i(s)),r!=null&&(c=ua(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&&GM(n.instruments,r)})},t}();var tY=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(t){tY(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 qf(n,s._aggregationCardinalityLimit),s._temporalMetricStorage=new Kf(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}($f);var VO=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)}}(),cc=function(){function t(){}return t.Noop=function(){return nY},t}();var rY=function(t){VO(e,t);function e(){return t!==null&&t.apply(this,arguments)||this}return e.prototype.process=function(r,n){return r},e}(cc);var WO=function(t){VO(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}(cc);var nY=new rY;var oY=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())})},iY=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}}},aY=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},$O=function(){function t(e,r){this._meterProviderSharedState=e,this._instrumentationScope=r,this.metricStorageRegistry=new kO,this.observableRegistry=new GO,this.meter=new OO(this)}return t.prototype.registerMetricStorage=function(e){var r=this._registerMetricStorage(e,jO);return r.length===1?r[0]:new UO(r)},t.prototype.registerAsyncMetricStorage=function(e){var r=this._registerMetricStorage(e,DO);return r},t.prototype.collect=function(e,r,n){return oY(this,void 0,void 0,function(){var o,i,a;return iY(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(FM),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=WM(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=aY(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,cc.Noop(),[u],f);return n.metricStorageRegistry.registerForCollector(u,h),h});i=i.concat(s)}return i},t}();var sY=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.")},qO=function(){function t(e){this.resource=e,this.viewRegistry=new CO,this.metricCollectors=[],this.meterSharedStates=new Map}return t.prototype.getMeterSharedState=function(e){var r=BM(e),n=this.meterSharedStates.get(r);return n==null&&(n=new $O(this,e),this.meterSharedStates.set(r,n)),n},t.prototype.selectAggregations=function(e){var r,n,o=[];try{for(var i=sY(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 Yf=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())})},Xf=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}}},lY=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},cY=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(e,r){this._sharedState=e,this._metricReader=r}return t.prototype.collect=function(e){return Yf(this,void 0,void 0,function(){var r,n,o,i,a=this;return Xf(this,function(s){switch(s.label){case 0:return r=ys(Date.now()),n=[],o=[],i=Array.from(this._sharedState.meterSharedStates.values()).map(function(c){return Yf(a,void 0,void 0,function(){var l;return Xf(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,cY([],lY(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 Yf(this,void 0,void 0,function(){return Xf(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 Yf(this,void 0,void 0,function(){return Xf(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 YO=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())})},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}}},JO=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 uY(t,e){var r=e??jf.empty();return t?jf.default().merge(r):r}var UT=function(){function t(e){var r,n,o,i,a;if(this._shutdown=!1,this._sharedState=new qO(uY((a=e?.mergeResourceWithDefaults)!==null&&a!==void 0?a:!0,e?.resource)),e?.views!=null&&e.views.length>0)try{for(var s=JO(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=JO(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"),GE()):this._sharedState.getMeterSharedState({name:e,version:r,schemaUrl:n.schemaUrl}).meter},t.prototype.addMetricReader=function(e){var r=new KO(this._sharedState,e);e.setMetricProducer(r),this._sharedState.metricCollectors.push(r)},t.prototype.shutdown=function(e){return YO(this,void 0,void 0,function(){return XO(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 YO(this,void 0,void 0,function(){return XO(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 dY=/[\^$\\.+?()[\]{}|]/g,Jf=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(dY,"\\$&").replace("*",".*")+"$"},t.hasWildcard=function(e){return e.includes("*")},t}();var uc=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 QO=function(){function t(e){var r;this._nameFilter=new Jf((r=e?.name)!==null&&r!==void 0?r:"*"),this._type=e?.type,this._unitFilter=new uc(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 ZO=function(){function t(e){this._nameFilter=new uc(e?.name),this._versionFilter=new uc(e?.version),this._schemaUrlFilter=new uc(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 pY(t){return t.instrumentName==null&&t.instrumentType==null&&t.instrumentUnit==null&&t.meterName==null&&t.meterVersion==null&&t.meterSchemaUrl==null}var Qf=function(){function t(e){var r;if(pY(e))throw new Error("Cannot create view with no selector arguments supplied");if(e.name!=null&&(e?.instrumentName==null||Jf.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 WO(e.attributeKeys):this.attributesProcessor=cc.Noop(),this.name=e.name,this.description=e.description,this.aggregation=(r=e.aggregation)!==null&&r!==void 0?r:Yn.Default(),this.instrumentSelector=new QO({name:e.instrumentName,type:e.instrumentType,unit:e.instrumentUnit}),this.meterSelector=new ZO({name:e.meterName,version:e.meterVersion,schemaUrl:e.meterSchemaUrl}),this.aggregationCardinalityLimit=e.aggregationCardinalityLimit}return t}();var ENe=process.env.APP||"unknown";yt();import{v4 as fY}from"uuid";function hY(){return new DM({url:"https://us-west.metrics.momentic.ai/v1/metrics",headers:{"x-momentic-metrics-api-key":"c60c6a0f-60da-41a7-a61b-07969a0aa303"},temporalityPreference:gs.DELTA})}var gY=[new Qf({instrumentName:"test_event_duration",instrumentType:Ye.HISTOGRAM,aggregation:new Ld([100,500,1e3,2e3,3e3,4e3,5e3,7500,1e4,15e3,2e4],!1)}),new Qf({instrumentName:"test_step_duration",instrumentType:Ye.HISTOGRAM,aggregation:new Ld([100,500,1e3,2e3,3e3,4e3,5e3,7500,1e4,15e3,2e4],!1)})],Zf=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 aT({[Sf]:e.serviceName,[MP]:r,[LP]:typeof process<"u"&&process.env.SERVICE_INSTANCE_ID?process.env.SERVICE_INSTANCE_ID:fY()}),o=hY(),i=new PT({exporter:o,exportIntervalMillis:e.exportIntervalMs??6e4});this.provider=new UT({resource:n,readers:[i],views:gY}),mf.setGlobalMeterProvider(this.provider),this.meter=mf.getMeter("momentic-serverless")}increment(e,r,n){try{let o=uf(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=uf(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 cf;function eL(t){t.disabled||(Wt=new Zf(t))}var FT=!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.72.0",tracesSampleRate:0,sendDefaultPii:!0}),BI(t.captureException),FT=!0}catch{}import{Argument as qte,Command as Kte,Option as Hr}from"@commander-js/extra-typings";import{execSync as Yte}from"child_process";import{existsSync as SY,statSync as yY}from"fs";function tL(t){try{return SY(t)&&yY(t).isDirectory()}catch(e){return v.error({err:e},`Error reading path ${t} during directory existence check`),!1}}import{confirm as EY,input as TY}from"@inquirer/prompts";import{existsSync as bY,mkdirSync as vY,statSync as AY}from"fs";import{dirname as CY}from"path";var RY=!1,nL=(()=>{try{return AY("/.dockerenv"),!0}catch{return!1}})();async function yr(t){return ds||RY||nL?!0:(await v.flush(),await new Promise(r=>setTimeout(r,100)),await EY({message:t}))}async function BT(t){let e=CY(t);return tL(e)?bY(t)?yr(`File '${rL(t)}' already exists. Overwrite existing content?`):!0:await yr(`Directory '${rL(e)}' doesn't exist. Create it now?`)?(vY(e,{recursive:!0}),!0):!1}function rL(t){return t.replace(/(\s+)/g,"\\$1")}async function oL(t,e){return ds||nL?e:(await TY({message:t,default:e})).trim()||e}import qo,{supportsColor as xY}from"chalk";import{Console as iL}from"console";import{format as kd}from"util";var zT=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}},eh=class t extends iL{_buffer=[];_groupDepth=0;Console=iL;constructor(){super({write:e=>(t.write(this._buffer,"log",e),!0)})}static write(e,r,n,o=2){let i=new zT(void 0,t.write).stack;if(!i)return e;let a=i.split(`
|
|
36
|
+
`,LT(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 UO=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 FO=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===Tn.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 BO=function(){function t(){this._buffer=new Map}return t.prototype.observe=function(e,r,n){if(n===void 0&&(n={}),!!Nd(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===Tn.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 DT=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())})},kT=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}}},zO=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},HO=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(){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(Nd));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(Nd)),o=this._findBatchCallback(e,n);o<0||this._batchCallbacks.splice(o,1)},t.prototype.observe=function(e,r){return DT(this,void 0,void 0,function(){var n,o,i,a;return kT(this,function(s){switch(s.label){case 0:return n=this._observeCallbacks(e,r),o=this._observeBatchCallbacks(e,r),[4,zM(HO(HO([],zO(n),!1),zO(o),!1))];case 1:return i=s.sent(),a=i.filter(HM).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 DT(n,void 0,void 0,function(){var s,c;return kT(this,function(l){switch(l.label){case 0:return s=new FO(a._descriptor.name,a._descriptor.valueType),c=Promise.resolve(i(s)),r!=null&&(c=ua(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 DT(n,void 0,void 0,function(){var s,c;return kT(this,function(l){switch(l.label){case 0:return s=new BO,c=Promise.resolve(i(s)),r!=null&&(c=ua(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&&GM(n.instruments,r)})},t}();var tY=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(t){tY(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 qf(n,s._aggregationCardinalityLimit),s._temporalMetricStorage=new Kf(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}($f);var VO=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)}}(),cc=function(){function t(){}return t.Noop=function(){return nY},t}();var rY=function(t){VO(e,t);function e(){return t!==null&&t.apply(this,arguments)||this}return e.prototype.process=function(r,n){return r},e}(cc);var WO=function(t){VO(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}(cc);var nY=new rY;var oY=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())})},iY=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}}},aY=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},$O=function(){function t(e,r){this._meterProviderSharedState=e,this._instrumentationScope=r,this.metricStorageRegistry=new kO,this.observableRegistry=new GO,this.meter=new OO(this)}return t.prototype.registerMetricStorage=function(e){var r=this._registerMetricStorage(e,jO);return r.length===1?r[0]:new UO(r)},t.prototype.registerAsyncMetricStorage=function(e){var r=this._registerMetricStorage(e,DO);return r},t.prototype.collect=function(e,r,n){return oY(this,void 0,void 0,function(){var o,i,a;return iY(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(FM),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=WM(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=aY(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,cc.Noop(),[u],f);return n.metricStorageRegistry.registerForCollector(u,h),h});i=i.concat(s)}return i},t}();var sY=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.")},qO=function(){function t(e){this.resource=e,this.viewRegistry=new CO,this.metricCollectors=[],this.meterSharedStates=new Map}return t.prototype.getMeterSharedState=function(e){var r=BM(e),n=this.meterSharedStates.get(r);return n==null&&(n=new $O(this,e),this.meterSharedStates.set(r,n)),n},t.prototype.selectAggregations=function(e){var r,n,o=[];try{for(var i=sY(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 Yf=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())})},Xf=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}}},lY=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},cY=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(e,r){this._sharedState=e,this._metricReader=r}return t.prototype.collect=function(e){return Yf(this,void 0,void 0,function(){var r,n,o,i,a=this;return Xf(this,function(s){switch(s.label){case 0:return r=ys(Date.now()),n=[],o=[],i=Array.from(this._sharedState.meterSharedStates.values()).map(function(c){return Yf(a,void 0,void 0,function(){var l;return Xf(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,cY([],lY(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 Yf(this,void 0,void 0,function(){return Xf(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 Yf(this,void 0,void 0,function(){return Xf(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 YO=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())})},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}}},JO=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 uY(t,e){var r=e??jf.empty();return t?jf.default().merge(r):r}var UT=function(){function t(e){var r,n,o,i,a;if(this._shutdown=!1,this._sharedState=new qO(uY((a=e?.mergeResourceWithDefaults)!==null&&a!==void 0?a:!0,e?.resource)),e?.views!=null&&e.views.length>0)try{for(var s=JO(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=JO(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"),GE()):this._sharedState.getMeterSharedState({name:e,version:r,schemaUrl:n.schemaUrl}).meter},t.prototype.addMetricReader=function(e){var r=new KO(this._sharedState,e);e.setMetricProducer(r),this._sharedState.metricCollectors.push(r)},t.prototype.shutdown=function(e){return YO(this,void 0,void 0,function(){return XO(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 YO(this,void 0,void 0,function(){return XO(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 dY=/[\^$\\.+?()[\]{}|]/g,Jf=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(dY,"\\$&").replace("*",".*")+"$"},t.hasWildcard=function(e){return e.includes("*")},t}();var uc=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 QO=function(){function t(e){var r;this._nameFilter=new Jf((r=e?.name)!==null&&r!==void 0?r:"*"),this._type=e?.type,this._unitFilter=new uc(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 ZO=function(){function t(e){this._nameFilter=new uc(e?.name),this._versionFilter=new uc(e?.version),this._schemaUrlFilter=new uc(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 pY(t){return t.instrumentName==null&&t.instrumentType==null&&t.instrumentUnit==null&&t.meterName==null&&t.meterVersion==null&&t.meterSchemaUrl==null}var Qf=function(){function t(e){var r;if(pY(e))throw new Error("Cannot create view with no selector arguments supplied");if(e.name!=null&&(e?.instrumentName==null||Jf.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 WO(e.attributeKeys):this.attributesProcessor=cc.Noop(),this.name=e.name,this.description=e.description,this.aggregation=(r=e.aggregation)!==null&&r!==void 0?r:Yn.Default(),this.instrumentSelector=new QO({name:e.instrumentName,type:e.instrumentType,unit:e.instrumentUnit}),this.meterSelector=new ZO({name:e.meterName,version:e.meterVersion,schemaUrl:e.meterSchemaUrl}),this.aggregationCardinalityLimit=e.aggregationCardinalityLimit}return t}();var TNe=process.env.APP||"unknown";yt();import{v4 as fY}from"uuid";function hY(){return new DM({url:"https://us-west.metrics.momentic.ai/v1/metrics",headers:{"x-momentic-metrics-api-key":"c60c6a0f-60da-41a7-a61b-07969a0aa303"},temporalityPreference:gs.DELTA})}var gY=[new Qf({instrumentName:"test_event_duration",instrumentType:Ye.HISTOGRAM,aggregation:new Ld([100,500,1e3,2e3,3e3,4e3,5e3,7500,1e4,15e3,2e4],!1)}),new Qf({instrumentName:"test_step_duration",instrumentType:Ye.HISTOGRAM,aggregation:new Ld([100,500,1e3,2e3,3e3,4e3,5e3,7500,1e4,15e3,2e4],!1)})],Zf=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 aT({[Sf]:e.serviceName,[MP]:r,[LP]:typeof process<"u"&&process.env.SERVICE_INSTANCE_ID?process.env.SERVICE_INSTANCE_ID:fY()}),o=hY(),i=new PT({exporter:o,exportIntervalMillis:e.exportIntervalMs??6e4});this.provider=new UT({resource:n,readers:[i],views:gY}),mf.setGlobalMeterProvider(this.provider),this.meter=mf.getMeter("momentic-serverless")}increment(e,r,n){try{let o=uf(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=uf(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 cf;function eL(t){t.disabled||(Wt=new Zf(t))}var FT=!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.72.1",tracesSampleRate:0,sendDefaultPii:!0}),BI(t.captureException),FT=!0}catch{}import{Argument as qte,Command as Kte,Option as Hr}from"@commander-js/extra-typings";import{execSync as Yte}from"child_process";import{existsSync as SY,statSync as yY}from"fs";function tL(t){try{return SY(t)&&yY(t).isDirectory()}catch(e){return v.error({err:e},`Error reading path ${t} during directory existence check`),!1}}import{confirm as EY,input as TY}from"@inquirer/prompts";import{existsSync as bY,mkdirSync as vY,statSync as AY}from"fs";import{dirname as CY}from"path";var RY=!1,nL=(()=>{try{return AY("/.dockerenv"),!0}catch{return!1}})();async function yr(t){return ds||RY||nL?!0:(await v.flush(),await new Promise(r=>setTimeout(r,100)),await EY({message:t}))}async function BT(t){let e=CY(t);return tL(e)?bY(t)?yr(`File '${rL(t)}' already exists. Overwrite existing content?`):!0:await yr(`Directory '${rL(e)}' doesn't exist. Create it now?`)?(vY(e,{recursive:!0}),!0):!1}function rL(t){return t.replace(/(\s+)/g,"\\$1")}async function oL(t,e){return ds||nL?e:(await TY({message:t,default:e})).trim()||e}import qo,{supportsColor as xY}from"chalk";import{Console as iL}from"console";import{format as kd}from"util";var zT=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}},eh=class t extends iL{_buffer=[];_groupDepth=0;Console=iL;constructor(){super({write:e=>(t.write(this._buffer,"log",e),!0)})}static write(e,r,n,o=2){let i=new zT(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",kd(e,...r))}error(e,...r){this._log("error",kd(e,...r))}info(e,...r){this._log("info",kd(e,...r))}log(e,...r){this._log("log",kd(e,...r))}warn(e,...r){this._log("warn",kd(e,...r))}getBuffer(){return this._buffer.length>0?this._buffer:void 0}};function aL(t){let e=globalThis.console,r=new eh;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 sL(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 wY}from"os";var le=Yl({app:"cli",hostname:wY(),disableConsoleLogs:!0,captureExceptions:!0}).child({cliVersion:"2.72.
|
|
42
|
+
`)}import{hostname as wY}from"os";var le=Yl({app:"cli",hostname:wY(),disableConsoleLogs:!0,captureExceptions:!0}).child({cliVersion:"2.72.1"});var _Y=5;async function rh({getResults:t,checkDone:e,name:r,timeoutMs:n=18e5}){let o=Date.now(),i=0;for(;Date.now()-o<n;){let a;i>_Y&&(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 dc({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 aL(()=>{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 nh=(t,e)=>{if(!t.failureDetails||!t.failureReason)return;let r=Sl[t.failureDetails?.classification?.reason||t.failureReason],n=t.failureDetails?.classification?.summary||Vi[t.failureReason],o=t.failureDetails.classification?.rootCause;if(v.error(e),o){v.log(`${It}- Error type: ${qo.dim(r)}`);let i="- Root cause analysis:",a=sL(`${i} ${o}`,`${It} `,!1),s=a.indexOf(":");v.log(`${It}${i} ${qo.dim(a.slice(s+1))}`)}else v.log(`${It}Reason: ${qo.red(r)}`),v.log(`${It}Description: ${qo.red(n)}`)},Ud=({status:t,testLogRef:e,getRunningTestsCount:r,getTotalTestsCount:n,additionalText:o})=>{t=t.toUpperCase();let i=t,a;t.includes("FAIL")?(i=qo.bgRed.white("FAIL"),a=3):t.includes("PASS")?(i=qo.bgGreen.white("PASS"),a=3):t.includes("START")?(i=qo.bgBlue.white("START"),a=2):t.includes("CANCEL")?(i=qo.bgRgb(191,68,11).white("CANCEL"),a=1):t.includes("RETRY")?(i=qo.bgRgb(191,68,11).white("RETRY"),a=2):t.includes("RUN")||t.includes("PROG")?(i=qo.bgMagenta.white("RUNNING"),a=0):(v.warn(`Unknown status tried to be logged in run test locally: ${t}`),a=0),xY||(i=`${i}`),v.log(`${i}${" ".repeat(a)} ${e} ${o?`${o} `:""}(${r()}/${n()})`)};import IY from"fs";import{platform as PY,tmpdir as MY}from"os";import OY from"path";import{program as LY}from"playwright-core/lib/cli/program";import{registry as Fd}from"playwright-core/lib/server";import lL from"proper-lockfile";var cL=OY.join(MY(),"momenticBrowserInstallation");var oh=["chrome","chromium","chrome-for-testing","ffmpeg"],HT=[...oh.filter(t=>t!=="ffmpeg")],NY={Chromium:"chromium","Google Chrome":"chrome","Chrome for Testing":"chrome-for-testing"};function uL(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 dL={chrome:"chrome",chromium:"chromium","chrome-for-testing":"chromium-headless-shell",ffmpeg:"ffmpeg"};function pL(t){if(t==="Org Default")return!1;let e=dL[NY[t]??""]??"",r=Fd.findExecutable(e);return!r||r.installType==="none"?!1:GT(r)}function GT(t){let e=t.executablePath();return IY.existsSync(e)}function DY(t,e){let r=dL[t];if(!r)throw new Error(`Requested install of unknown browser type ${t}`);let n=Fd.findExecutable(r);if(!n||n.installType==="none")throw new Error(`Requested install of unknown browser type ${t}`);if(!(!e&>(n)))return n}async function kY({browser:t,force:e}){let r=DY(t,e);if(!r){v.info(`Browser '${t}' is already installed, skipping...`);return}v.info(`Installing browser '${t}'...`);try{await Fd.installDeps([r],!1),await Fd.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=Fd.findExecutable(t),i=5*60*1e3,a=Date.now();for(;Date.now()-a<i&&!GT(o);)v.info("Waiting for browser to finish installing..."),await new Promise(s=>setTimeout(s,5e3))}else throw n}}async function UY(){if(PY()==="win32"){v.info("Installing Windows dependencies for Playwright...");try{await LY.parseAsync(["","","install","winldd"])}catch(t){v.warn(`Failed to install Windows dependencies: ${t}. Continuing with browser installation...`)}}}async function mL({rawBrowsers:t,force:e=!1,all:r=!1}){await UY();let n=r?oh:Array.from(new Set(t));try{await lL.lock(cL,{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 kY({browser:i,force:e})}catch(a){o=a,v.error(`Failed to install the ${i} browser: ${a}`)}}finally{await lL.unlock(cL,{realpath:!1})}if(o)throw o}import{createServer as FY}from"http";async function fL(t,e,r=30){for(let n=0;n<r;n+=1){let o=t+n;if(await BY(o))return o}v.error(`Could not find an available port for ${e} starting from ${t} after ${r} attempts`),process.exit(1)}async function BY(t){return new Promise((e,r)=>{let n=FY();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 zY from"blocked-at";import HY from"why-is-node-running";function hL(t){GY(t),jY()}function GY(t){zY((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 jY(){process.on("SIGINT",()=>{if("_getActiveHandles"in process){let t=process._getActiveHandles();console.log("Active handles:",t.map(e=>e.constructor?.name))}HY(),setImmediate(()=>{setTimeout(()=>{process.exit(1)},2e3).unref()})})}function gL(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 VY(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 SL(t){let{items:e,shardIndex:r,shardCount:n,sortKey:o}=t;return n>1?VY(e,r,n,o):e}function ih({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 jT(t,e,r){return t instanceof Wa?(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 pc({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 yL}from"lodash-es";var EL=[],ah=yL(async({reason:t,logger:e,exitCode:r})=>{for(let n of EL.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([rf(),Wt.flush()]),{milliseconds:5e3})}catch{}r!=null?process.exit(r):process.exit()}),mc=yL((t,e)=>{process.once("SIGINT",()=>ah({reason:"SIGINT",logger:t,exitCode:0})),process.once("SIGTERM",()=>ah({reason:"SIGTERM",logger:t,exitCode:0})),e&&(process.once("uncaughtException",r=>(t.error({err:r},"Uncaught exception, shutting down"),ah({reason:"uncaughtException",logger:t,exitCode:1}))),process.once("unhandledRejection",r=>(t.error({reason:r},"Unhandled rejection, shutting down"),ah({reason:"unhandledRejection",logger:t,exitCode:1}))))});function bs(t){EL.push(t)}import{randomUUID as Xte}from"crypto";import VB from"body-parser";import bee from"cors";import vee from"dedent";import{Router as NJ}from"express";import{diff as M4}from"deep-object-diff";import Qn from"fs";import xs from"path";function vt(t,e,r=!1){return t.length<e?t:t.slice(0,e-3)+(r?"...TRUNCATED...":"[...]")}var Ti={EQUALS:"equals",CONTAINS:"contains",STARTS_WITH:"starts with",EXISTS:"exists"},bi={EQUALS:"does not equal",CONTAINS:"does not contain",STARTS_WITH:"does not start with",EXISTS:"does not exist"},VT={EXISTS:"exists",VISIBLE:"is visible",ENABLED:"is enabled",EDITABLE:"is editable",FOCUSED:"is focused"},WT={EXISTS:"does not exist",VISIBLE:"is not visible",ENABLED:"is disabled",EDITABLE:"is not editable",FOCUSED:"is not focused"};function TL(t){switch(t.type){case"ELEMENT_CONTENT":return`content ${t.negated?bi[t.operation]:Ti[t.operation]} '${t.value}'`;case"ELEMENT_ATTRIBUTE":{let r=t.negated?bi[t.operation]:Ti[t.operation];return t.operation==="EXISTS"?`attribute '${t.attr}' ${r}`:`attribute '${t.attr}' ${r} '${t.value}'`}case"ELEMENT_NAME":{let r=t.negated?bi[t.operation]:Ti[t.operation];return t.operation==="EXISTS"?`tag name ${r}`:`tag name ${r} '${t.value}'`}case"ELEMENT_STYLE":{let r=t.negated?bi[t.operation]:Ti[t.operation];return t.operation==="EXISTS"?`style property '${t.property}' ${r}`:`style property '${t.property}' ${r} '${t.value}'`}case"ELEMENT_EXISTENCE":return t.negated?WT[t.condition]:VT[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 Fke={CONTENT:"The page"};function WY(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 lh(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 sh(t){let e="";return t.method&&(e=` with method ${t.method}`),`${lh(t.urlMatcher)}${e}`}function $Y(t){return`${t.negated?bi.CONTAINS:Ti.CONTAINS} '${t.value}'`}function qY(t){switch(t.type){case"CONTENT":return $Y(t);default:return t.type,""}}function vi(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=WY(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)} ${TL(t.assertion)}`;case"PAGE_CHECK":return`Check the page ${qY(t.assertion)}`;case"WAIT_FOR_URL":return`Wait for page URL to ${lh(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 ${sh(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 ${sh(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 ${sh(t.requestMatcher)}`:`Set a ${t.name} header for all requests`:"Set a header";case"MOCK_ROUTE":return t.requestMatcher?`Mock requests that ${sh(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 KY(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(KY(t)){let e={};return Object.entries(t).forEach(([r,n])=>{n!==void 0&&(e[r]=vo(n))}),e}return t}function Bd(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 bL(t){return t.type==="ELEMENT_EXISTENCE"&&t.negated&&(t.condition==="EXISTS"||t.condition==="VISIBLE")}function fc(t){return t.type==="ELEMENT_EXISTENCE"?t.negated?VT[t.condition]:WT[t.condition]:t.negated?Ti[t.operation]:bi[t.operation]}import{diff as JY}from"deep-object-diff";import{cloneDeep as ph}from"lodash-es";function cn(t){let e={parentChain:[]};return ch(t,e),e}function ch(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||ch({...t,steps:c.steps},e)&&i)return!0;if(ch({...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),ch({...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 vL(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!!vs([t],r,i).result}function AL(t){if(t.type==="RESOLVED_MODULE")return!0;let e=!1;return cn({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 YY(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 XY(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 CL(t,e){let r=e[e.length-1];if(!r)return null;let n=e.slice(0,-1),{result:o}=vs(t,r,n);return o?XY(o):null}function RL(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=YY(c)}return n}function vs(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 cn({steps:t,earlyStop:!0,onPresetAction:i,onConditional:i,onSimpleStepContainer:i}),{result:n,parentChain:o}}function wL(t,e){e(t);for(let r in t){let n=t[r];n&&(Array.isArray(n)?dh(n,e):typeof n=="object"&&wL(n,e))}}function dh(t,e){for(let r of t)r&&(Array.isArray(r)?dh(r,e):typeof r=="object"&&wL(r,e))}function zd(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 uh(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),uh({...t,results:e.results});break;case"CONDITIONAL":t.onConditional?.(e),e.assertionResult&&t.onPresetAction(e.assertionResult),uh({...t,results:e.results});break;default:throw new Error(`Unsupported result type: ${e.type}`)}}function Ai(t,e){return!t&&!e?!1:!t||!e?!0:Object.keys(JY(t,e)).length>0}function hc({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=QY(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}=hc({...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}=hc({...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(!qp.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}=hc({...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}=hc({...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 IL(t,e){return e?`${e}:${t}`:t}function QY(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 $T(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:IL(t.id,e.join(":")),organizationId:t.orgId,value:t.value,testId:t.testId,environment:t.environment}}function PL(t){let e=new Set;return dh(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 mh({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"&&ji(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 Gd(t,e,r){let n=t.cache&&"memory"in t.cache?t.cache.memory?.traces:void 0;Ai(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 ML({logger:t,steps:e}){let r={};return cn({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=IL(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 Hd(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 ZY(t,e){return t&&!Ai(t.memory,e.memory)?t:{...t,memory:e.memory,updatedAt:e.updatedAt}}function qT(t,e){return t?Ai(t.target.memory,e.target.memory)?{target:{...t.target,memory:e.target.memory},updatedAt:e.updatedAt}:t:{target:Hd(e.target),updatedAt:e.updatedAt}}function e4(t,e){let r=ph(t);return r.fromTarget?Ai(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=Hd(r.fromTarget),r.updatedAt=e.updatedAt)),r.toTarget?Ai(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=Hd(r.toTarget),r.updatedAt=e.updatedAt)),r}function OL({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;Ai(a,i.memory)&&(n.value.cache=ZY(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(Ai(a,i.target.memory)){let s=hn.safeParse(n.value.cache);n.value.cache=qT(s.data,i),r.push(n)}}else if("fromTarget"in i||"toTarget"in i){let a=LS.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};Ai(c,s)&&(n.value.cache=e4(a,i),r.push(n))}}}return r}async function fh({cacheStorage:t,logger:e,schemaVersion:r,stepLists:n,testId:o,environment:i}){let a=ph(n.steps),s=ph(n.beforeSteps)??void 0,c=ph(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 LL(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 yL}from"lodash-es";var EL=[],ah=yL(async({reason:t,logger:e,exitCode:r})=>{for(let n of EL.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([rf(),Wt.flush()]),{milliseconds:5e3})}catch{}r!=null?process.exit(r):process.exit()}),mc=yL((t,e)=>{process.once("SIGINT",()=>ah({reason:"SIGINT",logger:t,exitCode:0})),process.once("SIGTERM",()=>ah({reason:"SIGTERM",logger:t,exitCode:0})),e&&(process.once("uncaughtException",r=>(t.error({err:r},"Uncaught exception, shutting down"),ah({reason:"uncaughtException",logger:t,exitCode:1}))),process.once("unhandledRejection",r=>(t.error({reason:r},"Unhandled rejection, shutting down"),ah({reason:"unhandledRejection",logger:t,exitCode:1}))))});function bs(t){EL.push(t)}import{randomUUID as Xte}from"crypto";import VB from"body-parser";import bee from"cors";import vee from"dedent";import{Router as NJ}from"express";import{diff as M4}from"deep-object-diff";import Qn from"fs";import xs from"path";function vt(t,e,r=!1){return t.length<e?t:t.slice(0,e-3)+(r?"...TRUNCATED...":"[...]")}var Ti={EQUALS:"equals",CONTAINS:"contains",STARTS_WITH:"starts with",EXISTS:"exists"},bi={EQUALS:"does not equal",CONTAINS:"does not contain",STARTS_WITH:"does not start with",EXISTS:"does not exist"},VT={EXISTS:"exists",VISIBLE:"is visible",ENABLED:"is enabled",EDITABLE:"is editable",FOCUSED:"is focused"},WT={EXISTS:"does not exist",VISIBLE:"is not visible",ENABLED:"is disabled",EDITABLE:"is not editable",FOCUSED:"is not focused"};function TL(t){switch(t.type){case"ELEMENT_CONTENT":return`content ${t.negated?bi[t.operation]:Ti[t.operation]} '${t.value}'`;case"ELEMENT_ATTRIBUTE":{let r=t.negated?bi[t.operation]:Ti[t.operation];return t.operation==="EXISTS"?`attribute '${t.attr}' ${r}`:`attribute '${t.attr}' ${r} '${t.value}'`}case"ELEMENT_NAME":{let r=t.negated?bi[t.operation]:Ti[t.operation];return t.operation==="EXISTS"?`tag name ${r}`:`tag name ${r} '${t.value}'`}case"ELEMENT_STYLE":{let r=t.negated?bi[t.operation]:Ti[t.operation];return t.operation==="EXISTS"?`style property '${t.property}' ${r}`:`style property '${t.property}' ${r} '${t.value}'`}case"ELEMENT_EXISTENCE":return t.negated?WT[t.condition]:VT[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 Bke={CONTENT:"The page"};function WY(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 lh(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 sh(t){let e="";return t.method&&(e=` with method ${t.method}`),`${lh(t.urlMatcher)}${e}`}function $Y(t){return`${t.negated?bi.CONTAINS:Ti.CONTAINS} '${t.value}'`}function qY(t){switch(t.type){case"CONTENT":return $Y(t);default:return t.type,""}}function vi(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=WY(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)} ${TL(t.assertion)}`;case"PAGE_CHECK":return`Check the page ${qY(t.assertion)}`;case"WAIT_FOR_URL":return`Wait for page URL to ${lh(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 ${sh(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 ${sh(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 ${sh(t.requestMatcher)}`:`Set a ${t.name} header for all requests`:"Set a header";case"MOCK_ROUTE":return t.requestMatcher?`Mock requests that ${sh(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 KY(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(KY(t)){let e={};return Object.entries(t).forEach(([r,n])=>{n!==void 0&&(e[r]=vo(n))}),e}return t}function Bd(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 bL(t){return t.type==="ELEMENT_EXISTENCE"&&t.negated&&(t.condition==="EXISTS"||t.condition==="VISIBLE")}function fc(t){return t.type==="ELEMENT_EXISTENCE"?t.negated?VT[t.condition]:WT[t.condition]:t.negated?Ti[t.operation]:bi[t.operation]}import{diff as JY}from"deep-object-diff";import{cloneDeep as ph}from"lodash-es";function cn(t){let e={parentChain:[]};return ch(t,e),e}function ch(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||ch({...t,steps:c.steps},e)&&i)return!0;if(ch({...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),ch({...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 vL(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!!vs([t],r,i).result}function AL(t){if(t.type==="RESOLVED_MODULE")return!0;let e=!1;return cn({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 YY(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 XY(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 CL(t,e){let r=e[e.length-1];if(!r)return null;let n=e.slice(0,-1),{result:o}=vs(t,r,n);return o?XY(o):null}function RL(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=YY(c)}return n}function vs(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 cn({steps:t,earlyStop:!0,onPresetAction:i,onConditional:i,onSimpleStepContainer:i}),{result:n,parentChain:o}}function wL(t,e){e(t);for(let r in t){let n=t[r];n&&(Array.isArray(n)?dh(n,e):typeof n=="object"&&wL(n,e))}}function dh(t,e){for(let r of t)r&&(Array.isArray(r)?dh(r,e):typeof r=="object"&&wL(r,e))}function zd(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 uh(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),uh({...t,results:e.results});break;case"CONDITIONAL":t.onConditional?.(e),e.assertionResult&&t.onPresetAction(e.assertionResult),uh({...t,results:e.results});break;default:throw new Error(`Unsupported result type: ${e.type}`)}}function Ai(t,e){return!t&&!e?!1:!t||!e?!0:Object.keys(JY(t,e)).length>0}function hc({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=QY(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}=hc({...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}=hc({...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(!qp.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}=hc({...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}=hc({...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 IL(t,e){return e?`${e}:${t}`:t}function QY(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 $T(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:IL(t.id,e.join(":")),organizationId:t.orgId,value:t.value,testId:t.testId,environment:t.environment}}function PL(t){let e=new Set;return dh(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 mh({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"&&ji(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 Gd(t,e,r){let n=t.cache&&"memory"in t.cache?t.cache.memory?.traces:void 0;Ai(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 ML({logger:t,steps:e}){let r={};return cn({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=IL(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 Hd(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 ZY(t,e){return t&&!Ai(t.memory,e.memory)?t:{...t,memory:e.memory,updatedAt:e.updatedAt}}function qT(t,e){return t?Ai(t.target.memory,e.target.memory)?{target:{...t.target,memory:e.target.memory},updatedAt:e.updatedAt}:t:{target:Hd(e.target),updatedAt:e.updatedAt}}function e4(t,e){let r=ph(t);return r.fromTarget?Ai(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=Hd(r.fromTarget),r.updatedAt=e.updatedAt)),r.toTarget?Ai(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=Hd(r.toTarget),r.updatedAt=e.updatedAt)),r}function OL({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;Ai(a,i.memory)&&(n.value.cache=ZY(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(Ai(a,i.target.memory)){let s=hn.safeParse(n.value.cache);n.value.cache=qT(s.data,i),r.push(n)}}else if("fromTarget"in i||"toTarget"in i){let a=LS.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};Ai(c,s)&&(n.value.cache=e4(a,i),r.push(n))}}}return r}async function fh({cacheStorage:t,logger:e,schemaVersion:r,stepLists:n,testId:o,environment:i}){let a=ph(n.steps),s=ph(n.beforeSteps)??void 0,c=ph(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 LL(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 rBe}from"lodash-es";import KT from"semver";function hh(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(!KT.valid(r.toVersion)||!KT.valid(r.fromVersion))throw new Error(`Migration '${r.name}' has invalid version`);if(!KT.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 n4,{gte as o4}from"semver";var ma=3.1783027;function t4(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(YT(t)/ma)}function YT(t){let e=0;if(typeof t=="string"){let r=t;r=r.replaceAll(`
|
|
51
51
|
`,""),r=r.replaceAll(" ","");let n=t4(r);return r.length-n+ma*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+=YT(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*ma:e+=85*ma:n==="source"&&typeof r[n]=="object"&&r[n]?.type==="base64"?e+=1600*ma:e+=YT(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 jd=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 XT=class extends jd{constructor(){super(...arguments),this.tokenize=r4}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:IL(t.id,e.join(":")),organizationId:t.orgId,va
|
|
|
55
55
|
`)&&(r=r.slice(0,-1))),super.equals(e,r,n)}},NL=new XT;function JT(t,e,r){return NL.diff(t,e,r)}function r4(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 Vd(t,e,r){r=r||{};let n=r.n_surrounding??-1;n=n>=0?n:-1;let o=JT(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 gh=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 i4(t){return t.every(e=>e&&typeof e=="object"&&!Array.isArray(e))}async function QT({metadata:t,steps:e,logger:r,toVersion:n,migrations:o}){let i=e,{schemaVersion:a,id:s}=t,c=o.findIndex(d=>n4.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&&o4(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 DL(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=Vd(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 DL(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)||i4(i)&&(n[o]=await DL(i,e))}return r}var kL={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 UL={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 a4=[kL,UL];hh(ty,a4);var FL={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 BL={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 s4=["target","fromTarget","toTarget"];function zL(t){for(let e of s4){if(t[e]===void 0)continue;let r=t[e];r.elementDescriptor!==void 0?r.type="description":t[e]={type:"description",elementDescriptor:""}}}var HL={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 zL(e.command),e;case"AI_ACTION":{let r=e.commands;for(let n of r??[])zL(n);return e}default:return e}})};import{v4 as l4}from"uuid";var GL={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=l4()),e;default:return e}})};import{v4 as jL}from"uuid";var VL={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??jL(),e}case"AI_ACTION":return e.commands&&(e.steps=e.commands.map(r=>({type:"PRESET_ACTION",command:{...r,id:r.id??jL()}})),delete e.commands),e;default:return e}})};var WL={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 c4}from"uuid";var $L={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=c4()),e))};import{v4 as qL}from"uuid";var KL={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=qL())}return e.id=qL(),e})};var YL={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 u4}from"uuid";var XL={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=u4()),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 JL={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 QL={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&&ZL(r),e})};function ZL(t){t&&Object.keys(t).forEach(e=>{if(typeof t[e]=="object"&&t[e]){ZL(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 eN={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 tN={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 rN={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 nN={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 oN={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 iN={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 aN={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 Sh=new Set(["CLICK","TYPE","SELECT_OPTION"]),sN={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||Sh.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||Sh.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||Sh.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||Sh.has(m))&&(d.target={elementDescriptor:p??""})})}),e}),stopOnFailure:!0};var lN={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 cN={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 uN=[aN,lN,cN,sN,FL,BL,HL,GL,VL,WL,$L,KL,YL,XL,JL,QL,eN,tN,rN,nN,oN,iN];hh(De,uN);async function gc({metadata:t,steps:e,logger:r,toVersion:n}){return await QT({metadata:t,steps:e,logger:r,toVersion:n,migrations:uN})}import fBe from"zod";import{diff as yBe}from"deep-object-diff";import{cloneDeep as TBe}from"lodash-es";import{v4 as zBe}from"uuid";import{cloneDeep as f4}from"lodash-es";import yN from"truncate-json";import{v4 as mN}from"uuid";import{cloneDeep as gze,unset as Sze}from"lodash-es";function dN(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 vi(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 Xn(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 vi(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 Sc(t,e){return t.split(`
|
|
58
|
+
`)}var gh=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 i4(t){return t.every(e=>e&&typeof e=="object"&&!Array.isArray(e))}async function QT({metadata:t,steps:e,logger:r,toVersion:n,migrations:o}){let i=e,{schemaVersion:a,id:s}=t,c=o.findIndex(d=>n4.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&&o4(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 DL(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=Vd(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 DL(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)||i4(i)&&(n[o]=await DL(i,e))}return r}var kL={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 UL={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 a4=[kL,UL];hh(ty,a4);var FL={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 BL={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 s4=["target","fromTarget","toTarget"];function zL(t){for(let e of s4){if(t[e]===void 0)continue;let r=t[e];r.elementDescriptor!==void 0?r.type="description":t[e]={type:"description",elementDescriptor:""}}}var HL={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 zL(e.command),e;case"AI_ACTION":{let r=e.commands;for(let n of r??[])zL(n);return e}default:return e}})};import{v4 as l4}from"uuid";var GL={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=l4()),e;default:return e}})};import{v4 as jL}from"uuid";var VL={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??jL(),e}case"AI_ACTION":return e.commands&&(e.steps=e.commands.map(r=>({type:"PRESET_ACTION",command:{...r,id:r.id??jL()}})),delete e.commands),e;default:return e}})};var WL={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 c4}from"uuid";var $L={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=c4()),e))};import{v4 as qL}from"uuid";var KL={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=qL())}return e.id=qL(),e})};var YL={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 u4}from"uuid";var XL={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=u4()),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 JL={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 QL={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&&ZL(r),e})};function ZL(t){t&&Object.keys(t).forEach(e=>{if(typeof t[e]=="object"&&t[e]){ZL(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 eN={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 tN={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 rN={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 nN={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 oN={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 iN={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 aN={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 Sh=new Set(["CLICK","TYPE","SELECT_OPTION"]),sN={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||Sh.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||Sh.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||Sh.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||Sh.has(m))&&(d.target={elementDescriptor:p??""})})}),e}),stopOnFailure:!0};var lN={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 cN={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 uN=[aN,lN,cN,sN,FL,BL,HL,GL,VL,WL,$L,KL,YL,XL,JL,QL,eN,tN,rN,nN,oN,iN];hh(De,uN);async function gc({metadata:t,steps:e,logger:r,toVersion:n}){return await QT({metadata:t,steps:e,logger:r,toVersion:n,migrations:uN})}import hBe from"zod";import{diff as EBe}from"deep-object-diff";import{cloneDeep as bBe}from"lodash-es";import{v4 as HBe}from"uuid";import{cloneDeep as f4}from"lodash-es";import yN from"truncate-json";import{v4 as mN}from"uuid";import{cloneDeep as Sze,unset as yze}from"lodash-es";function dN(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 vi(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 Xn(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 vi(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 Sc(t,e){return t.split(`
|
|
59
59
|
`).map(r=>" ".repeat(e)+r).join(`
|
|
60
60
|
`)}function ZT(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
|
${Sc(`Number of sub-steps: ${e}`,2)}`}case"PRESET_ACTION":return vi(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(Sc(`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(Sc("Conditional check:",2)),e.push(Sc(ZT(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(Sc(`${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
|
${Sc(`Number of sub-steps: ${e}`,2)}`}default:return(r=>{throw new Error("You missed a case in the switch above")})(t)}}function pN(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 fN=1e3,hN=5e7,h4="[FAILED]";async function gN(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 g4(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 EN(t)?t.message||"Section start placeholder":(o=>e?`${e==="start"?"Start":"End"} of ${r}
|
|
65
|
-
${o}`:o)(ZT(t))}function S4(t,{unflattenedIndex:e,parentStep:r}){if(!(e===void 0||EN(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 EN(t){return t.type==="PRESET_ACTION"&&t.command?.type==="SUCCESS"&&!!t.message?.match(/^Starting the [\w- ]+ section$/)}function Eh(t,e={}){let r=e.followingStepStart??e.precedingStepEnd??new Date;return{type:"PRESET_ACTION",id:mN(),message:`Starting the ${t.replace(/-/g," ")} section`,startedAt:r,finishedAt:r,status:"SUCCESS",command:{id:mN(),type:"SUCCESS"},results:[]}}function yh(t,e={}){let{index:r,includeDomState:n=!1,header:o,unflattenedIndex:i,parentStep:a,includeUserFacingStepReference:s}=e,c=g4(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=`${h4} ${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=S4(t,{parentStep:a,unflattenedIndex:i})),t.status==="FAILED"&&n)try{let m=vw.array().parse(t.details);for(let f of m)"pageState"in f&&(p.pageState=f.pageState)}catch{}return p}async function TN(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(yh(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(yh(f,{index:n?h:void 0,includeDomState:o,includeUserFacingStepReference:l,header:"start",unflattenedIndex:S,parentStep:u})),s+=1;let{failureIndex:g,results:E}=await TN(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(yh(f,{index:n?s+m:void 0,includeDomState:o,includeUserFacingStepReference:l,parentStep:u,header:"end"}))}else p.push(yh(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 yc(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 TN(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 gN(t,e,g.afterSnapshot,a)),i&&g.beforeSnapshot&&(y=await gN(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 Wd({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}=yN(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 eb(t,e){for(let r=0;r<t.length;r++){let n=t[r];try{if(n.data){let{jsonString:o}=yN(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":SN(n);break;case"CONDITIONAL":n.assertionResult&&SN(n.assertionResult),eb(n.results,e);break;case"AI_ACTION_DYNAMIC":case"AI_ACTION":case"MODULE":case"SECTION":{eb(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 SN(t){let e=t.command;"cache"in e&&e.cache&&(e.cache=void 0)}function Th(t,e){let r=f4(t);if(eb(r,e),r.length>fN)return e.warn("Results too long, truncating before insertion"),r.slice(r.length-fN,r.length);let n=JSON.stringify(r);if(n.length>hN)for(e.warn({serializedLength:n.length,resultsArrayLength:r.length},"Database content violation: results too large, truncating before insertion");n.length>hN;)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 Fze}from"lodash-es";import{diff as THe}from"deep-object-diff";import{diff as AN}from"deep-object-diff";import{cloneDeep as bN}from"lodash-es";import{v4 as tb}from"uuid";async function Ut(t){let e=new Map,r=new Set,n=qi.parse({steps:t.stepLists.steps??[],beforeSteps:t.stepLists.beforeSteps??void 0,afterSteps:t.stepLists.afterSteps??void 0}),o=bN(n.steps),i=await As({...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=bN(n[s]);if(!c)continue;let l=await As({...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 As({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?tb():u.id,u.type){case"PRESET_ACTION":{let p=u.command;l.cachesToSave=l.cachesToSave.concat(vN({...e,command:p})),l.stepsToSave.push({...u,command:p});break}case"RESOLVED_MODULE":{let p=c?tb():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 As({...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({...rn.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 As({...e,steps:u.steps});try{u.steps=Sn.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(vN({...e,command:f.assertion.command}));let{stepsToSave:h,cachesToSave:S,moduleUpdates:g}=await As({...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 As({...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 As({...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 vN({command:t,cacheCreationParams:e,createNewCacheIds:r,moduleIdParents:n,moduleStepParents:o}){let i=[];if(t.id=r?tb():t.id,"cache"in t&&t.cache){if(e){let a=$T({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 Cs({logger:t,cacheStorage:e,orgId:r,testId:n,environment:o,originalStepsWithCaches:i,updatedStepsWithCaches:a}){let s=AN(i,a);if(Object.keys(s).length!==0){t.debug("Updating step caches post-success");try{let{cachesToSave:c}=await Ut({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 Ec({logger:t,cacheStorage:e,orgId:r,testId:n,environment:o,originalStepsWithCaches:i,updatedStepsWithCaches:a}){let s=AN(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=ML({logger:t,steps:p});for(let[f,h]of Object.entries(m))c[f]=h}let{cachesToSave:l}=await Ut({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=OL({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 CN(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 RN}from"lodash-es";import{z as y4}from"zod";async function wN({rawSteps:t,metadata:e,logger:r,callbacks:n}){CN(e,"defaultOnCloud");let o={},{resolvedSteps:i,newSchemaVersion:a}=await bh({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 bh({rawSteps:l,migrationMetadata:e,logger:r,callbacks:n,resolvedModuleCache:o});s[c]=u}return{resolvedTest:s,moduleIds:Array.from(Object.keys(o))}}async function Rs(t,e,r){let{newVersion:n,steps:o}=await gc({metadata:t,steps:e,logger:r});try{return{steps:bt.array().parse(o),newVersion:n}}catch(i){throw i instanceof y4.ZodError?(r.warn({type:"zod",zodIssues:i.issues,newVersion:n,id:t.id},"Failed to parse test steps while migrating test"),new Wa("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 fu(`Failed to parse test steps while migrating test: ${i}`,t.id,"entity",{cause:i}))}}async function bh({rawSteps:t,migrationMetadata:e,logger:r,callbacks:n,resolvedModuleCache:o={}}){let{newVersion:i,steps:a}=await Rs(e,t,r),s=[];for(let c of a)s.push(await $d({step:c,callbacks:n,logger:r,resolvedModuleCache:o}));return{resolvedSteps:s,newSchemaVersion:i}}async function $d({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{...RN(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 gc({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=>$d({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]=RN(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 $d({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 $d({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 $d({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 E4}from"lodash-es";import{stringify as xN}from"yaml";async function _N({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 T4({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:xN(a),modules:o}}async function T4({originalStepLists:t,modules:e,processedModuleNames:r,createNewCacheIds:n}){let o=E4(t);Object.values(o).forEach(s=>{b4(s??[])});let{stepsToSave:i,moduleUpdates:a}=await Ut({stepLists:o,createNewCacheIds:n});for(let s of a)r.has(s.name)||(e[s.name]=v4(s),r.add(s.name));return i}function b4(t){cn({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 v4(t){let e=rn.parse(t),r={fileType:ye.MODULE,...e,schemaVersion:De,steps:t.steps};return xN(r)}async function qd({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 Kd({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 qd({promiseGenerator:t,signal:a.signal,codePath:r,logger:n})}finally{i=!0,o?.removeEventListener("abort",s),clearTimeout(c)}}function IN(t,e){let r=Math.max(1,e),n=t/r;return Math.max(n,1e3)}function vh(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:vh(r.steps)};e.push(bt.parse(n));break}case"CONDITIONAL":{let n={...r,blocks:r.blocks.map(o=>({assertion:o.assertion,steps:vh(o.steps)})),elseSteps:r.elseSteps?vh(r.elseSteps):void 0};e.push(qa.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 Ah(t){return vh([t])[0]}import A4 from"picomatch";var Ch=(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||A4(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},Rh=(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}},Tc=t=>{try{return new URL(t),!0}catch{return!1}},PN=t=>!t.toLowerCase().startsWith("http"),bc=(t,e)=>{try{return new URL(t,e),!0}catch{return!1}};function ws(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 C4(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 yc(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 MN(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=[Eh("setup",{followingStepStart:d?.startedAt}),...o?.beforeResults??[]]}else if(i==="TeardownFailureError"){let d=u.at(-1),p=(o?.afterResults??[])[0],m=Eh("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=Eh("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 C4({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 ON(t,e,r){let{organizationId:n="local",runKey:o=e,createdBy:i="local-user",runGroupMetadata:a,runAttempts:s=[]}=r??{},c=t.trigger===nn.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 LN}from"uuid";function rb(t,e){return{...t,testId:e?.testId??"",testName:e?.testName??"",suiteId:e?.suiteId??"",suiteName:e?.suiteName??""}}var wh=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:rb({},this.metadata)}]).catch(s=>e.error({err:s},"Failed to report billable event"))]}trackStepExecution(e){if(Bx(e.type)){this.creditsUsedV2+=1;return}let r=Qy(e.type);if(this.creditsUsedV1+=r??0,e.type==="PRESET_ACTION"){this.creditsUsedV2+=1;let n=Zy(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:LN(),properties:rb({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:LN(),properties:rb({creditsUsed:this.creditsUsedV2},this.metadata)}]).catch(r=>e.error({err:r},"Failed to report credits used"))),await Promise.allSettled(this.asyncWork)}};import{cloneDeep as R4}from"lodash-es";function xh(t,e){if(t.length===0)return`${e}: (no steps)`;let r=ib(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)(ZT(t))}function S4(t,{unflattenedIndex:e,parentStep:r}){if(!(e===void 0||EN(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 EN(t){return t.type==="PRESET_ACTION"&&t.command?.type==="SUCCESS"&&!!t.message?.match(/^Starting the [\w- ]+ section$/)}function Eh(t,e={}){let r=e.followingStepStart??e.precedingStepEnd??new Date;return{type:"PRESET_ACTION",id:mN(),message:`Starting the ${t.replace(/-/g," ")} section`,startedAt:r,finishedAt:r,status:"SUCCESS",command:{id:mN(),type:"SUCCESS"},results:[]}}function yh(t,e={}){let{index:r,includeDomState:n=!1,header:o,unflattenedIndex:i,parentStep:a,includeUserFacingStepReference:s}=e,c=g4(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=`${h4} ${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=S4(t,{parentStep:a,unflattenedIndex:i})),t.status==="FAILED"&&n)try{let m=vw.array().parse(t.details);for(let f of m)"pageState"in f&&(p.pageState=f.pageState)}catch{}return p}async function TN(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(yh(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(yh(f,{index:n?h:void 0,includeDomState:o,includeUserFacingStepReference:l,header:"start",unflattenedIndex:S,parentStep:u})),s+=1;let{failureIndex:g,results:E}=await TN(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(yh(f,{index:n?s+m:void 0,includeDomState:o,includeUserFacingStepReference:l,parentStep:u,header:"end"}))}else p.push(yh(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 yc(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 TN(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 gN(t,e,g.afterSnapshot,a)),i&&g.beforeSnapshot&&(y=await gN(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 Wd({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}=yN(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 eb(t,e){for(let r=0;r<t.length;r++){let n=t[r];try{if(n.data){let{jsonString:o}=yN(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":SN(n);break;case"CONDITIONAL":n.assertionResult&&SN(n.assertionResult),eb(n.results,e);break;case"AI_ACTION_DYNAMIC":case"AI_ACTION":case"MODULE":case"SECTION":{eb(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 SN(t){let e=t.command;"cache"in e&&e.cache&&(e.cache=void 0)}function Th(t,e){let r=f4(t);if(eb(r,e),r.length>fN)return e.warn("Results too long, truncating before insertion"),r.slice(r.length-fN,r.length);let n=JSON.stringify(r);if(n.length>hN)for(e.warn({serializedLength:n.length,resultsArrayLength:r.length},"Database content violation: results too large, truncating before insertion");n.length>hN;)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 Bze}from"lodash-es";import{diff as bHe}from"deep-object-diff";import{diff as AN}from"deep-object-diff";import{cloneDeep as bN}from"lodash-es";import{v4 as tb}from"uuid";async function Ut(t){let e=new Map,r=new Set,n=qi.parse({steps:t.stepLists.steps??[],beforeSteps:t.stepLists.beforeSteps??void 0,afterSteps:t.stepLists.afterSteps??void 0}),o=bN(n.steps),i=await As({...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=bN(n[s]);if(!c)continue;let l=await As({...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 As({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?tb():u.id,u.type){case"PRESET_ACTION":{let p=u.command;l.cachesToSave=l.cachesToSave.concat(vN({...e,command:p})),l.stepsToSave.push({...u,command:p});break}case"RESOLVED_MODULE":{let p=c?tb():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 As({...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({...rn.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 As({...e,steps:u.steps});try{u.steps=Sn.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(vN({...e,command:f.assertion.command}));let{stepsToSave:h,cachesToSave:S,moduleUpdates:g}=await As({...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 As({...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 As({...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 vN({command:t,cacheCreationParams:e,createNewCacheIds:r,moduleIdParents:n,moduleStepParents:o}){let i=[];if(t.id=r?tb():t.id,"cache"in t&&t.cache){if(e){let a=$T({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 Cs({logger:t,cacheStorage:e,orgId:r,testId:n,environment:o,originalStepsWithCaches:i,updatedStepsWithCaches:a}){let s=AN(i,a);if(Object.keys(s).length!==0){t.debug("Updating step caches post-success");try{let{cachesToSave:c}=await Ut({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 Ec({logger:t,cacheStorage:e,orgId:r,testId:n,environment:o,originalStepsWithCaches:i,updatedStepsWithCaches:a}){let s=AN(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=ML({logger:t,steps:p});for(let[f,h]of Object.entries(m))c[f]=h}let{cachesToSave:l}=await Ut({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=OL({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 CN(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 RN}from"lodash-es";import{z as y4}from"zod";async function wN({rawSteps:t,metadata:e,logger:r,callbacks:n}){CN(e,"defaultOnCloud");let o={},{resolvedSteps:i,newSchemaVersion:a}=await bh({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 bh({rawSteps:l,migrationMetadata:e,logger:r,callbacks:n,resolvedModuleCache:o});s[c]=u}return{resolvedTest:s,moduleIds:Array.from(Object.keys(o))}}async function Rs(t,e,r){let{newVersion:n,steps:o}=await gc({metadata:t,steps:e,logger:r});try{return{steps:bt.array().parse(o),newVersion:n}}catch(i){throw i instanceof y4.ZodError?(r.warn({type:"zod",zodIssues:i.issues,newVersion:n,id:t.id},"Failed to parse test steps while migrating test"),new Wa("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 fu(`Failed to parse test steps while migrating test: ${i}`,t.id,"entity",{cause:i}))}}async function bh({rawSteps:t,migrationMetadata:e,logger:r,callbacks:n,resolvedModuleCache:o={}}){let{newVersion:i,steps:a}=await Rs(e,t,r),s=[];for(let c of a)s.push(await $d({step:c,callbacks:n,logger:r,resolvedModuleCache:o}));return{resolvedSteps:s,newSchemaVersion:i}}async function $d({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{...RN(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 gc({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=>$d({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]=RN(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 $d({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 $d({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 $d({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 E4}from"lodash-es";import{stringify as xN}from"yaml";async function _N({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 T4({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:xN(a),modules:o}}async function T4({originalStepLists:t,modules:e,processedModuleNames:r,createNewCacheIds:n}){let o=E4(t);Object.values(o).forEach(s=>{b4(s??[])});let{stepsToSave:i,moduleUpdates:a}=await Ut({stepLists:o,createNewCacheIds:n});for(let s of a)r.has(s.name)||(e[s.name]=v4(s),r.add(s.name));return i}function b4(t){cn({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 v4(t){let e=rn.parse(t),r={fileType:ye.MODULE,...e,schemaVersion:De,steps:t.steps};return xN(r)}async function qd({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 Kd({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 qd({promiseGenerator:t,signal:a.signal,codePath:r,logger:n})}finally{i=!0,o?.removeEventListener("abort",s),clearTimeout(c)}}function IN(t,e){let r=Math.max(1,e),n=t/r;return Math.max(n,1e3)}function vh(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:vh(r.steps)};e.push(bt.parse(n));break}case"CONDITIONAL":{let n={...r,blocks:r.blocks.map(o=>({assertion:o.assertion,steps:vh(o.steps)})),elseSteps:r.elseSteps?vh(r.elseSteps):void 0};e.push(qa.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 Ah(t){return vh([t])[0]}import A4 from"picomatch";var Ch=(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||A4(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},Rh=(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}},Tc=t=>{try{return new URL(t),!0}catch{return!1}},PN=t=>!t.toLowerCase().startsWith("http"),bc=(t,e)=>{try{return new URL(t,e),!0}catch{return!1}};function ws(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 C4(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 yc(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 MN(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=[Eh("setup",{followingStepStart:d?.startedAt}),...o?.beforeResults??[]]}else if(i==="TeardownFailureError"){let d=u.at(-1),p=(o?.afterResults??[])[0],m=Eh("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=Eh("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 C4({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 ON(t,e,r){let{organizationId:n="local",runKey:o=e,createdBy:i="local-user",runGroupMetadata:a,runAttempts:s=[]}=r??{},c=t.trigger===nn.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 LN}from"uuid";function rb(t,e){return{...t,testId:e?.testId??"",testName:e?.testName??"",suiteId:e?.suiteId??"",suiteName:e?.suiteName??""}}var wh=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:rb({},this.metadata)}]).catch(s=>e.error({err:s},"Failed to report billable event"))]}trackStepExecution(e){if(Bx(e.type)){this.creditsUsedV2+=1;return}let r=Qy(e.type);if(this.creditsUsedV1+=r??0,e.type==="PRESET_ACTION"){this.creditsUsedV2+=1;let n=Zy(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:LN(),properties:rb({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:LN(),properties:rb({creditsUsed:this.creditsUsedV2},this.metadata)}]).catch(r=>e.error({err:r},"Failed to report credits used"))),await Promise.allSettled(this.asyncWork)}};import{cloneDeep as R4}from"lodash-es";function xh(t,e){if(t.length===0)return`${e}: (no steps)`;let r=ib(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 ib(t,e={}){let{includeCache:r=!0}=e,n=R4(t);return cn({steps:n,earlyStop:!1,onPresetAction:(o,i)=>{let a=o;a.parentStepIdChain=i.parentChain.map(l=>l.id),nb(o);let s;if(r&&ji(o.command)&&o.command.cache!==void 0){let l=x4(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),nb(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,nb(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 nb(t){let e=t;delete e.aiSuggested,delete e.retries,delete e.skipped}function w4(t){return t.selector?t.selector:t.generatedSelectors?.[0]}function ob(t){let e=w4(t),r=t.nodeOnlySerializedHtml,n={};return e&&(n.selector=e),r&&(n.nodeOnlySerializedHtml=r),Object.keys(n).length?n:void 0}function x4(t){if(!t)return;let e={};if("target"in t)return{target:ob(t.target)};if("fromTarget"in t||"toTarget"in t){let r=t.fromTarget?ob(t.fromTarget):void 0,n=t.toTarget?ob(t.toTarget):void 0;return r&&(e.fromTarget=r),n&&(e.toTarget=n),Object.keys(e).length?e:void 0}}import _s from"yaml";import{z as UN}from"zod";import{execSync as _4}from"child_process";function Ci(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{_4(n,{encoding:"utf-8"})}catch(o){v.warn({err:o,postSaveCommand:n},"Failed to execute post-save hook command, continuing...")}}import{diff as NN}from"deep-object-diff";import Ao from"fs";import{cloneDeep as I4}from"lodash-es";import Yd from"path";import{v4 as P4}from"uuid";import vc from"yaml";function DN(t,e){let r=vc.stringify(t);Ao.writeFileSync(e,r,"utf-8")}function Jn({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=vc.parse(a),c;if(t.name&&t.name!==s.name){let m=`${dt(t.name)}.module.yaml`;if(c=Yd.join(Yd.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,...gE.parse(l),steps:bt.array().parse(t.steps)}),d=NN(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=vc.stringify(u);Ao.writeFileSync(i,p,"utf-8"),c&&Ao.renameSync(i,c),Ci(c||i,n.config)}function kN({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=Ri(i,o),s={...a,...e},c=vo({fileType:ye.MODULE,...gE.parse(s),steps:a.steps}),l=NN(c,a);if(l&&Object.keys(l).length===0){v.debug(`Skipping save for module ${t} since there are no changes`);return}let u=vc.stringify(c);Ao.writeFileSync(i,u,"utf-8");let d;if(e.name){let p=`${dt(e.name)}.module.yaml`;if(d=Yd.join(Yd.dirname(i),p),Ao.existsSync(d))throw new Error(`Module with name '${e.name}' already exists at path '${d}'`);Ao.renameSync(i,d)}Ci(d||i,n.config)}async function _h({name:t,description:e,enabled:r,steps:n,folder:o,project:i}){let a=dt(t),s=Yd.join(o,`${a}.module.yaml`),c=P4(),{stepsToSave:l}=await Ut({stepLists:{steps:n}}),u={fileType:ye.MODULE,schemaVersion:De,moduleId:c,name:t,description:e,enabled:r,steps:l.steps},d=vc.stringify(u);return Ao.writeFileSync(s,d,"utf-8"),Ci(s,i.config),{moduleId:c,name:t,description:e,enabled:r,steps:n}}function Ri(t,e){let r=Ao.readFileSync(t,"utf-8"),n=vc.parse(r);try{return rE.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 xi(t,e,r,n){let o=Ri(t.fullFilePath,r),{resolvedSteps:i}=await bh({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 Ri(c,r)}}}),a={...o,steps:i};return n&&(n[t.id]=I4(a)),a}async function Ih(t,e){let r={};return await Promise.all(Object.values(t.modules).map(async n=>{await xi(n,t,e,r)})),Array.from(Object.values(r))}function FN(t,e){let r=_s.stringify(t);Qn.writeFileSync(e,r,"utf-8")}async function BN({test:t,name:e,folder:r}){let n=await _N({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=xs.join(r,i);return Qn.writeFileSync(a,n.test,"utf-8"),a}function ab(t,e,r){let n=xs.join(r.rootDir,t);if(!Qn.existsSync(n))throw new Error(`Test not found at path '${t}' in project '${r.rootDir}'`);let o=Qn.readFileSync(n,"utf-8"),i=_s.parse(o),a,s;if(e.name&&e.name!==i.name){let p=`${dt(e.name)}.test.yaml`;if(a=xs.join(xs.dirname(t),p),s=xs.join(r.rootDir,a),Qn.existsSync(s))throw new Error(`Test with name '${e.name}' already exists at path '${s}'`)}let c={...i,...e},l=Gn.parse(c),u=vo({fileType:ye.TEST,...Gn.parse(l),beforeSteps:i.beforeSteps??void 0,steps:i.steps,afterSteps:i.afterSteps??void 0,retries:l.retries??void 0}),d=_s.stringify(u);return Qn.writeFileSync(n,d,"utf-8"),s&&Qn.renameSync(n,s),Ci(n,r.config),{newRelativeTestPath:a}}function bn({relativeTestPath:t,steps:e,schemaVersion:r,project:n,forceSaveOnNoDiffs:o}){let i=xs.join(n.rootDir,t);if(!Qn.existsSync(i))throw new Error(`Test not found at path '${t}' in project '${n.rootDir}'`);let a=Qn.readFileSync(i,"utf-8"),s=_s.parse(a),c=Gn.parse({...s,schemaVersion:r}),l=bt.array().or(UN.undefined()).parse(e.beforeSteps),u=bt.array().parse(e.steps),d=bt.array().or(UN.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=M4(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=_s.stringify(p);Qn.writeFileSync(i,f,"utf-8"),v.debug(`Saving test ${c.name} to ${i}`),Ci(i,n.config)}function Xd(t,e){let r=xs.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=Qn.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=_s.parse(n)}catch(i){throw new Error(`Could not parse test file ${r} as YAML: ${i}`)}return Or.parse(o)}function Is(t,e,r){let n=r.project.rootDir,o;try{o=Qn.readFileSync(t,"utf-8")}catch(a){throw e.error({err:a,projectRoot:n},a.message),new Error(a.message)}let i=_s.parse(o);if(!i.steps||!Array.isArray(i.steps))throw new Error(`Test ${t} is missing steps`);return i}async function Ft(t,e,r){let n=Is(t,e,r),o;try{o=Gn.parse(n)}catch(a){throw new Error(`Test ${t} is missing metadata or has invalid metadata: ${a}`)}let{resolvedTest:i}=await wN({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 Ri(c,s)}}});return i}import O4 from"@dotenvx/dotenvx";import L4 from"fs";import zN from"path";function Ph(t,e){return(t.config.environments??[]).map(r=>Ps(r.name,t,e))}function HN(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 N4(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=HN(i);s&&(n[o]=s);continue}let a;try{a=L4.readFileSync(zN.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 D4(t){let{project:e,envFile:r,logger:n}=t,o={};if(!r)return o;let i=O4.config({path:zN.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 Ps(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]:HN(n.baseUrl)},i=N4({envVariables:n.envVariables,project:e});Object.assign(o,i);let a=D4({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 U4,readFileSync as F4,readdirSync as B4,writeFileSync as z4}from"fs";import{glob as H4}from"glob";import Ms,{dirname as GN}from"path";import{cwd as lb}from"process";import jN from"yaml";import{z as gt}from"zod";import k4 from"zod";var Mh=["**/*.test.yaml","**/*.module.yaml"],sb=k4.string().refine(t=>/^[a-zA-Z0-9-]+$/.test(t)),Oh=15;var fa="momentic.config.yaml",cb="momentic.workspace.yaml",G4=gt.object({projects:gt.string().array().describe("list of glob patterns to find project (momentic.config.yaml) files")}),j4=gt.union([gt.string(),gt.object({fromFile:gt.string(),json:gt.boolean().optional()})]),V4=gt.object({name:sb,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(),j4).optional(),inheritFromShell:gt.boolean().optional().describe("inherit all environment variables from the shell - might be noisy"),browser:Qa.optional().describe("NB: most things should use project-level configuration only")}),W4=gt.object({postSave:gt.string().optional()}),$4=gt.object({name:sb,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(V4).optional(),gitMainBranch:gt.string().optional().readonly(),gitProtectedBranches:gt.string().array().optional().readonly(),ai:mi.optional(),browser:Qa.optional(),emulator:iE.optional(),advanced:py.optional(),displayRoot:gt.string().optional().describe("relative path from project root to use as the Repository root"),hooks:W4.optional()});function VN(t,e){let r;try{r=F4(t,"utf-8")}catch(o){v.warn(`Could not read possible Momentic ${e} file at ${t}: ${o}`);return}let n;try{if(n=jN.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 ub(t){let e=VN(t,"project configuration");if(e!==void 0)try{return $4.parse(e)}catch(r){v.warn(`Possible Momentic project configuration file at ${t} does not adhere to the required schema: ${r}`);return}}function q4(t){let e=VN(t,"workspace configuration");if(e!==void 0)try{return G4.parse(e)}catch(r){v.warn(`Possible Momentic workspace configuration file at ${t} does not adhere to the required schema: ${r}`);return}}function K4(){let t=[],e=lb(),r=Ms.parse(e).root,n=15,o=0;for(;o<n;){o++;let i=Ms.basename(e);if(zm.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 B4(e))if(a.endsWith(fa)){let s=Ms.join(e,a),c=ub(s);c&&t.push({configFilePath:s,config:c,rootDir:GN(s)})}if(t.length)return t;if(e=Ms.dirname(e),e===r)break}return t}async function Ct(t={}){let{configFilePath:e,nameFilter:r,skipExitOnError:n}=t,o=await db(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 Y4(t){let e=q4(t);if(!e||!e.projects||!e.projects.length)return;let r=e.projects.map(a=>(a.endsWith("/")||(a+="/"),`${a}*${fa}`)),n=AbortSignal.timeout(2e3),o;try{o=await H4(r,{absolute:!1,cwd:lb(),dotRelative:!1,maxDepth:Oh,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 ${cb} is misconfigured.`),a}let i=[];for(let a of o){let s=Ms.join(lb(),a),c=ub(s);c&&i.push({configFilePath:s,config:c,rootDir:GN(s)})}return i}async function db(t,e){if(t){t=Ms.resolve(t);let n=ub(t);return n?[{config:n,configFilePath:t,rootDir:Ms.dirname(t)}]:(console.error(`No valid Momentic project file found at ${t}.`),e||process.exit(1),[])}if(U4(cb)){let n=await Y4(cb);if(n)return n}return K4()}function ha(t,e){let r=jN.stringify(t);z4(e,r)}import $N from"fs";import{glob as X4}from"glob";import Jd from"path";import J4 from"yaml";import{z as WN}from"zod";var qN=!1,Q4=WN.object({fileType:WN.nativeEnum(ye)});async function fe(t,e=!1){let r={project:t,tests:{},modules:{},mobileTests:{},mobileModules:{},duplicateEntities:{}},n=t.config.include??Mh,o=Array.from(t.config.exclude??[]).concat(Hm),i=AbortSignal.timeout(5e3),a;try{a=await X4(n,{absolute:!1,cwd:t.rootDir,ignore:o,dotRelative:!1,maxDepth:Oh,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=Z4(t.rootDir,s,r,e?Ho:v);c&&(r.duplicateEntities[c.id]=c.paths)}return qN=!0,r}function Z4(t,e,r,n){let o=Jd.join(t,e),i=eX(o,n);if(!i)return;let a=tX(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=rX(o,n);if(!l)return;let u=nX(e,o,l);switch(c){case ye.TEST:try{return oX(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 iX(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 sX(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 aX(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 eX(t,e){try{return $N.readFileSync(t,"utf-8")}catch(r){e.warn(`Could not read possible Momentic file at ${t}, skipping: ${r}`);return}}function tX(t,e,r){try{let n=J4.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 rX(t,e){try{return $N.statSync(t)}catch(r){e.warn(`Skipping path '${t}' because it could not be stat, skipping: ${r}`);return}}function nX(t,e,r){return{relativePath:t,fullFilePath:e,platformSep:Jd.sep,fullPathSegments:e.split(Jd.sep),relativePathSegments:t.split(Jd.sep),fileName:Jd.basename(e),lastModified:r.mtime,createdAt:r.birthtime}}function oX(t,e,r,n,o){let i=Gn.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 iX(t,e,r,n,o){let i=rn.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!qN&&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 aX(t,e,r,n,o){let i=Lm.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 sX(t,e,r,n,o){let i=aE.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 Ac from"fs";import pb from"path";import{z as mb}from"zod";var KN="golden/visual-diff",YN="reports",XN="test-results";var lX=mb.object({width:mb.number(),height:mb.number()}),Cc=class{defaultGoldenScreenshotDir;regenerateGoldenFiles;apiClient;constructor(e,r,n){let o=pb.join(e.rootDir,e.config.goldenFileDir??KN);this.defaultGoldenScreenshotDir=o,this.regenerateGoldenFiles=n,this.apiClient=r}async prepareGoldenScreenshotForComparison(e,r,n){if(LC(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=pb.join(this.defaultGoldenScreenshotDir,`${r.id}.jpg`));let i=`${o}.metadata.json`;if(this.regenerateGoldenFiles)return Ac.mkdirSync(pb.dirname(o),{recursive:!0}),Ac.writeFileSync(o,n.buffer),Ac.writeFileSync(i,JSON.stringify({width:n.width,height:n.height})),{buffer:Buffer.from(n.buffer),width:n.width,height:n.height};if(Ac.existsSync(o)){let a=Ac.readFileSync(o),s=lX.parse(JSON.parse(Ac.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 cX}from"node:child_process";import{promisify as uX}from"node:util";import dX from"simple-git";var JN=3e3,ft=dX(),pX=uX(cX);async function Zn(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>JN&&e.warn({operation:r,durationMs:a,thresholdMs:JN,...o??{}},"[timing] slow git metadata operation")}}function _i(t){if(t)try{let e=new Date(t);return isNaN(e.getTime())?void 0:e}catch{return}}async function mX(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 fX(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 pX("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 hX(t,e,r){let n=e?.includes("github.com"),o=e?.includes("gitlab.com");try{if(n)return fX(t,e,r);if(o)return}catch{}}function Lh(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 gX(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(gX(r))return;t.error({err:r},"Failed to run git command");return}}function SX(){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 yX(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?_i(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 EX(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?_i(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 TX(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?Lh(i):void 0;return{ciProvider:"CircleCI",gitCommitSha:process.env.CIRCLE_SHA1,gitCommitShaShort:process.env.CIRCLE_SHA1?.slice(0,6),gitCommitTimestamp:e?_i(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 bX(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?Lh(o):void 0;return{ciProvider:"Buildkite",gitCommitSha:process.env.BUILDKITE_COMMIT,gitCommitShaShort:process.env.BUILDKITE_COMMIT?.slice(0,6),gitCommitTimestamp:e?_i(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 vX(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?Lh(o):void 0;return{ciProvider:"AzureDevOps",gitCommitSha:process.env["Build.SourceVersion"],gitCommitShaShort:process.env["Build.SourceVersion"]?.slice(0,6),gitCommitTimestamp:e?_i(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 AX(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),mX(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?Lh(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 hX(t,a,d):void 0)??y??b??void 0;return{ciProvider:"none",gitCommitSha:n,gitCommitShaShort:o,gitBranchName:i,gitOriginUrl:a,gitCommitTimestamp:s?_i(s):void 0,gitCommitMessage:c,gitCommitAuthorName:l,gitLocalUsername:_,gitLocalEmail:g,gitLocalName:E,lastCommitOnMainSha:p,lastCommitOnMainTimestamp:m?_i(m):void 0,githubRepository:f?S:void 0,gitlabProjectPath:h?S:void 0,pipelineId:void 0}}async function CX(){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 RX(){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:_i(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:_i(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 wX(t){let e=[...t.config.gitProtectedBranches??[]];return t.config.gitMainBranch&&e.push(t.config.gitMainBranch),{gitMainBranch:t.config.gitMainBranch,gitProtectedBranches:e}}async function Ii(t,e,r){let n=SX();if(!n)return AX(t,e,r);switch(n){case"GithubActions":return yX(t);case"GitlabCI":return EX(t);case"CircleCI":return TX(t);case"Buildkite":return bX(t);case"AzureDevOps":return vX(t);case"GCPCloudBuild":return CX();case"Custom":return RX()}}async function xX(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 Zn({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 Zn({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 Zn({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 _X(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 Zn({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 Zn({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 Zn({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 IX(t,e,r){try{if(r.githubRepository){let[n,o]=r.githubRepository.split("/");return await Zn({logger:t,operation:"getRemoteMetadataIfNeeded.getRemoteMetadataFromGitHub",fn:()=>_X(t,e,n,o,r),context:{githubRepository:r.githubRepository}})}else if(r.gitlabProjectPath){let n=r.gitlabProjectPath;return await Zn({logger:t,operation:"getRemoteMetadataIfNeeded.getRemoteMetadataFromGitlab",fn:()=>xX(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 Zn({logger:t,operation:"getGitMetadata.total",fn:async()=>{let[a,s]=await Promise.all([Zn({logger:t,operation:"getGitMetadata.getConfiguredGitMetadata",fn:()=>wX(r),context:{projectConfigPath:r.configFilePath}}),Zn({logger:t,operation:"getGitMetadata.getEnvironmentGitMetadata",fn:async()=>{let u=await Ii(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 Zn({logger:t,operation:"getGitMetadata.getRemoteMetadataIfNeeded",fn:()=>IX(t,e,c),context:{githubRepository:c.githubRepository,gitlabProjectPath:c.gitlabProjectPath,gitBranchName:c.gitBranchName}});return{...a,...s,...l}},context:o})}async function QN(){try{let t=await ft.remote(["show","origin"]);return t?t.match(/HEAD branch: (.*)$/m)?.[1]?.trim():void 0}catch{return}}async function ZN(){try{return!!(await ft.show(["--no-patch","--format=%ci"])).trim()}catch{return null}}import{diff as Hje}from"deep-object-diff";import{cloneDeep as jje}from"lodash-es";import{v4 as tVe}from"uuid";import nVe from"yaml";import yVe from"yaml";import Os from"zod";var vVe=Os.discriminatedUnion("platform",[km.extend({steps:Os.record(Os.string(),Os.unknown()).array()}),Um.extend({steps:Os.record(Os.string(),Os.unknown()).array()})]);import{randomUUID as PX}from"crypto";import ga from"fs";import Rc from"path";var tD=new Set([".DS_Store","__MACOSX"]),rD={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 MX(t,e,r){if(rD[r]){let i=rD[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 fb=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 nD(t,e){try{let r=Rc.join(e,"metadata.json");return ql.parse(JSON.parse(ga.readFileSync(r,"utf-8")))}catch{throw new fb(t,e)}}function oD(t,e,r){let n=PX(),o=t.child({runGroupId:n});ga.rmSync(e,{recursive:!0,force:!0});let i=ga.readdirSync(r).filter(c=>!tD.has(c)).map(c=>Rc.join(r,c));if(i.length===0)throw new Error(`No run groups found in results path: ${r}`);ga.mkdirSync(e,{recursive:!0});let a={...nD(r,i[0]),id:n};for(let c of i){let l=Rc.join(c,"runs");if(!ga.existsSync(l))continue;let u=nD(r,c);o.info({oldRunGroupId:u.id},"Merging run groups");for(let p in u){if(p==="id")continue;let m=p;a[m]=MX(a,u,m)}let d=ga.readdirSync(l);for(let p of d){if(tD.has(p))continue;let m=Rc.join(l,p),f=Rc.join(e,"runs",p);ga.cpSync(m,f,{recursive:!0})}}let s=Rc.join(e,"metadata.json");ga.writeFileSync(s,JSON.stringify(a,null,2))}import GD from"adm-zip";import Ub from"fs";import{z as yJ}from"zod";var Y="v1",hb="cli",Ls="2.72.0";var OX=9e4,LX=3,NX=1500,DX=15e3,Co=class extends Error{status;rawError;constructor(e,r,n,o={}){super(n,o),this.status=e,this.rawError=r}};async function kX(t){return t.text().then(e=>{try{return JSON.parse(e).error}catch{return e}})}var gb=class{baseUrl;logger;constructor(e){this.baseUrl=e.baseUrl,this.logger=e.logger}getHeaders(){let e={"Content-Type":"application/json"};return Ls&&(e[qm]=Ls),hb&&(e[__]=hb),e}async sendRequest(e,r){let{retries:n=LX,requestTimeoutMs:o=OX,initialRetryDelayMs:i=NX,maxRetryDelayMs:a=DX,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 aa),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 kX(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 gb{apiKey;mode;constructor(e){super(e),this.apiKey=e.apiKey,this.mode=e.mode}getHeaders(){return{...super.getHeaders(),Authorization:`Bearer ${this.apiKey}`,[x_]:this.mode??""}}};import{createAnthropic as SJ}from"@ai-sdk/anthropic";import{InvalidArgumentError as FX}from"@ai-sdk/provider";import{APICallError as WVe}from"@ai-sdk/provider";import{APICallError as zX}from"@ai-sdk/provider";import{LoadAPIKeyError as kh}from"@ai-sdk/provider";import{LoadSettingError as YVe}from"@ai-sdk/provider";import{JSONParseError as zh,TypeValidationError as $X}from"@ai-sdk/provider";import{TypeValidationError as bb}from"@ai-sdk/provider";import{TypeValidationError as XX}from"@ai-sdk/provider";var Nh=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 Sb(t){}function iD(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=Sb,onError:r=Sb,onRetry:n=Sb,onComment:o}=t,i="",a=!0,s,c="",l="";function u(h){let S=a?h.replace(/^\xEF\xBB\xBF/,""):h,[g,E]=UX(`${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 fX(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 pX("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 hX(t,e,r){let n=e?.includes("github.com"),o=e?.includes("gitlab.com");try{if(n)return fX(t,e,r);if(o)return}catch{}}function Lh(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 gX(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(gX(r))return;t.error({err:r},"Failed to run git command");return}}function SX(){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 yX(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?_i(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 EX(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?_i(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 TX(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?Lh(i):void 0;return{ciProvider:"CircleCI",gitCommitSha:process.env.CIRCLE_SHA1,gitCommitShaShort:process.env.CIRCLE_SHA1?.slice(0,6),gitCommitTimestamp:e?_i(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 bX(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?Lh(o):void 0;return{ciProvider:"Buildkite",gitCommitSha:process.env.BUILDKITE_COMMIT,gitCommitShaShort:process.env.BUILDKITE_COMMIT?.slice(0,6),gitCommitTimestamp:e?_i(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 vX(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?Lh(o):void 0;return{ciProvider:"AzureDevOps",gitCommitSha:process.env["Build.SourceVersion"],gitCommitShaShort:process.env["Build.SourceVersion"]?.slice(0,6),gitCommitTimestamp:e?_i(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 AX(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),mX(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?Lh(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 hX(t,a,d):void 0)??y??b??void 0;return{ciProvider:"none",gitCommitSha:n,gitCommitShaShort:o,gitBranchName:i,gitOriginUrl:a,gitCommitTimestamp:s?_i(s):void 0,gitCommitMessage:c,gitCommitAuthorName:l,gitLocalUsername:_,gitLocalEmail:g,gitLocalName:E,lastCommitOnMainSha:p,lastCommitOnMainTimestamp:m?_i(m):void 0,githubRepository:f?S:void 0,gitlabProjectPath:h?S:void 0,pipelineId:void 0}}async function CX(){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 RX(){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:_i(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:_i(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 wX(t){let e=[...t.config.gitProtectedBranches??[]];return t.config.gitMainBranch&&e.push(t.config.gitMainBranch),{gitMainBranch:t.config.gitMainBranch,gitProtectedBranches:e}}async function Ii(t,e,r){let n=SX();if(!n)return AX(t,e,r);switch(n){case"GithubActions":return yX(t);case"GitlabCI":return EX(t);case"CircleCI":return TX(t);case"Buildkite":return bX(t);case"AzureDevOps":return vX(t);case"GCPCloudBuild":return CX();case"Custom":return RX()}}async function xX(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 Zn({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 Zn({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 Zn({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 _X(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 Zn({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 Zn({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 Zn({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 IX(t,e,r){try{if(r.githubRepository){let[n,o]=r.githubRepository.split("/");return await Zn({logger:t,operation:"getRemoteMetadataIfNeeded.getRemoteMetadataFromGitHub",fn:()=>_X(t,e,n,o,r),context:{githubRepository:r.githubRepository}})}else if(r.gitlabProjectPath){let n=r.gitlabProjectPath;return await Zn({logger:t,operation:"getRemoteMetadataIfNeeded.getRemoteMetadataFromGitlab",fn:()=>xX(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 Zn({logger:t,operation:"getGitMetadata.total",fn:async()=>{let[a,s]=await Promise.all([Zn({logger:t,operation:"getGitMetadata.getConfiguredGitMetadata",fn:()=>wX(r),context:{projectConfigPath:r.configFilePath}}),Zn({logger:t,operation:"getGitMetadata.getEnvironmentGitMetadata",fn:async()=>{let u=await Ii(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 Zn({logger:t,operation:"getGitMetadata.getRemoteMetadataIfNeeded",fn:()=>IX(t,e,c),context:{githubRepository:c.githubRepository,gitlabProjectPath:c.gitlabProjectPath,gitBranchName:c.gitBranchName}});return{...a,...s,...l}},context:o})}async function QN(){try{let t=await ft.remote(["show","origin"]);return t?t.match(/HEAD branch: (.*)$/m)?.[1]?.trim():void 0}catch{return}}async function ZN(){try{return!!(await ft.show(["--no-patch","--format=%ci"])).trim()}catch{return null}}import{diff as Gje}from"deep-object-diff";import{cloneDeep as Vje}from"lodash-es";import{v4 as rVe}from"uuid";import oVe from"yaml";import EVe from"yaml";import Os from"zod";var AVe=Os.discriminatedUnion("platform",[km.extend({steps:Os.record(Os.string(),Os.unknown()).array()}),Um.extend({steps:Os.record(Os.string(),Os.unknown()).array()})]);import{randomUUID as PX}from"crypto";import ga from"fs";import Rc from"path";var tD=new Set([".DS_Store","__MACOSX"]),rD={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 MX(t,e,r){if(rD[r]){let i=rD[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 fb=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 nD(t,e){try{let r=Rc.join(e,"metadata.json");return ql.parse(JSON.parse(ga.readFileSync(r,"utf-8")))}catch{throw new fb(t,e)}}function oD(t,e,r){let n=PX(),o=t.child({runGroupId:n});ga.rmSync(e,{recursive:!0,force:!0});let i=ga.readdirSync(r).filter(c=>!tD.has(c)).map(c=>Rc.join(r,c));if(i.length===0)throw new Error(`No run groups found in results path: ${r}`);ga.mkdirSync(e,{recursive:!0});let a={...nD(r,i[0]),id:n};for(let c of i){let l=Rc.join(c,"runs");if(!ga.existsSync(l))continue;let u=nD(r,c);o.info({oldRunGroupId:u.id},"Merging run groups");for(let p in u){if(p==="id")continue;let m=p;a[m]=MX(a,u,m)}let d=ga.readdirSync(l);for(let p of d){if(tD.has(p))continue;let m=Rc.join(l,p),f=Rc.join(e,"runs",p);ga.cpSync(m,f,{recursive:!0})}}let s=Rc.join(e,"metadata.json");ga.writeFileSync(s,JSON.stringify(a,null,2))}import GD from"adm-zip";import Ub from"fs";import{z as yJ}from"zod";var Y="v1",hb="cli",Ls="2.72.1";var OX=9e4,LX=3,NX=1500,DX=15e3,Co=class extends Error{status;rawError;constructor(e,r,n,o={}){super(n,o),this.status=e,this.rawError=r}};async function kX(t){return t.text().then(e=>{try{return JSON.parse(e).error}catch{return e}})}var gb=class{baseUrl;logger;constructor(e){this.baseUrl=e.baseUrl,this.logger=e.logger}getHeaders(){let e={"Content-Type":"application/json"};return Ls&&(e[qm]=Ls),hb&&(e[__]=hb),e}async sendRequest(e,r){let{retries:n=LX,requestTimeoutMs:o=OX,initialRetryDelayMs:i=NX,maxRetryDelayMs:a=DX,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 aa),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 kX(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 gb{apiKey;mode;constructor(e){super(e),this.apiKey=e.apiKey,this.mode=e.mode}getHeaders(){return{...super.getHeaders(),Authorization:`Bearer ${this.apiKey}`,[x_]:this.mode??""}}};import{createAnthropic as SJ}from"@ai-sdk/anthropic";import{InvalidArgumentError as FX}from"@ai-sdk/provider";import{APICallError as $Ve}from"@ai-sdk/provider";import{APICallError as zX}from"@ai-sdk/provider";import{LoadAPIKeyError as kh}from"@ai-sdk/provider";import{LoadSettingError as XVe}from"@ai-sdk/provider";import{JSONParseError as zh,TypeValidationError as $X}from"@ai-sdk/provider";import{TypeValidationError as bb}from"@ai-sdk/provider";import{TypeValidationError as XX}from"@ai-sdk/provider";var Nh=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 Sb(t){}function iD(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=Sb,onError:r=Sb,onRetry:n=Sb,onComment:o}=t,i="",a=!0,s,c="",l="";function u(h){let S=a?h.replace(/^\xEF\xBB\xBF/,""):h,[g,E]=UX(`${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 Nh(`Invalid \`retry\` value: "${S}"`,{type:"invalid-retry",value:S,line:g}));break;default:r(new Nh(`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 UX(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 RD({functionality:"tool messages"});default:{let a=o;throw new Error(`Unsupported role: ${a}`)}}return n+=`${r}:
|
|
87
87
|
`,{prompt:n,stopSequences:[`
|
|
88
|
-
${e}:`]}}function wD({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 xD(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 u3=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()}))),d3=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()}),Ob]))),_D=Tt(()=>Ee(Yo.object({echo:Yo.boolean().optional(),logitBias:Yo.record(Yo.string(),Yo.number()).optional(),suffix:Yo.string().optional(),user:Yo.string().optional(),logprobs:Yo.union([Yo.boolean(),Yo.number()]).optional()}))),p3=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 Xr({provider:"openai",providerOptions:p,schema:_D}),...await Xr({provider:this.providerOptionsName,providerOptions:p,schema:_D})};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}=c3({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 Jr({url:this.config.url({path:"/completions",modelId:this.modelId}),headers:br(this.config.headers(),t.headers),body:o,failedResponseHandler:Xo,successfulResponseHandler:to(u3),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:xD(l.finish_reason),request:{body:o},response:{...wD(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 Jr({url:this.config.url({path:"/completions",modelId:this.modelId}),headers:br(this.config.headers(),t.headers),body:n,failedResponseHandler:Xo,successfulResponseHandler:xc(d3),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",...wD(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=xD(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}}}},f3=Tt(()=>Ee(Ib.object({dimensions:Ib.number().optional(),user:Ib.string().optional()}))),h3=Tt(()=>Ee(Ns.object({data:Ns.array(Ns.object({embedding:Ns.array(Ns.number())})),usage:Ns.object({prompt_tokens:Ns.number()}).nullish()}))),g3=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 m3({provider:this.provider,modelId:this.modelId,maxEmbeddingsPerCall:this.maxEmbeddingsPerCall,values:t});let i=(o=await Xr({provider:"openai",providerOptions:n,schema:f3}))!=null?o:{},{responseHeaders:a,value:s,rawValue:c}=await Jr({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:Xo,successfulResponseHandler:to(h3),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}}}},S3=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()}))),y3={"dall-e-3":1,"dall-e-2":10,"gpt-image-1":10,"gpt-image-1-mini":10,"gpt-image-1.5":10},E3=new Set(["gpt-image-1","gpt-image-1-mini","gpt-image-1.5"]),T3=class{constructor(t,e){this.modelId=t,this.config=e,this.specificationVersion="v2"}get maxImagesPerCall(){var t;return(t=y3[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 Jr({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:{},...E3.has(this.modelId)?{}:{response_format:"b64_json"}},failedResponseHandler:Xo,successfulResponseHandler:to(S3),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}:{}}))}}}}},b3=Bt(()=>Ee(cr.object({code:cr.string().nullish(),containerId:cr.string()}))),v3=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()}))),A3=Bt(()=>Ee(cr.object({container:cr.union([cr.string(),cr.object({fileIds:cr.array(cr.string()).optional()})]).optional()}))),C3=eo({id:"openai.code_interpreter",name:"code_interpreter",inputSchema:b3,outputSchema:v3}),R3=(t={})=>C3(t),DD=Xe.object({key:Xe.string(),type:Xe.enum(["eq","ne","gt","gte","lt","lte","in","nin"]),value:Xe.union([Xe.string(),Xe.number(),Xe.boolean(),Xe.array(Xe.string())])}),kD=Xe.object({type:Xe.enum(["and","or"]),filters:Xe.array(Xe.union([DD,Xe.lazy(()=>kD)]))}),w3=Bt(()=>Ee(Xe.object({vectorStoreIds:Xe.array(Xe.string()),maxNumResults:Xe.number().optional(),ranking:Xe.object({ranker:Xe.string().optional(),scoreThreshold:Xe.number().optional()}).optional(),filters:Xe.union([DD,kD]).optional()}))),x3=Bt(()=>Ee(Xe.object({queries:Xe.array(Xe.string()),results:Xe.array(Xe.object({attributes:Xe.record(Xe.string(),Xe.unknown()),fileId:Xe.string(),filename:Xe.string(),score:Xe.number(),text:Xe.string()})).nullable()}))),_3=eo({id:"openai.file_search",name:"file_search",inputSchema:Xe.object({}),outputSchema:x3}),I3=Bt(()=>Ee(Dr.object({background:Dr.enum(["auto","opaque","transparent"]).optional(),inputFidelity:Dr.enum(["low","high"]).optional(),inputImageMask:Dr.object({fileId:Dr.string().optional(),imageUrl:Dr.string().optional()}).optional(),model:Dr.string().optional(),moderation:Dr.enum(["auto"]).optional(),outputCompression:Dr.number().int().min(0).max(100).optional(),outputFormat:Dr.enum(["png","jpeg","webp"]).optional(),partialImages:Dr.number().int().min(0).max(3).optional(),quality:Dr.enum(["auto","low","medium","high"]).optional(),size:Dr.enum(["1024x1024","1024x1536","1536x1024","auto"]).optional()}).strict())),P3=Bt(()=>Ee(Dr.object({}))),M3=Bt(()=>Ee(Dr.object({result:Dr.string()}))),O3=eo({id:"openai.image_generation",name:"image_generation",inputSchema:P3,outputSchema:M3}),L3=(t={})=>O3(t),UD=Bt(()=>Ee(Cn.object({action:Cn.object({type:Cn.literal("exec"),command:Cn.array(Cn.string()),timeoutMs:Cn.number().optional(),user:Cn.string().optional(),workingDirectory:Cn.string().optional(),env:Cn.record(Cn.string(),Cn.string()).optional()})}))),FD=Bt(()=>Ee(Cn.object({output:Cn.string()}))),N3=eo({id:"openai.local_shell",name:"local_shell",inputSchema:UD,outputSchema:FD}),D3=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()}))),k3=Bt(()=>Ee(it.object({}))),U3=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()}))),F3=eo({id:"openai.web_search",name:"web_search",inputSchema:k3,outputSchema:U3}),B3=(t={})=>F3(t),z3=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()}))),H3=Bt(()=>Ee($t.object({}))),G3=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()})])}))),j3=eo({id:"openai.web_search_preview",name:"web_search_preview",inputSchema:H3,outputSchema:G3}),V3={codeInterpreter:R3,fileSearch:_3,imageGeneration:L3,localShell:N3,webSearchPreview:j3,webSearch:B3};function ID(t,e){return e?e.some(r=>t.startsWith(r)):!1}async function q3({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"&&ID(m.data,r)?{file_id:m.data}:{image_url:`data:${E};base64,${Sa(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"&&ID(m.data,r)?{file_id:m.data}:{filename:(g=m.filename)!=null?g:`part-${f}.pdf`,file_data:`data:application/pdf;base64,${Sa(m.data)}`}};throw new $3({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 Ko({value:h.input,schema:UD});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 Xr({provider:"openai",providerOptions:h.providerOptions,schema:K3}),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 Ko({value:f.value,schema:FD});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 K3=Pb.object({itemId:Pb.string().nullish(),reasoningEncryptedContent:Pb.string().nullish()});function PD({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 Y3=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}))]))),X3=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()}))),BD=20,J3=["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"],r$e=["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",...J3],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(BD)]).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 eJ({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 Ko({value:a.args,schema:w3});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 Ko({value:a.args,schema:z3});o.push({type:"web_search_preview",search_context_size:s.searchContextSize,user_location:s.userLocation});break}case"openai.web_search":{let s=await Ko({value:a.args,schema:D3});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 Ko({value:a.args,schema:A3});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 Ko({value:a.args,schema:I3});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 Z3({functionality:`tool choice type: ${a}`})}}}var tJ=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=ND(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 Xr({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 q3({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?BD: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 U=y?.store;U===!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:U,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 eJ({tools:u,toolChoice:d,strictJsonSchema:I});return{webSearchToolName:B,args:{...G,tools:z,tool_choice:ae},warnings:[...g,...W],store:U}}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,U;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 Jr({url:W,headers:br(this.config.headers(),t.headers),body:G,failedResponseHandler:Xo,successfulResponseHandler:to(X3),abortSignal:t.abortSignal,fetch:this.config.fetch});if(ne.error)throw new W3({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:An(),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:An(),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:An(),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:An(),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:OD(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:PD({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:(U=(B=ve.input_tokens_details)==null?void 0:B.cached_tokens)!=null?U: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 Jr({url:this.config.url({path:"/responses",modelId:this.modelId}),headers:br(this.config.headers(),t.headers),body:{...e,stream:!0},failedResponseHandler:Xo,successfulResponseHandler:xc(Y3),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,U,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(MD(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}}})):MD(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(nJ(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:OD(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(([pn,Mo])=>Mo==="active"||Mo==="can-conclude").map(([pn])=>pn);for(let pn of Ae)y.enqueue({type:"reasoning-end",id:`${x.item.id}:${pn}`,providerMetadata:{[c]:{itemId:x.item.id,reasoningEncryptedContent:(_=x.item.encrypted_content)!=null?_:null}}});delete S[x.item.id]}}else if(aJ(x)){let se=m[x.output_index];se!=null&&y.enqueue({type:"tool-input-delta",id:se.toolCallId,delta:x.delta})}else if(sJ(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(lJ(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(iJ(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(rJ(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":oJ(x)?(l=PD({finishReason:(U=x.response.incomplete_details)==null?void 0:U.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)):cJ(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:An(),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:An(),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}}}:{}})):uJ(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 rJ(t){return t.type==="response.output_text.delta"}function nJ(t){return t.type==="response.output_item.done"}function oJ(t){return t.type==="response.completed"||t.type==="response.incomplete"}function iJ(t){return t.type==="response.created"}function aJ(t){return t.type==="response.function_call_arguments.delta"}function sJ(t){return t.type==="response.code_interpreter_call_code.delta"}function lJ(t){return t.type==="response.code_interpreter_call_code.done"}function MD(t){return t.type==="response.output_item.added"}function cJ(t){return t.type==="response.output_text.annotation.added"}function uJ(t){return t.type==="error"}function OD(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 dJ=Tt(()=>Ee(Mb.object({instructions:Mb.string().nullish(),speed:Mb.number().min(.25).max(4).default(1).nullish()}))),pJ=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 Xr({provider:"openai",providerOptions:a,schema:dJ}),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 Jr({url:this.config.url({path:"/audio/speech",modelId:this.modelId}),headers:br(this.config.headers(),t.headers),body:i,failedResponseHandler:Xo,successfulResponseHandler:gD(),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}}}},mJ=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()}))),fJ=Tt(()=>Ee(Ea.object({include:Ea.array(Ea.string()).optional(),language:Ea.string().optional(),prompt:Ea.string().optional(),temperature:Ea.number().min(0).max(1).default(0).optional(),timestampGranularities:Ea.array(Ea.enum(["word","segment"])).default(["segment"]).optional()}))),LD={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"},hJ=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 Xr({provider:"openai",providerOptions:r,schema:fJ}),i=new FormData,a=t instanceof Uint8Array?new Blob([t]):new Blob([vD(t)]);i.append("model",this.modelId);let s=dD(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 mD({url:this.config.url({path:"/audio/transcriptions",modelId:this.modelId}),headers:br(this.config.headers(),t.headers),formData:u,failedResponseHandler:Xo,successfulResponseHandler:to(mJ),abortSignal:t.abortSignal,fetch:this.config.fetch}),h=p.language!=null&&p.language in LD?LD[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}}}},gJ="2.0.89";function Lb(t={}){var e,r;let n=(e=AD(uD({settingValue:t.baseURL,environmentVariableName:"OPENAI_BASE_URL"})))!=null?e:"https://api.openai.com/v1",o=(r=t.name)!=null?r:"openai",i=()=>Ab({Authorization:`Bearer ${cD({apiKey:t.apiKey,environmentVariableName:"OPENAI_API_KEY",description:"OpenAI"})}`,"OpenAI-Organization":t.organization,"OpenAI-Project":t.project,...t.headers},`ai-sdk/openai/${gJ}`),a=h=>new s3(h,{provider:`${o}.chat`,url:({path:S})=>`${n}${S}`,headers:i,fetch:t.fetch}),s=h=>new p3(h,{provider:`${o}.completion`,url:({path:S})=>`${n}${S}`,headers:i,fetch:t.fetch}),c=h=>new g3(h,{provider:`${o}.embedding`,url:({path:S})=>`${n}${S}`,headers:i,fetch:t.fetch}),l=h=>new T3(h,{provider:`${o}.image`,url:({path:S})=>`${n}${S}`,headers:i,fetch:t.fetch}),u=h=>new hJ(h,{provider:`${o}.transcription`,url:({path:S})=>`${n}${S}`,headers:i,fetch:t.fetch}),d=h=>new pJ(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 tJ(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=V3,f}var m$e=Lb();function zD(t){let{apiKey:e,sessionId:r,extraHeaders:n,loggerTags:o}=t,i={Authorization:`Bearer ${e}`,[qm]:Ls??"",...r&&{[P_]:r},...n||{}};return o&&(i[I_]=JSON.stringify(o)),i}var Vh=t=>e=>{let r=zD(t);return SJ({baseURL:`${t.baseUrl}/v1/llm/anthropic/${e}`,headers:r,apiKey:t.apiKey})(e)},Nb=t=>e=>{let r=zD(t);return Lb({baseURL:`${t.baseUrl}/v1/llm/openai/${e}`,headers:r,apiKey:t.apiKey})(e)};var un=class extends Tr{agentConfig;constructor(e,r){let n={..._l,...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 ww.parse(o)}async rankChunksWithRag(e,r){let n=await this.sendRequest(`/${Y}/web-agent/recommend-chunks`,{method:"POST",body:{cliVersion:Ls,...e},signal:r.abortSignal});return Rw.parse(n)}async getScreenshotFromS3(e){let r=await this.sendRequest(`/${Y}/s3/visual-diff-screenshot`,{method:"POST",body:{url:e}});return yJ.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 k_.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 yE.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 D_.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 O_.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 L_.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 N_.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 yE.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 M_.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 ny.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 U_.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 nm.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 ew.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 tw.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 HS.parse(n)}async getExtractedKeywords(e,r){let n=await this.sendRequest(`/${Y}/web-agent/extract-keywords`,{method:"POST",body:e,signal:r.abortSignal});return Hw.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 XR.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 QR.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 JR.parse(n)}async getIframeRegex(e,r){let n=await this.sendRequest(`/${Y}/web-agent/iframe-regex`,{method:"POST",body:e,signal:r.abortSignal});return aC.parse(n)}getAnthropicModelFactory(e){let{sessionId:r,logger:n,streamType:o}=e;return Vh({baseUrl:this.baseUrl,apiKey:this.apiKey,loggerTags:{...ot(n),promptType:o},sessionId:r})}getOpenAIModelFactory(e){let{sessionId:r,logger:n,streamType:o}=e;return Nb({baseUrl:this.baseUrl,apiKey:this.apiKey,loggerTags:{...ot(n),promptType:o},sessionId:r})}};import{z as Db}from"zod";var pt=class extends Tr{constructor(e){super({...e,mode:void 0})}getAppUrl(){return Wl(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 X_.parse(e)}async bulkGetRunStatus(e){let r=await this.sendRequest(`/${Y}/runs/status`,{method:"POST",body:e,retries:3,requestTimeoutMs:1e4});return $_.parse(r)}async getTestYAMLExport(e){let r=await this.sendRequest(`/${Y}/tests/export`,{method:"POST",body:e,retries:3,requestTimeoutMs:3e4});return B_.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 H_.parse(n)}async getWebStepCacheMemoryTraces(e){let r=await this.sendRequest(`/${Y}/cache/traces`,{method:"POST",body:e,retries:10,requestTimeoutMs:3e4,initialRetryDelayMs:3e3});return TE.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 TE.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 G_(Pm(e)).parse(o)}async queueTests(e){let r=await this.sendRequest(`/${Y}/tests/queue`,{method:"POST",body:e,retries:3,requestTimeoutMs:1e4});return F_.parse(r)}async uploadScreenshot(e){let r=await this.sendRequest(`/${Y}/screenshots`,{method:"POST",body:e,retries:3,requestTimeoutMs:5e3});return Y_.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 J_.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 hI.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 Q_.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 bw.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 Z_.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 eI.parse(n)}async generateTestResultsUploadUrl(){let e=await this.sendRequest(`/${Y}/results/uploads`,{method:"POST",retries:3,requestTimeoutMs:1e4});return tI.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 rI.parse(n)}async fetchIconKnowledgeBase(e){try{let r=await this.sendRequest(`/${Y}/knowledge-base/icons`,{method:"GET",retries:3,requestTimeoutMs:5e3});return TI.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 cd.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 cd.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 AE.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 cd.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 cd.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 AE.parse(a)}async getAgentConfig(){let e=await this.sendRequest(`/${Y}/web-agent/agent-config`,{method:"GET",retries:3,requestTimeoutMs:5e3});return Db.record(Db.string(),Db.string()).parse(e)}async getQuarantinedTests(){let e=await this.sendRequest(`/${Y}/quarantine`,{method:"GET"});return nI.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 oI.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 aI.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 sI.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 lI.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 iI.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 $x.parse(r)}};async function Wh(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 $h=class{apiClient;constructor(e){this.apiClient=e}async reportBillableEvents(e,r){await this.apiClient.reportBillableEvents(e,r)}};var Ta=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 sC.parse(n)}async constructIframeRegex(e,r={}){return this.generator.getIframeRegex(e,{abortSignal:r.signal})}};var _c=class{constructor(e,r){this.client=e;this.orgId=r}getApiServerUrl(){return this.client.baseUrl}getAppServerUrl(){let e=this.getApiServerUrl();return Wl(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 EJ,en as TJ}from"@faker-js/faker";var Ic="v1",Jo=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 EJ({locale:TJ}),this.fakerInstance.seed(e.fakerSeed))}async sendAiGenerate(e){let r=typeof e=="string"?{input:e}:e;return this.httpClient.sendRequest(`/${Ic}/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(`/${Ic}/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(`/${Ic}/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(`/${Ic}/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(`/${Ic}/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(`/${Ic}/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 HD(t,e,r){return fetch(t,{method:"PUT",body:r,headers:{"Content-Type":e}})}var qh=class{constructor(e){this.client=e}async uploadResultsArchive(e,r){let{uploadUrl:n,id:o}=await this.client.generateTestResultsUploadUrl(),i=await HD(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 Km:new kb(t,e,r,n,{regenerateCache:o,alwaysSaveCache:i,bustOldestCachePercentage:c,isolateCachesByEnvironment:s})}var kb=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=EE(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:CE(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&&hc({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 Ut({stepLists:e.stepLists,cacheCreationParams:{environment:e.environment,testId:e.testId,orgId:this.orgId}});this.saveStepCacheEntries({entries:a,logger:e.logger})}};import Kh from"path";function bJ(t){let e=new GD,r=Kh.join(t,"metadata.json"),n=ql.parse(JSON.parse(Ub.readFileSync(r,"utf-8")));e.addLocalFile(r);for(let o of Ub.readdirSync(Kh.join(t,"runs"))){if(!o.endsWith(".zip"))continue;let i=o.replace(/\.zip$/,""),a=new GD(Kh.join(t,"runs",o));for(let s of a.getEntries())s.isDirectory||e.addFile(Kh.join("runs",i,s.entryName),s.getData())}return{runGroupId:n.id,buffer:e.toBuffer()}}async function Yh(t){let{client:e,consoleLogger:r,resultsPath:n}=t;if(!Ub.existsSync(n)){r.warn("Results path does not exist, skipping upload.");return}let o=new qh(e);try{let{runGroupId:i,buffer:a}=bJ(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 vJ from"adm-zip";import kr from"fs";import ro from"path";var Zd=class t{constructor(e){this.filePath=e;kr.rmSync(this.filePath,{recursive:!0,force:!0}),kr.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(ro.join(this.filePath,e));return this.children.push(r),r}cwd(){return this.filePath}mkdir(e){kr.mkdirSync(ro.join(this.filePath,e),{recursive:!0})}readFile(e){let r=ro.join(this.filePath,e);if(kr.existsSync(r))return kr.readFileSync(r)}storeFile(e){let{name:r,contents:n}=e,o=ro.join(this.filePath,r);try{kr.writeFileSync(o,n)}catch{}}createFileStream(e){let r=ro.join(this.filePath,e),n=kr.createWriteStream(r);return this.streams.push(n),n}createRunArchive(e){let r=new Fb(ro.join(this.filePath,"runs"),e);return this.children.push(r),r}},Fb=class{children=[];tempPath;finalPath;constructor(e,r){this.tempPath=ro.join(e,`temp-storage-${r}`),this.finalPath=ro.join(e,`${r}.zip`),kr.rmSync(this.tempPath,{recursive:!0,force:!0}),kr.rmSync(this.finalPath,{recursive:!0,force:!0}),kr.mkdirSync(this.tempPath,{recursive:!0})}readFile(e){let r=ro.join(this.tempPath,e);if(kr.existsSync(r))return kr.readFileSync(r)}mkdir(e){kr.mkdirSync(ro.join(this.tempPath,e),{recursive:!0})}cd(e){let r=new Zd(ro.join(this.tempPath,e));return this.children.push(r),r}cwd(){return this.tempPath}storeFile(e){let{name:r,contents:n}=e,o=ro.join(this.tempPath,r);kr.writeFileSync(o,n)}close(){for(let n of this.children)n.close();let e=new vJ;e.addLocalFolder(this.tempPath,void 0,n=>n!==".DS_Store");let r=e.toBuffer();kr.writeFileSync(this.finalPath,r),kr.rmSync(this.tempPath,{recursive:!0,force:!0})}};import AJ from"adm-zip";import{randomUUID as CJ}from"crypto";import rr from"fs";import Ar from"path";function $D(t){try{return rr.existsSync(t)?JSON.parse(rr.readFileSync(t,"utf-8")):void 0}catch{return}}function jD(t){return rr.existsSync(t)?rr.readFileSync(t,"utf-8").split(`
|
|
88
|
+
${e}:`]}}function wD({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 xD(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 u3=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()}))),d3=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()}),Ob]))),_D=Tt(()=>Ee(Yo.object({echo:Yo.boolean().optional(),logitBias:Yo.record(Yo.string(),Yo.number()).optional(),suffix:Yo.string().optional(),user:Yo.string().optional(),logprobs:Yo.union([Yo.boolean(),Yo.number()]).optional()}))),p3=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 Xr({provider:"openai",providerOptions:p,schema:_D}),...await Xr({provider:this.providerOptionsName,providerOptions:p,schema:_D})};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}=c3({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 Jr({url:this.config.url({path:"/completions",modelId:this.modelId}),headers:br(this.config.headers(),t.headers),body:o,failedResponseHandler:Xo,successfulResponseHandler:to(u3),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:xD(l.finish_reason),request:{body:o},response:{...wD(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 Jr({url:this.config.url({path:"/completions",modelId:this.modelId}),headers:br(this.config.headers(),t.headers),body:n,failedResponseHandler:Xo,successfulResponseHandler:xc(d3),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",...wD(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=xD(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}}}},f3=Tt(()=>Ee(Ib.object({dimensions:Ib.number().optional(),user:Ib.string().optional()}))),h3=Tt(()=>Ee(Ns.object({data:Ns.array(Ns.object({embedding:Ns.array(Ns.number())})),usage:Ns.object({prompt_tokens:Ns.number()}).nullish()}))),g3=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 m3({provider:this.provider,modelId:this.modelId,maxEmbeddingsPerCall:this.maxEmbeddingsPerCall,values:t});let i=(o=await Xr({provider:"openai",providerOptions:n,schema:f3}))!=null?o:{},{responseHeaders:a,value:s,rawValue:c}=await Jr({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:Xo,successfulResponseHandler:to(h3),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}}}},S3=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()}))),y3={"dall-e-3":1,"dall-e-2":10,"gpt-image-1":10,"gpt-image-1-mini":10,"gpt-image-1.5":10},E3=new Set(["gpt-image-1","gpt-image-1-mini","gpt-image-1.5"]),T3=class{constructor(t,e){this.modelId=t,this.config=e,this.specificationVersion="v2"}get maxImagesPerCall(){var t;return(t=y3[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 Jr({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:{},...E3.has(this.modelId)?{}:{response_format:"b64_json"}},failedResponseHandler:Xo,successfulResponseHandler:to(S3),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}:{}}))}}}}},b3=Bt(()=>Ee(cr.object({code:cr.string().nullish(),containerId:cr.string()}))),v3=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()}))),A3=Bt(()=>Ee(cr.object({container:cr.union([cr.string(),cr.object({fileIds:cr.array(cr.string()).optional()})]).optional()}))),C3=eo({id:"openai.code_interpreter",name:"code_interpreter",inputSchema:b3,outputSchema:v3}),R3=(t={})=>C3(t),DD=Xe.object({key:Xe.string(),type:Xe.enum(["eq","ne","gt","gte","lt","lte","in","nin"]),value:Xe.union([Xe.string(),Xe.number(),Xe.boolean(),Xe.array(Xe.string())])}),kD=Xe.object({type:Xe.enum(["and","or"]),filters:Xe.array(Xe.union([DD,Xe.lazy(()=>kD)]))}),w3=Bt(()=>Ee(Xe.object({vectorStoreIds:Xe.array(Xe.string()),maxNumResults:Xe.number().optional(),ranking:Xe.object({ranker:Xe.string().optional(),scoreThreshold:Xe.number().optional()}).optional(),filters:Xe.union([DD,kD]).optional()}))),x3=Bt(()=>Ee(Xe.object({queries:Xe.array(Xe.string()),results:Xe.array(Xe.object({attributes:Xe.record(Xe.string(),Xe.unknown()),fileId:Xe.string(),filename:Xe.string(),score:Xe.number(),text:Xe.string()})).nullable()}))),_3=eo({id:"openai.file_search",name:"file_search",inputSchema:Xe.object({}),outputSchema:x3}),I3=Bt(()=>Ee(Dr.object({background:Dr.enum(["auto","opaque","transparent"]).optional(),inputFidelity:Dr.enum(["low","high"]).optional(),inputImageMask:Dr.object({fileId:Dr.string().optional(),imageUrl:Dr.string().optional()}).optional(),model:Dr.string().optional(),moderation:Dr.enum(["auto"]).optional(),outputCompression:Dr.number().int().min(0).max(100).optional(),outputFormat:Dr.enum(["png","jpeg","webp"]).optional(),partialImages:Dr.number().int().min(0).max(3).optional(),quality:Dr.enum(["auto","low","medium","high"]).optional(),size:Dr.enum(["1024x1024","1024x1536","1536x1024","auto"]).optional()}).strict())),P3=Bt(()=>Ee(Dr.object({}))),M3=Bt(()=>Ee(Dr.object({result:Dr.string()}))),O3=eo({id:"openai.image_generation",name:"image_generation",inputSchema:P3,outputSchema:M3}),L3=(t={})=>O3(t),UD=Bt(()=>Ee(Cn.object({action:Cn.object({type:Cn.literal("exec"),command:Cn.array(Cn.string()),timeoutMs:Cn.number().optional(),user:Cn.string().optional(),workingDirectory:Cn.string().optional(),env:Cn.record(Cn.string(),Cn.string()).optional()})}))),FD=Bt(()=>Ee(Cn.object({output:Cn.string()}))),N3=eo({id:"openai.local_shell",name:"local_shell",inputSchema:UD,outputSchema:FD}),D3=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()}))),k3=Bt(()=>Ee(it.object({}))),U3=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()}))),F3=eo({id:"openai.web_search",name:"web_search",inputSchema:k3,outputSchema:U3}),B3=(t={})=>F3(t),z3=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()}))),H3=Bt(()=>Ee($t.object({}))),G3=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()})])}))),j3=eo({id:"openai.web_search_preview",name:"web_search_preview",inputSchema:H3,outputSchema:G3}),V3={codeInterpreter:R3,fileSearch:_3,imageGeneration:L3,localShell:N3,webSearchPreview:j3,webSearch:B3};function ID(t,e){return e?e.some(r=>t.startsWith(r)):!1}async function q3({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"&&ID(m.data,r)?{file_id:m.data}:{image_url:`data:${E};base64,${Sa(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"&&ID(m.data,r)?{file_id:m.data}:{filename:(g=m.filename)!=null?g:`part-${f}.pdf`,file_data:`data:application/pdf;base64,${Sa(m.data)}`}};throw new $3({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 Ko({value:h.input,schema:UD});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 Xr({provider:"openai",providerOptions:h.providerOptions,schema:K3}),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 Ko({value:f.value,schema:FD});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 K3=Pb.object({itemId:Pb.string().nullish(),reasoningEncryptedContent:Pb.string().nullish()});function PD({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 Y3=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}))]))),X3=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()}))),BD=20,J3=["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"],n$e=["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",...J3],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(BD)]).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 eJ({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 Ko({value:a.args,schema:w3});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 Ko({value:a.args,schema:z3});o.push({type:"web_search_preview",search_context_size:s.searchContextSize,user_location:s.userLocation});break}case"openai.web_search":{let s=await Ko({value:a.args,schema:D3});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 Ko({value:a.args,schema:A3});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 Ko({value:a.args,schema:I3});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 Z3({functionality:`tool choice type: ${a}`})}}}var tJ=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=ND(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 Xr({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 q3({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?BD: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 U=y?.store;U===!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:U,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 eJ({tools:u,toolChoice:d,strictJsonSchema:I});return{webSearchToolName:B,args:{...G,tools:z,tool_choice:ae},warnings:[...g,...W],store:U}}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,U;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 Jr({url:W,headers:br(this.config.headers(),t.headers),body:G,failedResponseHandler:Xo,successfulResponseHandler:to(X3),abortSignal:t.abortSignal,fetch:this.config.fetch});if(ne.error)throw new W3({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:An(),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:An(),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:An(),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:An(),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:OD(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:PD({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:(U=(B=ve.input_tokens_details)==null?void 0:B.cached_tokens)!=null?U: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 Jr({url:this.config.url({path:"/responses",modelId:this.modelId}),headers:br(this.config.headers(),t.headers),body:{...e,stream:!0},failedResponseHandler:Xo,successfulResponseHandler:xc(Y3),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,U,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(MD(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}}})):MD(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(nJ(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:OD(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(([pn,Mo])=>Mo==="active"||Mo==="can-conclude").map(([pn])=>pn);for(let pn of Ae)y.enqueue({type:"reasoning-end",id:`${x.item.id}:${pn}`,providerMetadata:{[c]:{itemId:x.item.id,reasoningEncryptedContent:(_=x.item.encrypted_content)!=null?_:null}}});delete S[x.item.id]}}else if(aJ(x)){let se=m[x.output_index];se!=null&&y.enqueue({type:"tool-input-delta",id:se.toolCallId,delta:x.delta})}else if(sJ(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(lJ(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(iJ(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(rJ(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":oJ(x)?(l=PD({finishReason:(U=x.response.incomplete_details)==null?void 0:U.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)):cJ(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:An(),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:An(),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}}}:{}})):uJ(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 rJ(t){return t.type==="response.output_text.delta"}function nJ(t){return t.type==="response.output_item.done"}function oJ(t){return t.type==="response.completed"||t.type==="response.incomplete"}function iJ(t){return t.type==="response.created"}function aJ(t){return t.type==="response.function_call_arguments.delta"}function sJ(t){return t.type==="response.code_interpreter_call_code.delta"}function lJ(t){return t.type==="response.code_interpreter_call_code.done"}function MD(t){return t.type==="response.output_item.added"}function cJ(t){return t.type==="response.output_text.annotation.added"}function uJ(t){return t.type==="error"}function OD(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 dJ=Tt(()=>Ee(Mb.object({instructions:Mb.string().nullish(),speed:Mb.number().min(.25).max(4).default(1).nullish()}))),pJ=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 Xr({provider:"openai",providerOptions:a,schema:dJ}),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 Jr({url:this.config.url({path:"/audio/speech",modelId:this.modelId}),headers:br(this.config.headers(),t.headers),body:i,failedResponseHandler:Xo,successfulResponseHandler:gD(),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}}}},mJ=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()}))),fJ=Tt(()=>Ee(Ea.object({include:Ea.array(Ea.string()).optional(),language:Ea.string().optional(),prompt:Ea.string().optional(),temperature:Ea.number().min(0).max(1).default(0).optional(),timestampGranularities:Ea.array(Ea.enum(["word","segment"])).default(["segment"]).optional()}))),LD={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"},hJ=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 Xr({provider:"openai",providerOptions:r,schema:fJ}),i=new FormData,a=t instanceof Uint8Array?new Blob([t]):new Blob([vD(t)]);i.append("model",this.modelId);let s=dD(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 mD({url:this.config.url({path:"/audio/transcriptions",modelId:this.modelId}),headers:br(this.config.headers(),t.headers),formData:u,failedResponseHandler:Xo,successfulResponseHandler:to(mJ),abortSignal:t.abortSignal,fetch:this.config.fetch}),h=p.language!=null&&p.language in LD?LD[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}}}},gJ="2.0.89";function Lb(t={}){var e,r;let n=(e=AD(uD({settingValue:t.baseURL,environmentVariableName:"OPENAI_BASE_URL"})))!=null?e:"https://api.openai.com/v1",o=(r=t.name)!=null?r:"openai",i=()=>Ab({Authorization:`Bearer ${cD({apiKey:t.apiKey,environmentVariableName:"OPENAI_API_KEY",description:"OpenAI"})}`,"OpenAI-Organization":t.organization,"OpenAI-Project":t.project,...t.headers},`ai-sdk/openai/${gJ}`),a=h=>new s3(h,{provider:`${o}.chat`,url:({path:S})=>`${n}${S}`,headers:i,fetch:t.fetch}),s=h=>new p3(h,{provider:`${o}.completion`,url:({path:S})=>`${n}${S}`,headers:i,fetch:t.fetch}),c=h=>new g3(h,{provider:`${o}.embedding`,url:({path:S})=>`${n}${S}`,headers:i,fetch:t.fetch}),l=h=>new T3(h,{provider:`${o}.image`,url:({path:S})=>`${n}${S}`,headers:i,fetch:t.fetch}),u=h=>new hJ(h,{provider:`${o}.transcription`,url:({path:S})=>`${n}${S}`,headers:i,fetch:t.fetch}),d=h=>new pJ(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 tJ(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=V3,f}var f$e=Lb();function zD(t){let{apiKey:e,sessionId:r,extraHeaders:n,loggerTags:o}=t,i={Authorization:`Bearer ${e}`,[qm]:Ls??"",...r&&{[P_]:r},...n||{}};return o&&(i[I_]=JSON.stringify(o)),i}var Vh=t=>e=>{let r=zD(t);return SJ({baseURL:`${t.baseUrl}/v1/llm/anthropic/${e}`,headers:r,apiKey:t.apiKey})(e)},Nb=t=>e=>{let r=zD(t);return Lb({baseURL:`${t.baseUrl}/v1/llm/openai/${e}`,headers:r,apiKey:t.apiKey})(e)};var un=class extends Tr{agentConfig;constructor(e,r){let n={..._l,...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 ww.parse(o)}async rankChunksWithRag(e,r){let n=await this.sendRequest(`/${Y}/web-agent/recommend-chunks`,{method:"POST",body:{cliVersion:Ls,...e},signal:r.abortSignal});return Rw.parse(n)}async getScreenshotFromS3(e){let r=await this.sendRequest(`/${Y}/s3/visual-diff-screenshot`,{method:"POST",body:{url:e}});return yJ.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 k_.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 yE.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 D_.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 O_.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 L_.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 N_.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 yE.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 M_.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 ny.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 U_.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 nm.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 ew.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 tw.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 HS.parse(n)}async getExtractedKeywords(e,r){let n=await this.sendRequest(`/${Y}/web-agent/extract-keywords`,{method:"POST",body:e,signal:r.abortSignal});return Hw.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 XR.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 QR.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 JR.parse(n)}async getIframeRegex(e,r){let n=await this.sendRequest(`/${Y}/web-agent/iframe-regex`,{method:"POST",body:e,signal:r.abortSignal});return aC.parse(n)}getAnthropicModelFactory(e){let{sessionId:r,logger:n,streamType:o}=e;return Vh({baseUrl:this.baseUrl,apiKey:this.apiKey,loggerTags:{...ot(n),promptType:o},sessionId:r})}getOpenAIModelFactory(e){let{sessionId:r,logger:n,streamType:o}=e;return Nb({baseUrl:this.baseUrl,apiKey:this.apiKey,loggerTags:{...ot(n),promptType:o},sessionId:r})}};import{z as Db}from"zod";var pt=class extends Tr{constructor(e){super({...e,mode:void 0})}getAppUrl(){return Wl(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 X_.parse(e)}async bulkGetRunStatus(e){let r=await this.sendRequest(`/${Y}/runs/status`,{method:"POST",body:e,retries:3,requestTimeoutMs:1e4});return $_.parse(r)}async getTestYAMLExport(e){let r=await this.sendRequest(`/${Y}/tests/export`,{method:"POST",body:e,retries:3,requestTimeoutMs:3e4});return B_.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 H_.parse(n)}async getWebStepCacheMemoryTraces(e){let r=await this.sendRequest(`/${Y}/cache/traces`,{method:"POST",body:e,retries:10,requestTimeoutMs:3e4,initialRetryDelayMs:3e3});return TE.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 TE.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 G_(Pm(e)).parse(o)}async queueTests(e){let r=await this.sendRequest(`/${Y}/tests/queue`,{method:"POST",body:e,retries:3,requestTimeoutMs:1e4});return F_.parse(r)}async uploadScreenshot(e){let r=await this.sendRequest(`/${Y}/screenshots`,{method:"POST",body:e,retries:3,requestTimeoutMs:5e3});return Y_.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 J_.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 hI.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 Q_.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 bw.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 Z_.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 eI.parse(n)}async generateTestResultsUploadUrl(){let e=await this.sendRequest(`/${Y}/results/uploads`,{method:"POST",retries:3,requestTimeoutMs:1e4});return tI.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 rI.parse(n)}async fetchIconKnowledgeBase(e){try{let r=await this.sendRequest(`/${Y}/knowledge-base/icons`,{method:"GET",retries:3,requestTimeoutMs:5e3});return TI.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 cd.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 cd.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 AE.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 cd.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 cd.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 AE.parse(a)}async getAgentConfig(){let e=await this.sendRequest(`/${Y}/web-agent/agent-config`,{method:"GET",retries:3,requestTimeoutMs:5e3});return Db.record(Db.string(),Db.string()).parse(e)}async getQuarantinedTests(){let e=await this.sendRequest(`/${Y}/quarantine`,{method:"GET"});return nI.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 oI.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 aI.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 sI.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 lI.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 iI.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 $x.parse(r)}};async function Wh(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 $h=class{apiClient;constructor(e){this.apiClient=e}async reportBillableEvents(e,r){await this.apiClient.reportBillableEvents(e,r)}};var Ta=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 sC.parse(n)}async constructIframeRegex(e,r={}){return this.generator.getIframeRegex(e,{abortSignal:r.signal})}};var _c=class{constructor(e,r){this.client=e;this.orgId=r}getApiServerUrl(){return this.client.baseUrl}getAppServerUrl(){let e=this.getApiServerUrl();return Wl(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 EJ,en as TJ}from"@faker-js/faker";var Ic="v1",Jo=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 EJ({locale:TJ}),this.fakerInstance.seed(e.fakerSeed))}async sendAiGenerate(e){let r=typeof e=="string"?{input:e}:e;return this.httpClient.sendRequest(`/${Ic}/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(`/${Ic}/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(`/${Ic}/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(`/${Ic}/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(`/${Ic}/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(`/${Ic}/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 HD(t,e,r){return fetch(t,{method:"PUT",body:r,headers:{"Content-Type":e}})}var qh=class{constructor(e){this.client=e}async uploadResultsArchive(e,r){let{uploadUrl:n,id:o}=await this.client.generateTestResultsUploadUrl(),i=await HD(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 Km:new kb(t,e,r,n,{regenerateCache:o,alwaysSaveCache:i,bustOldestCachePercentage:c,isolateCachesByEnvironment:s})}var kb=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=EE(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:CE(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&&hc({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 Ut({stepLists:e.stepLists,cacheCreationParams:{environment:e.environment,testId:e.testId,orgId:this.orgId}});this.saveStepCacheEntries({entries:a,logger:e.logger})}};import Kh from"path";function bJ(t){let e=new GD,r=Kh.join(t,"metadata.json"),n=ql.parse(JSON.parse(Ub.readFileSync(r,"utf-8")));e.addLocalFile(r);for(let o of Ub.readdirSync(Kh.join(t,"runs"))){if(!o.endsWith(".zip"))continue;let i=o.replace(/\.zip$/,""),a=new GD(Kh.join(t,"runs",o));for(let s of a.getEntries())s.isDirectory||e.addFile(Kh.join("runs",i,s.entryName),s.getData())}return{runGroupId:n.id,buffer:e.toBuffer()}}async function Yh(t){let{client:e,consoleLogger:r,resultsPath:n}=t;if(!Ub.existsSync(n)){r.warn("Results path does not exist, skipping upload.");return}let o=new qh(e);try{let{runGroupId:i,buffer:a}=bJ(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 vJ from"adm-zip";import kr from"fs";import ro from"path";var Zd=class t{constructor(e){this.filePath=e;kr.rmSync(this.filePath,{recursive:!0,force:!0}),kr.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(ro.join(this.filePath,e));return this.children.push(r),r}cwd(){return this.filePath}mkdir(e){kr.mkdirSync(ro.join(this.filePath,e),{recursive:!0})}readFile(e){let r=ro.join(this.filePath,e);if(kr.existsSync(r))return kr.readFileSync(r)}storeFile(e){let{name:r,contents:n}=e,o=ro.join(this.filePath,r);try{kr.writeFileSync(o,n)}catch{}}createFileStream(e){let r=ro.join(this.filePath,e),n=kr.createWriteStream(r);return this.streams.push(n),n}createRunArchive(e){let r=new Fb(ro.join(this.filePath,"runs"),e);return this.children.push(r),r}},Fb=class{children=[];tempPath;finalPath;constructor(e,r){this.tempPath=ro.join(e,`temp-storage-${r}`),this.finalPath=ro.join(e,`${r}.zip`),kr.rmSync(this.tempPath,{recursive:!0,force:!0}),kr.rmSync(this.finalPath,{recursive:!0,force:!0}),kr.mkdirSync(this.tempPath,{recursive:!0})}readFile(e){let r=ro.join(this.tempPath,e);if(kr.existsSync(r))return kr.readFileSync(r)}mkdir(e){kr.mkdirSync(ro.join(this.tempPath,e),{recursive:!0})}cd(e){let r=new Zd(ro.join(this.tempPath,e));return this.children.push(r),r}cwd(){return this.tempPath}storeFile(e){let{name:r,contents:n}=e,o=ro.join(this.tempPath,r);kr.writeFileSync(o,n)}close(){for(let n of this.children)n.close();let e=new vJ;e.addLocalFolder(this.tempPath,void 0,n=>n!==".DS_Store");let r=e.toBuffer();kr.writeFileSync(this.finalPath,r),kr.rmSync(this.tempPath,{recursive:!0,force:!0})}};import AJ from"adm-zip";import{randomUUID as CJ}from"crypto";import rr from"fs";import Ar from"path";function $D(t){try{return rr.existsSync(t)?JSON.parse(rr.readFileSync(t,"utf-8")):void 0}catch{return}}function jD(t){return rr.existsSync(t)?rr.readFileSync(t,"utf-8").split(`
|
|
89
89
|
`).map(r=>r.trim()).filter(r=>r.length>0):[]}function RJ(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=$D(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 VD(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 Xh=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}-${CJ()}`);rr.mkdirSync(n,{recursive:!0}),new AJ(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 RJ(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=$D(Ar.join(o,"console.json")),a=lE.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 jD(i)){let d=od.safeParse(WD(u));d.success&&(s[d.data.id]=d.data)}let c={},l=jD(a);for(let u=0;u<l.length;u++){let d=l[u],p=id.safeParse(WD(d));if(!p.success)continue;let m=`${p.data.startedDateTime}-${u}`;c[m]=p.data}if(Object.keys(c).length!==0)return uE(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=VD(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=VD(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 WD(t){try{return JSON.parse(t)}catch{return}}function Jh({test:t,envNameOverride:e,urlOverride:r,resolveEnv:n}){let o=e??wJ(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 wJ(t){for(let e of t.envs??[])if(e.default)return e.name}var xJ={test:"tests",module:"modules",mobileTest:"mobileTests",mobileModule:"mobileModules"};async function ba(t,e,r){let n=await fe(t),o=n[xJ[r]],i=_J(o,e);if(e.id){if(i.length===0)throw new or(`No ${r} found with id '${e.id}' in project '${t.rootDir}'.`);return Qh(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 Qh(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 Qh(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 Qh(i,n)}throw new Error("No valid selector field provided. Exactly one of id, name, or path must be specified.")}function Qh(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 _J(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 Zh from"fs";import IJ from"path";var PJ=new gh(30,60*1e3),tg="https://api.momentic.ai",zb,qD,rg=t=>{tg=t},qt=()=>tg,KD=()=>Wl(tg),ng=t=>{qD=t},Ds=()=>qD,Mc=()=>zb;var Pc,Hb,eg,og=async t=>{if(zb&&Pc&&eg)return Pc;let e=new pt({baseUrl:tg,apiKey:t,logger:v});zb=e;try{let r=await e.getAuthInfo();return Pc=r.orgId,Hb=r.userId,eg=t,Pc}catch(r){throw new Error(`Error checking API key against server: ${r}`,{cause:r})}},Kt=()=>{if(!Pc)throw new Error("Your organization ID is invalid.");return Pc},Qo=()=>{if(!Hb)throw new Error("Your user ID is invalid.");return Hb},Cr=()=>{if(!eg)throw new Error("Your API key is invalid.");return eg},Gb,Bb,Oc=(t,e)=>{Gb=t,Bb?.abort(),Bb=new AbortController;let r=Bb.signal,n=[t.configFilePath];t.config.environments?.forEach(o=>{if(!o.envFile)return;let i=IJ.resolve(t.rootDir,o.envFile);try{if(Zh.lstatSync(i).isSymbolicLink())return;Zh.existsSync(i)&&n.push(i)}catch(a){v.warn({err:a},`Failed to check if env file ${i} exists`)}});try{MJ({filesToWatch:n,revalidator:e,signal:r,project:t})}catch(o){v.error({err:o},"Failed to start config file watchers")}},Re=()=>Gb;function MJ({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()&&(PJ.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.`),Gb=await Promise.resolve(e(n.configFilePath)))};Zh.watchFile(o,{persistent:!1},i);let a=()=>{Zh.unwatchFile(o,i),r.removeEventListener("abort",a)};r.addEventListener("abort",a),process.once("SIGUSR2",()=>{a(),process.kill(process.pid,"SIGUSR2")})})}function Ge(t){return function(...e){let r=e[e.length-1],n=t(...e);Promise.resolve(n).catch(r)}}import{hostname as OJ}from"os";var LJ="2.72.0",ks=Yl({app:"desktop-server",hostname:OJ(),disableConsoleLogs:!0,captureExceptions:!0}).child({cliVersion:LJ});(async()=>{try{let t=await Ii(ks);t.gitBranchName&&ks.addBinding("branch",t.gitBranchName)}catch{}})();var YD=NJ();YD.get("/",async(t,e)=>{let r=Re(),n=Mc();if(!n){e.status(500).json({message:"API client not initialized"});return}let o=await Er(ks,n,r),i=o?.gitProtectedBranches&&o?.gitBranchName&&o.gitProtectedBranches.includes(o.gitBranchName),{noCache:a,alwaysSaveCache:s}=Ds(),c=!a&&(s||!i);e.status(200).json({saveCaches:c,checkedOutBranch:o?.gitBranchName})});var jb=YD;import{Router as DJ}from"express";import Ur from"fs";import{glob as kJ}from"glob";import ur from"path";var UJ=5e3;function Vb(t={}){let e=DJ();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=Ur.statSync(i),c=n(i);return mE.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("/",Ge(async(i,a,s)=>{let c;try{c=f_.parse(i.body).pathSegments}catch(g){a.status(400).json({error:`Failed to parse folder read body: ${g}`});return}let l=r(c);if(!Ur.existsSync(l)){a.status(404).json({error:`Path not found: ${c.join(ur.sep)}`});return}if(!Ur.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(Hm),m=AbortSignal.timeout(UJ),f;try{f=await kJ("*",{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 FJ(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("/",Ge(async(i,a,s)=>{let c;try{c=h_.parse(i.body).pathSegments}catch(d){a.status(400).json({error:`Failed to parse folder create body: ${d}`});return}let l=r(c);if(Ur.existsSync(l)){a.status(200).json({success:!0,message:`Folder already exists: ${c.join(ur.sep)}`,pathSegments:c});return}Ur.mkdirSync(l,{recursive:!0});let u={success:!0,message:`Folder created: ${c.join(ur.sep)}`,pathSegments:c};a.status(201).json(u)})),e.patch("/",Ge(async(i,a,s)=>{let c,l;try{let f=g_.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(!Ur.existsSync(u)){a.status(400).json({error:`Folder not found: ${c.join(ur.sep)}`});return}if(Ur.existsSync(d)){a.status(400).json({error:`Destination already exists: ${l.join(ur.sep)}`});return}let p=ur.dirname(d);Ur.existsSync(p)||Ur.mkdirSync(p,{recursive:!0}),Ur.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("/",Ge(async(i,a,s)=>{let c,l=!0;try{let m=S_.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(!Ur.existsSync(u)){a.status(200).json({success:!0,message:`Folder not found: ${c.join(ur.sep)}`,pathSegments:c});return}if(!Ur.statSync(u).isDirectory()){a.status(400).json({error:`Path is not a directory: ${c.join(ur.sep)}`});return}if(l)Ur.rmSync(u,{recursive:!0,force:!0});else{if(Ur.readdirSync(u).length>0){a.status(409).json({error:`Cannot delete non-empty directory without recursive flag: ${c.join("/")}`});return}Ur.rmdirSync(u)}let p={success:!0,message:`Folder deleted: ${c.join("/")}`,pathSegments:c};a.status(200).json(p)})),e}async function FJ(t){try{let e=await Ur.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 BJ}from"express";var XD=BJ();XD.get("/",async(t,e)=>{let r=Re(),n=Mc();if(!n){e.status(500).json({message:"API client not initialized"});return}let o=await Er(ks,n,r);e.status(200).json(o)});var Wb=XD;import Aee from"events";import WB,{Router as Cee}from"express";import Ree from"http";import wee from"path";import{Server as oZ}from"socket.io";var zJ=({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{}}},JD={event:"cancel",createHandler:zJ};var HJ=({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})}}},QD={event:"fetchA11yTree",createHandler:HJ};var GJ=({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})}}},ZD={event:"fetchDom",createHandler:GJ};var jJ=({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)}},ek={event:"disconnect",createHandler:jJ};function no(t){let{result:e,nestedResults:r}=t;if(!t.nestedResults.length)return;let{firstMetadata:n,lastMetadata:o}=VJ(r);WJ(e,n,o);let i=[...t.asyncTasks];t.asyncTasks.push((async()=>{try{await $J(i,e,n,o)}catch(a){t.logger.error({result:t.result,err:a},"Error hoisting scalar result metadata")}})())}function VJ(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 WJ(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 $J(t,e,r,n){await Promise.allSettled(t),r&&(e.beforeSnapshot=r.beforeSnapshot),n&&(e.afterSnapshot=n.afterSnapshot)}import{randomUUID as n6}from"crypto";import{faker as qJ}from"@faker-js/faker";import KJ from"assert";import YJ from"axios";import*as XJ from"child_process";import JJ from"moment";import*as QJ from"otpauth";import ZJ from"pg";async function tk(t){let e;try{e=new URL(t.url).hostname}catch{}let r=[];return t.headers.getSetCookie()?.forEach(n=>{let o=_m(n,e);r.push(...o)}),r}function e6(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 t6(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 r6=Object.getPrototypeOf(async function(){}).constructor;async function rk(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 r6("axios","moment","faker","assert","pg","Octokit","createAppAuth","OTPAuth","child_process","extractCookiesFromResponse","env","setVariable","setPersistentVariable","sendSms","waitForLatestSms","email","sms","ai","mock",...Object.keys(i??{}),n)(YJ,JJ,c.fakerInstance??qJ,KJ,ZJ,m,f,QJ,XJ,tk,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,e6(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 t6(e.options.responseSerialization??"RAW",y)}catch(y){r.error({err:y,env:o,evalCode:n},`[${t}] Error executing code: ${y}`),S=!1,y instanceof aa?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 nk({code:t,fragment:e,context:r,localTools:n,logger:o,signal:i,timeoutMs:a=ta,disallowVariableUpdates:s,additionalBindings:c,responseSerialization:l,mock:u}){let d=n6(),p=await rk(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 o6,randomUUID as i6}from"crypto";import a6 from"fetch-retry";var s6=a6(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}}),ok=process.env.GCP_JS_EVAL_FUNCTION_ENDPOINT,ik=process.env.MOMENTIC_LAMBDA_AUTH_SECRET;async function ak({orgId:t,code:e,fragment:r,context:n,timeoutMs:o=ta,retries:i=2,signal:a,logger:s,additionalBindings:c,disallowVariableUpdates:l,responseSerialization:u,mock:d}){if(!ok)throw new Error("GCP_JS_EVAL_FUNCTION_ENDPOINT environment variable not set");let p,m,f=0;if(!ik)throw new Error("Missing lambda auth secret.");let h=o6("sha256",ik).update(t).digest("hex");for(;f<=i;){f++,a?.throwIfAborted();let g={id:i6(),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(s6(ok,{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=Yx.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 va(t){let e;if(process.env.GCP_JS_EVAL_FUNCTION_ENDPOINT)e=await ak(t);else if(t.localTools)e=await nk({...t,localTools:t.localTools});else throw new Error("No code evaluation environment available");if(e.error){let r=`Failed to evaluate code:
|
|
91
|
+
`))}return Qh(i,n)}throw new Error("No valid selector field provided. Exactly one of id, name, or path must be specified.")}function Qh(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 _J(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 Zh from"fs";import IJ from"path";var PJ=new gh(30,60*1e3),tg="https://api.momentic.ai",zb,qD,rg=t=>{tg=t},qt=()=>tg,KD=()=>Wl(tg),ng=t=>{qD=t},Ds=()=>qD,Mc=()=>zb;var Pc,Hb,eg,og=async t=>{if(zb&&Pc&&eg)return Pc;let e=new pt({baseUrl:tg,apiKey:t,logger:v});zb=e;try{let r=await e.getAuthInfo();return Pc=r.orgId,Hb=r.userId,eg=t,Pc}catch(r){throw new Error(`Error checking API key against server: ${r}`,{cause:r})}},Kt=()=>{if(!Pc)throw new Error("Your organization ID is invalid.");return Pc},Qo=()=>{if(!Hb)throw new Error("Your user ID is invalid.");return Hb},Cr=()=>{if(!eg)throw new Error("Your API key is invalid.");return eg},Gb,Bb,Oc=(t,e)=>{Gb=t,Bb?.abort(),Bb=new AbortController;let r=Bb.signal,n=[t.configFilePath];t.config.environments?.forEach(o=>{if(!o.envFile)return;let i=IJ.resolve(t.rootDir,o.envFile);try{if(Zh.lstatSync(i).isSymbolicLink())return;Zh.existsSync(i)&&n.push(i)}catch(a){v.warn({err:a},`Failed to check if env file ${i} exists`)}});try{MJ({filesToWatch:n,revalidator:e,signal:r,project:t})}catch(o){v.error({err:o},"Failed to start config file watchers")}},Re=()=>Gb;function MJ({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()&&(PJ.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.`),Gb=await Promise.resolve(e(n.configFilePath)))};Zh.watchFile(o,{persistent:!1},i);let a=()=>{Zh.unwatchFile(o,i),r.removeEventListener("abort",a)};r.addEventListener("abort",a),process.once("SIGUSR2",()=>{a(),process.kill(process.pid,"SIGUSR2")})})}function Ge(t){return function(...e){let r=e[e.length-1],n=t(...e);Promise.resolve(n).catch(r)}}import{hostname as OJ}from"os";var LJ="2.72.1",ks=Yl({app:"desktop-server",hostname:OJ(),disableConsoleLogs:!0,captureExceptions:!0}).child({cliVersion:LJ});(async()=>{try{let t=await Ii(ks);t.gitBranchName&&ks.addBinding("branch",t.gitBranchName)}catch{}})();var YD=NJ();YD.get("/",async(t,e)=>{let r=Re(),n=Mc();if(!n){e.status(500).json({message:"API client not initialized"});return}let o=await Er(ks,n,r),i=o?.gitProtectedBranches&&o?.gitBranchName&&o.gitProtectedBranches.includes(o.gitBranchName),{noCache:a,alwaysSaveCache:s}=Ds(),c=!a&&(s||!i);e.status(200).json({saveCaches:c,checkedOutBranch:o?.gitBranchName})});var jb=YD;import{Router as DJ}from"express";import Ur from"fs";import{glob as kJ}from"glob";import ur from"path";var UJ=5e3;function Vb(t={}){let e=DJ();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=Ur.statSync(i),c=n(i);return mE.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("/",Ge(async(i,a,s)=>{let c;try{c=f_.parse(i.body).pathSegments}catch(g){a.status(400).json({error:`Failed to parse folder read body: ${g}`});return}let l=r(c);if(!Ur.existsSync(l)){a.status(404).json({error:`Path not found: ${c.join(ur.sep)}`});return}if(!Ur.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(Hm),m=AbortSignal.timeout(UJ),f;try{f=await kJ("*",{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 FJ(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("/",Ge(async(i,a,s)=>{let c;try{c=h_.parse(i.body).pathSegments}catch(d){a.status(400).json({error:`Failed to parse folder create body: ${d}`});return}let l=r(c);if(Ur.existsSync(l)){a.status(200).json({success:!0,message:`Folder already exists: ${c.join(ur.sep)}`,pathSegments:c});return}Ur.mkdirSync(l,{recursive:!0});let u={success:!0,message:`Folder created: ${c.join(ur.sep)}`,pathSegments:c};a.status(201).json(u)})),e.patch("/",Ge(async(i,a,s)=>{let c,l;try{let f=g_.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(!Ur.existsSync(u)){a.status(400).json({error:`Folder not found: ${c.join(ur.sep)}`});return}if(Ur.existsSync(d)){a.status(400).json({error:`Destination already exists: ${l.join(ur.sep)}`});return}let p=ur.dirname(d);Ur.existsSync(p)||Ur.mkdirSync(p,{recursive:!0}),Ur.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("/",Ge(async(i,a,s)=>{let c,l=!0;try{let m=S_.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(!Ur.existsSync(u)){a.status(200).json({success:!0,message:`Folder not found: ${c.join(ur.sep)}`,pathSegments:c});return}if(!Ur.statSync(u).isDirectory()){a.status(400).json({error:`Path is not a directory: ${c.join(ur.sep)}`});return}if(l)Ur.rmSync(u,{recursive:!0,force:!0});else{if(Ur.readdirSync(u).length>0){a.status(409).json({error:`Cannot delete non-empty directory without recursive flag: ${c.join("/")}`});return}Ur.rmdirSync(u)}let p={success:!0,message:`Folder deleted: ${c.join("/")}`,pathSegments:c};a.status(200).json(p)})),e}async function FJ(t){try{let e=await Ur.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 BJ}from"express";var XD=BJ();XD.get("/",async(t,e)=>{let r=Re(),n=Mc();if(!n){e.status(500).json({message:"API client not initialized"});return}let o=await Er(ks,n,r);e.status(200).json(o)});var Wb=XD;import Aee from"events";import WB,{Router as Cee}from"express";import Ree from"http";import wee from"path";import{Server as oZ}from"socket.io";var zJ=({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{}}},JD={event:"cancel",createHandler:zJ};var HJ=({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})}}},QD={event:"fetchA11yTree",createHandler:HJ};var GJ=({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})}}},ZD={event:"fetchDom",createHandler:GJ};var jJ=({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)}},ek={event:"disconnect",createHandler:jJ};function no(t){let{result:e,nestedResults:r}=t;if(!t.nestedResults.length)return;let{firstMetadata:n,lastMetadata:o}=VJ(r);WJ(e,n,o);let i=[...t.asyncTasks];t.asyncTasks.push((async()=>{try{await $J(i,e,n,o)}catch(a){t.logger.error({result:t.result,err:a},"Error hoisting scalar result metadata")}})())}function VJ(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 WJ(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 $J(t,e,r,n){await Promise.allSettled(t),r&&(e.beforeSnapshot=r.beforeSnapshot),n&&(e.afterSnapshot=n.afterSnapshot)}import{randomUUID as n6}from"crypto";import{faker as qJ}from"@faker-js/faker";import KJ from"assert";import YJ from"axios";import*as XJ from"child_process";import JJ from"moment";import*as QJ from"otpauth";import ZJ from"pg";async function tk(t){let e;try{e=new URL(t.url).hostname}catch{}let r=[];return t.headers.getSetCookie()?.forEach(n=>{let o=_m(n,e);r.push(...o)}),r}function e6(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 t6(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 r6=Object.getPrototypeOf(async function(){}).constructor;async function rk(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 r6("axios","moment","faker","assert","pg","Octokit","createAppAuth","OTPAuth","child_process","extractCookiesFromResponse","env","setVariable","setPersistentVariable","sendSms","waitForLatestSms","email","sms","ai","mock",...Object.keys(i??{}),n)(YJ,JJ,c.fakerInstance??qJ,KJ,ZJ,m,f,QJ,XJ,tk,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,e6(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 t6(e.options.responseSerialization??"RAW",y)}catch(y){r.error({err:y,env:o,evalCode:n},`[${t}] Error executing code: ${y}`),S=!1,y instanceof aa?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 nk({code:t,fragment:e,context:r,localTools:n,logger:o,signal:i,timeoutMs:a=ta,disallowVariableUpdates:s,additionalBindings:c,responseSerialization:l,mock:u}){let d=n6(),p=await rk(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 o6,randomUUID as i6}from"crypto";import a6 from"fetch-retry";var s6=a6(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}}),ok=process.env.GCP_JS_EVAL_FUNCTION_ENDPOINT,ik=process.env.MOMENTIC_LAMBDA_AUTH_SECRET;async function ak({orgId:t,code:e,fragment:r,context:n,timeoutMs:o=ta,retries:i=2,signal:a,logger:s,additionalBindings:c,disallowVariableUpdates:l,responseSerialization:u,mock:d}){if(!ok)throw new Error("GCP_JS_EVAL_FUNCTION_ENDPOINT environment variable not set");let p,m,f=0;if(!ik)throw new Error("Missing lambda auth secret.");let h=o6("sha256",ik).update(t).digest("hex");for(;f<=i;){f++,a?.throwIfAborted();let g={id:i6(),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(s6(ok,{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=Yx.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 va(t){let e;if(process.env.GCP_JS_EVAL_FUNCTION_ENDPOINT)e=await ak(t);else if(t.localTools)e=await nk({...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 l6}from"lodash-es";async function Qr(t){let{orgId:e,s:r,context:n,logger:o,signal:i,retries:a=2,timeoutMs:s=ta,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 va({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 ig(t){return sk(t)}async function sk({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 Qr({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 sk({obj:l,bannedKeys:e,context:n,prefixPath:u,replacements:i,allowList:c?void 0:r,...a})}return i}function lk(t,e){for(let{path:r,original:n}of e)l6(t,r,n)}import c6 from"fetch-retry";var h5e=process.env.MAILINATOR_API_KEY,g5e=c6(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 e9}from"os";var $b={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 l6}from"lodash-es";async function Qr(t){let{orgId:e,s:r,context:n,logger:o,signal:i,retries:a=2,timeoutMs:s=ta,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 va({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 ig(t){return sk(t)}async function sk({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 Qr({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 sk({obj:l,bannedKeys:e,context:n,prefixPath:u,replacements:i,allowList:c?void 0:r,...a})}return i}function lk(t,e){for(let{path:r,original:n}of e)l6(t,r,n)}import c6 from"fetch-retry";var g5e=process.env.MAILINATOR_API_KEY,S5e=c6(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 e9}from"os";var $b={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",
|
|
@@ -4599,7 +4599,7 @@ ${c}`,{errOptions:{cause:t}})}if(i.includes("element is not visible")){let c="Th
|
|
|
4599
4599
|
writable: false,
|
|
4600
4600
|
configurable: false,
|
|
4601
4601
|
});`),`${r}
|
|
4602
|
-
//# sourceURL=momentic-injected/extra-scripts.js`}function fv(t){let e=[],r="";for(let n of t)n==="+"&&r?(e.push(r),r=""):r+=n;return e.push(r),e}var nQ=["clipboard-read","clipboard-write","microphone","camera","geolocation","local-network-access"],oQ=["local-network-access"];function Yk(t){return Vn?t.filter(e=>!oQ.includes(e)):t}function Xk(t){return Yk(t||nQ)}var hv="__momentic_session_storage_initialized";function Jk(t){return t.parentFrame!==void 0}async function Qk(t,e,r){try{let n=await iQ(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 iQ(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}},hv)}function Zk(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 e0(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 aQ(t){return t?t.match(/^\s*<\s*([a-zA-Z0-9-]+)/)?.[1]?.toLowerCase():void 0}function sQ(t){if(!t)return;let e=t.match(/\srole\s*=\s*(?:"([^"]+)"|'([^']+)'|([^\s>]+))/i);return e?.[1]??e?.[2]??e?.[3]}function gv(t,e){let r=e?.tagName??aQ(t.nodeOnlySerializedHtml);if(r&&Tk.includes(r.toLowerCase()))return!0;let n=sQ(t.nodeOnlySerializedHtml);return!!(n&&bk.includes(n.toLowerCase()))}async function lQ(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 Sv(t){let{logger:e}=t;try{let r=await lQ(t);if(!r)return;throw e.warn({failReason:r},"Locator no longer matches cache, re-triggering evaluation"),new Wi("Locator no longer matches cache")}catch(r){if(r instanceof Wi)throw r;e.warn({err:r},"Failed to check whether locator has drifted from cache")}}import t0 from"jpeg-js";import cQ from"pixelmatch";function r0(t,e,r=.01){if(t.equals(e))return 0;let n=t0.decode(t),o=t0.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 cQ(n.data,o.data,s,i,a,{threshold:r})/(i*a)*100}var o0=["date","datetime-local","month","time","week"],n0={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 i0(t){try{await J(uQ(t),{milliseconds:pe})}catch(e){t.logger.warn({err:e},"Failed to transform native datetime input, continuing...")}}async function uQ({root:t,text:e,options:r,logger:n,callbacks:o}){let i=(await Qt({root:t,fn:()=>document.activeElement?.getAttribute("type")??"",timeout:Je,arg:void 0,waitForPageLoad:o.waitForPageLoad,codePath:"transforming native datetime input"})).toLowerCase();if(!n0[i])return;n0[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 Zr}from"zod";var a0=Zr.object({doubleClick:Zr.boolean().optional(),rightClick:Zr.boolean().optional(),force:Zr.boolean().optional(),waitForDownload:Zr.boolean().optional(),delayMs:Zr.number().optional(),downloadTimeoutMs:Zr.number().optional(),relativePosition:Zr.object({x:Zr.number(),y:Zr.number()}).optional(),iterations:Zr.number().optional()}),s6e=Zr.object({repeat:Zr.number().optional(),convertMeta:Zr.boolean().optional().describe("misleading name due to backcompat. converts keyshortcuts + meta/control to platform-specific combos. defaults to true"),delayMs:Zr.number().optional()});async function pg({locator:t,callbacks:e,logger:r,timeoutMs:n=Je}){try{await yv(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 yv(t,e=Je){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 Ev(t){let e=!!t.browserCallbacks.state.userBrowserSettings.visualActions;return Bs({action:"clicking element",targetingResult:t.targetingResult,logger:t.logger,retryTimeoutMs:t.retryTimeoutMs,callbacks:t.browserCallbacks,func:async r=>l0({...t,targetingResult:r,useVisualClick:e})})}async function fQ({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 Ck({targetingResult:r,logger:n});return i?{locator:i.locator,position:i.relativePoint,redirected:!0}:{locator:o,position:e,redirected:!1}}async function hQ(t,e){try{return await gQ(t,e)}catch(r){throw e.logger.warn({redirectionAttemptError:r,originalError:t},"Error handling click error, rethrowing original error"),t}}async function gQ(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:Je});if(!i)throw t;let a=o.page().locator(`[for=${JSON.stringify(i)}]`),s=await a.boundingBox({timeout:Je});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"),l0({...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 SQ(t){let{logger:e,targetingResult:r,position:n,options:o}=t,i=a0.safeParse(o),a=Date.now(),{clickX:s,clickY:c,reason:l}=await TQ({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 yQ(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 fQ({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(vQ(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..."),hQ(l,{...t,targetingResult:r});throw l}}return{locatorSource:c}}async function l0(t){let{options:e,logger:r,browserCallbacks:n,controllerCallbacks:o,useVisualClick:i,targetingResult:a}=t,s;e?.waitForDownload&&(s=(async()=>{let u=e.downloadTimeoutMs??Kb;try{return await a.locator.page().waitForEvent("download",{timeout:u})}catch(d){return d instanceof mQ.TimeoutError?new L("ActionFailureError",`Download did not complete in ${u}ms`):new L("ActionFailureError",`Download failed: ${d.message}`)}})());try{await pg({locator:a.locator,callbacks:n,logger:r,timeoutMs:Je})}catch(u){r.warn({err:u},"Error highlighting locator in click, continuing...")}let c,l;if(i?c=await SQ(t):l=(await yQ(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??Kb});if(u instanceof Error)throw u;return{downloadedFile:await bQ(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 EQ(t,e){let r=t.serverSideBoundingBox??await t.locator.boundingBox({timeout:pe});if(!r){let i=t.originalElementLocationResult?.serializedElement;throw new L("ActionFailureError",`${GS}${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 TQ({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 EQ(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 bQ(t,e,r){r.info("Download detected, saving file to disk");let n=await t.path(),o=nv(t.suggestedFilename()),i=e();await t.saveAs(pQ(i,o)),s0(n,{force:!0}),setTimeout(()=>{s0(i,{recursive:!0,force:!0})},5*60*1e3);let a=xk(dQ(i),o);return r.info({uri:a,downloadFolder:i},"Saved download to isolated folder"),a}function vQ(t){return t.message.includes("locator.click: Timeout")&&t.message.includes("click action done")}import{platform as AQ}from"os";var CQ={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 RQ(){let t=AQ();return t==="win32"?"win32":t==="darwin"?"darwin":"linux"}function c0(t){return JSON.stringify(t.split("+").sort())}function mg(t,e){let r=RQ(),n=c0(t);for(let o of Object.values(CQ))if(Object.values(o).some(i=>c0(i)===n))return o[r];return process.platform==="darwin"&&!e?t=t.replaceAll("Control","Meta"):t=t.replaceAll("Meta","Control"),t}async function Tv({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:Je}),[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:Je});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 bv(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 vv(t){let{page:e,deltaX:r,deltaY:n,steps:o,visualTarget:i,isAndroid:a,hoverDurationMs:s}=t;if(a){await wQ(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??Aa),await e.mouse.up()}async function u0({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 vv({page:t,deltaX:c-u,deltaY:l-d,steps:n,dragDurationMs:o,hoverDurationMs:i,visualTarget:{x:u,y:d},isAndroid:!0})}async function d0(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,sg)),await t.mouse.up()}async function wQ(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 NQ}from"crypto";import{cloneDeep as Rv}from"lodash-es";function xa(t,e){let r=t.findIndex(n=>n===e);if(!(r===-1||!t[r+1]))return t[r+1]}import{createHash as xQ}from"crypto";var _Q="v1";function Av(t,e){if(t.tagName.toLowerCase()==="svg"&&!PQ(t))try{let r=p0(t,e),n=IQ(JSON.stringify(r));return{version:_Q,json:r,hash:n}}catch{return}}function IQ(t){return xQ("md5").update(t).digest("hex")}function p0(t,e){let r=t.tagName.toLowerCase(),n=MQ(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=p0(a,e);s&&o.children.push(s)}}return o}function PQ(t){let e=t.computedStyles.display,r=t.computedStyles.visibility,n=t.computedStyles.opacity;return e==="none"||r==="hidden"||n==="0"}function MQ(t){let e={},r=t.attributes;for(let n of Object.keys(r))Rn.visualAttributesForSvgSerialization.includes(n)&&(e[n]=r[n]);return r.id&&t.tagName.toLowerCase()!=="svg"&&(e.id=r.id),e}var zs={r:147,g:196,b:125,a:.55},f0={showRulers:!1,showStyles:!1,showExtensionLines:!1,contrastAlgorithm:"aa",contentColor:zs,paddingColor:zs,borderColor:zs,marginColor:zs,eventTargetColor:zs,shapeColor:zs,shapeMarginColor:zs,showInfo:!0,showAccessibilityInfo:!0};function h0({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=OQ({allDocuments:i,stringConstants:o,computedStylesToFetch:r,devicePixelRatio:e,frameIndex:u,backendIdToNode:a,frameIndexToIframeNode:s,logger:n});c.roots.push(d)}),c}function OQ({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,U=B!==void 0?h[B]:void 0,G=U!==void 0?a[U]: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:U??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 Cv(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=`${Cv(r,e)}${a}`}return t.mPathSelector=n,n}function m0(t,e){return t.parentBackendNodeId!==null?e.backendIdToNode[t.parentBackendNodeId]:t.frameIndex===0?void 0:e.frameIndexToIframeNode[t.frameIndex]}var LQ=["html","#document","#document-fragment"];function g0({node:t,domGraph:e}){let r=[],n=t,o=m0(t,e);if(!o)return[t.tagName];let i=()=>{if(n=o,o=m0(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++,LQ.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 S0(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 y0(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=xa(o,Us);if(!i)throw new Error(`Could not find attribute ${Us} for object ${e}`);return i}var DQ=["svg","i"],kQ=["focusable","keyshortcuts","controls","live","relevant","orientation"],UQ=["selected","readonly","modal","required","invalid"],FQ=["id","name","role","content"],E0=["absolute","fixed","sticky"],BQ=["i","label"],zQ=["path"],HQ=["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"],v0=["ariaHiddenElement","ariaHiddenSubtree","hiddenByChildTree","inertElement","inertSubtree","notRendered","notVisible"],A0=["activeAriaModalDialog","activeFullscreenElement","activeModalDialog"],GQ=["menulistpopup","statictext","inlinetextbox"],jQ=80,T0=100,wv=50,Iv=["StaticText","ListMarker","RootWebArea","LineBreak","::before","::after"],VQ=["cite"],WQ={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"]},$Q={name:!0,value:!0,title:!0,alt:!0,placeholder:!0,checked:!0,selected:!0,contenteditable:!0},b0={indentLevel:0},xv=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<wv?r:""),this.role=this.role||(e.domNode.attributes.role??""),XQ(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&&zQ.includes(this.domNode.tagName)&&!this.domNode.attributes["aria-label"]||this.ignoredReasons.some(n=>A0.includes(n)))return!1;if(e){if(Object.keys(this.domNode?.attributes??{}).some(o=>_0(o,e)))return!0;let n=this.domNode?.attributes.class?.split(" ");if(n&&n.length>0&&n.some(o=>I0(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&&BQ.includes(this.domNode.tagName)||HQ.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)||Rn.alwaysInterestingTruthyPropertyNames.some(n=>!!this.properties[n]))return!0;let r=this.properties.class;return typeof r=="string"&&r.split(" ").some(n=>x0(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 Ak({tagName:this.domNode.tagName,width:this.domNode.bounds.width,height:this.domNode.bounds.height})&&e}serialize(e=b0){let r=Object.assign({},b0,e),{indentLevel:n,noChildren:o,noProperties:i,noId:a,noContent:s,condensedMode:c}=r,l=Rv(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<wv?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=Iv.includes(this.role)||VQ.includes(this.tagName||"");if(this.role==="StaticText")return`${u}${m}
|
|
4602
|
+
//# sourceURL=momentic-injected/extra-scripts.js`}function fv(t){let e=[],r="";for(let n of t)n==="+"&&r?(e.push(r),r=""):r+=n;return e.push(r),e}var nQ=["clipboard-read","clipboard-write","microphone","camera","geolocation","local-network-access"],oQ=["local-network-access"];function Yk(t){return Vn?t.filter(e=>!oQ.includes(e)):t}function Xk(t){return Yk(t||nQ)}var hv="__momentic_session_storage_initialized";function Jk(t){return t.parentFrame!==void 0}async function Qk(t,e,r){try{let n=await iQ(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 iQ(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}},hv)}function Zk(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 e0(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 aQ(t){return t?t.match(/^\s*<\s*([a-zA-Z0-9-]+)/)?.[1]?.toLowerCase():void 0}function sQ(t){if(!t)return;let e=t.match(/\srole\s*=\s*(?:"([^"]+)"|'([^']+)'|([^\s>]+))/i);return e?.[1]??e?.[2]??e?.[3]}function gv(t,e){let r=e?.tagName??aQ(t.nodeOnlySerializedHtml);if(r&&Tk.includes(r.toLowerCase()))return!0;let n=sQ(t.nodeOnlySerializedHtml);return!!(n&&bk.includes(n.toLowerCase()))}async function lQ(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 Sv(t){let{logger:e}=t;try{let r=await lQ(t);if(!r)return;throw e.warn({failReason:r},"Locator no longer matches cache, re-triggering evaluation"),new Wi("Locator no longer matches cache")}catch(r){if(r instanceof Wi)throw r;e.warn({err:r},"Failed to check whether locator has drifted from cache")}}import t0 from"jpeg-js";import cQ from"pixelmatch";function r0(t,e,r=.01){if(t.equals(e))return 0;let n=t0.decode(t),o=t0.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 cQ(n.data,o.data,s,i,a,{threshold:r})/(i*a)*100}var o0=["date","datetime-local","month","time","week"],n0={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 i0(t){try{await J(uQ(t),{milliseconds:pe})}catch(e){t.logger.warn({err:e},"Failed to transform native datetime input, continuing...")}}async function uQ({root:t,text:e,options:r,logger:n,callbacks:o}){let i=(await Qt({root:t,fn:()=>document.activeElement?.getAttribute("type")??"",timeout:Je,arg:void 0,waitForPageLoad:o.waitForPageLoad,codePath:"transforming native datetime input"})).toLowerCase();if(!n0[i])return;n0[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 Zr}from"zod";var a0=Zr.object({doubleClick:Zr.boolean().optional(),rightClick:Zr.boolean().optional(),force:Zr.boolean().optional(),waitForDownload:Zr.boolean().optional(),delayMs:Zr.number().optional(),downloadTimeoutMs:Zr.number().optional(),relativePosition:Zr.object({x:Zr.number(),y:Zr.number()}).optional(),iterations:Zr.number().optional()}),l6e=Zr.object({repeat:Zr.number().optional(),convertMeta:Zr.boolean().optional().describe("misleading name due to backcompat. converts keyshortcuts + meta/control to platform-specific combos. defaults to true"),delayMs:Zr.number().optional()});async function pg({locator:t,callbacks:e,logger:r,timeoutMs:n=Je}){try{await yv(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 yv(t,e=Je){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 Ev(t){let e=!!t.browserCallbacks.state.userBrowserSettings.visualActions;return Bs({action:"clicking element",targetingResult:t.targetingResult,logger:t.logger,retryTimeoutMs:t.retryTimeoutMs,callbacks:t.browserCallbacks,func:async r=>l0({...t,targetingResult:r,useVisualClick:e})})}async function fQ({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 Ck({targetingResult:r,logger:n});return i?{locator:i.locator,position:i.relativePoint,redirected:!0}:{locator:o,position:e,redirected:!1}}async function hQ(t,e){try{return await gQ(t,e)}catch(r){throw e.logger.warn({redirectionAttemptError:r,originalError:t},"Error handling click error, rethrowing original error"),t}}async function gQ(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:Je});if(!i)throw t;let a=o.page().locator(`[for=${JSON.stringify(i)}]`),s=await a.boundingBox({timeout:Je});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"),l0({...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 SQ(t){let{logger:e,targetingResult:r,position:n,options:o}=t,i=a0.safeParse(o),a=Date.now(),{clickX:s,clickY:c,reason:l}=await TQ({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 yQ(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 fQ({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(vQ(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..."),hQ(l,{...t,targetingResult:r});throw l}}return{locatorSource:c}}async function l0(t){let{options:e,logger:r,browserCallbacks:n,controllerCallbacks:o,useVisualClick:i,targetingResult:a}=t,s;e?.waitForDownload&&(s=(async()=>{let u=e.downloadTimeoutMs??Kb;try{return await a.locator.page().waitForEvent("download",{timeout:u})}catch(d){return d instanceof mQ.TimeoutError?new L("ActionFailureError",`Download did not complete in ${u}ms`):new L("ActionFailureError",`Download failed: ${d.message}`)}})());try{await pg({locator:a.locator,callbacks:n,logger:r,timeoutMs:Je})}catch(u){r.warn({err:u},"Error highlighting locator in click, continuing...")}let c,l;if(i?c=await SQ(t):l=(await yQ(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??Kb});if(u instanceof Error)throw u;return{downloadedFile:await bQ(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 EQ(t,e){let r=t.serverSideBoundingBox??await t.locator.boundingBox({timeout:pe});if(!r){let i=t.originalElementLocationResult?.serializedElement;throw new L("ActionFailureError",`${GS}${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 TQ({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 EQ(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 bQ(t,e,r){r.info("Download detected, saving file to disk");let n=await t.path(),o=nv(t.suggestedFilename()),i=e();await t.saveAs(pQ(i,o)),s0(n,{force:!0}),setTimeout(()=>{s0(i,{recursive:!0,force:!0})},5*60*1e3);let a=xk(dQ(i),o);return r.info({uri:a,downloadFolder:i},"Saved download to isolated folder"),a}function vQ(t){return t.message.includes("locator.click: Timeout")&&t.message.includes("click action done")}import{platform as AQ}from"os";var CQ={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 RQ(){let t=AQ();return t==="win32"?"win32":t==="darwin"?"darwin":"linux"}function c0(t){return JSON.stringify(t.split("+").sort())}function mg(t,e){let r=RQ(),n=c0(t);for(let o of Object.values(CQ))if(Object.values(o).some(i=>c0(i)===n))return o[r];return process.platform==="darwin"&&!e?t=t.replaceAll("Control","Meta"):t=t.replaceAll("Meta","Control"),t}async function Tv({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:Je}),[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:Je});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 bv(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 vv(t){let{page:e,deltaX:r,deltaY:n,steps:o,visualTarget:i,isAndroid:a,hoverDurationMs:s}=t;if(a){await wQ(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??Aa),await e.mouse.up()}async function u0({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 vv({page:t,deltaX:c-u,deltaY:l-d,steps:n,dragDurationMs:o,hoverDurationMs:i,visualTarget:{x:u,y:d},isAndroid:!0})}async function d0(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,sg)),await t.mouse.up()}async function wQ(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 NQ}from"crypto";import{cloneDeep as Rv}from"lodash-es";function xa(t,e){let r=t.findIndex(n=>n===e);if(!(r===-1||!t[r+1]))return t[r+1]}import{createHash as xQ}from"crypto";var _Q="v1";function Av(t,e){if(t.tagName.toLowerCase()==="svg"&&!PQ(t))try{let r=p0(t,e),n=IQ(JSON.stringify(r));return{version:_Q,json:r,hash:n}}catch{return}}function IQ(t){return xQ("md5").update(t).digest("hex")}function p0(t,e){let r=t.tagName.toLowerCase(),n=MQ(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=p0(a,e);s&&o.children.push(s)}}return o}function PQ(t){let e=t.computedStyles.display,r=t.computedStyles.visibility,n=t.computedStyles.opacity;return e==="none"||r==="hidden"||n==="0"}function MQ(t){let e={},r=t.attributes;for(let n of Object.keys(r))Rn.visualAttributesForSvgSerialization.includes(n)&&(e[n]=r[n]);return r.id&&t.tagName.toLowerCase()!=="svg"&&(e.id=r.id),e}var zs={r:147,g:196,b:125,a:.55},f0={showRulers:!1,showStyles:!1,showExtensionLines:!1,contrastAlgorithm:"aa",contentColor:zs,paddingColor:zs,borderColor:zs,marginColor:zs,eventTargetColor:zs,shapeColor:zs,shapeMarginColor:zs,showInfo:!0,showAccessibilityInfo:!0};function h0({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=OQ({allDocuments:i,stringConstants:o,computedStylesToFetch:r,devicePixelRatio:e,frameIndex:u,backendIdToNode:a,frameIndexToIframeNode:s,logger:n});c.roots.push(d)}),c}function OQ({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,U=B!==void 0?h[B]:void 0,G=U!==void 0?a[U]: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:U??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 Cv(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=`${Cv(r,e)}${a}`}return t.mPathSelector=n,n}function m0(t,e){return t.parentBackendNodeId!==null?e.backendIdToNode[t.parentBackendNodeId]:t.frameIndex===0?void 0:e.frameIndexToIframeNode[t.frameIndex]}var LQ=["html","#document","#document-fragment"];function g0({node:t,domGraph:e}){let r=[],n=t,o=m0(t,e);if(!o)return[t.tagName];let i=()=>{if(n=o,o=m0(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++,LQ.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 S0(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 y0(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=xa(o,Us);if(!i)throw new Error(`Could not find attribute ${Us} for object ${e}`);return i}var DQ=["svg","i"],kQ=["focusable","keyshortcuts","controls","live","relevant","orientation"],UQ=["selected","readonly","modal","required","invalid"],FQ=["id","name","role","content"],E0=["absolute","fixed","sticky"],BQ=["i","label"],zQ=["path"],HQ=["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"],v0=["ariaHiddenElement","ariaHiddenSubtree","hiddenByChildTree","inertElement","inertSubtree","notRendered","notVisible"],A0=["activeAriaModalDialog","activeFullscreenElement","activeModalDialog"],GQ=["menulistpopup","statictext","inlinetextbox"],jQ=80,T0=100,wv=50,Iv=["StaticText","ListMarker","RootWebArea","LineBreak","::before","::after"],VQ=["cite"],WQ={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"]},$Q={name:!0,value:!0,title:!0,alt:!0,placeholder:!0,checked:!0,selected:!0,contenteditable:!0},b0={indentLevel:0},xv=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<wv?r:""),this.role=this.role||(e.domNode.attributes.role??""),XQ(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&&zQ.includes(this.domNode.tagName)&&!this.domNode.attributes["aria-label"]||this.ignoredReasons.some(n=>A0.includes(n)))return!1;if(e){if(Object.keys(this.domNode?.attributes??{}).some(o=>_0(o,e)))return!0;let n=this.domNode?.attributes.class?.split(" ");if(n&&n.length>0&&n.some(o=>I0(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&&BQ.includes(this.domNode.tagName)||HQ.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)||Rn.alwaysInterestingTruthyPropertyNames.some(n=>!!this.properties[n]))return!0;let r=this.properties.class;return typeof r=="string"&&r.split(" ").some(n=>x0(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 Ak({tagName:this.domNode.tagName,width:this.domNode.bounds.width,height:this.domNode.bounds.height})&&e}serialize(e=b0){let r=Object.assign({},b0,e),{indentLevel:n,noChildren:o,noProperties:i,noId:a,noContent:s,condensedMode:c}=r,l=Rv(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<wv?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=Iv.includes(this.role)||VQ.includes(this.tagName||"");if(this.role==="StaticText")return`${u}${m}
|
|
4603
4603
|
`;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&&!(WQ[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+=` ${Rn.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)),U=Math.round((R.y??0)+(R.height??0));E+=` bounds=[${M} ${P} ${B} ${U}]`}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(!kQ.includes(R)){{if(UQ.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&&!$Q[R])return}typeof M=="string"?E+=` ${R}="${vt(M,T0,!0)}"`:typeof M=="boolean"?M?E+=` ${R}`:E+=` ${R}={false}`:typeof M<"u"&&(E+=` ${R}={${vt(JSON.stringify(M),T0,!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+=` />
|
|
4604
4604
|
`;else{let R="";for(let P of this.children)R+=P.serialize({...e,indentLevel:n+2,neighbors:0});let M=R.trim();M.length<=jQ&&!M.includes(`
|
|
4605
4605
|
`)?E+=`>${M}</${p}>
|
|
@@ -4607,7 +4607,7 @@ ${c}`,{errOptions:{cause:t}})}if(i.includes("element is not visible")){let c="Th
|
|
|
4607
4607
|
${R}${u}</${p}>
|
|
4608
4608
|
`}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||""}
|
|
4609
4609
|
${E}
|
|
4610
|
-
${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:Rv(this.internalProperties),importantProperties:this.importantProperties,parentFrame:this.parentFrame,flagNotActionableNodes:this.flagNotActionableNodes});return e.tagName=this.tagName,e.dataMomenticId=this.dataMomenticId,e.properties=Rv(this.properties),e}},_v=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(Iv.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 qQ(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 KQ(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?(Vm({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?(Vm({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 C0({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=GQ.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&&!KQ(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 xv({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??v0).includes(W.name)||A0.includes(W.name))??[],pathFromRoot:(e?`${e.pathFromRoot} `:"")+qQ(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 U=C?.childrenBackendIds?.length??0,G=(t.childIds??[]).filter(W=>!!P.get(parseInt(W))).length;if(U>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 C0({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 JQ(R),C&&p&&Cv(C,i),[R]}function R0({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:Iv.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=Av(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=R0({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 w0({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=NQ(),g=new Set,E=M=>{let P=M.allNodes.filter(U=>!U.ignoredReasons?.find(z=>(m??v0).includes(z.name))),B=new Map;return P.forEach(U=>{B.set(parseInt(U.nodeId),U)}),B},y={};Object.entries(t).forEach(([M,P])=>{y[M]=E(P)});let b=await C0({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 R0({node:b[0],a11yIdNodeMap:C,dataMomenticIdMap:I,selectorToNodeMap:_,nodeIdHasPointingLabelMap:R,explicitLabelTargetDomIds:g,domGraph:e,logger:n,callId:S,useMPaths:u,iconKnowledgeBase:p}),new _v(b[0],C,I,_,R)}function YQ(t,e,r,n){if(t==="class"){if(DQ.includes(r.tagName?.toLowerCase()??""))return e.split(" ").filter(a=>a.length<wv&&!Rn.bannedClassSubstrings.some(s=>a.includes(s))).slice(0,3).join(" ");let o=e.split(" "),i=[];for(let a of o)if(x0(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 XQ(t,e,r){if(!e)return;Object.entries(e.attributes).forEach(([a,s])=>{let c=t[a]||a.startsWith("aria")||FQ.includes(a);if((Rn.relevantElementAttributes.includes(a)||_0(a,r))&&!c){let u=YQ(a,s,e,r);u!==null&&(t[a]=u)}});let n,o=[];if(e.computedStyles.position&&E0.includes(e.computedStyles.position))n=e.computedStyles.position;else if(e.attributes.style){for(let a of E0)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 JQ(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 x0(t,e){if(e&&I0(t,e))return!0;if(Rn.bannedClassSubstrings.some(r=>t.includes(r)))return!1;if(Rn.alwaysInterestingClassNames.includes(t))return!0;for(let r of Rn.alwaysInterestingClassPrefixes)if(t.startsWith(r))return!0;return!1}function _0(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 I0(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 ZQ=["Accessibility","DOMSnapshot","DOMStorage"],fg=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 ZQ)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 Nc="<empty>";function e8(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 M0(t){let e=t.adFrameStatus?.adFrameType;return e==="child"||e==="root"||e8(t.url)}async function t8(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 Dc({cdpClient:t,page:e,logger:r}){let n={type:"root",childFrames:[],page:e},o=[],[i,a]=await Promise.all([t.send({timeout:Lc,method:"Page.getFrameTree",params:{}}),t.send({timeout:Lc,method:"DOM.getDocument",params:{depth:0}})]),l=(i.frameTree.childFrames??[]).map(async(d,p)=>{if(M0(d.frame))return null;try{return await O0({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 O0({cdpClient:t,rawFrameTree:e,indices:r,parent:n,warnings:o,logger:i}){let a=e.frame.id,s=await t8(t,a),c=s.attributes??[],l=null,u=[];for(let f of["src","name","id","title","srcdoc","sandbox"]){let h=xa(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(M0(f.frame))return null;try{return await O0({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 r8(t){try{return await t.owner().count()===1}catch{return!1}}async function n8(t){try{return await t.count()===1}catch{return!1}}async function ei(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,Nc]){let p=o.frameLocator(d===Nc?"iframe":`iframe[${d}]`);if(await r8(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,Nc]){let u=o.locator(l===Nc?"iframe":`iframe[${l}]`);if(await n8(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 P0(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 L0({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===Nc?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===Nc?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 ei(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=P0(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 ei(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=P0(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 ei(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 ei(n,t)).frame,handle:n,mPathSelectorTokens:r.mPathSelectorTokens,frameTree:e},logs:i};throw i.push(`Found ${a.length} frames with indices ${r.indices}`),new gn("Failed to find the iframe that previously contained this element",[{type:"AUTO_FRAME",matched:!1,logs:i}],"could-not-find-iframe")}function hg(t){return t.type==="auto"?JSON.stringify({type:"auto",frameId:t.handle.frameId}):JSON.stringify(t)}function Pv(t){for(;t.parent.type==="frame";)t=t.parent;return t.parent}function N0(t){let e=Pv(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 D0(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 k0({frame:t,logger:e,signal:r}){let n;try{n=await t.frameElement(),await o8({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 o8({frameElementHandle:t,logger:e,signal:r}){let n=await t.boundingBox(),i=await Kd({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 Mv=()=>{let t,e,r=new Promise((n,o)=>{t=n,e=o});return{resolve:t,reject:e,value:r}};var U0=(t,e)=>{let r=t.name??`batcher:${Math.random().toString(16).slice(2)})`,n=t.scheduler??i8(10),o=globalThis.__BATSHIT_DEVTOOLS__?.for(r),i=e??{seq:0,batch:new Set,currentRequest:Mv(),timer:void 0,start:null,latest:null,abortController:new AbortController};o?.create({seq:i.seq});let a=()=>{i.batch=new Set,i.currentRequest=Mv(),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 i8=t=>(e,r)=>{let n=r-e;return t-n};var F0=({windowMs:t,maxBatchSize:e})=>(r,n,o)=>{if(o>=e)return"immediate";let i=n-r;return t-i};import{reduce as a8}from"lodash-es";var s8=100,l8=2e3;function B0(t){return U0({fetcher:async r=>{t(a8(r,(n,o)=>({...n,...o}),{}))},resolver:()=>{},scheduler:F0({windowMs:l8,maxBatchSize:s8})})}async function z0({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 ti}from"crypto";import c8 from"js-beautify";var u8=["Dead"],gg=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:ti(),type:"PRESET_ACTION",command:ui(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=ui(i);a={id:ti(),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=ui(i);a={id:ti(),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=ui(i);a={id:ti(),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=c8.html(d,{indent_size:1,indent_with_tabs:!1,preserve_newlines:!1}),d=pk(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(u8.includes(r)||this.signal.aborted)return;let o="normal";r.length>1&&(o="special");let i;if(o==="normal"){let d=ui("TYPE");i={id:ti(),type:"PRESET_ACTION",command:{...d,target:void 0,value:r,clearContent:!1}}}else{let d=ui("PRESS");i={id:ti(),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:ti(),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:ti(),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=ui(l);u.deltaY=Math.abs(i);let d={id:ti(),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=ui(l);u.deltaX=Math.abs(i);let d={id:ti(),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 Ov}from"zod";var C8e=Ov.object({type:Ov.literal("url"),url:Ov.string()});var Sg=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=Pv(e),{frame:o,mPathSelectorTokens:i}=await ei(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 Dc({cdpClient:this.cdpClient,page:r,logger:this.logger}),{resolution:o,logs:i}=await L0({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(hg(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:hg(this.frameConfig),cacheTime:Date.now(),frameTree:this.frameConfig.frameTree,mPathSelectorTokens:this.frameConfig.mPathSelectorTokens},await k0({frame:n.frame,logger:e,signal:r}),this.activeFrameCache=n,n}async executeFunctionInAllFrames(e,r){let n=this.pageGetter(),o=await Dc({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(ei(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 Dc({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 oo({fn:()=>this.getDomGraph({devicePixelRatio:e.devicePixelRatio??1,signal:o,logger:n}),codePath:"domFetch",logObject:r,signal:o,logger:n}),c=await oo({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 oo({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 oo({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 oo({fn:()=>Dc({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 oo({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:Ho,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=g0({node:o,domGraph:this.domGraph});return S0(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 y0(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(Pi(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 Dc({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:hg(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=xa(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 ei(s,o)});break}}else if(n.trim()===d.trim()){a.push({handle:s,matchType:"url",...await ei(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 w0({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 ei(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(xa(r,"aria-hidden")==="true")return{shouldUnroll:!1,reason:"aria-hidden"};let n=xa(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 oo({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 oo({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 oo({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 oo({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 oo({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 h0({snapshot:o,devicePixelRatio:e,computedStylesToFetch:this.computedStylesToFetch,logger:n})}constructIframeRegexAsync(e,r){if(r.frameSrcRegex||r.frameUrlRegex)return;let n=N0(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 io=class t{static USER_AGENT=lg;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}){vI(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={[dk]:this.userBrowserSettings.visualActions},a=[];this.userControlledBrowserSettings.extraHeaders&&a.push(this.context.setExtraHTTPHeaders(this.userControlledBrowserSettings.extraHeaders)),e&&a.push(this.context.grantPermissions(Xk(r))),a.push(this.context.addInitScript({content:`${$b.htmlUtilsLibJs}
|
|
4610
|
+
${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:Rv(this.internalProperties),importantProperties:this.importantProperties,parentFrame:this.parentFrame,flagNotActionableNodes:this.flagNotActionableNodes});return e.tagName=this.tagName,e.dataMomenticId=this.dataMomenticId,e.properties=Rv(this.properties),e}},_v=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(Iv.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 qQ(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 KQ(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?(Vm({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?(Vm({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 C0({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=GQ.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&&!KQ(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 xv({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??v0).includes(W.name)||A0.includes(W.name))??[],pathFromRoot:(e?`${e.pathFromRoot} `:"")+qQ(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 U=C?.childrenBackendIds?.length??0,G=(t.childIds??[]).filter(W=>!!P.get(parseInt(W))).length;if(U>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 C0({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 JQ(R),C&&p&&Cv(C,i),[R]}function R0({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:Iv.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=Av(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=R0({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 w0({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=NQ(),g=new Set,E=M=>{let P=M.allNodes.filter(U=>!U.ignoredReasons?.find(z=>(m??v0).includes(z.name))),B=new Map;return P.forEach(U=>{B.set(parseInt(U.nodeId),U)}),B},y={};Object.entries(t).forEach(([M,P])=>{y[M]=E(P)});let b=await C0({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 R0({node:b[0],a11yIdNodeMap:C,dataMomenticIdMap:I,selectorToNodeMap:_,nodeIdHasPointingLabelMap:R,explicitLabelTargetDomIds:g,domGraph:e,logger:n,callId:S,useMPaths:u,iconKnowledgeBase:p}),new _v(b[0],C,I,_,R)}function YQ(t,e,r,n){if(t==="class"){if(DQ.includes(r.tagName?.toLowerCase()??""))return e.split(" ").filter(a=>a.length<wv&&!Rn.bannedClassSubstrings.some(s=>a.includes(s))).slice(0,3).join(" ");let o=e.split(" "),i=[];for(let a of o)if(x0(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 XQ(t,e,r){if(!e)return;Object.entries(e.attributes).forEach(([a,s])=>{let c=t[a]||a.startsWith("aria")||FQ.includes(a);if((Rn.relevantElementAttributes.includes(a)||_0(a,r))&&!c){let u=YQ(a,s,e,r);u!==null&&(t[a]=u)}});let n,o=[];if(e.computedStyles.position&&E0.includes(e.computedStyles.position))n=e.computedStyles.position;else if(e.attributes.style){for(let a of E0)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 JQ(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 x0(t,e){if(e&&I0(t,e))return!0;if(Rn.bannedClassSubstrings.some(r=>t.includes(r)))return!1;if(Rn.alwaysInterestingClassNames.includes(t))return!0;for(let r of Rn.alwaysInterestingClassPrefixes)if(t.startsWith(r))return!0;return!1}function _0(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 I0(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 ZQ=["Accessibility","DOMSnapshot","DOMStorage"],fg=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 ZQ)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 Nc="<empty>";function e8(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 M0(t){let e=t.adFrameStatus?.adFrameType;return e==="child"||e==="root"||e8(t.url)}async function t8(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 Dc({cdpClient:t,page:e,logger:r}){let n={type:"root",childFrames:[],page:e},o=[],[i,a]=await Promise.all([t.send({timeout:Lc,method:"Page.getFrameTree",params:{}}),t.send({timeout:Lc,method:"DOM.getDocument",params:{depth:0}})]),l=(i.frameTree.childFrames??[]).map(async(d,p)=>{if(M0(d.frame))return null;try{return await O0({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 O0({cdpClient:t,rawFrameTree:e,indices:r,parent:n,warnings:o,logger:i}){let a=e.frame.id,s=await t8(t,a),c=s.attributes??[],l=null,u=[];for(let f of["src","name","id","title","srcdoc","sandbox"]){let h=xa(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(M0(f.frame))return null;try{return await O0({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 r8(t){try{return await t.owner().count()===1}catch{return!1}}async function n8(t){try{return await t.count()===1}catch{return!1}}async function ei(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,Nc]){let p=o.frameLocator(d===Nc?"iframe":`iframe[${d}]`);if(await r8(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,Nc]){let u=o.locator(l===Nc?"iframe":`iframe[${l}]`);if(await n8(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 P0(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 L0({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===Nc?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===Nc?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 ei(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=P0(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 ei(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=P0(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 ei(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 ei(n,t)).frame,handle:n,mPathSelectorTokens:r.mPathSelectorTokens,frameTree:e},logs:i};throw i.push(`Found ${a.length} frames with indices ${r.indices}`),new gn("Failed to find the iframe that previously contained this element",[{type:"AUTO_FRAME",matched:!1,logs:i}],"could-not-find-iframe")}function hg(t){return t.type==="auto"?JSON.stringify({type:"auto",frameId:t.handle.frameId}):JSON.stringify(t)}function Pv(t){for(;t.parent.type==="frame";)t=t.parent;return t.parent}function N0(t){let e=Pv(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 D0(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 k0({frame:t,logger:e,signal:r}){let n;try{n=await t.frameElement(),await o8({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 o8({frameElementHandle:t,logger:e,signal:r}){let n=await t.boundingBox(),i=await Kd({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 Mv=()=>{let t,e,r=new Promise((n,o)=>{t=n,e=o});return{resolve:t,reject:e,value:r}};var U0=(t,e)=>{let r=t.name??`batcher:${Math.random().toString(16).slice(2)})`,n=t.scheduler??i8(10),o=globalThis.__BATSHIT_DEVTOOLS__?.for(r),i=e??{seq:0,batch:new Set,currentRequest:Mv(),timer:void 0,start:null,latest:null,abortController:new AbortController};o?.create({seq:i.seq});let a=()=>{i.batch=new Set,i.currentRequest=Mv(),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 i8=t=>(e,r)=>{let n=r-e;return t-n};var F0=({windowMs:t,maxBatchSize:e})=>(r,n,o)=>{if(o>=e)return"immediate";let i=n-r;return t-i};import{reduce as a8}from"lodash-es";var s8=100,l8=2e3;function B0(t){return U0({fetcher:async r=>{t(a8(r,(n,o)=>({...n,...o}),{}))},resolver:()=>{},scheduler:F0({windowMs:l8,maxBatchSize:s8})})}async function z0({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 ti}from"crypto";import c8 from"js-beautify";var u8=["Dead"],gg=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:ti(),type:"PRESET_ACTION",command:ui(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=ui(i);a={id:ti(),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=ui(i);a={id:ti(),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=ui(i);a={id:ti(),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=c8.html(d,{indent_size:1,indent_with_tabs:!1,preserve_newlines:!1}),d=pk(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(u8.includes(r)||this.signal.aborted)return;let o="normal";r.length>1&&(o="special");let i;if(o==="normal"){let d=ui("TYPE");i={id:ti(),type:"PRESET_ACTION",command:{...d,target:void 0,value:r,clearContent:!1}}}else{let d=ui("PRESS");i={id:ti(),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:ti(),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:ti(),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=ui(l);u.deltaY=Math.abs(i);let d={id:ti(),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=ui(l);u.deltaX=Math.abs(i);let d={id:ti(),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 Ov}from"zod";var R8e=Ov.object({type:Ov.literal("url"),url:Ov.string()});var Sg=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=Pv(e),{frame:o,mPathSelectorTokens:i}=await ei(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 Dc({cdpClient:this.cdpClient,page:r,logger:this.logger}),{resolution:o,logs:i}=await L0({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(hg(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:hg(this.frameConfig),cacheTime:Date.now(),frameTree:this.frameConfig.frameTree,mPathSelectorTokens:this.frameConfig.mPathSelectorTokens},await k0({frame:n.frame,logger:e,signal:r}),this.activeFrameCache=n,n}async executeFunctionInAllFrames(e,r){let n=this.pageGetter(),o=await Dc({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(ei(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 Dc({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 oo({fn:()=>this.getDomGraph({devicePixelRatio:e.devicePixelRatio??1,signal:o,logger:n}),codePath:"domFetch",logObject:r,signal:o,logger:n}),c=await oo({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 oo({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 oo({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 oo({fn:()=>Dc({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 oo({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:Ho,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=g0({node:o,domGraph:this.domGraph});return S0(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 y0(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(Pi(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 Dc({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:hg(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=xa(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 ei(s,o)});break}}else if(n.trim()===d.trim()){a.push({handle:s,matchType:"url",...await ei(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 w0({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 ei(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(xa(r,"aria-hidden")==="true")return{shouldUnroll:!1,reason:"aria-hidden"};let n=xa(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 oo({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 oo({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 oo({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 oo({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 oo({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 h0({snapshot:o,devicePixelRatio:e,computedStylesToFetch:this.computedStylesToFetch,logger:n})}constructIframeRegexAsync(e,r){if(r.frameSrcRegex||r.frameUrlRegex)return;let n=N0(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 io=class t{static USER_AGENT=lg;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}){vI(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={[dk]:this.userBrowserSettings.visualActions},a=[];this.userControlledBrowserSettings.extraHeaders&&a.push(this.context.setExtraHTTPHeaders(this.userControlledBrowserSettings.extraHeaders)),e&&a.push(this.context.grantPermissions(Xk(r))),a.push(this.context.addInitScript({content:`${$b.htmlUtilsLibJs}
|
|
4611
4611
|
//# sourceURL=momentic-injected/browser-scripts.js`}),this.context.addInitScript({content:mv(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:`${$b.htmlUtilsLibJs}
|
|
4612
4612
|
//# sourceURL=momentic-injected/browser-scripts.js`}),this.page.addScriptTag({content:mv(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"&&S8()==="darwin"&&d8("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 fg.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 Sg({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 Kk(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 bv(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=yg(),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()||!ws(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=yg(),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=>{Mk(e,o,this.debugData,a,this.logger)});let i=async()=>{!this.userBrowserSettings.disableBrowserMonitoring&&!this.userControlledBrowserSettings.disableNetworkLogs&&(Nk(this.logger,r,this.clientCallbacks?.onNetworkPage,e),!this.harBatcher&&this.clientCallbacks?.onNetworkLogs&&(this.harBatcher=B0(this.clientCallbacks.onNetworkLogs)),await e.route("**/*",async(a,s)=>{await av({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("**/*",zk(this.customHeaders,this.logger))),Vn&&await e.route("**/*",rp),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"||!ws(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(yv(this.getBrowserCallbacks()),{milliseconds:Je})}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<Lc;){a++,n?.throwIfAborted();try{if(await Qt({fn:()=>{let c=window;return!!(c.generateCssSelectors&&c.evaluateCssSelectors&&c.evaluatePrimaryCaches&&c.generateHtmlCacheAttributes&&c.ldist)},timeout:Je,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(Aa),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 G0.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&&f8(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 G0.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}){PN(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:Je})}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(Ek.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:Je,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 i0({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(Aa),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??AC}),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 pg({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:Je}),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 Pk(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:Je,fn:async()=>{for(let c of e.origins??[])for(let l of c.localStorage)try{await this.cdpClient.send({timeout:Je,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:hv}),this.logger.info(`Loaded ${a} session storage entries`);let s=e.idb;s&&Object.keys(s).length>0&&(await Ik(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 _k(this.page,this.logger),await Qk(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 bv(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 El)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||!gv(e,n))return;let i=await r.boundingBox({timeout:Je});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=yg(),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,Rn.serializedElementForCachingTruncateLength)}if(o?.attributes&&o.attributes.length>0){let c={};for(let l of o.attributes){let u=l.trim().toLowerCase();if(!(!u||Rn.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:Zk(r,l),relativeDistance:e0(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:D0(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 gu)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 gn&&(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:op(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 gn("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 gu("Insufficient data to resolve target using primary methods (missing node HTML)");let s={x:0,y:0};if(Jk(e)){let P=await(await e.frameElement()).boundingBox();P&&(s=P)}let c=i?n:Ho,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:yk,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 gn("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(Pi(_));else throw new L("InternalWebAgentError","Received an element resolution result with no identifying attributes");let R=op(r);await this.updateCacheWithNewNodeDetails({node:I,target:r,locator:C,logger:n,originalElementLocationResult:E,allowNotActionableNodesOverride:o,skipSavingVisualAttributes:a});let M=Lv(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 Sv({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:Je});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<Sk){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(Pi(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=op(r);await this.updateCacheWithNewNodeDetails({node:d,target:r,locator:p,logger:o,originalElementLocationResult:l,allowNotActionableNodesOverride:a,skipSavingVisualAttributes:s});let h=Lv(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 Sv({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&&gv(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=T8(),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=op(r);await this.updateCacheWithNewNodeDetails({target:r,node:h,locator:d,allowNotActionableNodesOverride:o});let g=Lv(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:Je})??"";let i=o0.some(a=>a===o.toLowerCase());return await Ev({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 Ev({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(),Ch(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"} ${lh(r)} in ${o}ms.
|
|
4613
4613
|
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 u0({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(Aa),await this.page.mouse.up()}async hover(e){await this.highlight(e.locator),await Bs({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 Bs({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:Je,codePath:"blurring the active element"});return}await this.highlight(e.locator),await Bs({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 Bs({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=mg(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=mg(e,this.properties.isAndroid);n!==e&&(this.logger.info({keyString:e,convertedKey:n},"Converted platform dependent keys"),e=n)}for(let n of fv(e))await this.page.keyboard.down(n)}async keyUp(e,r){if(r.convertMeta){let n=mg(e,this.properties.isAndroid);n!==e&&(this.logger.info({keyString:e,convertedKey:n},"Converted platform dependent keys"),e=n)}for(let n of fv(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:Ho;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 dn().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<Aa&&await xe(Aa-(p-d),o),d=Date.now(),!(Date.now()-e.value<qb)){if(s)try{let m=await this.screenshot(c);if(r0(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<qb)){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 d0(this.page,e,r,n)}async mouseDragUsingVisualCoordinates(e){let{fromTarget:r,...n}=e;await vv({...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=hk);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 Tv({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 Tv({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=j0(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)}.
|
|
@@ -4616,7 +4616,7 @@ ${t}`;case"ELEMENT_CHECK":return`${K0}
|
|
|
4616
4616
|
${t}`;default:return t}}async function ao({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 A8=["NAVIGATE","NEW_TAB","TAB","REFRESH","WAIT_FOR_URL"];async function J0({beforeUrl:t,beforePages:e,browser:r,command:n,logger:o}){if(A8.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(ws(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 ri(t,e={}){let r=await t.getBrowserState(e);return{serializedTree:r.serialize(e.serializationOpts),tree:r}}var Q0=t=>!!t&&nl(t),Z0=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&&!Y0(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 P8}from"crypto";var tU={minChunkTokenCount:500,acceptableChunkTokenCount:3e3,maxChunkTokenCount:8e3,maxLineLength:4e3},rU={minChunkTokenCount:5e3,acceptableChunkTokenCount:1e4,maxChunkTokenCount:3e4,maxLineLength:500},eU=/<(\S+) id="(\d+)".*?>/g,R8=/(<\/(\S+)>)|(<(\S+).*?\/>)/g,nU=["h1","h2","section","footer","nav","aside","form","label","dialog"],w8=[...nU,"span","div","h3"],x8=["table","select","form","ul","ol","menu","pre","code","dialog"],_8=["table","form","dialog","nav","section","ul","select"];function Tg(t){return I8(t)}function I8({logger:t,serializedTree:e,options:r}){let{minChunkTokenCount:n,acceptableChunkTokenCount:o,maxChunkTokenCount:i,maxLineLength:a}=r,s=[],c=e.split(`
|
|
4617
4617
|
`),l=0,u=[],d=0,p=[],m=[],f=!1;for(;l<c.length;){f&&(s.push({ids:p,content:u.join(`
|
|
4618
4618
|
`),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(eU)).map(z=>z&&z.length>=3?{tagName:z[1],id:z[2]}:void 0).filter(z=>!!z),C=Array.from(h.matchAll(R8)).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=>x8.includes(z.tagName)),R=c[l+1]??"",M=et(R),B=Array.from(R.matchAll(eU)).map(z=>z&&z.length>2?z[1]:void 0).filter(z=>!!z),U=B.some(z=>nU.includes(z)),G=B.some(z=>w8.includes(z));d+M>=i&&(f=!0),d>=n&&(U&&!_||C.some(z=>_8.includes(z)))&&(f=!0),d>=o&&G&&!_&&(f=!0),l++}return u.length&&s.push({ids:p,content:u.join(`
|
|
4619
|
-
`),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 M8=75e4,bg=3e5;async function Hs(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>M8)try{let p=Tg({serializedTree:u,options:{minChunkTokenCount:1e4,maxChunkTokenCount:1e5,acceptableChunkTokenCount:5e4,maxLineLength:4e3},logger:i});l=await L8({...t,tokenLimit:bg-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(bg*ma),u=l.serialize();let m=et(u);i.info({oldTokens:d,newTokens:m},"Filtered page using naive truncation"),d=m}if(d>bg)try{if(o){let p=Tg({serializedTree:u,options:rU,logger:i}),m=P8();l=await J(O8({...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=Tg({serializedTree:u,options:tU,logger:i});l=await J(N8({...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(bg*ma),u=l.serialize(),i.info("Filtered page using naive truncation")}return u}async function O8({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 L8(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 N8(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 Dv(t,e){if(!t.description)throw new L("UserConfigurationError","Cannot locate element with empty description");return ao({action:async()=>D8(t,e),frameConfig:t.iframeUrl?{type:"url",url:t.iframeUrl}:void 0,browser:e.browser,logger:t.logger})}async function D8(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=dn(),C=t.useMemory&&!r;n&&(y=await Qr({orgId:f,s:y,context:n,localTools:S,signal:E,logger:l})),a&&(y=X0(y,a));let{serializedTree:I,tree:_}=await b.startAsyncSpan("GET_PAGE_STATE",async()=>ri(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,U=`data:image/jpeg;base64,${R.toString("base64")}`;M=await Hs({type:"locator",description:y,screenshot:U,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:U,source:a,memory:C?s:void 0},{disableCache:r,abortSignal:E,loggerTags:ot(l),useMemory:C});if(X.result=ne,b.storeTraceAsset){let de=oU();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 yl(`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=oU();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:U}}import{randomUUID as iU}from"crypto";var k8=15;async function vg({command:t,aiPageFiltering:e,logger:r,fixtures:n,useMemory:o,maxRetries:i=k8}){if(!t.assertion.trim())throw new L("ActionFailureError","Assertion command is missing the assertion content");let a=hy.optional().catch(void 0).parse(t.source);t.source&&!a&&r.warn(`Invalid source ${t.source} for AI assertion, ignoring...`);let s=dn();return s.startAsyncSpan("AI_ASSERTION_CALL",async c=>{let{browser:l}=n,u=t.timeout?t.timeout*1e3:l.smartWaitingTimeout,d=IN(u,i-1),p=0,m=Date.now(),f=m+u,h=m,S,g,E;try{await ao({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 ao({action:async()=>{let M=await aU(l,r,n.abortSignal);return g&&g.serializedTree===M.serializedTree&&g.screenshotBuff.equals(M.screenshotBuff)?(_=!0,S):(g=M,sU({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&&Gd(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 ao({action:async()=>sU({command:t,state:await aU(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&&Gd(t,S.updatedMemory,r);let y=S?.afterScreenshotOverride;if(y&&s.storeTraceAsset){let C=iU();s.storeTraceAsset({snapshotId:C,data:y}),c.screenshotSnapshotId=C}let b=S?.elementScreenshotOverride;if(b&&s.storeTraceAsset){let C=iU();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 aU(t,e,r){let[n,o]=await Promise.all([ri(t,{abortSignal:r,skipWait:!0,skipWaitForPageLoad:!0,logger:e}),t.screenshot({retries:1,respectActiveFrame:!0})]);return{...n,screenshotBuff:o}}async function sU({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 Hs({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 U8(_.relevantElements,u,l)}return{success:_.result,thoughts:_.thoughts,afterScreenshotOverride:S,elementScreenshotOverride:R,updatedMemory:o?_.updatedMemory:void 0}}async function U8(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 F8=1e5,Ag=class extends Error{constructor(){super("The page content exceeds the maximum token limit for AI smart waiting."),this.name="ExceededMaxAISmartWaitingTokensError"}};async function lU(t,e){let{logger:r}=t,{abortSignal:n,browser:o}=e,i=Date.now();try{await B8(i,t,e)}catch(a){if(a instanceof Error&&(a.name==="AbortError"||a.name==="TimeoutError")||n.aborted)return;a instanceof Ag?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 B8(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(z8(t,e,r),{milliseconds:o.smartWaitingTimeout})}async function z8(t,e,r){let{logger:n,iframeUrl:o}=e,{browser:i}=r;for(;Date.now()-t<i.smartWaitingTimeout;)if(await ao({action:async()=>H8(e,r),frameConfig:o?{type:"url",url:o}:void 0,browser:i,logger:n}))return}async function H8(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 Qr({orgId:l,s:d,context:r,localTools:c,signal:s,logger:n}));let{serializedTree:p}=await ri(a,{allowNotActionableNodesOverride:i,filterByViewport:o,abortSignal:s,logger:n});if(et(p)>F8)throw new Ag;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 uU}from"lodash-es";async function dU(t){return dn().startAsyncSpan("ELEMENT_ASSERTION",async r=>G8(t,r),{name:"Element check"})}async function G8(t,e){let{command:r,timeoutMs:n,fixtures:o,disableCache:i}=t,{abortSignal:a}=o,s=()=>jp(r.cache)?r.cache:void 0,c=s(),l=!i&&!!c?.target&&nl(c.target),u=uU(c),d=(E=!1)=>{if(c=s(),!!c)if(E){let y=qT(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 cU({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 cU({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=Hd(g.target),g.updatedAt=new Date),e.result={success:f.success,message:f.err?.message},f}async function cU({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&&!Gi(o.target))throw new Error("Element assertion with x/y is not supported yet");let u=bL(o.assertion),d,p=!1,m=uU(t);try{let{elementInteractedDisplayString:f,result:h,thoughts:S}=await c({tracer:s,command:o,target:o.target,cache:m?.target,action:async g=>j8(g.locator,n),options:{...o,allowNotActionableNodesOverride:!0,disableCache:i,memory:m?.target?.memory,disableGlobalLocatorRedirect:!0,source:Ja(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 j8(t,{command:e,fixtures:r}){return await r.browser.highlight(t),await V8(t,e.assertion)}async function V8(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)},!Bd(a,e.value,e.operation,{negated:!!e.negated,ignoreCase:!1})){let s=fc(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(!Bd(a,e.value,e.operation,{negated:!!e.negated,ignoreCase:!1})){let s=fc(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},kn*1e3);break}case"EDITABLE":{r=await t.isEditable({timeout:kn*1e3});break}case"EXISTS":{r=!0;break}case"ENABLED":{r=await t.isEnabled({timeout:kn*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=fc(e);n=new L("AssertionFailureError",`The element ${a}`)}break}case"ELEMENT_NAME":{let a=await t.evaluate(s=>s.tagName);if(!Bd(a,e.value,e.operation,{negated:!!e.negated,ignoreCase:!0})){let s=fc(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(!Bd(a,e.value,e.operation,{negated:!!e.negated,ignoreCase:!1})){let s=fc(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 pU(t){return t.type==="ELEMENT_EXISTENCE"&&t.negated&&t.condition==="EXISTS"}import{Jimp as W8}from"jimp";async function ip(t,e){let r=await t.screenshot(e),n=await W8.fromBuffer(r);return{buffer:r,width:Math.ceil(n.bitmap.width??0),height:Math.ceil(n.bitmap.height??0)}}import{Jimp as mU}from"jimp";import kv from"jpeg-js";import $8 from"pixelmatch";async function fU({tracer:t,command:e,disableCache:r,browser:n,targetingWrapper:o,logger:i,screenshotStorage:a}){if(e.target&&!Gi(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=>ip(n,{locator:P.locator,...s}),options:{...e,disableCache:r,disableGlobalLocatorRedirect:!0,memory:e.cache?.target?.memory,targetName:"target"}})).result:c=await ip(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 mU.fromBuffer(c.buffer),d={width:c.width,height:c.height},p=await mU.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=$8(kv.decode(l.buffer).data,kv.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:kv.encode(y,75).data,succeedImmediately:!1,urlAfterCommand:n.url()}}var q8=3e4;function K8(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 hU({command:t,logger:e,baseUrl:r,fetchImplementation:n=fetch}){let o=t.timeout??q8/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(Tc(t.url)&&(c=t.url),r&&bc(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=K8(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 Y8=5e3;async function Cg({timeout:t=kn,...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 gU(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),Y8);else return i}return i=await gU(e),i}async function gU({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(SU,{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(SU,{value:t.value,negated:!!t.negated,returnHtml:!0},"checking page content"));if(!i){let c=t.negated?Ti.CONTAINS:bi.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 SU({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 X8=3e4;async function yU({command:t,logger:e,baseUrl:r,fetchImplementation:n=fetch}){let o=t.timeout??X8/1e3,i=new AbortController,a=Object.fromEntries(Object.entries(t.headers||{}).filter(([d,p])=>d&&p));a["Content-Type"]="application/json";let s;if(Tc(t.url)&&(s=t.url),r&&bc(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 _a=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([ri(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 Hs({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([ri(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 Hs({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 ri(this.browser,e)}async locateElement(e){return await Dv({...e,aiPageFiltering:!!this.options?.aiPageFiltering},this.getControllerFixtures())}async locateElementWithSelector(e,r){return ao({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=dn(),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=J8();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 dn().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 gn&&(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 ao({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=dn(),f=this.logger.child({commandId:a.id}),h=this.shouldUseMemory(),S=EU(e.cache);if((!S||u)&&!_S(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=Z0({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(!Q0(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.72.0"]),mh({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=jS(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.72.0",`missReason:${C instanceof gn?C.cacheMissReason:"unknown"}`]);let _;return S.memory&&zp(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 lU({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 Dv({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 yl&&b.updatedLocatorMemory){let C={id:-1,...c,memory:b.updatedLocatorMemory};mh({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 mh({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&&jS(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 ip(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 J0({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{lk(r,s)}}createCallbacksForBrowser(e){return{createIsolatedFolder:()=>rv(e)}}async traceBrowserInteraction(e,r,n){return dn().startAsyncSpan("BROWSER_INTERACTION",async()=>r(),{name:e,...n})}async resolveCommandTemplateStrings(e,r){return ig({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()?vg({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 vg({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=bI(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(!Tc(r.url)&&!bc(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 Rh(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(!Gi(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:Ja(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 va({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=EU(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:Ja(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 Rh(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(!Gi(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&&!Gi(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 Rh(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 Z8,s=Q8(fetch,a),c;try{c=new URL(r.url).hostname}catch{}let l=await hU({command:r,baseUrl:this.browser.baseUrl,logger:i,fetchImplementation:s});return{data:uu.parse({...l,cookies:bx(a,c)}),succeedImmediately:!1,urlAfterCommand:this.browser.url()}}case"GRAPHQL_REQUEST":return{data:await yU({command:r,baseUrl:this.browser.baseUrl,logger:i}),succeedImmediately:!1,urlAfterCommand:this.browser.url()};case"VISUAL_DIFF":return fU({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 wk({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 va({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=Im.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??kn)*1e3,s=this.generator.getAgentConfig()?.assertion;if(pU(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 vg({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&&Gd(r,l.cache?.memory.traces,i)}}let c=await dU({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 ao({action:async()=>Cg({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 Ra(r.requestMatcher),s=this.browser.registerRequestListener(a);return this.registeredListeners[r.key]=s.then(async c=>await sv(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 Ra(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]=ug(c)},onRequestComplete:(s,c)=>{this.recordedRequests[r.key]?.[s]&&(this.recordedRequests[r.key][s]=ug(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 Ra(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 Ra(r.requestMatcher),async(s,c)=>{let l=await va({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=Kx.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 gg({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 Uv=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(Wd({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 Qr({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<R_;){d?.throwIfAborted();let y=await i.getCacheResult(h);if(y){n.info({cacheResult:vt(y,1e3,!0)},"Got result from module execution cache"),p=Rg(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:${e9()};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 t9(t);else if(e.autoAuth){let S=Im.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 Cg({timeout:kn,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),Uv(t)}}finally{try{f!==void 0&&!m&&p?.status==="SUCCESS"&&await r9({step:e,result:p,browser:s.browser,cacheKeyPrefix:f,logger:n,storage:i})}finally{f!==void 0&&await i.releaseCacheLock(f)}}return p},t9=async t=>{let{currentParentIdChain:e}=t,{step:r,tracer:n}=t.moduleParams,o=Rg(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,no({asyncTasks:t.work.asyncTasks,nestedResults:s,result:o,logger:t.fixtures.logger}),o};function Rg(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 TU({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 va({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 r9({step:t,result:e,browser:r,cacheKeyPrefix:n,logger:o,storage:i}){let a=t.cacheConfig?.cacheExpiryMs;(!a||a===gI)&&(a=t.defaultCacheTtl??SI);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:Wd({json:s,maxJsonStringSize:1e4})},"Setting module cache result"),await i.setCacheResult({result:s,keyPrefix:n,ttlMs:a})}async function Gs(t,e,r){return n9(t,e,r)}async function n9(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=Rg(t,{},"FAILED");return c.message=s,c.startedAt=n,c.finishedAt=i,c}return{...Ah(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 O9}from"lodash-es";import{randomUUID as bU}from"crypto";import{diff as o9}from"deep-object-diff";import{cloneDeep as vU}from"lodash-es";var wg=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?vU(e.command.cache):{},d=o.browser.url(),p=new Date,m,f=bU(),h=bU();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 ${vi(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?vU(e.command.cache):{},b=o9(u,y);b&&Object.keys(b).length>0&&l.info({diffs:Om(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 i9(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,()=>wg({...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 a9(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}=vs(a.steps,e,o);if(s)return i}return-1}async function AU(t){let{currentParentIdChain:e}=t,{step:r}=t.conditionalParams,{logger:n}=t.fixtures,{fromStep:o}=t.inputs,i=new Date,a=Ah(r),s=!!o&&zd(e,o.parentStepIdChain),c=r.elseSteps,l=!0,u=[],d,p=!1;if(s&&o){let g=a9(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 i9(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 no({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 no({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 no({asyncTasks:t.work.asyncTasks,nestedResults:[...u,...f.results],result:S,logger:n}),S}import{randomUUID as CU}from"crypto";var RU=async t=>{let{tracer:e}=t.aiStepParams,{controller:r}=t.fixtures;await r.browser.waitForStability();let n=await r.browser.screenshot({}),o=await s9(t);o.finishedAt=new Date,no({asyncTasks:t.work.asyncTasks,result:o,nestedResults:o.results,logger:t.fixtures.logger});let i=await r.browser.screenshot({}),a=CU();o.beforeSnapshot=a,e.attachBeforeScreenshot({snapshotId:a,screenshot:n});let s=CU();return o.afterSnapshot=s,e.attachAfterScreenshot({snapshotId:s,screenshot:i}),o},s9=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 Hv}from"crypto";var wU=t=>{throw new Error(`Exhaustive check failed for value: ${t}`)};import{streamText as E9}from"ai";var xg=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 g9,stepCountIs as S9}from"ai";import xU from"dedent";var c9=xU`
|
|
4619
|
+
`),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 M8=75e4,bg=3e5;async function Hs(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>M8)try{let p=Tg({serializedTree:u,options:{minChunkTokenCount:1e4,maxChunkTokenCount:1e5,acceptableChunkTokenCount:5e4,maxLineLength:4e3},logger:i});l=await L8({...t,tokenLimit:bg-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(bg*ma),u=l.serialize();let m=et(u);i.info({oldTokens:d,newTokens:m},"Filtered page using naive truncation"),d=m}if(d>bg)try{if(o){let p=Tg({serializedTree:u,options:rU,logger:i}),m=P8();l=await J(O8({...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=Tg({serializedTree:u,options:tU,logger:i});l=await J(N8({...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(bg*ma),u=l.serialize(),i.info("Filtered page using naive truncation")}return u}async function O8({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 L8(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 N8(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 Dv(t,e){if(!t.description)throw new L("UserConfigurationError","Cannot locate element with empty description");return ao({action:async()=>D8(t,e),frameConfig:t.iframeUrl?{type:"url",url:t.iframeUrl}:void 0,browser:e.browser,logger:t.logger})}async function D8(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=dn(),C=t.useMemory&&!r;n&&(y=await Qr({orgId:f,s:y,context:n,localTools:S,signal:E,logger:l})),a&&(y=X0(y,a));let{serializedTree:I,tree:_}=await b.startAsyncSpan("GET_PAGE_STATE",async()=>ri(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,U=`data:image/jpeg;base64,${R.toString("base64")}`;M=await Hs({type:"locator",description:y,screenshot:U,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:U,source:a,memory:C?s:void 0},{disableCache:r,abortSignal:E,loggerTags:ot(l),useMemory:C});if(X.result=ne,b.storeTraceAsset){let de=oU();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 yl(`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=oU();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:U}}import{randomUUID as iU}from"crypto";var k8=15;async function vg({command:t,aiPageFiltering:e,logger:r,fixtures:n,useMemory:o,maxRetries:i=k8}){if(!t.assertion.trim())throw new L("ActionFailureError","Assertion command is missing the assertion content");let a=hy.optional().catch(void 0).parse(t.source);t.source&&!a&&r.warn(`Invalid source ${t.source} for AI assertion, ignoring...`);let s=dn();return s.startAsyncSpan("AI_ASSERTION_CALL",async c=>{let{browser:l}=n,u=t.timeout?t.timeout*1e3:l.smartWaitingTimeout,d=IN(u,i-1),p=0,m=Date.now(),f=m+u,h=m,S,g,E;try{await ao({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 ao({action:async()=>{let M=await aU(l,r,n.abortSignal);return g&&g.serializedTree===M.serializedTree&&g.screenshotBuff.equals(M.screenshotBuff)?(_=!0,S):(g=M,sU({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&&Gd(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 ao({action:async()=>sU({command:t,state:await aU(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&&Gd(t,S.updatedMemory,r);let y=S?.afterScreenshotOverride;if(y&&s.storeTraceAsset){let C=iU();s.storeTraceAsset({snapshotId:C,data:y}),c.screenshotSnapshotId=C}let b=S?.elementScreenshotOverride;if(b&&s.storeTraceAsset){let C=iU();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 aU(t,e,r){let[n,o]=await Promise.all([ri(t,{abortSignal:r,skipWait:!0,skipWaitForPageLoad:!0,logger:e}),t.screenshot({retries:1,respectActiveFrame:!0})]);return{...n,screenshotBuff:o}}async function sU({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 Hs({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 U8(_.relevantElements,u,l)}return{success:_.result,thoughts:_.thoughts,afterScreenshotOverride:S,elementScreenshotOverride:R,updatedMemory:o?_.updatedMemory:void 0}}async function U8(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 F8=1e5,Ag=class extends Error{constructor(){super("The page content exceeds the maximum token limit for AI smart waiting."),this.name="ExceededMaxAISmartWaitingTokensError"}};async function lU(t,e){let{logger:r}=t,{abortSignal:n,browser:o}=e,i=Date.now();try{await B8(i,t,e)}catch(a){if(a instanceof Error&&(a.name==="AbortError"||a.name==="TimeoutError")||n.aborted)return;a instanceof Ag?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 B8(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(z8(t,e,r),{milliseconds:o.smartWaitingTimeout})}async function z8(t,e,r){let{logger:n,iframeUrl:o}=e,{browser:i}=r;for(;Date.now()-t<i.smartWaitingTimeout;)if(await ao({action:async()=>H8(e,r),frameConfig:o?{type:"url",url:o}:void 0,browser:i,logger:n}))return}async function H8(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 Qr({orgId:l,s:d,context:r,localTools:c,signal:s,logger:n}));let{serializedTree:p}=await ri(a,{allowNotActionableNodesOverride:i,filterByViewport:o,abortSignal:s,logger:n});if(et(p)>F8)throw new Ag;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 uU}from"lodash-es";async function dU(t){return dn().startAsyncSpan("ELEMENT_ASSERTION",async r=>G8(t,r),{name:"Element check"})}async function G8(t,e){let{command:r,timeoutMs:n,fixtures:o,disableCache:i}=t,{abortSignal:a}=o,s=()=>jp(r.cache)?r.cache:void 0,c=s(),l=!i&&!!c?.target&&nl(c.target),u=uU(c),d=(E=!1)=>{if(c=s(),!!c)if(E){let y=qT(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 cU({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 cU({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=Hd(g.target),g.updatedAt=new Date),e.result={success:f.success,message:f.err?.message},f}async function cU({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&&!Gi(o.target))throw new Error("Element assertion with x/y is not supported yet");let u=bL(o.assertion),d,p=!1,m=uU(t);try{let{elementInteractedDisplayString:f,result:h,thoughts:S}=await c({tracer:s,command:o,target:o.target,cache:m?.target,action:async g=>j8(g.locator,n),options:{...o,allowNotActionableNodesOverride:!0,disableCache:i,memory:m?.target?.memory,disableGlobalLocatorRedirect:!0,source:Ja(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 j8(t,{command:e,fixtures:r}){return await r.browser.highlight(t),await V8(t,e.assertion)}async function V8(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)},!Bd(a,e.value,e.operation,{negated:!!e.negated,ignoreCase:!1})){let s=fc(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(!Bd(a,e.value,e.operation,{negated:!!e.negated,ignoreCase:!1})){let s=fc(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},kn*1e3);break}case"EDITABLE":{r=await t.isEditable({timeout:kn*1e3});break}case"EXISTS":{r=!0;break}case"ENABLED":{r=await t.isEnabled({timeout:kn*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=fc(e);n=new L("AssertionFailureError",`The element ${a}`)}break}case"ELEMENT_NAME":{let a=await t.evaluate(s=>s.tagName);if(!Bd(a,e.value,e.operation,{negated:!!e.negated,ignoreCase:!0})){let s=fc(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(!Bd(a,e.value,e.operation,{negated:!!e.negated,ignoreCase:!1})){let s=fc(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 pU(t){return t.type==="ELEMENT_EXISTENCE"&&t.negated&&t.condition==="EXISTS"}import{Jimp as W8}from"jimp";async function ip(t,e){let r=await t.screenshot(e),n=await W8.fromBuffer(r);return{buffer:r,width:Math.ceil(n.bitmap.width??0),height:Math.ceil(n.bitmap.height??0)}}import{Jimp as mU}from"jimp";import kv from"jpeg-js";import $8 from"pixelmatch";async function fU({tracer:t,command:e,disableCache:r,browser:n,targetingWrapper:o,logger:i,screenshotStorage:a}){if(e.target&&!Gi(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=>ip(n,{locator:P.locator,...s}),options:{...e,disableCache:r,disableGlobalLocatorRedirect:!0,memory:e.cache?.target?.memory,targetName:"target"}})).result:c=await ip(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 mU.fromBuffer(c.buffer),d={width:c.width,height:c.height},p=await mU.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=$8(kv.decode(l.buffer).data,kv.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:kv.encode(y,75).data,succeedImmediately:!1,urlAfterCommand:n.url()}}var q8=3e4;function K8(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 hU({command:t,logger:e,baseUrl:r,fetchImplementation:n=fetch}){let o=t.timeout??q8/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(Tc(t.url)&&(c=t.url),r&&bc(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=K8(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 Y8=5e3;async function Cg({timeout:t=kn,...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 gU(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),Y8);else return i}return i=await gU(e),i}async function gU({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(SU,{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(SU,{value:t.value,negated:!!t.negated,returnHtml:!0},"checking page content"));if(!i){let c=t.negated?Ti.CONTAINS:bi.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 SU({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 X8=3e4;async function yU({command:t,logger:e,baseUrl:r,fetchImplementation:n=fetch}){let o=t.timeout??X8/1e3,i=new AbortController,a=Object.fromEntries(Object.entries(t.headers||{}).filter(([d,p])=>d&&p));a["Content-Type"]="application/json";let s;if(Tc(t.url)&&(s=t.url),r&&bc(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 _a=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([ri(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 Hs({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([ri(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 Hs({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 ri(this.browser,e)}async locateElement(e){return await Dv({...e,aiPageFiltering:!!this.options?.aiPageFiltering},this.getControllerFixtures())}async locateElementWithSelector(e,r){return ao({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=dn(),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=J8();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 dn().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 gn&&(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 ao({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=dn(),f=this.logger.child({commandId:a.id}),h=this.shouldUseMemory(),S=EU(e.cache);if((!S||u)&&!_S(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=Z0({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(!Q0(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.72.1"]),mh({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=jS(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.72.1",`missReason:${C instanceof gn?C.cacheMissReason:"unknown"}`]);let _;return S.memory&&zp(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 lU({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 Dv({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 yl&&b.updatedLocatorMemory){let C={id:-1,...c,memory:b.updatedLocatorMemory};mh({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 mh({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&&jS(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 ip(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 J0({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{lk(r,s)}}createCallbacksForBrowser(e){return{createIsolatedFolder:()=>rv(e)}}async traceBrowserInteraction(e,r,n){return dn().startAsyncSpan("BROWSER_INTERACTION",async()=>r(),{name:e,...n})}async resolveCommandTemplateStrings(e,r){return ig({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()?vg({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 vg({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=bI(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(!Tc(r.url)&&!bc(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 Rh(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(!Gi(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:Ja(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 va({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=EU(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:Ja(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 Rh(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(!Gi(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&&!Gi(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 Rh(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 Z8,s=Q8(fetch,a),c;try{c=new URL(r.url).hostname}catch{}let l=await hU({command:r,baseUrl:this.browser.baseUrl,logger:i,fetchImplementation:s});return{data:uu.parse({...l,cookies:bx(a,c)}),succeedImmediately:!1,urlAfterCommand:this.browser.url()}}case"GRAPHQL_REQUEST":return{data:await yU({command:r,baseUrl:this.browser.baseUrl,logger:i}),succeedImmediately:!1,urlAfterCommand:this.browser.url()};case"VISUAL_DIFF":return fU({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 wk({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 va({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=Im.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??kn)*1e3,s=this.generator.getAgentConfig()?.assertion;if(pU(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 vg({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&&Gd(r,l.cache?.memory.traces,i)}}let c=await dU({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 ao({action:async()=>Cg({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 Ra(r.requestMatcher),s=this.browser.registerRequestListener(a);return this.registeredListeners[r.key]=s.then(async c=>await sv(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 Ra(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]=ug(c)},onRequestComplete:(s,c)=>{this.recordedRequests[r.key]?.[s]&&(this.recordedRequests[r.key][s]=ug(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 Ra(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 Ra(r.requestMatcher),async(s,c)=>{let l=await va({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=Kx.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 gg({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 Uv=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(Wd({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 Qr({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<R_;){d?.throwIfAborted();let y=await i.getCacheResult(h);if(y){n.info({cacheResult:vt(y,1e3,!0)},"Got result from module execution cache"),p=Rg(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:${e9()};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 t9(t);else if(e.autoAuth){let S=Im.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 Cg({timeout:kn,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),Uv(t)}}finally{try{f!==void 0&&!m&&p?.status==="SUCCESS"&&await r9({step:e,result:p,browser:s.browser,cacheKeyPrefix:f,logger:n,storage:i})}finally{f!==void 0&&await i.releaseCacheLock(f)}}return p},t9=async t=>{let{currentParentIdChain:e}=t,{step:r,tracer:n}=t.moduleParams,o=Rg(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,no({asyncTasks:t.work.asyncTasks,nestedResults:s,result:o,logger:t.fixtures.logger}),o};function Rg(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 TU({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 va({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 r9({step:t,result:e,browser:r,cacheKeyPrefix:n,logger:o,storage:i}){let a=t.cacheConfig?.cacheExpiryMs;(!a||a===gI)&&(a=t.defaultCacheTtl??SI);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:Wd({json:s,maxJsonStringSize:1e4})},"Setting module cache result"),await i.setCacheResult({result:s,keyPrefix:n,ttlMs:a})}async function Gs(t,e,r){return n9(t,e,r)}async function n9(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=Rg(t,{},"FAILED");return c.message=s,c.startedAt=n,c.finishedAt=i,c}return{...Ah(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 O9}from"lodash-es";import{randomUUID as bU}from"crypto";import{diff as o9}from"deep-object-diff";import{cloneDeep as vU}from"lodash-es";var wg=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?vU(e.command.cache):{},d=o.browser.url(),p=new Date,m,f=bU(),h=bU();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 ${vi(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?vU(e.command.cache):{},b=o9(u,y);b&&Object.keys(b).length>0&&l.info({diffs:Om(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 i9(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,()=>wg({...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 a9(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}=vs(a.steps,e,o);if(s)return i}return-1}async function AU(t){let{currentParentIdChain:e}=t,{step:r}=t.conditionalParams,{logger:n}=t.fixtures,{fromStep:o}=t.inputs,i=new Date,a=Ah(r),s=!!o&&zd(e,o.parentStepIdChain),c=r.elseSteps,l=!0,u=[],d,p=!1;if(s&&o){let g=a9(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 i9(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 no({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 no({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 no({asyncTasks:t.work.asyncTasks,nestedResults:[...u,...f.results],result:S,logger:n}),S}import{randomUUID as CU}from"crypto";var RU=async t=>{let{tracer:e}=t.aiStepParams,{controller:r}=t.fixtures;await r.browser.waitForStability();let n=await r.browser.screenshot({}),o=await s9(t);o.finishedAt=new Date,no({asyncTasks:t.work.asyncTasks,result:o,nestedResults:o.results,logger:t.fixtures.logger});let i=await r.browser.screenshot({}),a=CU();o.beforeSnapshot=a,e.attachBeforeScreenshot({snapshotId:a,screenshot:n});let s=CU();return o.afterSnapshot=s,e.attachAfterScreenshot({snapshotId:s,screenshot:i}),o},s9=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 Hv}from"crypto";var wU=t=>{throw new Error(`Exhaustive check failed for value: ${t}`)};import{streamText as E9}from"ai";var xg=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 g9,stepCountIs as S9}from"ai";import xU from"dedent";var c9=xU`
|
|
4620
4620
|
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.
|
|
4621
4621
|
`,_U=t=>xU`
|
|
4622
4622
|
<background>
|
|
@@ -5198,7 +5198,7 @@ ${o}`}]}async function AF({rootDir:t,cutoffTime:e}){let r=await sZ(t,{withFileTy
|
|
|
5198
5198
|
**Example:** \`--step-type AI_ACTION_DYNAMIC --text "Log in with credentials"\`
|
|
5199
5199
|
`),o.join(`
|
|
5200
5200
|
|
|
5201
|
-
`)}import
|
|
5201
|
+
`)}import hut from"dedent";var UZ=iC(Qv(),1);var xut={CONTAINS:"CONTAINS",EQUALS:"EQUALS",STARTS_WITH:"STARTS_WITH"},_ut={EXISTS:"EXISTS",VISIBLE:"VISIBLE",ENABLED:"ENABLED",EDITABLE:"EDITABLE",FOCUSED:"FOCUSED"};import{Command as ndt,Option as odt}from"@commander-js/extra-typings";var hdt=`Refer to the data returned from the ${gi} tool for the proper step schema.`;import WZ from"path";import VZ from"path";var kg=new Pg;var Ia=class extends _c{constructor(r,n,o){super(r,n);this.client=r;this.orgId=n;this.project=o}project;getApiServerUrl(){return qt()}getAppServerUrl(){return KD()}async fetchTestMetadata(r){let o=(await fe(this.project)).tests[r];if(o)return Xd(o.relativePath,this.project)}async fetchApiTestMetadata(){throw new Error("API tests are not available in the desktop app")}async fetchEnvironment(r,n){return Ps(r,this.project,Ho)}async fetchIconKnowledgeBase(r){try{return await this.client.fetchIconKnowledgeBase(r)}catch(n){return r.error({err:n},"Failed to fetch icon knowledge base"),null}}};var Vs=class{constructor(e){this.apiClient=e}async prepareGoldenScreenshotForComparison(e,r,n){return await new Cc(Re(),this.apiClient,!1).prepareGoldenScreenshotForComparison(e,r,n)}};import{existsSync as FZ,mkdirSync as BZ}from"fs";import{writeFile as Zv}from"fs/promises";import pp from"path";function UF(){try{return pp.join(Re().rootDir,sp)}catch{return pp.resolve(sp)}}function eA(){let t=UF();FZ(t)||BZ(t,{recursive:!0})}function zZ(){return`${Date.now()}`}function tA({entity:t,ext:e}){return pp.join(UF(),`${t}-${zZ()}.${e}`)}function HZ(t){let e=pp.relative(process.cwd(),t);return e.startsWith(".")?e:`./${e}`}function rA({filePath:t,title:e}){return`- [${e}](${HZ(t)})`}async function GZ({browser:t,supportsFileOutput:e,returnSnapshot:r=!0,tokenLimit:n}){let o=t.getActivePage(),i=[];if(r){let s=await t.getBrowserState({skipWait:!1});i.push("- Page Snapshot:","```xml",s.serialize(),"```")}let a=[`- Page URL: ${o.url()}`,`- Page Title: ${await o.title()}`,...i].join(`
|
|
5202
5202
|
`);if(!e&&n!==void 0&&et(a)>n)return me({text:["### Page state",`- Page URL: ${o.url()}`,`- Page Title: ${await o.title()}`,"- Page Snapshot:","<WARNING>","The page state was too long and we had to truncate the page state.","</WARNING>"].join(`
|
|
5203
5203
|
`),section:"Page State"});if(e){eA();let s=tA({entity:"page-state",ext:"txt"});return await Zv(s,a,"utf8"),me({text:rA({filePath:s,title:"Page state"}),section:"Page State"})}return me({text:a,section:"Page State"})}async function Fr({browser:t,supportsFileOutput:e}){let r=await t.screenshot({retries:2}),n=r.toString("base64");if(e){let o=tA({entity:"screenshot",ext:"jpeg"});return eA(),await Zv(o,r),[...Wv({imageDataUri:n,mediaType:"image/jpeg",section:"Screenshot"}),...me({text:rA({filePath:o,title:"Screenshot"}),section:"Screenshot Path"})]}return Wv({imageDataUri:n,mediaType:"image/jpeg",section:"Screenshot"})}async function jZ({project:t,testPath:e,logger:r,envName:n}){let o=await fe(t),i=await Ft(pp.join(t.rootDir,e),r,o);try{let{alwaysSaveCache:s,noCache:c}=Ds(),l=new pt({baseUrl:qt(),apiKey:Cr(),logger:r}),u=await Er(r,l,t),d=xo({logger:r,orgId:Kt(),client:l,gitMetadata:u,regenerateCache:!1,alwaysSaveCache:s,noCache:c,isolateCachesByEnvironment:t.config?.advanced?.isolateCachesByEnvironment,bustOldestCachePercentage:void 0}),{steps:p,beforeSteps:m,afterSteps:f}=await fh({cacheStorage:d,logger:r,schemaVersion:i.schemaVersion,stepLists:{steps:i.steps,beforeSteps:i.beforeSteps,afterSteps:i.afterSteps},testId:i.id,environment:n});i.beforeSteps=m,i.steps=p,i.afterSteps=f}catch(s){r.error({err:s},"Failed to resolve step cache entries for agent test view")}let a=[];return a.push(`Name: ${i.name}`),i.description&&a.push(`Description: ${i.description}`),a.push(""),i.beforeSteps&&i.beforeSteps.length>0&&(a.push(xh(i.beforeSteps,"Setup Steps")),a.push("")),a.push(xh(i.steps,"Main Steps")),i.afterSteps&&i.afterSteps.length>0&&(a.push(""),a.push(xh(i.afterSteps,"Teardown Steps"))),me({text:a.join(`
|
|
5204
5204
|
`),section:"Test Content"})}async function nA({browser:t,tokenLimit:e,returnBrowserState:r=!0,returnScreenshot:n=!0,supportsFileOutput:o}){let[i,a]=await Promise.all([GZ({browser:t,supportsFileOutput:o,returnSnapshot:r,tokenLimit:e}),n===!1?Promise.resolve([]):Fr({browser:t,supportsFileOutput:o})]);return[...i,...a]}async function FF(t){return Pt(await nA(t))}async function Ug({project:t,testPath:e,envName:r,logger:n}){return Pt(await jZ({project:t,testPath:e,envName:r,logger:n}))}async function so({testContext:t,supportsFileOutput:e,limits:r}){let n=r?.tokenLimit,o=r?.perItemLimit??2e4,i=t.toObjectCopy(),a=JSON.stringify(i,null,2);if(e){eA();let p=tA({entity:"environment-variables",ext:"json"});return await Zv(p,a,"utf8"),me({text:rA({filePath:p,title:"Environment variables"}),section:"Environment Variables"})}if(n===void 0)return me({text:a,section:"Environment Variables"});if(et(a)<=n)return me({text:a,section:"Environment Variables"});let c=pF(i,o),l=JSON.stringify(c,null,2);if(et(l)<=n)return me({text:l,section:"Environment Variables"});let d=mF(c,n);return me({text:JSON.stringify(d,null,2),section:"Environment Variables"})}async function BF({testContext:t,limits:e,supportsFileOutput:r}){return Pt(await so({testContext:t,supportsFileOutput:r,limits:e}))}async function oA({logger:t,project:e,entity:r,headfulOverride:n,resolvedTest:o,envName:i,customHeaders:a,devicePixelRatio:s}){let c=Cr(),l=Kt(),u=qt(),d=new pt({apiKey:c,baseUrl:u,logger:t}),p=new Vs(d),m=new Ia(d,l,e),f=new Jo({httpClient:new Tr({baseUrl:u,apiKey:c,logger:t,mode:"interactive"}),fakerSeed:e.config.advanced?.fakerConstantSeed?jl:void 0}),h=o??await Ft(r.fullFilePath,t,await fe(e)),{envName:S,resolvedEnv:g,environmentVariables:E,baseUrl:y}=Jh({test:h,envNameOverride:i,resolveEnv:G=>Ps(G,e,t)}),b={...e.config.browser??{},...g?.browser??{},...h.advanced},C={...e.config.ai??{},...h.advanced??{}},I=await kc({settings:b,customHeaders:a,envVariables:E,envName:S,testName:h.name,baseUrl:y,logger:t,localTools:f,orgId:l}),_=new un(e.config.ai?.agentConfig,{baseUrl:u,apiKey:c,logger:t,mode:"interactive"}),R=new Ta({baseUrl:u,apiKey:c,logger:t,mode:"interactive"},_),M={viewport:h.advanced?.viewport??Ir,locale:h.advanced?.locale??Ki,timezoneId:h.advanced?.timezone??Yi,geolocation:h.advanced?.geolocation??Xi,colorScheme:h.advanced?.colorScheme};s!==void 0&&(M.deviceScaleFactor=s);let P=await io.init({baseUrl:y,userBrowserSettings:I,enricher:R,storage:m,logger:t,contextArgs:M,iconKnowledgeBase:null,callbacks:{},headfulOverride:n});await P.navigate({url:y,initialNavigation:!0});let B=new _a({browser:P,generator:_,logger:t,orgId:l,options:{scratchPadId:void 0,slowMoMs:I.slowMoMs,autoFollowNewTabs:I.autoFollowNewTabs,useMemory:C.useMemory,aiPageFiltering:C.aiPageFiltering??!0},storage:m,localCodeEvalTools:f,visualDiffScreenshotStorage:p}),U=new qr({baseUrl:y,currentUrl:P.url(),variablesFromEnvironment:E,envName:S,testName:h.name});return{controller:B,context:U,baseUrl:y,envName:S,storage:m,codeEvalTools:f,orgId:l}}async function Fg({project:t,logger:e,testPath:r,orgId:n,storage:o,apiKey:i,baseUrl:a,controller:s,testContext:c,supportsFileOutput:l}){let u=await fe(t),d=await Ft(VZ.join(t.rootDir,r),e,u),p={ai:t.config.ai??{},browser:t.config.browser??{}},{baseUrl:m,envName:f,environmentVariables:h,testName:S}=await ni({testId:d.id,orgId:n,logger:e,storage:o,authorization:{type:"API_KEY",apiKey:i,baseUrl:a},settings:p}),{baseUrl:g}=await Uc({controller:s,context:c,baseUrl:m,envName:f,testName:S,environmentVariables:h}),[E,y]=await Promise.all([Fr({browser:s.browser,supportsFileOutput:l}),so({testContext:c,supportsFileOutput:l})]),b=[...me({text:`Session reset to ${g}.`,section:"Result"}),...E,...y];return Pt(b)}var Pa=5,iA=class extends Wm{constructor(){super({sessionTypeLabel:"browser session"})}async kill(e,r){let n;try{e.controller.setClosed()}catch(o){n=o,e.logger.error({err:o,sessionId:e.sessionId,reason:r},"Failed to mark granular session as closed")}try{return await e.controller.browser.cleanup(),n&&e.logger.warn({err:n,sessionId:e.sessionId,reason:r},"Granular session cleaned up despite close failure"),!0}catch(o){return e.logger.error({err:o,sessionId:e.sessionId,reason:r},"Failed to clean up granular session"),!1}}async startSession({logger:e,testId:r,idleTimeoutMs:n,headfulOverride:o,envName:i,projectConfigPath:a,projectNameFilter:s,customHeaders:c,devicePixelRatio:l,skipExitOnError:u}){let d=await Ct({configFilePath:a,nameFilter:s,skipExitOnError:u}),{entity:p,momenticFiles:m}=await ba(d,{id:r},"test"),f=p,h=await Ft(f.fullFilePath,e,m),{controller:S,context:g,baseUrl:E,envName:y,storage:b,codeEvalTools:C,orgId:I}=await oA({logger:e,project:d,entity:f,headfulOverride:o,resolvedTest:h,envName:i,customHeaders:c,devicePixelRatio:l});return{session:this.registerSession({...this.buildManagedSessionState({logger:e,idleTimeoutMs:n}),testId:f.id,relativeTestPath:f.relativePath,testFileAbsolutePath:WZ.join(d.rootDir,f.relativePath),envName:y,controller:S,context:g,storage:b,codeEvalTools:C,orgId:I,tempCaches:{}}),baseUrl:E,envName:y}}},ii=new iA,Ws=(t,e)=>{let r=ii.touchSession(e);if(r)return r;t.addError(JSON.stringify({message:`No active session found for id '${e}'.`,availableSessionIds:ii.listSessionIds()},null,2))};import{streamObject as KZ}from"ai";import Bg from"dedent";import YZ from"path";import{z as Ma}from"zod";import{tool as $Z}from"ai";import{z as qZ}from"zod";var zF=t=>({builder:r=>$Z({description:t.schema.description,inputSchema:qZ.object(t.schema.inputSchema),execute:async n=>{let o=new Fc;r.logger.info({input:n},`Executing tool ${t.schema.name}`);try{await t.handle(r,n,o,void 0)}catch(a){o.addError(Yt(a))}let i=await o.serialize();return i.isError?r.logger.warn({toolName:t.schema.name,input:n,err:i.content.map(a=>"text"in a?a.text:"").join(`
|
|
@@ -5274,10 +5274,10 @@ with this test we are editing:
|
|
|
5274
5274
|
to pick which of these modules are relevant:
|
|
5275
5275
|
|
|
5276
5276
|
`;let h=e7(p);f+=h;let S=KZ({schema:aA,model:m("claude-sonnet-4-5-20250929"),system:ZZ,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=aA.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)}`)}}}),zg=[r7,XZ,JZ];var HF=Zt({schema:{name:gi,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=Dg(),a=["## Project context","",`- **projectRoot**: \`${n}\``,`- **cwd**: \`${o}\``,"","## Step schema","",i].join(`
|
|
5277
|
-
`);r.addPartFromText(a)}});import{z as Hg}from"zod";var GF=Zt({schema:{name:MI,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:Hg.string().describe("The session id to query."),returnBrowserState:Hg.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:Hg.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=Ws(r,e.sessionId);if(!n)return;n.controller.setOpen();let o=await nA({browser:n.controller.browser,supportsFileOutput:t.supportsFileOutput,returnBrowserState:e.returnBrowserState,returnScreenshot:e.returnScreenshot});r.addContentParts(o)}}),jF=Zt({schema:{name:OI,description:"Get the current environment variables for a session.",inputSchema:{sessionId:Hg.string()}},handle:async(t,e,r)=>{let n=Ws(r,e.sessionId);if(!n)return;let o=await so({testContext:n.context,supportsFileOutput:t.supportsFileOutput});r.addContentParts(o)}});import{z as Bc}from"zod";var VF=Zt({schema:{name:II,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:Bc.string().describe("The test id to target when starting a session."),envName:Bc.string().optional().describe("Optional environment override (matches CLI --env behavior). Defaults to the test's default env when omitted."),projectConfigPath:Bc.string().optional().describe("Optional path to a momentic.config.yaml file (matches CLI --config)."),projectNameFilter:Bc.string().optional().describe("Optional project name filter for workspace configs (matches CLI --filter)."),headfulBrowser:Bc.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 ii.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))}}}),WF=Zt({schema:{name:PI,description:"Kill a granular browser session by sessionId. Returns available session ids if the target is missing.",inputSchema:{sessionId:Bc.string().describe("The session id to terminate.")}},handle:async(t,e,r)=>{try{if(!await ii.killSession(e.sessionId,"explicit kill")){r.addError(JSON.stringify({message:`No active session found for id '${e.sessionId}'.`,availableSessionIds:ii.listSessionIds()},null,2));return}r.addPartFromText(JSON.stringify({sessionId:e.sessionId,killed:!0},null,2))}catch(n){r.addError(String(n))}}});import{z as lo}from"zod";import $F from"path";import{v4 as n7}from"uuid";async function mp({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:n7(),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=$F.join(t.rootDir,...e.pathSegments||[]),s=await BN({test:i,name:e.name,folder:a});return{...i,relativeFilePath:$F.relative(t.rootDir,s)}}import{randomUUID as i7}from"crypto";import{cloneDeep as a7}from"lodash-es";import{randomUUID as o7}from"crypto";var zc=async({step:t,controller:e,executionOptions:r,storage:n,codeEvalTools:o,logger:i,socket:a,testContext:s,orgId:c})=>{let{results:l}=await sA({steps:[t],controller:e,executionOptions:r,storage:n,codeEvalTools:o,logger:i,socket:a,testContext:s,orgId:c});return l[0]},sA=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 Ul},m=n??(l?new Li({orgId:d,parentStep:null,parentTracer:null,socket:l}):new ud);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:o7(),steps:t,testMetadata:null,orgSettings:{},fromStep:e,toStep:r},callbacks:{test:{},step:{}},work:f});return i?o.withExecutionOptions(i,h):h()};async function Gg({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 Ng(t,{project:e,logger:r,tempCaches:u});switch(d.type){case"PRESET_ACTION":return s7({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 l7({step:d,logger:r,storage:n,controller:o,codeEvalTools:i,socket:a,orgId:s,testContext:c,supportsFileOutput:l});case"RESOLVED_MODULE":return c7({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}),so({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 s7({step:t,logger:e,storage:r,controller:n,codeEvalTools:o,socket:i,orgId:a,testContext:s,supportsFileOutput:c,tempCaches:l}){let u=await zc({step:t,logger:e,storage:r,controller:n,executionOptions:{skipAISmartWaiting:!0},codeEvalTools:o,socket:i,orgId:a,testContext:s}),d=[];u?u.status==="SUCCESS"?(u7({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}),so({testContext:s,supportsFileOutput:c})]);return d.push(...p,...m),d}async function l7({step:t,logger:e,storage:r,controller:n,codeEvalTools:o,socket:i,orgId:a,testContext:s,supportsFileOutput:c}){let l=await zc({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}),so({testContext:s,supportsFileOutput:c})]);return u.push(...d,...p),u}async function c7({step:t,logger:e,storage:r,controller:n,codeEvalTools:o,socket:i,orgId:a,testContext:s,supportsFileOutput:c}){let l=await zc({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}),so({testContext:s,supportsFileOutput:c})]);return u.push(...d,...p),u}function u7({logger:t,tempCaches:e,command:r,parts:n}){if(e&&ji(r)&&r.cache)try{let o=i7();e[o]=po.parse(a7({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 v7}from"lodash-es";import aB from"path";var SA=Symbol.for("immer-nothing"),fp=Symbol.for("immer-draftable"),wn=Symbol.for("immer-state");function Br(t,...e){throw new Error(`[Immer] minified error nr: ${t}. Full error at: https://bit.ly/3cXEKWf`)}var qs=Object.getPrototypeOf;function Ks(t){return!!t&&!!t[wn]}function Oa(t){return t?JF(t)||Array.isArray(t)||!!t[fp]||!!t.constructor?.[fp]||Ep(t)||Tp(t):!1}var d7=Object.prototype.constructor.toString();function JF(t){if(!t||typeof t!="object")return!1;let e=qs(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)===d7}function hp(t,e){Ys(t)===0?Reflect.ownKeys(t).forEach(r=>{e(r,t[r],t)}):t.forEach((r,n)=>e(n,r,t))}function Ys(t){let e=t[wn];return e?e.type_:Array.isArray(t)?1:Ep(t)?2:Tp(t)?3:0}function gp(t,e){return Ys(t)===2?t.has(e):Object.prototype.hasOwnProperty.call(t,e)}function lA(t,e){return Ys(t)===2?t.get(e):t[e]}function QF(t,e,r){let n=Ys(t);n===2?t.set(e,r):n===3?t.add(r):t[e]=r}function p7(t,e){return t===e?t!==0||1/t===1/e:t!==t&&e!==e}function Ep(t){return t instanceof Map}function Tp(t){return t instanceof Set}function $s(t){return t.copy_||t.base_}function dA(t,e){if(Ep(t))return new Map(t);if(Tp(t))return new Set(t);if(Array.isArray(t))return Array.prototype.slice.call(t);let r=JF(t);if(e===!0||e==="class_only"&&!r){let n=Object.getOwnPropertyDescriptors(t);delete n[wn];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(qs(t),n)}else{let n=qs(t);if(n!==null&&r)return{...t};let o=Object.create(n);return Object.assign(o,t)}}function yA(t,e=!1){return Wg(t)||Ks(t)||!Oa(t)||(Ys(t)>1&&(t.set=t.add=t.clear=t.delete=m7),Object.freeze(t),e&&Object.entries(t).forEach(([r,n])=>yA(n,!0))),t}function m7(){Br(2)}function Wg(t){return Object.isFrozen(t)}var pA={};function Xs(t){let e=pA[t];return e||Br(0,t),e}function f7(t,e){pA[t]||(pA[t]=e)}var Sp;function ZF(){return Sp}function h7(t,e){return{drafts_:[],parent_:t,immer_:e,canAutoFreeze_:!0,unfinalizedDrafts_:0}}function qF(t,e){e&&(Xs("Patches"),t.patches_=[],t.inversePatches_=[],t.patchListener_=e)}function mA(t){fA(t),t.drafts_.forEach(g7),t.drafts_=null}function fA(t){t===Sp&&(Sp=t.parent_)}function KF(t){return Sp=h7(Sp,t)}function g7(t){let e=t[wn];e.type_===0||e.type_===1?e.revoke_():e.revoked_=!0}function YF(t,e){e.unfinalizedDrafts_=e.drafts_.length;let r=e.drafts_[0];return t!==void 0&&t!==r?(r[wn].modified_&&(mA(e),Br(4)),Oa(t)&&(t=jg(e,t),e.parent_||Vg(e,t)),e.patches_&&Xs("Patches").generateReplacementPatches_(r[wn].base_,t,e.patches_,e.inversePatches_)):t=jg(e,r,[]),mA(e),e.patches_&&e.patchListener_(e.patches_,e.inversePatches_),t!==SA?t:void 0}function jg(t,e,r){if(Wg(e))return e;let n=e[wn];if(!n)return hp(e,(o,i)=>XF(t,n,e,o,i,r)),e;if(n.scope_!==t)return e;if(!n.modified_)return Vg(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),hp(i,(s,c)=>XF(t,n,o,s,c,r,a)),Vg(t,o,!1),r&&t.patches_&&Xs("Patches").generatePatches_(n,r,t.patches_,t.inversePatches_)}return n.copy_}function XF(t,e,r,n,o,i,a){if(Ks(o)){let s=i&&e&&e.type_!==3&&!gp(e.assigned_,n)?i.concat(n):void 0,c=jg(t,o,s);if(QF(r,n,c),Ks(c))t.canAutoFreeze_=!1;else return}else a&&r.add(o);if(Oa(o)&&!Wg(o)){if(!t.immer_.autoFreeze_&&t.unfinalizedDrafts_<1)return;jg(t,o),(!e||!e.scope_.parent_)&&typeof n!="symbol"&&Object.prototype.propertyIsEnumerable.call(r,n)&&Vg(t,o)}}function Vg(t,e,r=!1){!t.parent_&&t.immer_.autoFreeze_&&t.canAutoFreeze_&&yA(e,r)}function S7(t,e){let r=Array.isArray(t),n={type_:r?1:0,scope_:e?e.scope_:ZF(),modified_:!1,finalized_:!1,assigned_:{},parent_:e,base_:t,draft_:null,copy_:null,revoke_:null,isManual_:!1},o=n,i=EA;r&&(o=[n],i=yp);let{revoke:a,proxy:s}=Proxy.revocable(o,i);return n.draft_=s,n.revoke_=a,s}var EA={get(t,e){if(e===wn)return t;let r=$s(t);if(!gp(r,e))return y7(t,r,e);let n=r[e];return t.finalized_||!Oa(n)?n:n===cA(t.base_,e)?(uA(t),t.copy_[e]=gA(n,t)):n},has(t,e){return e in $s(t)},ownKeys(t){return Reflect.ownKeys($s(t))},set(t,e,r){let n=eB($s(t),e);if(n?.set)return n.set.call(t.draft_,r),!0;if(!t.modified_){let o=cA($s(t),e),i=o?.[wn];if(i&&i.base_===r)return t.copy_[e]=r,t.assigned_[e]=!1,!0;if(p7(r,o)&&(r!==void 0||gp(t.base_,e)))return!0;uA(t),hA(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 cA(t.base_,e)!==void 0||e in t.base_?(t.assigned_[e]=!1,uA(t),hA(t)):delete t.assigned_[e],t.copy_&&delete t.copy_[e],!0},getOwnPropertyDescriptor(t,e){let r=$s(t),n=Reflect.getOwnPropertyDescriptor(r,e);return n&&{writable:!0,configurable:t.type_!==1||e!=="length",enumerable:n.enumerable,value:r[e]}},defineProperty(){Br(11)},getPrototypeOf(t){return qs(t.base_)},setPrototypeOf(){Br(12)}},yp={};hp(EA,(t,e)=>{yp[t]=function(){return arguments[0]=arguments[0][0],e.apply(this,arguments)}});yp.deleteProperty=function(t,e){return yp.set.call(this,t,e,void 0)};yp.set=function(t,e,r){return EA.set.call(this,t[0],e,r,t[0])};function cA(t,e){let r=t[wn];return(r?$s(r):t)[e]}function y7(t,e,r){let n=eB(e,r);return n?"value"in n?n.value:n.get?.call(t.draft_):void 0}function eB(t,e){if(!(e in t))return;let r=qs(t);for(;r;){let n=Object.getOwnPropertyDescriptor(r,e);if(n)return n;r=qs(r)}}function hA(t){t.modified_||(t.modified_=!0,t.parent_&&hA(t.parent_))}function uA(t){t.copy_||(t.copy_=dA(t.base_,t.scope_.immer_.useStrictShallowCopy_))}var E7=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"&&Br(6),n!==void 0&&typeof n!="function"&&Br(7);let o;if(Oa(e)){let i=KF(this),a=gA(e,void 0),s=!0;try{o=r(a),s=!1}finally{s?mA(i):fA(i)}return qF(i,n),YF(o,i)}else if(!e||typeof e!="object"){if(o=r(e),o===void 0&&(o=e),o===SA&&(o=void 0),this.autoFreeze_&&yA(o,!0),n){let i=[],a=[];Xs("Patches").generateReplacementPatches_(e,o,i,a),n(i,a)}return o}else Br(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){Oa(t)||Br(8),Ks(t)&&(t=T7(t));let e=KF(this),r=gA(t,void 0);return r[wn].isManual_=!0,fA(e),r}finishDraft(t,e){let r=t&&t[wn];(!r||!r.isManual_)&&Br(9);let{scope_:n}=r;return qF(n,e),YF(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=Xs("Patches").applyPatches_;return Ks(t)?n(t,e):this.produce(t,o=>n(o,e))}};function gA(t,e){let r=Ep(t)?Xs("MapSet").proxyMap_(t,e):Tp(t)?Xs("MapSet").proxySet_(t,e):S7(t,e);return(e?e.scope_:ZF()).drafts_.push(r),r}function T7(t){return Ks(t)||Br(10,t),tB(t)}function tB(t){if(!Oa(t)||Wg(t))return t;let e=t[wn],r;if(e){if(!e.modified_)return e.base_;e.finalized_=!0,r=dA(t,e.scope_.immer_.useStrictShallowCopy_)}else r=dA(t,!0);return hp(r,(n,o)=>{QF(r,n,tB(o))}),e&&(e.finalized_=!1),r}function rB(){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;hp(p.assigned_,(E,y)=>{let b=lA(S,E),C=lA(g,E),I=y?gp(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===SA?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=Ys(g),_=h[C];typeof _!="string"&&typeof _!="number"&&(_=""+_),(I===0||I===1)&&(_==="__proto__"||_==="constructor")&&Br(19),typeof g=="function"&&_==="prototype"&&Br(19),g=lA(g,_),typeof g!="object"&&Br(18,h.join("/"))}let E=Ys(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:Br(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:Br(17,S)}}),p}function u(p){if(!Oa(p))return p;if(Array.isArray(p))return p.map(u);if(Ep(p))return new Map(Array.from(p.entries()).map(([f,h])=>[f,u(h)]));if(Tp(p))return new Set(Array.from(p).map(u));let m=Object.create(qs(p));for(let f in p)m[f]=u(p[f]);return gp(p,fp)&&(m[fp]=p[fp]),m}function d(p){return Ks(p)?u(p):p}f7("Patches",{applyPatches_:l,generatePatches_:o,generateReplacementPatches_:c})}var xn=new E7,Sft=xn.produce,nB=xn.produceWithPatches.bind(xn),yft=xn.setAutoFreeze.bind(xn),Eft=xn.setUseStrictShallowCopy.bind(xn),Tft=xn.applyPatches.bind(xn),bft=xn.createDraft.bind(xn),vft=xn.finishDraft.bind(xn);import{v4 as b7}from"uuid";rB();function $g({logger:t,socket:e,baseState:r,recipe:n,description:o}){let[i,a,s]=nB(r,n),c={id:b7(),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 oB=({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=lp(i.id,s,e.fromStepId,e.parentStepIdChain);if(n.fastForwardingToStep){if(!c)return!1;n.fastForwardingToStep=!1}return n.total+=1,!!(r&&lp(i.id,s,r.toStepId,r.parentStepIdChain))};return cn({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=lp(i.id,s,e.fromStepId,e.parentStepIdChain);if(n.fastForwardingToStep){if(!c)return!1;n.fastForwardingToStep=!1}return!!(r&&lp(i.id,s,r.toStepId,r.parentStepIdChain))},onSimpleStepContainer:(i,a)=>o(i,a.parentChain)}),n.total};var A7=t=>{throw new Error(`Unknown test section: ${t}`)};function bA(t,e){switch(e){case"setup":return t.beforeSteps??[];case"teardown":return t.afterSteps??[];case"main":return t.steps;default:return A7(e)}}function TA(t,e,r){let n=bA(t,e);if(!r?.length)return n;let o=CL(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 C7({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 R7({steps:t,sectionLabel:e,startIndexOffset:r}){if(t.length===0)return`${e}: (no steps)`;let n=ib(t,{includeCache:!1});n.forEach((i,a)=>{i.index=r+a});let o=["```json",JSON.stringify(n,null,2),"```"].join(`
|
|
5277
|
+
`);r.addPartFromText(a)}});import{z as Hg}from"zod";var GF=Zt({schema:{name:MI,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:Hg.string().describe("The session id to query."),returnBrowserState:Hg.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:Hg.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=Ws(r,e.sessionId);if(!n)return;n.controller.setOpen();let o=await nA({browser:n.controller.browser,supportsFileOutput:t.supportsFileOutput,returnBrowserState:e.returnBrowserState,returnScreenshot:e.returnScreenshot});r.addContentParts(o)}}),jF=Zt({schema:{name:OI,description:"Get the current environment variables for a session.",inputSchema:{sessionId:Hg.string()}},handle:async(t,e,r)=>{let n=Ws(r,e.sessionId);if(!n)return;let o=await so({testContext:n.context,supportsFileOutput:t.supportsFileOutput});r.addContentParts(o)}});import{z as Bc}from"zod";var VF=Zt({schema:{name:II,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:Bc.string().describe("The test id to target when starting a session."),envName:Bc.string().optional().describe("Optional environment override (matches CLI --env behavior). Defaults to the test's default env when omitted."),projectConfigPath:Bc.string().optional().describe("Optional path to a momentic.config.yaml file (matches CLI --config)."),projectNameFilter:Bc.string().optional().describe("Optional project name filter for workspace configs (matches CLI --filter)."),headfulBrowser:Bc.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 ii.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))}}}),WF=Zt({schema:{name:PI,description:"Kill a granular browser session by sessionId. Returns available session ids if the target is missing.",inputSchema:{sessionId:Bc.string().describe("The session id to terminate.")}},handle:async(t,e,r)=>{try{if(!await ii.killSession(e.sessionId,"explicit kill")){r.addError(JSON.stringify({message:`No active session found for id '${e.sessionId}'.`,availableSessionIds:ii.listSessionIds()},null,2));return}r.addPartFromText(JSON.stringify({sessionId:e.sessionId,killed:!0},null,2))}catch(n){r.addError(String(n))}}});import{z as lo}from"zod";import $F from"path";import{v4 as n7}from"uuid";async function mp({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:n7(),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=$F.join(t.rootDir,...e.pathSegments||[]),s=await BN({test:i,name:e.name,folder:a});return{...i,relativeFilePath:$F.relative(t.rootDir,s)}}import{randomUUID as i7}from"crypto";import{cloneDeep as a7}from"lodash-es";import{randomUUID as o7}from"crypto";var zc=async({step:t,controller:e,executionOptions:r,storage:n,codeEvalTools:o,logger:i,socket:a,testContext:s,orgId:c})=>{let{results:l}=await sA({steps:[t],controller:e,executionOptions:r,storage:n,codeEvalTools:o,logger:i,socket:a,testContext:s,orgId:c});return l[0]},sA=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 Ul},m=n??(l?new Li({orgId:d,parentStep:null,parentTracer:null,socket:l}):new ud);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:o7(),steps:t,testMetadata:null,orgSettings:{},fromStep:e,toStep:r},callbacks:{test:{},step:{}},work:f});return i?o.withExecutionOptions(i,h):h()};async function Gg({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 Ng(t,{project:e,logger:r,tempCaches:u});switch(d.type){case"PRESET_ACTION":return s7({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 l7({step:d,logger:r,storage:n,controller:o,codeEvalTools:i,socket:a,orgId:s,testContext:c,supportsFileOutput:l});case"RESOLVED_MODULE":return c7({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}),so({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 s7({step:t,logger:e,storage:r,controller:n,codeEvalTools:o,socket:i,orgId:a,testContext:s,supportsFileOutput:c,tempCaches:l}){let u=await zc({step:t,logger:e,storage:r,controller:n,executionOptions:{skipAISmartWaiting:!0},codeEvalTools:o,socket:i,orgId:a,testContext:s}),d=[];u?u.status==="SUCCESS"?(u7({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}),so({testContext:s,supportsFileOutput:c})]);return d.push(...p,...m),d}async function l7({step:t,logger:e,storage:r,controller:n,codeEvalTools:o,socket:i,orgId:a,testContext:s,supportsFileOutput:c}){let l=await zc({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}),so({testContext:s,supportsFileOutput:c})]);return u.push(...d,...p),u}async function c7({step:t,logger:e,storage:r,controller:n,codeEvalTools:o,socket:i,orgId:a,testContext:s,supportsFileOutput:c}){let l=await zc({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}),so({testContext:s,supportsFileOutput:c})]);return u.push(...d,...p),u}function u7({logger:t,tempCaches:e,command:r,parts:n}){if(e&&ji(r)&&r.cache)try{let o=i7();e[o]=po.parse(a7({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 v7}from"lodash-es";import aB from"path";var SA=Symbol.for("immer-nothing"),fp=Symbol.for("immer-draftable"),wn=Symbol.for("immer-state");function Br(t,...e){throw new Error(`[Immer] minified error nr: ${t}. Full error at: https://bit.ly/3cXEKWf`)}var qs=Object.getPrototypeOf;function Ks(t){return!!t&&!!t[wn]}function Oa(t){return t?JF(t)||Array.isArray(t)||!!t[fp]||!!t.constructor?.[fp]||Ep(t)||Tp(t):!1}var d7=Object.prototype.constructor.toString();function JF(t){if(!t||typeof t!="object")return!1;let e=qs(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)===d7}function hp(t,e){Ys(t)===0?Reflect.ownKeys(t).forEach(r=>{e(r,t[r],t)}):t.forEach((r,n)=>e(n,r,t))}function Ys(t){let e=t[wn];return e?e.type_:Array.isArray(t)?1:Ep(t)?2:Tp(t)?3:0}function gp(t,e){return Ys(t)===2?t.has(e):Object.prototype.hasOwnProperty.call(t,e)}function lA(t,e){return Ys(t)===2?t.get(e):t[e]}function QF(t,e,r){let n=Ys(t);n===2?t.set(e,r):n===3?t.add(r):t[e]=r}function p7(t,e){return t===e?t!==0||1/t===1/e:t!==t&&e!==e}function Ep(t){return t instanceof Map}function Tp(t){return t instanceof Set}function $s(t){return t.copy_||t.base_}function dA(t,e){if(Ep(t))return new Map(t);if(Tp(t))return new Set(t);if(Array.isArray(t))return Array.prototype.slice.call(t);let r=JF(t);if(e===!0||e==="class_only"&&!r){let n=Object.getOwnPropertyDescriptors(t);delete n[wn];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(qs(t),n)}else{let n=qs(t);if(n!==null&&r)return{...t};let o=Object.create(n);return Object.assign(o,t)}}function yA(t,e=!1){return Wg(t)||Ks(t)||!Oa(t)||(Ys(t)>1&&(t.set=t.add=t.clear=t.delete=m7),Object.freeze(t),e&&Object.entries(t).forEach(([r,n])=>yA(n,!0))),t}function m7(){Br(2)}function Wg(t){return Object.isFrozen(t)}var pA={};function Xs(t){let e=pA[t];return e||Br(0,t),e}function f7(t,e){pA[t]||(pA[t]=e)}var Sp;function ZF(){return Sp}function h7(t,e){return{drafts_:[],parent_:t,immer_:e,canAutoFreeze_:!0,unfinalizedDrafts_:0}}function qF(t,e){e&&(Xs("Patches"),t.patches_=[],t.inversePatches_=[],t.patchListener_=e)}function mA(t){fA(t),t.drafts_.forEach(g7),t.drafts_=null}function fA(t){t===Sp&&(Sp=t.parent_)}function KF(t){return Sp=h7(Sp,t)}function g7(t){let e=t[wn];e.type_===0||e.type_===1?e.revoke_():e.revoked_=!0}function YF(t,e){e.unfinalizedDrafts_=e.drafts_.length;let r=e.drafts_[0];return t!==void 0&&t!==r?(r[wn].modified_&&(mA(e),Br(4)),Oa(t)&&(t=jg(e,t),e.parent_||Vg(e,t)),e.patches_&&Xs("Patches").generateReplacementPatches_(r[wn].base_,t,e.patches_,e.inversePatches_)):t=jg(e,r,[]),mA(e),e.patches_&&e.patchListener_(e.patches_,e.inversePatches_),t!==SA?t:void 0}function jg(t,e,r){if(Wg(e))return e;let n=e[wn];if(!n)return hp(e,(o,i)=>XF(t,n,e,o,i,r)),e;if(n.scope_!==t)return e;if(!n.modified_)return Vg(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),hp(i,(s,c)=>XF(t,n,o,s,c,r,a)),Vg(t,o,!1),r&&t.patches_&&Xs("Patches").generatePatches_(n,r,t.patches_,t.inversePatches_)}return n.copy_}function XF(t,e,r,n,o,i,a){if(Ks(o)){let s=i&&e&&e.type_!==3&&!gp(e.assigned_,n)?i.concat(n):void 0,c=jg(t,o,s);if(QF(r,n,c),Ks(c))t.canAutoFreeze_=!1;else return}else a&&r.add(o);if(Oa(o)&&!Wg(o)){if(!t.immer_.autoFreeze_&&t.unfinalizedDrafts_<1)return;jg(t,o),(!e||!e.scope_.parent_)&&typeof n!="symbol"&&Object.prototype.propertyIsEnumerable.call(r,n)&&Vg(t,o)}}function Vg(t,e,r=!1){!t.parent_&&t.immer_.autoFreeze_&&t.canAutoFreeze_&&yA(e,r)}function S7(t,e){let r=Array.isArray(t),n={type_:r?1:0,scope_:e?e.scope_:ZF(),modified_:!1,finalized_:!1,assigned_:{},parent_:e,base_:t,draft_:null,copy_:null,revoke_:null,isManual_:!1},o=n,i=EA;r&&(o=[n],i=yp);let{revoke:a,proxy:s}=Proxy.revocable(o,i);return n.draft_=s,n.revoke_=a,s}var EA={get(t,e){if(e===wn)return t;let r=$s(t);if(!gp(r,e))return y7(t,r,e);let n=r[e];return t.finalized_||!Oa(n)?n:n===cA(t.base_,e)?(uA(t),t.copy_[e]=gA(n,t)):n},has(t,e){return e in $s(t)},ownKeys(t){return Reflect.ownKeys($s(t))},set(t,e,r){let n=eB($s(t),e);if(n?.set)return n.set.call(t.draft_,r),!0;if(!t.modified_){let o=cA($s(t),e),i=o?.[wn];if(i&&i.base_===r)return t.copy_[e]=r,t.assigned_[e]=!1,!0;if(p7(r,o)&&(r!==void 0||gp(t.base_,e)))return!0;uA(t),hA(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 cA(t.base_,e)!==void 0||e in t.base_?(t.assigned_[e]=!1,uA(t),hA(t)):delete t.assigned_[e],t.copy_&&delete t.copy_[e],!0},getOwnPropertyDescriptor(t,e){let r=$s(t),n=Reflect.getOwnPropertyDescriptor(r,e);return n&&{writable:!0,configurable:t.type_!==1||e!=="length",enumerable:n.enumerable,value:r[e]}},defineProperty(){Br(11)},getPrototypeOf(t){return qs(t.base_)},setPrototypeOf(){Br(12)}},yp={};hp(EA,(t,e)=>{yp[t]=function(){return arguments[0]=arguments[0][0],e.apply(this,arguments)}});yp.deleteProperty=function(t,e){return yp.set.call(this,t,e,void 0)};yp.set=function(t,e,r){return EA.set.call(this,t[0],e,r,t[0])};function cA(t,e){let r=t[wn];return(r?$s(r):t)[e]}function y7(t,e,r){let n=eB(e,r);return n?"value"in n?n.value:n.get?.call(t.draft_):void 0}function eB(t,e){if(!(e in t))return;let r=qs(t);for(;r;){let n=Object.getOwnPropertyDescriptor(r,e);if(n)return n;r=qs(r)}}function hA(t){t.modified_||(t.modified_=!0,t.parent_&&hA(t.parent_))}function uA(t){t.copy_||(t.copy_=dA(t.base_,t.scope_.immer_.useStrictShallowCopy_))}var E7=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"&&Br(6),n!==void 0&&typeof n!="function"&&Br(7);let o;if(Oa(e)){let i=KF(this),a=gA(e,void 0),s=!0;try{o=r(a),s=!1}finally{s?mA(i):fA(i)}return qF(i,n),YF(o,i)}else if(!e||typeof e!="object"){if(o=r(e),o===void 0&&(o=e),o===SA&&(o=void 0),this.autoFreeze_&&yA(o,!0),n){let i=[],a=[];Xs("Patches").generateReplacementPatches_(e,o,i,a),n(i,a)}return o}else Br(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){Oa(t)||Br(8),Ks(t)&&(t=T7(t));let e=KF(this),r=gA(t,void 0);return r[wn].isManual_=!0,fA(e),r}finishDraft(t,e){let r=t&&t[wn];(!r||!r.isManual_)&&Br(9);let{scope_:n}=r;return qF(n,e),YF(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=Xs("Patches").applyPatches_;return Ks(t)?n(t,e):this.produce(t,o=>n(o,e))}};function gA(t,e){let r=Ep(t)?Xs("MapSet").proxyMap_(t,e):Tp(t)?Xs("MapSet").proxySet_(t,e):S7(t,e);return(e?e.scope_:ZF()).drafts_.push(r),r}function T7(t){return Ks(t)||Br(10,t),tB(t)}function tB(t){if(!Oa(t)||Wg(t))return t;let e=t[wn],r;if(e){if(!e.modified_)return e.base_;e.finalized_=!0,r=dA(t,e.scope_.immer_.useStrictShallowCopy_)}else r=dA(t,!0);return hp(r,(n,o)=>{QF(r,n,tB(o))}),e&&(e.finalized_=!1),r}function rB(){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;hp(p.assigned_,(E,y)=>{let b=lA(S,E),C=lA(g,E),I=y?gp(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===SA?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=Ys(g),_=h[C];typeof _!="string"&&typeof _!="number"&&(_=""+_),(I===0||I===1)&&(_==="__proto__"||_==="constructor")&&Br(19),typeof g=="function"&&_==="prototype"&&Br(19),g=lA(g,_),typeof g!="object"&&Br(18,h.join("/"))}let E=Ys(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:Br(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:Br(17,S)}}),p}function u(p){if(!Oa(p))return p;if(Array.isArray(p))return p.map(u);if(Ep(p))return new Map(Array.from(p.entries()).map(([f,h])=>[f,u(h)]));if(Tp(p))return new Set(Array.from(p).map(u));let m=Object.create(qs(p));for(let f in p)m[f]=u(p[f]);return gp(p,fp)&&(m[fp]=p[fp]),m}function d(p){return Ks(p)?u(p):p}f7("Patches",{applyPatches_:l,generatePatches_:o,generateReplacementPatches_:c})}var xn=new E7,yft=xn.produce,nB=xn.produceWithPatches.bind(xn),Eft=xn.setAutoFreeze.bind(xn),Tft=xn.setUseStrictShallowCopy.bind(xn),bft=xn.applyPatches.bind(xn),vft=xn.createDraft.bind(xn),Aft=xn.finishDraft.bind(xn);import{v4 as b7}from"uuid";rB();function $g({logger:t,socket:e,baseState:r,recipe:n,description:o}){let[i,a,s]=nB(r,n),c={id:b7(),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 oB=({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=lp(i.id,s,e.fromStepId,e.parentStepIdChain);if(n.fastForwardingToStep){if(!c)return!1;n.fastForwardingToStep=!1}return n.total+=1,!!(r&&lp(i.id,s,r.toStepId,r.parentStepIdChain))};return cn({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=lp(i.id,s,e.fromStepId,e.parentStepIdChain);if(n.fastForwardingToStep){if(!c)return!1;n.fastForwardingToStep=!1}return!!(r&&lp(i.id,s,r.toStepId,r.parentStepIdChain))},onSimpleStepContainer:(i,a)=>o(i,a.parentChain)}),n.total};var A7=t=>{throw new Error(`Unknown test section: ${t}`)};function bA(t,e){switch(e){case"setup":return t.beforeSteps??[];case"teardown":return t.afterSteps??[];case"main":return t.steps;default:return A7(e)}}function TA(t,e,r){let n=bA(t,e);if(!r?.length)return n;let o=CL(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 C7({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 R7({steps:t,sectionLabel:e,startIndexOffset:r}){if(t.length===0)return`${e}: (no steps)`;let n=ib(t,{includeCache:!1});n.forEach((i,a)=>{i.index=r+a});let o=["```json",JSON.stringify(n,null,2),"```"].join(`
|
|
5278
5278
|
`);return`${e}:
|
|
5279
5279
|
${o}`}function iB(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??[]])cn({steps:o,onPresetAction:n,onConditional:n,onSimpleStepContainer:n})}async function qg({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 Ft(aB.join(t.rootDir,n),r,l),d={steps:u.steps??[],beforeSteps:u.beforeSteps??[],afterSteps:u.afterSteps??[]},p=await Promise.all(s.steps.map(b=>Ng(b,{project:t,logger:r,tempCaches:a}))),m=s.parentStepIdChain,f;try{f=TA(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=$g({logger:r,socket:o,baseState:d,recipe:I=>{let _;if(m?.length&&(_=RL(bA(I,s.targetSection),m,s.targetSection),_.some(P=>P.type==="RESOLVED_MODULE")&&p.some(P=>P.type==="RESOLVED_MODULE")))throw new Error(g);TA(I,s.targetSection,m).splice(s.startIndex,s.deleteCount,...p);for(let M of p)M.type==="RESOLVED_MODULE"&&iB(I,M);if(_)for(let M of _)M.type==="RESOLVED_MODULE"&&iB(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 Ut({stepLists:E});C.forEach(I=>{Jn({content:I,schemaVersion:De,momenticFiles:l,project:t})}),bn({relativeTestPath:n,steps:b,schemaVersion:De,project:t})}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(y.push(...await w7({logger:r,project:t,orgId:e,testId:u.id,environment:c,originalSteps:d,updatedSteps:E})),s.returnTest)y.push(...me({text:JSON.stringify(await Ug({project:t,testPath:n,envName:c,logger:r}),null,2),section:"Test Content"}));else{let b=TA(E,s.targetSection,m),{windowStart:C,windowEndExclusive:I}=C7({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}`,"",R7({steps:_,sectionLabel:"Changed Step Window",startIndexOffset:C})].join(`
|
|
5280
|
-
`),section:"Changed Steps"}))}return Pt(y)}async function Kg({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 Ft(aB.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}=Ds(),_=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=bA(E,S),M=v7({steps:E.steps,beforeSteps:E.beforeSteps,afterSteps:E.afterSteps}),{result:P}=vs(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}=vs(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=oB({steps:R,fromStep:f,toStep:h});u.setProgressTotal(te)}o.setOpen();let{results:B}=await sA({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 U=B.at(-1);if(!U)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=U.status!=="SUCCESS";if(z)U.status==="FAILED"&&await Ec(G);else try{await Cs(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 ${U.id} failed: ${U.message}`,section:"Error"}));else{o.setOpen();let te=`${X} executed successfully.`;ne.push(...me({text:te,section:"Result"})),U.data&&ne.push(...me({text:`Data: ${JSON.stringify(U.data,null,2)}`,section:"Result Data"}))}let[de,Te]=await Promise.all([Fr({browser:o.browser,supportsFileOutput:m}),so({testContext:l,supportsFileOutput:m,limits:{tokenLimit:p}})]);return Pt([...ne,...de,...Te])}async function w7({logger:t,project:e,orgId:r,testId:n,environment:o,originalSteps:i,updatedSteps:a}){let s=[];try{let c=new pt({baseUrl:qt(),apiKey:Cr(),logger:t}),l=await Er(t,c,e),{alwaysSaveCache:u,noCache:d}=Ds(),p=xo({logger:t,orgId:r,client:c,gitMetadata:l,regenerateCache:!1,alwaysSaveCache:u,noCache:d,isolateCachesByEnvironment:e.config?.advanced?.isolateCachesByEnvironment,bustOldestCachePercentage:void 0});await Cs({logger:t,cacheStorage:p,orgId:r,testId:n,environment:o,originalStepsWithCaches:i,updatedStepsWithCaches:a})}catch(c){t.warn({err:c},"Failed to save step caches after execution, future runs may be slower"),s.push(...me({text:"Warning: Steps were saved successfully, but updating the step cache failed. Future runs may be slower until the cache is refreshed.",section:"Warning"}))}return s}var vA=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 Yg(this.reporter,this.parentStepIdChain.concat(this.step.id),this.setTotal)}},Yg=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 vA(this.reporter,e.step,this.parentStepIdChain,this.setTotal)}};function sB(t,e,r,n){let o=qv(t),i={completed:0,total:0},a=new AbortController,s=!1,c=p=>{o&&xF(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: ${Xn(p)}`)},onStepComplete:p=>{n(),l(),i.completed+=1,i.total<i.completed&&(i.total=i.completed),c(`Completed: ${Xn(p)}`)}};return new Yg(d,[],u)}var x7=Zt({schema:{name:wI,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:pE},handle:async(t,e,r,n)=>{let{project:o}=t;try{let i=await mp({project:o,input:e});r.addPartFromText(JSON.stringify(i,null,2))}catch(i){r.addError(Yt(i));return}}}),_7=Zt({schema:{name:RI,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=Ph(o,i),l=await bF({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)}}),lB=Zt({schema:{name:LI,description:"Execute a step without adding it to the test.",inputSchema:{sessionId:lo.string(),step:lo.string().describe(`CLI-style step definition. Use data returned from the ${gi} tool to get the full step schema.`)}},handle:async(t,e,r,n)=>{let{sessionId:o,step:i}=e,a=Ws(r,o);if(!a)return;a.controller.setOpen();let s=await Gg({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)}}),cB=Zt({schema:{name:xI,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:lo.string(),startIndex:lo.number(),deleteCount:lo.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:lo.array(lo.string()).describe(`CLI-style definition of steps to insert. Use data returned from the ${gi} tool to get the full step schema.`),targetSection:Xa.default("main"),parentStepIdChain:lo.array(lo.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:lo.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=Ws(r,e.sessionId);if(!o)return;let a=(await qg({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)}}),uB=Zt({schema:{name:_I,description:"Run one or more steps from the test bound to an active session.",inputSchema:{sessionId:lo.string(),fromStep:mm,toStep:fm.optional(),targetSection:Xa.default("main"),resetSession:lo.boolean().default(!1).describe("Whether to reset the browser session before running the steps.")}},handle:async(t,e,r,n)=>{let o=Ws(r,e.sessionId);if(!o)return;o.controller.setOpen(),e.resetSession&&await Fg({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=sB(n,t.logger,r,()=>{ii.touchSession(o.sessionId)}),s=(await Kg({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)}}),dB=[_7,x7];var pB=[HF,GF,jF,VF,WF,lB,uB,cB];import{z as Rr}from"zod";import P7 from"fs";import bp from"path";import I7 from"fs";import Hc from"path";function mB(t){let e=t.subDir?Hc.join(t.project.rootDir,t.subDir):t.project.rootDir,r=`${dt(t.name)}.module.yaml`,n=Hc.join(e,r),o=Hc.relative(t.project.rootDir,n),i=I7.statSync(n);return{type:ye.MODULE,name:t.name,id:t.moduleId,description:t.description??void 0,relativePath:o,fullFilePath:n,platformSep:Hc.sep,fullPathSegments:n.split(Hc.sep),relativePathSegments:o.split(Hc.sep),fileName:r,lastModified:i.mtime,createdAt:i.birthtime}}async function M7({moduleMetadata:t,steps:e,momenticFiles:r,project:n}){let{stepsToSave:o}=await Ut({stepLists:{steps:e}});Jn({content:{...t,steps:o.steps},schemaVersion:De,momenticFiles:r,project:n})}async function Xg({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=bp.isAbsolute(r)?r:bp.join(t.rootDir,r);s=(await Ft(f,e,a)).steps}let{stepsToExtract:c,startIndex:l,endIndex:u}=PF({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:AL}),d=i.subDir?bp.join(t.rootDir,i.subDir):t.rootDir;i.subDir&&P7.mkdirSync(d,{recursive:!0});let p=await _h({name:i.name,description:i.description??"",enabled:i.enabled??!0,steps:c,folder:d,project:t}),m=mB({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 M7({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=bp.isAbsolute(r)?r:bp.join(t.rootDir,r),h=await Ft(f,e,a),S={steps:h.steps??[],beforeSteps:h.beforeSteps??[],afterSteps:h.afterSteps??[]},g=await up({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}=$g({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 Ut({stepLists:y});C.forEach(I=>{Jn({content:I,schemaVersion:De,momenticFiles:a,project:t})}),bn({relativeTestPath:r,steps:b,schemaVersion:De,project:t})}}return{module:p}}var fB=Zt({schema:{name:CI,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(oa),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=fF({projectRoot:t.project.rootDir,filePath:o,pathLabel:"testPath"}),s=await Xg({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 Jg=[...dB,...zg,...pB,fB];var AA=async(t,e)=>{try{let{killed:r,failed:n}=await ii.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 CA({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}){mc(e,!0),rg(n),ng({alwaysSaveCache:s,noCache:c}),await og(r),Oc(t,g=>Ct({configFilePath:g}));let m={serverId:O7(),applicationName:i,cliVersion:o},f=e.child({orgId:Kt(),userId:Qo(),...m}),h=new un(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:Pa)*60*1e3,customHeaders:u,devicePixelRatio:d};return IF({context:S,info:m,tools:Jg,shutdownHandlers:[AA]})}import{Router as U7}from"express";import{Router as N7}from"express";import Cp from"fs";import Ap from"path";import{v4 as D7}from"uuid";import k7 from"yaml";import{hostname as L7}from"os";var vp="2.72.0",ut=Yl({app:"desktop-server",hostname:L7(),disableConsoleLogs:!0,captureExceptions:!0}).child({cliVersion:vp});(async()=>{try{let t=await Ii(ut);t.gitBranchName&&ut.addBinding("branch",t.gitBranchName)}catch{}})();var Js=N7();async function Qg(t){return(await Ih(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)}Js.get("/",Ge(async(t,e)=>{let r=Re(),n=await fe(r),o=await Qg(n);e.status(200).json(o)}));Js.get("/tests-join",Ge(async(t,e)=>{let r=Re(),n=await fe(r),o=await Qg(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 Ft(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)cn({steps:m??[],onPresetAction:()=>{},onConditional:()=>{},onSimpleStepContainer:f=>{JS(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)}));Js.post("/",Ge(async(t,e)=>{let r;try{r=u_.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=Ap.join(n.rootDir,r.folderPath??"");if(!Cp.existsSync(i)||!Cp.statSync(i).isDirectory()){e.status(400).json({error:`The folder configured for module creation '${i}' does not exist.`});return}let a=await _h({...r,folder:i,project:n});e.status(201).json(a)}));Js.get("/:moduleId",Ge(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 xi(n,r,v);e.json(o)}catch(o){e.status(400).json({err:o})}}));Js.post("/:moduleId/duplicate",Ge(async(t,e)=>{if(!t.params.moduleId){e.status(400).json({error:"Missing moduleId in url path."});return}let r;try{r=c_.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 xi(i,o,v),s=Ap.join(n.rootDir,Ap.dirname(i.relativePath));if(!Cp.existsSync(s)||!Cp.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=Ap.join(s,`${c}.module.yaml`),u=D7(),{stepsToSave:d}=await Ut({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=k7.stringify(p);Cp.writeFileSync(l,m,"utf-8");let f={relativeFilePath:Ap.relative(n.rootDir,l)};e.status(201).json(f)}));Js.patch("/:moduleId/metadata",Ge(async(t,e)=>{if(!t.params.moduleId){e.status(400).json({error:"Missing moduleId in url path."});return}let r;try{r=d_.parse(t.body)}catch(i){e.status(400).json({error:`Invalid request body: ${i}`});return}let n=Re(),o=await fe(n);kN({moduleId:t.params.moduleId,content:r,momenticFiles:o,logger:v,project:n}),e.status(201).json({message:"ok"})}));var hB=Js;var gB=U7();gB.get("/",Ge(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 Qg(n),c={labels:i,tests:a,modules:s};e.status(200).json(c)}));var SB=gB;import{Router as F7}from"express";var RA=F7();RA.get("/",Ge((t,e)=>{let r=Ph(Re(),ut);e.status(200).json(r)}));RA.get("/names",Ge((t,e)=>{let n=Re().config.environments?.map(o=>o.name)??[];e.status(200).json(n)}));var yB=RA;import{Router as B7}from"express";var EB=B7();EB.get("/",Ge((t,e)=>{let r={userId:Qo(),orgId:Kt(),cliVersion:vp??"0.0.0"};e.status(200).json(r)}));var TB=EB;import{StreamableHTTPServerTransport as z7}from"@modelcontextprotocol/sdk/server/streamableHttp.js";import{isInitializeRequest as H7}from"@modelcontextprotocol/sdk/types.js";import{randomUUID as vB}from"crypto";import{Router as G7}from"express";var wA="mcp-session-id",bB="MOMENTIC_SESSION_IDLE_TIMEOUT_MINUTES",Zg=G7();function j7(){let t=process.env[bB];if(!t)return Pa*60*1e3;let e=Number.parseInt(t,10);return Number.isNaN(e)||e<1?(ut.warn({envVar:bB,rawValue:t,fallback:Pa},"Invalid MCP session idle timeout env var; falling back to default"),Pa*60*1e3):e*60*1e3}function V7(t,e){let r={serverId:vB(),applicationName:"momentic-mcp-desktop-server",cliVersion:vp??"0.0.0"},n=Re(),o=Cr(),i=qt(),a=ut.child({orgId:Kt(),userId:Qo(),...r}),s=Gl(process.env.MOMENTIC_HEADFUL_BROWSER),c=new un(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:j7(),headfulBrowserDefault:t??s??!0},info:r}}var Di={};Zg.post("/",async(t,e)=>{let r=String(t.headers[wA]??"");try{if(r&&Di[r]){await Di[r].handleRequest(t,e,t.body);return}if(!r&&H7(t.body)){let{context:n,info:o}=V7(),i=Kv(n,o,Jg),a=new z7({sessionIdGenerator:()=>vB(),enableDnsRebindingProtection:!1,onsessioninitialized:s=>{Di[s]=a}});a.onclose=()=>{let s=a.sessionId;s&&Di[s]&&delete Di[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})}});Zg.get("/",async(t,e)=>{let r=String(t.headers[wA]??"");if(!r||!Di[r]){e.status(400).send("Invalid or missing session ID");return}await Di[r].handleRequest(t,e)});Zg.delete("/",async(t,e)=>{let r=String(t.headers[wA]??"");if(!r||!Di[r]){e.status(400).send("Invalid or missing session ID");return}let n=Di[r];try{await n.handleRequest(t,e)}catch{e.headersSent||e.status(500).send("Error processing session termination")}});var AB=Zg;import{Router as W7}from"express";var CB=W7();CB.get("/:id",Ge(async(t,e)=>{let{id:r}=t.params;if(!r){e.status(400).json({error:"Missing ID"});return}let n=Mc();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 RB=CB;import{Router as $7}from"express";var eS=$7();eS.get("/",Ge(async(t,e)=>{let r=(await db()).map(n=>({name:n.config.name,configFilePath:n.configFilePath}));e.status(200).json(r)}));eS.get("/current",Ge((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)}));eS.post("/set",Ge(async(t,e)=>{let r;try{r=m_.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});Oc(n,o=>Ct({configFilePath:o}))}catch(n){e.status(400).json({error:`Error setting project: ${n}`});return}e.sendStatus(204)}));var wB=eS;import{Router as q7}from"express";var xB=q7();xB.get("/",Ge((t,e)=>{let r=Re(),n={ai:r.config.ai,browser:r.config.browser,displayRoot:r.config.displayRoot};e.status(200).json(n)}));var _B=xB;import{streamText as See}from"ai";import{Router as yee}from"express";import rS from"fs";import Vc from"path";import{v4 as Eee}from"uuid";import Tee from"yaml";import{convertToModelMessages as nee,pruneMessages as oee,stepCountIs as iee}from"ai";import tS from"dedent";var Gc="3",K7=tS`
|
|
5280
|
+
`),section:"Changed Steps"}))}return Pt(y)}async function Kg({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 Ft(aB.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}=Ds(),_=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=bA(E,S),M=v7({steps:E.steps,beforeSteps:E.beforeSteps,afterSteps:E.afterSteps}),{result:P}=vs(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}=vs(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=oB({steps:R,fromStep:f,toStep:h});u.setProgressTotal(te)}o.setOpen();let{results:B}=await sA({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 U=B.at(-1);if(!U)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=U.status!=="SUCCESS";if(z)U.status==="FAILED"&&await Ec(G);else try{await Cs(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 ${U.id} failed: ${U.message}`,section:"Error"}));else{o.setOpen();let te=`${X} executed successfully.`;ne.push(...me({text:te,section:"Result"})),U.data&&ne.push(...me({text:`Data: ${JSON.stringify(U.data,null,2)}`,section:"Result Data"}))}let[de,Te]=await Promise.all([Fr({browser:o.browser,supportsFileOutput:m}),so({testContext:l,supportsFileOutput:m,limits:{tokenLimit:p}})]);return Pt([...ne,...de,...Te])}async function w7({logger:t,project:e,orgId:r,testId:n,environment:o,originalSteps:i,updatedSteps:a}){let s=[];try{let c=new pt({baseUrl:qt(),apiKey:Cr(),logger:t}),l=await Er(t,c,e),{alwaysSaveCache:u,noCache:d}=Ds(),p=xo({logger:t,orgId:r,client:c,gitMetadata:l,regenerateCache:!1,alwaysSaveCache:u,noCache:d,isolateCachesByEnvironment:e.config?.advanced?.isolateCachesByEnvironment,bustOldestCachePercentage:void 0});await Cs({logger:t,cacheStorage:p,orgId:r,testId:n,environment:o,originalStepsWithCaches:i,updatedStepsWithCaches:a})}catch(c){t.warn({err:c},"Failed to save step caches after execution, future runs may be slower"),s.push(...me({text:"Warning: Steps were saved successfully, but updating the step cache failed. Future runs may be slower until the cache is refreshed.",section:"Warning"}))}return s}var vA=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 Yg(this.reporter,this.parentStepIdChain.concat(this.step.id),this.setTotal)}},Yg=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 vA(this.reporter,e.step,this.parentStepIdChain,this.setTotal)}};function sB(t,e,r,n){let o=qv(t),i={completed:0,total:0},a=new AbortController,s=!1,c=p=>{o&&xF(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: ${Xn(p)}`)},onStepComplete:p=>{n(),l(),i.completed+=1,i.total<i.completed&&(i.total=i.completed),c(`Completed: ${Xn(p)}`)}};return new Yg(d,[],u)}var x7=Zt({schema:{name:wI,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:pE},handle:async(t,e,r,n)=>{let{project:o}=t;try{let i=await mp({project:o,input:e});r.addPartFromText(JSON.stringify(i,null,2))}catch(i){r.addError(Yt(i));return}}}),_7=Zt({schema:{name:RI,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=Ph(o,i),l=await bF({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)}}),lB=Zt({schema:{name:LI,description:"Execute a step without adding it to the test.",inputSchema:{sessionId:lo.string(),step:lo.string().describe(`CLI-style step definition. Use data returned from the ${gi} tool to get the full step schema.`)}},handle:async(t,e,r,n)=>{let{sessionId:o,step:i}=e,a=Ws(r,o);if(!a)return;a.controller.setOpen();let s=await Gg({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)}}),cB=Zt({schema:{name:xI,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:lo.string(),startIndex:lo.number(),deleteCount:lo.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:lo.array(lo.string()).describe(`CLI-style definition of steps to insert. Use data returned from the ${gi} tool to get the full step schema.`),targetSection:Xa.default("main"),parentStepIdChain:lo.array(lo.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:lo.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=Ws(r,e.sessionId);if(!o)return;let a=(await qg({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)}}),uB=Zt({schema:{name:_I,description:"Run one or more steps from the test bound to an active session.",inputSchema:{sessionId:lo.string(),fromStep:mm,toStep:fm.optional(),targetSection:Xa.default("main"),resetSession:lo.boolean().default(!1).describe("Whether to reset the browser session before running the steps.")}},handle:async(t,e,r,n)=>{let o=Ws(r,e.sessionId);if(!o)return;o.controller.setOpen(),e.resetSession&&await Fg({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=sB(n,t.logger,r,()=>{ii.touchSession(o.sessionId)}),s=(await Kg({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)}}),dB=[_7,x7];var pB=[HF,GF,jF,VF,WF,lB,uB,cB];import{z as Rr}from"zod";import P7 from"fs";import bp from"path";import I7 from"fs";import Hc from"path";function mB(t){let e=t.subDir?Hc.join(t.project.rootDir,t.subDir):t.project.rootDir,r=`${dt(t.name)}.module.yaml`,n=Hc.join(e,r),o=Hc.relative(t.project.rootDir,n),i=I7.statSync(n);return{type:ye.MODULE,name:t.name,id:t.moduleId,description:t.description??void 0,relativePath:o,fullFilePath:n,platformSep:Hc.sep,fullPathSegments:n.split(Hc.sep),relativePathSegments:o.split(Hc.sep),fileName:r,lastModified:i.mtime,createdAt:i.birthtime}}async function M7({moduleMetadata:t,steps:e,momenticFiles:r,project:n}){let{stepsToSave:o}=await Ut({stepLists:{steps:e}});Jn({content:{...t,steps:o.steps},schemaVersion:De,momenticFiles:r,project:n})}async function Xg({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=bp.isAbsolute(r)?r:bp.join(t.rootDir,r);s=(await Ft(f,e,a)).steps}let{stepsToExtract:c,startIndex:l,endIndex:u}=PF({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:AL}),d=i.subDir?bp.join(t.rootDir,i.subDir):t.rootDir;i.subDir&&P7.mkdirSync(d,{recursive:!0});let p=await _h({name:i.name,description:i.description??"",enabled:i.enabled??!0,steps:c,folder:d,project:t}),m=mB({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 M7({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=bp.isAbsolute(r)?r:bp.join(t.rootDir,r),h=await Ft(f,e,a),S={steps:h.steps??[],beforeSteps:h.beforeSteps??[],afterSteps:h.afterSteps??[]},g=await up({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}=$g({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 Ut({stepLists:y});C.forEach(I=>{Jn({content:I,schemaVersion:De,momenticFiles:a,project:t})}),bn({relativeTestPath:r,steps:b,schemaVersion:De,project:t})}}return{module:p}}var fB=Zt({schema:{name:CI,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(oa),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=fF({projectRoot:t.project.rootDir,filePath:o,pathLabel:"testPath"}),s=await Xg({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 Jg=[...dB,...zg,...pB,fB];var AA=async(t,e)=>{try{let{killed:r,failed:n}=await ii.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 CA({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}){mc(e,!0),rg(n),ng({alwaysSaveCache:s,noCache:c}),await og(r),Oc(t,g=>Ct({configFilePath:g}));let m={serverId:O7(),applicationName:i,cliVersion:o},f=e.child({orgId:Kt(),userId:Qo(),...m}),h=new un(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:Pa)*60*1e3,customHeaders:u,devicePixelRatio:d};return IF({context:S,info:m,tools:Jg,shutdownHandlers:[AA]})}import{Router as U7}from"express";import{Router as N7}from"express";import Cp from"fs";import Ap from"path";import{v4 as D7}from"uuid";import k7 from"yaml";import{hostname as L7}from"os";var vp="2.72.1",ut=Yl({app:"desktop-server",hostname:L7(),disableConsoleLogs:!0,captureExceptions:!0}).child({cliVersion:vp});(async()=>{try{let t=await Ii(ut);t.gitBranchName&&ut.addBinding("branch",t.gitBranchName)}catch{}})();var Js=N7();async function Qg(t){return(await Ih(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)}Js.get("/",Ge(async(t,e)=>{let r=Re(),n=await fe(r),o=await Qg(n);e.status(200).json(o)}));Js.get("/tests-join",Ge(async(t,e)=>{let r=Re(),n=await fe(r),o=await Qg(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 Ft(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)cn({steps:m??[],onPresetAction:()=>{},onConditional:()=>{},onSimpleStepContainer:f=>{JS(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)}));Js.post("/",Ge(async(t,e)=>{let r;try{r=u_.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=Ap.join(n.rootDir,r.folderPath??"");if(!Cp.existsSync(i)||!Cp.statSync(i).isDirectory()){e.status(400).json({error:`The folder configured for module creation '${i}' does not exist.`});return}let a=await _h({...r,folder:i,project:n});e.status(201).json(a)}));Js.get("/:moduleId",Ge(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 xi(n,r,v);e.json(o)}catch(o){e.status(400).json({err:o})}}));Js.post("/:moduleId/duplicate",Ge(async(t,e)=>{if(!t.params.moduleId){e.status(400).json({error:"Missing moduleId in url path."});return}let r;try{r=c_.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 xi(i,o,v),s=Ap.join(n.rootDir,Ap.dirname(i.relativePath));if(!Cp.existsSync(s)||!Cp.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=Ap.join(s,`${c}.module.yaml`),u=D7(),{stepsToSave:d}=await Ut({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=k7.stringify(p);Cp.writeFileSync(l,m,"utf-8");let f={relativeFilePath:Ap.relative(n.rootDir,l)};e.status(201).json(f)}));Js.patch("/:moduleId/metadata",Ge(async(t,e)=>{if(!t.params.moduleId){e.status(400).json({error:"Missing moduleId in url path."});return}let r;try{r=d_.parse(t.body)}catch(i){e.status(400).json({error:`Invalid request body: ${i}`});return}let n=Re(),o=await fe(n);kN({moduleId:t.params.moduleId,content:r,momenticFiles:o,logger:v,project:n}),e.status(201).json({message:"ok"})}));var hB=Js;var gB=U7();gB.get("/",Ge(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 Qg(n),c={labels:i,tests:a,modules:s};e.status(200).json(c)}));var SB=gB;import{Router as F7}from"express";var RA=F7();RA.get("/",Ge((t,e)=>{let r=Ph(Re(),ut);e.status(200).json(r)}));RA.get("/names",Ge((t,e)=>{let n=Re().config.environments?.map(o=>o.name)??[];e.status(200).json(n)}));var yB=RA;import{Router as B7}from"express";var EB=B7();EB.get("/",Ge((t,e)=>{let r={userId:Qo(),orgId:Kt(),cliVersion:vp??"0.0.0"};e.status(200).json(r)}));var TB=EB;import{StreamableHTTPServerTransport as z7}from"@modelcontextprotocol/sdk/server/streamableHttp.js";import{isInitializeRequest as H7}from"@modelcontextprotocol/sdk/types.js";import{randomUUID as vB}from"crypto";import{Router as G7}from"express";var wA="mcp-session-id",bB="MOMENTIC_SESSION_IDLE_TIMEOUT_MINUTES",Zg=G7();function j7(){let t=process.env[bB];if(!t)return Pa*60*1e3;let e=Number.parseInt(t,10);return Number.isNaN(e)||e<1?(ut.warn({envVar:bB,rawValue:t,fallback:Pa},"Invalid MCP session idle timeout env var; falling back to default"),Pa*60*1e3):e*60*1e3}function V7(t,e){let r={serverId:vB(),applicationName:"momentic-mcp-desktop-server",cliVersion:vp??"0.0.0"},n=Re(),o=Cr(),i=qt(),a=ut.child({orgId:Kt(),userId:Qo(),...r}),s=Gl(process.env.MOMENTIC_HEADFUL_BROWSER),c=new un(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:j7(),headfulBrowserDefault:t??s??!0},info:r}}var Di={};Zg.post("/",async(t,e)=>{let r=String(t.headers[wA]??"");try{if(r&&Di[r]){await Di[r].handleRequest(t,e,t.body);return}if(!r&&H7(t.body)){let{context:n,info:o}=V7(),i=Kv(n,o,Jg),a=new z7({sessionIdGenerator:()=>vB(),enableDnsRebindingProtection:!1,onsessioninitialized:s=>{Di[s]=a}});a.onclose=()=>{let s=a.sessionId;s&&Di[s]&&delete Di[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})}});Zg.get("/",async(t,e)=>{let r=String(t.headers[wA]??"");if(!r||!Di[r]){e.status(400).send("Invalid or missing session ID");return}await Di[r].handleRequest(t,e)});Zg.delete("/",async(t,e)=>{let r=String(t.headers[wA]??"");if(!r||!Di[r]){e.status(400).send("Invalid or missing session ID");return}let n=Di[r];try{await n.handleRequest(t,e)}catch{e.headersSent||e.status(500).send("Error processing session termination")}});var AB=Zg;import{Router as W7}from"express";var CB=W7();CB.get("/:id",Ge(async(t,e)=>{let{id:r}=t.params;if(!r){e.status(400).json({error:"Missing ID"});return}let n=Mc();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 RB=CB;import{Router as $7}from"express";var eS=$7();eS.get("/",Ge(async(t,e)=>{let r=(await db()).map(n=>({name:n.config.name,configFilePath:n.configFilePath}));e.status(200).json(r)}));eS.get("/current",Ge((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)}));eS.post("/set",Ge(async(t,e)=>{let r;try{r=m_.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});Oc(n,o=>Ct({configFilePath:o}))}catch(n){e.status(400).json({error:`Error setting project: ${n}`});return}e.sendStatus(204)}));var wB=eS;import{Router as q7}from"express";var xB=q7();xB.get("/",Ge((t,e)=>{let r=Re(),n={ai:r.config.ai,browser:r.config.browser,displayRoot:r.config.displayRoot};e.status(200).json(n)}));var _B=xB;import{streamText as See}from"ai";import{Router as yee}from"express";import rS from"fs";import Vc from"path";import{v4 as Eee}from"uuid";import Tee from"yaml";import{convertToModelMessages as nee,pruneMessages as oee,stepCountIs as iee}from"ai";import tS from"dedent";var Gc="3",K7=tS`
|
|
5281
5281
|
<ai-actions>
|
|
5282
5282
|
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:
|
|
5283
5283
|
- Multi-step workflows that require decision-making (e.g., "Find and click the first available appointment slot")
|
|
@@ -5579,7 +5579,7 @@ ${t.map(p=>`${It}- ${p}`).join(`
|
|
|
5579
5579
|
`))}async function zz({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 pS({prompt:"Select a test to unquarantine.",inputtedTest:t,testOptions:l}),d=await mS({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 Hz(t){return t?dt(t):"Unknown suite"}async function Gz({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 rh({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} ${Hz(g.suite?.name)}`)))}),S.every(d))}),m=t.getAppUrl(),h=dc({results:p,startTime:c,onFailed:S=>{let g=Hz(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 jz({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 rh({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=dc({results:d,startTime:u,onFailed:m=>{let f=m.testName||m.test?.name;nh(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 Hte}from"crypto";import Gte from"fs";import{existsSync as gte,mkdirSync as Ste,statSync as yte}from"fs";import{randomUUID as Zs}from"crypto";import Kc,{writeFileSync as Vz}from"fs";import{hostname as Yee}from"os";import ai from"path";import{z as fS}from"zod";async function gS(t,e,r,n){if(n){let o=await e.getScreenshot(t,n);if(o){let i=`screenshot-${n}.jpeg`,a=ai.join(r,i);return Kc.writeFileSync(a,o),i}}}async function Xee(t,e,r,n){let o=r.folder,i={uuid:n.runAttemptId??Zs(),historyId:n.runId??Zs(),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:Yee()},{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 XA(t,e,r.folder,i.steps,n.results);let a=Jee(e,o,i.uuid);a.length>0&&(i.attachments=a);let s=`${n.runAttemptId}-result.json`;Kc.writeFileSync(ai.join(o,s),JSON.stringify(i,void 0,2))}async function hS(t,e,r,n){let o={name:dN(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 gS(t,e,r,n.beforeSnapshot);i&&o.attachments.push({name:"Screenshot before step",source:i,type:"image/jpeg"});let a=await gS(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(uu.safeParse(n.data).success){let s=uu.parse(n.data),c=s.request,l={...s,request:void 0},u=`output-attachment-api-request-${Zs()}.json`,d=`output-attachment-api-response-${Zs()}.json`,p=ai.join(r,u),m=ai.join(r,d);Kc.writeFileSync(p,JSON.stringify(c,null,2)),Kc.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=fS.union([fS.object({}).passthrough(),fS.array(fS.any())]).safeParse(n.data).success,c=`output-attachment-${Zs()}.json`,l=ai.join(r,c);Kc.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 XA(t,e,r,n,o){for(let i of o){let a;switch(i.type){case"PRESET_ACTION":{a=await hS(t,e,r,i);break}case"CONDITIONAL":{a=await hS(t,e,r,i),a.steps=[],i.assertionResult&&a.steps.push(await hS(t,e,r,i.assertionResult)),await XA(t,e,r,a.steps,i.results);break}case"AI_ACTION_DYNAMIC":case"AI_ACTION":case"SECTION":case"MODULE":{if(a=await hS(t,e,r,i),await XA(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-${Zs()}.json`,c=ai.join(r,s);Vz(c,Wz(i.beforeTestContext.env)),a.attachments.push({name:"Test context before step",source:s,type:"application/json"})}if(i.afterTestContext){let s=`after-context-${Zs()}.json`,c=ai.join(r,s);Vz(c,Wz(i.afterTestContext.env)),a.attachments.push({name:"Test context after step",source:s,type:"application/json"})}n.push(a)}}async function $z(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 Xee(t,a,{folder:r,suiteName:n.suiteName},i)}finally{a.close()}}}function Wz(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 Jee(t,e,r){let n=t.listVideoAssetPaths();if(n.length===0)return[];let o=[];for(let i of n){let a=ai.basename(i),s=a,c=ai.join(e,s);try{Kc.copyFileSync(i,c)}catch{continue}let l,u=ai.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 Yz}from"crypto";import Qee from"fs";import yS from"path";function SS(t){if(t.status!=="FAILED")return"none";switch(t.failureReason){case"SetupFailureError":return"setup";case"TeardownFailureError":return"teardown";default:return"main"}}function Zee(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 r_(t)}}function Xz(t){let e=yS.relative(".",t);return e===""?t:e}function qz(t,e){return Math.max(0,(t.getTime()-e.getTime())/1e3)}function ete(t,e,r){let n=qz(e,t),o=qz(r,t);return{start_at:n,end_at:o,duration:Math.max(0,o-n)}}function Jz(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 tte(t){if(t.status!=="FAILED"||!t.failureReason)return;let e=t.failureDetails?.classification,r=Sl[e?.reason||t.failureReason],n=e?.summary||t.failureDetails?.errorMessage||Vi[t.failureReason];return`${r}: ${n}`}function rte(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(`
|
|
5580
5580
|
`).map(n=>n.trim()).filter(Boolean)||[];if(!(e.length===0&&r.length===0))return[{expanded:e,backtrace:r}]}function nte(t){let e=t.status==="FAILED"?SS(t):void 0;return Jz([["failure_section",e],["quarantined",t.quarantined?"true":"false"],["failure_recovery",t.failureRecoveryDetails?.attempts?"true":"false"]])}function ote(t,e,r){let n=Xz(r.filePath);return{id:r.runId||Yz(),scope:t,name:r.testName,location:n,file_name:yS.basename(n),result:Zee(r.status),failure_reason:tte(r),failure_expanded:rte(r),history:ete(e,r.lastAttemptStartedAt,r.finishedAt),tags:nte(r)}}function Kz(t,e,r,n,o){let i=Xz(e);return{id:Yz(),scope:t,name:r,location:i,file_name:yS.basename(i),result:"skipped",history:{start_at:0,end_at:0,duration:0},tags:Jz([["quarantined",o?.quarantined||"false"],["failure_recovery","false"]])}}function ite(t,e){let r=e.map(i=>ote(t.suiteName,t.startedAt,i)),n=t.testsToSkip.map(i=>Kz(t.suiteName,i.relativeFilePath,i.name,i.id,void 0)),o=t.quarantinedTestsToSkip.map(i=>Kz(t.suiteName,i.relativeFilePath,i.name,i.id,{quarantined:"true"}));return[...r,...n,...o]}function Qz(t,e,r){let n=ite(e,r);Qee.writeFileSync(yS.join(t,`${e.suiteName}.buildkite.json`),JSON.stringify(n,null,2))}import ate from"junit-report-builder";import ES from"path";function Zz(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 ste(t,e){let r=SS(t);if(e.name(t.testName).className(t.testName).file(ES.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&&Zz(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=Sl[t.failureDetails?.classification?.reason||t.failureReason],o=t.failureDetails?.classification?.summary||Vi[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 lte(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();ste(d,p)}for(let d of s){let p=u.testCase();p.name(d.name).className(d.name).file(ES.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(ES.relative(".",d.relativeFilePath)).property("id",d.id);let m=l[d.id];m&&Zz(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 eH(t,e,r){let n=ate.newBuilder();lte(n,e,r),n.writeTo(ES.join(t,`${e.suiteName}.xml`))}import cte from"fs";import ute from"path";function tH(t){return{title:Xn(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(tH):[]}}async function dte(t,e,r,n){if(n.results?.length){let o=await gS(t,e,r,n.results[n.results.length-1].afterSnapshot);return o?[{name:"Final state screenshot",path:o,contentType:"image/jpeg"}]:[]}return[]}async function pte(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||Vi[n.failureReason]}:void 0,retry:n.attempts-1,steps:n.results?.map(tH)||[],startTime:n.lastAttemptStartedAt.toISOString(),attachments:await dte(t,e,r,n)}}async function mte(t,e,r,n){return{expectedStatus:"passed",status:n.status==="PASSED"?"expected":"unexpected",results:[await pte(t,e,r,n)]}}async function fte(t,e,r,n){return{tags:[],title:n.test.name,ok:n.status==="PASSED",tests:[await mte(t,e,r,n)],id:n.runId,file:n.filePath}}function JA(t,e){return t.reduce((r,n)=>e(n)?r+1:r,0)}async function hte(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 nd;try{return await fte(t,a,r,i)}finally{a.close()}}))}],errors:[],stats:{startTime:n.startedAt.toISOString(),duration:n.finishedAt.getTime()-n.startedAt.getTime(),expected:JA(o,i=>i.status==="PASSED"),unexpected:JA(o,i=>i.status!=="PASSED"),flaky:JA(o,i=>!!i.isFlake),skipped:0}}}async function rH(t,e,r,n,o){let i=await hte(t,e,r,n,o);cte.writeFileSync(ute.join(r,`${n.suiteName}.json`),JSON.stringify(i,null,2))}function nH(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 oH({logger:t,callbacks:e,format:r,params:n,runs:o,folder:i}){switch(gte(i)?yte(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...`),Ste(i,{recursive:!0})),r){case"junit":{let a=o.map(nH);eH(i,n,a);return}case"buildkite-json":{let a=o.map(nH);Qz(i,n,a);return}case"allure":case"allure-json":await $z(t,e,i,n,o);return;case"playwright-json":await rH(t,e,i,n,o);return;default:throw new Error(`Unknown reporter format requested: '${r}'`)}}import jte from"wait-on";import{execSync as Ete}from"child_process";import{platform as Tte}from"os";function TS(){return iH()?(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.
|
|
5581
5581
|
`),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.
|
|
5582
|
-
`),1)}function iH(){return Tte()==="darwin"&&Ete("system_profiler SPDisplaysDataType").toString().includes("Retina")}function bS(t){iH()&&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 bte from"@actions/exec";import vte from"@actions/io";import Ate from"quote";import Cte from"string-argv";async function aH(t,e=!0){let r=Cte(t),n=await vte.which(r[0],!0),o=r.slice(1),i=bte.exec(Ate(n),o,{delay:100});if(e)return i}import Rte from"csv-parser";import{createReadStream as wte}from"fs";function QA(t){return new Promise((e,r)=>{let n=[];wte(t).pipe(Rte()).on("data",o=>n.push(o)).on("end",()=>e(n)).on("error",o=>r(o))})}import Yc from"semver";import{z as vS}from"zod";var en="2.72.0",xte="https://registry.npmjs.org/momentic",_te=vS.object({versions:vS.record(vS.string(),vS.unknown()).optional()});async function Po(t){try{await Ite(t)}catch(e){v.warn({err:e},"Failed to check CLI version against NPM servers")}}async function ZA(){let t=await J(fetch(xte),{milliseconds:5e3});if(!t.ok)throw new Error(`Got error status code ${t.statusText}`);let e=await t.json(),r=_te.parse(e).versions;if(!r)throw new Error("Failed to fetch npm registry data. Skipping version check.");let n=en;for(let o of Object.keys(r))Yc.valid(o)&&Yc.major(o)===Yc.major(en)&&Yc.gt(o,n)&&Yc.prerelease(o)===null&&(n=o);return n}async function Ite(t){let e;for(let r=0;r<2;r++)try{e=await ZA()}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}Yc.eq(en,e)||(v.warn(`Update available: v${en} -> 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 Fi(){try{await J(Promise.all([rf(),Wt.flush()]),{milliseconds:5e3})}catch{}}import{partition as Pte}from"lodash-es";function AS(t){return t.length===1?"test":"tests"}function sH(t){return t===1?"1 worker":`${t} workers`}function lH(t){t.length!==0&&(v.info(`Skipping ${t.length} disabled ${AS(t)}:`),t.forEach(e=>{v.info(`${It}- ${[e.relativeFilePath]}`)}),v.log(""))}function cH(t,e){t.length!==0&&(v.info(`Skipping ${t.length} quarantined ${AS(t)}:`),t.forEach(r=>{v.info(`${It}- ${[r.relativeFilePath]}: ${e[r.id]?.quarantinedReason}`)}),v.log(""))}function Mte(t,e){t.length!==0&&(v.info(`Running ${t.length} quarantined ${AS(t)} with ${sH(e)}:`),t.forEach(r=>{v.info(`${It}- ${[r.testDefinition.relativeFilePath]}${typeof r.inputIndex=="number"?` with input set ${r.inputIndex}`:""}`)}),v.log(""))}function Ote(t,e,r){e.length===0&&t.length>0||(v.info(`Running ${e.length} ${AS(e)} with ${sH(r)}:`),e.forEach(n=>{v.info(`${It}- ${[n.testDefinition.relativeFilePath]}${typeof n.inputIndex=="number"?` with input set ${n.inputIndex}`:""}`)}),v.log(""))}function uH({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]=Pte(e,s=>s.quarantined);Mte(i,r),Ote(i,a,r)}import{randomUUID as Lte}from"crypto";import{cloneDeep as Xc}from"lodash-es";import{dirname as Nte}from"path";async function dH({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 Qr({orgId:t,s:c,localTools:e,logger:r,context:o})}return i}async function pH({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 kc({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=am({browserTypeOverride:E,configuredBrowserType:y.browserType,orgDefaultBrowserType:f.defaultBrowserType});if(y.browserType=C,!pL(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 io.init({baseUrl:t,logger:d,userBrowserSettings:y,storage:a,enricher:new Ta(b,c),contextArgs:{viewport:i.advanced.viewport??Ir,locale:i.advanced.locale??Ki,geolocation:i.advanced.geolocation??Xi,timezoneId:i.advanced.timezone??Yi,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 _a({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 qr({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:U}=M,G=m?.[P];U&&G===void 0&&(v.error(`Required parameter '${P}' is required by test '${i.name}' but not provided`),process.exit(1));let z=await Qr({orgId:l,s:G??B,localTools:s,logger:d,context:qr.dummyContext(R.getEnvName())});R.setMomenticSystemVariable(P,z)})),{controller:_,context:R}}async function mH({testAdvancedSettings:t,orgSettings:e,logger:r}){if(t.failureRecovery===!1||t.failureRecovery===void 0&&!e?.failureRecovery)return!1;if(!ds){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 fH({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 mH({testAdvancedSettings:p.advanced,orgSettings:m.ai,logger:l})};return await Ig({fixtures:f,inputs:h,options:S,callbacks:{step:{},test:{onTestComplete:async()=>{await i.browser.cleanup()}}},testParams:{tracer:d}})}async function hH(t){let{testDefinition:e,logger:r}=t,n=new Date;try{return await Dte(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 Dte(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 _c(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}=Jh({test:e,envNameOverride:t.envName,urlOverride:i,resolveEnv:U=>Ps(U,r,s)}),C=await fh({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:Nte(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(([U,G])=>{y[U]=G});let B=await kte({...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 kte(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,U=i.config.ai?.aiFailureAnalysis??!1,G=new Date,z=new Cc(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=Lte(),te=await C.startAttempt(Te),be=I.child(te.loggerBindings||{}),Pe={...e,steps:Xc(r),beforeSteps:Xc(n),afterSteps:Xc(o)};de!==0&&b("RETRY",`attempt ${de+1}/${X+1}`);let ve=new Date,x=ae.advanced?.fakerConstantSeed,se=new Jo({httpClient:new Tr({baseUrl:s.baseUrl,apiKey:s.apiKey,logger:be,mode:"runner"}),fakerSeed:x?jl:void 0}),Ae=te;try{let{controller:pn,context:Mo}=await pH({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 fH({attemptMetadata:{attemptNumber:de+1,orgId:d,runId:C.runId},attemptFixtures:{logger:be,storageClient:u,usageTracker:B,codeEvalTools:se,apiClient:s,context:Mo,controller:pn,tracer:te},attemptInputs:{test:Pe,orgSettings:ae}});let On=new Date,Oo={logger:I,cacheStorage:_,orgId:d,testId:e.id,environment:p,originalStepsWithCaches:{steps:Xc(r),beforeSteps:Xc(n),afterSteps:Xc(o)},updatedStepsWithCaches:{steps:Pe.steps,beforeSteps:Pe.beforeSteps,afterSteps:Pe.afterSteps}};q?.status==="PASSED"?await Cs(Oo):q?.status==="FAILED"&&de===X&&await Ec(Oo),await te.finish({logger:be,result:q}),ne.unshift(q.status);let ce=await dH({orgId:d,codeEvalTools:se,logger:be,outputDefinitions:e.outputs??[],testContext:Mo}),si=Ew(ne),Np=de+1;if(q.status!=="FAILED")return{...q,runAttemptId:Te,parameters:W,test:Pe,filePath:Pe.relativeFilePath,startedAt:G,lastAttemptStartedAt:ve,finishedAt:On,attempts:Np,baseUrl:l,outputs:ce,isFlake:si,quarantined:M,quarantinedMetadata:P};let Da=q.failedStepResult,co=Da?.message||"Unknown failure",zi=Da?.failureReason??vR(co)??"UnknownError",tl=be.child({failureReason:zi,errorMessage:co,numAttempts:(X+1).toString(),name:Pe.name});if(de<X){tl.warn(`Retrying failed execution attempt for run: ${co}`);continue}tl.error(`Test failed after all exhausting attempts: ${co}`);let Jc=new Error(co),rl={errorMessage:co,errorStack:Jc.stack},Hi;if(U){let Dp;try{if(q.results&&q.results.length>0){let{classification:Qc,aiFailureReason:tt}=await MN({logger:be,browserStateStorage:Ae,generator:c,fullResults:q,failureReason:zi,error:Jc,maxItemsFromEnd:void 0,numStepsWithScreenshots:void 0,disableCache:!1});Dp=Qc,Hi=tt}}catch(Qc){be.warn({err:Qc},"Failed to classify test results")}Dp&&(rl.classification=Dp,zi=Hi??zi)}return{...q,runAttemptId:Te,parameters:W,failureDetails:rl,failureReason:zi,test:Pe,filePath:Pe.relativeFilePath,startedAt:G,lastAttemptStartedAt:ve,finishedAt:On,attempts:de+1,baseUrl:l,outputs:ce,quarantined:M,quarantinedMetadata:P}}catch(pn){let Mo=`Encountered fatal platform error while running test '${Pe.name}': ${pn}`,On=new Date,Oo=de+1;be.error({err:pn},Mo),v.error(Mo);let ce={errorMessage:pn.message,errStack:pn.stack},si={status:"FAILED",failureDetails:ce,failureReason:"InternalPlatformError",finishedAt:On};return await te.finish({logger:be,result:{status:"FAILED",results:[]}}),{...si,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 Bte from"adm-zip";import zte from"path";function Ute(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 el=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 eC(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:Ute(e.status),finishedAt:e.finishedAt}))),this.sendFinalizedStepStats())}};function Fte(t){switch(t){case"SUCCESS":return"PASSED";case"FAILED":return"FAILED";case"CANCELLED":return"CANCELLED";case"RUNNING":return"RUNNING";case"IDLE":return"PENDING"}}var eC=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 Oi(void 0,a=>this.storeTraceAsset(a)),Mi.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(!tf(e.step))return;let r=ef(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:Fte(e.status),finishedAt:e.finishedAt}))))}async finish(e){await this.finishInternal(e.step),e.step.trace=this.interactionTracer.getRootSpan()}async startSubSteps(){let e=new el(this.orgId,this.testId,this.testName,this.diskStorage);return this.children.push(e),e}};var Mp=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=YI({keepSamples:!1,onSample:c=>{this.resourceUsageStream.write(`${JSON.stringify(c)}
|
|
5582
|
+
`),1)}function iH(){return Tte()==="darwin"&&Ete("system_profiler SPDisplaysDataType").toString().includes("Retina")}function bS(t){iH()&&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 bte from"@actions/exec";import vte from"@actions/io";import Ate from"quote";import Cte from"string-argv";async function aH(t,e=!0){let r=Cte(t),n=await vte.which(r[0],!0),o=r.slice(1),i=bte.exec(Ate(n),o,{delay:100});if(e)return i}import Rte from"csv-parser";import{createReadStream as wte}from"fs";function QA(t){return new Promise((e,r)=>{let n=[];wte(t).pipe(Rte()).on("data",o=>n.push(o)).on("end",()=>e(n)).on("error",o=>r(o))})}import Yc from"semver";import{z as vS}from"zod";var en="2.72.1",xte="https://registry.npmjs.org/momentic",_te=vS.object({versions:vS.record(vS.string(),vS.unknown()).optional()});async function Po(t){try{await Ite(t)}catch(e){v.warn({err:e},"Failed to check CLI version against NPM servers")}}async function ZA(){let t=await J(fetch(xte),{milliseconds:5e3});if(!t.ok)throw new Error(`Got error status code ${t.statusText}`);let e=await t.json(),r=_te.parse(e).versions;if(!r)throw new Error("Failed to fetch npm registry data. Skipping version check.");let n=en;for(let o of Object.keys(r))Yc.valid(o)&&Yc.major(o)===Yc.major(en)&&Yc.gt(o,n)&&Yc.prerelease(o)===null&&(n=o);return n}async function Ite(t){let e;for(let r=0;r<2;r++)try{e=await ZA()}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}Yc.eq(en,e)||(v.warn(`Update available: v${en} -> 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 Fi(){try{await J(Promise.all([rf(),Wt.flush()]),{milliseconds:5e3})}catch{}}import{partition as Pte}from"lodash-es";function AS(t){return t.length===1?"test":"tests"}function sH(t){return t===1?"1 worker":`${t} workers`}function lH(t){t.length!==0&&(v.info(`Skipping ${t.length} disabled ${AS(t)}:`),t.forEach(e=>{v.info(`${It}- ${[e.relativeFilePath]}`)}),v.log(""))}function cH(t,e){t.length!==0&&(v.info(`Skipping ${t.length} quarantined ${AS(t)}:`),t.forEach(r=>{v.info(`${It}- ${[r.relativeFilePath]}: ${e[r.id]?.quarantinedReason}`)}),v.log(""))}function Mte(t,e){t.length!==0&&(v.info(`Running ${t.length} quarantined ${AS(t)} with ${sH(e)}:`),t.forEach(r=>{v.info(`${It}- ${[r.testDefinition.relativeFilePath]}${typeof r.inputIndex=="number"?` with input set ${r.inputIndex}`:""}`)}),v.log(""))}function Ote(t,e,r){e.length===0&&t.length>0||(v.info(`Running ${e.length} ${AS(e)} with ${sH(r)}:`),e.forEach(n=>{v.info(`${It}- ${[n.testDefinition.relativeFilePath]}${typeof n.inputIndex=="number"?` with input set ${n.inputIndex}`:""}`)}),v.log(""))}function uH({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]=Pte(e,s=>s.quarantined);Mte(i,r),Ote(i,a,r)}import{randomUUID as Lte}from"crypto";import{cloneDeep as Xc}from"lodash-es";import{dirname as Nte}from"path";async function dH({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 Qr({orgId:t,s:c,localTools:e,logger:r,context:o})}return i}async function pH({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 kc({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=am({browserTypeOverride:E,configuredBrowserType:y.browserType,orgDefaultBrowserType:f.defaultBrowserType});if(y.browserType=C,!pL(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 io.init({baseUrl:t,logger:d,userBrowserSettings:y,storage:a,enricher:new Ta(b,c),contextArgs:{viewport:i.advanced.viewport??Ir,locale:i.advanced.locale??Ki,geolocation:i.advanced.geolocation??Xi,timezoneId:i.advanced.timezone??Yi,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 _a({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 qr({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:U}=M,G=m?.[P];U&&G===void 0&&(v.error(`Required parameter '${P}' is required by test '${i.name}' but not provided`),process.exit(1));let z=await Qr({orgId:l,s:G??B,localTools:s,logger:d,context:qr.dummyContext(R.getEnvName())});R.setMomenticSystemVariable(P,z)})),{controller:_,context:R}}async function mH({testAdvancedSettings:t,orgSettings:e,logger:r}){if(t.failureRecovery===!1||t.failureRecovery===void 0&&!e?.failureRecovery)return!1;if(!ds){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 fH({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 mH({testAdvancedSettings:p.advanced,orgSettings:m.ai,logger:l})};return await Ig({fixtures:f,inputs:h,options:S,callbacks:{step:{},test:{onTestComplete:async()=>{await i.browser.cleanup()}}},testParams:{tracer:d}})}async function hH(t){let{testDefinition:e,logger:r}=t,n=new Date;try{return await Dte(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 Dte(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 _c(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}=Jh({test:e,envNameOverride:t.envName,urlOverride:i,resolveEnv:U=>Ps(U,r,s)}),C=await fh({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:Nte(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(([U,G])=>{y[U]=G});let B=await kte({...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 kte(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,U=i.config.ai?.aiFailureAnalysis??!1,G=new Date,z=new Cc(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=Lte(),te=await C.startAttempt(Te),be=I.child(te.loggerBindings||{}),Pe={...e,steps:Xc(r),beforeSteps:Xc(n),afterSteps:Xc(o)};de!==0&&b("RETRY",`attempt ${de+1}/${X+1}`);let ve=new Date,x=ae.advanced?.fakerConstantSeed,se=new Jo({httpClient:new Tr({baseUrl:s.baseUrl,apiKey:s.apiKey,logger:be,mode:"runner"}),fakerSeed:x?jl:void 0}),Ae=te;try{let{controller:pn,context:Mo}=await pH({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 fH({attemptMetadata:{attemptNumber:de+1,orgId:d,runId:C.runId},attemptFixtures:{logger:be,storageClient:u,usageTracker:B,codeEvalTools:se,apiClient:s,context:Mo,controller:pn,tracer:te},attemptInputs:{test:Pe,orgSettings:ae}});let On=new Date,Oo={logger:I,cacheStorage:_,orgId:d,testId:e.id,environment:p,originalStepsWithCaches:{steps:Xc(r),beforeSteps:Xc(n),afterSteps:Xc(o)},updatedStepsWithCaches:{steps:Pe.steps,beforeSteps:Pe.beforeSteps,afterSteps:Pe.afterSteps}};q?.status==="PASSED"?await Cs(Oo):q?.status==="FAILED"&&de===X&&await Ec(Oo),await te.finish({logger:be,result:q}),ne.unshift(q.status);let ce=await dH({orgId:d,codeEvalTools:se,logger:be,outputDefinitions:e.outputs??[],testContext:Mo}),si=Ew(ne),Np=de+1;if(q.status!=="FAILED")return{...q,runAttemptId:Te,parameters:W,test:Pe,filePath:Pe.relativeFilePath,startedAt:G,lastAttemptStartedAt:ve,finishedAt:On,attempts:Np,baseUrl:l,outputs:ce,isFlake:si,quarantined:M,quarantinedMetadata:P};let Da=q.failedStepResult,co=Da?.message||"Unknown failure",zi=Da?.failureReason??vR(co)??"UnknownError",tl=be.child({failureReason:zi,errorMessage:co,numAttempts:(X+1).toString(),name:Pe.name});if(de<X){tl.warn(`Retrying failed execution attempt for run: ${co}`);continue}tl.error(`Test failed after all exhausting attempts: ${co}`);let Jc=new Error(co),rl={errorMessage:co,errorStack:Jc.stack},Hi;if(U){let Dp;try{if(q.results&&q.results.length>0){let{classification:Qc,aiFailureReason:tt}=await MN({logger:be,browserStateStorage:Ae,generator:c,fullResults:q,failureReason:zi,error:Jc,maxItemsFromEnd:void 0,numStepsWithScreenshots:void 0,disableCache:!1});Dp=Qc,Hi=tt}}catch(Qc){be.warn({err:Qc},"Failed to classify test results")}Dp&&(rl.classification=Dp,zi=Hi??zi)}return{...q,runAttemptId:Te,parameters:W,failureDetails:rl,failureReason:zi,test:Pe,filePath:Pe.relativeFilePath,startedAt:G,lastAttemptStartedAt:ve,finishedAt:On,attempts:de+1,baseUrl:l,outputs:ce,quarantined:M,quarantinedMetadata:P}}catch(pn){let Mo=`Encountered fatal platform error while running test '${Pe.name}': ${pn}`,On=new Date,Oo=de+1;be.error({err:pn},Mo),v.error(Mo);let ce={errorMessage:pn.message,errStack:pn.stack},si={status:"FAILED",failureDetails:ce,failureReason:"InternalPlatformError",finishedAt:On};return await te.finish({logger:be,result:{status:"FAILED",results:[]}}),{...si,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 Bte from"adm-zip";import zte from"path";function Ute(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 el=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 eC(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:Ute(e.status),finishedAt:e.finishedAt}))),this.sendFinalizedStepStats())}};function Fte(t){switch(t){case"SUCCESS":return"PASSED";case"FAILED":return"FAILED";case"CANCELLED":return"CANCELLED";case"RUNNING":return"RUNNING";case"IDLE":return"PENDING"}}var eC=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 Oi(void 0,a=>this.storeTraceAsset(a)),Mi.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(!tf(e.step))return;let r=ef(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:Fte(e.status),finishedAt:e.finishedAt}))))}async finish(e){await this.finishInternal(e.step),e.step.trace=this.interactionTracer.getRootSpan()}async startSubSteps(){let e=new el(this.orgId,this.testId,this.testName,this.diskStorage);return this.children.push(e),e}};var Mp=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=YI({keepSamples:!1,onSample:c=>{this.resourceUsageStream.write(`${JSON.stringify(c)}
|
|
5583
5583
|
`),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 zte.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)}
|
|
5584
5584
|
`)}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)}
|
|
5585
5585
|
`)):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 Bte;i.addLocalFolder(o,void 0,a=>a!==".DS_Store"),this.diskStorage.storeFile({name:`${gr}/${wE}`,contents:i.toBuffer()}),n.info({browserCrashZipName:wE},"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:Th(n.results,r),beforeResults:n.beforeResults?Th(n.beforeResults,r):void 0,afterResults:n.afterResults?Th(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)}
|
|
@@ -5589,4 +5589,4 @@ ${t.map(p=>`${It}- ${p}`).join(`
|
|
|
5589
5589
|
${o}`),v.success(`Initialized Momentic project file at ${pr.resolve(fa)}`);let i=pr.join("swag-labs");Bi.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)DN(p,pr.join(i,d));for(let{fileName:d,data:p}of u)FN(p,pr.join(i,d));v.success(`Created sample Swag Labs tests and modules in ${pr.resolve(i)}/`)});nr.command("app").addOption(Pn).addOption(Mn).addOption(La).addOption(sS).addOption(zr).addOption(pz).addOption(jA).addOption(uS).addOption(dS).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;ih({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 Ip({project:l,fix:!1});d>0?(pc({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)),XI(le);let h=new pt({baseUrl:n,apiKey:e,logger:le});await Wh({client:h,skipPrompts:r});let S=bH(import.meta.url),g=pr.dirname(S),E=pr.resolve(g,"..","static"),y=pr.resolve(g,"..","assets"),b=o??TS();bS(b),await qB({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 Qte(C)});nr.command("mcp").description("Start the MCP server over stdio.").addOption(Pn).addOption(Mn).addOption(zr).addOption(uS).addOption(dS).addOption(mz).addOption(sS).addOption(Mz).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;ih({disableCache:o,saveCache:n});let c=i!==void 0?i:Gl(process.env.MOMENTIC_HEADFUL_BROWSER)??!0,l=a??TS();bS(l);let u=await Ct({configFilePath:t.config,nameFilter:void 0}),{errors:d,parsingErrors:p,failedTestFilePaths:m,failedModuleFilePaths:f,parsingErrorDetails:h}=await Ip({project:u,fix:!1});p>0?(pc({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 Wh({client:S,skipPrompts:!0}),!en)throw new Error("CLI_VERSION is not set");await CA({project:u,logger:le,apiKey:e,serverUrl:r,cliVersion:en,supportsFileOutput:!0,alwaysSaveCache:n??!1,noCache:o??!1,headfulBrowserDefault:c,devicePixelRatio:l,sessionIdleTimeoutMinutes:s})});var RH=nr.command("queue").description("Queue tests or suites to run on Momentic Cloud");RH.command("suites").description("Run one or more suites on Momentic Cloud").addOption(Pn).addOption(Mn).addOption(UA).addOption(FA).addOption(La).addArgument(xz).addOption(cS).addOption(lS).addOption(aS).action(async(t,e)=>{await Po(le);let{apiKey:r,server:n,wait:o,waitTimeout:i,env:a,urlOverride:s}=e,c=iS(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 Gz({client:l,orgId:u,wait:o,suitePaths:t,waitTimeout:i,env:a,urlOverride:s,customHeaders:c}),await Fi()});RH.command("tests").description("Run one or more tests on Momentic Cloud").addOption(Pn).addOption(Mn).addOption(La).addOption(aS).addOption(GA).addOption(cS).addOption(lS).addOption(new Hr("--all","Run all tests.").default(!1)).addOption(UA).addOption(FA).addArgument(Rz).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=iS(e.customHeaders);for(let h of t)(h.endsWith(".yaml")||Bi.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 QA(a)),await jz({client:p,orgId:m,tests:t,all:r,customHeaders:d,env:o,urlOverride:s,wait:c,waitTimeout:l,testInputMatrix:f,yes:u}),await Fi(),process.exit(0)});var ere=nr.command("list").description("List test paths");ere.addOption(zr).addOption(Na).addOption(zA).addOption(HA).addOption(new Hr("--labels <labels...>","Only run tests with the specified label(s).")).addArgument(VA).action(async(t,e)=>{let r=await Ct({configFilePath:e.config,nameFilter:e.filter}),n=await fe(r),o=await qc({tests:t,momenticFiles:n,yes:!0,project:r,include:e.include,exclude:e.exclude,labels:e.labels,logger:new us(40,{})});v.info(o.map(i=>i.relativeFilePath).join(`
|
|
5590
5590
|
`)),process.exit(0)});var tre=nr.command("run").alias("test").description("Run tests on the local machine");tre.addOption(Pn).addOption(Mn).addOption(zr).addOption(Na).addOption(La).addOption(aS).addOption(GA).addOption(jA).addOption(uS).addOption(dS).addOption(Tz).addOption(Cz).addOption(bz).addOption(vz).addOption(Az).addOption(lS).addOption(cS).addOption(sS).addOption(new Hr("--start <start>","Arbitrary setup command that will run before Momentic steps begin.")).addOption(new Hr("--wait-on <waitOn>","URL to wait to become accessible before Momentic tests begin.")).addOption(new Hr("--wait-on-proxy <waitOnProxy>","HTTP proxy to use with the --wait-on command. Specify as https://username:pass@domain.com:2345")).addOption(new Hr("--wait-on-timeout <waitOnTimeout>","Max time in seconds to wait for the --wait-on URL to become accessible.").default(60).argParser(In)).addOption(new Hr("--retries <retries>","Number of retries to attempt when running tests locally. Defaults to each test's own retry configuration.").argParser(In)).addOption(new Hr("-p, --parallel <parallel>","The number of tests to run in parallel. Defaults to 1.").argParser(In)).addOption(new Hr("--labels <labels...>","Only run tests with the specified label(s).")).addOption(Pz).addOption(new Hr("--update-golden-files","Update locally stored golden files for steps that this is enabled for.").default(!1)).addOption(fz).addOption(hz).addOption(BA).addOption(gz).addOption(yz).addOption(Sz).addOption(zA).addOption(HA).addOption(Iz).addOption(Oz).addArgument(VA).action(async(t,e)=>{await Po(le);let{disableCache:r,saveCache:n,regenerateCache:o,name:i}=e;ih({disableCache:r,saveCache:n,regenerateCache:o}),gL({shardIndex:e.shardIndex,shardCount:e.shardCount});let a=iS(e.customHeaders),s=await Ct({configFilePath:e.config,nameFilter:e.filter}),c=e.parallel??s.config.parallel??1;TH().length<c*2&&v.warn(`You requested to run tests in parallel ${c} at a time on a machine with ${TH().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 Ip({project:s,fix:!1});u>0?(pc({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 Wh({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=Xte(),b=le.child({cliVersion:en,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 QA(e.inputCsv));let _=e.pixelRatio??TS();bS(_);try{let R=await SH({...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 Fi(),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 Fi(),process.exit(1)}});var rre=nr.command("apply").description("Apply an operation to local resources");rre.command("patch").addOption(Pn).addOption(Mn).addOption(zr).addOption(Na).addOption(La).addOption(new Hr("--from <from>","Name or ID of the patch to apply").makeOptionMandatory()).addOption(new Hr("--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 ez({client:s,test:l,fragment:u,yes:o,entities:c,logger:le}),process.exit(0)});var rC=nr.command("results").description("Merge and upload test results.");rC.command("merge").description("Merge test results files.").addOption(BA).addArgument(_z).action(async(t,e)=>{let{outputDir:r}=e;r||(v.error("Output directory is required."),process.exit(1)),Bi.existsSync(t)||(v.warn("Results path does not exist, skipping merge."),process.exit(0)),Bi.existsSync(r)&&v.warn(`Output directory ${r} already exists, removing before merging...`),oD(le,r,t)});rC.command("upload").description("Upload test results to Momentic cloud.").addOption(Pn).addOption(Mn).addArgument(WA).action(async(t,e)=>{let{apiKey:r,server:n}=e,o=le,i=new pt({baseUrl:n,apiKey:r,logger:o});await Yh({consoleLogger:v,resultsPath:t,client:i}),process.exit(0)});rC.command("view").description("Launch the run viewer to view test results in your current directory.").addOption(new Hr("--port <port>",`Port to run the backend server on. Defaults to ${Gm}.`).argParser(In)).addArgument(WA).addArgument(new qte("<runId>","Run ID to open in the viewer.").argOptional()).action(async(t,e,r)=>{await Po(le),le.setApp("local-run-viewer");let n=bH(import.meta.url),o=pr.dirname(n),i=pr.resolve(o,"..","run-viewer-static");await DA({logger:le,staticDir:i,resultsPath:t,runId:e,port:r.port})});var nC=nr.command("quarantine").description("Manage test quarantines");nC.command("add").description("Add a test to the quarantine. This will prevent it from running.").addOption(Pn).addOption(Mn).addOption(zr).addOption(Na).addOption($A).addArgument(qA).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 Dz({test:t,reason:i,apiClient:c,project:s,logger:a,identity:l})});nC.command("list").description("List quarantined tests.").addOption(Pn).addOption(Mn).addOption(zr).addOption(Na).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 Bz({apiClient:a,project:i})});nC.command("remove").description("Remove a test from the quarantine. This will allow it to run again.").addOption(Pn).addOption(Mn).addOption(zr).addOption(Na).addOption($A).addArgument(qA).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 zz({test:t,reason:i,apiClient:c,project:s,identity:l})});nr.command("upgrade").description("Upgrade your configuration to the latest recommended settings").addOption(zr).addOption(Na).action(async t=>{let e=await Ct({configFilePath:t.config,nameFilter:t.filter});v.info("Updating Momentic version in package.json..."),await yH(),v.info("Updating project configuration..."),EH(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 nre(){AH("Main program started");try{await nr.parseAsync(process.argv),await Fi()}catch(t){let e={};try{e.playwrightVersion=Yte("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 Fi(),process.exit(1)}}Jte.setMaxListeners(25);process.on("warning",t=>{le.warn({err:t},`Node warning received on CLI: ${t.message}`)});AH("CLI parsing setup complete");nre();
|
|
5591
5591
|
//# sourceMappingURL=cli.js.map
|
|
5592
|
-
//# debugId=
|
|
5592
|
+
//# debugId=e8f17de5-e335-58a2-b652-fad7f23ed7c0
|