momentic-mobile 0.0.30 → 0.1.0
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 +99 -60
- package/npm-shrinkwrap.json +120 -14
- package/package.json +3 -1
- package/static/assets/{index-qWlEsKJT.js → index-GA9diIbe.js} +176 -165
- package/static/index.html +1 -1
package/bin/cli.js
CHANGED
|
@@ -1,32 +1,38 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
var Ex=Object.defineProperty;var He=(r,e)=>()=>(r&&(e=r(r=0)),e);var Tx=(r,e)=>{for(var t in e)Ex(r,t,{get:e[t],enumerable:!0})};var oh,ih=He(()=>{"use strict";oh=typeof globalThis=="object"?globalThis:global});var ah=He(()=>{"use strict";ih()});var sh=He(()=>{"use strict";ah()});var Vr,Eu=He(()=>{"use strict";Vr="1.9.0"});function Ax(r){var e=new Set([r]),t=new Set,n=r.match(lh);if(!n)return function(){return!1};var o={major:+n[1],minor:+n[2],patch:+n[3],prerelease:n[4]};if(o.prerelease!=null)return function(c){return c===r};function i(s){return t.add(s),!1}function a(s){return e.add(s),!0}return function(c){if(e.has(c))return!0;if(t.has(c))return!1;var l=c.match(lh);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 lh,ch,uh=He(()=>{"use strict";Eu();lh=/^(\d+)\.(\d+)\.(\d+)(-(.+))?$/;ch=Ax(Vr)});function _o(r,e,t,n){var o;n===void 0&&(n=!1);var i=ki[Ni]=(o=ki[Ni])!==null&&o!==void 0?o:{version:Vr};if(!n&&i[r]){var a=new Error("@opentelemetry/api: Attempted duplicate registration of API: "+r);return t.error(a.stack||a.message),!1}if(i.version!==Vr){var a=new Error("@opentelemetry/api: Registration of version v"+i.version+" for "+r+" does not match previously registered API v"+Vr);return t.error(a.stack||a.message),!1}return i[r]=e,t.debug("@opentelemetry/api: Registered a global for "+r+" v"+Vr+"."),!0}function Wr(r){var e,t,n=(e=ki[Ni])===null||e===void 0?void 0:e.version;if(!(!n||!ch(n)))return(t=ki[Ni])===null||t===void 0?void 0:t[r]}function Mo(r,e){e.debug("@opentelemetry/api: Unregistering a global for "+r+" v"+Vr+".");var t=ki[Ni];t&&delete t[r]}var wx,Ni,ki,Di=He(()=>{"use strict";sh();Eu();uh();wx=Vr.split(".")[0],Ni=Symbol.for("opentelemetry.js.api."+wx),ki=oh});function Ui(r,e,t){var n=Wr("diag");if(n)return t.unshift(e),n[r].apply(n,Cx([],Rx(t),!1))}var Rx,Cx,dh,ph=He(()=>{"use strict";Di();Rx=function(r,e){var t=typeof Symbol=="function"&&r[Symbol.iterator];if(!t)return r;var n=t.call(r),o,i=[],a;try{for(;(e===void 0||e-- >0)&&!(o=n.next()).done;)i.push(o.value)}catch(s){a={error:s}}finally{try{o&&!o.done&&(t=n.return)&&t.call(n)}finally{if(a)throw a.error}}return i},Cx=function(r,e,t){if(t||arguments.length===2)for(var n=0,o=e.length,i;n<o;n++)(i||!(n in e))&&(i||(i=Array.prototype.slice.call(e,0,n)),i[n]=e[n]);return r.concat(i||Array.prototype.slice.call(e))},dh=function(){function r(e){this._namespace=e.namespace||"DiagComponentLogger"}return r.prototype.debug=function(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];return Ui("debug",this._namespace,e)},r.prototype.error=function(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];return Ui("error",this._namespace,e)},r.prototype.info=function(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];return Ui("info",this._namespace,e)},r.prototype.warn=function(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];return Ui("warn",this._namespace,e)},r.prototype.verbose=function(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];return Ui("verbose",this._namespace,e)},r}()});var Ne,bs=He(()=>{"use strict";(function(r){r[r.NONE=0]="NONE",r[r.ERROR=30]="ERROR",r[r.WARN=50]="WARN",r[r.INFO=60]="INFO",r[r.DEBUG=70]="DEBUG",r[r.VERBOSE=80]="VERBOSE",r[r.ALL=9999]="ALL"})(Ne||(Ne={}))});function mh(r,e){r<Ne.NONE?r=Ne.NONE:r>Ne.ALL&&(r=Ne.ALL),e=e||{};function t(n,o){var i=e[n];return typeof i=="function"&&r>=o?i.bind(e):function(){}}return{error:t("error",Ne.ERROR),warn:t("warn",Ne.WARN),info:t("info",Ne.INFO),debug:t("debug",Ne.DEBUG),verbose:t("verbose",Ne.VERBOSE)}}var gh=He(()=>{"use strict";bs()});var xx,_x,Mx,Rr,Fi=He(()=>{"use strict";ph();gh();bs();Di();xx=function(r,e){var t=typeof Symbol=="function"&&r[Symbol.iterator];if(!t)return r;var n=t.call(r),o,i=[],a;try{for(;(e===void 0||e-- >0)&&!(o=n.next()).done;)i.push(o.value)}catch(s){a={error:s}}finally{try{o&&!o.done&&(t=n.return)&&t.call(n)}finally{if(a)throw a.error}}return i},_x=function(r,e,t){if(t||arguments.length===2)for(var n=0,o=e.length,i;n<o;n++)(i||!(n in e))&&(i||(i=Array.prototype.slice.call(e,0,n)),i[n]=e[n]);return r.concat(i||Array.prototype.slice.call(e))},Mx="diag",Rr=function(){function r(){function e(o){return function(){for(var i=[],a=0;a<arguments.length;a++)i[a]=arguments[a];var s=Wr("diag");if(s)return s[o].apply(s,_x([],xx(i),!1))}}var t=this,n=function(o,i){var a,s,c;if(i===void 0&&(i={logLevel:Ne.INFO}),o===t){var l=new Error("Cannot use diag as the logger for itself. Please use a DiagLogger implementation like ConsoleDiagLogger or a custom implementation");return t.error((a=l.stack)!==null&&a!==void 0?a:l.message),!1}typeof i=="number"&&(i={logLevel:i});var u=Wr("diag"),d=mh((s=i.logLevel)!==null&&s!==void 0?s:Ne.INFO,o);if(u&&!i.suppressOverrideMessage){var p=(c=new Error().stack)!==null&&c!==void 0?c:"<failed to generate stacktrace>";u.warn("Current logger will be overwritten from "+p),d.warn("Current logger will overwrite one already registered from "+p)}return _o("diag",d,t,!0)};t.setLogger=n,t.disable=function(){Mo(Mx,t)},t.createComponentLogger=function(o){return new dh(o)},t.verbose=e("verbose"),t.debug=e("debug"),t.info=e("info"),t.warn=e("warn"),t.error=e("error")}return r.instance=function(){return this._instance||(this._instance=new r),this._instance},r}()});var hh,fh=He(()=>{"use strict";hh=Symbol("BaggageEntryMetadata")});function Tu(r){return typeof r!="string"&&(Ix.error("Cannot create baggage metadata from unknown type: "+typeof r),r=""),{__TYPE__:hh,toString:function(){return r}}}var Ix,Sh=He(()=>{"use strict";Fi();fh();Ix=Rr.instance()});function vu(r){return Symbol.for(r)}var Px,Au,wu=He(()=>{"use strict";Px=function(){function r(e){var t=this;t._currentContext=e?new Map(e):new Map,t.getValue=function(n){return t._currentContext.get(n)},t.setValue=function(n,o){var i=new r(t._currentContext);return i._currentContext.set(n,o),i},t.deleteValue=function(n){var o=new r(t._currentContext);return o._currentContext.delete(n),o}}return r}(),Au=new Px});function xu(){return Cu}var Un,Ox,Es,Lx,Nx,kx,Dx,Ru,Ux,Fx,Bx,Cu,zx,Hx,Gx,jx,Vx,Wx,$x,_u=He(()=>{"use strict";Un=function(){var r=function(e,t){return r=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(n,o){n.__proto__=o}||function(n,o){for(var i in o)Object.prototype.hasOwnProperty.call(o,i)&&(n[i]=o[i])},r(e,t)};return function(e,t){if(typeof t!="function"&&t!==null)throw new TypeError("Class extends value "+String(t)+" is not a constructor or null");r(e,t);function n(){this.constructor=e}e.prototype=t===null?Object.create(t):(n.prototype=t.prototype,new n)}}(),Ox=function(){function r(){}return r.prototype.createGauge=function(e,t){return Hx},r.prototype.createHistogram=function(e,t){return Gx},r.prototype.createCounter=function(e,t){return zx},r.prototype.createUpDownCounter=function(e,t){return jx},r.prototype.createObservableGauge=function(e,t){return Wx},r.prototype.createObservableCounter=function(e,t){return Vx},r.prototype.createObservableUpDownCounter=function(e,t){return $x},r.prototype.addBatchObservableCallback=function(e,t){},r.prototype.removeBatchObservableCallback=function(e){},r}(),Es=function(){function r(){}return r}(),Lx=function(r){Un(e,r);function e(){return r!==null&&r.apply(this,arguments)||this}return e.prototype.add=function(t,n){},e}(Es),Nx=function(r){Un(e,r);function e(){return r!==null&&r.apply(this,arguments)||this}return e.prototype.add=function(t,n){},e}(Es),kx=function(r){Un(e,r);function e(){return r!==null&&r.apply(this,arguments)||this}return e.prototype.record=function(t,n){},e}(Es),Dx=function(r){Un(e,r);function e(){return r!==null&&r.apply(this,arguments)||this}return e.prototype.record=function(t,n){},e}(Es),Ru=function(){function r(){}return r.prototype.addCallback=function(e){},r.prototype.removeCallback=function(e){},r}(),Ux=function(r){Un(e,r);function e(){return r!==null&&r.apply(this,arguments)||this}return e}(Ru),Fx=function(r){Un(e,r);function e(){return r!==null&&r.apply(this,arguments)||this}return e}(Ru),Bx=function(r){Un(e,r);function e(){return r!==null&&r.apply(this,arguments)||this}return e}(Ru),Cu=new Ox,zx=new Lx,Hx=new kx,Gx=new Dx,jx=new Nx,Vx=new Ux,Wx=new Fx,$x=new Bx});var Ht,yh=He(()=>{"use strict";(function(r){r[r.INT=0]="INT",r[r.DOUBLE=1]="DOUBLE"})(Ht||(Ht={}))});var qx,Kx,bh,Eh=He(()=>{"use strict";wu();qx=function(r,e){var t=typeof Symbol=="function"&&r[Symbol.iterator];if(!t)return r;var n=t.call(r),o,i=[],a;try{for(;(e===void 0||e-- >0)&&!(o=n.next()).done;)i.push(o.value)}catch(s){a={error:s}}finally{try{o&&!o.done&&(t=n.return)&&t.call(n)}finally{if(a)throw a.error}}return i},Kx=function(r,e,t){if(t||arguments.length===2)for(var n=0,o=e.length,i;n<o;n++)(i||!(n in e))&&(i||(i=Array.prototype.slice.call(e,0,n)),i[n]=e[n]);return r.concat(i||Array.prototype.slice.call(e))},bh=function(){function r(){}return r.prototype.active=function(){return Au},r.prototype.with=function(e,t,n){for(var o=[],i=3;i<arguments.length;i++)o[i-3]=arguments[i];return t.call.apply(t,Kx([n],qx(o),!1))},r.prototype.bind=function(e,t){return t},r.prototype.enable=function(){return this},r.prototype.disable=function(){return this},r}()});var Yx,Xx,Mu,Jx,Th,vh=He(()=>{"use strict";Eh();Di();Fi();Yx=function(r,e){var t=typeof Symbol=="function"&&r[Symbol.iterator];if(!t)return r;var n=t.call(r),o,i=[],a;try{for(;(e===void 0||e-- >0)&&!(o=n.next()).done;)i.push(o.value)}catch(s){a={error:s}}finally{try{o&&!o.done&&(t=n.return)&&t.call(n)}finally{if(a)throw a.error}}return i},Xx=function(r,e,t){if(t||arguments.length===2)for(var n=0,o=e.length,i;n<o;n++)(i||!(n in e))&&(i||(i=Array.prototype.slice.call(e,0,n)),i[n]=e[n]);return r.concat(i||Array.prototype.slice.call(e))},Mu="context",Jx=new bh,Th=function(){function r(){}return r.getInstance=function(){return this._instance||(this._instance=new r),this._instance},r.prototype.setGlobalContextManager=function(e){return _o(Mu,e,Rr.instance())},r.prototype.active=function(){return this._getContextManager().active()},r.prototype.with=function(e,t,n){for(var o,i=[],a=3;a<arguments.length;a++)i[a-3]=arguments[a];return(o=this._getContextManager()).with.apply(o,Xx([e,t,n],Yx(i),!1))},r.prototype.bind=function(e,t){return this._getContextManager().bind(e,t)},r.prototype._getContextManager=function(){return Wr(Mu)||Jx},r.prototype.disable=function(){this._getContextManager().disable(),Mo(Mu,Rr.instance())},r}()});var Io,Ah=He(()=>{"use strict";vh();Io=Th.getInstance()});var W,wh=He(()=>{"use strict";Fi();W=Rr.instance()});var Zx,Rh,Ch=He(()=>{"use strict";_u();Zx=function(){function r(){}return r.prototype.getMeter=function(e,t,n){return Cu},r}(),Rh=new Zx});var Iu,xh,_h=He(()=>{"use strict";Ch();Di();Fi();Iu="metrics",xh=function(){function r(){}return r.getInstance=function(){return this._instance||(this._instance=new r),this._instance},r.prototype.setGlobalMeterProvider=function(e){return _o(Iu,e,Rr.instance())},r.prototype.getMeterProvider=function(){return Wr(Iu)||Rh},r.prototype.getMeter=function(e,t,n){return this.getMeterProvider().getMeter(e,t,n)},r.prototype.disable=function(){Mo(Iu,Rr.instance())},r}()});var Ts,Mh=He(()=>{"use strict";_h();Ts=xh.getInstance()});var Ce=He(()=>{"use strict";Sh();wu();bs();_u();yh();Ah();wh();Mh()});import{Argument as nh,Command as sG,Option as lG}from"@commander-js/extra-typings";import GI from"appium";import{tmpdir as jI}from"os";import{remote as VI}from"webdriverio";import{createInstanceClient as FI}from"@limrun/api";import{execSync as BI}from"child_process";var Ss=class{increment(e,t,n){}gauge(e,t){}distribution(e,t,n){}async flush(){}async recordDuration({fn:e}){return await e()}};function vx(r){if(!r||r.length===0)return{};let e={};for(let t of r){let n=t.indexOf(":");if(n>-1){let o=t.slice(0,n).trim(),i=t.slice(n+1).trim();o&&(e[o]=i);continue}e[t]=!0}return e}function ys(r,e){let t=vx(r);return!e||Object.keys(e).length===0?t:{...e,...t}}var Ih="=",vs=";",Pu=",";var Ph=8192;var Po={};Tx(Po,{getKeyPairs:()=>t_,parseKeyPairsIntoRecord:()=>r_,parsePairKeyValue:()=>Oh,serializeKeyPairs:()=>e_});Ce();var Qx=function(r,e){var t=typeof Symbol=="function"&&r[Symbol.iterator];if(!t)return r;var n=t.call(r),o,i=[],a;try{for(;(e===void 0||e-- >0)&&!(o=n.next()).done;)i.push(o.value)}catch(s){a={error:s}}finally{try{o&&!o.done&&(t=n.return)&&t.call(n)}finally{if(a)throw a.error}}return i};function e_(r){return r.reduce(function(e,t){var n=""+e+(e!==""?Pu:"")+t;return n.length>Ph?e:n},"")}function t_(r){return r.getAllEntries().map(function(e){var t=Qx(e,2),n=t[0],o=t[1],i=encodeURIComponent(n)+"="+encodeURIComponent(o.value);return o.metadata!==void 0&&(i+=vs+o.metadata.toString()),i})}function Oh(r){var e=r.split(vs);if(!(e.length<=0)){var t=e.shift();if(t){var n=t.indexOf(Ih);if(!(n<=0)){var o=decodeURIComponent(t.substring(0,n).trim()),i=decodeURIComponent(t.substring(n+1).trim()),a;return e.length>0&&(a=Tu(e.join(vs))),{key:o,value:i,metadata:a}}}}}function r_(r){return typeof r!="string"||r.length===0?{}:r.split(Pu).map(function(e){return Oh(e)}).filter(function(e){return e!==void 0&&e.value.length>0}).reduce(function(e,t){return e[t.key]=t.value,e},{})}Ce();var As;(function(r){r.AlwaysOff="always_off",r.AlwaysOn="always_on",r.ParentBasedAlwaysOff="parentbased_always_off",r.ParentBasedAlwaysOn="parentbased_always_on",r.ParentBasedTraceIdRatio="parentbased_traceidratio",r.TraceIdRatio="traceidratio"})(As||(As={}));var n_=",",o_=["OTEL_SDK_DISABLED"];function i_(r){return o_.indexOf(r)>-1}var a_=["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 s_(r){return a_.indexOf(r)>-1}var l_=["OTEL_NO_PATCH_MODULES","OTEL_PROPAGATORS"];function c_(r){return l_.indexOf(r)>-1}var Ou=1/0,Lu=128,u_=128,d_=128,Nu={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:Ne.INFO,OTEL_NO_PATCH_MODULES:[],OTEL_PROPAGATORS:["tracecontext","baggage"],OTEL_RESOURCE_ATTRIBUTES:"",OTEL_SERVICE_NAME:"",OTEL_ATTRIBUTE_VALUE_LENGTH_LIMIT:Ou,OTEL_ATTRIBUTE_COUNT_LIMIT:Lu,OTEL_SPAN_ATTRIBUTE_VALUE_LENGTH_LIMIT:Ou,OTEL_SPAN_ATTRIBUTE_COUNT_LIMIT:Lu,OTEL_LOGRECORD_ATTRIBUTE_VALUE_LENGTH_LIMIT:Ou,OTEL_LOGRECORD_ATTRIBUTE_COUNT_LIMIT:Lu,OTEL_SPAN_EVENT_COUNT_LIMIT:128,OTEL_SPAN_LINK_COUNT_LIMIT:128,OTEL_SPAN_ATTRIBUTE_PER_EVENT_COUNT_LIMIT:u_,OTEL_SPAN_ATTRIBUTE_PER_LINK_COUNT_LIMIT:d_,OTEL_TRACES_EXPORTER:"",OTEL_TRACES_SAMPLER:As.ParentBasedAlwaysOn,OTEL_TRACES_SAMPLER_ARG:"",OTEL_LOGS_EXPORTER:"",OTEL_EXPORTER_OTLP_INSECURE:"",OTEL_EXPORTER_OTLP_TRACES_INSECURE:"",OTEL_EXPORTER_OTLP_METRICS_INSECURE:"",OTEL_EXPORTER_OTLP_LOGS_INSECURE:"",OTEL_EXPORTER_OTLP_CERTIFICATE:"",OTEL_EXPORTER_OTLP_TRACES_CERTIFICATE:"",OTEL_EXPORTER_OTLP_METRICS_CERTIFICATE:"",OTEL_EXPORTER_OTLP_LOGS_CERTIFICATE:"",OTEL_EXPORTER_OTLP_COMPRESSION:"",OTEL_EXPORTER_OTLP_TRACES_COMPRESSION:"",OTEL_EXPORTER_OTLP_METRICS_COMPRESSION:"",OTEL_EXPORTER_OTLP_LOGS_COMPRESSION:"",OTEL_EXPORTER_OTLP_CLIENT_KEY:"",OTEL_EXPORTER_OTLP_TRACES_CLIENT_KEY:"",OTEL_EXPORTER_OTLP_METRICS_CLIENT_KEY:"",OTEL_EXPORTER_OTLP_LOGS_CLIENT_KEY:"",OTEL_EXPORTER_OTLP_CLIENT_CERTIFICATE:"",OTEL_EXPORTER_OTLP_TRACES_CLIENT_CERTIFICATE:"",OTEL_EXPORTER_OTLP_METRICS_CLIENT_CERTIFICATE:"",OTEL_EXPORTER_OTLP_LOGS_CLIENT_CERTIFICATE:"",OTEL_EXPORTER_OTLP_PROTOCOL:"http/protobuf",OTEL_EXPORTER_OTLP_TRACES_PROTOCOL:"http/protobuf",OTEL_EXPORTER_OTLP_METRICS_PROTOCOL:"http/protobuf",OTEL_EXPORTER_OTLP_LOGS_PROTOCOL:"http/protobuf",OTEL_EXPORTER_OTLP_METRICS_TEMPORALITY_PREFERENCE:"cumulative"};function p_(r,e,t){if(!(typeof t[r]>"u")){var n=String(t[r]);e[r]=n.toLowerCase()==="true"}}function m_(r,e,t,n,o){if(n===void 0&&(n=-1/0),o===void 0&&(o=1/0),typeof t[r]<"u"){var i=Number(t[r]);isNaN(i)||(i<n?e[r]=n:i>o?e[r]=o:e[r]=i)}}function g_(r,e,t,n){n===void 0&&(n=n_);var o=t[r];typeof o=="string"&&(e[r]=o.split(n).map(function(i){return i.trim()}))}var h_={ALL:Ne.ALL,VERBOSE:Ne.VERBOSE,DEBUG:Ne.DEBUG,INFO:Ne.INFO,WARN:Ne.WARN,ERROR:Ne.ERROR,NONE:Ne.NONE};function f_(r,e,t){var n=t[r];if(typeof n=="string"){var o=h_[n.toUpperCase()];o!=null&&(e[r]=o)}}function Lh(r){var e={};for(var t in Nu){var n=t;switch(n){case"OTEL_LOG_LEVEL":f_(n,e,r);break;default:if(i_(n))p_(n,e,r);else if(s_(n))m_(n,e,r);else if(c_(n))g_(n,e,r);else{var o=r[n];typeof o<"u"&&o!==null&&(e[n]=String(o))}}}return e}function mt(){var r=Lh(process.env);return Object.assign({},Nu,r)}function Nh(r){return r>=48&&r<=57?r-48:r>=97&&r<=102?r-87:r-55}function ws(r){for(var e=new Uint8Array(r.length/2),t=0,n=0;n<r.length;n+=2){var o=Nh(r.charCodeAt(n)),i=Nh(r.charCodeAt(n+1));e[t++]=o<<4|i}return e}var kh="1.25.1";var S_="deployment.environment";var y_="process.runtime.name";var b_="service.name";var E_="service.instance.id";var T_="telemetry.sdk.name",v_="telemetry.sdk.language",A_="telemetry.sdk.version";var Dh=S_;var Uh=y_;var Rs=b_;var Fh=E_;var zi=T_,Hi=v_,Gi=A_;var w_="nodejs";var Bh=w_;var Oo,Cs=(Oo={},Oo[zi]="opentelemetry",Oo[Uh]="node",Oo[Hi]=Bh,Oo[Gi]=kh,Oo);var R_=9,C_=6,x_=Math.pow(10,C_),__=Math.pow(10,R_);function zh(r){var e=r/1e3,t=Math.trunc(e),n=Math.round(r%1e3*x_);return[t,n]}function Hh(r){return r[0]*__+r[1]}function ji(r){return r[0]*1e6+r[1]/1e3}var Fn;(function(r){r[r.SUCCESS=0]="SUCCESS",r[r.FAILED=1]="FAILED"})(Fn||(Fn={}));var Gh=function(){function r(){var e=this;this._promise=new Promise(function(t,n){e._resolve=t,e._reject=n})}return Object.defineProperty(r.prototype,"promise",{get:function(){return this._promise},enumerable:!1,configurable:!0}),r.prototype.resolve=function(e){this._resolve(e)},r.prototype.reject=function(e){this._reject(e)},r}();var M_=function(r,e){var t=typeof Symbol=="function"&&r[Symbol.iterator];if(!t)return r;var n=t.call(r),o,i=[],a;try{for(;(e===void 0||e-- >0)&&!(o=n.next()).done;)i.push(o.value)}catch(s){a={error:s}}finally{try{o&&!o.done&&(t=n.return)&&t.call(n)}finally{if(a)throw a.error}}return i},I_=function(r,e,t){if(t||arguments.length===2)for(var n=0,o=e.length,i;n<o;n++)(i||!(n in e))&&(i||(i=Array.prototype.slice.call(e,0,n)),i[n]=e[n]);return r.concat(i||Array.prototype.slice.call(e))},jh=function(){function r(e,t){this._callback=e,this._that=t,this._isCalled=!1,this._deferred=new Gh}return Object.defineProperty(r.prototype,"isCalled",{get:function(){return this._isCalled},enumerable:!1,configurable:!0}),Object.defineProperty(r.prototype,"promise",{get:function(){return this._deferred.promise},enumerable:!1,configurable:!0}),r.prototype.call=function(){for(var e,t=this,n=[],o=0;o<arguments.length;o++)n[o]=arguments[o];if(!this._isCalled){this._isCalled=!0;try{Promise.resolve((e=this._callback).call.apply(e,I_([this._that],M_(n),!1))).then(function(i){return t._deferred.resolve(i)},function(i){return t._deferred.reject(i)})}catch(i){this._deferred.reject(i)}}return this._deferred.promise},r}();var qt;(function(r){r[r.DELTA=0]="DELTA",r[r.CUMULATIVE=1]="CUMULATIVE"})(qt||(qt={}));var ft;(function(r){r[r.HISTOGRAM=0]="HISTOGRAM",r[r.EXPONENTIAL_HISTOGRAM=1]="EXPONENTIAL_HISTOGRAM",r[r.GAUGE=2]="GAUGE",r[r.SUM=3]="SUM"})(ft||(ft={}));var P_=function(){var r=function(e,t){return r=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(n,o){n.__proto__=o}||function(n,o){for(var i in o)Object.prototype.hasOwnProperty.call(o,i)&&(n[i]=o[i])},r(e,t)};return function(e,t){if(typeof t!="function"&&t!==null)throw new TypeError("Class extends value "+String(t)+" is not a constructor or null");r(e,t);function n(){this.constructor=e}e.prototype=t===null?Object.create(t):(n.prototype=t.prototype,new n)}}();var RV=function(r){P_(e,r);function e(t){var n=r.call(this,t)||this;return Object.setPrototypeOf(n,e.prototype),n}return e}(Error);function Vh(r,e){for(var t=0,n=r.length-1;n-t>1;){var o=Math.trunc((n+t)/2);r[o]<=e?t=o:n=o-1}return r[n]<=e?n:r[t]<=e?t:-1}Ce();var Kt;(function(r){r[r.DROP=0]="DROP",r[r.SUM=1]="SUM",r[r.LAST_VALUE=2]="LAST_VALUE",r[r.HISTOGRAM=3]="HISTOGRAM",r[r.EXPONENTIAL_HISTOGRAM=4]="EXPONENTIAL_HISTOGRAM"})(Kt||(Kt={}));var Wh=function(){function r(){this.kind=Kt.DROP}return r.prototype.createAccumulation=function(){},r.prototype.merge=function(e,t){},r.prototype.diff=function(e,t){},r.prototype.toMetricData=function(e,t,n,o){},r}();var ie;(function(r){r.COUNTER="COUNTER",r.GAUGE="GAUGE",r.HISTOGRAM="HISTOGRAM",r.UP_DOWN_COUNTER="UP_DOWN_COUNTER",r.OBSERVABLE_COUNTER="OBSERVABLE_COUNTER",r.OBSERVABLE_GAUGE="OBSERVABLE_GAUGE",r.OBSERVABLE_UP_DOWN_COUNTER="OBSERVABLE_UP_DOWN_COUNTER"})(ie||(ie={}));var O_=function(r,e){var t=typeof Symbol=="function"&&r[Symbol.iterator];if(!t)return r;var n=t.call(r),o,i=[],a;try{for(;(e===void 0||e-- >0)&&!(o=n.next()).done;)i.push(o.value)}catch(s){a={error:s}}finally{try{o&&!o.done&&(t=n.return)&&t.call(n)}finally{if(a)throw a.error}}return i};function L_(r){var e=r.map(function(){return 0});return e.push(0),{buckets:{boundaries:r,counts:e},sum:0,count:0,hasMinMax:!1,min:1/0,max:-1/0}}var ku=function(){function r(e,t,n,o){n===void 0&&(n=!0),o===void 0&&(o=L_(t)),this.startTime=e,this._boundaries=t,this._recordMinMax=n,this._current=o}return r.prototype.record=function(e){if(!Number.isNaN(e)){this._current.count+=1,this._current.sum+=e,this._recordMinMax&&(this._current.min=Math.min(e,this._current.min),this._current.max=Math.max(e,this._current.max),this._current.hasMinMax=!0);var t=Vh(this._boundaries,e);this._current.buckets.counts[t+1]+=1}},r.prototype.setStartTime=function(e){this.startTime=e},r.prototype.toPointValue=function(){return this._current},r}();var Du=function(){function r(e,t){this._boundaries=e,this._recordMinMax=t,this.kind=Kt.HISTOGRAM}return r.prototype.createAccumulation=function(e){return new ku(e,this._boundaries,this._recordMinMax)},r.prototype.merge=function(e,t){for(var n=e.toPointValue(),o=t.toPointValue(),i=n.buckets.counts,a=o.buckets.counts,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 ku(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})},r.prototype.diff=function(e,t){for(var n=e.toPointValue(),o=t.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 ku(t.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})},r.prototype.toMetricData=function(e,t,n,o){return{descriptor:e,aggregationTemporality:t,dataPointType:ft.HISTOGRAM,dataPoints:n.map(function(i){var a=O_(i,2),s=a[0],c=a[1],l=c.toPointValue(),u=e.type===ie.GAUGE||e.type===ie.UP_DOWN_COUNTER||e.type===ie.OBSERVABLE_GAUGE||e.type===ie.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}}})}},r}();Ce();var Uu=function(r,e){var t=typeof Symbol=="function"&&r[Symbol.iterator];if(!t)return r;var n=t.call(r),o,i=[],a;try{for(;(e===void 0||e-- >0)&&!(o=n.next()).done;)i.push(o.value)}catch(s){a={error:s}}finally{try{o&&!o.done&&(t=n.return)&&t.call(n)}finally{if(a)throw a.error}}return i},Fu=function(r,e,t){if(t||arguments.length===2)for(var n=0,o=e.length,i;n<o;n++)(i||!(n in e))&&(i||(i=Array.prototype.slice.call(e,0,n)),i[n]=e[n]);return r.concat(i||Array.prototype.slice.call(e))},Bu=function(){function r(e,t,n,o){e===void 0&&(e=new N_),t===void 0&&(t=0),n===void 0&&(n=0),o===void 0&&(o=0),this.backing=e,this.indexBase=t,this.indexStart=n,this.indexEnd=o}return Object.defineProperty(r.prototype,"offset",{get:function(){return this.indexStart},enumerable:!1,configurable:!0}),Object.defineProperty(r.prototype,"length",{get:function(){return this.backing.length===0||this.indexEnd===this.indexStart&&this.at(0)===0?0:this.indexEnd-this.indexStart+1},enumerable:!1,configurable:!0}),r.prototype.counts=function(){var e=this;return Array.from({length:this.length},function(t,n){return e.at(n)})},r.prototype.at=function(e){var t=this.indexBase-this.indexStart;return e<t&&(e+=this.backing.length),e-=t,this.backing.countAt(e)},r.prototype.incrementBucket=function(e,t){this.backing.increment(e,t)},r.prototype.decrementBucket=function(e,t){this.backing.decrement(e,t)},r.prototype.trim=function(){for(var e=0;e<this.length;e++)if(this.at(e)!==0){this.indexStart+=e;break}else if(e===this.length-1){this.indexStart=this.indexEnd=this.indexBase=0;return}for(var e=this.length-1;e>=0;e--)if(this.at(e)!==0){this.indexEnd-=this.length-e-1;break}this._rotate()},r.prototype.downscale=function(e){this._rotate();for(var t=1+this.indexEnd-this.indexStart,n=1<<e,o=0,i=0,a=this.indexStart;a<=this.indexEnd;){var s=a%n;s<0&&(s+=n);for(var c=s;c<n&&o<t;c++)this._relocateBucket(i,o),o++,a++;i++}this.indexStart>>=e,this.indexEnd>>=e,this.indexBase=this.indexStart},r.prototype.clone=function(){return new r(this.backing.clone(),this.indexBase,this.indexStart,this.indexEnd)},r.prototype._rotate=function(){var e=this.indexBase-this.indexStart;e!==0&&(e>0?(this.backing.reverse(0,this.backing.length),this.backing.reverse(0,e),this.backing.reverse(e,this.backing.length)):(this.backing.reverse(0,this.backing.length),this.backing.reverse(0,this.backing.length+e)),this.indexBase=this.indexStart)},r.prototype._relocateBucket=function(e,t){e!==t&&this.incrementBucket(e,this.backing.emptyBucket(t))},r}();var N_=function(){function r(e){e===void 0&&(e=[0]),this._counts=e}return Object.defineProperty(r.prototype,"length",{get:function(){return this._counts.length},enumerable:!1,configurable:!0}),r.prototype.countAt=function(e){return this._counts[e]},r.prototype.growTo=function(e,t,n){var o=new Array(e).fill(0);o.splice.apply(o,Fu([n,this._counts.length-t],Uu(this._counts.slice(t)),!1)),o.splice.apply(o,Fu([0,t],Uu(this._counts.slice(0,t)),!1)),this._counts=o},r.prototype.reverse=function(e,t){for(var n=Math.floor((e+t)/2)-e,o=0;o<n;o++){var i=this._counts[e+o];this._counts[e+o]=this._counts[t-o-1],this._counts[t-o-1]=i}},r.prototype.emptyBucket=function(e){var t=this._counts[e];return this._counts[e]=0,t},r.prototype.increment=function(e,t){this._counts[e]+=t},r.prototype.decrement=function(e,t){this._counts[e]>=t?this._counts[e]-=t:this._counts[e]=0},r.prototype.clone=function(){return new r(Fu([],Uu(this._counts),!1))},r}();var $h=52,k_=2146435072,D_=1048575,zu=1023,xs=-zu+1,_s=zu,Vi=Math.pow(2,-1022);function Ms(r){var e=new DataView(new ArrayBuffer(8));e.setFloat64(0,r);var t=e.getUint32(0),n=(t&k_)>>20;return n-zu}function Is(r){var e=new DataView(new ArrayBuffer(8));e.setFloat64(0,r);var t=e.getUint32(0),n=e.getUint32(4),o=(t&D_)*Math.pow(2,32);return o+n}function Wi(r,e){return r===0||r===Number.POSITIVE_INFINITY||r===Number.NEGATIVE_INFINITY||Number.isNaN(r)?r:r*Math.pow(2,e)}function Kh(r){return r--,r|=r>>1,r|=r>>2,r|=r>>4,r|=r>>8,r|=r>>16,r++,r}var U_=function(){var r=function(e,t){return r=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(n,o){n.__proto__=o}||function(n,o){for(var i in o)Object.prototype.hasOwnProperty.call(o,i)&&(n[i]=o[i])},r(e,t)};return function(e,t){if(typeof t!="function"&&t!==null)throw new TypeError("Class extends value "+String(t)+" is not a constructor or null");r(e,t);function n(){this.constructor=e}e.prototype=t===null?Object.create(t):(n.prototype=t.prototype,new n)}}(),nn=function(r){U_(e,r);function e(){return r!==null&&r.apply(this,arguments)||this}return e}(Error);var Xh=function(){function r(e){this._shift=-e}return r.prototype.mapToIndex=function(e){if(e<Vi)return this._minNormalLowerBoundaryIndex();var t=Ms(e),n=this._rightShift(Is(e)-1,$h);return t+n>>this._shift},r.prototype.lowerBoundary=function(e){var t=this._minNormalLowerBoundaryIndex();if(e<t)throw new nn("underflow: "+e+" is < minimum lower boundary: "+t);var n=this._maxNormalLowerBoundaryIndex();if(e>n)throw new nn("overflow: "+e+" is > maximum lower boundary: "+n);return Wi(1,e<<this._shift)},Object.defineProperty(r.prototype,"scale",{get:function(){return this._shift===0?0:-this._shift},enumerable:!1,configurable:!0}),r.prototype._minNormalLowerBoundaryIndex=function(){var e=xs>>this._shift;return this._shift<2&&e--,e},r.prototype._maxNormalLowerBoundaryIndex=function(){return _s>>this._shift},r.prototype._rightShift=function(e,t){return Math.floor(e*Math.pow(2,-t))},r}();var Jh=function(){function r(e){this._scale=e,this._scaleFactor=Wi(Math.LOG2E,e),this._inverseFactor=Wi(Math.LN2,-e)}return r.prototype.mapToIndex=function(e){if(e<=Vi)return this._minNormalLowerBoundaryIndex()-1;if(Is(e)===0){var t=Ms(e);return(t<<this._scale)-1}var n=Math.floor(Math.log(e)*this._scaleFactor),o=this._maxNormalLowerBoundaryIndex();return n>=o?o:n},r.prototype.lowerBoundary=function(e){var t=this._maxNormalLowerBoundaryIndex();if(e>=t){if(e===t)return 2*Math.exp((e-(1<<this._scale))/this._scaleFactor);throw new nn("overflow: "+e+" is > maximum lower boundary: "+t)}var n=this._minNormalLowerBoundaryIndex();if(e<=n){if(e===n)return Vi;if(e===n-1)return Math.exp((e+(1<<this._scale))/this._scaleFactor)/2;throw new nn("overflow: "+e+" is < minimum lower boundary: "+n)}return Math.exp(e*this._inverseFactor)},Object.defineProperty(r.prototype,"scale",{get:function(){return this._scale},enumerable:!1,configurable:!0}),r.prototype._minNormalLowerBoundaryIndex=function(){return xs<<this._scale},r.prototype._maxNormalLowerBoundaryIndex=function(){return(_s+1<<this._scale)-1},r}();var Zh=-10,Qh=20,F_=Array.from({length:31},function(r,e){return e>10?new Jh(e-10):new Xh(e-10)});function Hu(r){if(r>Qh||r<Zh)throw new nn("expected scale >= "+Zh+" && <= "+Qh+", got: "+r);return F_[r+10]}var B_=function(r,e){var t=typeof Symbol=="function"&&r[Symbol.iterator];if(!t)return r;var n=t.call(r),o,i=[],a;try{for(;(e===void 0||e-- >0)&&!(o=n.next()).done;)i.push(o.value)}catch(s){a={error:s}}finally{try{o&&!o.done&&(t=n.return)&&t.call(n)}finally{if(a)throw a.error}}return i},Ps=function(){function r(e,t){this.low=e,this.high=t}return r.combine=function(e,t){return new r(Math.min(e.low,t.low),Math.max(e.high,t.high))},r}(),z_=20,H_=160,Gu=2,G_=function(){function r(e,t,n,o,i,a,s,c,l,u,d){e===void 0&&(e=e),t===void 0&&(t=H_),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 Bu),u===void 0&&(u=new Bu),d===void 0&&(d=Hu(z_)),this.startTime=e,this._maxSize=t,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<Gu&&(W.warn("Exponential Histogram Max Size set to "+this._maxSize+", changing to the minimum size of: "+Gu),this._maxSize=Gu)}return r.prototype.record=function(e){this.updateByIncrement(e,1)},r.prototype.setStartTime=function(e){this.startTime=e},r.prototype.toPointValue=function(){return{hasMinMax:this._recordMinMax,min:this.min,max:this.max,sum:this.sum,positive:{offset:this.positive.offset,bucketCounts:this.positive.counts()},negative:{offset:this.negative.offset,bucketCounts:this.negative.counts()},count:this.count,scale:this.scale,zeroCount:this.zeroCount}},Object.defineProperty(r.prototype,"sum",{get:function(){return this._sum},enumerable:!1,configurable:!0}),Object.defineProperty(r.prototype,"min",{get:function(){return this._min},enumerable:!1,configurable:!0}),Object.defineProperty(r.prototype,"max",{get:function(){return this._max},enumerable:!1,configurable:!0}),Object.defineProperty(r.prototype,"count",{get:function(){return this._count},enumerable:!1,configurable:!0}),Object.defineProperty(r.prototype,"zeroCount",{get:function(){return this._zeroCount},enumerable:!1,configurable:!0}),Object.defineProperty(r.prototype,"scale",{get:function(){return this._count===this._zeroCount?0:this._mapping.scale},enumerable:!1,configurable:!0}),Object.defineProperty(r.prototype,"positive",{get:function(){return this._positive},enumerable:!1,configurable:!0}),Object.defineProperty(r.prototype,"negative",{get:function(){return this._negative},enumerable:!1,configurable:!0}),r.prototype.updateByIncrement=function(e,t){if(!Number.isNaN(e)){if(e>this._max&&(this._max=e),e<this._min&&(this._min=e),this._count+=t,e===0){this._zeroCount+=t;return}this._sum+=e*t,e>0?this._updateBuckets(this._positive,e,t):this._updateBuckets(this._negative,-e,t)}},r.prototype.merge=function(e){this._count===0?(this._min=e.min,this._max=e.max):e.count!==0&&(e.min<this.min&&(this._min=e.min),e.max>this.max&&(this._max=e.max)),this.startTime=e.startTime,this._sum+=e.sum,this._count+=e.count,this._zeroCount+=e.zeroCount;var t=this._minScale(e);this._downscale(this.scale-t),this._mergeBuckets(this.positive,e,e.positive,t),this._mergeBuckets(this.negative,e,e.negative,t)},r.prototype.diff=function(e){this._min=1/0,this._max=-1/0,this._sum-=e.sum,this._count-=e.count,this._zeroCount-=e.zeroCount;var t=this._minScale(e);this._downscale(this.scale-t),this._diffBuckets(this.positive,e,e.positive,t),this._diffBuckets(this.negative,e,e.negative,t)},r.prototype.clone=function(){return new r(this.startTime,this._maxSize,this._recordMinMax,this._sum,this._count,this._zeroCount,this._min,this._max,this.positive.clone(),this.negative.clone(),this._mapping)},r.prototype._updateBuckets=function(e,t,n){var o=this._mapping.mapToIndex(t),i=!1,a=0,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(t)}this._incrementIndexBy(e,o,n)},r.prototype._incrementIndexBy=function(e,t,n){if(n!==0){if(e.length===0&&(e.indexStart=e.indexEnd=e.indexBase=t),t<e.indexStart){var o=e.indexEnd-t;o>=e.backing.length&&this._grow(e,o+1),e.indexStart=t}else if(t>e.indexEnd){var o=t-e.indexStart;o>=e.backing.length&&this._grow(e,o+1),e.indexEnd=t}var i=t-e.indexBase;i<0&&(i+=e.backing.length),e.incrementBucket(i,n)}},r.prototype._grow=function(e,t){var n=e.backing.length,o=e.indexBase-e.indexStart,i=n-o,a=Kh(t);a>this._maxSize&&(a=this._maxSize);var s=a-o;e.backing.growTo(a,i,s)},r.prototype._changeScale=function(e,t){for(var n=0;e-t>=this._maxSize;)e>>=1,t>>=1,n++;return n},r.prototype._downscale=function(e){if(e!==0){if(e<0)throw new Error("impossible change of scale: "+this.scale);var t=this._mapping.scale-e;this._positive.downscale(e),this._negative.downscale(e),this._mapping=Hu(t)}},r.prototype._minScale=function(e){var t=Math.min(this.scale,e.scale),n=Ps.combine(this._highLowAtScale(this.positive,this.scale,t),this._highLowAtScale(e.positive,e.scale,t)),o=Ps.combine(this._highLowAtScale(this.negative,this.scale,t),this._highLowAtScale(e.negative,e.scale,t));return Math.min(t-this._changeScale(n.high,n.low),t-this._changeScale(o.high,o.low))},r.prototype._highLowAtScale=function(e,t,n){if(e.length===0)return new Ps(0,-1);var o=t-n;return new Ps(e.indexStart>>o,e.indexEnd>>o)},r.prototype._mergeBuckets=function(e,t,n,o){for(var i=n.offset,a=t.scale-o,s=0;s<n.length;s++)this._incrementIndexBy(e,i+s>>a,n.at(s))},r.prototype._diffBuckets=function(e,t,n,o){for(var i=n.offset,a=t.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()},r}();var ef=function(){function r(e,t){this._maxSize=e,this._recordMinMax=t,this.kind=Kt.EXPONENTIAL_HISTOGRAM}return r.prototype.createAccumulation=function(e){return new G_(e,this._maxSize,this._recordMinMax)},r.prototype.merge=function(e,t){var n=t.clone();return n.merge(e),n},r.prototype.diff=function(e,t){var n=t.clone();return n.diff(e),n},r.prototype.toMetricData=function(e,t,n,o){return{descriptor:e,aggregationTemporality:t,dataPointType:ft.EXPONENTIAL_HISTOGRAM,dataPoints:n.map(function(i){var a=B_(i,2),s=a[0],c=a[1],l=c.toPointValue(),u=e.type===ie.GAUGE||e.type===ie.UP_DOWN_COUNTER||e.type===ie.OBSERVABLE_GAUGE||e.type===ie.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}}})}},r}();var j_=function(r,e){var t=typeof Symbol=="function"&&r[Symbol.iterator];if(!t)return r;var n=t.call(r),o,i=[],a;try{for(;(e===void 0||e-- >0)&&!(o=n.next()).done;)i.push(o.value)}catch(s){a={error:s}}finally{try{o&&!o.done&&(t=n.return)&&t.call(n)}finally{if(a)throw a.error}}return i},ju=function(){function r(e,t,n){t===void 0&&(t=0),n===void 0&&(n=[0,0]),this.startTime=e,this._current=t,this.sampleTime=n}return r.prototype.record=function(e){this._current=e,this.sampleTime=zh(Date.now())},r.prototype.setStartTime=function(e){this.startTime=e},r.prototype.toPointValue=function(){return this._current},r}();var tf=function(){function r(){this.kind=Kt.LAST_VALUE}return r.prototype.createAccumulation=function(e){return new ju(e)},r.prototype.merge=function(e,t){var n=ji(t.sampleTime)>=ji(e.sampleTime)?t:e;return new ju(e.startTime,n.toPointValue(),n.sampleTime)},r.prototype.diff=function(e,t){var n=ji(t.sampleTime)>=ji(e.sampleTime)?t:e;return new ju(t.startTime,n.toPointValue(),n.sampleTime)},r.prototype.toMetricData=function(e,t,n,o){return{descriptor:e,aggregationTemporality:t,dataPointType:ft.GAUGE,dataPoints:n.map(function(i){var a=j_(i,2),s=a[0],c=a[1];return{attributes:s,startTime:c.startTime,endTime:o,value:c.toPointValue()}})}},r}();var V_=function(r,e){var t=typeof Symbol=="function"&&r[Symbol.iterator];if(!t)return r;var n=t.call(r),o,i=[],a;try{for(;(e===void 0||e-- >0)&&!(o=n.next()).done;)i.push(o.value)}catch(s){a={error:s}}finally{try{o&&!o.done&&(t=n.return)&&t.call(n)}finally{if(a)throw a.error}}return i},$i=function(){function r(e,t,n,o){n===void 0&&(n=0),o===void 0&&(o=!1),this.startTime=e,this.monotonic=t,this._current=n,this.reset=o}return r.prototype.record=function(e){this.monotonic&&e<0||(this._current+=e)},r.prototype.setStartTime=function(e){this.startTime=e},r.prototype.toPointValue=function(){return this._current},r}();var Vu=function(){function r(e){this.monotonic=e,this.kind=Kt.SUM}return r.prototype.createAccumulation=function(e){return new $i(e,this.monotonic)},r.prototype.merge=function(e,t){var n=e.toPointValue(),o=t.toPointValue();return t.reset?new $i(t.startTime,this.monotonic,o,t.reset):new $i(e.startTime,this.monotonic,n+o)},r.prototype.diff=function(e,t){var n=e.toPointValue(),o=t.toPointValue();return this.monotonic&&n>o?new $i(t.startTime,this.monotonic,o,!0):new $i(t.startTime,this.monotonic,o-n)},r.prototype.toMetricData=function(e,t,n,o){return{descriptor:e,aggregationTemporality:t,dataPointType:ft.SUM,dataPoints:n.map(function(i){var a=V_(i,2),s=a[0],c=a[1];return{attributes:s,startTime:c.startTime,endTime:o,value:c.toPointValue()}}),isMonotonic:this.monotonic}},r}();var Bn=function(){var r=function(e,t){return r=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(n,o){n.__proto__=o}||function(n,o){for(var i in o)Object.prototype.hasOwnProperty.call(o,i)&&(n[i]=o[i])},r(e,t)};return function(e,t){if(typeof t!="function"&&t!==null)throw new TypeError("Class extends value "+String(t)+" is not a constructor or null");r(e,t);function n(){this.constructor=e}e.prototype=t===null?Object.create(t):(n.prototype=t.prototype,new n)}}(),Cr=function(){function r(){}return r.Drop=function(){return uf},r.Sum=function(){return df},r.LastValue=function(){return pf},r.Histogram=function(){return mf},r.ExponentialHistogram=function(){return W_},r.Default=function(){return $_},r}();var rf=function(r){Bn(e,r);function e(){return r!==null&&r.apply(this,arguments)||this}return e.prototype.createAggregator=function(t){return e.DEFAULT_INSTANCE},e.DEFAULT_INSTANCE=new Wh,e}(Cr);var nf=function(r){Bn(e,r);function e(){return r!==null&&r.apply(this,arguments)||this}return e.prototype.createAggregator=function(t){switch(t.type){case ie.COUNTER:case ie.OBSERVABLE_COUNTER:case ie.HISTOGRAM:return e.MONOTONIC_INSTANCE;default:return e.NON_MONOTONIC_INSTANCE}},e.MONOTONIC_INSTANCE=new Vu(!0),e.NON_MONOTONIC_INSTANCE=new Vu(!1),e}(Cr);var of=function(r){Bn(e,r);function e(){return r!==null&&r.apply(this,arguments)||this}return e.prototype.createAggregator=function(t){return e.DEFAULT_INSTANCE},e.DEFAULT_INSTANCE=new tf,e}(Cr);var af=function(r){Bn(e,r);function e(){return r!==null&&r.apply(this,arguments)||this}return e.prototype.createAggregator=function(t){return e.DEFAULT_INSTANCE},e.DEFAULT_INSTANCE=new Du([0,5,10,25,50,75,100,250,500,750,1e3,2500,5e3,7500,1e4],!0),e}(Cr);var sf=function(r){Bn(e,r);function e(t,n){n===void 0&&(n=!0);var o=r.call(this)||this;if(o._recordMinMax=n,t==null)throw new Error("ExplicitBucketHistogramAggregation should be created with explicit boundaries, if a single bucket histogram is required, please pass an empty array");t=t.concat(),t=t.sort(function(s,c){return s-c});var i=t.lastIndexOf(-1/0),a=t.indexOf(1/0);return a===-1&&(a=void 0),o._boundaries=t.slice(i+1,a),o}return e.prototype.createAggregator=function(t){return new Du(this._boundaries,this._recordMinMax)},e}(Cr);var lf=function(r){Bn(e,r);function e(t,n){t===void 0&&(t=160),n===void 0&&(n=!0);var o=r.call(this)||this;return o._maxSize=t,o._recordMinMax=n,o}return e.prototype.createAggregator=function(t){return new ef(this._maxSize,this._recordMinMax)},e}(Cr);var cf=function(r){Bn(e,r);function e(){return r!==null&&r.apply(this,arguments)||this}return e.prototype._resolve=function(t){switch(t.type){case ie.COUNTER:case ie.UP_DOWN_COUNTER:case ie.OBSERVABLE_COUNTER:case ie.OBSERVABLE_UP_DOWN_COUNTER:return df;case ie.GAUGE:case ie.OBSERVABLE_GAUGE:return pf;case ie.HISTOGRAM:return t.advice.explicitBucketBoundaries?new sf(t.advice.explicitBucketBoundaries):mf}return W.warn("Unable to recognize instrument type: "+t.type),uf},e.prototype.createAggregator=function(t){return this._resolve(t).createAggregator(t)},e}(Cr);var uf=new rf,df=new nf,pf=new of,mf=new af,W_=new lf,$_=new cf;Ce();function Os(){return"unknown_service:"+process.argv0}var on=function(){return on=Object.assign||function(r){for(var e,t=1,n=arguments.length;t<n;t++){e=arguments[t];for(var o in e)Object.prototype.hasOwnProperty.call(e,o)&&(r[o]=e[o])}return r},on.apply(this,arguments)},q_=function(r,e,t,n){function o(i){return i instanceof t?i:new t(function(a){a(i)})}return new(t||(t=Promise))(function(i,a){function 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(r,e||[])).next())})},K_=function(r,e){var t={label:0,sent:function(){if(i[0]&1)throw i[1];return i[1]},trys:[],ops:[]},n,o,i,a;return a={next: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(;t;)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 t.label++,{value:l[1],done:!1};case 5:t.label++,o=l[1],l=[0];continue;case 7:l=t.ops.pop(),t.trys.pop();continue;default:if(i=t.trys,!(i=i.length>0&&i[i.length-1])&&(l[0]===6||l[0]===2)){t=0;continue}if(l[0]===3&&(!i||l[1]>i[0]&&l[1]<i[3])){t.label=l[1];break}if(l[0]===6&&t.label<i[1]){t.label=i[1],i=l;break}if(i&&t.label<i[2]){t.label=i[2],t.ops.push(l);break}i[2]&&t.ops.pop(),t.trys.pop();continue}l=e.call(r,t)}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}}},Y_=function(r,e){var t=typeof Symbol=="function"&&r[Symbol.iterator];if(!t)return r;var n=t.call(r),o,i=[],a;try{for(;(e===void 0||e-- >0)&&!(o=n.next()).done;)i.push(o.value)}catch(s){a={error:s}}finally{try{o&&!o.done&&(t=n.return)&&t.call(n)}finally{if(a)throw a.error}}return i},Wu=function(){function r(e,t){var n=this,o;this._attributes=e,this.asyncAttributesPending=t!=null,this._syncAttributes=(o=this._attributes)!==null&&o!==void 0?o:{},this._asyncAttributesPromise=t?.then(function(i){return n._attributes=Object.assign({},n._attributes,i),n.asyncAttributesPending=!1,i},function(i){return W.debug("a resource's async attributes promise rejected: %s",i),n.asyncAttributesPending=!1,{}})}return r.empty=function(){return r.EMPTY},r.default=function(){var e;return new r((e={},e[Rs]=Os(),e[Hi]=Cs[Hi],e[zi]=Cs[zi],e[Gi]=Cs[Gi],e))},Object.defineProperty(r.prototype,"attributes",{get:function(){var e;return this.asyncAttributesPending&&W.error("Accessing resource attributes before async attributes settled"),(e=this._attributes)!==null&&e!==void 0?e:{}},enumerable:!1,configurable:!0}),r.prototype.waitForAsyncAttributes=function(){return q_(this,void 0,void 0,function(){return K_(this,function(e){switch(e.label){case 0:return this.asyncAttributesPending?[4,this._asyncAttributesPromise]:[3,2];case 1:e.sent(),e.label=2;case 2:return[2]}})})},r.prototype.merge=function(e){var t=this,n;if(!e)return this;var o=on(on({},this._syncAttributes),(n=e._syncAttributes)!==null&&n!==void 0?n:e.attributes);if(!this._asyncAttributesPromise&&!e._asyncAttributesPromise)return new r(o);var i=Promise.all([this._asyncAttributesPromise,e._asyncAttributesPromise]).then(function(a){var s,c=Y_(a,2),l=c[0],u=c[1];return on(on(on(on({},t._syncAttributes),l),(s=e._syncAttributes)!==null&&s!==void 0?s:e.attributes),u)});return new r(o,i)},r.EMPTY=new r({}),r}();var zn;(function(r){r[r.DELTA=0]="DELTA",r[r.CUMULATIVE=1]="CUMULATIVE",r[r.LOWMEMORY=2]="LOWMEMORY"})(zn||(zn={}));Ce();var X_=function(r,e,t,n){function o(i){return i instanceof t?i:new t(function(a){a(i)})}return new(t||(t=Promise))(function(i,a){function 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(r,e||[])).next())})},J_=function(r,e){var t={label:0,sent:function(){if(i[0]&1)throw i[1];return i[1]},trys:[],ops:[]},n,o,i,a;return a={next: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(;t;)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 t.label++,{value:l[1],done:!1};case 5:t.label++,o=l[1],l=[0];continue;case 7:l=t.ops.pop(),t.trys.pop();continue;default:if(i=t.trys,!(i=i.length>0&&i[i.length-1])&&(l[0]===6||l[0]===2)){t=0;continue}if(l[0]===3&&(!i||l[1]>i[0]&&l[1]<i[3])){t.label=l[1];break}if(l[0]===6&&t.label<i[1]){t.label=i[1],i=l;break}if(i&&t.label<i[2]){t.label=i[2],t.ops.push(l);break}i[2]&&t.ops.pop(),t.trys.pop();continue}l=e.call(r,t)}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}}},$u=function(){return qt.CUMULATIVE},gf=function(r){switch(r){case ie.COUNTER:case ie.OBSERVABLE_COUNTER:case ie.GAUGE:case ie.HISTOGRAM:case ie.OBSERVABLE_GAUGE:return qt.DELTA;case ie.UP_DOWN_COUNTER:case ie.OBSERVABLE_UP_DOWN_COUNTER:return qt.CUMULATIVE}},hf=function(r){switch(r){case ie.COUNTER:case ie.HISTOGRAM:return qt.DELTA;case ie.GAUGE:case ie.UP_DOWN_COUNTER:case ie.OBSERVABLE_UP_DOWN_COUNTER:case ie.OBSERVABLE_COUNTER:case ie.OBSERVABLE_GAUGE:return qt.CUMULATIVE}};function Z_(){var r=mt(),e=r.OTEL_EXPORTER_OTLP_METRICS_TEMPORALITY_PREFERENCE.trim().toLowerCase();return e==="cumulative"?$u:e==="delta"?gf:e==="lowmemory"?hf:(W.warn("OTEL_EXPORTER_OTLP_METRICS_TEMPORALITY_PREFERENCE is set to '"+r.OTEL_EXPORTER_OTLP_METRICS_TEMPORALITY_PREFERENCE+"', but only 'cumulative' and 'delta' are allowed. Using default ('cumulative') instead."),$u)}function Q_(r){return r!=null?r===zn.DELTA?gf:r===zn.LOWMEMORY?hf:$u:Z_()}function eM(r){return r?.aggregationPreference?r.aggregationPreference:function(e){return Cr.Default()}}var ff=function(){function r(e,t){this._otlpExporter=e,this._aggregationSelector=eM(t),this._aggregationTemporalitySelector=Q_(t?.temporalityPreference)}return r.prototype.export=function(e,t){this._otlpExporter.export([e],t)},r.prototype.shutdown=function(){return X_(this,void 0,void 0,function(){return J_(this,function(e){switch(e.label){case 0:return[4,this._otlpExporter.shutdown()];case 1:return e.sent(),[2]}})})},r.prototype.forceFlush=function(){return Promise.resolve()},r.prototype.selectAggregation=function(e){return this._aggregationSelector(e)},r.prototype.selectAggregationTemporality=function(e){return this._aggregationTemporalitySelector(e)},r}();Ce();Ce();var tM=function(r,e){var t=typeof Symbol=="function"&&r[Symbol.iterator];if(!t)return r;var n=t.call(r),o,i=[],a;try{for(;(e===void 0||e-- >0)&&!(o=n.next()).done;)i.push(o.value)}catch(s){a={error:s}}finally{try{o&&!o.done&&(t=n.return)&&t.call(n)}finally{if(a)throw a.error}}return i},Sf=1e4,yf=5,bf=1e3,Ef=5e3,Tf=1.5;function qi(r){r===void 0&&(r={});var e={};return Object.entries(r).forEach(function(t){var n=tM(t,2),o=n[0],i=n[1];typeof i<"u"?e[o]=String(i):W.warn('Header "'+o+'" has invalid value ('+i+") and will be ignored")}),e}function qu(r,e){return r.endsWith("/")||(r=r+"/"),r+e}function Ku(r){try{var e=new URL(r);return e.pathname===""&&(e.pathname=e.pathname+"/"),e.toString()}catch{return W.warn("Could not parse export URL: '"+r+"'"),r}}function Yu(r){return typeof r=="number"?r<=0?Xu(r,Sf):r:rM()}function rM(){var r,e=Number((r=mt().OTEL_EXPORTER_OTLP_TRACES_TIMEOUT)!==null&&r!==void 0?r:mt().OTEL_EXPORTER_OTLP_TIMEOUT);return e<=0?Xu(e,Sf):e}function Xu(r,e){return W.warn("Timeout must be greater than 0",r),e}function vf(r){var e=[429,502,503,504];return e.includes(r)}function Af(r){if(r==null)return-1;var e=Number.parseInt(r,10);if(Number.isInteger(e))return e>0?e*1e3:-1;var t=new Date(r).getTime()-Date.now();return t>=0?t:0}var wf=function(){function r(e){e===void 0&&(e={}),this._sendingPromises=[],this.url=this.getDefaultUrl(e),typeof e.hostname=="string"&&(this.hostname=e.hostname),this.shutdown=this.shutdown.bind(this),this._shutdownOnce=new jh(this._shutdown,this),this._concurrencyLimit=typeof e.concurrencyLimit=="number"?e.concurrencyLimit:30,this.timeoutMillis=Yu(e.timeoutMillis),this.onInit(e)}return r.prototype.export=function(e,t){if(this._shutdownOnce.isCalled){t({code:Fn.FAILED,error:new Error("Exporter has been shutdown")});return}if(this._sendingPromises.length>=this._concurrencyLimit){t({code:Fn.FAILED,error:new Error("Concurrent export limit reached")});return}this._export(e).then(function(){t({code:Fn.SUCCESS})}).catch(function(n){t({code:Fn.FAILED,error:n})})},r.prototype._export=function(e){var t=this;return new Promise(function(n,o){try{W.debug("items to be sent",e),t.send(e,n,o)}catch(i){o(i)}})},r.prototype.shutdown=function(){return this._shutdownOnce.call()},r.prototype.forceFlush=function(){return Promise.all(this._sendingPromises).then(function(){})},r.prototype._shutdown=function(){return W.debug("shutdown started"),this.onShutdown(),this.forceFlush()},r}();Ce();import*as Ju from"url";import*as Ns from"http";import*as ks from"https";import*as Rf from"zlib";import{Readable as oM}from"stream";var an;(function(r){r.NONE="none",r.GZIP="gzip"})(an||(an={}));var nM=function(){var r=function(e,t){return r=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(n,o){n.__proto__=o}||function(n,o){for(var i in o)Object.prototype.hasOwnProperty.call(o,i)&&(n[i]=o[i])},r(e,t)};return function(e,t){if(typeof t!="function"&&t!==null)throw new TypeError("Class extends value "+String(t)+" is not a constructor or null");r(e,t);function n(){this.constructor=e}e.prototype=t===null?Object.create(t):(n.prototype=t.prototype,new n)}}(),Lo=function(r){nM(e,r);function e(t,n,o){var i=r.call(this,t)||this;return i.name="OTLPExporterError",i.data=o,i.code=n,i}return e}(Error);var Ls=function(){return Ls=Object.assign||function(r){for(var e,t=1,n=arguments.length;t<n;t++){e=arguments[t];for(var o in e)Object.prototype.hasOwnProperty.call(e,o)&&(r[o]=e[o])}return r},Ls.apply(this,arguments)};function Zu(r,e,t,n,o){var i=r.timeoutMillis,a=new Ju.URL(r.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 Lo("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:Ls({"Content-Type":t},r.headers),agent:r.agent},g=a.protocol==="http:"?Ns.request:ks.request,m=function(h,f){switch(h===void 0&&(h=yf),f===void 0&&(f=bf),l=g(p,function(S){var A="";S.on("data",function(C){return A+=C}),S.on("aborted",function(){if(u){var C=new Lo("Request Timeout");o(C)}}),S.on("end",function(){if(u===!1)if(S.statusCode&&S.statusCode<299)W.debug("statusCode: "+S.statusCode,A),n(),clearTimeout(d),clearTimeout(c);else if(S.statusCode&&vf(S.statusCode)&&h>0){var C=void 0;f=Tf*f,S.headers["retry-after"]?C=Af(S.headers["retry-after"]):C=Math.round(Math.random()*(Ef-f)+f),c=setTimeout(function(){m(h-1,f)},C)}else{var T=new Lo(S.statusMessage,S.statusCode,A);o(T),clearTimeout(d),clearTimeout(c)}})}),l.on("error",function(S){if(u){var A=new Lo("Request Timeout",S.code);o(A)}else o(S);clearTimeout(d),clearTimeout(c)}),l.on("abort",function(){if(u){var S=new Lo("Request Timeout");o(S)}clearTimeout(d),clearTimeout(c)}),r.compression){case an.GZIP:{l.setHeader("Content-Encoding","gzip");var E=iM(e);E.on("error",o).pipe(Rf.createGzip()).on("error",o).pipe(l);break}default:l.end(Buffer.from(e));break}};m()}function iM(r){var e=new oM;return e.push(r),e.push(null),e}function Qu(r){if(r.httpAgentOptions&&r.keepAlive===!1){W.warn("httpAgentOptions is used only when keepAlive is true");return}if(!(r.keepAlive===!1||!r.url))try{var e=new Ju.URL(r.url),t=e.protocol==="http:"?Ns.Agent:ks.Agent;return new t(Ls({keepAlive:!0},r.httpAgentOptions))}catch(n){W.error("collector exporter failed to create http agent. err: "+n.message);return}}function ed(r){if(r)return r;var e=mt().OTEL_EXPORTER_OTLP_TRACES_COMPRESSION||mt().OTEL_EXPORTER_OTLP_COMPRESSION;return e===an.GZIP?an.GZIP:an.NONE}Ce();var aM=function(){var r=function(e,t){return r=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(n,o){n.__proto__=o}||function(n,o){for(var i in o)Object.prototype.hasOwnProperty.call(o,i)&&(n[i]=o[i])},r(e,t)};return function(e,t){if(typeof t!="function"&&t!==null)throw new TypeError("Class extends value "+String(t)+" is not a constructor or null");r(e,t);function n(){this.constructor=e}e.prototype=t===null?Object.create(t):(n.prototype=t.prototype,new n)}}(),Ds=function(r){aM(e,r);function e(t,n,o){t===void 0&&(t={});var i=r.call(this,t)||this;return i.DEFAULT_HEADERS={},i._contentType=o,t.metadata&&W.warn("Metadata cannot be set when using http"),i.headers=Object.assign(i.DEFAULT_HEADERS,qi(t.headers),Po.parseKeyPairsIntoRecord(mt().OTEL_EXPORTER_OTLP_HEADERS)),i.agent=Qu(t),i.compression=ed(t.compression),i._serializer=n,i}return e.prototype.onInit=function(t){},e.prototype.send=function(t,n,o){var i=this;if(this._shutdownOnce.isCalled){W.debug("Shutdown already started. Cannot send objects");return}var a=new Promise(function(c,l){var u;Zu(i,(u=i._serializer.serializeRequest(t))!==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}(wf);function xf(r){var e=BigInt(1e9);return BigInt(r[0])*e+BigInt(r[1])}function sM(r){var e=Number(BigInt.asUintN(32,r)),t=Number(BigInt.asUintN(32,r>>BigInt(32)));return{low:e,high:t}}function _f(r){var e=xf(r);return sM(e)}function lM(r){var e=xf(r);return e.toString()}var cM=typeof BigInt<"u"?lM:Hh;function Cf(r){return r}function Mf(r){if(r!==void 0)return ws(r)}var uM={encodeHrTime:_f,encodeSpanContext:ws,encodeOptionalSpanContext:Mf};function If(r){var e,t;if(r===void 0)return uM;var n=(e=r.useLongBits)!==null&&e!==void 0?e:!0,o=(t=r.useHex)!==null&&t!==void 0?t:!1;return{encodeHrTime:n?_f:cM,encodeSpanContext:o?Cf:ws,encodeOptionalSpanContext:o?Cf:Mf}}var dM=function(r,e){var t=typeof Symbol=="function"&&r[Symbol.iterator];if(!t)return r;var n=t.call(r),o,i=[],a;try{for(;(e===void 0||e-- >0)&&!(o=n.next()).done;)i.push(o.value)}catch(s){a={error:s}}finally{try{o&&!o.done&&(t=n.return)&&t.call(n)}finally{if(a)throw a.error}}return i};function Pf(r){return{name:r.name,version:r.version}}function No(r){return Object.keys(r).map(function(e){return Of(e,r[e])})}function Of(r,e){return{key:r,value:Lf(e)}}function Lf(r){var e=typeof r;return e==="string"?{stringValue:r}:e==="number"?Number.isInteger(r)?{intValue:r}:{doubleValue:r}:e==="boolean"?{boolValue:r}:r instanceof Uint8Array?{bytesValue:r}:Array.isArray(r)?{arrayValue:{values:r.map(Lf)}}:e==="object"&&r!=null?{kvlistValue:{values:Object.entries(r).map(function(t){var n=dM(t,2),o=n[0],i=n[1];return Of(o,i)})}}:{}}function Nf(r){return{attributes:No(r.attributes),droppedAttributesCount:0}}Ce();function Df(r,e){var t=If(e);return{resource:Nf(r.resource),schemaUrl:void 0,scopeMetrics:pM(r.scopeMetrics,t)}}function pM(r,e){return Array.from(r.map(function(t){return{scope:Pf(t.scope),metrics:t.metrics.map(function(n){return mM(n,e)}),schemaUrl:t.scope.schemaUrl}}))}function mM(r,e){var t={name:r.descriptor.name,description:r.descriptor.description,unit:r.descriptor.unit},n=SM(r.aggregationTemporality);switch(r.dataPointType){case ft.SUM:t.sum={aggregationTemporality:n,isMonotonic:r.isMonotonic,dataPoints:kf(r,e)};break;case ft.GAUGE:t.gauge={dataPoints:kf(r,e)};break;case ft.HISTOGRAM:t.histogram={aggregationTemporality:n,dataPoints:hM(r,e)};break;case ft.EXPONENTIAL_HISTOGRAM:t.exponentialHistogram={aggregationTemporality:n,dataPoints:fM(r,e)};break}return t}function gM(r,e,t){var n={attributes:No(r.attributes),startTimeUnixNano:t.encodeHrTime(r.startTime),timeUnixNano:t.encodeHrTime(r.endTime)};switch(e){case Ht.INT:n.asInt=r.value;break;case Ht.DOUBLE:n.asDouble=r.value;break}return n}function kf(r,e){return r.dataPoints.map(function(t){return gM(t,r.descriptor.valueType,e)})}function hM(r,e){return r.dataPoints.map(function(t){var n=t.value;return{attributes:No(t.attributes),bucketCounts:n.buckets.counts,explicitBounds:n.buckets.boundaries,count:n.count,sum:n.sum,min:n.min,max:n.max,startTimeUnixNano:e.encodeHrTime(t.startTime),timeUnixNano:e.encodeHrTime(t.endTime)}})}function fM(r,e){return r.dataPoints.map(function(t){var n=t.value;return{attributes:No(t.attributes),count:n.count,min:n.min,max:n.max,sum:n.sum,positive:{offset:n.positive.offset,bucketCounts:n.positive.bucketCounts},negative:{offset:n.negative.offset,bucketCounts:n.negative.bucketCounts},scale:n.scale,zeroCount:n.zeroCount,startTimeUnixNano:e.encodeHrTime(t.startTime),timeUnixNano:e.encodeHrTime(t.endTime)}})}function SM(r){switch(r){case qt.DELTA:return 1;case qt.CUMULATIVE:return 2}}function Uf(r,e){return{resourceMetrics:r.map(function(t){return Df(t,e)})}}var td={serializeRequest:function(r){var e=Uf(r,{useLongBits:!1}),t=new TextEncoder;return t.encode(JSON.stringify(e))},deserializeResponse:function(r){var e=new TextDecoder;return JSON.parse(e.decode(r))}};var Ff="0.52.1";var Bf=function(){var r=function(e,t){return r=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(n,o){n.__proto__=o}||function(n,o){for(var i in o)Object.prototype.hasOwnProperty.call(o,i)&&(n[i]=o[i])},r(e,t)};return function(e,t){if(typeof t!="function"&&t!==null)throw new TypeError("Class extends value "+String(t)+" is not a constructor or null");r(e,t);function n(){this.constructor=e}e.prototype=t===null?Object.create(t):(n.prototype=t.prototype,new n)}}(),ko=function(){return ko=Object.assign||function(r){for(var e,t=1,n=arguments.length;t<n;t++){e=arguments[t];for(var o in e)Object.prototype.hasOwnProperty.call(e,o)&&(r[o]=e[o])}return r},ko.apply(this,arguments)},zf="v1/metrics",yM="http://localhost:4318/"+zf,bM={"User-Agent":"OTel-OTLP-Exporter-JavaScript/"+Ff},EM=function(r){Bf(e,r);function e(t){var n=r.call(this,t,td,"application/json")||this;return n.headers=ko(ko(ko(ko({},n.headers),bM),Po.parseKeyPairsIntoRecord(mt().OTEL_EXPORTER_OTLP_METRICS_HEADERS)),qi(t?.headers)),n}return e.prototype.getDefaultUrl=function(t){return typeof t.url=="string"?t.url:mt().OTEL_EXPORTER_OTLP_METRICS_ENDPOINT.length>0?Ku(mt().OTEL_EXPORTER_OTLP_METRICS_ENDPOINT):mt().OTEL_EXPORTER_OTLP_ENDPOINT.length>0?qu(mt().OTEL_EXPORTER_OTLP_ENDPOINT,zf):yM},e}(Ds),Hf=function(r){Bf(e,r);function e(t){return r.call(this,new EM(t),t)||this}return e}(ff);var Do;(function(r){r[r.DELTA=0]="DELTA",r[r.CUMULATIVE=1]="CUMULATIVE"})(Do||(Do={}));var xr;(function(r){r[r.HISTOGRAM=0]="HISTOGRAM",r[r.EXPONENTIAL_HISTOGRAM=1]="EXPONENTIAL_HISTOGRAM",r[r.GAUGE=2]="GAUGE",r[r.SUM=3]="SUM"})(xr||(xr={}));Ce();var TM=function(){var r=function(e,t){return r=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(n,o){n.__proto__=o}||function(n,o){for(var i in o)Object.prototype.hasOwnProperty.call(o,i)&&(n[i]=o[i])},r(e,t)};return function(e,t){if(typeof t!="function"&&t!==null)throw new TypeError("Class extends value "+String(t)+" is not a constructor or null");r(e,t);function n(){this.constructor=e}e.prototype=t===null?Object.create(t):(n.prototype=t.prototype,new n)}}(),Gf=function(r,e,t,n){function o(i){return i instanceof t?i:new t(function(a){a(i)})}return new(t||(t=Promise))(function(i,a){function 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(r,e||[])).next())})},jf=function(r,e){var t={label:0,sent:function(){if(i[0]&1)throw i[1];return i[1]},trys:[],ops:[]},n,o,i,a;return a={next: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(;t;)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 t.label++,{value:l[1],done:!1};case 5:t.label++,o=l[1],l=[0];continue;case 7:l=t.ops.pop(),t.trys.pop();continue;default:if(i=t.trys,!(i=i.length>0&&i[i.length-1])&&(l[0]===6||l[0]===2)){t=0;continue}if(l[0]===3&&(!i||l[1]>i[0]&&l[1]<i[3])){t.label=l[1];break}if(l[0]===6&&t.label<i[1]){t.label=i[1],i=l;break}if(i&&t.label<i[2]){t.label=i[2],t.ops.push(l);break}i[2]&&t.ops.pop(),t.trys.pop();continue}l=e.call(r,t)}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}}},vM=function(r,e){var t=typeof Symbol=="function"&&r[Symbol.iterator];if(!t)return r;var n=t.call(r),o,i=[],a;try{for(;(e===void 0||e-- >0)&&!(o=n.next()).done;)i.push(o.value)}catch(s){a={error:s}}finally{try{o&&!o.done&&(t=n.return)&&t.call(n)}finally{if(a)throw a.error}}return i},AM=function(r,e,t){if(t||arguments.length===2)for(var n=0,o=e.length,i;n<o;n++)(i||!(n in e))&&(i||(i=Array.prototype.slice.call(e,0,n)),i[n]=e[n]);return r.concat(i||Array.prototype.slice.call(e))},wM=function(r){var e=typeof Symbol=="function"&&Symbol.iterator,t=e&&r[e],n=0;if(t)return t.call(r);if(r&&typeof r.length=="number")return{next:function(){return r&&n>=r.length&&(r=void 0),{value:r&&r[n++],done:!r}}};throw new TypeError(e?"Object is not iterable.":"Symbol.iterator is not defined.")};function Vf(r){return r!=null}function Us(r){var e=Object.keys(r);return e.length===0?"":(e=e.sort(),JSON.stringify(e.map(function(t){return[t,r[t]]})))}function Wf(r){var e,t;return r.name+":"+((e=r.version)!==null&&e!==void 0?e:"")+":"+((t=r.schemaUrl)!==null&&t!==void 0?t:"")}var rd=function(r){TM(e,r);function e(t){var n=r.call(this,t)||this;return Object.setPrototypeOf(n,e.prototype),n}return e}(Error);function sn(r,e){var t,n=new Promise(function(i,a){t=setTimeout(function(){a(new rd("Operation timed out."))},e)});return Promise.race([r,n]).then(function(o){return clearTimeout(t),o},function(o){throw clearTimeout(t),o})}function $f(r){return Gf(this,void 0,void 0,function(){var e=this;return jf(this,function(t){return[2,Promise.all(r.map(function(n){return Gf(e,void 0,void 0,function(){var o,i;return jf(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 qf(r){return r.status==="rejected"}function nd(r,e){var t=[];return r.forEach(function(n){t.push.apply(t,AM([],vM(e(n)),!1))}),t}function Kf(r,e){var t,n;if(r.size!==e.size)return!1;try{for(var o=wM(r),i=o.next();!i.done;i=o.next()){var a=i.value;if(!e.has(a))return!1}}catch(s){t={error:s}}finally{try{i&&!i.done&&(n=o.return)&&n.call(o)}finally{if(t)throw t.error}}return!0}function Yf(r,e){for(var t=0,n=r.length-1,o=r.length;n>=t;){var i=t+Math.trunc((n-t)/2);r[i]<e?t=i+1:(o=i,n=i-1)}return o}function Xf(r,e){return r.toLowerCase()===e.toLowerCase()}Ce();var Yt;(function(r){r[r.DROP=0]="DROP",r[r.SUM=1]="SUM",r[r.LAST_VALUE=2]="LAST_VALUE",r[r.HISTOGRAM=3]="HISTOGRAM",r[r.EXPONENTIAL_HISTOGRAM=4]="EXPONENTIAL_HISTOGRAM"})(Yt||(Yt={}));var od=function(){function r(){this.kind=Yt.DROP}return r.prototype.createAccumulation=function(){},r.prototype.merge=function(e,t){},r.prototype.diff=function(e,t){},r.prototype.toMetricData=function(e,t,n,o){},r}();Ce();var pe;(function(r){r.COUNTER="COUNTER",r.GAUGE="GAUGE",r.HISTOGRAM="HISTOGRAM",r.UP_DOWN_COUNTER="UP_DOWN_COUNTER",r.OBSERVABLE_COUNTER="OBSERVABLE_COUNTER",r.OBSERVABLE_GAUGE="OBSERVABLE_GAUGE",r.OBSERVABLE_UP_DOWN_COUNTER="OBSERVABLE_UP_DOWN_COUNTER"})(pe||(pe={}));function _r(r,e,t){var n,o,i,a;return CM(r)||W.warn('Invalid metric name: "'+r+'". The metric name should be a ASCII string with a length no greater than 255 characters.'),{name:r,type:e,description:(n=t?.description)!==null&&n!==void 0?n:"",unit:(o=t?.unit)!==null&&o!==void 0?o:"",valueType:(i=t?.valueType)!==null&&i!==void 0?i:Ht.DOUBLE,advice:(a=t?.advice)!==null&&a!==void 0?a:{}}}function Jf(r,e){var t,n;return{name:(t=r.name)!==null&&t!==void 0?t:e.name,description:(n=r.description)!==null&&n!==void 0?n:e.description,type:e.type,unit:e.unit,valueType:e.valueType,advice:e.advice}}function Zf(r,e){return Xf(r.name,e.name)&&r.unit===e.unit&&r.type===e.type&&r.valueType===e.valueType}var RM=/^[a-z][a-z0-9_.\-/]{0,254}$/i;function CM(r){return r.match(RM)!=null}var xM=function(r,e){var t=typeof Symbol=="function"&&r[Symbol.iterator];if(!t)return r;var n=t.call(r),o,i=[],a;try{for(;(e===void 0||e-- >0)&&!(o=n.next()).done;)i.push(o.value)}catch(s){a={error:s}}finally{try{o&&!o.done&&(t=n.return)&&t.call(n)}finally{if(a)throw a.error}}return i};function _M(r){var e=r.map(function(){return 0});return e.push(0),{buckets:{boundaries:r,counts:e},sum:0,count:0,hasMinMax:!1,min:1/0,max:-1/0}}var Fs=function(){function r(e,t,n,o){n===void 0&&(n=!0),o===void 0&&(o=_M(t)),this.startTime=e,this._boundaries=t,this._recordMinMax=n,this._current=o}return r.prototype.record=function(e){if(!Number.isNaN(e)){this._current.count+=1,this._current.sum+=e,this._recordMinMax&&(this._current.min=Math.min(e,this._current.min),this._current.max=Math.max(e,this._current.max),this._current.hasMinMax=!0);var t=Yf(this._boundaries,e);this._current.buckets.counts[t]+=1}},r.prototype.setStartTime=function(e){this.startTime=e},r.prototype.toPointValue=function(){return this._current},r}();var Bs=function(){function r(e,t){this._boundaries=e,this._recordMinMax=t,this.kind=Yt.HISTOGRAM}return r.prototype.createAccumulation=function(e){return new Fs(e,this._boundaries,this._recordMinMax)},r.prototype.merge=function(e,t){for(var n=e.toPointValue(),o=t.toPointValue(),i=n.buckets.counts,a=o.buckets.counts,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 Fs(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})},r.prototype.diff=function(e,t){for(var n=e.toPointValue(),o=t.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 Fs(t.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})},r.prototype.toMetricData=function(e,t,n,o){return{descriptor:e,aggregationTemporality:t,dataPointType:xr.HISTOGRAM,dataPoints:n.map(function(i){var a=xM(i,2),s=a[0],c=a[1],l=c.toPointValue(),u=e.type===pe.GAUGE||e.type===pe.UP_DOWN_COUNTER||e.type===pe.OBSERVABLE_GAUGE||e.type===pe.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}}})}},r}();Ce();var id=function(r,e){var t=typeof Symbol=="function"&&r[Symbol.iterator];if(!t)return r;var n=t.call(r),o,i=[],a;try{for(;(e===void 0||e-- >0)&&!(o=n.next()).done;)i.push(o.value)}catch(s){a={error:s}}finally{try{o&&!o.done&&(t=n.return)&&t.call(n)}finally{if(a)throw a.error}}return i},ad=function(r,e,t){if(t||arguments.length===2)for(var n=0,o=e.length,i;n<o;n++)(i||!(n in e))&&(i||(i=Array.prototype.slice.call(e,0,n)),i[n]=e[n]);return r.concat(i||Array.prototype.slice.call(e))},sd=function(){function r(e,t,n,o){e===void 0&&(e=new MM),t===void 0&&(t=0),n===void 0&&(n=0),o===void 0&&(o=0),this.backing=e,this.indexBase=t,this.indexStart=n,this.indexEnd=o}return Object.defineProperty(r.prototype,"offset",{get:function(){return this.indexStart},enumerable:!1,configurable:!0}),Object.defineProperty(r.prototype,"length",{get:function(){return this.backing.length===0||this.indexEnd===this.indexStart&&this.at(0)===0?0:this.indexEnd-this.indexStart+1},enumerable:!1,configurable:!0}),r.prototype.counts=function(){var e=this;return Array.from({length:this.length},function(t,n){return e.at(n)})},r.prototype.at=function(e){var t=this.indexBase-this.indexStart;return e<t&&(e+=this.backing.length),e-=t,this.backing.countAt(e)},r.prototype.incrementBucket=function(e,t){this.backing.increment(e,t)},r.prototype.decrementBucket=function(e,t){this.backing.decrement(e,t)},r.prototype.trim=function(){for(var e=0;e<this.length;e++)if(this.at(e)!==0){this.indexStart+=e;break}else if(e===this.length-1){this.indexStart=this.indexEnd=this.indexBase=0;return}for(var e=this.length-1;e>=0;e--)if(this.at(e)!==0){this.indexEnd-=this.length-e-1;break}this._rotate()},r.prototype.downscale=function(e){this._rotate();for(var t=1+this.indexEnd-this.indexStart,n=1<<e,o=0,i=0,a=this.indexStart;a<=this.indexEnd;){var s=a%n;s<0&&(s+=n);for(var c=s;c<n&&o<t;c++)this._relocateBucket(i,o),o++,a++;i++}this.indexStart>>=e,this.indexEnd>>=e,this.indexBase=this.indexStart},r.prototype.clone=function(){return new r(this.backing.clone(),this.indexBase,this.indexStart,this.indexEnd)},r.prototype._rotate=function(){var e=this.indexBase-this.indexStart;e!==0&&(e>0?(this.backing.reverse(0,this.backing.length),this.backing.reverse(0,e),this.backing.reverse(e,this.backing.length)):(this.backing.reverse(0,this.backing.length),this.backing.reverse(0,this.backing.length+e)),this.indexBase=this.indexStart)},r.prototype._relocateBucket=function(e,t){e!==t&&this.incrementBucket(e,this.backing.emptyBucket(t))},r}();var MM=function(){function r(e){e===void 0&&(e=[0]),this._counts=e}return Object.defineProperty(r.prototype,"length",{get:function(){return this._counts.length},enumerable:!1,configurable:!0}),r.prototype.countAt=function(e){return this._counts[e]},r.prototype.growTo=function(e,t,n){var o=new Array(e).fill(0);o.splice.apply(o,ad([n,this._counts.length-t],id(this._counts.slice(t)),!1)),o.splice.apply(o,ad([0,t],id(this._counts.slice(0,t)),!1)),this._counts=o},r.prototype.reverse=function(e,t){for(var n=Math.floor((e+t)/2)-e,o=0;o<n;o++){var i=this._counts[e+o];this._counts[e+o]=this._counts[t-o-1],this._counts[t-o-1]=i}},r.prototype.emptyBucket=function(e){var t=this._counts[e];return this._counts[e]=0,t},r.prototype.increment=function(e,t){this._counts[e]+=t},r.prototype.decrement=function(e,t){this._counts[e]>=t?this._counts[e]-=t:this._counts[e]=0},r.prototype.clone=function(){return new r(ad([],id(this._counts),!1))},r}();var Qf=52,IM=2146435072,PM=1048575,ld=1023,zs=-ld+1,Hs=ld,Ki=Math.pow(2,-1022);function Gs(r){var e=new DataView(new ArrayBuffer(8));e.setFloat64(0,r);var t=e.getUint32(0),n=(t&IM)>>20;return n-ld}function js(r){var e=new DataView(new ArrayBuffer(8));e.setFloat64(0,r);var t=e.getUint32(0),n=e.getUint32(4),o=(t&PM)*Math.pow(2,32);return o+n}function Yi(r,e){return r===0||r===Number.POSITIVE_INFINITY||r===Number.NEGATIVE_INFINITY||Number.isNaN(r)?r:r*Math.pow(2,e)}function tS(r){return r--,r|=r>>1,r|=r>>2,r|=r>>4,r|=r>>8,r|=r>>16,r++,r}var OM=function(){var r=function(e,t){return r=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(n,o){n.__proto__=o}||function(n,o){for(var i in o)Object.prototype.hasOwnProperty.call(o,i)&&(n[i]=o[i])},r(e,t)};return function(e,t){if(typeof t!="function"&&t!==null)throw new TypeError("Class extends value "+String(t)+" is not a constructor or null");r(e,t);function n(){this.constructor=e}e.prototype=t===null?Object.create(t):(n.prototype=t.prototype,new n)}}(),ln=function(r){OM(e,r);function e(){return r!==null&&r.apply(this,arguments)||this}return e}(Error);var nS=function(){function r(e){this._shift=-e}return r.prototype.mapToIndex=function(e){if(e<Ki)return this._minNormalLowerBoundaryIndex();var t=Gs(e),n=this._rightShift(js(e)-1,Qf);return t+n>>this._shift},r.prototype.lowerBoundary=function(e){var t=this._minNormalLowerBoundaryIndex();if(e<t)throw new ln("underflow: "+e+" is < minimum lower boundary: "+t);var n=this._maxNormalLowerBoundaryIndex();if(e>n)throw new ln("overflow: "+e+" is > maximum lower boundary: "+n);return Yi(1,e<<this._shift)},Object.defineProperty(r.prototype,"scale",{get:function(){return this._shift===0?0:-this._shift},enumerable:!1,configurable:!0}),r.prototype._minNormalLowerBoundaryIndex=function(){var e=zs>>this._shift;return this._shift<2&&e--,e},r.prototype._maxNormalLowerBoundaryIndex=function(){return Hs>>this._shift},r.prototype._rightShift=function(e,t){return Math.floor(e*Math.pow(2,-t))},r}();var oS=function(){function r(e){this._scale=e,this._scaleFactor=Yi(Math.LOG2E,e),this._inverseFactor=Yi(Math.LN2,-e)}return r.prototype.mapToIndex=function(e){if(e<=Ki)return this._minNormalLowerBoundaryIndex()-1;if(js(e)===0){var t=Gs(e);return(t<<this._scale)-1}var n=Math.floor(Math.log(e)*this._scaleFactor),o=this._maxNormalLowerBoundaryIndex();return n>=o?o:n},r.prototype.lowerBoundary=function(e){var t=this._maxNormalLowerBoundaryIndex();if(e>=t){if(e===t)return 2*Math.exp((e-(1<<this._scale))/this._scaleFactor);throw new ln("overflow: "+e+" is > maximum lower boundary: "+t)}var n=this._minNormalLowerBoundaryIndex();if(e<=n){if(e===n)return Ki;if(e===n-1)return Math.exp((e+(1<<this._scale))/this._scaleFactor)/2;throw new ln("overflow: "+e+" is < minimum lower boundary: "+n)}return Math.exp(e*this._inverseFactor)},Object.defineProperty(r.prototype,"scale",{get:function(){return this._scale},enumerable:!1,configurable:!0}),r.prototype._minNormalLowerBoundaryIndex=function(){return zs<<this._scale},r.prototype._maxNormalLowerBoundaryIndex=function(){return(Hs+1<<this._scale)-1},r}();var iS=-10,aS=20,LM=Array.from({length:31},function(r,e){return e>10?new oS(e-10):new nS(e-10)});function cd(r){if(r>aS||r<iS)throw new ln("expected scale >= "+iS+" && <= "+aS+", got: "+r);return LM[r+10]}var NM=function(r,e){var t=typeof Symbol=="function"&&r[Symbol.iterator];if(!t)return r;var n=t.call(r),o,i=[],a;try{for(;(e===void 0||e-- >0)&&!(o=n.next()).done;)i.push(o.value)}catch(s){a={error:s}}finally{try{o&&!o.done&&(t=n.return)&&t.call(n)}finally{if(a)throw a.error}}return i},Vs=function(){function r(e,t){this.low=e,this.high=t}return r.combine=function(e,t){return new r(Math.min(e.low,t.low),Math.max(e.high,t.high))},r}(),kM=20,DM=160,ud=2,sS=function(){function r(e,t,n,o,i,a,s,c,l,u,d){e===void 0&&(e=e),t===void 0&&(t=DM),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 sd),u===void 0&&(u=new sd),d===void 0&&(d=cd(kM)),this.startTime=e,this._maxSize=t,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<ud&&(W.warn("Exponential Histogram Max Size set to "+this._maxSize+", changing to the minimum size of: "+ud),this._maxSize=ud)}return r.prototype.record=function(e){this.updateByIncrement(e,1)},r.prototype.setStartTime=function(e){this.startTime=e},r.prototype.toPointValue=function(){return{hasMinMax:this._recordMinMax,min:this.min,max:this.max,sum:this.sum,positive:{offset:this.positive.offset,bucketCounts:this.positive.counts()},negative:{offset:this.negative.offset,bucketCounts:this.negative.counts()},count:this.count,scale:this.scale,zeroCount:this.zeroCount}},Object.defineProperty(r.prototype,"sum",{get:function(){return this._sum},enumerable:!1,configurable:!0}),Object.defineProperty(r.prototype,"min",{get:function(){return this._min},enumerable:!1,configurable:!0}),Object.defineProperty(r.prototype,"max",{get:function(){return this._max},enumerable:!1,configurable:!0}),Object.defineProperty(r.prototype,"count",{get:function(){return this._count},enumerable:!1,configurable:!0}),Object.defineProperty(r.prototype,"zeroCount",{get:function(){return this._zeroCount},enumerable:!1,configurable:!0}),Object.defineProperty(r.prototype,"scale",{get:function(){return this._count===this._zeroCount?0:this._mapping.scale},enumerable:!1,configurable:!0}),Object.defineProperty(r.prototype,"positive",{get:function(){return this._positive},enumerable:!1,configurable:!0}),Object.defineProperty(r.prototype,"negative",{get:function(){return this._negative},enumerable:!1,configurable:!0}),r.prototype.updateByIncrement=function(e,t){if(!Number.isNaN(e)){if(e>this._max&&(this._max=e),e<this._min&&(this._min=e),this._count+=t,e===0){this._zeroCount+=t;return}this._sum+=e*t,e>0?this._updateBuckets(this._positive,e,t):this._updateBuckets(this._negative,-e,t)}},r.prototype.merge=function(e){this._count===0?(this._min=e.min,this._max=e.max):e.count!==0&&(e.min<this.min&&(this._min=e.min),e.max>this.max&&(this._max=e.max)),this.startTime=e.startTime,this._sum+=e.sum,this._count+=e.count,this._zeroCount+=e.zeroCount;var t=this._minScale(e);this._downscale(this.scale-t),this._mergeBuckets(this.positive,e,e.positive,t),this._mergeBuckets(this.negative,e,e.negative,t)},r.prototype.diff=function(e){this._min=1/0,this._max=-1/0,this._sum-=e.sum,this._count-=e.count,this._zeroCount-=e.zeroCount;var t=this._minScale(e);this._downscale(this.scale-t),this._diffBuckets(this.positive,e,e.positive,t),this._diffBuckets(this.negative,e,e.negative,t)},r.prototype.clone=function(){return new r(this.startTime,this._maxSize,this._recordMinMax,this._sum,this._count,this._zeroCount,this._min,this._max,this.positive.clone(),this.negative.clone(),this._mapping)},r.prototype._updateBuckets=function(e,t,n){var o=this._mapping.mapToIndex(t),i=!1,a=0,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(t)}this._incrementIndexBy(e,o,n)},r.prototype._incrementIndexBy=function(e,t,n){if(n!==0){if(e.length===0&&(e.indexStart=e.indexEnd=e.indexBase=t),t<e.indexStart){var o=e.indexEnd-t;o>=e.backing.length&&this._grow(e,o+1),e.indexStart=t}else if(t>e.indexEnd){var o=t-e.indexStart;o>=e.backing.length&&this._grow(e,o+1),e.indexEnd=t}var i=t-e.indexBase;i<0&&(i+=e.backing.length),e.incrementBucket(i,n)}},r.prototype._grow=function(e,t){var n=e.backing.length,o=e.indexBase-e.indexStart,i=n-o,a=tS(t);a>this._maxSize&&(a=this._maxSize);var s=a-o;e.backing.growTo(a,i,s)},r.prototype._changeScale=function(e,t){for(var n=0;e-t>=this._maxSize;)e>>=1,t>>=1,n++;return n},r.prototype._downscale=function(e){if(e!==0){if(e<0)throw new Error("impossible change of scale: "+this.scale);var t=this._mapping.scale-e;this._positive.downscale(e),this._negative.downscale(e),this._mapping=cd(t)}},r.prototype._minScale=function(e){var t=Math.min(this.scale,e.scale),n=Vs.combine(this._highLowAtScale(this.positive,this.scale,t),this._highLowAtScale(e.positive,e.scale,t)),o=Vs.combine(this._highLowAtScale(this.negative,this.scale,t),this._highLowAtScale(e.negative,e.scale,t));return Math.min(t-this._changeScale(n.high,n.low),t-this._changeScale(o.high,o.low))},r.prototype._highLowAtScale=function(e,t,n){if(e.length===0)return new Vs(0,-1);var o=t-n;return new Vs(e.indexStart>>o,e.indexEnd>>o)},r.prototype._mergeBuckets=function(e,t,n,o){for(var i=n.offset,a=t.scale-o,s=0;s<n.length;s++)this._incrementIndexBy(e,i+s>>a,n.at(s))},r.prototype._diffBuckets=function(e,t,n,o){for(var i=n.offset,a=t.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()},r}();var dd=function(){function r(e,t){this._maxSize=e,this._recordMinMax=t,this.kind=Yt.EXPONENTIAL_HISTOGRAM}return r.prototype.createAccumulation=function(e){return new sS(e,this._maxSize,this._recordMinMax)},r.prototype.merge=function(e,t){var n=t.clone();return n.merge(e),n},r.prototype.diff=function(e,t){var n=t.clone();return n.diff(e),n},r.prototype.toMetricData=function(e,t,n,o){return{descriptor:e,aggregationTemporality:t,dataPointType:xr.EXPONENTIAL_HISTOGRAM,dataPoints:n.map(function(i){var a=NM(i,2),s=a[0],c=a[1],l=c.toPointValue(),u=e.type===pe.GAUGE||e.type===pe.UP_DOWN_COUNTER||e.type===pe.OBSERVABLE_GAUGE||e.type===pe.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}}})}},r}();Ce();var UM=vu("OpenTelemetry SDK Context Key SUPPRESS_TRACING");function lS(r){return r.setValue(UM,!0)}Ce();function cS(){return function(r){W.error(FM(r))}}function FM(r){return typeof r=="string"?r:JSON.stringify(BM(r))}function BM(r){for(var e={},t=r;t!==null;)Object.getOwnPropertyNames(t).forEach(function(n){if(!e[n]){var o=t[n];o&&(e[n]=String(o))}}),t=Object.getPrototypeOf(t);return e}var zM=cS();function Ws(r){try{zM(r)}catch{}}var uS="1.30.1";var HM="process.runtime.name";var GM="service.name";var jM="telemetry.sdk.name",VM="telemetry.sdk.language",WM="telemetry.sdk.version";var dS=HM;var pS=GM;var Xi=jM,Ji=VM,Zi=WM;var $M="nodejs";var mS=$M;var Uo,Hn=(Uo={},Uo[Xi]="opentelemetry",Uo[dS]="node",Uo[Ji]=mS,Uo[Zi]=uS,Uo);function Qi(r){r.unref()}var QM=9,eI=6,tI=Math.pow(10,eI),Mq=Math.pow(10,QM);function Gn(r){var e=r/1e3,t=Math.trunc(e),n=Math.round(r%1e3*tI);return[t,n]}function Fo(r){return r[0]*1e6+r[1]/1e3}var ea;(function(r){r[r.SUCCESS=0]="SUCCESS",r[r.FAILED=1]="FAILED"})(ea||(ea={}));Ce();function gS(r,e){return new Promise(function(t){Io.with(lS(Io.active()),function(){r.export(e,function(n){t(n)})})})}var hS={_export:gS};var rI=function(r,e){var t=typeof Symbol=="function"&&r[Symbol.iterator];if(!t)return r;var n=t.call(r),o,i=[],a;try{for(;(e===void 0||e-- >0)&&!(o=n.next()).done;)i.push(o.value)}catch(s){a={error:s}}finally{try{o&&!o.done&&(t=n.return)&&t.call(n)}finally{if(a)throw a.error}}return i},$s=function(){function r(e,t,n){t===void 0&&(t=0),n===void 0&&(n=[0,0]),this.startTime=e,this._current=t,this.sampleTime=n}return r.prototype.record=function(e){this._current=e,this.sampleTime=Gn(Date.now())},r.prototype.setStartTime=function(e){this.startTime=e},r.prototype.toPointValue=function(){return this._current},r}();var pd=function(){function r(){this.kind=Yt.LAST_VALUE}return r.prototype.createAccumulation=function(e){return new $s(e)},r.prototype.merge=function(e,t){var n=Fo(t.sampleTime)>=Fo(e.sampleTime)?t:e;return new $s(e.startTime,n.toPointValue(),n.sampleTime)},r.prototype.diff=function(e,t){var n=Fo(t.sampleTime)>=Fo(e.sampleTime)?t:e;return new $s(t.startTime,n.toPointValue(),n.sampleTime)},r.prototype.toMetricData=function(e,t,n,o){return{descriptor:e,aggregationTemporality:t,dataPointType:xr.GAUGE,dataPoints:n.map(function(i){var a=rI(i,2),s=a[0],c=a[1];return{attributes:s,startTime:c.startTime,endTime:o,value:c.toPointValue()}})}},r}();var nI=function(r,e){var t=typeof Symbol=="function"&&r[Symbol.iterator];if(!t)return r;var n=t.call(r),o,i=[],a;try{for(;(e===void 0||e-- >0)&&!(o=n.next()).done;)i.push(o.value)}catch(s){a={error:s}}finally{try{o&&!o.done&&(t=n.return)&&t.call(n)}finally{if(a)throw a.error}}return i},Bo=function(){function r(e,t,n,o){n===void 0&&(n=0),o===void 0&&(o=!1),this.startTime=e,this.monotonic=t,this._current=n,this.reset=o}return r.prototype.record=function(e){this.monotonic&&e<0||(this._current+=e)},r.prototype.setStartTime=function(e){this.startTime=e},r.prototype.toPointValue=function(){return this._current},r}();var qs=function(){function r(e){this.monotonic=e,this.kind=Yt.SUM}return r.prototype.createAccumulation=function(e){return new Bo(e,this.monotonic)},r.prototype.merge=function(e,t){var n=e.toPointValue(),o=t.toPointValue();return t.reset?new Bo(t.startTime,this.monotonic,o,t.reset):new Bo(e.startTime,this.monotonic,n+o)},r.prototype.diff=function(e,t){var n=e.toPointValue(),o=t.toPointValue();return this.monotonic&&n>o?new Bo(t.startTime,this.monotonic,o,!0):new Bo(t.startTime,this.monotonic,o-n)},r.prototype.toMetricData=function(e,t,n,o){return{descriptor:e,aggregationTemporality:t,dataPointType:xr.SUM,dataPoints:n.map(function(i){var a=nI(i,2),s=a[0],c=a[1];return{attributes:s,startTime:c.startTime,endTime:o,value:c.toPointValue()}}),isMonotonic:this.monotonic}},r}();var jn=function(){var r=function(e,t){return r=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(n,o){n.__proto__=o}||function(n,o){for(var i in o)Object.prototype.hasOwnProperty.call(o,i)&&(n[i]=o[i])},r(e,t)};return function(e,t){if(typeof t!="function"&&t!==null)throw new TypeError("Class extends value "+String(t)+" is not a constructor or null");r(e,t);function n(){this.constructor=e}e.prototype=t===null?Object.create(t):(n.prototype=t.prototype,new n)}}(),Xt=function(){function r(){}return r.Drop=function(){return vS},r.Sum=function(){return AS},r.LastValue=function(){return wS},r.Histogram=function(){return RS},r.ExponentialHistogram=function(){return oI},r.Default=function(){return iI},r}();var fS=function(r){jn(e,r);function e(){return r!==null&&r.apply(this,arguments)||this}return e.prototype.createAggregator=function(t){return e.DEFAULT_INSTANCE},e.DEFAULT_INSTANCE=new od,e}(Xt);var SS=function(r){jn(e,r);function e(){return r!==null&&r.apply(this,arguments)||this}return e.prototype.createAggregator=function(t){switch(t.type){case pe.COUNTER:case pe.OBSERVABLE_COUNTER:case pe.HISTOGRAM:return e.MONOTONIC_INSTANCE;default:return e.NON_MONOTONIC_INSTANCE}},e.MONOTONIC_INSTANCE=new qs(!0),e.NON_MONOTONIC_INSTANCE=new qs(!1),e}(Xt);var yS=function(r){jn(e,r);function e(){return r!==null&&r.apply(this,arguments)||this}return e.prototype.createAggregator=function(t){return e.DEFAULT_INSTANCE},e.DEFAULT_INSTANCE=new pd,e}(Xt);var bS=function(r){jn(e,r);function e(){return r!==null&&r.apply(this,arguments)||this}return e.prototype.createAggregator=function(t){return e.DEFAULT_INSTANCE},e.DEFAULT_INSTANCE=new Bs([0,5,10,25,50,75,100,250,500,750,1e3,2500,5e3,7500,1e4],!0),e}(Xt);var Ks=function(r){jn(e,r);function e(t,n){n===void 0&&(n=!0);var o=r.call(this)||this;if(o._recordMinMax=n,t==null)throw new Error("ExplicitBucketHistogramAggregation should be created with explicit boundaries, if a single bucket histogram is required, please pass an empty array");t=t.concat(),t=t.sort(function(s,c){return s-c});var i=t.lastIndexOf(-1/0),a=t.indexOf(1/0);return a===-1&&(a=void 0),o._boundaries=t.slice(i+1,a),o}return e.prototype.createAggregator=function(t){return new Bs(this._boundaries,this._recordMinMax)},e}(Xt);var ES=function(r){jn(e,r);function e(t,n){t===void 0&&(t=160),n===void 0&&(n=!0);var o=r.call(this)||this;return o._maxSize=t,o._recordMinMax=n,o}return e.prototype.createAggregator=function(t){return new dd(this._maxSize,this._recordMinMax)},e}(Xt);var TS=function(r){jn(e,r);function e(){return r!==null&&r.apply(this,arguments)||this}return e.prototype._resolve=function(t){switch(t.type){case pe.COUNTER:case pe.UP_DOWN_COUNTER:case pe.OBSERVABLE_COUNTER:case pe.OBSERVABLE_UP_DOWN_COUNTER:return AS;case pe.GAUGE:case pe.OBSERVABLE_GAUGE:return wS;case pe.HISTOGRAM:return t.advice.explicitBucketBoundaries?new Ks(t.advice.explicitBucketBoundaries):RS}return W.warn("Unable to recognize instrument type: "+t.type),vS},e.prototype.createAggregator=function(t){return this._resolve(t).createAggregator(t)},e}(Xt);var vS=new fS,AS=new SS,wS=new yS,RS=new bS,oI=new ES,iI=new TS;var CS=function(r){return Xt.Default()},xS=function(r){return Do.CUMULATIVE};var md=function(r,e,t,n){function o(i){return i instanceof t?i:new t(function(a){a(i)})}return new(t||(t=Promise))(function(i,a){function 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(r,e||[])).next())})},gd=function(r,e){var t={label:0,sent:function(){if(i[0]&1)throw i[1];return i[1]},trys:[],ops:[]},n,o,i,a;return a={next: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(;t;)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 t.label++,{value:l[1],done:!1};case 5:t.label++,o=l[1],l=[0];continue;case 7:l=t.ops.pop(),t.trys.pop();continue;default:if(i=t.trys,!(i=i.length>0&&i[i.length-1])&&(l[0]===6||l[0]===2)){t=0;continue}if(l[0]===3&&(!i||l[1]>i[0]&&l[1]<i[3])){t.label=l[1];break}if(l[0]===6&&t.label<i[1]){t.label=i[1],i=l;break}if(i&&t.label<i[2]){t.label=i[2],t.ops.push(l);break}i[2]&&t.ops.pop(),t.trys.pop();continue}l=e.call(r,t)}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}}},_S=function(r,e){var t=typeof Symbol=="function"&&r[Symbol.iterator];if(!t)return r;var n=t.call(r),o,i=[],a;try{for(;(e===void 0||e-- >0)&&!(o=n.next()).done;)i.push(o.value)}catch(s){a={error:s}}finally{try{o&&!o.done&&(t=n.return)&&t.call(n)}finally{if(a)throw a.error}}return i},aI=function(r,e,t){if(t||arguments.length===2)for(var n=0,o=e.length,i;n<o;n++)(i||!(n in e))&&(i||(i=Array.prototype.slice.call(e,0,n)),i[n]=e[n]);return r.concat(i||Array.prototype.slice.call(e))},MS=function(){function r(e){var t,n,o;this._shutdown=!1,this._aggregationSelector=(t=e?.aggregationSelector)!==null&&t!==void 0?t:CS,this._aggregationTemporalitySelector=(n=e?.aggregationTemporalitySelector)!==null&&n!==void 0?n:xS,this._metricProducers=(o=e?.metricProducers)!==null&&o!==void 0?o:[],this._cardinalitySelector=e?.cardinalitySelector}return r.prototype.setMetricProducer=function(e){if(this._sdkMetricProducer)throw new Error("MetricReader can not be bound to a MeterProvider again.");this._sdkMetricProducer=e,this.onInitialized()},r.prototype.selectAggregation=function(e){return this._aggregationSelector(e)},r.prototype.selectAggregationTemporality=function(e){return this._aggregationTemporalitySelector(e)},r.prototype.selectCardinalityLimit=function(e){return this._cardinalitySelector?this._cardinalitySelector(e):2e3},r.prototype.onInitialized=function(){},r.prototype.collect=function(e){return md(this,void 0,void 0,function(){var t,n,o,i,a,s;return gd(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(aI([this._sdkMetricProducer.collect({timeoutMillis:e?.timeoutMillis})],_S(this._metricProducers.map(function(l){return l.collect({timeoutMillis:e?.timeoutMillis})})),!1))];case 1:return t=_S.apply(void 0,[c.sent()]),n=t[0],o=t.slice(1),i=n.errors.concat(nd(o,function(l){return l.errors})),a=n.resourceMetrics.resource,s=n.resourceMetrics.scopeMetrics.concat(nd(o,function(l){return l.resourceMetrics.scopeMetrics})),[2,{resourceMetrics:{resource:a,scopeMetrics:s},errors:i}]}})})},r.prototype.shutdown=function(e){return md(this,void 0,void 0,function(){return gd(this,function(t){switch(t.label){case 0:return this._shutdown?(W.error("Cannot call shutdown twice."),[2]):e?.timeoutMillis!=null?[3,2]:[4,this.onShutdown()];case 1:return t.sent(),[3,4];case 2:return[4,sn(this.onShutdown(),e.timeoutMillis)];case 3:t.sent(),t.label=4;case 4:return this._shutdown=!0,[2]}})})},r.prototype.forceFlush=function(e){return md(this,void 0,void 0,function(){return gd(this,function(t){switch(t.label){case 0:return this._shutdown?(W.warn("Cannot forceFlush on already shutdown MetricReader."),[2]):e?.timeoutMillis!=null?[3,2]:[4,this.onForceFlush()];case 1:return t.sent(),[2];case 2:return[4,sn(this.onForceFlush(),e.timeoutMillis)];case 3:return t.sent(),[2]}})})},r}();Ce();var sI=function(){var r=function(e,t){return r=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(n,o){n.__proto__=o}||function(n,o){for(var i in o)Object.prototype.hasOwnProperty.call(o,i)&&(n[i]=o[i])},r(e,t)};return function(e,t){if(typeof t!="function"&&t!==null)throw new TypeError("Class extends value "+String(t)+" is not a constructor or null");r(e,t);function n(){this.constructor=e}e.prototype=t===null?Object.create(t):(n.prototype=t.prototype,new n)}}(),Ys=function(r,e,t,n){function o(i){return i instanceof t?i:new t(function(a){a(i)})}return new(t||(t=Promise))(function(i,a){function 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(r,e||[])).next())})},Xs=function(r,e){var t={label:0,sent:function(){if(i[0]&1)throw i[1];return i[1]},trys:[],ops:[]},n,o,i,a;return a={next: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(;t;)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 t.label++,{value:l[1],done:!1};case 5:t.label++,o=l[1],l=[0];continue;case 7:l=t.ops.pop(),t.trys.pop();continue;default:if(i=t.trys,!(i=i.length>0&&i[i.length-1])&&(l[0]===6||l[0]===2)){t=0;continue}if(l[0]===3&&(!i||l[1]>i[0]&&l[1]<i[3])){t.label=l[1];break}if(l[0]===6&&t.label<i[1]){t.label=i[1],i=l;break}if(i&&t.label<i[2]){t.label=i[2],t.ops.push(l);break}i[2]&&t.ops.pop(),t.trys.pop();continue}l=e.call(r,t)}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}}},lI=function(r,e){var t=typeof Symbol=="function"&&r[Symbol.iterator];if(!t)return r;var n=t.call(r),o,i=[],a;try{for(;(e===void 0||e-- >0)&&!(o=n.next()).done;)i.push(o.value)}catch(s){a={error:s}}finally{try{o&&!o.done&&(t=n.return)&&t.call(n)}finally{if(a)throw a.error}}return i},cI=function(r,e,t){if(t||arguments.length===2)for(var n=0,o=e.length,i;n<o;n++)(i||!(n in e))&&(i||(i=Array.prototype.slice.call(e,0,n)),i[n]=e[n]);return r.concat(i||Array.prototype.slice.call(e))},hd=function(r){sI(e,r);function e(t){var n,o,i,a,s=r.call(this,{aggregationSelector:(n=t.exporter.selectAggregation)===null||n===void 0?void 0:n.bind(t.exporter),aggregationTemporalitySelector:(o=t.exporter.selectAggregationTemporality)===null||o===void 0?void 0:o.bind(t.exporter),metricProducers:t.metricProducers})||this;if(t.exportIntervalMillis!==void 0&&t.exportIntervalMillis<=0)throw Error("exportIntervalMillis must be greater than 0");if(t.exportTimeoutMillis!==void 0&&t.exportTimeoutMillis<=0)throw Error("exportTimeoutMillis must be greater than 0");if(t.exportTimeoutMillis!==void 0&&t.exportIntervalMillis!==void 0&&t.exportIntervalMillis<t.exportTimeoutMillis)throw Error("exportIntervalMillis must be greater than or equal to exportTimeoutMillis");return s._exportInterval=(i=t.exportIntervalMillis)!==null&&i!==void 0?i:6e4,s._exportTimeout=(a=t.exportTimeoutMillis)!==null&&a!==void 0?a:3e4,s._exporter=t.exporter,s}return e.prototype._runOnce=function(){return Ys(this,void 0,void 0,function(){var t;return Xs(this,function(n){switch(n.label){case 0:return n.trys.push([0,2,,3]),[4,sn(this._doRun(),this._exportTimeout)];case 1:return n.sent(),[3,3];case 2:return t=n.sent(),t instanceof rd?(W.error("Export took longer than %s milliseconds and timed out.",this._exportTimeout),[2]):(Ws(t),[3,3]);case 3:return[2]}})})},e.prototype._doRun=function(){var t,n;return Ys(this,void 0,void 0,function(){var o,i,a,s,c,l;return Xs(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=W).error.apply(l,cI(["PeriodicExportingMetricReader: metrics collection errors"],lI(a),!1)),!i.resource.asyncAttributesPending)return[3,5];u.label=2;case 2:return u.trys.push([2,4,,5]),[4,(n=(t=i.resource).waitForAsyncAttributes)===null||n===void 0?void 0:n.call(t)];case 3:return u.sent(),[3,5];case 4:return s=u.sent(),W.debug("Error while resolving async portion of resource: ",s),Ws(s),[3,5];case 5:return i.scopeMetrics.length===0?[2]:[4,hS._export(this._exporter,i)];case 6:if(c=u.sent(),c.code!==ea.SUCCESS)throw new Error("PeriodicExportingMetricReader: metrics export failed (error "+c.error+")");return[2]}})})},e.prototype.onInitialized=function(){var t=this;this._interval=setInterval(function(){t._runOnce()},this._exportInterval),Qi(this._interval)},e.prototype.onForceFlush=function(){return Ys(this,void 0,void 0,function(){return Xs(this,function(t){switch(t.label){case 0:return[4,this._runOnce()];case 1:return t.sent(),[4,this._exporter.forceFlush()];case 2:return t.sent(),[2]}})})},e.prototype.onShutdown=function(){return Ys(this,void 0,void 0,function(){return Xs(this,function(t){switch(t.label){case 0:return this._interval&&clearInterval(this._interval),[4,this.onForceFlush()];case 1:return t.sent(),[4,this._exporter.shutdown()];case 2:return t.sent(),[2]}})})},e}(MS);Ce();Ce();function Js(){return"unknown_service:"+process.argv0}var cn=function(){return cn=Object.assign||function(r){for(var e,t=1,n=arguments.length;t<n;t++){e=arguments[t];for(var o in e)Object.prototype.hasOwnProperty.call(e,o)&&(r[o]=e[o])}return r},cn.apply(this,arguments)},uI=function(r,e,t,n){function o(i){return i instanceof t?i:new t(function(a){a(i)})}return new(t||(t=Promise))(function(i,a){function 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(r,e||[])).next())})},dI=function(r,e){var t={label:0,sent:function(){if(i[0]&1)throw i[1];return i[1]},trys:[],ops:[]},n,o,i,a;return a={next: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(;t;)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 t.label++,{value:l[1],done:!1};case 5:t.label++,o=l[1],l=[0];continue;case 7:l=t.ops.pop(),t.trys.pop();continue;default:if(i=t.trys,!(i=i.length>0&&i[i.length-1])&&(l[0]===6||l[0]===2)){t=0;continue}if(l[0]===3&&(!i||l[1]>i[0]&&l[1]<i[3])){t.label=l[1];break}if(l[0]===6&&t.label<i[1]){t.label=i[1],i=l;break}if(i&&t.label<i[2]){t.label=i[2],t.ops.push(l);break}i[2]&&t.ops.pop(),t.trys.pop();continue}l=e.call(r,t)}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}}},pI=function(r,e){var t=typeof Symbol=="function"&&r[Symbol.iterator];if(!t)return r;var n=t.call(r),o,i=[],a;try{for(;(e===void 0||e-- >0)&&!(o=n.next()).done;)i.push(o.value)}catch(s){a={error:s}}finally{try{o&&!o.done&&(t=n.return)&&t.call(n)}finally{if(a)throw a.error}}return i},Zs=function(){function r(e,t){var n=this,o;this._attributes=e,this.asyncAttributesPending=t!=null,this._syncAttributes=(o=this._attributes)!==null&&o!==void 0?o:{},this._asyncAttributesPromise=t?.then(function(i){return n._attributes=Object.assign({},n._attributes,i),n.asyncAttributesPending=!1,i},function(i){return W.debug("a resource's async attributes promise rejected: %s",i),n.asyncAttributesPending=!1,{}})}return r.empty=function(){return r.EMPTY},r.default=function(){var e;return new r((e={},e[pS]=Js(),e[Ji]=Hn[Ji],e[Xi]=Hn[Xi],e[Zi]=Hn[Zi],e))},Object.defineProperty(r.prototype,"attributes",{get:function(){var e;return this.asyncAttributesPending&&W.error("Accessing resource attributes before async attributes settled"),(e=this._attributes)!==null&&e!==void 0?e:{}},enumerable:!1,configurable:!0}),r.prototype.waitForAsyncAttributes=function(){return uI(this,void 0,void 0,function(){return dI(this,function(e){switch(e.label){case 0:return this.asyncAttributesPending?[4,this._asyncAttributesPromise]:[3,2];case 1:e.sent(),e.label=2;case 2:return[2]}})})},r.prototype.merge=function(e){var t=this,n;if(!e)return this;var o=cn(cn({},this._syncAttributes),(n=e._syncAttributes)!==null&&n!==void 0?n:e.attributes);if(!this._asyncAttributesPromise&&!e._asyncAttributesPromise)return new r(o);var i=Promise.all([this._asyncAttributesPromise,e._asyncAttributesPromise]).then(function(a){var s,c=pI(a,2),l=c[0],u=c[1];return cn(cn(cn(cn({},t._syncAttributes),l),(s=e._syncAttributes)!==null&&s!==void 0?s:e.attributes),u)});return new r(o,i)},r.EMPTY=new r({}),r}();var IS=function(){function r(){this._registeredViews=[]}return r.prototype.addView=function(e){this._registeredViews.push(e)},r.prototype.findViews=function(e,t){var n=this,o=this._registeredViews.filter(function(i){return n._matchInstrument(i.instrumentSelector,e)&&n._matchMeter(i.meterSelector,t)});return o},r.prototype._matchInstrument=function(e,t){return(e.getType()===void 0||t.type===e.getType())&&e.getNameFilter().match(t.name)&&e.getUnitFilter().match(t.unit)},r.prototype._matchMeter=function(e,t){return e.getNameFilter().match(t.name)&&(t.version===void 0||e.getVersionFilter().match(t.version))&&(t.schemaUrl===void 0||e.getSchemaUrlFilter().match(t.schemaUrl))},r}();Ce();var Vn=function(){var r=function(e,t){return r=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(n,o){n.__proto__=o}||function(n,o){for(var i in o)Object.prototype.hasOwnProperty.call(o,i)&&(n[i]=o[i])},r(e,t)};return function(e,t){if(typeof t!="function"&&t!==null)throw new TypeError("Class extends value "+String(t)+" is not a constructor or null");r(e,t);function n(){this.constructor=e}e.prototype=t===null?Object.create(t):(n.prototype=t.prototype,new n)}}(),Qs=function(){function r(e,t){this._writableMetricStorage=e,this._descriptor=t}return r.prototype._record=function(e,t,n){if(t===void 0&&(t={}),n===void 0&&(n=Io.active()),typeof e!="number"){W.warn("non-number value provided to metric "+this._descriptor.name+": "+e);return}this._descriptor.valueType===Ht.INT&&!Number.isInteger(e)&&(W.warn("INT value type cannot accept a floating-point value for "+this._descriptor.name+", ignoring the fractional digits."),e=Math.trunc(e),!Number.isInteger(e))||this._writableMetricStorage.record(e,t,n,Gn(Date.now()))},r}();var PS=function(r){Vn(e,r);function e(){return r!==null&&r.apply(this,arguments)||this}return e.prototype.add=function(t,n,o){this._record(t,n,o)},e}(Qs);var OS=function(r){Vn(e,r);function e(){return r!==null&&r.apply(this,arguments)||this}return e.prototype.add=function(t,n,o){if(t<0){W.warn("negative value provided to counter "+this._descriptor.name+": "+t);return}this._record(t,n,o)},e}(Qs);var LS=function(r){Vn(e,r);function e(){return r!==null&&r.apply(this,arguments)||this}return e.prototype.record=function(t,n,o){this._record(t,n,o)},e}(Qs);var NS=function(r){Vn(e,r);function e(){return r!==null&&r.apply(this,arguments)||this}return e.prototype.record=function(t,n,o){if(t<0){W.warn("negative value provided to histogram "+this._descriptor.name+": "+t);return}this._record(t,n,o)},e}(Qs);var el=function(){function r(e,t,n){this._observableRegistry=n,this._descriptor=e,this._metricStorages=t}return r.prototype.addCallback=function(e){this._observableRegistry.addCallback(e,this)},r.prototype.removeCallback=function(e){this._observableRegistry.removeCallback(e,this)},r}();var kS=function(r){Vn(e,r);function e(){return r!==null&&r.apply(this,arguments)||this}return e}(el);var DS=function(r){Vn(e,r);function e(){return r!==null&&r.apply(this,arguments)||this}return e}(el);var US=function(r){Vn(e,r);function e(){return r!==null&&r.apply(this,arguments)||this}return e}(el);function ta(r){return r instanceof el}var FS=function(){function r(e){this._meterSharedState=e}return r.prototype.createGauge=function(e,t){var n=_r(e,pe.GAUGE,t),o=this._meterSharedState.registerMetricStorage(n);return new LS(o,n)},r.prototype.createHistogram=function(e,t){var n=_r(e,pe.HISTOGRAM,t),o=this._meterSharedState.registerMetricStorage(n);return new NS(o,n)},r.prototype.createCounter=function(e,t){var n=_r(e,pe.COUNTER,t),o=this._meterSharedState.registerMetricStorage(n);return new OS(o,n)},r.prototype.createUpDownCounter=function(e,t){var n=_r(e,pe.UP_DOWN_COUNTER,t),o=this._meterSharedState.registerMetricStorage(n);return new PS(o,n)},r.prototype.createObservableGauge=function(e,t){var n=_r(e,pe.OBSERVABLE_GAUGE,t),o=this._meterSharedState.registerAsyncMetricStorage(n);return new DS(n,o,this._meterSharedState.observableRegistry)},r.prototype.createObservableCounter=function(e,t){var n=_r(e,pe.OBSERVABLE_COUNTER,t),o=this._meterSharedState.registerAsyncMetricStorage(n);return new kS(n,o,this._meterSharedState.observableRegistry)},r.prototype.createObservableUpDownCounter=function(e,t){var n=_r(e,pe.OBSERVABLE_UP_DOWN_COUNTER,t),o=this._meterSharedState.registerAsyncMetricStorage(n);return new US(n,o,this._meterSharedState.observableRegistry)},r.prototype.addBatchObservableCallback=function(e,t){this._meterSharedState.observableRegistry.addBatchCallback(e,t)},r.prototype.removeBatchObservableCallback=function(e,t){this._meterSharedState.observableRegistry.removeBatchCallback(e,t)},r}();var tl=function(){function r(e){this._instrumentDescriptor=e}return r.prototype.getInstrumentDescriptor=function(){return this._instrumentDescriptor},r.prototype.updateDescription=function(e){this._instrumentDescriptor=_r(this._instrumentDescriptor.name,this._instrumentDescriptor.type,{description:e,valueType:this._instrumentDescriptor.valueType,unit:this._instrumentDescriptor.unit,advice:this._instrumentDescriptor.advice})},r}();var mI=function(){var r=function(e,t){return r=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(n,o){n.__proto__=o}||function(n,o){for(var i in o)Object.prototype.hasOwnProperty.call(o,i)&&(n[i]=o[i])},r(e,t)};return function(e,t){if(typeof t!="function"&&t!==null)throw new TypeError("Class extends value "+String(t)+" is not a constructor or null");r(e,t);function n(){this.constructor=e}e.prototype=t===null?Object.create(t):(n.prototype=t.prototype,new n)}}(),BS=function(r,e){var t={label:0,sent:function(){if(i[0]&1)throw i[1];return i[1]},trys:[],ops:[]},n,o,i,a;return a={next: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(;t;)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 t.label++,{value:l[1],done:!1};case 5:t.label++,o=l[1],l=[0];continue;case 7:l=t.ops.pop(),t.trys.pop();continue;default:if(i=t.trys,!(i=i.length>0&&i[i.length-1])&&(l[0]===6||l[0]===2)){t=0;continue}if(l[0]===3&&(!i||l[1]>i[0]&&l[1]<i[3])){t.label=l[1];break}if(l[0]===6&&t.label<i[1]){t.label=i[1],i=l;break}if(i&&t.label<i[2]){t.label=i[2],t.ops.push(l);break}i[2]&&t.ops.pop(),t.trys.pop();continue}l=e.call(r,t)}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}}},gI=function(){function r(e){this._hash=e,this._valueMap=new Map,this._keyMap=new Map}return r.prototype.get=function(e,t){return t??(t=this._hash(e)),this._valueMap.get(t)},r.prototype.getOrDefault=function(e,t){var n=this._hash(e);if(this._valueMap.has(n))return this._valueMap.get(n);var o=t();return this._keyMap.has(n)||this._keyMap.set(n,e),this._valueMap.set(n,o),o},r.prototype.set=function(e,t,n){n??(n=this._hash(e)),this._keyMap.has(n)||this._keyMap.set(n,e),this._valueMap.set(n,t)},r.prototype.has=function(e,t){return t??(t=this._hash(e)),this._valueMap.has(t)},r.prototype.keys=function(){var e,t;return BS(this,function(n){switch(n.label){case 0:e=this._keyMap.entries(),t=e.next(),n.label=1;case 1:return t.done===!0?[3,3]:[4,[t.value[1],t.value[0]]];case 2:return n.sent(),t=e.next(),[3,1];case 3:return[2]}})},r.prototype.entries=function(){var e,t;return BS(this,function(n){switch(n.label){case 0:e=this._valueMap.entries(),t=e.next(),n.label=1;case 1:return t.done===!0?[3,3]:[4,[this._keyMap.get(t.value[0]),t.value[1],t.value[0]]];case 2:return n.sent(),t=e.next(),[3,1];case 3:return[2]}})},Object.defineProperty(r.prototype,"size",{get:function(){return this._valueMap.size},enumerable:!1,configurable:!0}),r}();var pr=function(r){mI(e,r);function e(){return r.call(this,Us)||this}return e}(gI);var hI=function(r,e){var t=typeof Symbol=="function"&&r[Symbol.iterator];if(!t)return r;var n=t.call(r),o,i=[],a;try{for(;(e===void 0||e-- >0)&&!(o=n.next()).done;)i.push(o.value)}catch(s){a={error:s}}finally{try{o&&!o.done&&(t=n.return)&&t.call(n)}finally{if(a)throw a.error}}return i},rl=function(){function r(e,t){this._aggregator=e,this._activeCollectionStorage=new pr,this._cumulativeMemoStorage=new pr,this._overflowAttributes={"otel.metric.overflow":!0},this._cardinalityLimit=(t??2e3)-1,this._overflowHashCode=Us(this._overflowAttributes)}return r.prototype.record=function(e,t,n,o){var i=this,a=this._activeCollectionStorage.get(t);if(!a){if(this._activeCollectionStorage.size>=this._cardinalityLimit){var s=this._activeCollectionStorage.getOrDefault(this._overflowAttributes,function(){return i._aggregator.createAccumulation(o)});s?.record(e);return}a=this._aggregator.createAccumulation(o),this._activeCollectionStorage.set(t,a)}a?.record(e)},r.prototype.batchCumulate=function(e,t){var n=this;Array.from(e.entries()).forEach(function(o){var i=hI(o,3),a=i[0],s=i[1],c=i[2],l=n._aggregator.createAccumulation(t);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)})},r.prototype.collect=function(){var e=this._activeCollectionStorage;return this._activeCollectionStorage=new pr,e},r}();var fd=function(r){var e=typeof Symbol=="function"&&Symbol.iterator,t=e&&r[e],n=0;if(t)return t.call(r);if(r&&typeof r.length=="number")return{next:function(){return r&&n>=r.length&&(r=void 0),{value:r&&r[n++],done:!r}}};throw new TypeError(e?"Object is not iterable.":"Symbol.iterator is not defined.")},zS=function(r,e){var t=typeof Symbol=="function"&&r[Symbol.iterator];if(!t)return r;var n=t.call(r),o,i=[],a;try{for(;(e===void 0||e-- >0)&&!(o=n.next()).done;)i.push(o.value)}catch(s){a={error:s}}finally{try{o&&!o.done&&(t=n.return)&&t.call(n)}finally{if(a)throw a.error}}return i},nl=function(){function r(e,t){var n=this;this._aggregator=e,this._unreportedAccumulations=new Map,this._reportHistory=new Map,t.forEach(function(o){n._unreportedAccumulations.set(o,[])})}return r.prototype.buildMetrics=function(e,t,n,o){this._stashAccumulations(n);var i=this._getMergedUnreportedAccumulations(e),a=i,s;if(this._reportHistory.has(e)){var c=this._reportHistory.get(e),l=c.collectionTime;s=c.aggregationTemporality,s===Do.CUMULATIVE?a=r.merge(c.accumulations,i,this._aggregator):a=r.calibrateStartTime(c.accumulations,i,l)}else s=e.selectAggregationTemporality(t.type);this._reportHistory.set(e,{accumulations:a,collectionTime:o,aggregationTemporality:s});var u=fI(a);if(u.length!==0)return this._aggregator.toMetricData(t,s,u,o)},r.prototype._stashAccumulations=function(e){var t,n,o=this._unreportedAccumulations.keys();try{for(var i=fd(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){t={error:l}}finally{try{a&&!a.done&&(n=i.return)&&n.call(i)}finally{if(t)throw t.error}}},r.prototype._getMergedUnreportedAccumulations=function(e){var t,n,o=new pr,i=this._unreportedAccumulations.get(e);if(this._unreportedAccumulations.set(e,[]),i===void 0)return o;try{for(var a=fd(i),s=a.next();!s.done;s=a.next()){var c=s.value;o=r.merge(o,c,this._aggregator)}}catch(l){t={error:l}}finally{try{s&&!s.done&&(n=a.return)&&n.call(a)}finally{if(t)throw t.error}}return o},r.merge=function(e,t,n){for(var o=e,i=t.entries(),a=i.next();a.done!==!0;){var s=zS(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},r.calibrateStartTime=function(e,t,n){var o,i;try{for(var a=fd(e.keys()),s=a.next();!s.done;s=a.next()){var c=zS(s.value,2),l=c[0],u=c[1],d=t.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 t},r}();function fI(r){return Array.from(r.entries())}var SI=function(){var r=function(e,t){return r=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(n,o){n.__proto__=o}||function(n,o){for(var i in o)Object.prototype.hasOwnProperty.call(o,i)&&(n[i]=o[i])},r(e,t)};return function(e,t){if(typeof t!="function"&&t!==null)throw new TypeError("Class extends value "+String(t)+" is not a constructor or null");r(e,t);function n(){this.constructor=e}e.prototype=t===null?Object.create(t):(n.prototype=t.prototype,new n)}}(),yI=function(r,e){var t=typeof Symbol=="function"&&r[Symbol.iterator];if(!t)return r;var n=t.call(r),o,i=[],a;try{for(;(e===void 0||e-- >0)&&!(o=n.next()).done;)i.push(o.value)}catch(s){a={error:s}}finally{try{o&&!o.done&&(t=n.return)&&t.call(n)}finally{if(a)throw a.error}}return i},HS=function(r){SI(e,r);function e(t,n,o,i,a){var s=r.call(this,t)||this;return s._attributesProcessor=o,s._aggregationCardinalityLimit=a,s._deltaMetricStorage=new rl(n,s._aggregationCardinalityLimit),s._temporalMetricStorage=new nl(n,i),s}return e.prototype.record=function(t,n){var o=this,i=new pr;Array.from(t.entries()).forEach(function(a){var s=yI(a,2),c=s[0],l=s[1];i.set(o._attributesProcessor.process(c),l)}),this._deltaMetricStorage.batchCumulate(i,n)},e.prototype.collect=function(t,n){var o=this._deltaMetricStorage.collect();return this._temporalMetricStorage.buildMetrics(t,this._instrumentDescriptor,o,n)},e}(tl);Ce();function Sd(r,e){var t="";return r.unit!==e.unit&&(t+=" - Unit '"+r.unit+"' does not match '"+e.unit+`'
|
|
3
|
-
`),r.type!==e.type&&(t+=" - Type '"+r.type+"' does not match '"+e.type+`'
|
|
4
|
-
`),r.valueType!==e.valueType&&(t+=" - Value Type '"+r.valueType+"' does not match '"+e.valueType+`'
|
|
5
|
-
`),r.description!==e.description&&(t+=" - Description '"+r.description+"' does not match '"+e.description+`'
|
|
6
|
-
`),t}function bI(r,e){return" - use valueType '"+r.valueType+"' on instrument creation or use an instrument name other than '"+e.name+"'"}function EI(r,e){return" - use unit '"+r.unit+"' on instrument creation or use an instrument name other than '"+e.name+"'"}function TI(r,e){var t={name:e.name,type:e.type,unit:e.unit},n=JSON.stringify(t);return" - create a new view with a name other than '"+r.name+"' and InstrumentSelector '"+n+"'"}function vI(r,e){var t={name:e.name,type:e.type,unit:e.unit},n=JSON.stringify(t);return" - create a new view with a name other than '"+r.name+"' and InstrumentSelector '"+n+`'
|
|
7
|
-
- OR - create a new view with the name `+r.name+" and description '"+r.description+"' and InstrumentSelector "+n+`
|
|
8
|
-
- OR - create a new view with the name `+e.name+" and description '"+r.description+"' and InstrumentSelector "+n}function yd(r,e){return r.valueType!==e.valueType?bI(r,e):r.unit!==e.unit?EI(r,e):r.type!==e.type?TI(r,e):r.description!==e.description?vI(r,e):""}var bd=function(r){var e=typeof Symbol=="function"&&Symbol.iterator,t=e&&r[e],n=0;if(t)return t.call(r);if(r&&typeof r.length=="number")return{next:function(){return r&&n>=r.length&&(r=void 0),{value:r&&r[n++],done:!r}}};throw new TypeError(e?"Object is not iterable.":"Symbol.iterator is not defined.")},GS=function(){function r(){this._sharedRegistry=new Map,this._perCollectorRegistry=new Map}return r.create=function(){return new r},r.prototype.getStorages=function(e){var t,n,o,i,a=[];try{for(var s=bd(this._sharedRegistry.values()),c=s.next();!c.done;c=s.next()){var l=c.value;a=a.concat(l)}}catch(g){t={error:g}}finally{try{c&&!c.done&&(n=s.return)&&n.call(s)}finally{if(t)throw t.error}}var u=this._perCollectorRegistry.get(e);if(u!=null)try{for(var d=bd(u.values()),p=d.next();!p.done;p=d.next()){var l=p.value;a=a.concat(l)}}catch(g){o={error:g}}finally{try{p&&!p.done&&(i=d.return)&&i.call(d)}finally{if(o)throw o.error}}return a},r.prototype.register=function(e){this._registerStorage(e,this._sharedRegistry)},r.prototype.registerForCollector=function(e,t){var n=this._perCollectorRegistry.get(e);n==null&&(n=new Map,this._perCollectorRegistry.set(e,n)),this._registerStorage(t,n)},r.prototype.findOrUpdateCompatibleStorage=function(e){var t=this._sharedRegistry.get(e.name);return t===void 0?null:this._findOrUpdateCompatibleStorage(e,t)},r.prototype.findOrUpdateCompatibleCollectorStorage=function(e,t){var n=this._perCollectorRegistry.get(e);if(n===void 0)return null;var o=n.get(t.name);return o===void 0?null:this._findOrUpdateCompatibleStorage(t,o)},r.prototype._registerStorage=function(e,t){var n=e.getInstrumentDescriptor(),o=t.get(n.name);if(o===void 0){t.set(n.name,[e]);return}o.push(e)},r.prototype._findOrUpdateCompatibleStorage=function(e,t){var n,o,i=null;try{for(var a=bd(t),s=a.next();!s.done;s=a.next()){var c=s.value,l=c.getInstrumentDescriptor();Zf(l,e)?(l.description!==e.description&&(e.description.length>l.description.length&&c.updateDescription(e.description),W.warn("A view or instrument with the name ",e.name,` has already been registered, but has a different description and is incompatible with another registered view.
|
|
9
|
-
`,`Details:
|
|
10
|
-
`,Sd(l,e),`The longer description will be used.
|
|
11
|
-
To resolve the conflict:`,yd(l,e))),i=c):W.warn("A view or instrument with the name ",e.name,` has already been registered and is incompatible with another registered view.
|
|
12
|
-
`,`Details:
|
|
13
|
-
`,Sd(l,e),`To resolve the conflict:
|
|
14
|
-
`,yd(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},r}();var jS=function(){function r(e){this._backingStorages=e}return r.prototype.record=function(e,t,n,o){this._backingStorages.forEach(function(i){i.record(e,t,n,o)})},r}();Ce();Ce();var VS=function(){function r(e,t){this._instrumentName=e,this._valueType=t,this._buffer=new pr}return r.prototype.observe=function(e,t){if(t===void 0&&(t={}),typeof e!="number"){W.warn("non-number value provided to metric "+this._instrumentName+": "+e);return}this._valueType===Ht.INT&&!Number.isInteger(e)&&(W.warn("INT value type cannot accept a floating-point value for "+this._instrumentName+", ignoring the fractional digits."),e=Math.trunc(e),!Number.isInteger(e))||this._buffer.set(t,e)},r}();var WS=function(){function r(){this._buffer=new Map}return r.prototype.observe=function(e,t,n){if(n===void 0&&(n={}),!!ta(e)){var o=this._buffer.get(e);if(o==null&&(o=new pr,this._buffer.set(e,o)),typeof t!="number"){W.warn("non-number value provided to metric "+e._descriptor.name+": "+t);return}e._descriptor.valueType===Ht.INT&&!Number.isInteger(t)&&(W.warn("INT value type cannot accept a floating-point value for "+e._descriptor.name+", ignoring the fractional digits."),t=Math.trunc(t),!Number.isInteger(t))||o.set(n,t)}},r}();var Ed=function(r,e,t,n){function o(i){return i instanceof t?i:new t(function(a){a(i)})}return new(t||(t=Promise))(function(i,a){function 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(r,e||[])).next())})},Td=function(r,e){var t={label:0,sent:function(){if(i[0]&1)throw i[1];return i[1]},trys:[],ops:[]},n,o,i,a;return a={next: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(;t;)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 t.label++,{value:l[1],done:!1};case 5:t.label++,o=l[1],l=[0];continue;case 7:l=t.ops.pop(),t.trys.pop();continue;default:if(i=t.trys,!(i=i.length>0&&i[i.length-1])&&(l[0]===6||l[0]===2)){t=0;continue}if(l[0]===3&&(!i||l[1]>i[0]&&l[1]<i[3])){t.label=l[1];break}if(l[0]===6&&t.label<i[1]){t.label=i[1],i=l;break}if(i&&t.label<i[2]){t.label=i[2],t.ops.push(l);break}i[2]&&t.ops.pop(),t.trys.pop();continue}l=e.call(r,t)}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}}},$S=function(r,e){var t=typeof Symbol=="function"&&r[Symbol.iterator];if(!t)return r;var n=t.call(r),o,i=[],a;try{for(;(e===void 0||e-- >0)&&!(o=n.next()).done;)i.push(o.value)}catch(s){a={error:s}}finally{try{o&&!o.done&&(t=n.return)&&t.call(n)}finally{if(a)throw a.error}}return i},qS=function(r,e,t){if(t||arguments.length===2)for(var n=0,o=e.length,i;n<o;n++)(i||!(n in e))&&(i||(i=Array.prototype.slice.call(e,0,n)),i[n]=e[n]);return r.concat(i||Array.prototype.slice.call(e))},KS=function(){function r(){this._callbacks=[],this._batchCallbacks=[]}return r.prototype.addCallback=function(e,t){var n=this._findCallback(e,t);n>=0||this._callbacks.push({callback:e,instrument:t})},r.prototype.removeCallback=function(e,t){var n=this._findCallback(e,t);n<0||this._callbacks.splice(n,1)},r.prototype.addBatchCallback=function(e,t){var n=new Set(t.filter(ta));if(n.size===0){W.error("BatchObservableCallback is not associated with valid instruments",t);return}var o=this._findBatchCallback(e,n);o>=0||this._batchCallbacks.push({callback:e,instruments:n})},r.prototype.removeBatchCallback=function(e,t){var n=new Set(t.filter(ta)),o=this._findBatchCallback(e,n);o<0||this._batchCallbacks.splice(o,1)},r.prototype.observe=function(e,t){return Ed(this,void 0,void 0,function(){var n,o,i,a;return Td(this,function(s){switch(s.label){case 0:return n=this._observeCallbacks(e,t),o=this._observeBatchCallbacks(e,t),[4,$f(qS(qS([],$S(n),!1),$S(o),!1))];case 1:return i=s.sent(),a=i.filter(qf).map(function(c){return c.reason}),[2,a]}})})},r.prototype._observeCallbacks=function(e,t){var n=this;return this._callbacks.map(function(o){var i=o.callback,a=o.instrument;return Ed(n,void 0,void 0,function(){var s,c;return Td(this,function(l){switch(l.label){case 0:return s=new VS(a._descriptor.name,a._descriptor.valueType),c=Promise.resolve(i(s)),t!=null&&(c=sn(c,t)),[4,c];case 1:return l.sent(),a._metricStorages.forEach(function(u){u.record(s._buffer,e)}),[2]}})})})},r.prototype._observeBatchCallbacks=function(e,t){var n=this;return this._batchCallbacks.map(function(o){var i=o.callback,a=o.instruments;return Ed(n,void 0,void 0,function(){var s,c;return Td(this,function(l){switch(l.label){case 0:return s=new WS,c=Promise.resolve(i(s)),t!=null&&(c=sn(c,t)),[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]}})})})},r.prototype._findCallback=function(e,t){return this._callbacks.findIndex(function(n){return n.callback===e&&n.instrument===t})},r.prototype._findBatchCallback=function(e,t){return this._batchCallbacks.findIndex(function(n){return n.callback===e&&Kf(n.instruments,t)})},r}();var AI=function(){var r=function(e,t){return r=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(n,o){n.__proto__=o}||function(n,o){for(var i in o)Object.prototype.hasOwnProperty.call(o,i)&&(n[i]=o[i])},r(e,t)};return function(e,t){if(typeof t!="function"&&t!==null)throw new TypeError("Class extends value "+String(t)+" is not a constructor or null");r(e,t);function n(){this.constructor=e}e.prototype=t===null?Object.create(t):(n.prototype=t.prototype,new n)}}(),YS=function(r){AI(e,r);function e(t,n,o,i,a){var s=r.call(this,t)||this;return s._attributesProcessor=o,s._aggregationCardinalityLimit=a,s._deltaMetricStorage=new rl(n,s._aggregationCardinalityLimit),s._temporalMetricStorage=new nl(n,i),s}return e.prototype.record=function(t,n,o,i){n=this._attributesProcessor.process(n,o),this._deltaMetricStorage.record(t,n,o,i)},e.prototype.collect=function(t,n){var o=this._deltaMetricStorage.collect();return this._temporalMetricStorage.buildMetrics(t,this._instrumentDescriptor,o,n)},e}(tl);var XS=function(){var r=function(e,t){return r=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(n,o){n.__proto__=o}||function(n,o){for(var i in o)Object.prototype.hasOwnProperty.call(o,i)&&(n[i]=o[i])},r(e,t)};return function(e,t){if(typeof t!="function"&&t!==null)throw new TypeError("Class extends value "+String(t)+" is not a constructor or null");r(e,t);function n(){this.constructor=e}e.prototype=t===null?Object.create(t):(n.prototype=t.prototype,new n)}}(),zo=function(){function r(){}return r.Noop=function(){return RI},r}();var wI=function(r){XS(e,r);function e(){return r!==null&&r.apply(this,arguments)||this}return e.prototype.process=function(t,n){return t},e}(zo);var JS=function(r){XS(e,r);function e(t){var n=r.call(this)||this;return n._allowedAttributeNames=t,n}return e.prototype.process=function(t,n){var o=this,i={};return Object.keys(t).filter(function(a){return o._allowedAttributeNames.includes(a)}).forEach(function(a){return i[a]=t[a]}),i},e}(zo);var RI=new wI;var CI=function(r,e,t,n){function o(i){return i instanceof t?i:new t(function(a){a(i)})}return new(t||(t=Promise))(function(i,a){function 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(r,e||[])).next())})},xI=function(r,e){var t={label:0,sent:function(){if(i[0]&1)throw i[1];return i[1]},trys:[],ops:[]},n,o,i,a;return a={next: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(;t;)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 t.label++,{value:l[1],done:!1};case 5:t.label++,o=l[1],l=[0];continue;case 7:l=t.ops.pop(),t.trys.pop();continue;default:if(i=t.trys,!(i=i.length>0&&i[i.length-1])&&(l[0]===6||l[0]===2)){t=0;continue}if(l[0]===3&&(!i||l[1]>i[0]&&l[1]<i[3])){t.label=l[1];break}if(l[0]===6&&t.label<i[1]){t.label=i[1],i=l;break}if(i&&t.label<i[2]){t.label=i[2],t.ops.push(l);break}i[2]&&t.ops.pop(),t.trys.pop();continue}l=e.call(r,t)}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}}},_I=function(r,e){var t=typeof Symbol=="function"&&r[Symbol.iterator];if(!t)return r;var n=t.call(r),o,i=[],a;try{for(;(e===void 0||e-- >0)&&!(o=n.next()).done;)i.push(o.value)}catch(s){a={error:s}}finally{try{o&&!o.done&&(t=n.return)&&t.call(n)}finally{if(a)throw a.error}}return i},ZS=function(){function r(e,t){this._meterProviderSharedState=e,this._instrumentationScope=t,this.metricStorageRegistry=new GS,this.observableRegistry=new KS,this.meter=new FS(this)}return r.prototype.registerMetricStorage=function(e){var t=this._registerMetricStorage(e,YS);return t.length===1?t[0]:new jS(t)},r.prototype.registerAsyncMetricStorage=function(e){var t=this._registerMetricStorage(e,HS);return t},r.prototype.collect=function(e,t,n){return CI(this,void 0,void 0,function(){var o,i,a;return xI(this,function(s){switch(s.label){case 0:return[4,this.observableRegistry.observe(t,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,t)}).filter(Vf),a.length===0?[2,{errors:o}]:[2,{scopeMetrics:{scope:this._instrumentationScope,metrics:a},errors:o}])}})})},r.prototype._registerMetricStorage=function(e,t){var n=this,o=this._meterProviderSharedState.viewRegistry.findViews(e,this._instrumentationScope),i=o.map(function(c){var l=Jf(c,e),u=n.metricStorageRegistry.findOrUpdateCompatibleStorage(l);if(u!=null)return u;var d=c.aggregation.createAggregator(l),p=new t(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=_I(c,2),u=l[0],d=l[1],p=n.metricStorageRegistry.findOrUpdateCompatibleCollectorStorage(u,e);if(p!=null)return p;var g=d.createAggregator(e),m=u.selectCardinalityLimit(e.type),h=new t(e,g,zo.Noop(),[u],m);return n.metricStorageRegistry.registerForCollector(u,h),h});i=i.concat(s)}return i},r}();var MI=function(r){var e=typeof Symbol=="function"&&Symbol.iterator,t=e&&r[e],n=0;if(t)return t.call(r);if(r&&typeof r.length=="number")return{next:function(){return r&&n>=r.length&&(r=void 0),{value:r&&r[n++],done:!r}}};throw new TypeError(e?"Object is not iterable.":"Symbol.iterator is not defined.")},QS=function(){function r(e){this.resource=e,this.viewRegistry=new IS,this.metricCollectors=[],this.meterSharedStates=new Map}return r.prototype.getMeterSharedState=function(e){var t=Wf(e),n=this.meterSharedStates.get(t);return n==null&&(n=new ZS(this,e),this.meterSharedStates.set(t,n)),n},r.prototype.selectAggregations=function(e){var t,n,o=[];try{for(var i=MI(this.metricCollectors),a=i.next();!a.done;a=i.next()){var s=a.value;o.push([s,s.selectAggregation(e)])}}catch(c){t={error:c}}finally{try{a&&!a.done&&(n=i.return)&&n.call(i)}finally{if(t)throw t.error}}return o},r}();var ol=function(r,e,t,n){function o(i){return i instanceof t?i:new t(function(a){a(i)})}return new(t||(t=Promise))(function(i,a){function 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(r,e||[])).next())})},il=function(r,e){var t={label:0,sent:function(){if(i[0]&1)throw i[1];return i[1]},trys:[],ops:[]},n,o,i,a;return a={next: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(;t;)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 t.label++,{value:l[1],done:!1};case 5:t.label++,o=l[1],l=[0];continue;case 7:l=t.ops.pop(),t.trys.pop();continue;default:if(i=t.trys,!(i=i.length>0&&i[i.length-1])&&(l[0]===6||l[0]===2)){t=0;continue}if(l[0]===3&&(!i||l[1]>i[0]&&l[1]<i[3])){t.label=l[1];break}if(l[0]===6&&t.label<i[1]){t.label=i[1],i=l;break}if(i&&t.label<i[2]){t.label=i[2],t.ops.push(l);break}i[2]&&t.ops.pop(),t.trys.pop();continue}l=e.call(r,t)}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}}},II=function(r,e){var t=typeof Symbol=="function"&&r[Symbol.iterator];if(!t)return r;var n=t.call(r),o,i=[],a;try{for(;(e===void 0||e-- >0)&&!(o=n.next()).done;)i.push(o.value)}catch(s){a={error:s}}finally{try{o&&!o.done&&(t=n.return)&&t.call(n)}finally{if(a)throw a.error}}return i},PI=function(r,e,t){if(t||arguments.length===2)for(var n=0,o=e.length,i;n<o;n++)(i||!(n in e))&&(i||(i=Array.prototype.slice.call(e,0,n)),i[n]=e[n]);return r.concat(i||Array.prototype.slice.call(e))},ey=function(){function r(e,t){this._sharedState=e,this._metricReader=t}return r.prototype.collect=function(e){return ol(this,void 0,void 0,function(){var t,n,o,i,a=this;return il(this,function(s){switch(s.label){case 0:return t=Gn(Date.now()),n=[],o=[],i=Array.from(this._sharedState.meterSharedStates.values()).map(function(c){return ol(a,void 0,void 0,function(){var l;return il(this,function(u){switch(u.label){case 0:return[4,c.collect(this,t,e)];case 1:return l=u.sent(),l?.scopeMetrics!=null&&n.push(l.scopeMetrics),l?.errors!=null&&o.push.apply(o,PI([],II(l.errors),!1)),[2]}})})}),[4,Promise.all(i)];case 1:return s.sent(),[2,{resourceMetrics:{resource:this._sharedState.resource,scopeMetrics:n},errors:o}]}})})},r.prototype.forceFlush=function(e){return ol(this,void 0,void 0,function(){return il(this,function(t){switch(t.label){case 0:return[4,this._metricReader.forceFlush(e)];case 1:return t.sent(),[2]}})})},r.prototype.shutdown=function(e){return ol(this,void 0,void 0,function(){return il(this,function(t){switch(t.label){case 0:return[4,this._metricReader.shutdown(e)];case 1:return t.sent(),[2]}})})},r.prototype.selectAggregationTemporality=function(e){return this._metricReader.selectAggregationTemporality(e)},r.prototype.selectAggregation=function(e){return this._metricReader.selectAggregation(e)},r.prototype.selectCardinalityLimit=function(e){var t,n,o;return(o=(n=(t=this._metricReader).selectCardinalityLimit)===null||n===void 0?void 0:n.call(t,e))!==null&&o!==void 0?o:2e3},r}();var ty=function(r,e,t,n){function o(i){return i instanceof t?i:new t(function(a){a(i)})}return new(t||(t=Promise))(function(i,a){function 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(r,e||[])).next())})},ry=function(r,e){var t={label:0,sent:function(){if(i[0]&1)throw i[1];return i[1]},trys:[],ops:[]},n,o,i,a;return a={next: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(;t;)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 t.label++,{value:l[1],done:!1};case 5:t.label++,o=l[1],l=[0];continue;case 7:l=t.ops.pop(),t.trys.pop();continue;default:if(i=t.trys,!(i=i.length>0&&i[i.length-1])&&(l[0]===6||l[0]===2)){t=0;continue}if(l[0]===3&&(!i||l[1]>i[0]&&l[1]<i[3])){t.label=l[1];break}if(l[0]===6&&t.label<i[1]){t.label=i[1],i=l;break}if(i&&t.label<i[2]){t.label=i[2],t.ops.push(l);break}i[2]&&t.ops.pop(),t.trys.pop();continue}l=e.call(r,t)}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}}},ny=function(r){var e=typeof Symbol=="function"&&Symbol.iterator,t=e&&r[e],n=0;if(t)return t.call(r);if(r&&typeof r.length=="number")return{next:function(){return r&&n>=r.length&&(r=void 0),{value:r&&r[n++],done:!r}}};throw new TypeError(e?"Object is not iterable.":"Symbol.iterator is not defined.")};function OI(r,e){var t=e??Zs.empty();return r?Zs.default().merge(t):t}var vd=function(){function r(e){var t,n,o,i,a;if(this._shutdown=!1,this._sharedState=new QS(OI((a=e?.mergeResourceWithDefaults)!==null&&a!==void 0?a:!0,e?.resource)),e?.views!=null&&e.views.length>0)try{for(var s=ny(e.views),c=s.next();!c.done;c=s.next()){var l=c.value;this._sharedState.viewRegistry.addView(l)}}catch(g){t={error:g}}finally{try{c&&!c.done&&(n=s.return)&&n.call(s)}finally{if(t)throw t.error}}if(e?.readers!=null&&e.readers.length>0)try{for(var u=ny(e.readers),d=u.next();!d.done;d=u.next()){var p=d.value;this.addMetricReader(p)}}catch(g){o={error:g}}finally{try{d&&!d.done&&(i=u.return)&&i.call(u)}finally{if(o)throw o.error}}}return r.prototype.getMeter=function(e,t,n){return t===void 0&&(t=""),n===void 0&&(n={}),this._shutdown?(W.warn("A shutdown MeterProvider cannot provide a Meter"),xu()):this._sharedState.getMeterSharedState({name:e,version:t,schemaUrl:n.schemaUrl}).meter},r.prototype.addMetricReader=function(e){var t=new ey(this._sharedState,e);e.setMetricProducer(t),this._sharedState.metricCollectors.push(t)},r.prototype.shutdown=function(e){return ty(this,void 0,void 0,function(){return ry(this,function(t){switch(t.label){case 0:return this._shutdown?(W.warn("shutdown may only be called once per MeterProvider"),[2]):(this._shutdown=!0,[4,Promise.all(this._sharedState.metricCollectors.map(function(n){return n.shutdown(e)}))]);case 1:return t.sent(),[2]}})})},r.prototype.forceFlush=function(e){return ty(this,void 0,void 0,function(){return ry(this,function(t){switch(t.label){case 0:return this._shutdown?(W.warn("invalid attempt to force flush after MeterProvider shutdown"),[2]):[4,Promise.all(this._sharedState.metricCollectors.map(function(n){return n.forceFlush(e)}))];case 1:return t.sent(),[2]}})})},r}();var LI=/[\^$\\.+?()[\]{}|]/g,al=function(){function r(e){e==="*"?(this._matchAll=!0,this._regexp=/.*/):(this._matchAll=!1,this._regexp=new RegExp(r.escapePattern(e)))}return r.prototype.match=function(e){return this._matchAll?!0:this._regexp.test(e)},r.escapePattern=function(e){return"^"+e.replace(LI,"\\$&").replace("*",".*")+"$"},r.hasWildcard=function(e){return e.includes("*")},r}();var Ho=function(){function r(e){this._matchAll=e===void 0,this._pattern=e}return r.prototype.match=function(e){return!!(this._matchAll||e===this._pattern)},r}();var oy=function(){function r(e){var t;this._nameFilter=new al((t=e?.name)!==null&&t!==void 0?t:"*"),this._type=e?.type,this._unitFilter=new Ho(e?.unit)}return r.prototype.getType=function(){return this._type},r.prototype.getNameFilter=function(){return this._nameFilter},r.prototype.getUnitFilter=function(){return this._unitFilter},r}();var iy=function(){function r(e){this._nameFilter=new Ho(e?.name),this._versionFilter=new Ho(e?.version),this._schemaUrlFilter=new Ho(e?.schemaUrl)}return r.prototype.getNameFilter=function(){return this._nameFilter},r.prototype.getVersionFilter=function(){return this._versionFilter},r.prototype.getSchemaUrlFilter=function(){return this._schemaUrlFilter},r}();function NI(r){return r.instrumentName==null&&r.instrumentType==null&&r.instrumentUnit==null&&r.meterName==null&&r.meterVersion==null&&r.meterSchemaUrl==null}var Ad=function(){function r(e){var t;if(NI(e))throw new Error("Cannot create view with no selector arguments supplied");if(e.name!=null&&(e?.instrumentName==null||al.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 JS(e.attributeKeys):this.attributesProcessor=zo.Noop(),this.name=e.name,this.description=e.description,this.aggregation=(t=e.aggregation)!==null&&t!==void 0?t:Xt.Default(),this.instrumentSelector=new oy({name:e.instrumentName,type:e.instrumentType,unit:e.instrumentUnit}),this.meterSelector=new iy({name:e.meterName,version:e.meterVersion,schemaUrl:e.meterSchemaUrl}),this.aggregationCardinalityLimit=e.aggregationCardinalityLimit}return r}();var cY=process.env.APP||"unknown";Ce();import{v4 as kI}from"uuid";function DI(){return new Hf({url:"https://us-west.metrics.momentic.ai/v1/metrics",headers:{"x-momentic-metrics-api-key":"c60c6a0f-60da-41a7-a61b-07969a0aa303"},temporalityPreference:zn.DELTA})}var UI=[new Ad({instrumentName:"test_operation_duration_ms",instrumentType:pe.HISTOGRAM,aggregation:new Ks([100,500,1e3,5e3,1e4,2e4])})],sl=class{globalAttributes;provider;meter;counterCache=new Map;histogramCache=new Map;observableGaugeCache=new Map;gaugeValues=new Map;getCounter(e){let t=this.counterCache.get(e);if(t)return t;let n=this.meter.createCounter(e);return this.counterCache.set(e,n),n}getHistogram(e){let t=this.histogramCache.get(e);if(t)return t;let n=this.meter.createHistogram(e);return this.histogramCache.set(e,n),n}ensureObservableGauge(e){let t=this.observableGaugeCache.get(e);if(t)return t;let n=this.meter.createObservableGauge(e);return n.addCallback(o=>{let i=this.gaugeValues.get(e);i!==void 0&&o.observe(i,this.globalAttributes)}),this.observableGaugeCache.set(e,n),n}constructor(e){this.globalAttributes={...e.globalAttributes??{}};let t=typeof process<"u"?"production":"unknown",n=new Wu({[Rs]:e.serviceName,[Dh]:t,[Fh]:typeof process<"u"&&process.env.SERVICE_INSTANCE_ID?process.env.SERVICE_INSTANCE_ID:kI()}),o=DI(),i=new hd({exporter:o,exportIntervalMillis:e.exportIntervalMs??15e3});this.provider=new vd({resource:n,readers:[i],views:UI}),Ts.setGlobalMeterProvider(this.provider),this.meter=Ts.getMeter("momentic-serverless")}increment(e,t,n){try{let o=ys(n,this.globalAttributes);this.getCounter(e).add(typeof t=="number"?t:1,o)}catch{}}gauge(e,t){try{this.ensureObservableGauge(e),this.gaugeValues.set(e,t)}catch{}}distribution(e,t,n){try{let o=ys(n,this.globalAttributes);this.getHistogram(e).record(t,o)}catch{}}async flush(){try{await this.provider.forceFlush()}catch{}}async recordDuration({fn:e,name:t,tags:n}){let o=Date.now();try{return await Promise.resolve(e())}finally{this.distribution(t,Date.now()-o,n)}}};var St=new Ss;function ay(r){r.disabled||(St=new sl(r))}import{hostname as zI}from"os";import HI from"path";async function sy(r){let{apiClient:e,logger:t,creationOpts:n,onStatusUpdate:o,logLevel:i,orgId:a}=r,{token:s,webRtcUrl:c,adbUrl:l,name:u,apkDownloadUrl:d,region:p}=await e.createAndroidEmulator({...n,hostname:zI()}),g;try{BI("adb --version"),g="adb"}catch{if(process.env.ANDROID_HOME)g=HI.join(process.env.ANDROID_HOME,"platform-tools","adb");else throw new Error("The adb binary was not found in PATH and ANDROID_HOME is not set either")}t.info({emulatorName:u,apkToInstall:n.apkToInstall,region:p,apkDownloadUrl:d},"Android instance creation ok");let m=await St.recordDuration({fn:async()=>await FI({adbUrl:l,endpointUrl:c,token:s,logLevel:i,adbPath:g}),name:"test_event_duration",tags:["name:limbar-client-creation",`orgId:${a}`]}),h=["https://github.com/appium/appium-uiautomator2-server/releases/download/v7.6.2/appium-uiautomator2-server-v7.6.2.apk","https://github.com/appium/appium-uiautomator2-server/releases/download/v7.6.2/appium-uiautomator2-server-debug-androidTest.apk","https://github.com/appium/io.appium.settings/releases/download/v5.14.15/settings_apk-debug.apk"];d&&h.push(d);let f=n.apkToInstall?.channel,E=n.apkToInstall?.tag;o(`Installing APK${f?` with channel ${f}`:""}${E?` and tag ${E}`:""}`),await Promise.all(h.map(A=>m.sendAsset(A))),o("Starting tunnel");let S=await St.recordDuration({fn:async()=>await m.startAdbTunnel(),name:"test_event_duration",tags:["name:limbar-tunnel-connect",`orgId:${a}`]});return{port:S.address.port,close:S.close,token:s,webRtcUrl:c,emulatorName:u}}async function ll({onStatusUpdate:r,creationOpts:e,apiClient:t,logger:n,driverLogLevel:o,appiumPort:i,socket:a,orgId:s}){let c=Date.now(),{close:l,port:u,limbarToken:d,limbarUrl:p,emulatorName:g}=await qI({apiClient:t,logger:n,creationOpts:e,onStatusUpdate:r,orgId:s}),m=[()=>t.deleteAndroidEmulator(g),l],h=async()=>{for(let E=m.length-1;E>=0;E-=1)try{await m[E]()}catch(S){if(S instanceof Error&&S.message.includes("ECONNREFUSED"))return;n.warn({err:S},"Error running cleanup task")}},f=async()=>{if(a&&!a.connected)throw await h(),new Error("Client disconnected before Appium driver could be started")};await f();try{let E=await WI({logger:n,driverLogLevel:o,appiumPort:i,port:u,limbarStart:c,emulatorName:g,apiClient:t,onStatusUpdate:r,creationOpts:e,orgId:s});return m.push(E.appiumClose),m.push(async()=>E.driver.deleteSession()),await f(),{...E,emulatorName:g,limbarToken:d,limbarUrl:p,adbTunnelPort:u,cleanup:h,appiumPort:i}}catch(E){throw await h(),new Error(`Failed to start Appium driver: ${E}`)}}async function WI({logger:r,driverLogLevel:e="warn",port:t,limbarStart:n,emulatorName:o,appiumPort:i,orgId:a}){let s=Date.now(),{close:c,logFile:l}=await $I({logger:r,logLevel:e,appiumPort:i}),u={platformName:"Android","appium:automationName":"UiAutomator2","appium:deviceName":"Android","appium:udid":`127.0.0.1:${t}`,"appium:adbExecTimeout":3e4,"appium:newCommandTimeout":600,"appium:skipDeviceInitialization":!0,"appium:skipServerInstallation":!0,"appium:androidInstallTimeout":6e4,"appium:autoWebview":!1,"appium:autoWebviewTimeout":0,"appium:clearDeviceLogsOnStart":!0},d={hostname:"localhost",port:i,logLevel:e,capabilities:u,connectionRetryTimeout:3e4,connectionRetryCount:2},p=Date.now(),g=await VI(d);await g.updateSettings({enableMultiWindows:!0});let m=new Map;return g.on("command",h=>{m.set(h.command,Date.now())}),g.on("result",h=>{let f=m.get(h.command);if(!f)return;let E=Date.now()-f;h.result instanceof Error?r.warn({err:h.result,command:h.command,args:h.body,durationMs:E},"Appium cmd failed"):E>1e4&&r.warn({command:h.command,args:h.body,durationMs:E},"Appium cmd took very long"),m.delete(h.command)}),r.info({timings:{limbarDuration:s-n,appiumDuration:p-s,wdioDuration:Date.now()-p},capabilities:u,emulatorName:o},"Started Appium driver"),{driver:g,appiumClose:c,appiumPort:i,appiumLogFile:l}}async function $I({logger:r,logLevel:e,appiumPort:t}){let n=`${jI()}/appium-port-${Date.now()}.log`,o=await GI.main({port:t,address:"localhost",relaxedSecurityEnabled:!0,longStacktrace:e==="debug",logFormat:"json",loglevel:e,logFile:n});return{logFile:n,close:async()=>{await o.close()}}}async function qI({apiClient:r,logger:e,onStatusUpdate:t,creationOpts:n,orgId:o}){let{close:i,port:a,token:s,webRtcUrl:c,emulatorName:l}=await sy({apiClient:r,logger:e,creationOpts:n,onStatusUpdate:t,orgId:o});return{port:a,close:i,limbarToken:s,limbarUrl:c,emulatorName:l}}import ly from"crypto";import KI from"fs";async function cl({tag:r,channel:e,filePath:t,apiClient:n,logger:o}){let i=await KI.promises.readFile(t),a=ly.createHash("md5").update(i).digest("base64"),s=ly.createHash("md5").update(i).digest("hex"),c=await n.generateAndroidAssetUrls({channel:e,tag:r??"latest",md5:a});if(c.md5&&(c.md5===a||c.md5===s)){o.info({channel:e,tag:r,md5:a,md5Hex:s},`Asset ${t} already exists on emulator platform`);return}if(c.uploadUrl){o.info({channel:e,tag:r,md5:a,uploadUrl:c.uploadUrl},`Uploading asset ${t} to emulator platform...`);try{let l=await fetch(c.uploadUrl,{headers:{"Content-Length":i.length.toString(),"Content-Type":"application/octet-stream"},method:"PUT",body:i});if(l.status!==200)throw new Error(`Got error response from emulator platform: ${l.status} ${await l.text()}`);o.info({channel:e,tag:r,md5:a},`Asset ${t} was uploaded successfully!`);return}catch(l){try{await n.deleteAndroidAsset(e,r??"latest")}catch(u){o.warn({err:u,tag:r,channel:e},"Failed to cleanup asset metadata for failed upload. Please contact Momentic support.")}throw o.error({err:l},"Failed to upload asset"),l}}throw new Error(`No upload URL was given for asset ${t}`)}import{execSync as QT}from"child_process";import{existsSync as sk}from"fs";import{platform as ev}from"os";import{dirname as lk,join as ck,resolve as uk}from"path";import{z as cy}from"zod";var JY=cy.object({input:cy.string()});import{z as rt}from"zod";var e5=rt.object({srcs:rt.array(rt.string()),urls:rt.array(rt.string()),desiredSrc:rt.string().optional(),desiredUrl:rt.string().optional()}),uy=rt.object({srcRegex:rt.string().optional(),urlRegex:rt.string().optional()}),dy=rt.object({x:rt.number(),y:rt.number(),correlation:rt.number()}),t5=rt.object({searchImageBase64String:rt.string(),pageImageBase64String:rt.string(),id:rt.string().uuid(),timeoutMs:rt.number().max(1e4).min(0).optional()});import{z as L}from"zod";import*as F from"zod";import{extendZodWithOpenApi as YI}from"zod-openapi";YI(F);var un=(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))(un||{}),XI=F.object({mPathSelectorTokens:F.string().array(),frameSrcRegex:F.string().optional(),frameUrlRegex:F.string().optional(),indices:F.number().array()}),wd=F.object({result:F.number(),traceId:F.string()}).array(),ul=F.object({type:F.literal("GCS_TRACES"),traces:wd}),py=F.object({text:F.string().optional(),attributes:F.record(F.string(),F.string()).optional(),boundingBox:F.object({x:F.number(),y:F.number(),width:F.number(),height:F.number()}).optional()}),JI=F.object({selectors:F.string().array(),requirements:py.optional()}),dn=F.object({id:F.number().int(),dataMomenticId:F.number().int().optional(),selector:F.string().optional(),hybridSelector:F.object({textContent:F.string().nullish(),attributes:F.record(F.string(),F.string().optional()),tagName:F.string(),expandShadowRoot:F.boolean().optional(),classNames:F.string().array(),nthChild:F.number()}).array().optional(),generatedSelectors:F.string().array().optional(),requirements:py.optional(),additionalElements:JI.array().optional(),role:F.string().optional(),name:F.string().optional(),numChildren:F.number().optional(),content:F.string().optional(),pathFromRoot:F.string().optional(),serializedHtml:F.string().optional().describe("pruned html including 1 neighbor and 1 layer of children. value for text inputs pruned."),nodeOnlySerializedHtml:F.string().optional().describe("outerHtml of the element without any children. value for text inputs pruned."),screenshotUrl:F.string().url().optional(),boundingBox:F.object({x:F.number().optional(),y:F.number().optional(),width:F.number(),height:F.number()}).describe("css pixel bounding box").optional(),frameCache:XI.optional(),inputDescription:F.string().optional().describe("the description that generated this cache"),targetSource:F.nativeEnum(un).optional(),targetUpdateTime:F.string().optional(),targetUpdateLoggerTags:F.record(F.string(),F.string()).optional(),cacheResolutionUpdateSource:F.string().optional(),cacheResolutionUpdateTime:F.string().optional(),cacheResolutionUpdateLoggerTags:F.record(F.string(),F.string()).optional(),memory:ul.optional()}).openapi({ref:"ElementTargetCache"});function dl(r){return!!(r.serializedHtml||r.screenshotUrl||r.generatedSelectors||r.hybridSelector)}var ZI=F.object({type:F.literal("description"),elementDescriptor:F.string().describe("Description of the element.")}).openapi({ref:"DescriptionTarget"}),QI=F.object({x:F.number(),y:F.number()}),eP=F.object({type:F.literal("coordinates"),pixels:QI}).openapi({ref:"CoordinatesTarget"});function pn(r){return r.type==="description"}function Mr(r){return r.type==="coordinates"}var yt=F.discriminatedUnion("type",[ZI,eP]).openapi({ref:"ElementTarget"});function Rd(r){if(!r)return!1;switch(r.type){case"description":return!!r.elementDescriptor}return!0}function my(r){return ul.safeParse(r).success}import{v4 as ye}from"uuid";import*as b from"zod";import{extendZodWithOpenApi as lP}from"zod-openapi";import{z as ne}from"zod";import{extendZodWithOpenApi as tP}from"zod-openapi";import{z as na}from"zod";import gy from"zod";var ra=gy.object({updatedAt:gy.coerce.date().optional()});var Cd=na.object({result:na.boolean(),traceId:na.string()}).array(),xd=na.object({type:na.literal("GCS_TRACES"),traces:Cd}),_d=ra.extend({memory:xd.optional()});tP(ne);var hy=ne.object({plan:ne.string().optional(),evidence:ne.string().optional(),thoughts:ne.string(),result:ne.boolean(),relevantElements:ne.array(ne.number()).optional(),updatedMemory:Cd.optional()}),$r=(o=>(o.CONTAINS="CONTAINS",o.STARTS_WITH="STARTS_WITH",o.EQUALS="EQUALS",o.EXISTS="EXISTS",o))($r||{});var rP=ne.object({type:ne.literal("ELEMENT_NAME"),negated:ne.boolean().optional(),operation:ne.nativeEnum($r),value:ne.string()}).openapi({ref:"ElementNameAssertion"}),nP=ne.object({type:ne.literal("ELEMENT_STYLE"),negated:ne.boolean().optional(),operation:ne.nativeEnum($r),property:ne.string(),value:ne.string()}).openapi({ref:"ElementStyleAssertion"}),oP=ne.object({type:ne.literal("ELEMENT_CONTENT"),negated:ne.boolean().optional(),operation:ne.nativeEnum($r),value:ne.string()}).openapi({ref:"ElementContentAssertion"}),iP=ne.object({type:ne.literal("ELEMENT_ATTRIBUTE"),negated:ne.boolean().optional(),operation:ne.nativeEnum($r),attr:ne.string(),value:ne.string()}).openapi({ref:"ElementAttributeValueAssertion"}),Wn=(i=>(i.EXISTS="EXISTS",i.VISIBLE="VISIBLE",i.ENABLED="ENABLED",i.EDITABLE="EDITABLE",i.FOCUSED="FOCUSED",i))(Wn||{}),aP=ne.object({type:ne.literal("ELEMENT_EXISTENCE"),negated:ne.boolean().optional(),condition:ne.nativeEnum(Wn).describe("Treated as the element exists AND is also ...")}).openapi({ref:"ElementExistenceAssertion"}),fy=ne.discriminatedUnion("type",[oP,iP,aP,rP,nP]).openapi({ref:"ManualElementAssertion"});var sP=ne.object({type:ne.literal("CONTENT"),negated:ne.boolean().optional(),value:ne.string()}).openapi({ref:"PageContentAssertion"}),Sy=ne.discriminatedUnion("type",[sP]).openapi({ref:"ManualPageAssertion"});import wt from"zod";var Md=wt.discriminatedUnion("type",[wt.object({type:wt.literal("SUBSTRING"),url:wt.string()}),wt.object({type:wt.literal("GLOB"),glob:wt.string()}),wt.object({type:wt.literal("REGEX"),regex:wt.string()}),wt.object({type:wt.literal("DOMAIN"),domain:wt.string()})]),oa=wt.object({urlMatcher:Md,method:wt.string().optional()});import{z as Se}from"zod";var Go=Se.object({url:Se.string(),method:Se.union([Se.literal("GET"),Se.literal("POST"),Se.literal("PUT"),Se.literal("DELETE"),Se.literal("PATCH")]),headers:Se.record(Se.string(),Se.string()).optional(),params:Se.record(Se.string(),Se.string()).optional(),body:Se.string().optional(),timeout:Se.number().int().optional().describe("Max seconds to wait for the request to complete")}),yy=Se.object({url:Se.string(),headers:Se.record(Se.string(),Se.string()).optional(),query:Se.string(),variables:Se.string().optional(),timeout:Se.number().int().optional().describe("Max seconds to wait for the request to complete")}),pl=Se.object({code:Se.string(),fragment:Se.boolean().optional().describe("Agents should not touch this unless explicitly told to"),environment:Se.union([Se.literal("NODE"),Se.literal("BROWSER")]).optional().describe("default NODE, Agents default to using node unless it is necessary to use browser"),timeout:Se.number().int().max(60).optional().describe("Max seconds for the code to complete")});var nt=(Y=>(Y.AI_EXTRACT="AI_EXTRACT",Y.AI_ASSERTION="AI_ASSERTION",Y.AUTH_LOAD="AUTH_LOAD",Y.AUTH_SAVE="AUTH_SAVE",Y.BLUR="BLUR",Y.CAPTCHA="CAPTCHA",Y.CLICK="CLICK",Y.COOKIE="COOKIE",Y.COPY="COPY",Y.DIALOG="DIALOG",Y.DRAG="DRAG",Y.ELEMENT_CHECK="ELEMENT_CHECK",Y.FILE_UPLOAD="FILE_UPLOAD",Y.FOCUS="FOCUS",Y.GO_BACK="GO_BACK",Y.GO_FORWARD="GO_FORWARD",Y.HOVER="HOVER",Y.JAVASCRIPT="JAVASCRIPT",Y.LOCAL_STORAGE="LOCAL_STORAGE",Y.MOUSE_DRAG="MOUSE_DRAG",Y.NAVIGATE="NAVIGATE",Y.NEW_TAB="NEW_TAB",Y.PAGE_CHECK="PAGE_CHECK",Y.PASTE="PASTE",Y.PRESS="PRESS",Y.KEY_DOWN="KEY_DOWN",Y.KEY_UP="KEY_UP",Y.REFRESH="REFRESH",Y.REQUEST="REQUEST",Y.GRAPHQL_REQUEST="GRAPHQL_REQUEST",Y.SCROLL_DOWN="SCROLL_DOWN",Y.SCROLL_UP="SCROLL_UP",Y.SCROLL_LEFT="SCROLL_LEFT",Y.SCROLL_RIGHT="SCROLL_RIGHT",Y.SELECT_OPTION="SELECT_OPTION",Y.SWITCH_TAB="TAB",Y.TYPE="TYPE",Y.VISUAL_DIFF="VISUAL_DIFF",Y.WAIT="WAIT",Y.WAIT_FOR_URL="WAIT_FOR_URL",Y.REGISTER_REQUEST_LISTENER="REGISTER_REQUEST_LISTENER",Y.AWAIT_LISTENER="AWAIT_LISTENER",Y.RECORD_REQUESTS="RECORD_REQUESTS",Y.GET_RECORDED_REQUESTS="GET_RECORDED_REQUESTS",Y.SET_HEADER="SET_HEADER",Y.MOCK_ROUTE="MOCK_ROUTE",Y.REMOVE_ROUTE_MOCK="REMOVE_ROUTE_MOCK",Y.OFFLINE_MODE="OFFLINE_MODE",Y.SUCCESS="SUCCESS",Y))(nt||{});lP(b);var q=b.object({thoughts:b.string().optional(),id:b.string().uuid().describe("unique identifier to this step, used for step cache")}),Jt=b.object({useSelector:b.boolean().optional(),force:b.boolean().optional(),disableCache:b.boolean().optional().describe("disable element caching for this step"),iframeUrl:b.string().optional().describe("url or url regex for the iframe")}).openapi({ref:"CommonTargetingOptions"}),Zt=ra.extend({target:dn}).optional().openapi({ref:"SingleTargetCache"});function by(r){return Zt.safeParse(r).success}var ml=b.object({loadTimeout:b.number().int().max(60).optional().describe("Max seconds for the page to load")}),cP=q.merge(ml).merge(b.object({type:b.literal("NAVIGATE"),url:b.string()})).openapi({ref:"NavigateCommand"}),gl=Jt.merge(b.object({cache:Zt})),jo=q.merge(gl.merge(b.object({target:yt.optional(),type:b.literal("SCROLL_UP"),deltaY:b.number().optional()}))).openapi({ref:"ScrollUpCommand"}),Vo=q.merge(gl.merge(b.object({target:yt.optional(),type:b.literal("SCROLL_DOWN"),deltaY:b.number().optional()}))).openapi({ref:"ScrollDownCommand"}),Wo=q.merge(gl.merge(b.object({target:yt.optional(),type:b.literal("SCROLL_LEFT"),deltaX:b.number().optional()}))).openapi({ref:"ScrollLeftCommand"}),$o=q.merge(gl.merge(b.object({target:yt.optional(),type:b.literal("SCROLL_RIGHT"),deltaX:b.number().optional()}))).openapi({ref:"ScrollRightCommand"}),P5=b.discriminatedUnion("type",[jo,Vo,Wo,$o]).openapi({ref:"AllScrollCommands"}),uP=q.merge(b.object({type:b.literal("DIALOG"),action:b.union([b.literal("ACCEPT"),b.literal("DISMISS")])})).openapi({ref:"DialogCommand"}),dP=q.merge(b.object({type:b.literal("WAIT"),delay:b.number()})).openapi({ref:"WaitCommand"}),pP=b.object({caseInsensitive:b.boolean().optional().describe("Whether to ignore case when matching the URL"),negated:b.boolean().optional().describe("Wait for the URL to NOT match the provided matcher instead."),timeout:b.number().int().optional().describe("Max seconds to wait for the URL to match")}),Ey=q.extend({type:b.literal("WAIT_FOR_URL"),matcher:Md}).merge(pP).openapi({ref:"WaitUrlCommand"}),mP=q.merge(ml).merge(b.object({type:b.literal("REFRESH")})).openapi({ref:"RefreshCommand"}),gP=q.merge(b.object({type:b.literal("GO_BACK")})).openapi({ref:"GoBackCommand"}),hP=q.merge(b.object({type:b.literal("GO_FORWARD")})).openapi({ref:"GoForwardCommand"}),fP=q.extend({type:b.literal("AUTH_SAVE")}).openapi({ref:"AuthSaveCommand"}),SP=q.extend({type:b.literal("AUTH_LOAD"),storageState:b.string().describe("JSON string auth state. Leave blank or set to the empty string to clear all existing authentication.")}).openapi({ref:"AuthLoadCommand"}),Pd=q.merge(Jt).extend({type:b.literal("CAPTCHA")}).openapi({ref:"CaptchaCommand"}),yP=q.extend({type:b.literal("COPY"),value:b.string()}).openapi({ref:"CopyCommand"}),bP=q.extend({type:b.literal("PASTE")}).openapi({ref:"PasteCommand"}),Ty=q.merge(pl).extend({type:b.literal("JAVASCRIPT")}).openapi({ref:"JavaScriptCommand"}),aa=q.merge(Jt).extend({type:b.literal("CLICK"),target:yt,doubleClick:b.boolean().optional(),rightClick:b.boolean().optional(),waitForDownload:b.boolean().optional().describe("Wait for the click to trigger a file download and for the file download to complete."),delayMs:b.number().optional(),downloadTimeoutMs:b.number().optional(),cache:Zt,relativePosition:b.object({x:b.number(),y:b.number()}).optional()}).openapi({ref:"ClickCommand"}),vy=ra.extend({fromTarget:dn.optional(),toTarget:dn.optional()}),sa=q.merge(Jt).merge(b.object({type:b.literal("DRAG"),fromTarget:yt,toTarget:yt,steps:b.number().optional(),hoverSeconds:b.number().optional().describe("Seconds to hover the object before dropping"),cache:vy.optional()})).openapi({ref:"DragCommand"}),la=q.merge(Jt).merge(b.object({type:b.literal("MOUSE_DRAG"),target:yt.optional(),deltaX:b.string().describe("pixels to move horizontally, can be template"),deltaY:b.string().describe("pixels to move vertically, can be template"),steps:b.number().optional(),cache:Zt})).openapi({ref:"MouseDragCommand"}),ca=q.merge(Jt).merge(b.object({type:b.literal("HOVER"),target:yt,cache:Zt})).openapi({ref:"HoverCommand"}),ua=q.merge(Jt).merge(b.object({type:b.literal("FOCUS"),target:yt,cache:Zt})).openapi({ref:"FocusCommand"}),da=q.merge(Jt).extend({type:b.literal("BLUR"),target:yt.optional(),cache:Zt}).openapi({ref:"BlurCommand"}),EP=b.object({type:b.literal("URL"),url:b.string()}).describe("Accessible link to the file, either public http or local file://").openapi({ref:"UrlSource"}),TP=b.object({type:b.literal("USER_FILE"),name:b.string()}).describe("Accessible link to the file, references the google cloud file").openapi({ref:"UploadedFileSource"}),vP=q.extend({type:b.literal("FILE_UPLOAD"),fileSource:b.discriminatedUnion("type",[EP,TP]),filename:b.string().optional()}).openapi({ref:"FileUploadCommand"}),Ay=b.discriminatedUnion("type",[b.object({type:b.literal("VALUE"),value:b.string()}),b.object({type:b.literal("LABEL"),label:b.string()}),b.object({type:b.literal("INDEX"),index:b.coerce.string()})]),pa=q.merge(Jt).extend({type:b.literal("SELECT_OPTION"),target:yt,cache:Zt,choice:Ay.describe("new field for selecting options, optional for backcompat")}).openapi({ref:"SelectOptionCommand"}),Od=b.union([b.literal("MULTIMODAL"),b.literal("VISION_ONLY")]),hl=q.merge(b.object({type:b.literal("AI_ASSERTION"),assertion:b.string(),disableCache:b.boolean().optional(),iframeUrl:b.string().optional(),contextChoice:Od.optional(),timeout:b.number().int().optional().describe("Max seconds to wait for assertion to be true"),cache:_d.optional()})).openapi({ref:"AIAssertionCommand"}),mn=5,Ld=600,qo=q.merge(Jt).extend({type:b.literal("ELEMENT_CHECK"),target:yt,assertion:fy,cache:Zt.or(_d).optional(),timeout:b.number().int().min(0).max(Ld).optional().describe("max seconds to wait for the assertion to be true")}).openapi({ref:"ElementAssertionCommand"}),wy=q.extend({type:b.literal("PAGE_CHECK"),assertion:Sy,iframeUrl:b.string().optional().describe("url or url regex for the iframe"),timeout:b.number().int().min(0).max(Ld).optional().describe("max seconds to wait for the assertion to be true")}).openapi({ref:"PageAssertionCommand"}),Ry=q.merge(b.object({type:b.literal("AI_EXTRACT"),goal:b.string(),schema:b.string().optional(),envKey:b.string().optional(),disableCache:b.boolean().optional(),iframeUrl:b.string().optional()})).openapi({ref:"AIExtractCommand"}),AP=b.object({clearContent:b.boolean().optional(),forceClearContent:b.boolean().optional(),delay:b.number().min(0).max(1e3).optional().describe("Delay between each press in milliseconds."),force:b.boolean().optional(),pressEnter:b.boolean().optional(),relativePosition:b.object({x:b.number(),y:b.number()}).optional()}),Cy=25,ma=q.merge(Jt).merge(AP).extend({type:b.literal("TYPE"),target:yt.optional(),value:b.string(),cache:Zt}).openapi({ref:"TypeCommand"}),wP=q.merge(b.object({type:b.literal("PRESS"),value:b.string(),repeat:b.number().optional(),convertMeta:b.boolean().optional(),delayMs:b.number().optional()})).openapi({ref:"PressCommand"}),RP=q.merge(b.object({type:b.literal("KEY_DOWN"),value:b.string(),convertMeta:b.boolean().optional()})).openapi({ref:"KeyDownCommand"}),CP=q.merge(b.object({type:b.literal("KEY_UP"),value:b.string(),convertMeta:b.boolean().optional()})).openapi({ref:"KeyUpCommand"}),xP=b.object({type:b.literal("SUBSTRING"),substring:b.string()}),_P=b.object({type:b.literal("REGEX"),pattern:b.string()}),MP=b.object({type:b.literal("INDEX"),index:b.coerce.string()}),IP=b.discriminatedUnion("type",[xP,_P,MP]),PP=q.merge(ml).merge(b.object({type:b.literal("TAB"),action:IP})).openapi({ref:"TabCommand"}),xy=q.merge(ml).merge(b.object({type:b.literal("NEW_TAB"),url:b.string()})).openapi({ref:"NewTabCommand"}),OP=q.merge(b.object({type:b.literal("COOKIE"),value:b.string()})).openapi({ref:"CookieCommand"}),LP=q.merge(b.object({type:b.literal("LOCAL_STORAGE"),key:b.string(),value:b.string()})).openapi({ref:"LocalStorageCommand"}),NP=q.extend({type:b.literal("REQUEST")}).merge(Go).openapi({ref:"RequestCommand"}),kP=q.extend({type:b.literal("GRAPHQL_REQUEST")}).merge(yy).openapi({ref:"GraphQLRequestCommand"}),DP=q.merge(b.object({type:b.literal("SUCCESS"),condition:hl.optional()})).openapi({ref:"SuccessCommand"}),_y=q.merge(b.object({type:b.literal("FAILURE")})).openapi({ref:"FailureCommand"}),UP=b.object({data:b.string().describe("location at which to find a jpg"),width:b.number(),height:b.number()}),ga=q.merge(Jt).merge(b.object({type:b.literal("VISUAL_DIFF"),threshold:b.number().optional().describe("default 0.1"),target:yt.optional(),screenshot:UP.optional(),cache:Zt})).openapi({ref:"VisualDiffCommand"}),FP=q.merge(b.object({type:b.literal("REGISTER_REQUEST_LISTENER"),requestMatcher:oa,key:b.string()})).openapi({ref:"RegisterRequestListenerCommand"}),BP=q.merge(b.object({type:b.literal("AWAIT_LISTENER"),key:b.string(),timeout:b.number().optional().describe("timeout")})).openapi({ref:"WaitForListenerCommand"}),zP=q.merge(b.object({type:b.literal("RECORD_REQUESTS"),requestMatcher:oa,key:b.string()})).openapi({ref:"RecordRequestsCommand"}),HP=q.merge(b.object({type:b.literal("GET_RECORDED_REQUESTS"),key:b.string()})).openapi({ref:"GetRecordedRequestsCommand"}),GP=q.merge(b.object({type:b.literal("SET_HEADER"),name:b.string(),value:b.string(),requestMatcher:oa.optional()})).openapi({ref:"SetHeaderCommand"}),jP=q.merge(b.object({type:b.literal("MOCK_ROUTE"),requestMatcher:oa,responseGenerator:b.string().describe("JavaScript code to generate a response"),fetchOriginalResponse:b.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:b.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"})),VP=q.merge(b.object({type:b.literal("REMOVE_ROUTE_MOCK"),key:b.string().optional().describe("Key of the mock to remove. If not set, all route mocks will be removed.")}).openapi({ref:"RemoveRouteMockCommandOptions"})),WP=q.merge(b.object({type:b.literal("OFFLINE_MODE"),enable:b.boolean()})).openapi({ref:"OfflineModeCommand"}),$P=b.discriminatedUnion("type",[aa,ma,wP,RP,CP,pa,cP,Vo,jo,hl,gP,ca,dP]),Nd=b.discriminatedUnion("type",[...$P.options,DP]),kd=b.discriminatedUnion("type",[...Nd.options,Ty,qo,wy,xy,Ey,Ry]),qP=b.discriminatedUnion("type",[Ry,SP,fP,Pd,OP,yP,uP,sa,qo,vP,hP,Ty,LP,la,xy,wy,bP,mP,NP,kP,Wo,$o,PP,ga,ua,da,Ey,FP,BP,zP,HP,GP,jP,VP,WP]),Ko=b.discriminatedUnion("type",[...Nd.options,...qP.options]).openapi({ref:"Command"}),fl=b.discriminatedUnion("type",[...Nd.options,_y]),O5=b.discriminatedUnion("type",[...kd.options,_y]);function qr(r){let e;switch(r){case"PASTE":case"AUTH_SAVE":case"VISUAL_DIFF":case"SUCCESS":case"SCROLL_DOWN":case"SCROLL_UP":case"SCROLL_LEFT":case"SCROLL_RIGHT":case"CAPTCHA":case"GO_BACK":case"GO_FORWARD":case"REFRESH":e={id:ye(),type:r};break;case"AUTH_LOAD":{e={id:ye(),type:r,storageState:""};break}case"AI_EXTRACT":e={id:ye(),type:r,goal:""};break;case"DIALOG":e={id:ye(),type:r,action:"DISMISS"};break;case"DRAG":e={id:ye(),type:r,fromTarget:{type:"description",elementDescriptor:""},toTarget:{type:"description",elementDescriptor:""}};break;case"MOUSE_DRAG":e={id:ye(),type:r,deltaX:"0",deltaY:"0",steps:1};break;case"WAIT_FOR_URL":e={id:ye(),type:r,matcher:{type:"SUBSTRING",url:""}};break;case"WAIT":e={id:ye(),type:r,delay:1};break;case"BLUR":e={id:ye(),type:r};break;case"HOVER":case"FOCUS":case"CLICK":e={id:ye(),type:r,target:{type:"description",elementDescriptor:""}};break;case"COOKIE":case"PRESS":case"COPY":case"TYPE":e={id:ye(),type:r,value:"",clearContent:!0};break;case"KEY_DOWN":case"KEY_UP":e={id:ye(),type:r,value:""};break;case"SELECT_OPTION":e={id:ye(),type:r,target:{type:"description",elementDescriptor:""},choice:{type:"VALUE",value:""}};break;case"NAVIGATE":case"NEW_TAB":return{id:ye(),type:r,url:""};case"TAB":e={id:ye(),type:r,action:{type:"SUBSTRING",substring:""}};break;case"REQUEST":e={id:ye(),type:r,url:"",method:"GET"};break;case"GRAPHQL_REQUEST":e={id:ye(),type:r,url:"",query:""};break;case"LOCAL_STORAGE":e={id:ye(),type:r,key:"",value:""};break;case"JAVASCRIPT":e={id:ye(),type:r,code:""};break;case"AI_ASSERTION":e={id:ye(),type:r,assertion:""};break;case"FILE_UPLOAD":{e={id:ye(),type:r,fileSource:{type:"URL",url:""}};break}case"ELEMENT_CHECK":{e={id:ye(),type:r,target:{type:"description",elementDescriptor:""},assertion:{type:"ELEMENT_EXISTENCE",condition:"EXISTS"}};break}case"PAGE_CHECK":{e={id:ye(),type:r,assertion:{type:"CONTENT",value:""}};break}case"REGISTER_REQUEST_LISTENER":{e={id:ye(),type:r,requestMatcher:{urlMatcher:{type:"REGEX",regex:""}},key:""};break}case"AWAIT_LISTENER":{e={id:ye(),type:r,key:""};break}case"RECORD_REQUESTS":{e={id:ye(),type:r,requestMatcher:{urlMatcher:{type:"REGEX",regex:""}},key:""};break}case"GET_RECORDED_REQUESTS":{e={id:ye(),type:r,key:""};break}case"SET_HEADER":{e={id:ye(),type:r,name:"",value:""};break}case"MOCK_ROUTE":{e={id:ye(),type:r,requestMatcher:{urlMatcher:{type:"REGEX",regex:""}},responseGenerator:""};break}case"REMOVE_ROUTE_MOCK":{e={id:ye(),type:r};break}case"OFFLINE_MODE":{e={id:ye(),type:r,enable:!0};break}default:return(n=>{throw"If Typescript complains about the line below, you missed a case or break in the switch above"})(r)}return e}function My(r){switch(r.type){case"BLUR":case"CLICK":case"DRAG":case"FOCUS":case"HOVER":case"MOUSE_DRAG":case"PRESS":case"KEY_DOWN":case"KEY_UP":case"SCROLL_DOWN":case"SCROLL_UP":case"SCROLL_LEFT":case"SCROLL_RIGHT":case"TYPE":return!0;case"AUTH_LOAD":case"AUTH_SAVE":case"AWAIT_LISTENER":case"SUCCESS":case"AI_ASSERTION":case"AI_EXTRACT":case"CAPTCHA":case"COOKIE":case"COPY":case"DIALOG":case"ELEMENT_CHECK":case"FILE_UPLOAD":case"GET_RECORDED_REQUESTS":case"GO_BACK":case"GO_FORWARD":case"GRAPHQL_REQUEST":case"JAVASCRIPT":case"LOCAL_STORAGE":case"NAVIGATE":case"NEW_TAB":case"PASTE":case"PAGE_CHECK":case"RECORD_REQUESTS":case"REGISTER_REQUEST_LISTENER":case"REFRESH":case"REQUEST":case"SELECT_OPTION":case"SET_HEADER":case"TAB":case"VISUAL_DIFF":case"WAIT":case"WAIT_FOR_URL":case"OFFLINE_MODE":case"MOCK_ROUTE":case"REMOVE_ROUTE_MOCK":return!1;default:return(t=>{throw"If Typescript complains about the line below, you missed a case or break in the switch above"})(r)}}import{z as KP}from"zod";var U5=KP.discriminatedUnion("type",[da,Pd,aa,sa,ua,ca,la,jo,Vo,Wo,$o,pa,ma,ga,qo]);import{z as YP}from"zod";import{z as gn}from"zod";function ha(r){return gn.object({key:gn.string(),testId:gn.string().optional(),moduleId:gn.string().optional(),organizationId:gn.string(),value:r})}function fa(r){return ha(r).extend({uniqueKey:gn.string()})}function Sl(r){return gn.record(gn.string(),fa(r))}var Rt={type:!0,cache:!0},Yo=YP.discriminatedUnion("type",[hl.pick(Rt),da.pick(Rt),aa.pick(Rt),sa.pick(Rt),qo.pick(Rt),ua.pick(Rt),ca.pick(Rt),la.pick(Rt),jo.pick(Rt),Vo.pick(Rt),Wo.pick(Rt),$o.pick(Rt),pa.pick(Rt),ma.pick(Rt),ga.pick(Rt)]),Dd=Object.values(nt).filter(r=>Yo.options.some(e=>e.shape.type.safeParse(r).success));Ko.options.forEach(r=>{if("target"in r.shape&&!Dd.includes(r.shape.type.value))throw new Error(`Command ${r.shape.type.value} has a target but no cache`)});function Iy(r){return Dd.includes(r.type)}var Py=ha(Yo),Oy=fa(Yo),W5=Sl(Yo);import{v4 as WX}from"uuid";import{z as M}from"zod";var Ny=Symbol("Let zodToJsonSchema decide on which parser to use");var Ly={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"},ky=r=>typeof r=="string"?{...Ly,name:r}:{...Ly,...r};var Dy=r=>{let e=ky(r),t=e.name!==void 0?[...e.basePath,e.definitionPath,e.name]:e.basePath;return{...e,flags:{hasReferencedOpenAiAnyType:!1},currentPath:t,propertyPath:void 0,seen:new Map(Object.entries(e.definitions).map(([n,o])=>[o._def,{def:o._def,path:[...e.basePath,e.definitionPath,n],jsonSchema:void 0}]))}};function Ud(r,e,t,n){n?.errorMessages&&t&&(r.errorMessage={...r.errorMessage,[e]:t})}function ue(r,e,t,n,o){r[e]=t,Ud(r,e,n,o)}var yl=(r,e)=>{let t=0;for(;t<r.length&&t<e.length&&r[t]===e[t];t++);return[(r.length-t).toString(),...e.slice(t)].join("/")};import{ZodFirstPartyTypeKind as le}from"zod";function De(r){if(r.target!=="openAi")return{};let e=[...r.basePath,r.definitionPath,r.openAiAnyTypeName];return r.flags.hasReferencedOpenAiAnyType=!0,{$ref:r.$refStrategy==="relative"?yl(e,r.currentPath):e.join("/")}}import{ZodFirstPartyTypeKind as XP}from"zod";function Uy(r,e){let t={type:"array"};return r.type?._def&&r.type?._def?.typeName!==XP.ZodAny&&(t.items=X(r.type._def,{...e,currentPath:[...e.currentPath,"items"]})),r.minLength&&ue(t,"minItems",r.minLength.value,r.minLength.message,e),r.maxLength&&ue(t,"maxItems",r.maxLength.value,r.maxLength.message,e),r.exactLength&&(ue(t,"minItems",r.exactLength.value,r.exactLength.message,e),ue(t,"maxItems",r.exactLength.value,r.exactLength.message,e)),t}function Fy(r,e){let t={type:"integer",format:"int64"};if(!r.checks)return t;for(let n of r.checks)switch(n.kind){case"min":e.target==="jsonSchema7"?n.inclusive?ue(t,"minimum",n.value,n.message,e):ue(t,"exclusiveMinimum",n.value,n.message,e):(n.inclusive||(t.exclusiveMinimum=!0),ue(t,"minimum",n.value,n.message,e));break;case"max":e.target==="jsonSchema7"?n.inclusive?ue(t,"maximum",n.value,n.message,e):ue(t,"exclusiveMaximum",n.value,n.message,e):(n.inclusive||(t.exclusiveMaximum=!0),ue(t,"maximum",n.value,n.message,e));break;case"multipleOf":ue(t,"multipleOf",n.value,n.message,e);break}return t}function By(){return{type:"boolean"}}function bl(r,e){return X(r.type._def,e)}var zy=(r,e)=>X(r.innerType._def,e);function Fd(r,e,t){let n=t??e.dateStrategy;if(Array.isArray(n))return{anyOf:n.map((o,i)=>Fd(r,e,o))};switch(n){case"string":case"format:date-time":return{type:"string",format:"date-time"};case"format:date":return{type:"string",format:"date"};case"integer":return JP(r,e)}}var JP=(r,e)=>{let t={type:"integer",format:"unix-time"};if(e.target==="openApi3")return t;for(let n of r.checks)switch(n.kind){case"min":ue(t,"minimum",n.value,n.message,e);break;case"max":ue(t,"maximum",n.value,n.message,e);break}return t};function Hy(r,e){return{...X(r.innerType._def,e),default:r.defaultValue()}}function Gy(r,e){return e.effectStrategy==="input"?X(r.schema._def,e):De(e)}function jy(r){return{type:"string",enum:Array.from(r.values)}}var ZP=r=>"type"in r&&r.type==="string"?!1:"allOf"in r;function Vy(r,e){let t=[X(r.left._def,{...e,currentPath:[...e.currentPath,"allOf","0"]}),X(r.right._def,{...e,currentPath:[...e.currentPath,"allOf","1"]})].filter(i=>!!i),n=e.target==="jsonSchema2019-09"?{unevaluatedProperties:!1}:void 0,o=[];return t.forEach(i=>{if(ZP(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 Wy(r,e){let t=typeof r.value;return t!=="bigint"&&t!=="number"&&t!=="boolean"&&t!=="string"?{type:Array.isArray(r.value)?"array":"object"}:e.target==="openApi3"?{type:t==="bigint"?"integer":t,enum:[r.value]}:{type:t==="bigint"?"integer":t,const:r.value}}import{ZodFirstPartyTypeKind as Sa}from"zod";var Bd,mr={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:()=>(Bd===void 0&&(Bd=RegExp("^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$","u")),Bd),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 El(r,e){let t={type:"string"};if(r.checks)for(let n of r.checks)switch(n.kind){case"min":ue(t,"minLength",typeof t.minLength=="number"?Math.max(t.minLength,n.value):n.value,n.message,e);break;case"max":ue(t,"maxLength",typeof t.maxLength=="number"?Math.min(t.maxLength,n.value):n.value,n.message,e);break;case"email":switch(e.emailStrategy){case"format:email":gr(t,"email",n.message,e);break;case"format:idn-email":gr(t,"idn-email",n.message,e);break;case"pattern:zod":Ct(t,mr.email,n.message,e);break}break;case"url":gr(t,"uri",n.message,e);break;case"uuid":gr(t,"uuid",n.message,e);break;case"regex":Ct(t,n.regex,n.message,e);break;case"cuid":Ct(t,mr.cuid,n.message,e);break;case"cuid2":Ct(t,mr.cuid2,n.message,e);break;case"startsWith":Ct(t,RegExp(`^${zd(n.value,e)}`),n.message,e);break;case"endsWith":Ct(t,RegExp(`${zd(n.value,e)}$`),n.message,e);break;case"datetime":gr(t,"date-time",n.message,e);break;case"date":gr(t,"date",n.message,e);break;case"time":gr(t,"time",n.message,e);break;case"duration":gr(t,"duration",n.message,e);break;case"length":ue(t,"minLength",typeof t.minLength=="number"?Math.max(t.minLength,n.value):n.value,n.message,e),ue(t,"maxLength",typeof t.maxLength=="number"?Math.min(t.maxLength,n.value):n.value,n.message,e);break;case"includes":{Ct(t,RegExp(zd(n.value,e)),n.message,e);break}case"ip":{n.version!=="v6"&&gr(t,"ipv4",n.message,e),n.version!=="v4"&&gr(t,"ipv6",n.message,e);break}case"base64url":Ct(t,mr.base64url,n.message,e);break;case"jwt":Ct(t,mr.jwt,n.message,e);break;case"cidr":{n.version!=="v6"&&Ct(t,mr.ipv4Cidr,n.message,e),n.version!=="v4"&&Ct(t,mr.ipv6Cidr,n.message,e);break}case"emoji":Ct(t,mr.emoji(),n.message,e);break;case"ulid":{Ct(t,mr.ulid,n.message,e);break}case"base64":{switch(e.base64Strategy){case"format:binary":{gr(t,"binary",n.message,e);break}case"contentEncoding:base64":{ue(t,"contentEncoding","base64",n.message,e);break}case"pattern:zod":{Ct(t,mr.base64,n.message,e);break}}break}case"nanoid":Ct(t,mr.nanoid,n.message,e);case"toLowerCase":case"toUpperCase":case"trim":break;default:}return t}function zd(r,e){return e.patternStrategy==="escape"?eO(r):r}var QP=new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789");function eO(r){let e="";for(let t=0;t<r.length;t++)QP.has(r[t])||(e+="\\"),e+=r[t];return e}function gr(r,e,t,n){r.format||r.anyOf?.some(o=>o.format)?(r.anyOf||(r.anyOf=[]),r.format&&(r.anyOf.push({format:r.format,...r.errorMessage&&n.errorMessages&&{errorMessage:{format:r.errorMessage.format}}}),delete r.format,r.errorMessage&&(delete r.errorMessage.format,Object.keys(r.errorMessage).length===0&&delete r.errorMessage)),r.anyOf.push({format:e,...t&&n.errorMessages&&{errorMessage:{format:t}}})):ue(r,"format",e,t,n)}function Ct(r,e,t,n){r.pattern||r.allOf?.some(o=>o.pattern)?(r.allOf||(r.allOf=[]),r.pattern&&(r.allOf.push({pattern:r.pattern,...r.errorMessage&&n.errorMessages&&{errorMessage:{pattern:r.errorMessage.pattern}}}),delete r.pattern,r.errorMessage&&(delete r.errorMessage.pattern,Object.keys(r.errorMessage).length===0&&delete r.errorMessage)),r.allOf.push({pattern:$y(e,n),...t&&n.errorMessages&&{errorMessage:{pattern:t}}})):ue(r,"pattern",$y(e,n),t,n)}function $y(r,e){if(!e.applyRegexFlags||!r.flags)return r.source;let t={i:r.flags.includes("i"),m:r.flags.includes("m"),s:r.flags.includes("s")},n=t.i?r.source.toLowerCase():r.source,o="",i=!1,a=!1,s=!1;for(let c=0;c<n.length;c++){if(i){o+=n[c],i=!1;continue}if(t.i){if(a){if(n[c].match(/[a-z]/)){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(t.m){if(n[c]==="^"){o+=`(^|(?<=[\r
|
|
2
|
+
var mC=Object.defineProperty;var ze=(r,e)=>()=>(r&&(e=r(r=0)),e);var gC=(r,e)=>{for(var t in e)mC(r,t,{get:e[t],enumerable:!0})};var Oy,Ly=ze(()=>{"use strict";Oy=typeof globalThis=="object"?globalThis:global});var Ny=ze(()=>{"use strict";Ly()});var Dy=ze(()=>{"use strict";Ny()});var Hr,_d=ze(()=>{"use strict";Hr="1.9.0"});function KP(r){var e=new Set([r]),t=new Set,n=r.match(ky);if(!n)return function(){return!1};var o={major:+n[1],minor:+n[2],patch:+n[3],prerelease:n[4]};if(o.prerelease!=null)return function(c){return c===r};function i(l){return t.add(l),!1}function a(l){return e.add(l),!0}return function(c){if(e.has(c))return!0;if(t.has(c))return!1;var s=c.match(ky);if(!s)return i(c);var u={major:+s[1],minor:+s[2],patch:+s[3],prerelease:s[4]};return u.prerelease!=null||o.major!==u.major?i(c):o.major===0?o.minor===u.minor&&o.patch<=u.patch?a(c):i(c):o.minor<=u.minor?a(c):i(c)}}var ky,Uy,Fy=ze(()=>{"use strict";_d();ky=/^(\d+)\.(\d+)\.(\d+)(-(.+))?$/;Uy=KP(Hr)});function Fo(r,e,t,n){var o;n===void 0&&(n=!1);var i=ua[ca]=(o=ua[ca])!==null&&o!==void 0?o:{version:Hr};if(!n&&i[r]){var a=new Error("@opentelemetry/api: Attempted duplicate registration of API: "+r);return t.error(a.stack||a.message),!1}if(i.version!==Hr){var a=new Error("@opentelemetry/api: Registration of version v"+i.version+" for "+r+" does not match previously registered API v"+Hr);return t.error(a.stack||a.message),!1}return i[r]=e,t.debug("@opentelemetry/api: Registered a global for "+r+" v"+Hr+"."),!0}function Gr(r){var e,t,n=(e=ua[ca])===null||e===void 0?void 0:e.version;if(!(!n||!Uy(n)))return(t=ua[ca])===null||t===void 0?void 0:t[r]}function Bo(r,e){e.debug("@opentelemetry/api: Unregistering a global for "+r+" v"+Hr+".");var t=ua[ca];t&&delete t[r]}var YP,ca,ua,da=ze(()=>{"use strict";Dy();_d();Fy();YP=Hr.split(".")[0],ca=Symbol.for("opentelemetry.js.api."+YP),ua=Oy});function pa(r,e,t){var n=Gr("diag");if(n)return t.unshift(e),n[r].apply(n,JP([],XP(t),!1))}var XP,JP,By,zy=ze(()=>{"use strict";da();XP=function(r,e){var t=typeof Symbol=="function"&&r[Symbol.iterator];if(!t)return r;var n=t.call(r),o,i=[],a;try{for(;(e===void 0||e-- >0)&&!(o=n.next()).done;)i.push(o.value)}catch(l){a={error:l}}finally{try{o&&!o.done&&(t=n.return)&&t.call(n)}finally{if(a)throw a.error}}return i},JP=function(r,e,t){if(t||arguments.length===2)for(var n=0,o=e.length,i;n<o;n++)(i||!(n in e))&&(i||(i=Array.prototype.slice.call(e,0,n)),i[n]=e[n]);return r.concat(i||Array.prototype.slice.call(e))},By=function(){function r(e){this._namespace=e.namespace||"DiagComponentLogger"}return r.prototype.debug=function(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];return pa("debug",this._namespace,e)},r.prototype.error=function(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];return pa("error",this._namespace,e)},r.prototype.info=function(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];return pa("info",this._namespace,e)},r.prototype.warn=function(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];return pa("warn",this._namespace,e)},r.prototype.verbose=function(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];return pa("verbose",this._namespace,e)},r}()});var Le,tl=ze(()=>{"use strict";(function(r){r[r.NONE=0]="NONE",r[r.ERROR=30]="ERROR",r[r.WARN=50]="WARN",r[r.INFO=60]="INFO",r[r.DEBUG=70]="DEBUG",r[r.VERBOSE=80]="VERBOSE",r[r.ALL=9999]="ALL"})(Le||(Le={}))});function Hy(r,e){r<Le.NONE?r=Le.NONE:r>Le.ALL&&(r=Le.ALL),e=e||{};function t(n,o){var i=e[n];return typeof i=="function"&&r>=o?i.bind(e):function(){}}return{error:t("error",Le.ERROR),warn:t("warn",Le.WARN),info:t("info",Le.INFO),debug:t("debug",Le.DEBUG),verbose:t("verbose",Le.VERBOSE)}}var Gy=ze(()=>{"use strict";tl()});var ZP,QP,eO,Cr,ma=ze(()=>{"use strict";zy();Gy();tl();da();ZP=function(r,e){var t=typeof Symbol=="function"&&r[Symbol.iterator];if(!t)return r;var n=t.call(r),o,i=[],a;try{for(;(e===void 0||e-- >0)&&!(o=n.next()).done;)i.push(o.value)}catch(l){a={error:l}}finally{try{o&&!o.done&&(t=n.return)&&t.call(n)}finally{if(a)throw a.error}}return i},QP=function(r,e,t){if(t||arguments.length===2)for(var n=0,o=e.length,i;n<o;n++)(i||!(n in e))&&(i||(i=Array.prototype.slice.call(e,0,n)),i[n]=e[n]);return r.concat(i||Array.prototype.slice.call(e))},eO="diag",Cr=function(){function r(){function e(o){return function(){for(var i=[],a=0;a<arguments.length;a++)i[a]=arguments[a];var l=Gr("diag");if(l)return l[o].apply(l,QP([],ZP(i),!1))}}var t=this,n=function(o,i){var a,l,c;if(i===void 0&&(i={logLevel:Le.INFO}),o===t){var s=new Error("Cannot use diag as the logger for itself. Please use a DiagLogger implementation like ConsoleDiagLogger or a custom implementation");return t.error((a=s.stack)!==null&&a!==void 0?a:s.message),!1}typeof i=="number"&&(i={logLevel:i});var u=Gr("diag"),d=Hy((l=i.logLevel)!==null&&l!==void 0?l:Le.INFO,o);if(u&&!i.suppressOverrideMessage){var p=(c=new Error().stack)!==null&&c!==void 0?c:"<failed to generate stacktrace>";u.warn("Current logger will be overwritten from "+p),d.warn("Current logger will overwrite one already registered from "+p)}return Fo("diag",d,t,!0)};t.setLogger=n,t.disable=function(){Bo(eO,t)},t.createComponentLogger=function(o){return new By(o)},t.verbose=e("verbose"),t.debug=e("debug"),t.info=e("info"),t.warn=e("warn"),t.error=e("error")}return r.instance=function(){return this._instance||(this._instance=new r),this._instance},r}()});var Vy,jy=ze(()=>{"use strict";Vy=Symbol("BaggageEntryMetadata")});function Id(r){return typeof r!="string"&&(tO.error("Cannot create baggage metadata from unknown type: "+typeof r),r=""),{__TYPE__:Vy,toString:function(){return r}}}var tO,Wy=ze(()=>{"use strict";ma();jy();tO=Cr.instance()});function Pd(r){return Symbol.for(r)}var rO,Od,Ld=ze(()=>{"use strict";rO=function(){function r(e){var t=this;t._currentContext=e?new Map(e):new Map,t.getValue=function(n){return t._currentContext.get(n)},t.setValue=function(n,o){var i=new r(t._currentContext);return i._currentContext.set(n,o),i},t.deleteValue=function(n){var o=new r(t._currentContext);return o._currentContext.delete(n),o}}return r}(),Od=new rO});function kd(){return Dd}var Hn,nO,rl,oO,iO,aO,sO,Nd,lO,cO,uO,Dd,dO,pO,mO,gO,hO,fO,SO,Ud=ze(()=>{"use strict";Hn=function(){var r=function(e,t){return r=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(n,o){n.__proto__=o}||function(n,o){for(var i in o)Object.prototype.hasOwnProperty.call(o,i)&&(n[i]=o[i])},r(e,t)};return function(e,t){if(typeof t!="function"&&t!==null)throw new TypeError("Class extends value "+String(t)+" is not a constructor or null");r(e,t);function n(){this.constructor=e}e.prototype=t===null?Object.create(t):(n.prototype=t.prototype,new n)}}(),nO=function(){function r(){}return r.prototype.createGauge=function(e,t){return pO},r.prototype.createHistogram=function(e,t){return mO},r.prototype.createCounter=function(e,t){return dO},r.prototype.createUpDownCounter=function(e,t){return gO},r.prototype.createObservableGauge=function(e,t){return fO},r.prototype.createObservableCounter=function(e,t){return hO},r.prototype.createObservableUpDownCounter=function(e,t){return SO},r.prototype.addBatchObservableCallback=function(e,t){},r.prototype.removeBatchObservableCallback=function(e){},r}(),rl=function(){function r(){}return r}(),oO=function(r){Hn(e,r);function e(){return r!==null&&r.apply(this,arguments)||this}return e.prototype.add=function(t,n){},e}(rl),iO=function(r){Hn(e,r);function e(){return r!==null&&r.apply(this,arguments)||this}return e.prototype.add=function(t,n){},e}(rl),aO=function(r){Hn(e,r);function e(){return r!==null&&r.apply(this,arguments)||this}return e.prototype.record=function(t,n){},e}(rl),sO=function(r){Hn(e,r);function e(){return r!==null&&r.apply(this,arguments)||this}return e.prototype.record=function(t,n){},e}(rl),Nd=function(){function r(){}return r.prototype.addCallback=function(e){},r.prototype.removeCallback=function(e){},r}(),lO=function(r){Hn(e,r);function e(){return r!==null&&r.apply(this,arguments)||this}return e}(Nd),cO=function(r){Hn(e,r);function e(){return r!==null&&r.apply(this,arguments)||this}return e}(Nd),uO=function(r){Hn(e,r);function e(){return r!==null&&r.apply(this,arguments)||this}return e}(Nd),Dd=new nO,dO=new oO,pO=new aO,mO=new sO,gO=new iO,hO=new lO,fO=new cO,SO=new uO});var Bt,$y=ze(()=>{"use strict";(function(r){r[r.INT=0]="INT",r[r.DOUBLE=1]="DOUBLE"})(Bt||(Bt={}))});var yO,bO,qy,Ky=ze(()=>{"use strict";Ld();yO=function(r,e){var t=typeof Symbol=="function"&&r[Symbol.iterator];if(!t)return r;var n=t.call(r),o,i=[],a;try{for(;(e===void 0||e-- >0)&&!(o=n.next()).done;)i.push(o.value)}catch(l){a={error:l}}finally{try{o&&!o.done&&(t=n.return)&&t.call(n)}finally{if(a)throw a.error}}return i},bO=function(r,e,t){if(t||arguments.length===2)for(var n=0,o=e.length,i;n<o;n++)(i||!(n in e))&&(i||(i=Array.prototype.slice.call(e,0,n)),i[n]=e[n]);return r.concat(i||Array.prototype.slice.call(e))},qy=function(){function r(){}return r.prototype.active=function(){return Od},r.prototype.with=function(e,t,n){for(var o=[],i=3;i<arguments.length;i++)o[i-3]=arguments[i];return t.call.apply(t,bO([n],yO(o),!1))},r.prototype.bind=function(e,t){return t},r.prototype.enable=function(){return this},r.prototype.disable=function(){return this},r}()});var EO,TO,Fd,vO,Yy,Xy=ze(()=>{"use strict";Ky();da();ma();EO=function(r,e){var t=typeof Symbol=="function"&&r[Symbol.iterator];if(!t)return r;var n=t.call(r),o,i=[],a;try{for(;(e===void 0||e-- >0)&&!(o=n.next()).done;)i.push(o.value)}catch(l){a={error:l}}finally{try{o&&!o.done&&(t=n.return)&&t.call(n)}finally{if(a)throw a.error}}return i},TO=function(r,e,t){if(t||arguments.length===2)for(var n=0,o=e.length,i;n<o;n++)(i||!(n in e))&&(i||(i=Array.prototype.slice.call(e,0,n)),i[n]=e[n]);return r.concat(i||Array.prototype.slice.call(e))},Fd="context",vO=new qy,Yy=function(){function r(){}return r.getInstance=function(){return this._instance||(this._instance=new r),this._instance},r.prototype.setGlobalContextManager=function(e){return Fo(Fd,e,Cr.instance())},r.prototype.active=function(){return this._getContextManager().active()},r.prototype.with=function(e,t,n){for(var o,i=[],a=3;a<arguments.length;a++)i[a-3]=arguments[a];return(o=this._getContextManager()).with.apply(o,TO([e,t,n],EO(i),!1))},r.prototype.bind=function(e,t){return this._getContextManager().bind(e,t)},r.prototype._getContextManager=function(){return Gr(Fd)||vO},r.prototype.disable=function(){this._getContextManager().disable(),Bo(Fd,Cr.instance())},r}()});var zo,Jy=ze(()=>{"use strict";Xy();zo=Yy.getInstance()});var H,Zy=ze(()=>{"use strict";ma();H=Cr.instance()});var AO,Qy,eb=ze(()=>{"use strict";Ud();AO=function(){function r(){}return r.prototype.getMeter=function(e,t,n){return Dd},r}(),Qy=new AO});var Bd,tb,rb=ze(()=>{"use strict";eb();da();ma();Bd="metrics",tb=function(){function r(){}return r.getInstance=function(){return this._instance||(this._instance=new r),this._instance},r.prototype.setGlobalMeterProvider=function(e){return Fo(Bd,e,Cr.instance())},r.prototype.getMeterProvider=function(){return Gr(Bd)||Qy},r.prototype.getMeter=function(e,t,n){return this.getMeterProvider().getMeter(e,t,n)},r.prototype.disable=function(){Bo(Bd,Cr.instance())},r}()});var nl,nb=ze(()=>{"use strict";rb();nl=tb.getInstance()});var Ce=ze(()=>{"use strict";Wy();Ld();tl();Ud();$y();Jy();Zy();nb()});import{Argument as Og,Command as Qz,Option as e1}from"@commander-js/extra-typings";import mD from"appium";import{tmpdir as gD}from"os";import{remote as hD}from"webdriverio";import{createInstanceClient as cD}from"@limrun/api";import{execSync as uD}from"child_process";import Q8,{multistream as t9}from"pino";import n9 from"pino-pretty";import{z as Lg}from"zod";var u1=Lg.object({input:Lg.string()});import{z as rt}from"zod";var m1=rt.object({srcs:rt.array(rt.string()),urls:rt.array(rt.string()),desiredSrc:rt.string().optional(),desiredUrl:rt.string().optional()}),Ng=rt.object({srcRegex:rt.string().optional(),urlRegex:rt.string().optional()}),Dg=rt.object({x:rt.number(),y:rt.number(),correlation:rt.number()}),g1=rt.object({searchImageBase64String:rt.string(),pageImageBase64String:rt.string(),id:rt.string().uuid(),timeoutMs:rt.number().max(1e4).min(0).optional()});import{z as P}from"zod";import*as N from"zod";import{extendZodWithOpenApi as hC}from"zod-openapi";hC(N);var qr=(l=>(l.AI="AI",l.AI_HEALED="AI_HEALED",l.CLICK_TO_FIND="CLICK_TO_FIND",l.XY_PERCENT="XY_PERCENT",l.RECORDING="RECORDING",l.USER_CSS_SELECTOR="USER_CSS_SELECTOR",l.HEURISTIC_HEALED="HEURISTIC_HEALED",l))(qr||{}),fC=N.object({mPathSelectorTokens:N.string().array(),frameSrcRegex:N.string().optional(),frameUrlRegex:N.string().optional(),indices:N.number().array()}),iu=N.object({result:N.number(),traceId:N.string()}).array(),rs=N.object({type:N.literal("GCS_TRACES"),traces:iu}),kg=N.object({text:N.string().optional(),attributes:N.record(N.string(),N.string()).optional(),boundingBox:N.object({x:N.number(),y:N.number(),width:N.number(),height:N.number()}).optional()}),SC=N.object({selectors:N.string().array(),requirements:kg.optional()}),Kr=N.object({id:N.number().int(),dataMomenticId:N.number().int().optional(),selector:N.string().optional(),hybridSelector:N.object({textContent:N.string().nullish(),attributes:N.record(N.string(),N.string().optional()),tagName:N.string(),expandShadowRoot:N.boolean().optional(),classNames:N.string().array(),nthChild:N.number()}).array().optional(),generatedSelectors:N.string().array().optional(),requirements:kg.optional(),additionalElements:SC.array().optional(),role:N.string().optional(),name:N.string().optional(),numChildren:N.number().optional(),content:N.string().optional(),pathFromRoot:N.string().optional(),serializedHtml:N.string().optional().describe("pruned html including 1 neighbor and 1 layer of children. value for text inputs pruned."),nodeOnlySerializedHtml:N.string().optional().describe("outerHtml of the element without any children. value for text inputs pruned."),screenshotUrl:N.string().url().optional(),boundingBox:N.object({x:N.number().optional(),y:N.number().optional(),width:N.number(),height:N.number()}).describe("css pixel bounding box").optional(),frameCache:fC.optional(),inputDescription:N.string().optional().describe("the description that generated this cache"),targetSource:N.nativeEnum(qr).optional(),targetUpdateTime:N.string().optional(),targetUpdateLoggerTags:N.record(N.string(),N.string()).optional(),cacheResolutionUpdateSource:N.string().optional(),cacheResolutionUpdateTime:N.string().optional(),cacheResolutionUpdateLoggerTags:N.record(N.string(),N.string()).optional(),memory:rs.optional()}).openapi({ref:"ElementTargetCache"});function ns(r){return!!(r.serializedHtml||r.screenshotUrl||r.generatedSelectors||r.hybridSelector)}var yC=N.object({type:N.literal("description"),elementDescriptor:N.string().describe("Description of the element.")}).openapi({ref:"DescriptionTarget"}),bC=N.object({x:N.number(),y:N.number()}),EC=N.object({type:N.literal("coordinates"),pixels:bC}).openapi({ref:"CoordinatesTarget"});function Yr(r){return r.type==="description"}function br(r){return r.type==="coordinates"}var ht=N.discriminatedUnion("type",[yC,EC]).openapi({ref:"ElementTarget"});function au(r){if(!r)return!1;switch(r.type){case"description":return!!r.elementDescriptor}return!0}function Ug(r){return rs.safeParse(r).success}import{v4 as Se}from"uuid";import*as y from"zod";import{extendZodWithOpenApi as MC}from"zod-openapi";import{z as Q}from"zod";import{extendZodWithOpenApi as TC}from"zod-openapi";import{z as Ai}from"zod";import Fg from"zod";var vi=Fg.object({updatedAt:Fg.coerce.date().optional()});var su=Ai.object({result:Ai.boolean(),traceId:Ai.string()}).array(),lu=Ai.object({type:Ai.literal("GCS_TRACES"),traces:su}),cu=vi.extend({memory:lu.optional()});TC(Q);var Bg=Q.object({plan:Q.string().optional(),evidence:Q.string().optional(),thoughts:Q.string(),result:Q.boolean(),relevantElements:Q.array(Q.number()).optional(),updatedMemory:su.optional()}),Ur=(o=>(o.CONTAINS="CONTAINS",o.STARTS_WITH="STARTS_WITH",o.EQUALS="EQUALS",o.EXISTS="EXISTS",o))(Ur||{});var vC=Q.object({type:Q.literal("ELEMENT_NAME"),negated:Q.boolean().optional(),operation:Q.nativeEnum(Ur),value:Q.string()}).openapi({ref:"ElementNameAssertion"}),AC=Q.object({type:Q.literal("ELEMENT_STYLE"),negated:Q.boolean().optional(),operation:Q.nativeEnum(Ur),property:Q.string(),value:Q.string()}).openapi({ref:"ElementStyleAssertion"}),wC=Q.object({type:Q.literal("ELEMENT_CONTENT"),negated:Q.boolean().optional(),operation:Q.nativeEnum(Ur),value:Q.string()}).openapi({ref:"ElementContentAssertion"}),RC=Q.object({type:Q.literal("ELEMENT_ATTRIBUTE"),negated:Q.boolean().optional(),operation:Q.nativeEnum(Ur),attr:Q.string(),value:Q.string()}).openapi({ref:"ElementAttributeValueAssertion"}),xn=(i=>(i.EXISTS="EXISTS",i.VISIBLE="VISIBLE",i.ENABLED="ENABLED",i.EDITABLE="EDITABLE",i.FOCUSED="FOCUSED",i))(xn||{}),CC=Q.object({type:Q.literal("ELEMENT_EXISTENCE"),negated:Q.boolean().optional(),condition:Q.nativeEnum(xn).describe("Treated as the element exists AND is also ...")}).openapi({ref:"ElementExistenceAssertion"}),zg=Q.discriminatedUnion("type",[wC,RC,CC,vC,AC]).openapi({ref:"ManualElementAssertion"});var xC=Q.object({type:Q.literal("CONTENT"),negated:Q.boolean().optional(),value:Q.string()}).openapi({ref:"PageContentAssertion"}),Hg=Q.discriminatedUnion("type",[xC]).openapi({ref:"ManualPageAssertion"});import At from"zod";var uu=At.discriminatedUnion("type",[At.object({type:At.literal("SUBSTRING"),url:At.string()}),At.object({type:At.literal("GLOB"),glob:At.string()}),At.object({type:At.literal("REGEX"),regex:At.string()}),At.object({type:At.literal("DOMAIN"),domain:At.string()})]),wi=At.object({urlMatcher:uu,method:At.string().optional()});import{z as fe}from"zod";var go=fe.object({url:fe.string(),method:fe.union([fe.literal("GET"),fe.literal("POST"),fe.literal("PUT"),fe.literal("DELETE"),fe.literal("PATCH")]),headers:fe.record(fe.string(),fe.string()).optional(),params:fe.record(fe.string(),fe.string()).optional(),body:fe.string().optional(),timeout:fe.number().int().optional().describe("Max seconds to wait for the request to complete")}),Gg=fe.object({url:fe.string(),headers:fe.record(fe.string(),fe.string()).optional(),query:fe.string(),variables:fe.string().optional(),timeout:fe.number().int().optional().describe("Max seconds to wait for the request to complete")}),os=fe.object({code:fe.string(),fragment:fe.boolean().optional().describe("Agents should not touch this unless explicitly told to"),environment:fe.union([fe.literal("NODE"),fe.literal("BROWSER")]).optional().describe("default NODE, Agents default to using node unless it is necessary to use browser"),timeout:fe.number().int().max(60).optional().describe("Max seconds for the code to complete")});var nt=(W=>(W.AI_EXTRACT="AI_EXTRACT",W.AI_ASSERTION="AI_ASSERTION",W.AUTH_LOAD="AUTH_LOAD",W.AUTH_SAVE="AUTH_SAVE",W.BLUR="BLUR",W.CAPTCHA="CAPTCHA",W.CLICK="CLICK",W.COOKIE="COOKIE",W.COPY="COPY",W.DIALOG="DIALOG",W.DRAG="DRAG",W.ELEMENT_CHECK="ELEMENT_CHECK",W.FILE_UPLOAD="FILE_UPLOAD",W.FOCUS="FOCUS",W.GO_BACK="GO_BACK",W.GO_FORWARD="GO_FORWARD",W.HOVER="HOVER",W.JAVASCRIPT="JAVASCRIPT",W.LOCAL_STORAGE="LOCAL_STORAGE",W.MOUSE_DRAG="MOUSE_DRAG",W.NAVIGATE="NAVIGATE",W.NEW_TAB="NEW_TAB",W.PAGE_CHECK="PAGE_CHECK",W.PASTE="PASTE",W.PRESS="PRESS",W.KEY_DOWN="KEY_DOWN",W.KEY_UP="KEY_UP",W.REFRESH="REFRESH",W.REQUEST="REQUEST",W.GRAPHQL_REQUEST="GRAPHQL_REQUEST",W.SCROLL_DOWN="SCROLL_DOWN",W.SCROLL_UP="SCROLL_UP",W.SCROLL_LEFT="SCROLL_LEFT",W.SCROLL_RIGHT="SCROLL_RIGHT",W.SELECT_OPTION="SELECT_OPTION",W.SWITCH_TAB="TAB",W.TYPE="TYPE",W.VISUAL_DIFF="VISUAL_DIFF",W.WAIT="WAIT",W.WAIT_FOR_URL="WAIT_FOR_URL",W.REGISTER_REQUEST_LISTENER="REGISTER_REQUEST_LISTENER",W.AWAIT_LISTENER="AWAIT_LISTENER",W.RECORD_REQUESTS="RECORD_REQUESTS",W.GET_RECORDED_REQUESTS="GET_RECORDED_REQUESTS",W.SET_HEADER="SET_HEADER",W.MOCK_ROUTE="MOCK_ROUTE",W.REMOVE_ROUTE_MOCK="REMOVE_ROUTE_MOCK",W.OFFLINE_MODE="OFFLINE_MODE",W.SUCCESS="SUCCESS",W))(nt||{});MC(y);var V=y.object({thoughts:y.string().optional(),id:y.string().uuid().describe("unique identifier to this step, used for step cache")}),jt=y.object({useSelector:y.boolean().optional(),force:y.boolean().optional(),disableCache:y.boolean().optional().describe("disable element caching for this step"),iframeUrl:y.string().optional().describe("url or url regex for the iframe")}).openapi({ref:"CommonTargetingOptions"}),Wt=vi.extend({target:Kr}).optional().openapi({ref:"SingleTargetCache"});function Vg(r){return Wt.safeParse(r).success}var is=y.object({loadTimeout:y.number().int().max(60).optional().describe("Max seconds for the page to load")}),_C=V.merge(is).merge(y.object({type:y.literal("NAVIGATE"),url:y.string()})).openapi({ref:"NavigateCommand"}),as=jt.merge(y.object({cache:Wt})),ho=V.merge(as.merge(y.object({target:ht.optional(),type:y.literal("SCROLL_UP"),deltaY:y.number().optional()}))).openapi({ref:"ScrollUpCommand"}),fo=V.merge(as.merge(y.object({target:ht.optional(),type:y.literal("SCROLL_DOWN"),deltaY:y.number().optional()}))).openapi({ref:"ScrollDownCommand"}),So=V.merge(as.merge(y.object({target:ht.optional(),type:y.literal("SCROLL_LEFT"),deltaX:y.number().optional()}))).openapi({ref:"ScrollLeftCommand"}),yo=V.merge(as.merge(y.object({target:ht.optional(),type:y.literal("SCROLL_RIGHT"),deltaX:y.number().optional()}))).openapi({ref:"ScrollRightCommand"}),j1=y.discriminatedUnion("type",[ho,fo,So,yo]).openapi({ref:"AllScrollCommands"}),IC=V.merge(y.object({type:y.literal("DIALOG"),action:y.union([y.literal("ACCEPT"),y.literal("DISMISS")])})).openapi({ref:"DialogCommand"}),PC=V.merge(y.object({type:y.literal("WAIT"),delay:y.number()})).openapi({ref:"WaitCommand"}),OC=y.object({caseInsensitive:y.boolean().optional().describe("Whether to ignore case when matching the URL"),negated:y.boolean().optional().describe("Wait for the URL to NOT match the provided matcher instead."),timeout:y.number().int().optional().describe("Max seconds to wait for the URL to match")}),jg=V.extend({type:y.literal("WAIT_FOR_URL"),matcher:uu}).merge(OC).openapi({ref:"WaitUrlCommand"}),LC=V.merge(is).merge(y.object({type:y.literal("REFRESH")})).openapi({ref:"RefreshCommand"}),NC=V.merge(y.object({type:y.literal("GO_BACK")})).openapi({ref:"GoBackCommand"}),DC=V.merge(y.object({type:y.literal("GO_FORWARD")})).openapi({ref:"GoForwardCommand"}),kC=V.extend({type:y.literal("AUTH_SAVE")}).openapi({ref:"AuthSaveCommand"}),UC=V.extend({type:y.literal("AUTH_LOAD"),storageState:y.string().describe("JSON string auth state. Leave blank or set to the empty string to clear all existing authentication.")}).openapi({ref:"AuthLoadCommand"}),pu=V.merge(jt).extend({type:y.literal("CAPTCHA")}).openapi({ref:"CaptchaCommand"}),FC=V.extend({type:y.literal("COPY"),value:y.string()}).openapi({ref:"CopyCommand"}),BC=V.extend({type:y.literal("PASTE")}).openapi({ref:"PasteCommand"}),Wg=V.merge(os).extend({type:y.literal("JAVASCRIPT")}).openapi({ref:"JavaScriptCommand"}),Ci=V.merge(jt).extend({type:y.literal("CLICK"),target:ht,doubleClick:y.boolean().optional(),rightClick:y.boolean().optional(),waitForDownload:y.boolean().optional().describe("Wait for the click to trigger a file download and for the file download to complete."),delayMs:y.number().optional(),downloadTimeoutMs:y.number().optional(),cache:Wt,relativePosition:y.object({x:y.number(),y:y.number()}).optional()}).openapi({ref:"ClickCommand"}),$g=vi.extend({fromTarget:Kr.optional(),toTarget:Kr.optional()}),xi=V.merge(jt).merge(y.object({type:y.literal("DRAG"),fromTarget:ht,toTarget:ht,steps:y.number().optional(),hoverSeconds:y.number().optional().describe("Seconds to hover the object before dropping"),cache:$g.optional()})).openapi({ref:"DragCommand"}),Mi=V.merge(jt).merge(y.object({type:y.literal("MOUSE_DRAG"),target:ht.optional(),deltaX:y.string().describe("pixels to move horizontally, can be template"),deltaY:y.string().describe("pixels to move vertically, can be template"),steps:y.number().optional(),cache:Wt})).openapi({ref:"MouseDragCommand"}),_i=V.merge(jt).merge(y.object({type:y.literal("HOVER"),target:ht,cache:Wt})).openapi({ref:"HoverCommand"}),Ii=V.merge(jt).merge(y.object({type:y.literal("FOCUS"),target:ht,cache:Wt})).openapi({ref:"FocusCommand"}),Pi=V.merge(jt).extend({type:y.literal("BLUR"),target:ht.optional(),cache:Wt}).openapi({ref:"BlurCommand"}),zC=y.object({type:y.literal("URL"),url:y.string()}).describe("Accessible link to the file, either public http or local file://").openapi({ref:"UrlSource"}),HC=y.object({type:y.literal("USER_FILE"),name:y.string()}).describe("Accessible link to the file, references the google cloud file").openapi({ref:"UploadedFileSource"}),GC=V.extend({type:y.literal("FILE_UPLOAD"),fileSource:y.discriminatedUnion("type",[zC,HC]),filename:y.string().optional()}).openapi({ref:"FileUploadCommand"}),qg=y.discriminatedUnion("type",[y.object({type:y.literal("VALUE"),value:y.string()}),y.object({type:y.literal("LABEL"),label:y.string()}),y.object({type:y.literal("INDEX"),index:y.coerce.string()})]),Oi=V.merge(jt).extend({type:y.literal("SELECT_OPTION"),target:ht,cache:Wt,choice:qg.describe("new field for selecting options, optional for backcompat")}).openapi({ref:"SelectOptionCommand"}),mu=y.union([y.literal("MULTIMODAL"),y.literal("VISION_ONLY")]),ss=V.merge(y.object({type:y.literal("AI_ASSERTION"),assertion:y.string(),disableCache:y.boolean().optional(),iframeUrl:y.string().optional(),contextChoice:mu.optional(),timeout:y.number().int().optional().describe("Max seconds to wait for assertion to be true"),cache:cu.optional()})).openapi({ref:"AIAssertionCommand"}),Xr=5,gu=600,bo=V.merge(jt).extend({type:y.literal("ELEMENT_CHECK"),target:ht,assertion:zg,cache:Wt.or(cu).optional(),timeout:y.number().int().min(0).max(gu).optional().describe("max seconds to wait for the assertion to be true")}).openapi({ref:"ElementAssertionCommand"}),Kg=V.extend({type:y.literal("PAGE_CHECK"),assertion:Hg,iframeUrl:y.string().optional().describe("url or url regex for the iframe"),timeout:y.number().int().min(0).max(gu).optional().describe("max seconds to wait for the assertion to be true")}).openapi({ref:"PageAssertionCommand"}),Yg=V.merge(y.object({type:y.literal("AI_EXTRACT"),goal:y.string(),schema:y.string().optional(),envKey:y.string().optional(),disableCache:y.boolean().optional(),iframeUrl:y.string().optional()})).openapi({ref:"AIExtractCommand"}),VC=y.object({clearContent:y.boolean().optional(),forceClearContent:y.boolean().optional(),delay:y.number().min(0).max(1e3).optional().describe("Delay between each press in milliseconds."),force:y.boolean().optional(),pressEnter:y.boolean().optional(),relativePosition:y.object({x:y.number(),y:y.number()}).optional()}),Xg=25,Li=V.merge(jt).merge(VC).extend({type:y.literal("TYPE"),target:ht.optional(),value:y.string(),cache:Wt}).openapi({ref:"TypeCommand"}),jC=V.merge(y.object({type:y.literal("PRESS"),value:y.string(),repeat:y.number().optional(),convertMeta:y.boolean().optional(),delayMs:y.number().optional()})).openapi({ref:"PressCommand"}),WC=V.merge(y.object({type:y.literal("KEY_DOWN"),value:y.string(),convertMeta:y.boolean().optional()})).openapi({ref:"KeyDownCommand"}),$C=V.merge(y.object({type:y.literal("KEY_UP"),value:y.string(),convertMeta:y.boolean().optional()})).openapi({ref:"KeyUpCommand"}),qC=y.object({type:y.literal("SUBSTRING"),substring:y.string()}),KC=y.object({type:y.literal("REGEX"),pattern:y.string()}),YC=y.object({type:y.literal("INDEX"),index:y.coerce.string()}),XC=y.discriminatedUnion("type",[qC,KC,YC]),JC=V.merge(is).merge(y.object({type:y.literal("TAB"),action:XC})).openapi({ref:"TabCommand"}),Jg=V.merge(is).merge(y.object({type:y.literal("NEW_TAB"),url:y.string()})).openapi({ref:"NewTabCommand"}),ZC=V.merge(y.object({type:y.literal("COOKIE"),value:y.string()})).openapi({ref:"CookieCommand"}),QC=V.merge(y.object({type:y.literal("LOCAL_STORAGE"),key:y.string(),value:y.string()})).openapi({ref:"LocalStorageCommand"}),ex=V.extend({type:y.literal("REQUEST")}).merge(go).openapi({ref:"RequestCommand"}),tx=V.extend({type:y.literal("GRAPHQL_REQUEST")}).merge(Gg).openapi({ref:"GraphQLRequestCommand"}),rx=V.merge(y.object({type:y.literal("SUCCESS"),condition:ss.optional()})).openapi({ref:"SuccessCommand"}),Zg=V.merge(y.object({type:y.literal("FAILURE")})).openapi({ref:"FailureCommand"}),nx=y.object({data:y.string().describe("location at which to find a jpg"),width:y.number(),height:y.number()}),Ni=V.merge(jt).merge(y.object({type:y.literal("VISUAL_DIFF"),threshold:y.number().optional().describe("default 0.1"),target:ht.optional(),screenshot:nx.optional(),cache:Wt})).openapi({ref:"VisualDiffCommand"}),ox=V.merge(y.object({type:y.literal("REGISTER_REQUEST_LISTENER"),requestMatcher:wi,key:y.string()})).openapi({ref:"RegisterRequestListenerCommand"}),ix=V.merge(y.object({type:y.literal("AWAIT_LISTENER"),key:y.string(),timeout:y.number().optional().describe("timeout")})).openapi({ref:"WaitForListenerCommand"}),ax=V.merge(y.object({type:y.literal("RECORD_REQUESTS"),requestMatcher:wi,key:y.string()})).openapi({ref:"RecordRequestsCommand"}),sx=V.merge(y.object({type:y.literal("GET_RECORDED_REQUESTS"),key:y.string()})).openapi({ref:"GetRecordedRequestsCommand"}),lx=V.merge(y.object({type:y.literal("SET_HEADER"),name:y.string(),value:y.string(),requestMatcher:wi.optional()})).openapi({ref:"SetHeaderCommand"}),cx=V.merge(y.object({type:y.literal("MOCK_ROUTE"),requestMatcher:wi,responseGenerator:y.string().describe("JavaScript code to generate a response"),fetchOriginalResponse:y.boolean().optional().describe("Whether to fetch the real response and pass it to the response generator. If enabled, the original response will be available as `response` in the code."),key:y.string().optional().describe("Key to reference this mock. This only needs to be set if you plan to remove the mock later in the test.")}).openapi({ref:"MockRouteCommandOptions"})),ux=V.merge(y.object({type:y.literal("REMOVE_ROUTE_MOCK"),key:y.string().optional().describe("Key of the mock to remove. If not set, all route mocks will be removed.")}).openapi({ref:"RemoveRouteMockCommandOptions"})),dx=V.merge(y.object({type:y.literal("OFFLINE_MODE"),enable:y.boolean()})).openapi({ref:"OfflineModeCommand"}),px=y.discriminatedUnion("type",[Ci,Li,jC,WC,$C,Oi,_C,fo,ho,ss,NC,_i,PC]),hu=y.discriminatedUnion("type",[...px.options,rx]),fu=y.discriminatedUnion("type",[...hu.options,Wg,bo,Kg,Jg,jg,Yg]),mx=y.discriminatedUnion("type",[Yg,UC,kC,pu,ZC,FC,IC,xi,bo,GC,DC,Wg,QC,Mi,Jg,Kg,BC,LC,ex,tx,So,yo,JC,Ni,Ii,Pi,jg,ox,ix,ax,sx,lx,cx,ux,dx]),Eo=y.discriminatedUnion("type",[...hu.options,...mx.options]).openapi({ref:"Command"}),ls=y.discriminatedUnion("type",[...hu.options,Zg]),W1=y.discriminatedUnion("type",[...fu.options,Zg]);function Fr(r){let e;switch(r){case"PASTE":case"AUTH_SAVE":case"VISUAL_DIFF":case"SUCCESS":case"SCROLL_DOWN":case"SCROLL_UP":case"SCROLL_LEFT":case"SCROLL_RIGHT":case"CAPTCHA":case"GO_BACK":case"GO_FORWARD":case"REFRESH":e={id:Se(),type:r};break;case"AUTH_LOAD":{e={id:Se(),type:r,storageState:""};break}case"AI_EXTRACT":e={id:Se(),type:r,goal:""};break;case"DIALOG":e={id:Se(),type:r,action:"DISMISS"};break;case"DRAG":e={id:Se(),type:r,fromTarget:{type:"description",elementDescriptor:""},toTarget:{type:"description",elementDescriptor:""}};break;case"MOUSE_DRAG":e={id:Se(),type:r,deltaX:"0",deltaY:"0",steps:1};break;case"WAIT_FOR_URL":e={id:Se(),type:r,matcher:{type:"SUBSTRING",url:""}};break;case"WAIT":e={id:Se(),type:r,delay:1};break;case"BLUR":e={id:Se(),type:r};break;case"HOVER":case"FOCUS":case"CLICK":e={id:Se(),type:r,target:{type:"description",elementDescriptor:""}};break;case"COOKIE":case"PRESS":case"COPY":case"TYPE":e={id:Se(),type:r,value:"",clearContent:!0};break;case"KEY_DOWN":case"KEY_UP":e={id:Se(),type:r,value:""};break;case"SELECT_OPTION":e={id:Se(),type:r,target:{type:"description",elementDescriptor:""},choice:{type:"VALUE",value:""}};break;case"NAVIGATE":case"NEW_TAB":return{id:Se(),type:r,url:""};case"TAB":e={id:Se(),type:r,action:{type:"SUBSTRING",substring:""}};break;case"REQUEST":e={id:Se(),type:r,url:"",method:"GET"};break;case"GRAPHQL_REQUEST":e={id:Se(),type:r,url:"",query:""};break;case"LOCAL_STORAGE":e={id:Se(),type:r,key:"",value:""};break;case"JAVASCRIPT":e={id:Se(),type:r,code:""};break;case"AI_ASSERTION":e={id:Se(),type:r,assertion:""};break;case"FILE_UPLOAD":{e={id:Se(),type:r,fileSource:{type:"URL",url:""}};break}case"ELEMENT_CHECK":{e={id:Se(),type:r,target:{type:"description",elementDescriptor:""},assertion:{type:"ELEMENT_EXISTENCE",condition:"EXISTS"}};break}case"PAGE_CHECK":{e={id:Se(),type:r,assertion:{type:"CONTENT",value:""}};break}case"REGISTER_REQUEST_LISTENER":{e={id:Se(),type:r,requestMatcher:{urlMatcher:{type:"REGEX",regex:""}},key:""};break}case"AWAIT_LISTENER":{e={id:Se(),type:r,key:""};break}case"RECORD_REQUESTS":{e={id:Se(),type:r,requestMatcher:{urlMatcher:{type:"REGEX",regex:""}},key:""};break}case"GET_RECORDED_REQUESTS":{e={id:Se(),type:r,key:""};break}case"SET_HEADER":{e={id:Se(),type:r,name:"",value:""};break}case"MOCK_ROUTE":{e={id:Se(),type:r,requestMatcher:{urlMatcher:{type:"REGEX",regex:""}},responseGenerator:""};break}case"REMOVE_ROUTE_MOCK":{e={id:Se(),type:r};break}case"OFFLINE_MODE":{e={id:Se(),type:r,enable:!0};break}default:return(n=>{throw"If Typescript complains about the line below, you missed a case or break in the switch above"})(r)}return e}function Qg(r){switch(r.type){case"BLUR":case"CLICK":case"DRAG":case"FOCUS":case"HOVER":case"MOUSE_DRAG":case"PRESS":case"KEY_DOWN":case"KEY_UP":case"SCROLL_DOWN":case"SCROLL_UP":case"SCROLL_LEFT":case"SCROLL_RIGHT":case"TYPE":return!0;case"AUTH_LOAD":case"AUTH_SAVE":case"AWAIT_LISTENER":case"SUCCESS":case"AI_ASSERTION":case"AI_EXTRACT":case"CAPTCHA":case"COOKIE":case"COPY":case"DIALOG":case"ELEMENT_CHECK":case"FILE_UPLOAD":case"GET_RECORDED_REQUESTS":case"GO_BACK":case"GO_FORWARD":case"GRAPHQL_REQUEST":case"JAVASCRIPT":case"LOCAL_STORAGE":case"NAVIGATE":case"NEW_TAB":case"PASTE":case"PAGE_CHECK":case"RECORD_REQUESTS":case"REGISTER_REQUEST_LISTENER":case"REFRESH":case"REQUEST":case"SELECT_OPTION":case"SET_HEADER":case"TAB":case"VISUAL_DIFF":case"WAIT":case"WAIT_FOR_URL":case"OFFLINE_MODE":case"MOCK_ROUTE":case"REMOVE_ROUTE_MOCK":return!1;default:return(t=>{throw"If Typescript complains about the line below, you missed a case or break in the switch above"})(r)}}import{z as gx}from"zod";var X1=gx.discriminatedUnion("type",[Pi,pu,Ci,xi,Ii,_i,Mi,ho,fo,So,yo,Oi,Li,Ni,bo]);import{z as hx}from"zod";import{z as Jr}from"zod";function Di(r){return Jr.object({key:Jr.string(),testId:Jr.string().optional(),moduleId:Jr.string().optional(),organizationId:Jr.string(),value:r})}function ki(r){return Di(r).extend({uniqueKey:Jr.string()})}function cs(r){return Jr.record(Jr.string(),ki(r))}var wt={type:!0,cache:!0},To=hx.discriminatedUnion("type",[ss.pick(wt),Pi.pick(wt),Ci.pick(wt),xi.pick(wt),bo.pick(wt),Ii.pick(wt),_i.pick(wt),Mi.pick(wt),ho.pick(wt),fo.pick(wt),So.pick(wt),yo.pick(wt),Oi.pick(wt),Li.pick(wt),Ni.pick(wt)]),Su=Object.values(nt).filter(r=>To.options.some(e=>e.shape.type.safeParse(r).success));Eo.options.forEach(r=>{if("target"in r.shape&&!Su.includes(r.shape.type.value))throw new Error(`Command ${r.shape.type.value} has a target but no cache`)});function eh(r){return Su.includes(r.type)}var th=Di(To),rh=ki(To),oH=cs(To);import{v4 as oj}from"uuid";import{z as C}from"zod";var oh=Symbol("Let zodToJsonSchema decide on which parser to use");var nh={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"},ih=r=>typeof r=="string"?{...nh,name:r}:{...nh,...r};var ah=r=>{let e=ih(r),t=e.name!==void 0?[...e.basePath,e.definitionPath,e.name]:e.basePath;return{...e,flags:{hasReferencedOpenAiAnyType:!1},currentPath:t,propertyPath:void 0,seen:new Map(Object.entries(e.definitions).map(([n,o])=>[o._def,{def:o._def,path:[...e.basePath,e.definitionPath,n],jsonSchema:void 0}]))}};function yu(r,e,t,n){n?.errorMessages&&t&&(r.errorMessage={...r.errorMessage,[e]:t})}function se(r,e,t,n,o){r[e]=t,yu(r,e,n,o)}var us=(r,e)=>{let t=0;for(;t<r.length&&t<e.length&&r[t]===e[t];t++);return[(r.length-t).toString(),...e.slice(t)].join("/")};import{ZodFirstPartyTypeKind as ie}from"zod";function De(r){if(r.target!=="openAi")return{};let e=[...r.basePath,r.definitionPath,r.openAiAnyTypeName];return r.flags.hasReferencedOpenAiAnyType=!0,{$ref:r.$refStrategy==="relative"?us(e,r.currentPath):e.join("/")}}import{ZodFirstPartyTypeKind as fx}from"zod";function sh(r,e){let t={type:"array"};return r.type?._def&&r.type?._def?.typeName!==fx.ZodAny&&(t.items=$(r.type._def,{...e,currentPath:[...e.currentPath,"items"]})),r.minLength&&se(t,"minItems",r.minLength.value,r.minLength.message,e),r.maxLength&&se(t,"maxItems",r.maxLength.value,r.maxLength.message,e),r.exactLength&&(se(t,"minItems",r.exactLength.value,r.exactLength.message,e),se(t,"maxItems",r.exactLength.value,r.exactLength.message,e)),t}function lh(r,e){let t={type:"integer",format:"int64"};if(!r.checks)return t;for(let n of r.checks)switch(n.kind){case"min":e.target==="jsonSchema7"?n.inclusive?se(t,"minimum",n.value,n.message,e):se(t,"exclusiveMinimum",n.value,n.message,e):(n.inclusive||(t.exclusiveMinimum=!0),se(t,"minimum",n.value,n.message,e));break;case"max":e.target==="jsonSchema7"?n.inclusive?se(t,"maximum",n.value,n.message,e):se(t,"exclusiveMaximum",n.value,n.message,e):(n.inclusive||(t.exclusiveMaximum=!0),se(t,"maximum",n.value,n.message,e));break;case"multipleOf":se(t,"multipleOf",n.value,n.message,e);break}return t}function ch(){return{type:"boolean"}}function ds(r,e){return $(r.type._def,e)}var uh=(r,e)=>$(r.innerType._def,e);function bu(r,e,t){let n=t??e.dateStrategy;if(Array.isArray(n))return{anyOf:n.map((o,i)=>bu(r,e,o))};switch(n){case"string":case"format:date-time":return{type:"string",format:"date-time"};case"format:date":return{type:"string",format:"date"};case"integer":return Sx(r,e)}}var Sx=(r,e)=>{let t={type:"integer",format:"unix-time"};if(e.target==="openApi3")return t;for(let n of r.checks)switch(n.kind){case"min":se(t,"minimum",n.value,n.message,e);break;case"max":se(t,"maximum",n.value,n.message,e);break}return t};function dh(r,e){return{...$(r.innerType._def,e),default:r.defaultValue()}}function ph(r,e){return e.effectStrategy==="input"?$(r.schema._def,e):De(e)}function mh(r){return{type:"string",enum:Array.from(r.values)}}var yx=r=>"type"in r&&r.type==="string"?!1:"allOf"in r;function gh(r,e){let t=[$(r.left._def,{...e,currentPath:[...e.currentPath,"allOf","0"]}),$(r.right._def,{...e,currentPath:[...e.currentPath,"allOf","1"]})].filter(i=>!!i),n=e.target==="jsonSchema2019-09"?{unevaluatedProperties:!1}:void 0,o=[];return t.forEach(i=>{if(yx(i))o.push(...i.allOf),i.unevaluatedProperties===void 0&&(n=void 0);else{let a=i;if("additionalProperties"in i&&i.additionalProperties===!1){let{additionalProperties:l,...c}=i;a=c}else n=void 0;o.push(a)}}),o.length?{allOf:o,...n}:void 0}function hh(r,e){let t=typeof r.value;return t!=="bigint"&&t!=="number"&&t!=="boolean"&&t!=="string"?{type:Array.isArray(r.value)?"array":"object"}:e.target==="openApi3"?{type:t==="bigint"?"integer":t,enum:[r.value]}:{type:t==="bigint"?"integer":t,const:r.value}}import{ZodFirstPartyTypeKind as Ui}from"zod";var Eu,cr={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:()=>(Eu===void 0&&(Eu=RegExp("^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$","u")),Eu),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 ps(r,e){let t={type:"string"};if(r.checks)for(let n of r.checks)switch(n.kind){case"min":se(t,"minLength",typeof t.minLength=="number"?Math.max(t.minLength,n.value):n.value,n.message,e);break;case"max":se(t,"maxLength",typeof t.maxLength=="number"?Math.min(t.maxLength,n.value):n.value,n.message,e);break;case"email":switch(e.emailStrategy){case"format:email":ur(t,"email",n.message,e);break;case"format:idn-email":ur(t,"idn-email",n.message,e);break;case"pattern:zod":Rt(t,cr.email,n.message,e);break}break;case"url":ur(t,"uri",n.message,e);break;case"uuid":ur(t,"uuid",n.message,e);break;case"regex":Rt(t,n.regex,n.message,e);break;case"cuid":Rt(t,cr.cuid,n.message,e);break;case"cuid2":Rt(t,cr.cuid2,n.message,e);break;case"startsWith":Rt(t,RegExp(`^${Tu(n.value,e)}`),n.message,e);break;case"endsWith":Rt(t,RegExp(`${Tu(n.value,e)}$`),n.message,e);break;case"datetime":ur(t,"date-time",n.message,e);break;case"date":ur(t,"date",n.message,e);break;case"time":ur(t,"time",n.message,e);break;case"duration":ur(t,"duration",n.message,e);break;case"length":se(t,"minLength",typeof t.minLength=="number"?Math.max(t.minLength,n.value):n.value,n.message,e),se(t,"maxLength",typeof t.maxLength=="number"?Math.min(t.maxLength,n.value):n.value,n.message,e);break;case"includes":{Rt(t,RegExp(Tu(n.value,e)),n.message,e);break}case"ip":{n.version!=="v6"&&ur(t,"ipv4",n.message,e),n.version!=="v4"&&ur(t,"ipv6",n.message,e);break}case"base64url":Rt(t,cr.base64url,n.message,e);break;case"jwt":Rt(t,cr.jwt,n.message,e);break;case"cidr":{n.version!=="v6"&&Rt(t,cr.ipv4Cidr,n.message,e),n.version!=="v4"&&Rt(t,cr.ipv6Cidr,n.message,e);break}case"emoji":Rt(t,cr.emoji(),n.message,e);break;case"ulid":{Rt(t,cr.ulid,n.message,e);break}case"base64":{switch(e.base64Strategy){case"format:binary":{ur(t,"binary",n.message,e);break}case"contentEncoding:base64":{se(t,"contentEncoding","base64",n.message,e);break}case"pattern:zod":{Rt(t,cr.base64,n.message,e);break}}break}case"nanoid":Rt(t,cr.nanoid,n.message,e);case"toLowerCase":case"toUpperCase":case"trim":break;default:}return t}function Tu(r,e){return e.patternStrategy==="escape"?Ex(r):r}var bx=new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789");function Ex(r){let e="";for(let t=0;t<r.length;t++)bx.has(r[t])||(e+="\\"),e+=r[t];return e}function ur(r,e,t,n){r.format||r.anyOf?.some(o=>o.format)?(r.anyOf||(r.anyOf=[]),r.format&&(r.anyOf.push({format:r.format,...r.errorMessage&&n.errorMessages&&{errorMessage:{format:r.errorMessage.format}}}),delete r.format,r.errorMessage&&(delete r.errorMessage.format,Object.keys(r.errorMessage).length===0&&delete r.errorMessage)),r.anyOf.push({format:e,...t&&n.errorMessages&&{errorMessage:{format:t}}})):se(r,"format",e,t,n)}function Rt(r,e,t,n){r.pattern||r.allOf?.some(o=>o.pattern)?(r.allOf||(r.allOf=[]),r.pattern&&(r.allOf.push({pattern:r.pattern,...r.errorMessage&&n.errorMessages&&{errorMessage:{pattern:r.errorMessage.pattern}}}),delete r.pattern,r.errorMessage&&(delete r.errorMessage.pattern,Object.keys(r.errorMessage).length===0&&delete r.errorMessage)),r.allOf.push({pattern:fh(e,n),...t&&n.errorMessages&&{errorMessage:{pattern:t}}})):se(r,"pattern",fh(e,n),t,n)}function fh(r,e){if(!e.applyRegexFlags||!r.flags)return r.source;let t={i:r.flags.includes("i"),m:r.flags.includes("m"),s:r.flags.includes("s")},n=t.i?r.source.toLowerCase():r.source,o="",i=!1,a=!1,l=!1;for(let c=0;c<n.length;c++){if(i){o+=n[c],i=!1;continue}if(t.i){if(a){if(n[c].match(/[a-z]/)){l?(o+=n[c],o+=`${n[c-2]}-${n[c]}`.toUpperCase(),l=!1):n[c+1]==="-"&&n[c+2]?.match(/[a-z]/)?(o+=n[c],l=!0):o+=`${n[c]}${n[c].toUpperCase()}`;continue}}else if(n[c].match(/[a-z]/)){o+=`[${n[c]}${n[c].toUpperCase()}]`;continue}}if(t.m){if(n[c]==="^"){o+=`(^|(?<=[\r
|
|
15
3
|
]))`;continue}else if(n[c]==="$"){o+=`($|(?=[\r
|
|
16
4
|
]))`;continue}}if(t.s&&n[c]==="."){o+=a?`${n[c]}\r
|
|
17
5
|
`:`[${n[c]}\r
|
|
18
|
-
]`;continue}o+=n[c],n[c]==="\\"?i=!0:a&&n[c]==="]"?a=!1:!a&&n[c]==="["&&(a=!0)}try{new RegExp(o)}catch{return console.warn(`Could not convert regex pattern at ${e.currentPath.join("/")} to a flag-independent form! Falling back to the flag-ignorant source`),r.source}return o}function Tl(r,e){if(e.target==="openAi"&&console.warn("Warning: OpenAI may not support records in schemas! Try an array of key-value pairs instead."),e.target==="openApi3"&&r.keyType?._def.typeName===Sa.ZodEnum)return{type:"object",required:r.keyType._def.values,properties:r.keyType._def.values.reduce((n,o)=>({...n,[o]:X(r.valueType._def,{...e,currentPath:[...e.currentPath,"properties",o]})??De(e)}),{}),additionalProperties:e.rejectedAdditionalProperties};let t={type:"object",additionalProperties:X(r.valueType._def,{...e,currentPath:[...e.currentPath,"additionalProperties"]})??e.allowedAdditionalProperties};if(e.target==="openApi3")return t;if(r.keyType?._def.typeName===Sa.ZodString&&r.keyType._def.checks?.length){let{type:n,...o}=El(r.keyType._def,e);return{...t,propertyNames:o}}else{if(r.keyType?._def.typeName===Sa.ZodEnum)return{...t,propertyNames:{enum:r.keyType._def.values}};if(r.keyType?._def.typeName===Sa.ZodBranded&&r.keyType._def.type._def.typeName===Sa.ZodString&&r.keyType._def.type._def.checks?.length){let{type:n,...o}=bl(r.keyType._def,e);return{...t,propertyNames:o}}}return t}function qy(r,e){if(e.mapStrategy==="record")return Tl(r,e);let t=X(r.keyType._def,{...e,currentPath:[...e.currentPath,"items","items","0"]})||De(e),n=X(r.valueType._def,{...e,currentPath:[...e.currentPath,"items","items","1"]})||De(e);return{type:"array",maxItems:125,items:{type:"array",items:[t,n],minItems:2,maxItems:2}}}function Ky(r){let e=r.values,n=Object.keys(r.values).filter(i=>typeof e[e[i]]!="number").map(i=>e[i]),o=Array.from(new Set(n.map(i=>typeof i)));return{type:o.length===1?o[0]==="string"?"string":"number":["string","number"],enum:n}}function Yy(r){return r.target==="openAi"?void 0:{not:De({...r,currentPath:[...r.currentPath,"not"]})}}function Xy(r){return r.target==="openApi3"?{enum:["null"],nullable:!0}:{type:"null"}}var ya={ZodString:"string",ZodNumber:"number",ZodBigInt:"integer",ZodBoolean:"boolean",ZodNull:"null"};function Zy(r,e){if(e.target==="openApi3")return Jy(r,e);let t=r.options instanceof Map?Array.from(r.options.values()):r.options;if(t.every(n=>n._def.typeName in ya&&(!n._def.checks||!n._def.checks.length))){let n=t.reduce((o,i)=>{let a=ya[i._def.typeName];return a&&!o.includes(a)?[...o,a]:o},[]);return{type:n.length>1?n:n[0]}}else if(t.every(n=>n._def.typeName==="ZodLiteral"&&!n.description)){let n=t.reduce((o,i)=>{let a=typeof i._def.value;switch(a){case"string":case"number":case"boolean":return[...o,a];case"bigint":return[...o,"integer"];case"object":if(i._def.value===null)return[...o,"null"];case"symbol":case"undefined":case"function":default:return o}},[]);if(n.length===t.length){let o=n.filter((i,a,s)=>s.indexOf(i)===a);return{type:o.length>1?o:o[0],enum:t.reduce((i,a)=>i.includes(a._def.value)?i:[...i,a._def.value],[])}}}else if(t.every(n=>n._def.typeName==="ZodEnum"))return{type:"string",enum:t.reduce((n,o)=>[...n,...o._def.values.filter(i=>!n.includes(i))],[])};return Jy(r,e)}var Jy=(r,e)=>{let t=(r.options instanceof Map?Array.from(r.options.values()):r.options).map((n,o)=>X(n._def,{...e,currentPath:[...e.currentPath,"anyOf",`${o}`]})).filter(n=>!!n&&(!e.strictUnions||typeof n=="object"&&Object.keys(n).length>0));return t.length?{anyOf:t}:void 0};function Qy(r,e){if(["ZodString","ZodNumber","ZodBigInt","ZodBoolean","ZodNull"].includes(r.innerType._def.typeName)&&(!r.innerType._def.checks||!r.innerType._def.checks.length))return e.target==="openApi3"?{type:ya[r.innerType._def.typeName],nullable:!0}:{type:[ya[r.innerType._def.typeName],"null"]};if(e.target==="openApi3"){let n=X(r.innerType._def,{...e,currentPath:[...e.currentPath]});return n&&"$ref"in n?{allOf:[n],nullable:!0}:n&&{...n,nullable:!0}}let t=X(r.innerType._def,{...e,currentPath:[...e.currentPath,"anyOf","0"]});return t&&{anyOf:[t,{type:"null"}]}}function eb(r,e){let t={type:"number"};if(!r.checks)return t;for(let n of r.checks)switch(n.kind){case"int":t.type="integer",Ud(t,"type",n.message,e);break;case"min":e.target==="jsonSchema7"?n.inclusive?ue(t,"minimum",n.value,n.message,e):ue(t,"exclusiveMinimum",n.value,n.message,e):(n.inclusive||(t.exclusiveMinimum=!0),ue(t,"minimum",n.value,n.message,e));break;case"max":e.target==="jsonSchema7"?n.inclusive?ue(t,"maximum",n.value,n.message,e):ue(t,"exclusiveMaximum",n.value,n.message,e):(n.inclusive||(t.exclusiveMaximum=!0),ue(t,"maximum",n.value,n.message,e));break;case"multipleOf":ue(t,"multipleOf",n.value,n.message,e);break}return t}function tb(r,e){let t=e.target==="openAi",n={type:"object",properties:{}},o=[],i=r.shape();for(let s in i){let c=i[s];if(c===void 0||c._def===void 0)continue;let l=rO(c);l&&t&&(c._def.typeName==="ZodOptional"&&(c=c._def.innerType),c.isNullable()||(c=c.nullable()),l=!1);let u=X(c._def,{...e,currentPath:[...e.currentPath,"properties",s],propertyPath:[...e.currentPath,"properties",s]});u!==void 0&&(n.properties[s]=u,l||o.push(s))}o.length&&(n.required=o);let a=tO(r,e);return a!==void 0&&(n.additionalProperties=a),n}function tO(r,e){if(r.catchall._def.typeName!=="ZodNever")return X(r.catchall._def,{...e,currentPath:[...e.currentPath,"additionalProperties"]});switch(r.unknownKeys){case"passthrough":return e.allowedAdditionalProperties;case"strict":return e.rejectedAdditionalProperties;case"strip":return e.removeAdditionalStrategy==="strict"?e.allowedAdditionalProperties:e.rejectedAdditionalProperties}}function rO(r){try{return r.isOptional()}catch{return!0}}var rb=(r,e)=>{if(e.currentPath.toString()===e.propertyPath?.toString())return X(r.innerType._def,e);let t=X(r.innerType._def,{...e,currentPath:[...e.currentPath,"anyOf","1"]});return t?{anyOf:[{not:De(e)},t]}:De(e)};var nb=(r,e)=>{if(e.pipeStrategy==="input")return X(r.in._def,e);if(e.pipeStrategy==="output")return X(r.out._def,e);let t=X(r.in._def,{...e,currentPath:[...e.currentPath,"allOf","0"]}),n=X(r.out._def,{...e,currentPath:[...e.currentPath,"allOf",t?"1":"0"]});return{allOf:[t,n].filter(o=>o!==void 0)}};function ob(r,e){return X(r.type._def,e)}function ib(r,e){let n={type:"array",uniqueItems:!0,items:X(r.valueType._def,{...e,currentPath:[...e.currentPath,"items"]})};return r.minSize&&ue(n,"minItems",r.minSize.value,r.minSize.message,e),r.maxSize&&ue(n,"maxItems",r.maxSize.value,r.maxSize.message,e),n}function ab(r,e){return r.rest?{type:"array",minItems:r.items.length,items:r.items.map((t,n)=>X(t._def,{...e,currentPath:[...e.currentPath,"items",`${n}`]})).reduce((t,n)=>n===void 0?t:[...t,n],[]),additionalItems:X(r.rest._def,{...e,currentPath:[...e.currentPath,"additionalItems"]})}:{type:"array",minItems:r.items.length,maxItems:r.items.length,items:r.items.map((t,n)=>X(t._def,{...e,currentPath:[...e.currentPath,"items",`${n}`]})).reduce((t,n)=>n===void 0?t:[...t,n],[])}}function sb(r){return{not:De(r)}}function lb(r){return De(r)}var cb=(r,e)=>X(r.innerType._def,e);var ub=(r,e,t)=>{switch(e){case le.ZodString:return El(r,t);case le.ZodNumber:return eb(r,t);case le.ZodObject:return tb(r,t);case le.ZodBigInt:return Fy(r,t);case le.ZodBoolean:return By();case le.ZodDate:return Fd(r,t);case le.ZodUndefined:return sb(t);case le.ZodNull:return Xy(t);case le.ZodArray:return Uy(r,t);case le.ZodUnion:case le.ZodDiscriminatedUnion:return Zy(r,t);case le.ZodIntersection:return Vy(r,t);case le.ZodTuple:return ab(r,t);case le.ZodRecord:return Tl(r,t);case le.ZodLiteral:return Wy(r,t);case le.ZodEnum:return jy(r);case le.ZodNativeEnum:return Ky(r);case le.ZodNullable:return Qy(r,t);case le.ZodOptional:return rb(r,t);case le.ZodMap:return qy(r,t);case le.ZodSet:return ib(r,t);case le.ZodLazy:return()=>r.getter()._def;case le.ZodPromise:return ob(r,t);case le.ZodNaN:case le.ZodNever:return Yy(t);case le.ZodEffects:return Gy(r,t);case le.ZodAny:return De(t);case le.ZodUnknown:return lb(t);case le.ZodDefault:return Hy(r,t);case le.ZodBranded:return bl(r,t);case le.ZodReadonly:return cb(r,t);case le.ZodCatch:return zy(r,t);case le.ZodPipeline:return nb(r,t);case le.ZodFunction:case le.ZodVoid:case le.ZodSymbol:return;default:return(n=>{})(e)}};function X(r,e,t=!1){let n=e.seen.get(r);if(e.override){let s=e.override?.(r,e,n,t);if(s!==Ny)return s}if(n&&!t){let s=nO(n,e);if(s!==void 0)return s}let o={def:r,path:e.currentPath,jsonSchema:void 0};e.seen.set(r,o);let i=ub(r,r.typeName,e),a=typeof i=="function"?X(i(),e):i;if(a&&oO(r,e,a),e.postProcess){let s=e.postProcess(a,r,e);return o.jsonSchema=a,s}return o.jsonSchema=a,a}var nO=(r,e)=>{switch(e.$refStrategy){case"root":return{$ref:r.path.join("/")};case"relative":return{$ref:yl(e.currentPath,r.path)};case"none":case"seen":return r.path.length<e.currentPath.length&&r.path.every((t,n)=>e.currentPath[n]===t)?(console.warn(`Recursive reference detected at ${e.currentPath.join("/")}! Defaulting to any`),De(e)):e.$refStrategy==="seen"?De(e):void 0}},oO=(r,e,t)=>(r.description&&(t.description=r.description,e.markdownDescription&&(t.markdownDescription=r.description)),t);var $n=(r,e)=>{let t=Dy(e),n=typeof e=="object"&&e.definitions?Object.entries(e.definitions).reduce((c,[l,u])=>({...c,[l]:X(u._def,{...t,currentPath:[...t.basePath,t.definitionPath,l]},!0)??De(t)}),{}):void 0,o=typeof e=="string"?e:e?.nameStrategy==="title"?void 0:e?.name,i=X(r._def,o===void 0?t:{...t,currentPath:[...t.basePath,t.definitionPath,o]},!1)??De(t),a=typeof e=="object"&&e.name!==void 0&&e.nameStrategy==="title"?e.name:void 0;a!==void 0&&(i.title=a),t.flags.hasReferencedOpenAiAnyType&&(n||(n={}),n[t.openAiAnyTypeName]||(n[t.openAiAnyTypeName]={type:["string","number","integer","boolean","array","null"],items:{$ref:t.$refStrategy==="relative"?"1":[...t.basePath,t.definitionPath,t.openAiAnyTypeName].join("/")}}));let s=o===void 0?n?{...i,[t.definitionPath]:n}:i:{$ref:[...t.$refStrategy==="relative"?[]:t.basePath,t.definitionPath,o].join("/"),[t.definitionPath]:{...n,[o]:i}};return t.target==="jsonSchema7"?s.$schema="http://json-schema.org/draft-07/schema#":(t.target==="jsonSchema2019-09"||t.target==="openAi")&&(s.$schema="https://json-schema.org/draft/2019-09/schema#"),t.target==="openAi"&&("anyOf"in s||"oneOf"in s||"allOf"in s||"type"in s&&Array.isArray(s.type))&&console.warn("Warning: OpenAI may not support schemas with unions as roots! Try wrapping it in an object property."),s};import{z as Ir}from"zod";import{extendZodWithOpenApi as iO}from"zod-openapi";iO(Ir);var Re=(p=>(p.AI_PROVIDER="AIProviderError",p.USER_INFRA="UserInfrastructureError",p.ACTION_FAILURE="ActionFailureError",p.ASSERTION_FAILURE="AssertionFailureError",p.CONFIG_ERROR="UserConfigurationError",p.SETUP_FAILURE="SetupFailureError",p.TEARDOWN_FAILURE="TeardownFailureError",p.WEB_AGENT_PLATFORM="InternalWebAgentError",p.UNKNOWN_PLATFORM="InternalPlatformError",p.JOB_TIMEOUT="JobTimeoutError",p.CONCURRENCY_ERROR="ConcurrencyError",p.UNKNOWN="UnknownError",p))(Re||{});var Hd=Ir.object({reason:Ir.nativeEnum(Re),previousStepsDescription:Ir.array(Ir.string()).optional(),summary:Ir.string(),rootCause:Ir.string().optional()}).openapi({ref:"TestResultClassification"}),vl=Ir.object({errorMessage:Ir.string(),errorStack:Ir.string().optional(),classification:Hd.optional()}).openapi({ref:"TestFailureDetails"});var _=class extends Error{reason;constructor(e,t,n){let o=!1;for(let i of Object.values(Re))if(t.startsWith(i)){o=!0,e=i;break}if(n?.errOptions?.cause)super(o?t:`${e}: ${t}`,n?.errOptions);else{let i=o?t:`${e}${t?`: ${t}`:""}`;super(i,n?.errOptions)}this.name="TestFailureError",this.stack=this.stack?.slice(this.name.length+2),this.reason=e}toString(){return this.message}toJSON(){return{message:this.message}}},Xo=class extends Error{updatedLocatorMemory;constructor(e,t,n={}){super(e,n),this.updatedLocatorMemory=t,this.name="NoElementsFoundUsingAIError"}},hn=class extends Error{decisions;constructor(e,t,n={}){super(e,n),this.decisions=t,this.name="NoElementsFoundUsingCacheError"}toString(){return`${this.message}
|
|
6
|
+
]`;continue}o+=n[c],n[c]==="\\"?i=!0:a&&n[c]==="]"?a=!1:!a&&n[c]==="["&&(a=!0)}try{new RegExp(o)}catch{return console.warn(`Could not convert regex pattern at ${e.currentPath.join("/")} to a flag-independent form! Falling back to the flag-ignorant source`),r.source}return o}function ms(r,e){if(e.target==="openAi"&&console.warn("Warning: OpenAI may not support records in schemas! Try an array of key-value pairs instead."),e.target==="openApi3"&&r.keyType?._def.typeName===Ui.ZodEnum)return{type:"object",required:r.keyType._def.values,properties:r.keyType._def.values.reduce((n,o)=>({...n,[o]:$(r.valueType._def,{...e,currentPath:[...e.currentPath,"properties",o]})??De(e)}),{}),additionalProperties:e.rejectedAdditionalProperties};let t={type:"object",additionalProperties:$(r.valueType._def,{...e,currentPath:[...e.currentPath,"additionalProperties"]})??e.allowedAdditionalProperties};if(e.target==="openApi3")return t;if(r.keyType?._def.typeName===Ui.ZodString&&r.keyType._def.checks?.length){let{type:n,...o}=ps(r.keyType._def,e);return{...t,propertyNames:o}}else{if(r.keyType?._def.typeName===Ui.ZodEnum)return{...t,propertyNames:{enum:r.keyType._def.values}};if(r.keyType?._def.typeName===Ui.ZodBranded&&r.keyType._def.type._def.typeName===Ui.ZodString&&r.keyType._def.type._def.checks?.length){let{type:n,...o}=ds(r.keyType._def,e);return{...t,propertyNames:o}}}return t}function Sh(r,e){if(e.mapStrategy==="record")return ms(r,e);let t=$(r.keyType._def,{...e,currentPath:[...e.currentPath,"items","items","0"]})||De(e),n=$(r.valueType._def,{...e,currentPath:[...e.currentPath,"items","items","1"]})||De(e);return{type:"array",maxItems:125,items:{type:"array",items:[t,n],minItems:2,maxItems:2}}}function yh(r){let e=r.values,n=Object.keys(r.values).filter(i=>typeof e[e[i]]!="number").map(i=>e[i]),o=Array.from(new Set(n.map(i=>typeof i)));return{type:o.length===1?o[0]==="string"?"string":"number":["string","number"],enum:n}}function bh(r){return r.target==="openAi"?void 0:{not:De({...r,currentPath:[...r.currentPath,"not"]})}}function Eh(r){return r.target==="openApi3"?{enum:["null"],nullable:!0}:{type:"null"}}var Fi={ZodString:"string",ZodNumber:"number",ZodBigInt:"integer",ZodBoolean:"boolean",ZodNull:"null"};function vh(r,e){if(e.target==="openApi3")return Th(r,e);let t=r.options instanceof Map?Array.from(r.options.values()):r.options;if(t.every(n=>n._def.typeName in Fi&&(!n._def.checks||!n._def.checks.length))){let n=t.reduce((o,i)=>{let a=Fi[i._def.typeName];return a&&!o.includes(a)?[...o,a]:o},[]);return{type:n.length>1?n:n[0]}}else if(t.every(n=>n._def.typeName==="ZodLiteral"&&!n.description)){let n=t.reduce((o,i)=>{let a=typeof i._def.value;switch(a){case"string":case"number":case"boolean":return[...o,a];case"bigint":return[...o,"integer"];case"object":if(i._def.value===null)return[...o,"null"];case"symbol":case"undefined":case"function":default:return o}},[]);if(n.length===t.length){let o=n.filter((i,a,l)=>l.indexOf(i)===a);return{type:o.length>1?o:o[0],enum:t.reduce((i,a)=>i.includes(a._def.value)?i:[...i,a._def.value],[])}}}else if(t.every(n=>n._def.typeName==="ZodEnum"))return{type:"string",enum:t.reduce((n,o)=>[...n,...o._def.values.filter(i=>!n.includes(i))],[])};return Th(r,e)}var Th=(r,e)=>{let t=(r.options instanceof Map?Array.from(r.options.values()):r.options).map((n,o)=>$(n._def,{...e,currentPath:[...e.currentPath,"anyOf",`${o}`]})).filter(n=>!!n&&(!e.strictUnions||typeof n=="object"&&Object.keys(n).length>0));return t.length?{anyOf:t}:void 0};function Ah(r,e){if(["ZodString","ZodNumber","ZodBigInt","ZodBoolean","ZodNull"].includes(r.innerType._def.typeName)&&(!r.innerType._def.checks||!r.innerType._def.checks.length))return e.target==="openApi3"?{type:Fi[r.innerType._def.typeName],nullable:!0}:{type:[Fi[r.innerType._def.typeName],"null"]};if(e.target==="openApi3"){let n=$(r.innerType._def,{...e,currentPath:[...e.currentPath]});return n&&"$ref"in n?{allOf:[n],nullable:!0}:n&&{...n,nullable:!0}}let t=$(r.innerType._def,{...e,currentPath:[...e.currentPath,"anyOf","0"]});return t&&{anyOf:[t,{type:"null"}]}}function wh(r,e){let t={type:"number"};if(!r.checks)return t;for(let n of r.checks)switch(n.kind){case"int":t.type="integer",yu(t,"type",n.message,e);break;case"min":e.target==="jsonSchema7"?n.inclusive?se(t,"minimum",n.value,n.message,e):se(t,"exclusiveMinimum",n.value,n.message,e):(n.inclusive||(t.exclusiveMinimum=!0),se(t,"minimum",n.value,n.message,e));break;case"max":e.target==="jsonSchema7"?n.inclusive?se(t,"maximum",n.value,n.message,e):se(t,"exclusiveMaximum",n.value,n.message,e):(n.inclusive||(t.exclusiveMaximum=!0),se(t,"maximum",n.value,n.message,e));break;case"multipleOf":se(t,"multipleOf",n.value,n.message,e);break}return t}function Rh(r,e){let t=e.target==="openAi",n={type:"object",properties:{}},o=[],i=r.shape();for(let l in i){let c=i[l];if(c===void 0||c._def===void 0)continue;let s=vx(c);s&&t&&(c._def.typeName==="ZodOptional"&&(c=c._def.innerType),c.isNullable()||(c=c.nullable()),s=!1);let u=$(c._def,{...e,currentPath:[...e.currentPath,"properties",l],propertyPath:[...e.currentPath,"properties",l]});u!==void 0&&(n.properties[l]=u,s||o.push(l))}o.length&&(n.required=o);let a=Tx(r,e);return a!==void 0&&(n.additionalProperties=a),n}function Tx(r,e){if(r.catchall._def.typeName!=="ZodNever")return $(r.catchall._def,{...e,currentPath:[...e.currentPath,"additionalProperties"]});switch(r.unknownKeys){case"passthrough":return e.allowedAdditionalProperties;case"strict":return e.rejectedAdditionalProperties;case"strip":return e.removeAdditionalStrategy==="strict"?e.allowedAdditionalProperties:e.rejectedAdditionalProperties}}function vx(r){try{return r.isOptional()}catch{return!0}}var Ch=(r,e)=>{if(e.currentPath.toString()===e.propertyPath?.toString())return $(r.innerType._def,e);let t=$(r.innerType._def,{...e,currentPath:[...e.currentPath,"anyOf","1"]});return t?{anyOf:[{not:De(e)},t]}:De(e)};var xh=(r,e)=>{if(e.pipeStrategy==="input")return $(r.in._def,e);if(e.pipeStrategy==="output")return $(r.out._def,e);let t=$(r.in._def,{...e,currentPath:[...e.currentPath,"allOf","0"]}),n=$(r.out._def,{...e,currentPath:[...e.currentPath,"allOf",t?"1":"0"]});return{allOf:[t,n].filter(o=>o!==void 0)}};function Mh(r,e){return $(r.type._def,e)}function _h(r,e){let n={type:"array",uniqueItems:!0,items:$(r.valueType._def,{...e,currentPath:[...e.currentPath,"items"]})};return r.minSize&&se(n,"minItems",r.minSize.value,r.minSize.message,e),r.maxSize&&se(n,"maxItems",r.maxSize.value,r.maxSize.message,e),n}function Ih(r,e){return r.rest?{type:"array",minItems:r.items.length,items:r.items.map((t,n)=>$(t._def,{...e,currentPath:[...e.currentPath,"items",`${n}`]})).reduce((t,n)=>n===void 0?t:[...t,n],[]),additionalItems:$(r.rest._def,{...e,currentPath:[...e.currentPath,"additionalItems"]})}:{type:"array",minItems:r.items.length,maxItems:r.items.length,items:r.items.map((t,n)=>$(t._def,{...e,currentPath:[...e.currentPath,"items",`${n}`]})).reduce((t,n)=>n===void 0?t:[...t,n],[])}}function Ph(r){return{not:De(r)}}function Oh(r){return De(r)}var Lh=(r,e)=>$(r.innerType._def,e);var Nh=(r,e,t)=>{switch(e){case ie.ZodString:return ps(r,t);case ie.ZodNumber:return wh(r,t);case ie.ZodObject:return Rh(r,t);case ie.ZodBigInt:return lh(r,t);case ie.ZodBoolean:return ch();case ie.ZodDate:return bu(r,t);case ie.ZodUndefined:return Ph(t);case ie.ZodNull:return Eh(t);case ie.ZodArray:return sh(r,t);case ie.ZodUnion:case ie.ZodDiscriminatedUnion:return vh(r,t);case ie.ZodIntersection:return gh(r,t);case ie.ZodTuple:return Ih(r,t);case ie.ZodRecord:return ms(r,t);case ie.ZodLiteral:return hh(r,t);case ie.ZodEnum:return mh(r);case ie.ZodNativeEnum:return yh(r);case ie.ZodNullable:return Ah(r,t);case ie.ZodOptional:return Ch(r,t);case ie.ZodMap:return Sh(r,t);case ie.ZodSet:return _h(r,t);case ie.ZodLazy:return()=>r.getter()._def;case ie.ZodPromise:return Mh(r,t);case ie.ZodNaN:case ie.ZodNever:return bh(t);case ie.ZodEffects:return ph(r,t);case ie.ZodAny:return De(t);case ie.ZodUnknown:return Oh(t);case ie.ZodDefault:return dh(r,t);case ie.ZodBranded:return ds(r,t);case ie.ZodReadonly:return Lh(r,t);case ie.ZodCatch:return uh(r,t);case ie.ZodPipeline:return xh(r,t);case ie.ZodFunction:case ie.ZodVoid:case ie.ZodSymbol:return;default:return(n=>{})(e)}};function $(r,e,t=!1){let n=e.seen.get(r);if(e.override){let l=e.override?.(r,e,n,t);if(l!==oh)return l}if(n&&!t){let l=Ax(n,e);if(l!==void 0)return l}let o={def:r,path:e.currentPath,jsonSchema:void 0};e.seen.set(r,o);let i=Nh(r,r.typeName,e),a=typeof i=="function"?$(i(),e):i;if(a&&wx(r,e,a),e.postProcess){let l=e.postProcess(a,r,e);return o.jsonSchema=a,l}return o.jsonSchema=a,a}var Ax=(r,e)=>{switch(e.$refStrategy){case"root":return{$ref:r.path.join("/")};case"relative":return{$ref:us(e.currentPath,r.path)};case"none":case"seen":return r.path.length<e.currentPath.length&&r.path.every((t,n)=>e.currentPath[n]===t)?(console.warn(`Recursive reference detected at ${e.currentPath.join("/")}! Defaulting to any`),De(e)):e.$refStrategy==="seen"?De(e):void 0}},wx=(r,e,t)=>(r.description&&(t.description=r.description,e.markdownDescription&&(t.markdownDescription=r.description)),t);var Mn=(r,e)=>{let t=ah(e),n=typeof e=="object"&&e.definitions?Object.entries(e.definitions).reduce((c,[s,u])=>({...c,[s]:$(u._def,{...t,currentPath:[...t.basePath,t.definitionPath,s]},!0)??De(t)}),{}):void 0,o=typeof e=="string"?e:e?.nameStrategy==="title"?void 0:e?.name,i=$(r._def,o===void 0?t:{...t,currentPath:[...t.basePath,t.definitionPath,o]},!1)??De(t),a=typeof e=="object"&&e.name!==void 0&&e.nameStrategy==="title"?e.name:void 0;a!==void 0&&(i.title=a),t.flags.hasReferencedOpenAiAnyType&&(n||(n={}),n[t.openAiAnyTypeName]||(n[t.openAiAnyTypeName]={type:["string","number","integer","boolean","array","null"],items:{$ref:t.$refStrategy==="relative"?"1":[...t.basePath,t.definitionPath,t.openAiAnyTypeName].join("/")}}));let l=o===void 0?n?{...i,[t.definitionPath]:n}:i:{$ref:[...t.$refStrategy==="relative"?[]:t.basePath,t.definitionPath,o].join("/"),[t.definitionPath]:{...n,[o]:i}};return t.target==="jsonSchema7"?l.$schema="http://json-schema.org/draft-07/schema#":(t.target==="jsonSchema2019-09"||t.target==="openAi")&&(l.$schema="https://json-schema.org/draft/2019-09/schema#"),t.target==="openAi"&&("anyOf"in l||"oneOf"in l||"allOf"in l||"type"in l&&Array.isArray(l.type))&&console.warn("Warning: OpenAI may not support schemas with unions as roots! Try wrapping it in an object property."),l};import{z as Er}from"zod";import{extendZodWithOpenApi as Rx}from"zod-openapi";Rx(Er);var we=(p=>(p.AI_PROVIDER="AIProviderError",p.USER_INFRA="UserInfrastructureError",p.ACTION_FAILURE="ActionFailureError",p.ASSERTION_FAILURE="AssertionFailureError",p.CONFIG_ERROR="UserConfigurationError",p.SETUP_FAILURE="SetupFailureError",p.TEARDOWN_FAILURE="TeardownFailureError",p.WEB_AGENT_PLATFORM="InternalWebAgentError",p.UNKNOWN_PLATFORM="InternalPlatformError",p.JOB_TIMEOUT="JobTimeoutError",p.CONCURRENCY_ERROR="ConcurrencyError",p.UNKNOWN="UnknownError",p))(we||{});var vu=Er.object({reason:Er.nativeEnum(we),previousStepsDescription:Er.array(Er.string()).optional(),summary:Er.string(),rootCause:Er.string().optional()}).openapi({ref:"TestResultClassification"}),gs=Er.object({errorMessage:Er.string(),errorStack:Er.string().optional(),classification:vu.optional()}).openapi({ref:"TestFailureDetails"});var w=class extends Error{reason;constructor(e,t,n){let o=!1;for(let i of Object.values(we))if(t.startsWith(i)){o=!0,e=i;break}if(n?.errOptions?.cause)super(o?t:`${e}: ${t}`,n?.errOptions);else{let i=o?t:`${e}${t?`: ${t}`:""}`;super(i,n?.errOptions)}this.name="TestFailureError",this.stack=this.stack?.slice(this.name.length+2),this.reason=e}toString(){return this.message}toJSON(){return{message:this.message}}},vo=class extends Error{updatedLocatorMemory;constructor(e,t,n={}){super(e,n),this.updatedLocatorMemory=t,this.name="NoElementsFoundUsingAIError"}},Zr=class extends Error{decisions;constructor(e,t,n={}){super(e,n),this.decisions=t,this.name="NoElementsFoundUsingCacheError"}toString(){return`${this.message}
|
|
19
7
|
Decisions:
|
|
20
8
|
${this.decisions.map(e=>e.toString()).join(`
|
|
21
|
-
`)}`}};function db(r){return r instanceof Error?r.message.includes("Timeout")&&r.message.includes("exceeded")&&r.message.includes("waiting for locator"):!1}function Gd(r){return!(r instanceof Error)||r.message.includes("locator resolved to visible")?!1:!!(r.message.includes("Timeout")&&r.message.includes("exceeded")&&r.message.includes("body >")||r.message.includes("Element is not attached to the DOM"))}var Pr=class extends Error{retryableWithAI;constructor(e,t,n={}){super(e,n),this.name="CacheAttributesDisqualifyElementError",this.retryableWithAI=t}},Al=class extends Pr{constructor(e,t={}){super(e,!0,t),this.name="BoundingBoxMovedError"}},wl=class extends Pr{constructor(e,t={}){super(e,!1,t),this.name="ZeroOpacityError"}};function jd(r){return r instanceof Error?r.message.includes("Could not find attribute data-momentic-id for object"):!1}function Vd(r){return r instanceof Error?r.message.includes("Timeout")&&r.message.includes("exceeded")&&r.message.includes("waiting for locator")&&r.message.includes("data-momentic-id")&&!r.message.includes("locator resolved")&&!r.message.includes("waiting for element to be"):!1}function Wd(r){return r instanceof Error?r.message.includes("Protocol error (DOM.resolveNode): No node with given id found")||r.message.includes("Could not resolve backend node"):!1}var ba=class extends Error{constructor(e,t={}){super(e,t),this.name="InsufficientCacheDataError"}};var aO={CLICK:"Click on an element on the page.",TYPE:"Type the specified text into an input on the page.",PRESS:"Press one or more keyboard keys.",KEY_DOWN:"Hold down one or more keyboard keys.",KEY_UP:"Release one or more keyboard keys.",SELECT_OPTION:"Choose an option from a native <select> component. Never use this command for non <select> elements. Instead, use a series of CLICK commands for those.",NAVIGATE:"Go to the specified fully qualified URL.",SCROLL_UP:"Scroll up.",SCROLL_DOWN:"Scroll down.",GO_BACK:"Go back to the previous page.",HOVER:"Hover over an element.",AI_ASSERTION:"Verify a statement about the current page, retrying until it is true. Only generate an assertion if the goal includes language like 'check that', 'verify that', etc..",WAIT:"Wait a fixed amount of seconds."},sO={...aO,JAVASCRIPT:"Execute JavaScript code in NODE or BROWSER environment.",ELEMENT_CHECK:"Perform a manual assertion on a specific element.",PAGE_CHECK:"Perform a manual assertion on the page.",NEW_TAB:"Open a new browser tab with the specified URL.",WAIT_FOR_URL:"Wait for the URL to match a pattern.",AI_EXTRACT:"Extract data from the page and optionally store it in an environment variable."};kd.options.forEach(r=>{let e=r.shape.type.value;if(e!=="SUCCESS"&&!sO[e])throw new Error(`Command type ${e} is missing a description`)});var lO=M.object({type:M.literal("CLICK"),description:M.string().describe("Description of the element to click in the Current Page. Never click on <select> elements, see SELECT_OPTION."),doubleClick:M.boolean().or(M.null()),rightClick:M.boolean().or(M.null())}),cO=M.object({type:M.literal("TYPE"),description:M.string().describe("Description of the element to type into, which must be an <input>, <textarea>, or contenteditable element."),text:M.string().describe("The text to enter, truncated to 500 characters. If the PM provided text in the goals, use it exactly without modification."),pressEnter:M.boolean().or(M.null()).describe("Press enter after typing (useful for form submissions)."),clearContent:M.boolean().describe("Clear existing content before typing. Disable to append to the existing text.")}),uO=M.object({type:M.literal("GO_BACK")}),dO=M.object({type:M.literal("PRESS"),keys:M.array(M.string()).describe('The keys to press. Only use key names supported by the Playwright press method, such as "a", "ArrowLeft", "Meta", "Control", and "Enter". Multiple keys will be pressed together. Do not suggest platform-specific key combinations, such as CTRL+C.')}),pO=M.object({type:M.literal("SELECT_OPTION"),description:M.string().describe("Description of the <select> element to choose from. Only use this command to interact with native HTML <select> elements. You must use CLICK to select from any other HTML element, such as <input>, <div>, or custom elements."),option:M.discriminatedUnion("type",[M.object({type:M.literal("VALUE"),value:M.string()}),M.object({type:M.literal("LABEL"),label:M.string()}),M.object({type:M.literal("INDEX"),index:M.string().describe("Zero-based index of the option within the select.")})]).describe("Which option to select. Choose 1 of 3 strategies for selecting. By value is exactly matching the 'value' attribute. By label is exactly matching the 'label' attribute. By index is using the zero-based index of the option within the select.")}),mO=M.object({type:M.literal("NAVIGATE"),url:M.string().describe("The URL to navigate to. Only navigate to URLs relevant to the user goal.")}),gO=M.object({type:M.literal("SCROLL"),y:M.number().describe("Scroll up or down by the specified pixels. Positive values scroll down.")}),hO=M.object({type:M.literal("WAIT"),timeout:M.number().describe("The number of seconds to wait.")}),fO=M.object({type:M.literal("AI_ASSERTION"),assertion:M.string().describe("The assertion to verify. This should be a statement verifiable based on the current page HTML or screenshot. Be specific enough that the assertion is not ambiguous or open to interpretation. Make sure the assertion aligns with what the user intends to verify."),timeout:M.number().describe("The max amount of seconds to wait for the assertion to be true. Respect user wishes but allow no more than 60. If unspecified, choose 5 for quick checks like form status, 10 for page loads, and 30 for actions that explicitly trigger a long time, like image generation.")}),SO=M.object({type:M.literal("HOVER"),description:M.string().describe("Description of the element to hover over. Prefer elements that have visible bounding boxes according to the screenshot, element class attribute, or child contents.")}),yO=M.object({type:M.literal("JAVASCRIPT"),code:M.string().describe("JavaScript code to execute. Defaults to NODE environment unless BROWSER is specified."),environment:M.union([M.literal("NODE"),M.literal("BROWSER")]).or(M.null()).describe("Execution environment. Default is NODE."),timeout:M.number().or(M.null()).describe("Max seconds for the code to complete. Max 60 seconds.")}),bO=M.object({type:M.literal("AI_EXTRACT"),goal:M.string().describe("Description of what data to extract from the page. Be specific about what you want to extract and where to find it."),schema:M.string().or(M.null()).describe("JSON schema defining the expected structure of the extracted data."),envKey:M.string().or(M.null()).describe("Environment variable name to store the extracted result in. If provided, the result will be stored and can be referenced later."),iframeUrl:M.string().or(M.null()).describe("URL or URL regex for the iframe to extract data from.")}),EO=M.object({type:M.literal("ELEMENT_CHECK"),description:M.string().describe("Description of the element to check."),assertionType:M.enum(["EXISTS","VISIBLE","CONTENT_CONTAINS","CONTENT_EQUALS"]).describe("The type of assertion. EXISTS checks if element exists, VISIBLE checks if visible, CONTENT_CONTAINS checks if text contains value, CONTENT_EQUALS checks if text equals value."),value:M.string().or(M.null()).describe("The value to check against (required for CONTENT assertions)."),negated:M.boolean().or(M.null()).describe("If true, asserts the opposite (e.g., does NOT exist)."),timeout:M.number().or(M.null()).describe("Max seconds to wait for the assertion to be true.")}),TO=M.object({type:M.literal("PAGE_CHECK"),value:M.string().describe("The text content to check for on the page."),negated:M.boolean().or(M.null()).describe("If true, checks that the content is NOT present."),timeout:M.number().or(M.null()).describe("Max seconds to wait for the assertion to be true.")}),vO=M.object({type:M.literal("NEW_TAB"),url:M.string().describe("The URL to open in the new tab.")}),AO=M.object({type:M.literal("WAIT_FOR_URL"),matcher:M.discriminatedUnion("type",[M.object({type:M.literal("SUBSTRING"),url:M.string()}),M.object({type:M.literal("GLOB"),glob:M.string()}),M.object({type:M.literal("REGEX"),regex:M.string()}),M.object({type:M.literal("DOMAIN"),domain:M.string()})]).describe("How to match the URL."),caseInsensitive:M.boolean().or(M.null()),negated:M.boolean().or(M.null()).describe("Wait for the URL to NOT match instead."),timeout:M.number().or(M.null()).describe("Max seconds to wait for the URL.")}),pb=M.object({type:M.literal("SUCCESS")}),$d=M.object({type:M.literal("FAILURE")}),Ea=M.discriminatedUnion("type",[lO,cO,dO,pO,mO,gO,hO,fO,SO,uO]),QX=$n(Ea),Rl=M.discriminatedUnion("type",[...Ea.options,yO,EO,TO,vO,AO,bO]),eJ=$n(Rl),wO=M.discriminatedUnion("type",[...Ea.options,$d]).describe("The command that will be executed next. This should naturally follow from your reasoning and be consistent with the goal."),tJ=$n(wO),RO=M.discriminatedUnion("type",[...Ea.options,pb,$d]),rJ=$n(RO),nJ=M.discriminatedUnion("type",[...Rl.options,pb,$d]),CO=M.object({command:Ea,thoughts:M.string()}),oJ=$n(CO),iJ=M.object({command:M.unknown(),thoughts:M.string()});import{z as qd}from"zod";import{extendZodWithOpenApi as MO}from"zod-openapi";import{z as mb}from"zod";import{extendZodWithOpenApi as xO}from"zod-openapi";import{z as qn}from"zod";var Qt=qn.object({index:qn.number().optional().describe("global index within a test (in-order traversal)"),id:qn.string(),skipped:qn.boolean().optional(),envKey:qn.string().optional().describe("key in the environment to save the result of this step to"),aiSuggested:qn.boolean().optional(),retries:qn.number().optional()});xO(mb);var _O=Qt.extend({type:mb.literal("PRESET_ACTION")}),er=_O.extend({command:Ko}).openapi({ref:"PresetAction"});MO(qd);var Kn=Qt.extend({type:qd.literal("AI_ACTION"),text:qd.string(),steps:er.array().optional()}).openapi({ref:"AIAction"});import{z as xt}from"zod";import{z as Cl}from"zod";import{extendZodWithOpenApi as IO}from"zod-openapi";IO(Cl);var Jo=Qt.extend({type:Cl.literal("AI_ACTION_DYNAMIC"),text:Cl.string(),retries:Cl.number().optional()}).openapi({ref:"AIActionDynamic"});import{z as gb}from"zod";var Kd=Qt.extend({type:gb.literal("CONDITIONAL"),skipped:gb.boolean().optional()});import{z as de}from"zod";var PO=de.object({cacheKey:de.string(),cacheExpiryMs:de.number()}),Yd=Qt.extend({id:de.string().uuid().describe("ID of the module step itself. Used to 'namespace' step cache entries."),inputs:de.record(de.string()).optional(),cacheConfig:PO.optional()}),Kr=Yd.extend({type:de.literal("MODULE"),moduleId:de.string().uuid()}),OO=de.union([Kr.pick({type:!0,moduleId:!0}),de.record(de.unknown())]),LO=de.object({type:de.literal("URL_REGEX"),regex:de.string()}),NO=de.object({type:de.literal("PAGE_CHECK"),substring:de.string()}),Xd=de.object({cacheInvalidation:de.discriminatedUnion("type",[NO,LO]).optional()}),tr=de.object({moduleId:de.string().uuid(),name:de.string(),description:de.string().nullish(),enabled:de.boolean().nullish(),parameters:de.string().array().nullish(),defaultParameters:de.record(de.string(),de.string()).nullish(),parameterEnums:de.record(de.string(),de.string().array()).nullish(),defaultCacheKey:de.string().nullish(),defaultCacheTtl:de.number().nullish(),defaultCacheAllInvocations:de.boolean().nullish(),autoAuth:de.boolean().nullish(),advanced:Xd.nullish()});import{z as rr}from"zod";var hb=(n=>(n.ALWAYS="ALWAYS",n.ON_FAILURE="ON_FAILURE",n.ON_ACTION_FAILURE="ON_ACTION_FAILURE",n))(hb||{});var kO=rr.discriminatedUnion("type",[rr.object({type:rr.literal("NAVIGATE_URL"),url:rr.string().url()}),rr.object({type:rr.literal("GO_TO_SECTION_START")})]),DO=rr.object({trigger:rr.nativeEnum(hb).optional(),attempts:rr.number().int().optional(),restartBehavior:kO}),Ta=Qt.extend({type:rr.literal("SECTION"),description:rr.string().describe("user provided goal of what the section should accomplish"),plan:rr.string().array().optional(),autohealingConfig:DO.optional()});var fb=tr.merge(Yd).extend({type:xt.literal("RESOLVED_MODULE"),steps:xt.lazy(()=>ot.array())}),va=tr.extend({steps:xt.lazy(()=>ot.array())}),Jd=Ta.extend({steps:xt.lazy(()=>_t.array())}),UO=Ta.extend({steps:xt.lazy(()=>ot.array())}),Zo=Kd.extend({blocks:xt.object({assertion:xt.lazy(()=>er),steps:xt.lazy(()=>_t.array())}).array(),elseSteps:xt.lazy(()=>_t.array().optional())}),FO=Kd.extend({blocks:xt.object({assertion:xt.lazy(()=>er),steps:xt.lazy(()=>ot.array())}).array(),elseSteps:xt.lazy(()=>ot.array().optional())}),_t=xt.discriminatedUnion("type",[er,Kn,Jo,Kr,Zo,Jd]),ot=xt.discriminatedUnion("type",[er,Kn,Jo,fb,FO,UO]);import{z as nr}from"zod";var BO=nr.object({steps:_t.array(),beforeSteps:_t.array().nullish(),afterSteps:_t.array().nullish()}),Yn=nr.object({steps:ot.array(),beforeSteps:ot.array().nullish(),afterSteps:ot.array().nullish()}),Xn=nr.object({steps:nr.record(nr.string(),nr.unknown()).array(),beforeSteps:nr.record(nr.string(),nr.unknown()).array().nullish(),afterSteps:nr.record(nr.string(),nr.unknown()).array().nullish()});var Jn="1.0.21",Zd="0.0.1";import{z as bt}from"zod";import{z as Zn}from"zod";var zO=/^[a-f0-9]{8}-[a-f0-9]{4}-[1-5][a-f0-9]{3}-[89ab][a-f0-9]{3}-[a-f0-9]{12}$/,fn=r=>{let e=r.trim().toLowerCase().replace(/[^a-z0-9]/g,"-");for(;e.includes("--");)e=e.replaceAll("--","-");return e.startsWith("-")&&(e=e.slice(1)),e.endsWith("-")&&(e=e.slice(0,e.length-1)),e};var Qo=Zn.string().min(1).max(255).superRefine((r,e)=>{try{Qd(r)}catch(t){return e.addIssue({code:Zn.ZodIssueCode.custom,message:t.message,fatal:!0}),Zn.NEVER}});function Qd(r){if(r=r.toLowerCase().trim(),r.length===0||r.length>255)throw new Error("Name must be between 1 and 255 characters long");if(/[<>:"/\\|?*]/.test(r))throw new Error('Name contains one of the following invalid characters: <>:"/\\|?*');if(r.endsWith("-")||r.startsWith("-"))throw new Error("Name cannot start or end with a dash.");if(r.includes("\0"))throw new Error("Name cannot contain null characters");if(/^(con|prn|aux|nul|com[0-9]|lpt[0-9])(\..*)?$/i.test(r))throw new Error(`"${r}" is a reserved name on Windows and cannot be used as a filename.`);if(/^\.+$/.test(r)||/^\s|\s$/.test(r))throw new Error("Name cannot start or end with a space or dot.");if(r.endsWith(".yaml"))throw new Error('Name cannot end with ".yaml".');if(r==="none")throw new Error("Name cannot be 'none'.");if(r.match(zO))throw new Error("Name cannot be a UUID. Please choose a different name.")}var xl=Zn.preprocess(r=>r===null?"":r,Zn.union([Zn.string().url(),Zn.literal("")])).optional();var HO=["AI_EXTRACT","JAVASCRIPT"],GO=bt.object({id:bt.string().optional().describe("Recommended way of selecting an entity. The id of the entity to resolve."),name:Qo.optional().describe("1-255 chars; Only letters/numbers/dashes. Cannot start/end with '-'. Not '.yaml', 'none', or UUID."),path:bt.string().optional().describe("The path of the entity to resolve.")}).describe("A selector for a single entity. Exactly one of id, name, or path must be provided. Id is recommended.").refine(r=>[r.id,r.name,r.path].filter(Boolean).length===1,"Exactly one of id, name, or path must be provided."),jO=bt.object({selector:GO,inputs:bt.record(bt.string()).or(bt.null())}),E6=bt.object({type:bt.literal("PRESET_ACTION"),action:Rl,envKey:bt.string().or(bt.null()).describe(`key in the environment to save the result of this step to. Only use this for ${HO.join(" or ")} steps.`)}),T6=bt.object({type:bt.literal("MODULE"),module:jO}),v6=bt.object({type:bt.literal("AI_ACTION_DYNAMIC"),text:bt.string().describe("The goal description for the AI action. Supports handlebars templates like {{env.VARIABLE_NAME}}.")});var Sb=L.object({phrase:L.string()}),ep=L.object({thoughts:L.string().optional(),result:L.union([L.literal("NOT_FOUND"),L.string(),L.number(),L.array(L.unknown()),L.record(L.unknown(),L.unknown()),L.unknown()])}),n8=L.object({text:L.string()}),yb=L.object({attributes:L.array(L.string()).optional(),text:L.boolean().optional(),boundingBox:L.boolean().optional()}),VO=L.object({id:L.number().int(),requirements:yb}),WO=VO.array(),bb=L.object({thoughts:L.string(),review:L.string().optional(),id:L.number().int(),updatedMemory:wd.optional(),requirements:yb.optional(),additionalElements:WO.optional()});var tp=(g=>(g.NO_DESCRIPTION_PROVIDED="NO_DESCRIPTION_PROVIDED",g.FEW_WORDS="FEW_WORDS",g.STYLE_TAG="STYLE_TAG",g.TYPE_IN_DESCRIPTION="TYPE_IN_DESCRIPTION",g.HARDCODED_ATTRIBUTE="HARDCODED_ATTRIBUTE",g.NONE="NONE",g.AMBIGUOUS_DESCRIPTION="AMBIGUOUS_DESCRIPTION",g.AMBIGUOUS_ASSERTION="AMBIGUOUS_ASSERTION",g.PREFER_PAGE_CHECK="PREFER_PAGE_CHECK",g.PREFER_ASSERTION="PREFER_ASSERTION",g.HTML_ELEMENTS="HTML_ELEMENTS",g.MULTIPLE_ELEMENTS_DESCRIPTION="MULTIPLE_ELEMENTS_DESCRIPTION",g.NEEDS_DATE_VARIABLE="NEEDS_DATE_VARIABLE",g))(tp||{}),Eb=(o=>(o.NONE="NONE",o.AMBIGUOUS_DESCRIPTION="AMBIGUOUS_DESCRIPTION",o.COPILOT_MISUSE="COPILOT_MISUSE",o.IRRELEVANT_MESSAGE="IRRELEVANT_MESSAGE",o))(Eb||{});var Tb=L.object({thoughts:L.string(),category:L.nativeEnum(tp)}),vb=L.object({thoughts:L.string(),category:L.nativeEnum(Eb)}),$O=L.discriminatedUnion("op",[L.object({op:L.literal("replace"),path:L.string(),value:L.string()}),L.object({op:L.literal("add"),path:L.string(),value:L.string()}),L.object({op:L.literal("remove"),path:L.string()})]),o8=L.object({thoughts:L.string(),patches:$O.array()}),qO=[L.literal("add"),L.literal("replace"),L.literal("remove")],KO=L.object({op:L.union(qO),path:L.string(),value:ot.optional()}),Ab=L.object({patches:KO.array(),thoughts:L.string()}),wb=(n=>(n.LEGITIMATE="LEGITIMATE",n.RECOVERABLE="RECOVERABLE",n.INELIGIBLE="INELIGIBLE",n))(wb||{}),Rb=L.object({thoughts:L.string(),scenario:L.nativeEnum(wb),instructions:L.string().nullish()}),Cb=L.object({reasoning:L.string(),scenario:L.string(),patch:L.null().optional()}),i8=L.object({thoughts:L.string(),evaluation:L.number().min(0).max(10)}),a8=L.object({observations:L.string(),reasoning:L.string(),command:fl});var rp=L.object({summary:L.string(),reasoning:L.string(),evaluation:L.discriminatedUnion("type",[L.object({type:L.literal("DONE")}),L.object({type:L.literal("RIGHT_TRACK")}),L.object({type:L.literal("WRONG_TRACK"),feedback:L.string()}),L.object({type:L.literal("IMPOSSIBLE")})])}),YO=L.object({startId:L.number().int(),endId:L.number().int()}),np=(n=>(n.SIMPLE_CONTENT_BASED_LOCATOR="SIMPLE_CONTENT_BASED_LOCATOR",n.SIMPLE_CONTENT_BASED_ASSERTION="SIMPLE_CONTENT_BASED_ASSERTION",n.OTHER="OTHER",n))(np||{}),xb=L.object({categoryThoughts:L.string(),category:L.nativeEnum(np),relevantSections:YO.array()});import{z as O}from"zod";import*as oe from"zod";var p8=oe.object({thoughts:oe.string().optional().describe("only provided if a description was provided"),target:dn.optional().describe("only provided if a description was provided"),pageState:oe.string().optional().describe("serialized a11y tree, only provided if a description was provided"),options:oe.object({label:oe.string(),value:oe.string()}).array().optional().describe("list of options, provided for <select> elements only"),screenshot:oe.object({data:oe.string(),height:oe.number().int(),width:oe.number().int()}).optional().describe("only provided if returnScreenshot is true")}),_b=oe.union([oe.literal("ELEMENT_CHECK"),oe.literal("NEGATED_CHECK"),oe.literal("NEGATED_ELEMENT_VISIBLE_CHECK"),oe.literal("SELECT_OPTION"),oe.literal("TYPE")]);function Aa(r){if(!("useSelector"in r&&r.useSelector)){if(r.type==="SELECT_OPTION")return"SELECT_OPTION";if(r.type==="TYPE")return"TYPE";if(r.type==="ELEMENT_CHECK"&&r.assertion.type==="ELEMENT_EXISTENCE"&&r.assertion.condition==="EXISTS"&&r.assertion.negated)return"NEGATED_CHECK";if(r.type==="ELEMENT_CHECK"&&r.assertion.type==="ELEMENT_EXISTENCE"&&r.assertion.condition==="VISIBLE"&&r.assertion.negated)return"NEGATED_ELEMENT_VISIBLE_CHECK";if(r.type==="ELEMENT_CHECK")return"ELEMENT_CHECK"}}var wa=(a=>(a.USER_SELECTOR="USER_SELECTOR",a.CSS_SELECTOR="CSS_SELECTOR",a.HYBRID_SELECTOR="HYBRID_SELECTOR",a.HTML_DISTANCE="HTML_DISTANCE",a.TEMPLATE_MATCHING="TEMPLATE_MATCHING",a.AUTO_FRAME="AUTO_FRAME",a))(wa||{}),ei=oe.object({matched:oe.boolean(),reason:oe.string().optional().describe("Human understandable description"),logs:oe.string().array().optional().describe("Logs for debugging")}),XO=ei.extend({type:oe.literal("USER_SELECTOR")}),JO=ei.extend({type:oe.literal("CSS_SELECTOR"),selectors:oe.string().array()}),ZO=ei.extend({type:oe.literal("HYBRID_SELECTOR")}),QO=ei.extend({type:oe.literal("HTML_DISTANCE"),distance:oe.number().optional(),closestElement:oe.string().optional(),savedElement:oe.string().optional()}),eL=ei.extend({type:oe.literal("TEMPLATE_MATCHING"),elementImageUrl:oe.string().url()}),tL=ei.extend({type:oe.literal("AUTO_FRAME"),logs:oe.string().array().optional()}),Mb=oe.discriminatedUnion("type",[XO,JO,ZO,QO,eL,tL]);import{z as _a}from"zod";import{z as dL}from"zod";import*as $ from"zod";import{extendZodWithOpenApi as nL}from"zod-openapi";import{cloneDeep as A8}from"lodash-es";import R8 from"truncate-json";import*as to from"zod";import{extendZodWithOpenApi as rL}from"zod-openapi";import{z as Et}from"zod";import{z as me}from"zod";var op=me.object({autoFollowNewTabs:me.boolean().optional().describe("Deprecated: Auto-follow new tabs that are opened."),showZeroOpacityElements:me.union([me.boolean(),me.literal("inputs-only")]).optional(),ignoreHrefForCaching:me.boolean().optional(),disableSecondaryCacheResolution:me.boolean().optional(),hybridSelectorMode:me.enum(["off","test","prefer"]).optional(),globalLocatorRedirect:me.union([me.boolean(),me.literal("always")]).optional(),visualActions:me.boolean().optional(),autoExpandIframes:me.boolean().optional(),disableHtmlSnapshots:me.boolean().optional(),importantAttributes:me.string().array().optional(),importantClasses:me.string().array().optional(),importantStyles:me.string().array().optional()});var Ib=1e4,Pb=6e4,Qn=op.extend({pageLoadTimeoutMs:me.number().optional().refine(r=>r===void 0||r<=Pb&&r>=-1,{message:`Page load timeout must be between 0 and ${Pb/1e3} seconds`}).describe("global page load timeout default for all tests in ms, can still be overridden by individual tests"),smartWaitingTimeoutMs:me.number().optional().refine(r=>r===void 0||r<=Ib&&r>=-1,{message:`Smart waiting timeout must be between 0 and ${Ib/1e3} seconds`}),localChromeExtensionPaths:me.string().array().optional(),extraHeaders:me.record(me.string(),me.string()).optional().describe("HTTP headers to be sent on every request"),initialLocalStorage:me.record(me.string(),me.record(me.string(),me.string())).optional().describe("Initial local storage key-value pairs to set per domain on browser startup"),userAgent:me.string().optional(),disableGpu:me.boolean().optional(),bustCacheOnBoundingBoxChange:me.boolean().optional().describe("Bust the cache if no elements are matched that have the same bounding box and location as the original element. This will improve accuracy on sites that use many same components, at the expense of stability and speed."),allowPartialAccessibilityTree:me.boolean().optional().describe("Allow fetching the partial accessibility tree if fetching the full tree takes too long."),ignoreHttpsErrors:me.boolean().optional().describe("Ignore HTTPS errors, such as self-signed certificates and certificate errors. This can be useful for testing sites that use self-signed certificates or certificate errors.")});var ip="BASE_URL";var eo="ENV_NAME",ti="TEST_NAME",y8={[ip]:"https://www.google.com"},Ob=Et.string().describe("Name of the fixture (must be available locally in the fixtures directory)."),Lb=Et.object({name:Et.string(),variables:Et.record(Et.string().describe("variable name"),Et.string().describe("variable value"))}),Nb=Et.object({name:Et.string(),variables:Et.record(Et.string().describe("variable name"),Et.unknown().describe("variable value")),browser:Qn.optional()});var b8=Et.object({name:Et.string(),variables:Et.record(Et.string().describe("variable name"),Et.unknown().describe("variable value"))});rL(to);var ap=to.object({env:to.record(to.unknown())}).openapi({ref:"TestContextSnapshot"});var it=(i=>(i.SUCCESS="SUCCESS",i.FAILED="FAILED",i.RUNNING="RUNNING",i.IDLE="IDLE",i.CANCELLED="CANCELLED",i))(it||{}),sp=(n=>(n.SUCCESS="SUCCESS",n.FAILED="FAILED",n.CANCELLED="CANCELLED",n))(sp||{});nL($);var lp=$.object({beforeUrl:$.string().optional(),afterUrl:$.string().optional(),message:$.string().optional(),beforeSnapshot:$.string().optional(),afterSnapshot:$.string().optional(),startedAt:$.coerce.date(),finishedAt:$.coerce.date()}),oL=lp.extend({viewport:$.object({height:$.number(),width:$.number()}).nullish(),status:$.nativeEnum(sp),message:$.string().optional(),elementInteracted:$.string().optional()}),ro=lp.extend({status:$.nativeEnum(it),message:$.string().optional(),data:$.unknown().optional(),beforeTestContext:ap.optional(),afterTestContext:ap.optional(),failureReason:$.nativeEnum(Re).optional(),details:$.unknown().describe("Parse using StepExecutionLogSchema.array() to get type safety. We don't explicitly type it because it's non-critical information.")}).openapi({ref:"StepResultMetadata"}),kb=(t=>(t.NOT_ELIGIBLE="NOT_ELIGIBLE",t.ATTEMPTED="ATTEMPTED",t))(kb||{}),_l=ro.merge(er).extend({results:oL.array().describe("Command that was executed. Array is just for consistency with other result types. There should only ever be one item."),previousAttempts:$.lazy(()=>lt.array()).optional(),failureRecoveryStatus:$.object({type:$.nativeEnum(kb),message:$.string()}).optional()}),iL=ro.merge(Kn).extend({results:$.lazy(()=>_l.array()),previousAttempts:$.lazy(()=>lt.array()).optional()}),aL=ro.merge(Jo).extend({results:$.lazy(()=>_l.array()),previousAttempts:$.lazy(()=>lt.array()).optional()}),sL=ro.merge(Kr).extend({moduleName:$.string().optional(),results:$.lazy(()=>lt.array()),previousAttempts:$.lazy(()=>lt.array()).optional()}),lL=ro.merge(Zo).extend({assertion:_l.optional(),results:$.lazy(()=>lt.array()).describe("results for the block actually executed"),previousAttempts:$.lazy(()=>lt.array()).optional()}),cL=ro.merge(Ta).extend({results:$.lazy(()=>lt.array()),healingAttempts:$.lazy(()=>lt.array().array()).optional(),previousAttempts:$.lazy(()=>lt.array()).optional()}),lt=$.discriminatedUnion("type",[iL,aL,_l,sL,lL,cL]),H8=ro.pick({startedAt:!0,finishedAt:!0,status:!0,message:!0,data:!0}),uL=lp.extend({index:$.number().optional(),description:$.string(),pageState:$.string().optional(),elementInteracted:$.string().optional(),startedAt:$.coerce.date().or($.string()).optional().catch(void 0),finishedAt:$.coerce.date().or($.string()).optional().catch(void 0)}),Ml=uL.extend({beforeScreenshot:$.string().optional(),afterScreenshot:$.string().optional()});var cp=dL.object({results:lt.array().describe("main results"),beforeResults:lt.array().optional(),afterResults:lt.array().optional()}),Ra=cp.partial();import{z as H}from"zod";import{extendZodWithOpenApi as yL}from"zod-openapi";var ri=(t=>(t.WEB="WEB",t.ANDROID="ANDROID",t))(ri||{});import{isValidCron as pL}from"cron-validator";import{z as ae}from"zod";import{z as up}from"zod";var Sn=(n=>(n.CHROMIUM="Chromium",n.GOOGLE_CHROME="Google Chrome",n.CHROME_FOR_TESTING="Chrome for Testing",n))(Sn||{});var Il=up.object({width:up.number().min(200).max(1e4),height:up.number().min(200).max(1e4)}),Db={"Desktop Large":{width:1920,height:1080},"Desktop Small":{width:1280,height:800},iPad:{width:768,height:1024},"Pixel 8":{width:448,height:998},"iPhone 15":{width:393,height:852}},K8=Object.keys(Db);var yn=Db["Desktop Large"],Ub="en-us",Fb="America/Los_Angeles";var Bb={latitude:37.7749,longitude:-122.4194};var zb=["Africa/Abidjan","Africa/Accra","Africa/Algiers","Africa/Bissau","Africa/Cairo","Africa/Casablanca","Africa/Ceuta","Africa/El_Aaiun","Africa/Johannesburg","Africa/Juba","Africa/Khartoum","Africa/Lagos","Africa/Maputo","Africa/Monrovia","Africa/Nairobi","Africa/Ndjamena","Africa/Sao_Tome","Africa/Tripoli","Africa/Tunis","Africa/Windhoek","America/Adak","America/Anchorage","America/Argentina/Buenos_Aires","America/Argentina/Catamarca","America/Argentina/Cordoba","America/Argentina/Jujuy","America/Argentina/La_Rioja","America/Argentina/Mendoza","America/Argentina/Rio_Gallegos","America/Argentina/Salta","America/Argentina/San_Juan","America/Argentina/San_Luis","America/Argentina/Tucuman","America/Argentina/Ushuaia","America/Araguaina","America/Asuncion","America/Atikokan","America/Bahia","America/Bahia_Banderas","America/Barbados","America/Belem","America/Belize","America/Blanc-Sablon","America/Boa_Vista","America/Bogota","America/Boise","America/Cambridge_Bay","America/Campo_Grande","America/Cancun","America/Caracas","America/Cayenne","America/Chicago","America/Chihuahua","America/Costa_Rica","America/Creston","America/Cuiaba","America/Curacao","America/Danmarkshavn","America/Dawson","America/Dawson_Creek","America/Denver","America/Detroit","America/Dominica","America/Edmonton","America/Eirunepe","America/El_Salvador","America/Fort_Nelson","America/Fortaleza","America/Glace_Bay","America/Goose_Bay","America/Grand_Turk","America/Grenada","America/Guadeloupe","America/Guatemala","America/Guayaquil","America/Guyana","America/Halifax","America/Havana","America/Hermosillo","America/Indiana/Indianapolis","America/Indiana/Knox","America/Indiana/Marengo","America/Indiana/Petersburg","America/Indiana/Tell_City","America/Indiana/Vevay","America/Indiana/Vincennes","America/Indiana/Winamac","America/Inuvik","America/Iqaluit","America/Jamaica","America/Juneau","America/Kentucky/Louisville","America/Kentucky/Monticello","America/La_Paz","America/Lima","America/Los_Angeles","America/Maceio","America/Managua","America/Manaus","America/Marigot","America/Martinique","America/Matamoros","America/Mazatlan","America/Menominee","America/Merida","America/Metlakatla","America/Mexico_City","America/Miquelon","America/Moncton","America/Monterrey","America/Montevideo","America/Montserrat","America/Nassau","America/New_York","America/Nipigon","America/Nome","America/Noronha","America/North_Dakota/Beulah","America/North_Dakota/Center","America/North_Dakota/New_Salem","America/Ojinaga","America/Panama","America/Pangnirtung","America/Paramaribo","America/Phoenix","America/Port-au-Prince","America/Port_of_Spain","America/Porto_Velho","America/Puerto_Rico","America/Punta_Arenas","America/Rainy_River","America/Rankin_Inlet","America/Recife","America/Regina","America/Resolute","America/Rio_Branco","America/Santarem","America/Santiago","America/Santo_Domingo","America/Sao_Paulo","America/Scoresbysund","America/Sitka","America/St_Barthelemy","America/St_Johns","America/St_Kitts","America/St_Lucia","America/St_Thomas","America/St_Vincent","America/Swift_Current","America/Tegucigalpa","America/Thule","America/Thunder_Bay","America/Tijuana","America/Toronto","America/Tortola","America/Vancouver","America/Whitehorse","America/Winnipeg","America/Yakutat","America/Yellowknife","Antarctica/Casey","Antarctica/Davis","Antarctica/DumontDUrville","Antarctica/Macquarie","Antarctica/Mawson","Antarctica/Palmer","Antarctica/Rothera","Antarctica/Syowa","Antarctica/Troll","Antarctica/Vostok","Arctic/Longyearbyen","Asia/Aden","Asia/Almaty","Asia/Amman","Asia/Anadyr","Asia/Aqtau","Asia/Aqtobe","Asia/Ashgabat","Asia/Atyrau","Asia/Baghdad","Asia/Bahrain","Asia/Baku","Asia/Bangkok","Asia/Barnaul","Asia/Beirut","Asia/Bishkek","Asia/Brunei","Asia/Chita","Asia/Choibalsan","Asia/Colombo","Asia/Damascus","Asia/Dhaka","Asia/Dili","Asia/Dubai","Asia/Dushanbe","Asia/Famagusta","Asia/Gaza","Asia/Hebron","Asia/Ho_Chi_Minh","Asia/Hong_Kong","Asia/Hovd","Asia/Irkutsk","Asia/Jakarta","Asia/Jayapura","Asia/Jerusalem","Asia/Kabul","Asia/Kamchatka","Asia/Karachi","Asia/Kathmandu","Asia/Khandyga","Asia/Kolkata","Asia/Krasnoyarsk","Asia/Kuala_Lumpur","Asia/Kuching","Asia/Kuwait","Asia/Macau","Asia/Magadan","Asia/Makassar","Asia/Manila","Asia/Muscat","Asia/Nicosia","Asia/Novokuznetsk","Asia/Novosibirsk","Asia/Omsk","Asia/Oral","Asia/Phnom_Penh","Asia/Pontianak","Asia/Pyongyang","Asia/Qatar","Asia/Qostanay","Asia/Qyzylorda","Asia/Riyadh","Asia/Sakhalin","Asia/Samarkand","Asia/Seoul","Asia/Shanghai","Asia/Singapore","Asia/Srednekolymsk","Asia/Taipei","Asia/Tashkent","Asia/Tbilisi","Asia/Tehran","Asia/Thimphu","Asia/Tokyo","Asia/Tomsk","Asia/Ulaanbaatar","Asia/Urumqi","Asia/Ust-Nera","Asia/Vientiane","Asia/Vladivostok","Asia/Yakutsk","Asia/Yangon","Asia/Yekaterinburg","Asia/Yerevan","Atlantic/Azores","Atlantic/Bermuda","Atlantic/Canary","Atlantic/Cape_Verde","Atlantic/Faroe","Atlantic/Madeira","Atlantic/Reykjavik","Atlantic/South_Georgia","Atlantic/Stanley","Australia/Adelaide","Australia/Brisbane","Australia/Broken_Hill","Australia/Currie","Australia/Darwin","Australia/Eucla","Australia/Hobart","Australia/Lindeman","Australia/Lord_Howe","Australia/Melbourne","Australia/Perth","Australia/Sydney","Europe/Amsterdam","Europe/Andorra","Europe/Astrakhan","Europe/Athens","Europe/Belgrade","Europe/Berlin","Europe/Bratislava","Europe/Brussels","Europe/Bucharest","Europe/Budapest","Europe/Busingen","Europe/Chisinau","Europe/Copenhagen","Europe/Dublin","Europe/Gibraltar","Europe/Guernsey","Europe/Helsinki","Europe/Isle_of_Man","Europe/Istanbul","Europe/Jersey","Europe/Kaliningrad","Europe/Kiev","Europe/Kirov","Europe/Lisbon","Europe/Ljubljana","Europe/London","Europe/Luxembourg","Europe/Madrid","Europe/Malta","Europe/Mariehamn","Europe/Minsk","Europe/Monaco","Europe/Moscow","Europe/Oslo","Europe/Paris","Europe/Podgorica","Europe/Prague","Europe/Riga","Europe/Rome","Europe/Samara","Europe/San_Marino","Europe/Sarajevo","Europe/Saratov","Europe/Simferopol","Europe/Skopje","Europe/Sofia","Europe/Stockholm","Europe/Tallinn","Europe/Tirane","Europe/Ulyanovsk","Europe/Uzhgorod","Europe/Vaduz","Europe/Vatican","Europe/Vienna","Europe/Vilnius","Europe/Volgograd","Europe/Warsaw","Europe/Zagreb","Europe/Zaporozhye","Europe/Zurich","Indian/Antananarivo","Indian/Chagos","Indian/Christmas","Indian/Cocos","Indian/Comoro","Indian/Kerguelen","Indian/Mahe","Indian/Maldives","Indian/Mauritius","Indian/Mayotte","Indian/Reunion","Pacific/Apia","Pacific/Auckland","Pacific/Bougainville","Pacific/Chatham","Pacific/Chuuk","Pacific/Easter","Pacific/Efate","Pacific/Enderbury","Pacific/Fakaofo","Pacific/Fiji","Pacific/Funafuti","Pacific/Galapagos","Pacific/Gambier","Pacific/Guadalcanal","Pacific/Guam","Pacific/Honolulu","Pacific/Kiritimati","Pacific/Kosrae","Pacific/Kwajalein","Pacific/Majuro","Pacific/Marquesas","Pacific/Midway","Pacific/Nauru","Pacific/Niue","Pacific/Norfolk","Pacific/Noumea","Pacific/Pago_Pago","Pacific/Palau","Pacific/Pitcairn","Pacific/Pohnpei","Pacific/Port_Moresby","Pacific/Rarotonga","Pacific/Saipan","Pacific/Tahiti","Pacific/Tarawa","Pacific/Tongatapu","Pacific/Wake","Pacific/Wallis"];var Hb=1e4,mL=Qn.extend({browserType:ae.nativeEnum(Sn).optional(),slowMoMs:ae.number().optional().refine(r=>r===void 0||r<=Hb&&r>=-1,{message:`Slow motion must be between 0 and ${Hb} milliseconds`}),basicAuthorization:ae.object({username:ae.string().optional(),password:ae.string().optional()}).optional(),geolocation:ae.object({latitude:ae.coerce.number().refine(r=>r>=-90&&r<=90,{message:"Latitude must be between -90 and 90 degrees"}),longitude:ae.coerce.number().refine(r=>r>=-180&&r<=180,{message:"Longitude must be between -180 and 180 degrees"})}).optional(),disableJavaScript:ae.boolean().optional(),locale:ae.string().optional(),timezone:ae.enum(zb).optional(),colorScheme:ae.enum(["light","dark"]).optional()});var dp=ae.object({useMemory:ae.boolean().optional(),failureRecovery:ae.boolean().optional().describe("undefined means inherit org settings")}),gL=dp.extend({disableAICaching:ae.boolean().optional(),failureRecoveryInstructions:ae.string().optional()}),hL=ae.object({viewport:Il.optional()}),Ca=hL.merge(gL).merge(mL),ni=ae.object({cron:ae.string().refine(r=>pL(r),{message:"Invalid cron expression."}).default("0 0 */1 * *"),enabled:ae.boolean().default(!1),env:ae.string().optional(),timeZone:ae.string().default("America/Los_Angeles"),jobKey:ae.string().optional()}),oi=ae.object({onSuccess:ae.boolean().default(!1),failureMessage:ae.string().optional(),onFailure:ae.boolean().default(!0),successMessage:ae.string().optional()}),fL=ae.object({name:ae.string(),required:ae.boolean().optional(),defaultValue:ae.string().describe("this is not optional because we need a value when the editor is first loaded")}),Pl=fL.array(),SL=ae.object({name:ae.string(),value:ae.string()}),Gb=SL.array(),Ol=ae.object({name:ae.string(),default:ae.boolean().optional(),fixtures:Ob.array().optional()});yL(H);var or={WEBHOOK:"WEBHOOK",CRON:"CRON",MANUAL:"MANUAL",CLI:"CLI"},Ae=(s=>(s.PENDING="PENDING",s.RUNNING="RUNNING",s.PASSED="PASSED",s.FAILED="FAILED",s.CANCELLED="CANCELLED",s.RETRYING="RETRYING",s.WAITING_FOR_USER="WAITING_FOR_USER",s))(Ae||{}),Ll=(t=>(t.BEFORE_ALL="BEFORE_ALL",t.AFTER_ALL="AFTER_ALL",t))(Ll||{});var Xe=H.string().pipe(H.coerce.date()).or(H.date()),xa=H.object({id:H.string(),runKey:H.string(),organizationId:H.string(),executionType:H.nativeEnum(ri).optional().default("WEB"),createdAt:Xe,createdBy:H.string(),flake:H.boolean().nullish(),scheduledAt:Xe.or(H.null()),startedAt:Xe.or(H.null()),updatedAt:Xe.nullish(),finishedAt:Xe.or(H.null()),resolvedBaseUrl:H.string().nullish(),environmentName:H.string().nullish(),gitBranchName:H.string().nullish(),githubRepository:H.string().nullish(),gitlabProjectPath:H.string().nullish(),labels:H.array(H.string()).optional(),gitOriginUrl:H.string().nullish(),gitCommitSha:H.string().nullish(),gitCommitShaShort:H.string().nullish(),gitCommitAuthorName:H.string().nullish(),cliVersion:H.string().nullish(),section:H.nativeEnum(Ll).nullish(),status:H.nativeEnum(Ae),trigger:H.nativeEnum(or),attempts:H.number(),runAttempts:H.array(H.object({id:H.string(),status:H.nativeEnum(Ae),startedAt:Xe.or(H.null()),finishedAt:Xe.or(H.null())})).optional(),videos:H.array(H.string()).optional(),failureReason:H.nativeEnum(Re).nullish(),failureDetails:vl.nullish(),failureRecoveryDetails:H.record(H.string(),H.unknown()).nullish(),pipelineId:H.string().nullish(),resolvedInputs:H.record(H.string(),H.string()).nullish(),quarantined:H.boolean().nullish().default(!1),quarantinedReason:H.string().nullish(),localTestId:H.string().nullish(),testId:H.string().nullish(),testName:H.string().nullish(),description:H.string().nullish(),test:H.object({name:H.string(),id:H.string()}).nullish().default(null),suiteId:H.string().nullish()}).openapi({ref:"RunMetadata"}),bL={id:!0,status:!0,testName:!0,localTestId:!0,testId:!0,test:{select:{name:!0,id:!0}},finishedAt:!0,failureReason:!0,failureDetails:!0},Nl=xa.pick({...bL,test:!0}),jb=xa.omit({failureReason:!0,failureDetails:!0,test:!0}),pp=xa.extend({stepsSnapshot:H.array(H.record(H.unknown())).nullish(),resolvedInputs:H.record(H.string(),H.string()).nullish(),test:H.object({name:H.string(),id:H.string(),description:H.string().nullish(),baseUrl:H.string().nullish(),advanced:Ca.nullish()}).nullish()}).merge(cp);var EL=_a.object({id:_a.string().uuid(),startedAt:Xe.or(_a.null()),finishedAt:Xe.or(_a.null()),status:_a.nativeEnum(Ae)}).merge(Ra),f9=EL.array();import{z as Je}from"zod";var TL=Je.object({id:Je.string(),status:Je.nativeEnum(Ae),trigger:Je.nativeEnum(or),createdAt:Xe,startedAt:Xe.nullish(),finishedAt:Xe.nullish(),gitCommitSha:Je.string().nullish(),gitCommitShaShort:Je.string().nullish(),gitCommitTimestamp:Xe.nullish(),gitBranchName:Je.string().nullish(),gitOriginUrl:Je.string().nullish(),gitCommitMessage:Je.string().nullish(),gitCommitAuthorName:Je.string().nullish(),githubRepository:Je.string().nullish(),gitlabProjectPath:Je.string().nullish(),pipelineId:Je.string().nullish(),cliVersion:Je.string().nullish(),labels:Je.string().array().optional(),suite:Je.object({id:Je.string(),name:Je.string()}).nullish(),runs:Je.object({status:Je.nativeEnum(Ae)}).array()}).openapi({ref:"RunGroup"}),Vb=TL.pick({id:!0,createdAt:!0,startedAt:!0,finishedAt:!0,status:!0,trigger:!0,suite:!0}).extend({runs:Nl.array()});import{z as ct}from"zod";var vL=ct.object({type:ct.literal("TARGETING"),name:ct.string().optional().describe("Target name to disambiguate for steps with multiple targets"),elementLocationDecisions:Mb.array(),pageState:ct.string().optional(),targetSource:ct.nativeEnum(un).optional(),targetUpdateTime:ct.string().optional()}),AL=ct.object({type:ct.literal("AI_LOCATION"),matched:ct.boolean(),pageState:ct.string().optional(),ragUsed:ct.boolean().optional(),thoughts:ct.string().optional()}),wL=ct.object({type:ct.literal("ASSERTION"),relevantElementsSerialized:ct.string().array().optional(),pageState:ct.string().optional(),ragUsed:ct.boolean().optional()}),RL=ct.discriminatedUnion("type",[vL,AL,wL]);import{z as We}from"zod";var CL=We.object({id:We.string(),name:We.string()}),I9=CL.merge(We.object({createdAt:Xe,createdBy:We.string(),schedule:ni,notification:oi,environment:We.object({name:We.string()}).nullish(),beforeTests:We.object({id:We.string()}).array().nullish(),afterTests:We.object({id:We.string()}).array().nullish()})),Wb=We.object({id:We.string().uuid(),orgId:We.string(),createdAt:Xe,startedAt:Xe.or(We.null()),finishedAt:Xe.or(We.null()),status:We.nativeEnum(Ae),trigger:We.nativeEnum(or),suite:We.object({id:We.string(),name:We.string()}).nullish(),runs:xa.array()}),P9=Wb.pick({id:!0,createdAt:!0,startedAt:!0,finishedAt:!0,status:!0,trigger:!0,suite:!0}),$b=Wb.extend({runs:Nl.array()});import{z as ir}from"zod";import{cloneDeep as N9}from"lodash-es";import{z as be}from"zod";var z9=be.object({thoughts:be.string(),subGoals:be.object({instruction:be.string()}).array()}),H9=be.object({thoughts:be.string(),newPlanMarkdown:be.string()}),G9=be.object({thoughts:be.string(),correct:be.boolean(),failedActionIndex:be.number().optional()}),xL=be.object({type:be.literal("PLANNING"),beforePlan:be.string(),goalDecision:be.string(),thoughts:be.string()}),_L=be.object({type:be.literal("RUNNING"),stepDisplayName:be.string(),status:be.nativeEnum(it),results:lt.array()}),ML=be.object({type:be.literal("REVISING"),beforePlan:be.string(),afterPlan:be.string(),errString:be.string(),diffs:be.string(),thoughts:be.string()}),IL=be.object({type:be.literal("SYSTEM"),message:be.string()}),PL=be.discriminatedUnion("type",[xL,_L,ML,IL]),qb=PL.array();var q9=ir.object({id:ir.string(),scheduledAt:ir.coerce.date().nullable(),startedAt:ir.coerce.date().nullable(),finishedAt:ir.coerce.date().nullable(),status:ir.nativeEnum(Ae),history:qb.nullable(),testPlan:ir.object({id:ir.string(),name:ir.string()}).nullable(),test:ir.object({id:ir.string(),name:ir.string()}).nullable()});import{z as Mt}from"zod";var mp=Mt.object({content:Mt.string(),ids:Mt.string().array(),tokenLength:Mt.number()}),OL=Mt.object({chunks:mp.array()}),uZ=Mt.object({ids:Mt.string().array(),score:Mt.number(),tokenLength:Mt.number()}),dZ=OL.extend({description:Mt.string().describe("Input to pass to RAG engine"),tokenLimit:Mt.number()}),Kb=Mt.object({ids:Mt.number().array()}),Yb=Mt.object({indices:Mt.number().array()});var Tt=O.object({disableCache:O.boolean().optional(),useMemory:O.boolean().optional(),loggerTags:O.record(O.string(),O.string()).optional(),langfuseSessionId:O.string().optional(),agentConfigVersion:O.string().optional()}),bZ=Tt.extend({chunks:mp.array(),description:O.string().describe("Input to pass to AI"),type:O.union([O.literal("locator"),O.literal("assertion"),O.literal("ai-action")]),softTokenLimit:O.number(),hardTokenLimit:O.number(),callId:O.string().optional()}),LL=O.object({screenshotBase64AfterCommand:O.string(),urlAfterCommand:O.string(),serializedCommand:O.string(),elementInteracted:O.string().optional(),thoughts:O.string().optional()}),Xb=O.object({goal:O.string(),browserState:O.string(),screenshot:O.string(),source:_b.optional().catch(void 0),memory:O.discriminatedUnion("type",[ul,O.object({type:O.literal("RESOLVED_TRACES"),traces:O.unknown().array()})]).optional()}),Jb=O.object({target:O.string().or(O.number()),browserState:O.string().optional(),screenshot:O.string().optional(),boundingBox:O.object({x:O.number(),y:O.number(),height:O.number(),width:O.number()}).optional()}),Zb=O.object({goal:O.string(),browserState:O.string(),screenshot:O.string().optional(),returnSchema:O.string().optional()}),NL=O.literal("NEGATED_CHECK"),Qb=O.object({goal:O.string(),browserState:O.string(),screenshot:O.string(),url:O.string(),contextChoice:Od.optional(),memory:O.discriminatedUnion("type",[xd,O.object({type:O.literal("RESOLVED_TRACES"),traces:O.unknown().array()})]).optional(),source:NL.optional()}),eE=O.object({command:Ko}),tE=O.object({message:O.string()}),gp=O.object({goal:O.string(),browserState:O.string(),startingScreenshot:O.string().optional(),screenshot:O.string(),url:O.string(),history:LL.array(),actionHint:O.string().optional(),lastError:O.string().optional()}),rE=O.object({results:Ml.array(),errorMessage:O.string(),errorStack:O.string().optional()}),nE=O.object({results:Ml.array(),goal:O.string(),errorMessage:O.string()}),oE=O.object({failedResults:Ml.array(),nextStepsSerialized:O.string().array(),currentUrl:O.string(),currentPageState:O.string(),currentScreenshot:O.string(),customInstructions:O.string().optional(),testDescription:O.string().optional()}),EZ=O.object({description:O.string(),type:O.union([O.literal("locator"),O.literal("assertion"),O.literal("ai-action")]),excerpt:O.string()}),iE=O.object({type:O.string(),browserContext:O.string(),currentStep:O.string(),screenshot:O.string()});import{z as Ma}from"zod";var AZ=Ma.object({goal:Ma.string()}),aE=Ma.object({keywords:Ma.array(Ma.string())});import{z as hp}from"zod";var kl=(o=>(o.LOCATOR="locator",o.ASSERTION="assertion",o.VISUAL_ASSERTION="visual-assertion",o.TEXT_EXTRACTION="text-extraction",o))(kl||{}),CZ=hp.nativeEnum(kl),kL=hp.enum(["v1","v2"]),xZ=kL.or(hp.string().describe("for people with special configurations"));import{z as Ue}from"zod";var sE=Ue.object({attributesRequired:Ue.array(Ue.string()).optional(),textRequired:Ue.boolean().optional(),boundsRequired:Ue.boolean().optional()}),lE=Ue.object({id:Ue.number(),thoughts:Ue.string(),inWebview:Ue.boolean().optional(),requirements:sE.optional(),additionalElements:Ue.object({id:Ue.number(),requirements:sE}).array().optional()}),cE=Ue.object({description:Ue.string(),screenXml:Ue.string(),screenshot:Ue.string()}),uE=Ue.object({assertion:Ue.string(),screenXml:Ue.string(),screenshot:Ue.string()}),dE=Ue.object({thoughts:Ue.string(),result:Ue.boolean(),relevantElements:Ue.array(Ue.number()).optional()});import{z as no}from"zod";var pE=no.object({id:no.string().uuid(),skipped:no.boolean().optional(),envKey:no.string().optional().describe("key in the environment to save the result of this step to")}),fp=pE.merge(Go).extend({type:no.literal("REQUEST")}),Sp=pE.merge(pl).extend({type:no.literal("JAVASCRIPT")}),yp=no.discriminatedUnion("type",[Sp,fp]);import{z as ar}from"zod";var mE=ar.object({id:ar.string(),name:Qo,description:ar.string().optional().nullish(),baseUrl:xl.nullish(),schemaVersion:ar.string(),advanced:ar.unknown().optional(),retries:ar.number(),envs:ar.array(Ol).nullish(),parameters:Pl.nullish()}),DL=ar.object({createdAt:ar.coerce.date(),updatedAt:ar.coerce.date(),schedule:ni.nullish(),notification:oi.nullish(),createdBy:ar.string(),organizationId:ar.string()}),UL=mE.merge(DL),JZ=UL.extend({steps:yp.array()}),ZZ=mE.extend({steps:yp.array()});import{z as Nt}from"zod";var gE=Nt.object({startedAt:Nt.coerce.date(),finishedAt:Nt.coerce.date(),status:Nt.nativeEnum(it),message:Nt.string().optional(),data:Nt.unknown().optional()}),FL=gE.merge(Sp).extend({type:Nt.literal("JAVASCRIPT")}),BL=gE.merge(fp).extend({type:Nt.literal("REQUEST")}),zL=Nt.discriminatedUnion("type",[FL,BL]),hE=Nt.object({startedAt:Nt.coerce.date(),finishedAt:Nt.coerce.date().nullish(),status:Nt.nativeEnum(Ae),results:zL.array(),failureReason:Nt.string().nullish(),failureDetails:vl.nullish()});import{z as kt}from"zod";var HL=kt.object({id:kt.string(),organizationId:kt.string(),createdAt:kt.coerce.date(),updatedAt:kt.coerce.date(),createdBy:kt.string(),scheduledAt:kt.coerce.date().nullish(),startedAt:kt.coerce.date().nullish(),finishedAt:kt.coerce.date().nullish(),status:kt.nativeEnum(Ae),trigger:kt.nativeEnum(or),results:hE.array().nullish(),apiTestName:kt.string().nullish(),apiTestPath:kt.string().nullish(),apiTestId:kt.string().nullish()}),lQ=HL.pick({status:!0,startedAt:!0,finishedAt:!0});var Ia=(o=>(o.TestRun="test-run",o.MobileTestRun="mobile-test-run",o.CreditsUsed="credits-used",o.CreditsUsedV2="credits-used-v2",o))(Ia||{}),fE=3;function GL(r){return r==="MODULE"||r==="CONDITIONAL"||r==="SECTION"||r==="RESOLVED_MODULE"}function bp(r){if(!GL(r))switch(r){case"PRESET_ACTION":return 0;case"AI_ACTION":return 3;case"AI_ACTION_DYNAMIC":return 5;default:(t=>{throw"If Typescript complains about the line below, you missed a case or break in the switch above"})(r)}}function Ep(r){switch(r.type){case"AI_EXTRACT":case"AI_ASSERTION":return fE;case"CAPTCHA":return 3;case"CLICK":case"TYPE":case"SELECT_OPTION":case"HOVER":case"ELEMENT_CHECK":case"FOCUS":case"BLUR":case"SCROLL_DOWN":case"SCROLL_LEFT":case"SCROLL_RIGHT":case"SCROLL_UP":case"MOUSE_DRAG":return r.useSelector||!r.target||r.target.type!=="description"?0:1;case"DRAG":return r.useSelector?0:1;case"VISUAL_DIFF":case"TAB":case"JAVASCRIPT":case"NAVIGATE":case"WAIT":case"SUCCESS":case"AUTH_LOAD":case"AUTH_SAVE":case"COOKIE":case"DIALOG":case"FILE_UPLOAD":case"GO_BACK":case"GO_FORWARD":case"LOCAL_STORAGE":case"NEW_TAB":case"PAGE_CHECK":case"PRESS":case"KEY_DOWN":case"KEY_UP":case"COPY":case"PASTE":case"REFRESH":case"REQUEST":case"GRAPHQL_REQUEST":case"WAIT_FOR_URL":case"REGISTER_REQUEST_LISTENER":case"AWAIT_LISTENER":case"RECORD_REQUESTS":case"GET_RECORDED_REQUESTS":case"SET_HEADER":case"MOCK_ROUTE":case"REMOVE_ROUTE_MOCK":case"OFFLINE_MODE":return 0;default:(t=>{throw"If Typescript complains about the line below, you missed a case or break in the switch above"})(r)}}var Dl=class{trackStepExecution(){}async flush(){}};import{parseString as jL,splitCookiesString as VL}from"set-cookie-parser";import{z as Te}from"zod";var Tp=Te.object({name:Te.string(),value:Te.string(),url:Te.string().optional(),domain:Te.string().optional(),path:Te.string().optional(),expires:Te.number().default(Date.now()/1e3+60*60*24*365),httpOnly:Te.boolean().optional(),secure:Te.boolean().default(!0),sameSite:Te.union([Te.literal("Strict"),Te.literal("Lax"),Te.literal("None")]).default("None")});function Ul(r,e){let t=[],n=VL(r);for(let o of n){let i=jL(o,{decodeValues:!1});if(!i.name)throw new Error("Name missing from cookie");if(!i.value)continue;let a;if(i.sameSite){let u=i.sameSite.trim().toLowerCase();if(u==="strict")a="Strict";else if(u==="lax")a="Lax";else if(u==="none")a="None";else throw new Error(`Invalid sameSite setting in cookie: ${u}`)}i.httpOnly===void 0&&(i.httpOnly=!1),!i.path&&i.domain&&(i.path="/"),!i.domain&&e&&(i.domain=e);let s=Tp.parse({...i,expires:i.expires?i.expires.getTime()/1e3:void 0,sameSite:a});t.push(s);let c=[s.name,...Object.keys(s)].map(u=>u.toLowerCase()),l=o.match(/\b(\S+)=([^;]*)/g);if(l)for(let u of l){let[d,p]=u.split("=");if(!d||!p)throw new Error(`Invalid key-value pair in cookie: ${u}`);c.includes(d.toLowerCase())||t.push({...s,name:d,value:p})}}return t}var WL=Te.object({origin:Te.string(),localStorage:Te.array(Te.object({name:Te.string(),value:Te.string()}))}),$L=Te.object({entries:Te.record(Te.string(),Te.array(Te.tuple([Te.unknown(),Te.unknown()]))),version:Te.number().optional()}),SE=Te.object({cookies:Tp.array().optional(),origins:WL.array().optional(),idb:Te.record(Te.string(),$L).optional().describe("key is db name")});function Fl(r,e){let t=[];return r.cloneSync()?.serializeSync()?.cookies.forEach(n=>{let o=Tp.safeParse({name:n.key,...n});if(!o.success)return;let i=o.data;!i.domain&&!i.url&&(i.domain=e),t.push(i)}),t}import dN from"zod";import{v4 as PQ}from"uuid";import{z as j}from"zod";import*as xe from"zod";var yE=xe.object({requiredText:xe.string().optional(),requiredAttributes:xe.record(xe.string(),xe.string()).optional(),requiredBounds:xe.boolean().optional()}),qL=xe.object({xPath:xe.string(),requirements:yE.optional()}),KL=xe.object({type:xe.literal("NATIVE"),bounds:xe.number().array(),resolvedDescription:xe.string(),xPath:xe.string(),elementOnlySerializedXml:xe.string(),requirements:yE.optional(),requiredRelatedElements:qL.array().optional()}),YL=xe.object({type:xe.literal("WEBVIEW"),resolvedDescription:xe.string(),xPath:xe.string(),browserCache:dn.optional()}),Bl=xe.discriminatedUnion("type",[KL,YL]);var oo=(m=>(m.AI_CHECK="AI_CHECK",m.TAP="TAP",m.TYPE="TYPE",m.PRESS="PRESS",m.PRESS_KEYBOARD="PRESS_KEYBOARD",m.OPEN_APP="OPEN_APP",m.OPEN_NOTIFICATION_DRAWER="OPEN_NOTIFICATION_DRAWER",m.SWIPE="SWIPE",m.JAVASCRIPT="JAVASCRIPT",m.REQUEST="REQUEST",m.WAIT="WAIT",m.ADD_FILE="ADD_FILE",m.ADB="ADB",m.STATE="STATE",m))(oo||{}),vp=(c=>(c.BACK="BACK",c.HOME="HOME",c.APP_SWITCHER="APP_SWITCHER",c.POWER="POWER",c.SEARCH="SEARCH",c.VOLUME_UP="VOLUME_UP",c.VOLUME_DOWN="VOLUME_DOWN",c.VOLUME_MUTE="VOLUME_MUTE",c))(vp||{}),Ap=(n=>(n.CLOSE_KEYBOARD="CLOSE_KEYBOARD",n.ENTER="ENTER",n.BACKSPACE="BACKSPACE",n))(Ap||{}),bE=j.object({type:j.literal("description"),description:j.string()}),XL=j.object({type:j.literal("coordinates"),xPercent:j.number(),yPercent:j.number()}),EE=j.discriminatedUnion("type",[bE,XL]),JL=j.object({updatedAt:j.coerce.date().optional()}),Dt=j.object({id:j.string().uuid(),disableCache:j.boolean().optional()}),ZL=Dt.extend({type:j.literal("STATE")}),TE=JL.extend({target:Bl}),QL=Dt.extend({type:j.literal("AI_CHECK"),assertion:j.string(),timeoutSecs:j.number().optional()}),wp=Dt.extend({type:j.literal("TAP"),target:EE,cache:TE.optional(),longPress:j.boolean().optional(),longPressDurationMs:j.number().optional(),doubleTap:j.boolean().optional(),doubleTapDelayMs:j.number().optional(),relativePosition:j.object({x:j.number(),y:j.number()}).optional()}),Rp=Dt.extend({type:j.literal("TYPE"),target:EE.optional(),cache:TE.optional(),keyPressDelayMs:j.number().optional(),text:j.string(),clearContent:j.boolean().optional()}),eN=Dt.extend({type:j.literal("PRESS"),key:j.nativeEnum(vp),longPress:j.boolean().optional()}),tN=Dt.extend({type:j.literal("PRESS_KEYBOARD"),key:j.nativeEnum(Ap)}),rN=Dt.extend({type:j.literal("OPEN_APP"),packageName:j.string(),activityName:j.string().optional(),intentExtras:j.string().optional()}),nN=Dt.extend({type:j.literal("OPEN_NOTIFICATION_DRAWER")}),oN=j.discriminatedUnion("type",[j.object({type:j.literal("SCREEN")}),j.object({type:j.literal("OPEN_APP")}),j.object({type:j.literal("CUSTOM"),target:bE})]),iN=Dt.extend({type:j.literal("SWIPE"),direction:j.enum(["up","down","left","right"]),scrollableElement:oN,viewportPercent:j.number().optional(),durationMs:j.number().optional()}),aN=Dt.extend({type:j.literal("JAVASCRIPT"),code:j.string(),timeout:j.number().int().max(60).optional().describe("Max seconds for the code to complete")}),sN=Dt.extend({type:j.literal("REQUEST")}).merge(Go),lN=Dt.extend({type:j.literal("WAIT"),timeoutSecs:j.number()}),cN=Dt.extend({type:j.literal("ADB"),command:j.string(),jsonArgs:j.string().optional()}),uN=Dt.extend({type:j.literal("ADD_FILE"),file:j.string(),storageLocation:j.string()}),vE=j.discriminatedUnion("type",[QL,wp,Rp,eN,rN,nN,tN,iN,aN,sN,lN,uN,cN,ZL]);var Cp=r=>{switch(r.type){case"description":return r.description;case"coordinates":return`${r.xPercent}%, ${r.yPercent}%`}};var AE={type:!0,cache:!0},bn=dN.discriminatedUnion("type",[wp.pick(AE),Rp.pick(AE)]),pN=Object.values(oo).filter(r=>bn.options.some(e=>e.shape.type.safeParse(r).success));function zl(r){return pN.includes(r.type)}var wE=ha(bn),RE=fa(bn),zQ=Sl(bn);import{cloneDeep as Pa}from"lodash-es";import CE from"truncate-json";var mN="\u2022\u2022\u2022\u2022\u2022\u2022\u2022\u2022\u2022\u2022\u2022\u2022\u2022\u2022\u2022",gN=[eo,ti],xE=[eo,ti],ii=class r{env={};varsFromMomenticEnvironment={};constructor(e){this.reset(e)}static dummyContext(e=void 0,t=void 0,n={}){return new r({testName:e,envName:t,variablesFromEnvironment:n})}static fromSnapshot({snapshot:e,environmentVariables:t}){let n=e.env[eo],o=e.env[ti],i={};for(let[s,c]of Object.entries(e.env))xE.includes(s)||(t??{})[s]===void 0&&(i[s]=c);return new r({dynamicVariables:i,envName:n,testName:o,variablesFromEnvironment:t??{}})}setEnvVariables(e){let t=Pa(e);this.env=Object.assign(this.env,t)}setInputs(e){e&&this.setEnvVariables(e)}setMomenticSystemVariable(e,t){this.varsFromMomenticEnvironment[e]=t}getVariable(e){return this.env[e]}setVariable(e,t){gN.includes(e)||(this.env[e]=t)}getEnvName(){return this.env[eo]}toObjectCopy(){let e={env:Object.assign({},this.env,this.varsFromMomenticEnvironment)};return Pa(e)}toEditorDisplayCopy(){return this.toObjectCopy()}toRedactedDisplayCopy(){let e=this.toObjectCopy();e.env=Object.fromEntries(Object.entries(e.env).map(([n,o])=>xE.includes(n)||this.varsFromMomenticEnvironment[n]===void 0?[n,o]:[n,mN]));for(let[n,o]of Object.entries(e.env)){if(!o){e.env[n]=o;continue}let{jsonString:i}=CE(JSON.stringify(o),1e3);try{e.env[n]=JSON.parse(i)}catch{e.env[n]=void 0}}let{jsonString:t}=CE(JSON.stringify(e.env),5e3);try{e.env=JSON.parse(t)}catch{e.env={}}return e}reset(e){this.env={},this.varsFromMomenticEnvironment={},this.setEnvVariables(e.dynamicVariables??{}),this.varsFromMomenticEnvironment=Pa(e.variablesFromEnvironment),e.envName&&this.setMomenticSystemVariable(eo,e.envName),e.testName&&this.setMomenticSystemVariable(ti,e.testName)}getDynamicVariablesCopy(){return Pa(this.env)}getVariablesFromEnvironmentCopy(){return Pa(this.varsFromMomenticEnvironment)}};var Oa=(t=>(t.USWest1="us-west1",t.EUNorth1="eu-north1",t))(Oa||{});import Ze from"zod";import{z as fr}from"zod";import{z as Fe}from"zod";var hr=Fe.object({id:Fe.string(),name:Qo,baseUrl:xl,description:Fe.string().optional().nullish(),schemaVersion:Fe.string(),advanced:Ca,retries:Fe.number(),envs:Fe.array(Ol).nullish(),parameters:Pl.nullish(),disabled:Fe.boolean().optional(),labels:Fe.array(Fe.string()).optional().catch([])}),JQ=Fe.enum(["INHERIT","ENABLED","DISABLED"]);var hN=Ca.extend({failureRecovery:Fe.boolean().or(Fe.string()).optional().transform(r=>typeof r=="string"?r:r===void 0?"INHERIT":r?"ENABLED":"DISABLED"),useMemory:Fe.boolean().or(Fe.string()).optional().transform(r=>typeof r=="string"?r:r===void 0?"INHERIT":r?"ENABLED":"DISABLED")});var ZQ=hr.pick({name:!0,description:!0,baseUrl:!0,retries:!0,disabled:!0,parameters:!0}).extend({advanced:hN}),QQ=hr.pick({name:!0,description:!0,baseUrl:!0,retries:!0,disabled:!0,advanced:!0,parameters:!0}),fN=Fe.object({labels:Fe.array(Fe.string()).optional(),outputs:Gb.nullish()}),ai=hr.merge(fN),SN=Fe.object({createdAt:Fe.coerce.date(),updatedAt:Fe.coerce.date(),updatedBy:Fe.string().nullable(),schedule:ni,notification:oi,createdBy:Fe.string(),organizationId:Fe.string(),folderId:Fe.string().nullable().optional()}),yN=hr.merge(SN),e7=yN.merge(Yn),Hl=hr.merge(Yn),t7=hr.merge(Xn);var bN="test",EN="module",TN="mobile-test",vN="mobile-module";var _e=(o=>(o.TEST=`momentic/${bN}`,o.MODULE=`momentic/${EN}`,o.MOBILE_TEST=`momentic/${TN}`,o.MOBILE_MODULE=`momentic/${vN}`,o))(_e||{}),l7=hr.merge(Xn),_E=tr.extend({steps:fr.array(fr.record(fr.string(),fr.unknown())),schemaVersion:fr.string()}),c7=_E.extend({fileType:fr.literal(_e.MODULE)}),u7=fr.object({test:fr.string().describe("YAML for the test, including metadata and steps"),modules:fr.record(fr.string(),fr.string()).describe("Map of module name to YAML for the module")});var xp=Ze.object({parameterNames:Ze.string().array(),defaultParameters:Ze.record(Ze.string(),Ze.string()).optional(),parameterEnums:Ze.record(Ze.string(),Ze.string().array()).optional()}),AN=Ze.object({moduleId:Ze.string().uuid(),name:Ze.string(),description:Ze.string().nullish(),parameters:xp.optional(),enabled:Ze.boolean().nullish(),schemaVersion:Ze.string()}),La=AN.omit({name:!0}),Gl=La.extend({steps:Ze.array(Ze.record(Ze.string(),Ze.unknown()))}),wN=Ze.object({fileType:Ze.literal(_e.MOBILE_MODULE)}).merge(Gl);import Ut from"zod";var Sr=(t=>(t.PRESET="MOBILE_PRESET_STEP",t.MODULE="MOBILE_MODULE_STEP",t))(Sr||{}),jl=Ut.object({id:Ut.string().uuid(),envKey:Ut.string().optional(),skipped:Ut.boolean().optional()}),Na=jl.extend({type:Ut.literal("MOBILE_PRESET_STEP"),command:vE,keyPressDelayMs:Ut.number().optional()}),si=Ut.object({moduleId:Ut.string(),inputs:Ut.record(Ut.string(),Ut.string()).optional(),parameters:xp.optional()}),ka=jl.merge(si.extend({type:Ut.literal("MOBILE_MODULE_STEP")})),y7=si.extend({steps:Ut.lazy(()=>yr.array())}),yr=Ut.discriminatedUnion("type",[Na,ka]);import Qe from"zod";import Vl from"zod";var Yr=(e=>(e.MODULE="RESOLVED_MOBILE_MODULE",e))(Yr||{}),RN=si.extend({steps:Vl.lazy(()=>Da.array()),name:Vl.string().describe("name of the module")}),CN=jl.merge(RN).extend({type:Vl.literal("RESOLVED_MOBILE_MODULE")}),Da=Vl.discriminatedUnion("type",[CN,Na]);function ME(r){return Object.values(Yr).includes(r)||Object.values(Sr).includes(r)}var xN=Qe.object({disableMomenticAccessibilityTree:Qe.boolean().optional(),autoGrantPermissions:Qe.boolean().optional()}),_p=xN.extend({region:Qe.nativeEnum(Oa).optional()}),Ua=Qe.object({retries:Qe.number().optional().describe("number of retries to run"),defaultChannel:Qe.string().optional().describe("default channel to use"),defaultTag:Qe.string().optional().describe("default tag to use, if not set uses latest"),defaultEnv:Qe.string().optional(),emulator:_p.optional()}),Or=Qe.object({id:Qe.string().uuid(),description:Qe.string(),schemaVersion:Qe.string(),settings:Ua.optional()}),_N=Or.merge(Qe.object({steps:Qe.array(yr)})),Wl=Qe.object({fileType:Qe.literal(_e.MOBILE_TEST)}).merge(_N),O7=Qe.object({name:Qe.string(),steps:Qe.array(yr).optional(),settings:Ua.optional()}),MN=Or.extend({steps:Da.array()});import ge from"zod";var En=ge.object({startTime:ge.number(),endTime:ge.number().optional(),durationMs:ge.number().optional(),error:ge.string().optional(),result:ge.unknown().optional(),attributes:ge.record(ge.string(),ge.unknown())});var IN=En.extend({type:ge.literal("SECTION"),name:ge.string(),subSpans:ge.lazy(()=>Mp.array())}),PN=En.extend({type:ge.literal("AI_LOCATOR_CALL"),result:ge.object({id:ge.number(),thoughts:ge.string()}).optional()}),ON=En.extend({type:ge.literal("AI_ASSERTION_CALL"),result:ge.object({thoughts:ge.string(),result:ge.boolean()}).optional()}),LN=En.extend({type:ge.literal("TARGET_RESOLUTION"),result:ge.object({serializedElement:ge.string()}).optional()}),NN=En.extend({type:ge.literal("WAIT_FOR_STABILITY"),reason:ge.string()}),kN=En.extend({type:ge.literal("EMULATOR_INTERACTION"),name:ge.string(),withinWebview:ge.boolean().optional()}),DN=En.extend({type:ge.literal("EMULATOR_READ_STATE"),name:ge.string()}),UN=En.extend({type:ge.literal("GENERIC"),name:ge.string()}),Mp=ge.discriminatedUnion("type",[IN,PN,ON,LN,NN,kN,DN,UN]);import br from"zod";var IE=br.object({message:br.string().optional(),startTime:br.number(),endTime:br.number(),status:br.nativeEnum(it),trace:br.unknown(),beforeSnapshot:br.string().optional(),afterSnapshot:br.string().optional(),data:br.unknown().optional().describe("output data from the step")}),FN=IE.merge(Na),BN=IE.merge(ka).extend({steps:br.lazy(()=>Er.array())}),Er=br.discriminatedUnion("type",[FN,BN]);var see=new Set(Object.values(nt));var zN={AI_ACTION:"AI action",AI_ACTION_DYNAMIC:"AI action",RESOLVED_MODULE:"Module",AI_ASSERTION:"AI check",AI_EXTRACT:"AI extract",CLICK:"Click",TYPE:"Type",JAVASCRIPT:"JavaScript",SELECT_OPTION:"Select",PRESS:"Press",KEY_DOWN:"Key down",KEY_UP:"Key up",NAVIGATE:"Navigate",SCROLL_UP:"Scroll up",SCROLL_DOWN:"Scroll down",SCROLL_LEFT:"Scroll left",SCROLL_RIGHT:"Scroll right",HOVER:"Hover",BLUR:"Blur",FILE_UPLOAD:"File upload",FOCUS:"Focus",GO_BACK:"Go back",GO_FORWARD:"Go forward",WAIT:"Wait",REFRESH:"Refresh",TAB:"Switch tab",NEW_TAB:"New tab",COOKIE:"Cookie",LOCAL_STORAGE:"localStorage",REQUEST:"API request",GRAPHQL_REQUEST:"GraphQL request",CAPTCHA:"CAPTCHA",DRAG:"Drag & drop",VISUAL_DIFF:"Visual diff",DIALOG:"Dialog",MOUSE_DRAG:"Mouse drag",AUTH_LOAD:"Load auth state",AUTH_SAVE:"Save auth state",ELEMENT_CHECK:"Element check",PAGE_CHECK:"Page check",WAIT_FOR_URL:"Wait for URL",COPY:"Copy",PASTE:"Paste",REGISTER_REQUEST_LISTENER:"Register request listener",AWAIT_LISTENER:"Await listener",RECORD_REQUESTS:"Record requests",GET_RECORDED_REQUESTS:"Get recorded requests",SET_HEADER:"Set header",MOCK_ROUTE:"Mock route",REMOVE_ROUTE_MOCK:"Remove route mock",OFFLINE_MODE:"Offline mode",SUCCESS:"Done"},lee={AI_ACTION:["ai","action","agent"],AI_ACTION_DYNAMIC:["ai","action","dynamic","agent"],RESOLVED_MODULE:[],AI_ASSERTION:["ai","check","assert","make sure","ensure"],AI_EXTRACT:["ai","extract","data"],CLICK:["click","press"],TYPE:["type","input","write","press"],JAVASCRIPT:["js","javascript","code","execute"],SELECT_OPTION:["select","option","choose"],PRESS:["keyboard","type","key"],KEY_DOWN:["keyboard","type","key","down","press"],KEY_UP:["keyboard","type","key","up","press"],NAVIGATE:["go to","visit"],SCROLL_UP:[],SCROLL_DOWN:[],SCROLL_LEFT:[],SCROLL_RIGHT:[],HOVER:["scroll into view","go to"],BLUR:[],FILE_UPLOAD:[],FOCUS:[],GO_BACK:[],GO_FORWARD:[],WAIT:[],REFRESH:[],TAB:[],NEW_TAB:[],COOKIE:[],LOCAL_STORAGE:[],REQUEST:[],GRAPHQL_REQUEST:[],CAPTCHA:[],DRAG:[],VISUAL_DIFF:[],DIALOG:[],MOUSE_DRAG:[],AUTH_LOAD:[],AUTH_SAVE:[],ELEMENT_CHECK:[],PAGE_CHECK:[],WAIT_FOR_URL:[],COPY:[],PASTE:[],REGISTER_REQUEST_LISTENER:[],AWAIT_LISTENER:[],RECORD_REQUESTS:[],GET_RECORDED_REQUESTS:[],SET_HEADER:[],MOCK_ROUTE:[],REMOVE_ROUTE_MOCK:[],OFFLINE_MODE:[],SUCCESS:[]},cee={AI_ACTION:"Ask AI achieve a specific goal. Saves the steps for reuse. Please use Dynamic AI action instead.",AI_ACTION_DYNAMIC:"Ask AI achieve a specific goal. Fully dynamic and does not save the steps for reuse. Our most capable AI agent.",RESOLVED_MODULE:"A list of steps that can be reused in multiple tests.",AI_ASSERTION:"Ask AI to verify whether something is true on the page.",CLICK:"Click on an element on the page.",DIALOG:"Specify how native browser dialogs should be handled.",AI_EXTRACT:"Ask AI to extract data from the page.",HOVER:"Hover over an element on the page.",FILE_UPLOAD:"Automatically upload a file when the native file upload dialog is activated.",FOCUS:"Focus an element on the page.",BLUR:"Remove focus from an element on the page.",SELECT_OPTION:"Select an option from an HTML Select <select> element.",TYPE:"Type the specified text into an element.",PRESS:"Press the specified keys using the keyboard. (e.g. Control+A)",KEY_DOWN:"Hold down the specified keys on the keyboard. (e.g. Control+A)",KEY_UP:"Release the specified keys on the keyboard. (e.g. Control+A)",NAVIGATE:"Navigate to the specified URL.",SCROLL_UP:"Scroll up by a specified height.",SCROLL_DOWN:"Scroll down by a specified height.",SCROLL_LEFT:"Scroll left by a specified width.",SCROLL_RIGHT:"Scroll right by a specified width.",GO_BACK:"Go back in browser history.",GO_FORWARD:"Go forward in browser history.",WAIT:"Wait for the specified number of seconds.",REFRESH:"Refresh the page. This will not clear cookies or session data.",TAB:"Switch to different tab in the browser.",NEW_TAB:"Create and switch to a new tab in the browser.",COOKIE:"Set a cookie that will persist throughout the browser session.",LOCAL_STORAGE:"Set a localStorage value that will persist throughout the browser session",CAPTCHA:"Solve CAPTCHAs on the page. This feature is only available on Momentic Cloud and may take up to 60 seconds. Disabling CAPTCHAs in non-production environments is strongly advised.",REQUEST:"Make an API request to a URL.",GRAPHQL_REQUEST:"Make a GraphQL request to a URL.",JAVASCRIPT:"Run JavaScript code in the browser or a Node.js environment.",DRAG:"Click and drag an element to another location.",VISUAL_DIFF:"Compare a screenshot of the page or a specific element to a baseline image.",MOUSE_DRAG:"Click and drag the mouse by a specified distance.",AUTH_LOAD:"Load or clear session state using a JavaScript object including cookies, localStorage, and IndexDB entries.",AUTH_SAVE:"Save authentication state (cookies, localStorage) into a JavaScript object.",ELEMENT_CHECK:"Assert on an element's state using pre-built conditions, including content, visibility, attribute value checks.",PAGE_CHECK:"Assert on the active page's contents using pre-built conditions.",WAIT_FOR_URL:"Wait for the active page's URL to match a target value or pattern.",COPY:"Copy the specified value to the browser clipboard.",PASTE:"Paste the browser clipboard contents.",REGISTER_REQUEST_LISTENER:"Register a listener for network requests.",AWAIT_LISTENER:"Wait for a listener to fire, and return the response data.",RECORD_REQUESTS:"Record network requests that match a given pattern.",GET_RECORDED_REQUESTS:"Get recorded requests that matched the pattern.",SET_HEADER:"Set a header.",MOCK_ROUTE:"Mock network requests to a specific URL.",REMOVE_ROUTE_MOCK:"Remove a previously set route mock.",OFFLINE_MODE:"Configure offline mode.",SUCCESS:"Indicate the entire AI action has succeeded, optionally based on a condition."},uee={AI_CHECK:"AI check",RESOLVED_MOBILE_MODULE:"Module",TAP:"Tap",TYPE:"Type",PRESS:"Press button",PRESS_KEYBOARD:"Press keyboard",SWIPE:"Swipe",OPEN_APP:"Open app",OPEN_NOTIFICATION_DRAWER:"Open notification drawer",JAVASCRIPT:"JavaScript",REQUEST:"API request",WAIT:"Wait",ADD_FILE:"Add file",ADB:"ADB command",STATE:"Debug state"},dee={AI_CHECK:"Ask AI to verify whether something is true on the screen.",RESOLVED_MOBILE_MODULE:"A list of steps that can be reused in multiple tests.",TAP:"Tap on an element on the screen.",TYPE:"Type the specified text into an element.",PRESS:"Press a physical button on the device.",PRESS_KEYBOARD:"Press a special key on the keyboard.",SWIPE:"Swipe on the screen.",OPEN_APP:"Open an app on the device.",OPEN_NOTIFICATION_DRAWER:"Open the notification drawer.",JAVASCRIPT:"Execute JavaScript code in a NodeJS context.",REQUEST:"Make an HTTP request to a URL.",WAIT:"Wait for a specified amount of time.",ADD_FILE:"Add a file to the device's disk.",ADB:"Execute an ADB command on the device.",STATE:"Get the debug state of the device."};import HN from"semver";import{z as GN}from"zod";var hee=GN.string().refine(r=>HN.valid(r),{message:"must be a valid semver string"});import{Faker as yee,en as bee}from"@faker-js/faker";import{z as k}from"zod";var Tee=k.object({body:k.string(),to:k.string(),from:k.string()}),vee=k.object({from:k.string().optional(),to:k.string(),timeout:k.number().optional(),beforeDate:k.string().pipe(k.coerce.date()).or(k.date()).optional(),afterDate:k.string().pipe(k.coerce.date()).or(k.date()).optional()}),Aee=k.object({to:k.string().email(),from:k.string(),subject:k.string(),body:k.string(),html:k.string().optional()}),wee=k.object({inbox:k.string().transform(r=>r.toLowerCase()),afterDate:k.string().pipe(k.coerce.date()).or(k.date()).optional(),timeout:k.number().optional(),trimWhitespace:k.boolean().optional()}),Ree=k.object({inbox:k.string(),limit:k.number().optional(),afterDate:k.string().pipe(k.coerce.date()).or(k.date()).optional(),trimWhitespace:k.boolean().optional()});var $l=(t=>(t.RAW="RAW",t.RESPONSE="RESPONSE",t))($l||{}),PE=k.object({body:k.string().nullish(),status:k.number().optional(),headers:k.array(k.tuple([k.string(),k.string()])).optional()}),jN=k.object({url:k.string(),options:k.object({method:k.string(),body:k.string().nullish(),headers:k.array(k.tuple([k.string(),k.string()])).optional()}).optional()}).optional(),VN=k.object({body:k.string().nullish(),options:k.object({status:k.number(),statusText:k.string().optional(),headers:k.array(k.tuple([k.string(),k.string()])).optional()}).optional()}).optional(),OE=k.object({result:k.unknown(),variableUpdates:k.record(k.string(),k.unknown()).optional(),persistentVariableUpdates:k.record(k.string(),k.unknown()).optional(),error:k.string().optional(),success:k.boolean()}),Cee=k.object({id:k.string().optional(),orgId:k.string(),momenticLambdaAuthHash:k.string(),code:k.string(),fragment:k.boolean(),state:k.object({env:k.record(k.string(),k.unknown()),request:jN,response:VN,additionalBindings:k.record(k.string(),k.unknown()).optional()}),timeoutMs:k.number().optional(),disallowVariableUpdates:k.boolean().optional(),responseSerialization:k.nativeEnum($l).optional()}),Tn=15e3;import*as vt from"zod";import{extendZodWithOpenApi as WN}from"zod-openapi";WN(vt);var $N=vt.object({url:vt.string(),lineNumber:vt.number(),columnNumber:vt.number()}).openapi({ref:"CodeLocation"}),ql=vt.object({timestamp:vt.number(),text:vt.string(),type:vt.string(),tabIndex:vt.number(),args:vt.unknown().array().optional(),url:vt.string().optional(),location:$N.optional()}).openapi({ref:"ConsoleLog"}),LE=ql.array(),qN=LE.array();import*as Ip from"zod";import{extendZodWithOpenApi as m0}from"zod-openapi";import{z as P}from"zod";var KN=P.object({name:P.string(),version:P.string(),comment:P.string().optional()}),YN=P.object({name:P.string(),version:P.string(),comment:P.string().optional()}),XN=P.object({onContentLoad:P.number().optional(),onLoad:P.number().optional(),comment:P.string().optional()}),kE=P.object({startedDateTime:P.string(),id:P.string(),title:P.string().optional(),pageTimings:XN,comment:P.string().optional()}),JN=P.array(kE),ZN=P.object({name:P.string(),value:P.string(),path:P.string().optional(),domain:P.string().optional(),expires:P.string().optional(),httpOnly:P.boolean().optional(),secure:P.boolean().optional(),comment:P.string().optional()}),DE=P.array(ZN),QN=P.object({name:P.string(),value:P.string(),comment:P.string().optional()}),UE=P.array(QN),e0=P.object({name:P.string(),value:P.string(),comment:P.string().optional()}),t0=P.array(e0),r0=P.object({name:P.string(),value:P.string().optional(),fileName:P.string().optional(),contentType:P.string().optional(),comment:P.string().optional()}),n0=P.array(r0),o0=P.object({mimeType:P.string(),params:n0,text:P.string(),comment:P.string().optional()}),i0=P.object({method:P.string(),url:P.string(),httpVersion:P.string().optional(),cookies:DE,headers:UE,queryString:t0,postData:o0.optional(),headersSize:P.number().optional(),bodySize:P.number().optional(),comment:P.string().optional()}),a0=P.object({size:P.number().optional(),compression:P.number().optional(),mimeType:P.string().optional(),text:P.string().optional(),encoding:P.string().optional(),comment:P.string().optional()}),s0=P.object({status:P.number(),statusText:P.string(),httpVersion:P.string().optional(),cookies:DE,headers:UE,content:a0,redirectURL:P.string().optional(),headersSize:P.number().optional(),bodySize:P.number().optional(),comment:P.string().optional(),_mocked:P.boolean().optional()}),NE=P.object({expires:P.string().optional(),lastAccess:P.string(),eTag:P.string(),hitCount:P.number(),comment:P.string().optional()}),l0=P.object({beforeRequest:NE.optional(),afterRequest:NE.optional(),comment:P.string().optional()}),c0=P.object({blocked:P.number().optional(),dns:P.number().optional(),connect:P.number().optional(),send:P.number(),wait:P.number(),receive:P.number(),ssl:P.number().optional(),comment:P.string().optional()}),FE=P.object({pageref:P.string().optional(),startedDateTime:P.string(),time:P.number().optional(),request:i0,response:s0.optional(),cache:l0.optional(),timings:c0,serverIPAddress:P.string().optional(),connection:P.string().optional(),comment:P.string().optional(),_resourceType:P.string().optional()}),u0=P.array(FE),d0=P.object({version:P.string().default("1.1"),creator:KN.optional(),browser:YN.optional(),pages:JN.optional(),entries:u0,comment:P.string().optional()}),p0=P.object({log:d0}),BE=P.record(P.string(),kE),zE=P.record(P.string(),FE);m0(Ip);var g0=Ip.object({logsPerPage:ql.array().array(),harPages:BE.optional(),harEntries:zE.optional()}).openapi({ref:"DebugData"});import{cloneDeep as h0}from"lodash-es";import{z as Lr}from"zod";var GE=(c=>(c.DisableClickhouseCaches="disable_clickhouse_caches",c.ShowZeroOpacityElements="show_zero_opacity_elements",c.VisualActions="visual_actions",c.RagV2="rag_v2",c.DisableSecondaryCacheResolution="disable_secondary_cache_resolution",c.GlobalLocatorRedirect="global_locator_redirect",c.FakerConstantSeed="faker_constant_seed",c.AutoExpandIframes="auto_expand_iframes",c))(GE||{});var HE=Lr.union([Lr.string(),Lr.number(),Lr.boolean(),Lr.null(),Lr.record(Lr.string(),Lr.lazy(()=>HE)),Lr.array(Lr.lazy(()=>HE))]),Kl=class{flags;payloads;constructor(e,t){this.flags=e,this.payloads=t}isBooleanFlagEnabled(e){return process.env&&process.env[`MOMENTIC_FLAG_OVERRIDE_${e.toUpperCase()}`]==="true"?!0:process.env&&process.env[`MOMENTIC_FLAG_OVERRIDE_${e.toUpperCase()}`]==="false"?!1:this.flags[e]===!0}getAllFlags(){let e=h0(this.flags);return Object.entries(e).forEach(([t,n])=>{typeof n=="boolean"&&Object.values(GE).includes(t)&&(e[t]=this.isBooleanFlagEnabled(t))}),e}getFlagPayload(e){let t=this.payloads[e];if(t!==void 0){if(typeof t=="string")try{return JSON.parse(t)}catch{return t}return t}}refresh(){throw new Error("Not implemented")}},hte=new Kl({},{});var Pp={".123":"application/vnd.lotus-1-2-3",".3dml":"text/vnd.in3d.3dml",".3g2":"video/3gpp2",".3gp":"video/3gpp",".a":"application/octet-stream",".aab":"application/x-authorware-bin",".aac":"audio/x-aac",".aam":"application/x-authorware-map",".aas":"application/x-authorware-seg",".abw":"application/x-abiword",".acc":"application/vnd.americandynamics.acc",".ace":"application/x-ace-compressed",".acu":"application/vnd.acucobol",".acutc":"application/vnd.acucorp",".adp":"audio/adpcm",".aep":"application/vnd.audiograph",".afm":"application/x-font-type1",".afp":"application/vnd.ibm.modcap",".ai":"application/postscript",".aif":"audio/x-aiff",".aifc":"audio/x-aiff",".aiff":"audio/x-aiff",".air":"application/vnd.adobe.air-application-installer-package+zip",".ami":"application/vnd.amiga.ami",".apk":"application/vnd.android.package-archive",".application":"application/x-ms-application",".apr":"application/vnd.lotus-approach",".asc":"application/pgp-signature",".asf":"video/x-ms-asf",".asm":"text/x-asm",".aso":"application/vnd.accpac.simply.aso",".asx":"video/x-ms-asf",".atc":"application/vnd.acucorp",".atom":"application/atom+xml",".atomcat":"application/atomcat+xml",".atomsvc":"application/atomsvc+xml",".atx":"application/vnd.antix.game-component",".au":"audio/basic",".avi":"video/x-msvideo",".aw":"application/applixware",".azf":"application/vnd.airzip.filesecure.azf",".azs":"application/vnd.airzip.filesecure.azs",".azw":"application/vnd.amazon.ebook",".bat":"application/x-msdownload",".bcpio":"application/x-bcpio",".bdf":"application/x-font-bdf",".bdm":"application/vnd.syncml.dm+wbxml",".bh2":"application/vnd.fujitsu.oasysprs",".bin":"application/octet-stream",".bmi":"application/vnd.bmi",".bmp":"image/bmp",".book":"application/vnd.framemaker",".box":"application/vnd.previewsystems.box",".boz":"application/x-bzip2",".bpk":"application/octet-stream",".btif":"image/prs.btif",".bz":"application/x-bzip",".bz2":"application/x-bzip2",".c":"text/x-c",".c4d":"application/vnd.clonk.c4group",".c4f":"application/vnd.clonk.c4group",".c4g":"application/vnd.clonk.c4group",".c4p":"application/vnd.clonk.c4group",".c4u":"application/vnd.clonk.c4group",".cab":"application/vnd.ms-cab-compressed",".car":"application/vnd.curl.car",".cat":"application/vnd.ms-pki.seccat",".cc":"text/x-c",".cct":"application/x-director",".ccxml":"application/ccxml+xml",".cdbcmsg":"application/vnd.contact.cmsg",".cdf":"application/x-netcdf",".cdkey":"application/vnd.mediastation.cdkey",".cdx":"chemical/x-cdx",".cdxml":"application/vnd.chemdraw+xml",".cdy":"application/vnd.cinderella",".cer":"application/pkix-cert",".cgm":"image/cgm",".chat":"application/x-chat",".chm":"application/vnd.ms-htmlhelp",".chrt":"application/vnd.kde.kchart",".cif":"chemical/x-cif",".cii":"application/vnd.anser-web-certificate-issue-initiation",".cil":"application/vnd.ms-artgalry",".cla":"application/vnd.claymore",".class":"application/java-vm",".clkk":"application/vnd.crick.clicker.keyboard",".clkp":"application/vnd.crick.clicker.palette",".clkt":"application/vnd.crick.clicker.template",".clkw":"application/vnd.crick.clicker.wordbank",".clkx":"application/vnd.crick.clicker",".clp":"application/x-msclip",".cmc":"application/vnd.cosmocaller",".cmdf":"chemical/x-cmdf",".cml":"chemical/x-cml",".cmp":"application/vnd.yellowriver-custom-menu",".cmx":"image/x-cmx",".cod":"application/vnd.rim.cod",".com":"application/x-msdownload",".conf":"text/plain",".cpio":"application/x-cpio",".cpp":"text/x-c",".cpt":"application/mac-compactpro",".crd":"application/x-mscardfile",".crl":"application/pkix-crl",".crt":"application/x-x509-ca-cert",".csh":"application/x-csh",".csml":"chemical/x-csml",".csp":"application/vnd.commonspace",".css":"text/css",".cst":"application/x-director",".csv":"text/csv",".cu":"application/cu-seeme",".curl":"text/vnd.curl",".cww":"application/prs.cww",".cxt":"application/x-director",".cxx":"text/x-c",".daf":"application/vnd.mobius.daf",".dataless":"application/vnd.fdsn.seed",".davmount":"application/davmount+xml",".dcr":"application/x-director",".dcurl":"text/vnd.curl.dcurl",".dd2":"application/vnd.oma.dd2+xml",".ddd":"application/vnd.fujixerox.ddd",".deb":"application/x-debian-package",".def":"text/plain",".deploy":"application/octet-stream",".der":"application/x-x509-ca-cert",".dfac":"application/vnd.dreamfactory",".dic":"text/x-c",".diff":"text/plain",".dir":"application/x-director",".dis":"application/vnd.mobius.dis",".dist":"application/octet-stream",".distz":"application/octet-stream",".djv":"image/vnd.djvu",".djvu":"image/vnd.djvu",".dll":"application/x-msdownload",".dmg":"application/octet-stream",".dms":"application/octet-stream",".dna":"application/vnd.dna",".doc":"application/msword",".docm":"application/vnd.ms-word.document.macroenabled.12",".docx":"application/vnd.openxmlformats-officedocument.wordprocessingml.document",".dot":"application/msword",".dotm":"application/vnd.ms-word.template.macroenabled.12",".dotx":"application/vnd.openxmlformats-officedocument.wordprocessingml.template",".dp":"application/vnd.osgi.dp",".dpg":"application/vnd.dpgraph",".dsc":"text/prs.lines.tag",".dtb":"application/x-dtbook+xml",".dtd":"application/xml-dtd",".dts":"audio/vnd.dts",".dtshd":"audio/vnd.dts.hd",".dump":"application/octet-stream",".dvi":"application/x-dvi",".dwf":"model/vnd.dwf",".dwg":"image/vnd.dwg",".dxf":"image/vnd.dxf",".dxp":"application/vnd.spotfire.dxp",".dxr":"application/x-director",".ecelp4800":"audio/vnd.nuera.ecelp4800",".ecelp7470":"audio/vnd.nuera.ecelp7470",".ecelp9600":"audio/vnd.nuera.ecelp9600",".ecma":"application/ecmascript",".edm":"application/vnd.novadigm.edm",".edx":"application/vnd.novadigm.edx",".efif":"application/vnd.picsel",".ei6":"application/vnd.pg.osasli",".elc":"application/octet-stream",".eml":"message/rfc822",".emma":"application/emma+xml",".eol":"audio/vnd.digital-winds",".eot":"application/vnd.ms-fontobject",".eps":"application/postscript",".epub":"application/epub+zip",".es3":"application/vnd.eszigno3+xml",".esf":"application/vnd.epson.esf",".et3":"application/vnd.eszigno3+xml",".etx":"text/x-setext",".exe":"application/x-msdownload",".ext":"application/vnd.novadigm.ext",".ez":"application/andrew-inset",".ez2":"application/vnd.ezpix-album",".ez3":"application/vnd.ezpix-package",".f":"text/x-fortran",".f4v":"video/x-f4v",".f77":"text/x-fortran",".f90":"text/x-fortran",".fbs":"image/vnd.fastbidsheet",".fdf":"application/vnd.fdf",".fe_launch":"application/vnd.denovo.fcselayout-link",".fg5":"application/vnd.fujitsu.oasysgp",".fgd":"application/x-director",".fh":"image/x-freehand",".fh4":"image/x-freehand",".fh5":"image/x-freehand",".fh7":"image/x-freehand",".fhc":"image/x-freehand",".fig":"application/x-xfig",".fli":"video/x-fli",".flo":"application/vnd.micrografx.flo",".flv":"video/x-flv",".flw":"application/vnd.kde.kivio",".flx":"text/vnd.fmi.flexstor",".fly":"text/vnd.fly",".fm":"application/vnd.framemaker",".fnc":"application/vnd.frogans.fnc",".for":"text/x-fortran",".fpx":"image/vnd.fpx",".frame":"application/vnd.framemaker",".fsc":"application/vnd.fsc.weblaunch",".fst":"image/vnd.fst",".ftc":"application/vnd.fluxtime.clip",".fti":"application/vnd.anser-web-funds-transfer-initiation",".fvt":"video/vnd.fvt",".fzs":"application/vnd.fuzzysheet",".g3":"image/g3fax",".gac":"application/vnd.groove-account",".gdl":"model/vnd.gdl",".geo":"application/vnd.dynageo",".gex":"application/vnd.geometry-explorer",".ggb":"application/vnd.geogebra.file",".ggt":"application/vnd.geogebra.tool",".ghf":"application/vnd.groove-help",".gif":"image/gif",".gim":"application/vnd.groove-identity-message",".gmx":"application/vnd.gmx",".gnumeric":"application/x-gnumeric",".gph":"application/vnd.flographit",".gqf":"application/vnd.grafeq",".gqs":"application/vnd.grafeq",".gram":"application/srgs",".gre":"application/vnd.geometry-explorer",".grv":"application/vnd.groove-injector",".grxml":"application/srgs+xml",".gsf":"application/x-font-ghostscript",".gtar":"application/x-gtar",".gtm":"application/vnd.groove-tool-message",".gtw":"model/vnd.gtw",".gv":"text/vnd.graphviz",".gz":"application/x-gzip",".h":"text/x-c",".h261":"video/h261",".h263":"video/h263",".h264":"video/h264",".hbci":"application/vnd.hbci",".hdf":"application/x-hdf",".hh":"text/x-c",".hlp":"application/winhlp",".hpgl":"application/vnd.hp-hpgl",".hpid":"application/vnd.hp-hpid",".hps":"application/vnd.hp-hps",".hqx":"application/mac-binhex40",".htke":"application/vnd.kenameaapp",".htm":"text/html",".html":"text/html",".hvd":"application/vnd.yamaha.hv-dic",".hvp":"application/vnd.yamaha.hv-voice",".hvs":"application/vnd.yamaha.hv-script",".icc":"application/vnd.iccprofile",".ice":"x-conference/x-cooltalk",".icm":"application/vnd.iccprofile",".ico":"image/x-icon",".ics":"text/calendar",".ief":"image/ief",".ifb":"text/calendar",".ifm":"application/vnd.shana.informed.formdata",".iges":"model/iges",".igl":"application/vnd.igloader",".igs":"model/iges",".igx":"application/vnd.micrografx.igx",".iif":"application/vnd.shana.informed.interchange",".imp":"application/vnd.accpac.simply.imp",".ims":"application/vnd.ms-ims",".in":"text/plain",".ipk":"application/vnd.shana.informed.package",".irm":"application/vnd.ibm.rights-management",".irp":"application/vnd.irepository.package+xml",".iso":"application/octet-stream",".itp":"application/vnd.shana.informed.formtemplate",".ivp":"application/vnd.immervision-ivp",".ivu":"application/vnd.immervision-ivu",".jad":"text/vnd.sun.j2me.app-descriptor",".jam":"application/vnd.jam",".jar":"application/java-archive",".java":"text/x-java-source",".jisp":"application/vnd.jisp",".jlt":"application/vnd.hp-jlyt",".jnlp":"application/x-java-jnlp-file",".joda":"application/vnd.joost.joda-archive",".jpe":"image/jpeg",".jpeg":"image/jpeg",".jpg":"image/jpeg",".jpgm":"video/jpm",".jpgv":"video/jpeg",".jpm":"video/jpm",".js":"application/javascript",".json":"application/json",".kar":"audio/midi",".karbon":"application/vnd.kde.karbon",".kfo":"application/vnd.kde.kformula",".kia":"application/vnd.kidspiration",".kil":"application/x-killustrator",".kml":"application/vnd.google-earth.kml+xml",".kmz":"application/vnd.google-earth.kmz",".kne":"application/vnd.kinar",".knp":"application/vnd.kinar",".kon":"application/vnd.kde.kontour",".kpr":"application/vnd.kde.kpresenter",".kpt":"application/vnd.kde.kpresenter",".ksh":"text/plain",".ksp":"application/vnd.kde.kspread",".ktr":"application/vnd.kahootz",".ktz":"application/vnd.kahootz",".kwd":"application/vnd.kde.kword",".kwt":"application/vnd.kde.kword",".latex":"application/x-latex",".lbd":"application/vnd.llamagraphics.life-balance.desktop",".lbe":"application/vnd.llamagraphics.life-balance.exchange+xml",".les":"application/vnd.hhe.lesson-player",".lha":"application/octet-stream",".link66":"application/vnd.route66.link66+xml",".list":"text/plain",".list3820":"application/vnd.ibm.modcap",".listafp":"application/vnd.ibm.modcap",".log":"text/plain",".lostxml":"application/lost+xml",".lrf":"application/octet-stream",".lrm":"application/vnd.ms-lrm",".ltf":"application/vnd.frogans.ltf",".lvp":"audio/vnd.lucent.voice",".lwp":"application/vnd.lotus-wordpro",".lzh":"application/octet-stream",".m13":"application/x-msmediaview",".m14":"application/x-msmediaview",".m1v":"video/mpeg",".m2a":"audio/mpeg",".m2v":"video/mpeg",".m3a":"audio/mpeg",".m3u":"audio/x-mpegurl",".m4u":"video/vnd.mpegurl",".m4v":"video/x-m4v",".ma":"application/mathematica",".mag":"application/vnd.ecowin.chart",".maker":"application/vnd.framemaker",".man":"text/troff",".mathml":"application/mathml+xml",".mb":"application/mathematica",".mbk":"application/vnd.mobius.mbk",".mbox":"application/mbox",".mc1":"application/vnd.medcalcdata",".mcd":"application/vnd.mcd",".mcurl":"text/vnd.curl.mcurl",".mdb":"application/x-msaccess",".mdi":"image/vnd.ms-modi",".me":"text/troff",".mesh":"model/mesh",".mfm":"application/vnd.mfmp",".mgz":"application/vnd.proteus.magazine",".mht":"message/rfc822",".mhtml":"message/rfc822",".mid":"audio/midi",".midi":"audio/midi",".mif":"application/vnd.mif",".mime":"message/rfc822",".mj2":"video/mj2",".mjp2":"video/mj2",".mkv":"video/x-matroska",".mlp":"application/vnd.dolby.mlp",".mmd":"application/vnd.chipnuts.karaoke-mmd",".mmf":"application/vnd.smaf",".mmr":"image/vnd.fujixerox.edmics-mmr",".mny":"application/x-msmoney",".mobi":"application/x-mobipocket-ebook",".mov":"video/quicktime",".movie":"video/x-sgi-movie",".mp2":"audio/mpeg",".mp2a":"audio/mpeg",".mp3":"audio/mpeg",".mp4":"video/mp4",".mp4a":"audio/mp4",".mp4s":"application/mp4",".mp4v":"video/mp4",".mpa":"video/mpeg",".mpc":"application/vnd.mophun.certificate",".mpe":"video/mpeg",".mpeg":"video/mpeg",".mpg":"video/mpeg",".mpg4":"video/mp4",".mpga":"audio/mpeg",".mpkg":"application/vnd.apple.installer+xml",".mpm":"application/vnd.blueice.multipass",".mpn":"application/vnd.mophun.application",".mpp":"application/vnd.ms-project",".mpt":"application/vnd.ms-project",".mpy":"application/vnd.ibm.minipay",".mqy":"application/vnd.mobius.mqy",".mrc":"application/marc",".ms":"text/troff",".mscml":"application/mediaservercontrol+xml",".mseed":"application/vnd.fdsn.mseed",".mseq":"application/vnd.mseq",".msf":"application/vnd.epson.msf",".msh":"model/mesh",".msi":"application/x-msdownload",".msl":"application/vnd.mobius.msl",".msty":"application/vnd.muvee.style",".mts":"model/vnd.mts",".mus":"application/vnd.musician",".musicxml":"application/vnd.recordare.musicxml+xml",".mvb":"application/x-msmediaview",".mwf":"application/vnd.mfer",".mxf":"application/mxf",".mxl":"application/vnd.recordare.musicxml",".mxml":"application/xv+xml",".mxs":"application/vnd.triscape.mxs",".mxu":"video/vnd.mpegurl",".n-gage":"application/vnd.nokia.n-gage.symbian.install",".nb":"application/mathematica",".nc":"application/x-netcdf",".ncx":"application/x-dtbncx+xml",".ngdat":"application/vnd.nokia.n-gage.data",".nlu":"application/vnd.neurolanguage.nlu",".nml":"application/vnd.enliven",".nnd":"application/vnd.noblenet-directory",".nns":"application/vnd.noblenet-sealer",".nnw":"application/vnd.noblenet-web",".npx":"image/vnd.net-fpx",".nsf":"application/vnd.lotus-notes",".nws":"message/rfc822",".o":"application/octet-stream",".oa2":"application/vnd.fujitsu.oasys2",".oa3":"application/vnd.fujitsu.oasys3",".oas":"application/vnd.fujitsu.oasys",".obd":"application/x-msbinder",".obj":"application/octet-stream",".oda":"application/oda",".odb":"application/vnd.oasis.opendocument.database",".odc":"application/vnd.oasis.opendocument.chart",".odf":"application/vnd.oasis.opendocument.formula",".odft":"application/vnd.oasis.opendocument.formula-template",".odg":"application/vnd.oasis.opendocument.graphics",".odi":"application/vnd.oasis.opendocument.image",".odp":"application/vnd.oasis.opendocument.presentation",".ods":"application/vnd.oasis.opendocument.spreadsheet",".odt":"application/vnd.oasis.opendocument.text",".oga":"audio/ogg",".ogg":"audio/ogg",".ogv":"video/ogg",".ogx":"application/ogg",".onepkg":"application/onenote",".onetmp":"application/onenote",".onetoc":"application/onenote",".onetoc2":"application/onenote",".opf":"application/oebps-package+xml",".oprc":"application/vnd.palm",".org":"application/vnd.lotus-organizer",".osf":"application/vnd.yamaha.openscoreformat",".osfpvg":"application/vnd.yamaha.openscoreformat.osfpvg+xml",".otc":"application/vnd.oasis.opendocument.chart-template",".otf":"application/x-font-otf",".otg":"application/vnd.oasis.opendocument.graphics-template",".oth":"application/vnd.oasis.opendocument.text-web",".oti":"application/vnd.oasis.opendocument.image-template",".otm":"application/vnd.oasis.opendocument.text-master",".otp":"application/vnd.oasis.opendocument.presentation-template",".ots":"application/vnd.oasis.opendocument.spreadsheet-template",".ott":"application/vnd.oasis.opendocument.text-template",".oxt":"application/vnd.openofficeorg.extension",".p":"text/x-pascal",".p10":"application/pkcs10",".p12":"application/x-pkcs12",".p7b":"application/x-pkcs7-certificates",".p7c":"application/pkcs7-mime",".p7m":"application/pkcs7-mime",".p7r":"application/x-pkcs7-certreqresp",".p7s":"application/pkcs7-signature",".pas":"text/x-pascal",".pbd":"application/vnd.powerbuilder6",".pbm":"image/x-portable-bitmap",".pcf":"application/x-font-pcf",".pcl":"application/vnd.hp-pcl",".pclxl":"application/vnd.hp-pclxl",".pct":"image/x-pict",".pcurl":"application/vnd.curl.pcurl",".pcx":"image/x-pcx",".pdb":"application/vnd.palm",".pdf":"application/pdf",".pfa":"application/x-font-type1",".pfb":"application/x-font-type1",".pfm":"application/x-font-type1",".pfr":"application/font-tdpfr",".pfx":"application/x-pkcs12",".pgm":"image/x-portable-graymap",".pgn":"application/x-chess-pgn",".pgp":"application/pgp-encrypted",".pic":"image/x-pict",".pkg":"application/octet-stream",".pki":"application/pkixcmp",".pkipath":"application/pkix-pkipath",".pl":"text/plain",".plb":"application/vnd.3gpp.pic-bw-large",".plc":"application/vnd.mobius.plc",".plf":"application/vnd.pocketlearn",".pls":"application/pls+xml",".pml":"application/vnd.ctc-posml",".png":"image/png",".pnm":"image/x-portable-anymap",".portpkg":"application/vnd.macports.portpkg",".pot":"application/vnd.ms-powerpoint",".potm":"application/vnd.ms-powerpoint.template.macroenabled.12",".potx":"application/vnd.openxmlformats-officedocument.presentationml.template",".ppa":"application/vnd.ms-powerpoint",".ppam":"application/vnd.ms-powerpoint.addin.macroenabled.12",".ppd":"application/vnd.cups-ppd",".ppm":"image/x-portable-pixmap",".pps":"application/vnd.ms-powerpoint",".ppsm":"application/vnd.ms-powerpoint.slideshow.macroenabled.12",".ppsx":"application/vnd.openxmlformats-officedocument.presentationml.slideshow",".ppt":"application/vnd.ms-powerpoint",".pptm":"application/vnd.ms-powerpoint.presentation.macroenabled.12",".pptx":"application/vnd.openxmlformats-officedocument.presentationml.presentation",".pqa":"application/vnd.palm",".prc":"application/x-mobipocket-ebook",".pre":"application/vnd.lotus-freelance",".prf":"application/pics-rules",".ps":"application/postscript",".psb":"application/vnd.3gpp.pic-bw-small",".psd":"image/vnd.adobe.photoshop",".psf":"application/x-font-linux-psf",".ptid":"application/vnd.pvi.ptid1",".pub":"application/x-mspublisher",".pvb":"application/vnd.3gpp.pic-bw-var",".pwn":"application/vnd.3m.post-it-notes",".pwz":"application/vnd.ms-powerpoint",".py":"text/x-python",".pya":"audio/vnd.ms-playready.media.pya",".pyc":"application/x-python-code",".pyo":"application/x-python-code",".pyv":"video/vnd.ms-playready.media.pyv",".qam":"application/vnd.epson.quickanime",".qbo":"application/vnd.intu.qbo",".qfx":"application/vnd.intu.qfx",".qps":"application/vnd.publishare-delta-tree",".qt":"video/quicktime",".qwd":"application/vnd.quark.quarkxpress",".qwt":"application/vnd.quark.quarkxpress",".qxb":"application/vnd.quark.quarkxpress",".qxd":"application/vnd.quark.quarkxpress",".qxl":"application/vnd.quark.quarkxpress",".qxt":"application/vnd.quark.quarkxpress",".ra":"audio/x-pn-realaudio",".ram":"audio/x-pn-realaudio",".rar":"application/x-rar-compressed",".ras":"image/x-cmu-raster",".rcprofile":"application/vnd.ipunplugged.rcprofile",".rdf":"application/rdf+xml",".rdz":"application/vnd.data-vision.rdz",".rep":"application/vnd.businessobjects",".res":"application/x-dtbresource+xml",".rgb":"image/x-rgb",".rif":"application/reginfo+xml",".rl":"application/resource-lists+xml",".rlc":"image/vnd.fujixerox.edmics-rlc",".rld":"application/resource-lists-diff+xml",".rm":"application/vnd.rn-realmedia",".rmi":"audio/midi",".rmp":"audio/x-pn-realaudio-plugin",".rms":"application/vnd.jcp.javame.midlet-rms",".rnc":"application/relax-ng-compact-syntax",".roff":"text/troff",".rpm":"application/x-rpm",".rpss":"application/vnd.nokia.radio-presets",".rpst":"application/vnd.nokia.radio-preset",".rq":"application/sparql-query",".rs":"application/rls-services+xml",".rsd":"application/rsd+xml",".rss":"application/rss+xml",".rtf":"application/rtf",".rtx":"text/richtext",".s":"text/x-asm",".saf":"application/vnd.yamaha.smaf-audio",".sbml":"application/sbml+xml",".sc":"application/vnd.ibm.secure-container",".scd":"application/x-msschedule",".scm":"application/vnd.lotus-screencam",".scq":"application/scvp-cv-request",".scs":"application/scvp-cv-response",".scurl":"text/vnd.curl.scurl",".sda":"application/vnd.stardivision.draw",".sdc":"application/vnd.stardivision.calc",".sdd":"application/vnd.stardivision.impress",".sdkd":"application/vnd.solent.sdkm+xml",".sdkm":"application/vnd.solent.sdkm+xml",".sdp":"application/sdp",".sdw":"application/vnd.stardivision.writer",".see":"application/vnd.seemail",".seed":"application/vnd.fdsn.seed",".sema":"application/vnd.sema",".semd":"application/vnd.semd",".semf":"application/vnd.semf",".ser":"application/java-serialized-object",".setpay":"application/set-payment-initiation",".setreg":"application/set-registration-initiation",".sfd-hdstx":"application/vnd.hydrostatix.sof-data",".sfs":"application/vnd.spotfire.sfs",".sgl":"application/vnd.stardivision.writer-global",".sgm":"text/sgml",".sgml":"text/sgml",".sh":"application/x-sh",".shar":"application/x-shar",".shf":"application/shf+xml",".si":"text/vnd.wap.si",".sic":"application/vnd.wap.sic",".sig":"application/pgp-signature",".silo":"model/mesh",".sis":"application/vnd.symbian.install",".sisx":"application/vnd.symbian.install",".sit":"application/x-stuffit",".sitx":"application/x-stuffitx",".skd":"application/vnd.koan",".skm":"application/vnd.koan",".skp":"application/vnd.koan",".skt":"application/vnd.koan",".sl":"text/vnd.wap.sl",".slc":"application/vnd.wap.slc",".sldm":"application/vnd.ms-powerpoint.slide.macroenabled.12",".sldx":"application/vnd.openxmlformats-officedocument.presentationml.slide",".slt":"application/vnd.epson.salt",".smf":"application/vnd.stardivision.math",".smi":"application/smil+xml",".smil":"application/smil+xml",".snd":"audio/basic",".snf":"application/x-font-snf",".so":"application/octet-stream",".spc":"application/x-pkcs7-certificates",".spf":"application/vnd.yamaha.smaf-phrase",".spl":"application/x-futuresplash",".spot":"text/vnd.in3d.spot",".spp":"application/scvp-vp-response",".spq":"application/scvp-vp-request",".spx":"audio/ogg",".src":"application/x-wais-source",".srx":"application/sparql-results+xml",".sse":"application/vnd.kodak-descriptor",".ssf":"application/vnd.epson.ssf",".ssml":"application/ssml+xml",".stc":"application/vnd.sun.xml.calc.template",".std":"application/vnd.sun.xml.draw.template",".stf":"application/vnd.wt.stf",".sti":"application/vnd.sun.xml.impress.template",".stk":"application/hyperstudio",".stl":"application/vnd.ms-pki.stl",".str":"application/vnd.pg.format",".stw":"application/vnd.sun.xml.writer.template",".sus":"application/vnd.sus-calendar",".susp":"application/vnd.sus-calendar",".sv4cpio":"application/x-sv4cpio",".sv4crc":"application/x-sv4crc",".svd":"application/vnd.svd",".svg":"image/svg+xml",".svgz":"image/svg+xml",".swa":"application/x-director",".swf":"application/x-shockwave-flash",".swi":"application/vnd.arastra.swi",".sxc":"application/vnd.sun.xml.calc",".sxd":"application/vnd.sun.xml.draw",".sxg":"application/vnd.sun.xml.writer.global",".sxi":"application/vnd.sun.xml.impress",".sxm":"application/vnd.sun.xml.math",".sxw":"application/vnd.sun.xml.writer",".t":"text/troff",".tao":"application/vnd.tao.intent-module-archive",".tar":"application/x-tar",".tcap":"application/vnd.3gpp2.tcap",".tcl":"application/x-tcl",".teacher":"application/vnd.smart.teacher",".tex":"application/x-tex",".texi":"application/x-texinfo",".texinfo":"application/x-texinfo",".text":"text/plain",".tfm":"application/x-tex-tfm",".tgz":"application/x-gzip",".tif":"image/tiff",".tiff":"image/tiff",".tmo":"application/vnd.tmobile-livetv",".torrent":"application/x-bittorrent",".tpl":"application/vnd.groove-tool-template",".tpt":"application/vnd.trid.tpt",".tr":"text/troff",".tra":"application/vnd.trueapp",".trm":"application/x-msterminal",".tsv":"text/tab-separated-values",".ttc":"application/x-font-ttf",".ttf":"application/x-font-ttf",".twd":"application/vnd.simtech-mindmapper",".twds":"application/vnd.simtech-mindmapper",".txd":"application/vnd.genomatix.tuxedo",".txf":"application/vnd.mobius.txf",".txt":"text/plain",".u32":"application/x-authorware-bin",".udeb":"application/x-debian-package",".ufd":"application/vnd.ufdl",".ufdl":"application/vnd.ufdl",".umj":"application/vnd.umajin",".unityweb":"application/vnd.unity",".uoml":"application/vnd.uoml+xml",".uri":"text/uri-list",".uris":"text/uri-list",".urls":"text/uri-list",".ustar":"application/x-ustar",".utz":"application/vnd.uiq.theme",".uu":"text/x-uuencode",".vcd":"application/x-cdlink",".vcf":"text/x-vcard",".vcg":"application/vnd.groove-vcard",".vcs":"text/x-vcalendar",".vcx":"application/vnd.vcx",".vis":"application/vnd.visionary",".viv":"video/vnd.vivo",".vor":"application/vnd.stardivision.writer",".vox":"application/x-authorware-bin",".vrml":"model/vrml",".vsd":"application/vnd.visio",".vsf":"application/vnd.vsf",".vss":"application/vnd.visio",".vst":"application/vnd.visio",".vsw":"application/vnd.visio",".vtu":"model/vnd.vtu",".vxml":"application/voicexml+xml",".w3d":"application/x-director",".webm":"video/webm",".wad":"application/x-doom",".wav":"audio/x-wav",".wax":"audio/x-ms-wax",".wbmp":"image/vnd.wap.wbmp",".wbs":"application/vnd.criticaltools.wbs+xml",".wbxml":"application/vnd.wap.wbxml",".wcm":"application/vnd.ms-works",".wdb":"application/vnd.ms-works",".wiz":"application/msword",".wks":"application/vnd.ms-works",".wm":"video/x-ms-wm",".wma":"audio/x-ms-wma",".wmd":"application/x-ms-wmd",".wmf":"application/x-msmetafile",".wml":"text/vnd.wap.wml",".wmlc":"application/vnd.wap.wmlc",".wmls":"text/vnd.wap.wmlscript",".wmlsc":"application/vnd.wap.wmlscriptc",".wmv":"video/x-ms-wmv",".wmx":"video/x-ms-wmx",".wmz":"application/x-ms-wmz",".wpd":"application/vnd.wordperfect",".wpl":"application/vnd.ms-wpl",".wps":"application/vnd.ms-works",".wqd":"application/vnd.wqd",".wri":"application/x-mswrite",".wrl":"model/vrml",".wsdl":"application/wsdl+xml",".wspolicy":"application/wspolicy+xml",".wtb":"application/vnd.webturbo",".wvx":"video/x-ms-wvx",".x32":"application/x-authorware-bin",".x3d":"application/vnd.hzn-3d-crossword",".xap":"application/x-silverlight-app",".xar":"application/vnd.xara",".xbap":"application/x-ms-xbap",".xbd":"application/vnd.fujixerox.docuworks.binder",".xbm":"image/x-xbitmap",".xdm":"application/vnd.syncml.dm+xml",".xdp":"application/vnd.adobe.xdp+xml",".xdw":"application/vnd.fujixerox.docuworks",".xenc":"application/xenc+xml",".xer":"application/patch-ops-error+xml",".xfdf":"application/vnd.adobe.xfdf",".xfdl":"application/vnd.xfdl",".xht":"application/xhtml+xml",".xhtml":"application/xhtml+xml",".xhvml":"application/xv+xml",".xif":"image/vnd.xiff",".xla":"application/vnd.ms-excel",".xlam":"application/vnd.ms-excel.addin.macroenabled.12",".xlb":"application/vnd.ms-excel",".xlc":"application/vnd.ms-excel",".xlm":"application/vnd.ms-excel",".xls":"application/vnd.ms-excel",".xlsb":"application/vnd.ms-excel.sheet.binary.macroenabled.12",".xlsm":"application/vnd.ms-excel.sheet.macroenabled.12",".xlsx":"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",".xlt":"application/vnd.ms-excel",".xltm":"application/vnd.ms-excel.template.macroenabled.12",".xltx":"application/vnd.openxmlformats-officedocument.spreadsheetml.template",".xlw":"application/vnd.ms-excel",".xml":"application/xml",".xo":"application/vnd.olpc-sugar",".xop":"application/xop+xml",".xpdl":"application/xml",".xpi":"application/x-xpinstall",".xpm":"image/x-xpixmap",".xpr":"application/vnd.is-xpr",".xps":"application/vnd.ms-xpsdocument",".xpw":"application/vnd.intercon.formnet",".xpx":"application/vnd.intercon.formnet",".xsl":"application/xml",".xslt":"application/xslt+xml",".xsm":"application/vnd.syncml+xml",".xspf":"application/xspf+xml",".xul":"application/vnd.mozilla.xul+xml",".xvm":"application/xv+xml",".xvml":"application/xv+xml",".xwd":"image/x-xwindowdump",".xyz":"chemical/x-xyz",".zaz":"application/vnd.zzazz.deck+xml",".zip":"application/zip",".zir":"application/vnd.zul",".zirz":"application/vnd.zul",".zmm":"application/vnd.handheld-entertainment+xml"},jE=[".sh",".exe",".app",".bat",".cmd",".msi",".apk",".jar",".py",".js",".cron",".php",".asp"],Ste=Object.keys(Pp);import*as VE from"zod";var bte=VE.custom().refine(r=>r&&r.length>0).refine(r=>r&&r[0]instanceof File,{message:"Please upload a valid file."});import{z as vn}from"zod";var vte=vn.object({id:vn.string(),name:vn.string(),createdAt:vn.coerce.date(),createdBy:vn.string(),updatedAt:vn.coerce.date(),updatedBy:vn.string().nullable(),organizationId:vn.string()});import{z as N}from"zod";import An from"zod";var li=An.object({platformSep:An.string(),fullPathSegments:An.string().array(),relativePathSegments:An.string().array(),relativePath:An.string().describe("path relative to the root test directory, i.e. my-folder/my-test.yaml"),fileName:An.string().describe("base name of the file including the extension, e.g. my-module.module.yaml"),lastModified:An.coerce.date(),createdAt:An.coerce.date()});var f0=N.array(li.extend({id:N.string(),name:N.string(),description:N.string().optional(),labels:N.string().array().optional()})),S0=N.array(li.extend({id:N.string(),name:N.string(),description:N.string().optional(),content:va})),kte=N.object({tests:f0,modules:S0,labels:N.string().array()}),Dte=Hl.merge(ai),Ute=N.object({schemaVersion:N.string(),stepLists:Yn}),Fte=ai.partial().merge(hr.pick({id:!0})),y0={name:N.string().min(1).max(255).describe("1-255 chars; Only letters/numbers/dashes. Cannot start/end with '-'. Not '.yaml', 'none', or UUID."),description:N.string().optional(),baseUrl:N.string().url().optional().describe("For LLM: Ask the user for the base URL if they don't provide it."),environment:N.string().optional().describe("For LLM: Do not include the variable unless the user explicitly asks for it and use the environment lookup tool to get the correct one before passing here."),browserType:N.nativeEnum(Sn).optional().describe("For LLM: Never assign this variable unless the user explicitly asks for it."),viewport:Il.optional().describe("For LLM: Never assign this variable unless the user explicitly asks for it."),pathSegments:N.string().array().optional().describe("For LLM: Only use if explicitly called for by the user. Used to create the test in the correct folder.")},Bte=N.object(y0),zte=Hl.merge(N.object({relativeFilePath:N.string().describe("relative to project root")})),Hte=N.object({name:N.string()}),Gte=N.object({relativeFilePath:N.string()}),jte=N.object({name:N.string()}),Vte=N.object({relativeFilePath:N.string()}),Wte=N.object({name:N.string(),description:N.string(),enabled:N.boolean(),steps:N.lazy(()=>ot.array()),testFilePath:N.string().describe("relative to the project root"),folderPath:N.string().optional().describe("user selected folder path")}),$te=N.object({name:N.string(),description:N.string(),enabled:N.boolean()}).partial();var qte=N.array(Nb),Kte=N.object({defaultEnv:N.string().optional().describe("name of the default env, or undefined to unset")}),Yte=N.object({configFilePath:N.string().describe("full path on disk")}),Xte=N.string().array(),Jte=N.object({message:N.string(),newRelativeTestPath:N.string().optional()}),Op=N.object({name:N.string(),absolutePath:N.string(),relativePath:N.string(),pathSegments:N.array(N.string()),isDirectory:N.boolean(),size:N.number(),createdAt:N.coerce.date(),modifiedAt:N.coerce.date(),accessedAt:N.coerce.date()}),WE=N.object({pathSegments:N.array(N.string())}),Zte=N.object({absolutePath:N.string(),pathSegments:N.array(N.string()),contents:N.array(Op)}),$E=N.object({pathSegments:N.array(N.string())}),qE=N.object({pathSegments:N.array(N.string()),newPathSegments:N.array(N.string())}),KE=N.object({pathSegments:N.array(N.string()),recursive:N.boolean().optional()}),Qte=N.object({success:N.boolean(),message:N.string(),pathSegments:N.array(N.string()).optional()});var Yl=["node_modules","dist","bin",".git",".npm",".next","out",".yarn","__pycache__","build",".env",".venv","venv","env","wheels"],Xl=Yl.map(r=>`**/${r}/**`),YE=!0,wn=!1;import Nr from"chalk";import b0 from"safe-stable-stringify";import E0 from"truncate-json";import T0 from"zod";var ci=b0.configure({deterministic:!1});function XE(r){let e=ci(r),{jsonString:t}=E0(e,5e4);return t}var v0=["app","version","env","namespace","host"];function ve(r){let e=r.bindings()??{},t={};for(let n of Object.keys(e)){let o=e[n];!v0.includes(n)&&typeof o=="string"&&(t[n]=o)}return t}var Zl=T0.enum(["debug","info","warn","error"]);var Fa={debug:20,info:30,warn:40,error:50},Ql={20:"debug",30:"info",40:"warn",50:"error"},Lp=class r{minLogLevel;logBindings;constructor(e,t){typeof e=="string"?this.minLogLevel=Fa[e]:this.minLogLevel=e,this.logBindings=t}logWithLevel(e,t,...n){try{this.logWithLevelHelper(e,t,...n)}catch(o){console.error(`Failed to log to console: ${o}`)}}logWithLevelHelper(e,t,...n){if(e<this.minLogLevel)return;let o;Array.isArray(n[0])?(o=n[0],n=n.slice(1)):typeof n[0]=="object"&&!(n[0]instanceof Error)&&Object.entries(n[0]).length&&(o={...n[0],...this.logBindings},n=n.slice(1));let i=[];if(i.push(...n),console.log(t(...i)),o&&!Array.isArray(o)){let a=Object.entries(o);for(let[s,c]of a){let l=c;c instanceof Error?(l=c.message,console.log(t(` ${s}:`,l)),console.log(t(" stack:",c.stack))):typeof c=="object"?(l=ci(c,void 0,2),l=l.split(`
|
|
9
|
+
`)}`}};function Dh(r){return r instanceof Error?r.message.includes("Timeout")&&r.message.includes("exceeded")&&r.message.includes("waiting for locator"):!1}function Au(r){return!(r instanceof Error)||r.message.includes("locator resolved to visible")?!1:!!(r.message.includes("Timeout")&&r.message.includes("exceeded")&&r.message.includes("body >")||r.message.includes("Element is not attached to the DOM"))}var Tr=class extends Error{retryableWithAI;constructor(e,t,n={}){super(e,n),this.name="CacheAttributesDisqualifyElementError",this.retryableWithAI=t}},hs=class extends Tr{constructor(e,t={}){super(e,!0,t),this.name="BoundingBoxMovedError"}},fs=class extends Tr{constructor(e,t={}){super(e,!1,t),this.name="ZeroOpacityError"}};function wu(r){return r instanceof Error?r.message.includes("Could not find attribute data-momentic-id for object"):!1}function Ru(r){return r instanceof Error?r.message.includes("Timeout")&&r.message.includes("exceeded")&&r.message.includes("waiting for locator")&&r.message.includes("data-momentic-id")&&!r.message.includes("locator resolved")&&!r.message.includes("waiting for element to be"):!1}function Cu(r){return r instanceof Error?r.message.includes("Protocol error (DOM.resolveNode): No node with given id found")||r.message.includes("Could not resolve backend node"):!1}var Bi=class extends Error{constructor(e,t={}){super(e,t),this.name="InsufficientCacheDataError"}};var Cx={CLICK:"Click on an element on the page.",TYPE:"Type the specified text into an input on the page.",PRESS:"Press one or more keyboard keys.",KEY_DOWN:"Hold down one or more keyboard keys.",KEY_UP:"Release one or more keyboard keys.",SELECT_OPTION:"Choose an option from a native <select> component. Never use this command for non <select> elements. Instead, use a series of CLICK commands for those.",NAVIGATE:"Go to the specified fully qualified URL.",SCROLL_UP:"Scroll up.",SCROLL_DOWN:"Scroll down.",GO_BACK:"Go back to the previous page.",HOVER:"Hover over an element.",AI_ASSERTION:"Verify a statement about the current page, retrying until it is true. Only generate an assertion if the goal includes language like 'check that', 'verify that', etc..",WAIT:"Wait a fixed amount of seconds."},xx={...Cx,JAVASCRIPT:"Execute JavaScript code in NODE or BROWSER environment.",ELEMENT_CHECK:"Perform a manual assertion on a specific element.",PAGE_CHECK:"Perform a manual assertion on the page.",NEW_TAB:"Open a new browser tab with the specified URL.",WAIT_FOR_URL:"Wait for the URL to match a pattern.",AI_EXTRACT:"Extract data from the page and optionally store it in an environment variable."};fu.options.forEach(r=>{let e=r.shape.type.value;if(e!=="SUCCESS"&&!xx[e])throw new Error(`Command type ${e} is missing a description`)});var Mx=C.object({type:C.literal("CLICK"),description:C.string().describe("Description of the element to click in the Current Page. Never click on <select> elements, see SELECT_OPTION."),doubleClick:C.boolean().or(C.null()),rightClick:C.boolean().or(C.null())}),_x=C.object({type:C.literal("TYPE"),description:C.string().describe("Description of the element to type into, which must be an <input>, <textarea>, or contenteditable element."),text:C.string().describe("The text to enter, truncated to 500 characters. If the PM provided text in the goals, use it exactly without modification."),pressEnter:C.boolean().or(C.null()).describe("Press enter after typing (useful for form submissions)."),clearContent:C.boolean().describe("Clear existing content before typing. Disable to append to the existing text.")}),Ix=C.object({type:C.literal("GO_BACK")}),Px=C.object({type:C.literal("PRESS"),keys:C.array(C.string()).describe('The keys to press. Only use key names supported by the Playwright press method, such as "a", "ArrowLeft", "Meta", "Control", and "Enter". Multiple keys will be pressed together. Do not suggest platform-specific key combinations, such as CTRL+C.')}),Ox=C.object({type:C.literal("SELECT_OPTION"),description:C.string().describe("Description of the <select> element to choose from. Only use this command to interact with native HTML <select> elements. You must use CLICK to select from any other HTML element, such as <input>, <div>, or custom elements."),option:C.discriminatedUnion("type",[C.object({type:C.literal("VALUE"),value:C.string()}),C.object({type:C.literal("LABEL"),label:C.string()}),C.object({type:C.literal("INDEX"),index:C.string().describe("Zero-based index of the option within the select.")})]).describe("Which option to select. Choose 1 of 3 strategies for selecting. By value is exactly matching the 'value' attribute. By label is exactly matching the 'label' attribute. By index is using the zero-based index of the option within the select.")}),Lx=C.object({type:C.literal("NAVIGATE"),url:C.string().describe("The URL to navigate to. Only navigate to URLs relevant to the user goal.")}),Nx=C.object({type:C.literal("SCROLL"),y:C.number().describe("Scroll up or down by the specified pixels. Positive values scroll down.")}),Dx=C.object({type:C.literal("WAIT"),timeout:C.number().describe("The number of seconds to wait.")}),kx=C.object({type:C.literal("AI_ASSERTION"),assertion:C.string().describe("The assertion to verify. This should be a statement verifiable based on the current page HTML or screenshot. Be specific enough that the assertion is not ambiguous or open to interpretation. Make sure the assertion aligns with what the user intends to verify."),timeout:C.number().describe("The max amount of seconds to wait for the assertion to be true. Respect user wishes but allow no more than 60. If unspecified, choose 5 for quick checks like form status, 10 for page loads, and 30 for actions that explicitly trigger a long time, like image generation.")}),Ux=C.object({type:C.literal("HOVER"),description:C.string().describe("Description of the element to hover over. Prefer elements that have visible bounding boxes according to the screenshot, element class attribute, or child contents.")}),Fx=C.object({type:C.literal("JAVASCRIPT"),code:C.string().describe("JavaScript code to execute. Defaults to NODE environment unless BROWSER is specified."),environment:C.union([C.literal("NODE"),C.literal("BROWSER")]).or(C.null()).describe("Execution environment. Default is NODE."),timeout:C.number().or(C.null()).describe("Max seconds for the code to complete. Max 60 seconds.")}),Bx=C.object({type:C.literal("AI_EXTRACT"),goal:C.string().describe("Description of what data to extract from the page. Be specific about what you want to extract and where to find it."),schema:C.string().or(C.null()).describe("JSON schema defining the expected structure of the extracted data."),envKey:C.string().or(C.null()).describe("Environment variable name to store the extracted result in. If provided, the result will be stored and can be referenced later."),iframeUrl:C.string().or(C.null()).describe("URL or URL regex for the iframe to extract data from.")}),zx=C.object({type:C.literal("ELEMENT_CHECK"),description:C.string().describe("Description of the element to check."),assertionType:C.enum(["EXISTS","VISIBLE","CONTENT_CONTAINS","CONTENT_EQUALS"]).describe("The type of assertion. EXISTS checks if element exists, VISIBLE checks if visible, CONTENT_CONTAINS checks if text contains value, CONTENT_EQUALS checks if text equals value."),value:C.string().or(C.null()).describe("The value to check against (required for CONTENT assertions)."),negated:C.boolean().or(C.null()).describe("If true, asserts the opposite (e.g., does NOT exist)."),timeout:C.number().or(C.null()).describe("Max seconds to wait for the assertion to be true.")}),Hx=C.object({type:C.literal("PAGE_CHECK"),value:C.string().describe("The text content to check for on the page."),negated:C.boolean().or(C.null()).describe("If true, checks that the content is NOT present."),timeout:C.number().or(C.null()).describe("Max seconds to wait for the assertion to be true.")}),Gx=C.object({type:C.literal("NEW_TAB"),url:C.string().describe("The URL to open in the new tab.")}),Vx=C.object({type:C.literal("WAIT_FOR_URL"),matcher:C.discriminatedUnion("type",[C.object({type:C.literal("SUBSTRING"),url:C.string()}),C.object({type:C.literal("GLOB"),glob:C.string()}),C.object({type:C.literal("REGEX"),regex:C.string()}),C.object({type:C.literal("DOMAIN"),domain:C.string()})]).describe("How to match the URL."),caseInsensitive:C.boolean().or(C.null()),negated:C.boolean().or(C.null()).describe("Wait for the URL to NOT match instead."),timeout:C.number().or(C.null()).describe("Max seconds to wait for the URL.")}),kh=C.object({type:C.literal("SUCCESS")}),xu=C.object({type:C.literal("FAILURE")}),zi=C.discriminatedUnion("type",[Mx,_x,Px,Ox,Lx,Nx,Dx,kx,Ux,Ix]),pj=Mn(zi),Ss=C.discriminatedUnion("type",[...zi.options,Fx,zx,Hx,Gx,Vx,Bx]),mj=Mn(Ss),jx=C.discriminatedUnion("type",[...zi.options,xu]).describe("The command that will be executed next. This should naturally follow from your reasoning and be consistent with the goal."),gj=Mn(jx),Wx=C.discriminatedUnion("type",[...zi.options,kh,xu]),hj=Mn(Wx),fj=C.discriminatedUnion("type",[...Ss.options,kh,xu]),$x=C.object({command:zi,thoughts:C.string()}),Sj=Mn($x),yj=C.object({command:C.unknown(),thoughts:C.string()});import{z as Mu}from"zod";import{extendZodWithOpenApi as Yx}from"zod-openapi";import{z as Uh}from"zod";import{extendZodWithOpenApi as qx}from"zod-openapi";import{z as _n}from"zod";var $t=_n.object({index:_n.number().optional().describe("global index within a test (in-order traversal)"),id:_n.string(),skipped:_n.boolean().optional(),envKey:_n.string().optional().describe("key in the environment to save the result of this step to"),aiSuggested:_n.boolean().optional(),retries:_n.number().optional()});qx(Uh);var Kx=$t.extend({type:Uh.literal("PRESET_ACTION")}),qt=Kx.extend({command:Eo}).openapi({ref:"PresetAction"});Yx(Mu);var In=$t.extend({type:Mu.literal("AI_ACTION"),text:Mu.string(),steps:qt.array().optional()}).openapi({ref:"AIAction"});import{z as Ct}from"zod";import{z as ys}from"zod";import{extendZodWithOpenApi as Xx}from"zod-openapi";Xx(ys);var Ao=$t.extend({type:ys.literal("AI_ACTION_DYNAMIC"),text:ys.string(),retries:ys.number().optional()}).openapi({ref:"AIActionDynamic"});import{z as Fh}from"zod";var _u=$t.extend({type:Fh.literal("CONDITIONAL"),skipped:Fh.boolean().optional()});import{z as le}from"zod";var Jx=le.object({cacheKey:le.string(),cacheExpiryMs:le.number()}),Iu=$t.extend({id:le.string().uuid().describe("ID of the module step itself. Used to 'namespace' step cache entries."),inputs:le.record(le.string()).optional(),cacheConfig:Jx.optional()}),Br=Iu.extend({type:le.literal("MODULE"),moduleId:le.string().uuid()}),Zx=le.union([Br.pick({type:!0,moduleId:!0}),le.record(le.unknown())]),Qx=le.object({type:le.literal("URL_REGEX"),regex:le.string()}),eM=le.object({type:le.literal("PAGE_CHECK"),substring:le.string()}),Pu=le.object({cacheInvalidation:le.discriminatedUnion("type",[eM,Qx]).optional()}),Kt=le.object({moduleId:le.string().uuid(),name:le.string(),description:le.string().nullish(),enabled:le.boolean().nullish(),parameters:le.string().array().nullish(),defaultParameters:le.record(le.string(),le.string()).nullish(),parameterEnums:le.record(le.string(),le.string().array()).nullish(),defaultCacheKey:le.string().nullish(),defaultCacheTtl:le.number().nullish(),defaultCacheAllInvocations:le.boolean().nullish(),autoAuth:le.boolean().nullish(),advanced:Pu.nullish()});import{z as Yt}from"zod";var Bh=(n=>(n.ALWAYS="ALWAYS",n.ON_FAILURE="ON_FAILURE",n.ON_ACTION_FAILURE="ON_ACTION_FAILURE",n))(Bh||{});var tM=Yt.discriminatedUnion("type",[Yt.object({type:Yt.literal("NAVIGATE_URL"),url:Yt.string().url()}),Yt.object({type:Yt.literal("GO_TO_SECTION_START")})]),rM=Yt.object({trigger:Yt.nativeEnum(Bh).optional(),attempts:Yt.number().int().optional(),restartBehavior:tM}),Hi=$t.extend({type:Yt.literal("SECTION"),description:Yt.string().describe("user provided goal of what the section should accomplish"),plan:Yt.string().array().optional(),autohealingConfig:rM.optional()});var zh=Kt.merge(Iu).extend({type:Ct.literal("RESOLVED_MODULE"),steps:Ct.lazy(()=>ot.array())}),Gi=Kt.extend({steps:Ct.lazy(()=>ot.array())}),Ou=Hi.extend({steps:Ct.lazy(()=>xt.array())}),nM=Hi.extend({steps:Ct.lazy(()=>ot.array())}),wo=_u.extend({blocks:Ct.object({assertion:Ct.lazy(()=>qt),steps:Ct.lazy(()=>xt.array())}).array(),elseSteps:Ct.lazy(()=>xt.array().optional())}),oM=_u.extend({blocks:Ct.object({assertion:Ct.lazy(()=>qt),steps:Ct.lazy(()=>ot.array())}).array(),elseSteps:Ct.lazy(()=>ot.array().optional())}),xt=Ct.discriminatedUnion("type",[qt,In,Ao,Br,wo,Ou]),ot=Ct.discriminatedUnion("type",[qt,In,Ao,zh,oM,nM]);import{z as Xt}from"zod";var iM=Xt.object({steps:xt.array(),beforeSteps:xt.array().nullish(),afterSteps:xt.array().nullish()}),Pn=Xt.object({steps:ot.array(),beforeSteps:ot.array().nullish(),afterSteps:ot.array().nullish()}),On=Xt.object({steps:Xt.record(Xt.string(),Xt.unknown()).array(),beforeSteps:Xt.record(Xt.string(),Xt.unknown()).array().nullish(),afterSteps:Xt.record(Xt.string(),Xt.unknown()).array().nullish()});var Ln="1.0.21",Lu="0.0.1";import{z as ft}from"zod";import{z as Nn}from"zod";var aM=/^[a-f0-9]{8}-[a-f0-9]{4}-[1-5][a-f0-9]{3}-[89ab][a-f0-9]{3}-[a-f0-9]{12}$/,Qr=r=>{let e=r.trim().toLowerCase().replace(/[^a-z0-9]/g,"-");for(;e.includes("--");)e=e.replaceAll("--","-");return e.startsWith("-")&&(e=e.slice(1)),e.endsWith("-")&&(e=e.slice(0,e.length-1)),e};var Ro=Nn.string().min(1).max(255).superRefine((r,e)=>{try{Nu(r)}catch(t){return e.addIssue({code:Nn.ZodIssueCode.custom,message:t.message,fatal:!0}),Nn.NEVER}});function Nu(r){if(r=r.toLowerCase().trim(),r.length===0||r.length>255)throw new Error("Name must be between 1 and 255 characters long");if(/[<>:"/\\|?*]/.test(r))throw new Error('Name contains one of the following invalid characters: <>:"/\\|?*');if(r.endsWith("-")||r.startsWith("-"))throw new Error("Name cannot start or end with a dash.");if(r.includes("\0"))throw new Error("Name cannot contain null characters");if(/^(con|prn|aux|nul|com[0-9]|lpt[0-9])(\..*)?$/i.test(r))throw new Error(`"${r}" is a reserved name on Windows and cannot be used as a filename.`);if(/^\.+$/.test(r)||/^\s|\s$/.test(r))throw new Error("Name cannot start or end with a space or dot.");if(r.endsWith(".yaml"))throw new Error('Name cannot end with ".yaml".');if(r==="none")throw new Error("Name cannot be 'none'.");if(r.match(aM))throw new Error("Name cannot be a UUID. Please choose a different name.")}var bs=Nn.preprocess(r=>r===null?"":r,Nn.union([Nn.string().url(),Nn.literal("")])).optional();var sM=["AI_EXTRACT","JAVASCRIPT"],lM=ft.object({id:ft.string().optional().describe("Recommended way of selecting an entity. The id of the entity to resolve."),name:Ro.optional().describe("1-255 chars; Only letters/numbers/dashes. Cannot start/end with '-'. Not '.yaml', 'none', or UUID."),path:ft.string().optional().describe("The path of the entity to resolve.")}).describe("A selector for a single entity. Exactly one of id, name, or path must be provided. Id is recommended.").refine(r=>[r.id,r.name,r.path].filter(Boolean).length===1,"Exactly one of id, name, or path must be provided."),cM=ft.object({selector:lM,inputs:ft.record(ft.string()).or(ft.null())}),LW=ft.object({type:ft.literal("PRESET_ACTION"),action:Ss,envKey:ft.string().or(ft.null()).describe(`key in the environment to save the result of this step to. Only use this for ${sM.join(" or ")} steps.`)}),NW=ft.object({type:ft.literal("MODULE"),module:cM}),DW=ft.object({type:ft.literal("AI_ACTION_DYNAMIC"),text:ft.string().describe("The goal description for the AI action. Supports handlebars templates like {{env.VARIABLE_NAME}}.")});var Hh=P.object({phrase:P.string()}),Du=P.object({thoughts:P.string().optional(),result:P.union([P.literal("NOT_FOUND"),P.string(),P.number(),P.array(P.unknown()),P.record(P.unknown(),P.unknown()),P.unknown()])}),f$=P.object({text:P.string()}),Gh=P.object({attributes:P.array(P.string()).optional(),text:P.boolean().optional(),boundingBox:P.boolean().optional()}),uM=P.object({id:P.number().int(),requirements:Gh}),dM=uM.array(),Vh=P.object({thoughts:P.string(),review:P.string().optional(),id:P.number().int(),updatedMemory:iu.optional(),requirements:Gh.optional(),additionalElements:dM.optional()});var ku=(m=>(m.NO_DESCRIPTION_PROVIDED="NO_DESCRIPTION_PROVIDED",m.FEW_WORDS="FEW_WORDS",m.STYLE_TAG="STYLE_TAG",m.TYPE_IN_DESCRIPTION="TYPE_IN_DESCRIPTION",m.HARDCODED_ATTRIBUTE="HARDCODED_ATTRIBUTE",m.NONE="NONE",m.AMBIGUOUS_DESCRIPTION="AMBIGUOUS_DESCRIPTION",m.AMBIGUOUS_ASSERTION="AMBIGUOUS_ASSERTION",m.PREFER_PAGE_CHECK="PREFER_PAGE_CHECK",m.PREFER_ASSERTION="PREFER_ASSERTION",m.HTML_ELEMENTS="HTML_ELEMENTS",m.MULTIPLE_ELEMENTS_DESCRIPTION="MULTIPLE_ELEMENTS_DESCRIPTION",m.NEEDS_DATE_VARIABLE="NEEDS_DATE_VARIABLE",m))(ku||{}),jh=(o=>(o.NONE="NONE",o.AMBIGUOUS_DESCRIPTION="AMBIGUOUS_DESCRIPTION",o.COPILOT_MISUSE="COPILOT_MISUSE",o.IRRELEVANT_MESSAGE="IRRELEVANT_MESSAGE",o))(jh||{});var Wh=P.object({thoughts:P.string(),category:P.nativeEnum(ku)}),$h=P.object({thoughts:P.string(),category:P.nativeEnum(jh)}),pM=P.discriminatedUnion("op",[P.object({op:P.literal("replace"),path:P.string(),value:P.string()}),P.object({op:P.literal("add"),path:P.string(),value:P.string()}),P.object({op:P.literal("remove"),path:P.string()})]),S$=P.object({thoughts:P.string(),patches:pM.array()}),mM=[P.literal("add"),P.literal("replace"),P.literal("remove")],gM=P.object({op:P.union(mM),path:P.string(),value:ot.optional()}),qh=P.object({patches:gM.array(),thoughts:P.string()}),Kh=(n=>(n.LEGITIMATE="LEGITIMATE",n.RECOVERABLE="RECOVERABLE",n.INELIGIBLE="INELIGIBLE",n))(Kh||{}),Yh=P.object({thoughts:P.string(),scenario:P.nativeEnum(Kh),instructions:P.string().nullish()}),Xh=P.object({reasoning:P.string(),scenario:P.string(),patch:P.null().optional()}),y$=P.object({thoughts:P.string(),evaluation:P.number().min(0).max(10)}),b$=P.object({observations:P.string(),reasoning:P.string(),command:ls});var Uu=P.object({summary:P.string(),reasoning:P.string(),evaluation:P.discriminatedUnion("type",[P.object({type:P.literal("DONE")}),P.object({type:P.literal("RIGHT_TRACK")}),P.object({type:P.literal("WRONG_TRACK"),feedback:P.string()}),P.object({type:P.literal("IMPOSSIBLE")})])}),hM=P.object({startId:P.number().int(),endId:P.number().int()}),Fu=(n=>(n.SIMPLE_CONTENT_BASED_LOCATOR="SIMPLE_CONTENT_BASED_LOCATOR",n.SIMPLE_CONTENT_BASED_ASSERTION="SIMPLE_CONTENT_BASED_ASSERTION",n.OTHER="OTHER",n))(Fu||{}),Jh=P.object({categoryThoughts:P.string(),category:P.nativeEnum(Fu),relevantSections:hM.array()});import{z as I}from"zod";import*as ee from"zod";var R$=ee.object({thoughts:ee.string().optional().describe("only provided if a description was provided"),target:Kr.optional().describe("only provided if a description was provided"),pageState:ee.string().optional().describe("serialized a11y tree, only provided if a description was provided"),options:ee.object({label:ee.string(),value:ee.string()}).array().optional().describe("list of options, provided for <select> elements only"),screenshot:ee.object({data:ee.string(),height:ee.number().int(),width:ee.number().int()}).optional().describe("only provided if returnScreenshot is true")}),Zh=ee.union([ee.literal("ELEMENT_CHECK"),ee.literal("NEGATED_CHECK"),ee.literal("NEGATED_ELEMENT_VISIBLE_CHECK"),ee.literal("SELECT_OPTION"),ee.literal("TYPE")]);function Vi(r){if(!("useSelector"in r&&r.useSelector)){if(r.type==="SELECT_OPTION")return"SELECT_OPTION";if(r.type==="TYPE")return"TYPE";if(r.type==="ELEMENT_CHECK"&&r.assertion.type==="ELEMENT_EXISTENCE"&&r.assertion.condition==="EXISTS"&&r.assertion.negated)return"NEGATED_CHECK";if(r.type==="ELEMENT_CHECK"&&r.assertion.type==="ELEMENT_EXISTENCE"&&r.assertion.condition==="VISIBLE"&&r.assertion.negated)return"NEGATED_ELEMENT_VISIBLE_CHECK";if(r.type==="ELEMENT_CHECK")return"ELEMENT_CHECK"}}var ji=(a=>(a.USER_SELECTOR="USER_SELECTOR",a.CSS_SELECTOR="CSS_SELECTOR",a.HYBRID_SELECTOR="HYBRID_SELECTOR",a.HTML_DISTANCE="HTML_DISTANCE",a.TEMPLATE_MATCHING="TEMPLATE_MATCHING",a.AUTO_FRAME="AUTO_FRAME",a))(ji||{}),Co=ee.object({matched:ee.boolean(),reason:ee.string().optional().describe("Human understandable description"),logs:ee.string().array().optional().describe("Logs for debugging")}),fM=Co.extend({type:ee.literal("USER_SELECTOR")}),SM=Co.extend({type:ee.literal("CSS_SELECTOR"),selectors:ee.string().array()}),yM=Co.extend({type:ee.literal("HYBRID_SELECTOR")}),bM=Co.extend({type:ee.literal("HTML_DISTANCE"),distance:ee.number().optional(),closestElement:ee.string().optional(),savedElement:ee.string().optional()}),EM=Co.extend({type:ee.literal("TEMPLATE_MATCHING"),elementImageUrl:ee.string().url()}),TM=Co.extend({type:ee.literal("AUTO_FRAME"),logs:ee.string().array().optional()}),Qh=ee.discriminatedUnion("type",[fM,SM,yM,bM,EM,TM]);import{z as Ki}from"zod";import{z as PM}from"zod";import*as G from"zod";import{extendZodWithOpenApi as AM}from"zod-openapi";import{cloneDeep as k$}from"lodash-es";import F$ from"truncate-json";import*as Un from"zod";import{extendZodWithOpenApi as vM}from"zod-openapi";import{z as St}from"zod";import{z as ue}from"zod";var Bu=ue.object({autoFollowNewTabs:ue.boolean().optional().describe("Deprecated: Auto-follow new tabs that are opened."),showZeroOpacityElements:ue.union([ue.boolean(),ue.literal("inputs-only")]).optional(),ignoreHrefForCaching:ue.boolean().optional(),disableSecondaryCacheResolution:ue.boolean().optional(),hybridSelectorMode:ue.enum(["off","test","prefer"]).optional(),globalLocatorRedirect:ue.union([ue.boolean(),ue.literal("always")]).optional(),visualActions:ue.boolean().optional(),autoExpandIframes:ue.boolean().optional(),disableHtmlSnapshots:ue.boolean().optional(),importantAttributes:ue.string().array().optional(),importantClasses:ue.string().array().optional(),importantStyles:ue.string().array().optional()});var ef=1e4,tf=6e4,Dn=Bu.extend({pageLoadTimeoutMs:ue.number().optional().refine(r=>r===void 0||r<=tf&&r>=-1,{message:`Page load timeout must be between 0 and ${tf/1e3} seconds`}).describe("global page load timeout default for all tests in ms, can still be overridden by individual tests"),smartWaitingTimeoutMs:ue.number().optional().refine(r=>r===void 0||r<=ef&&r>=-1,{message:`Smart waiting timeout must be between 0 and ${ef/1e3} seconds`}),localChromeExtensionPaths:ue.string().array().optional(),extraHeaders:ue.record(ue.string(),ue.string()).optional().describe("HTTP headers to be sent on every request"),initialLocalStorage:ue.record(ue.string(),ue.record(ue.string(),ue.string())).optional().describe("Initial local storage key-value pairs to set per domain on browser startup"),userAgent:ue.string().optional(),disableGpu:ue.boolean().optional(),bustCacheOnBoundingBoxChange:ue.boolean().optional().describe("Bust the cache if no elements are matched that have the same bounding box and location as the original element. This will improve accuracy on sites that use many same components, at the expense of stability and speed."),allowPartialAccessibilityTree:ue.boolean().optional().describe("Allow fetching the partial accessibility tree if fetching the full tree takes too long."),ignoreHttpsErrors:ue.boolean().optional().describe("Ignore HTTPS errors, such as self-signed certificates and certificate errors. This can be useful for testing sites that use self-signed certificates or certificate errors.")});var zu="BASE_URL";var kn="ENV_NAME",xo="TEST_NAME",P$={[zu]:"https://www.google.com"},rf=St.string().describe("Name of the fixture (must be available locally in the fixtures directory)."),nf=St.object({name:St.string(),variables:St.record(St.string().describe("variable name"),St.string().describe("variable value"))}),of=St.object({name:St.string(),variables:St.record(St.string().describe("variable name"),St.unknown().describe("variable value")),browser:Dn.optional()});var O$=St.object({name:St.string(),variables:St.record(St.string().describe("variable name"),St.unknown().describe("variable value"))});vM(Un);var Hu=Un.object({env:Un.record(Un.unknown())}).openapi({ref:"TestContextSnapshot"});var Ge=(i=>(i.SUCCESS="SUCCESS",i.FAILED="FAILED",i.RUNNING="RUNNING",i.IDLE="IDLE",i.CANCELLED="CANCELLED",i))(Ge||{}),Gu=(n=>(n.SUCCESS="SUCCESS",n.FAILED="FAILED",n.CANCELLED="CANCELLED",n))(Gu||{});AM(G);var Vu=G.object({beforeUrl:G.string().optional(),afterUrl:G.string().optional(),message:G.string().optional(),beforeSnapshot:G.string().optional(),afterSnapshot:G.string().optional(),startedAt:G.coerce.date(),finishedAt:G.coerce.date()}),wM=Vu.extend({viewport:G.object({height:G.number(),width:G.number()}).nullish(),status:G.nativeEnum(Gu),message:G.string().optional(),elementInteracted:G.string().optional()}),Fn=Vu.extend({status:G.nativeEnum(Ge),message:G.string().optional(),data:G.unknown().optional(),beforeTestContext:Hu.optional(),afterTestContext:Hu.optional(),failureReason:G.nativeEnum(we).optional(),details:G.unknown().describe("Parse using StepExecutionLogSchema.array() to get type safety. We don't explicitly type it because it's non-critical information.")}).openapi({ref:"StepResultMetadata"}),af=(t=>(t.NOT_ELIGIBLE="NOT_ELIGIBLE",t.ATTEMPTED="ATTEMPTED",t))(af||{}),Es=Fn.merge(qt).extend({results:wM.array().describe("Command that was executed. Array is just for consistency with other result types. There should only ever be one item."),previousAttempts:G.lazy(()=>st.array()).optional(),failureRecoveryStatus:G.object({type:G.nativeEnum(af),message:G.string()}).optional()}),RM=Fn.merge(In).extend({results:G.lazy(()=>Es.array()),previousAttempts:G.lazy(()=>st.array()).optional()}),CM=Fn.merge(Ao).extend({results:G.lazy(()=>Es.array()),previousAttempts:G.lazy(()=>st.array()).optional()}),xM=Fn.merge(Br).extend({moduleName:G.string().optional(),results:G.lazy(()=>st.array()),previousAttempts:G.lazy(()=>st.array()).optional()}),MM=Fn.merge(wo).extend({assertion:Es.optional(),results:G.lazy(()=>st.array()).describe("results for the block actually executed"),previousAttempts:G.lazy(()=>st.array()).optional()}),_M=Fn.merge(Hi).extend({results:G.lazy(()=>st.array()),healingAttempts:G.lazy(()=>st.array().array()).optional(),previousAttempts:G.lazy(()=>st.array()).optional()}),st=G.discriminatedUnion("type",[RM,CM,Es,xM,MM,_M]),eq=Fn.pick({startedAt:!0,finishedAt:!0,status:!0,message:!0,data:!0}),IM=Vu.extend({index:G.number().optional(),description:G.string(),pageState:G.string().optional(),elementInteracted:G.string().optional(),startedAt:G.coerce.date().or(G.string()).optional().catch(void 0),finishedAt:G.coerce.date().or(G.string()).optional().catch(void 0)}),Ts=IM.extend({beforeScreenshot:G.string().optional(),afterScreenshot:G.string().optional()});var ju=PM.object({results:st.array().describe("main results"),beforeResults:st.array().optional(),afterResults:st.array().optional()}),Wi=ju.partial();import{z as k}from"zod";import{extendZodWithOpenApi as FM}from"zod-openapi";var Mo=(t=>(t.WEB="WEB",t.ANDROID="ANDROID",t))(Mo||{});import{isValidCron as OM}from"cron-validator";import{z as te}from"zod";import{z as Wu}from"zod";var en=(n=>(n.CHROMIUM="Chromium",n.GOOGLE_CHROME="Google Chrome",n.CHROME_FOR_TESTING="Chrome for Testing",n))(en||{});var vs=Wu.object({width:Wu.number().min(200).max(1e4),height:Wu.number().min(200).max(1e4)}),sf={"Desktop Large":{width:1920,height:1080},"Desktop Small":{width:1280,height:800},iPad:{width:768,height:1024},"Pixel 8":{width:448,height:998},"iPhone 15":{width:393,height:852}},sq=Object.keys(sf);var tn=sf["Desktop Large"],lf="en-us",cf="America/Los_Angeles";var uf={latitude:37.7749,longitude:-122.4194};var df=["Africa/Abidjan","Africa/Accra","Africa/Algiers","Africa/Bissau","Africa/Cairo","Africa/Casablanca","Africa/Ceuta","Africa/El_Aaiun","Africa/Johannesburg","Africa/Juba","Africa/Khartoum","Africa/Lagos","Africa/Maputo","Africa/Monrovia","Africa/Nairobi","Africa/Ndjamena","Africa/Sao_Tome","Africa/Tripoli","Africa/Tunis","Africa/Windhoek","America/Adak","America/Anchorage","America/Argentina/Buenos_Aires","America/Argentina/Catamarca","America/Argentina/Cordoba","America/Argentina/Jujuy","America/Argentina/La_Rioja","America/Argentina/Mendoza","America/Argentina/Rio_Gallegos","America/Argentina/Salta","America/Argentina/San_Juan","America/Argentina/San_Luis","America/Argentina/Tucuman","America/Argentina/Ushuaia","America/Araguaina","America/Asuncion","America/Atikokan","America/Bahia","America/Bahia_Banderas","America/Barbados","America/Belem","America/Belize","America/Blanc-Sablon","America/Boa_Vista","America/Bogota","America/Boise","America/Cambridge_Bay","America/Campo_Grande","America/Cancun","America/Caracas","America/Cayenne","America/Chicago","America/Chihuahua","America/Costa_Rica","America/Creston","America/Cuiaba","America/Curacao","America/Danmarkshavn","America/Dawson","America/Dawson_Creek","America/Denver","America/Detroit","America/Dominica","America/Edmonton","America/Eirunepe","America/El_Salvador","America/Fort_Nelson","America/Fortaleza","America/Glace_Bay","America/Goose_Bay","America/Grand_Turk","America/Grenada","America/Guadeloupe","America/Guatemala","America/Guayaquil","America/Guyana","America/Halifax","America/Havana","America/Hermosillo","America/Indiana/Indianapolis","America/Indiana/Knox","America/Indiana/Marengo","America/Indiana/Petersburg","America/Indiana/Tell_City","America/Indiana/Vevay","America/Indiana/Vincennes","America/Indiana/Winamac","America/Inuvik","America/Iqaluit","America/Jamaica","America/Juneau","America/Kentucky/Louisville","America/Kentucky/Monticello","America/La_Paz","America/Lima","America/Los_Angeles","America/Maceio","America/Managua","America/Manaus","America/Marigot","America/Martinique","America/Matamoros","America/Mazatlan","America/Menominee","America/Merida","America/Metlakatla","America/Mexico_City","America/Miquelon","America/Moncton","America/Monterrey","America/Montevideo","America/Montserrat","America/Nassau","America/New_York","America/Nipigon","America/Nome","America/Noronha","America/North_Dakota/Beulah","America/North_Dakota/Center","America/North_Dakota/New_Salem","America/Ojinaga","America/Panama","America/Pangnirtung","America/Paramaribo","America/Phoenix","America/Port-au-Prince","America/Port_of_Spain","America/Porto_Velho","America/Puerto_Rico","America/Punta_Arenas","America/Rainy_River","America/Rankin_Inlet","America/Recife","America/Regina","America/Resolute","America/Rio_Branco","America/Santarem","America/Santiago","America/Santo_Domingo","America/Sao_Paulo","America/Scoresbysund","America/Sitka","America/St_Barthelemy","America/St_Johns","America/St_Kitts","America/St_Lucia","America/St_Thomas","America/St_Vincent","America/Swift_Current","America/Tegucigalpa","America/Thule","America/Thunder_Bay","America/Tijuana","America/Toronto","America/Tortola","America/Vancouver","America/Whitehorse","America/Winnipeg","America/Yakutat","America/Yellowknife","Antarctica/Casey","Antarctica/Davis","Antarctica/DumontDUrville","Antarctica/Macquarie","Antarctica/Mawson","Antarctica/Palmer","Antarctica/Rothera","Antarctica/Syowa","Antarctica/Troll","Antarctica/Vostok","Arctic/Longyearbyen","Asia/Aden","Asia/Almaty","Asia/Amman","Asia/Anadyr","Asia/Aqtau","Asia/Aqtobe","Asia/Ashgabat","Asia/Atyrau","Asia/Baghdad","Asia/Bahrain","Asia/Baku","Asia/Bangkok","Asia/Barnaul","Asia/Beirut","Asia/Bishkek","Asia/Brunei","Asia/Chita","Asia/Choibalsan","Asia/Colombo","Asia/Damascus","Asia/Dhaka","Asia/Dili","Asia/Dubai","Asia/Dushanbe","Asia/Famagusta","Asia/Gaza","Asia/Hebron","Asia/Ho_Chi_Minh","Asia/Hong_Kong","Asia/Hovd","Asia/Irkutsk","Asia/Jakarta","Asia/Jayapura","Asia/Jerusalem","Asia/Kabul","Asia/Kamchatka","Asia/Karachi","Asia/Kathmandu","Asia/Khandyga","Asia/Kolkata","Asia/Krasnoyarsk","Asia/Kuala_Lumpur","Asia/Kuching","Asia/Kuwait","Asia/Macau","Asia/Magadan","Asia/Makassar","Asia/Manila","Asia/Muscat","Asia/Nicosia","Asia/Novokuznetsk","Asia/Novosibirsk","Asia/Omsk","Asia/Oral","Asia/Phnom_Penh","Asia/Pontianak","Asia/Pyongyang","Asia/Qatar","Asia/Qostanay","Asia/Qyzylorda","Asia/Riyadh","Asia/Sakhalin","Asia/Samarkand","Asia/Seoul","Asia/Shanghai","Asia/Singapore","Asia/Srednekolymsk","Asia/Taipei","Asia/Tashkent","Asia/Tbilisi","Asia/Tehran","Asia/Thimphu","Asia/Tokyo","Asia/Tomsk","Asia/Ulaanbaatar","Asia/Urumqi","Asia/Ust-Nera","Asia/Vientiane","Asia/Vladivostok","Asia/Yakutsk","Asia/Yangon","Asia/Yekaterinburg","Asia/Yerevan","Atlantic/Azores","Atlantic/Bermuda","Atlantic/Canary","Atlantic/Cape_Verde","Atlantic/Faroe","Atlantic/Madeira","Atlantic/Reykjavik","Atlantic/South_Georgia","Atlantic/Stanley","Australia/Adelaide","Australia/Brisbane","Australia/Broken_Hill","Australia/Currie","Australia/Darwin","Australia/Eucla","Australia/Hobart","Australia/Lindeman","Australia/Lord_Howe","Australia/Melbourne","Australia/Perth","Australia/Sydney","Europe/Amsterdam","Europe/Andorra","Europe/Astrakhan","Europe/Athens","Europe/Belgrade","Europe/Berlin","Europe/Bratislava","Europe/Brussels","Europe/Bucharest","Europe/Budapest","Europe/Busingen","Europe/Chisinau","Europe/Copenhagen","Europe/Dublin","Europe/Gibraltar","Europe/Guernsey","Europe/Helsinki","Europe/Isle_of_Man","Europe/Istanbul","Europe/Jersey","Europe/Kaliningrad","Europe/Kiev","Europe/Kirov","Europe/Lisbon","Europe/Ljubljana","Europe/London","Europe/Luxembourg","Europe/Madrid","Europe/Malta","Europe/Mariehamn","Europe/Minsk","Europe/Monaco","Europe/Moscow","Europe/Oslo","Europe/Paris","Europe/Podgorica","Europe/Prague","Europe/Riga","Europe/Rome","Europe/Samara","Europe/San_Marino","Europe/Sarajevo","Europe/Saratov","Europe/Simferopol","Europe/Skopje","Europe/Sofia","Europe/Stockholm","Europe/Tallinn","Europe/Tirane","Europe/Ulyanovsk","Europe/Uzhgorod","Europe/Vaduz","Europe/Vatican","Europe/Vienna","Europe/Vilnius","Europe/Volgograd","Europe/Warsaw","Europe/Zagreb","Europe/Zaporozhye","Europe/Zurich","Indian/Antananarivo","Indian/Chagos","Indian/Christmas","Indian/Cocos","Indian/Comoro","Indian/Kerguelen","Indian/Mahe","Indian/Maldives","Indian/Mauritius","Indian/Mayotte","Indian/Reunion","Pacific/Apia","Pacific/Auckland","Pacific/Bougainville","Pacific/Chatham","Pacific/Chuuk","Pacific/Easter","Pacific/Efate","Pacific/Enderbury","Pacific/Fakaofo","Pacific/Fiji","Pacific/Funafuti","Pacific/Galapagos","Pacific/Gambier","Pacific/Guadalcanal","Pacific/Guam","Pacific/Honolulu","Pacific/Kiritimati","Pacific/Kosrae","Pacific/Kwajalein","Pacific/Majuro","Pacific/Marquesas","Pacific/Midway","Pacific/Nauru","Pacific/Niue","Pacific/Norfolk","Pacific/Noumea","Pacific/Pago_Pago","Pacific/Palau","Pacific/Pitcairn","Pacific/Pohnpei","Pacific/Port_Moresby","Pacific/Rarotonga","Pacific/Saipan","Pacific/Tahiti","Pacific/Tarawa","Pacific/Tongatapu","Pacific/Wake","Pacific/Wallis"];var pf=1e4,LM=Dn.extend({browserType:te.nativeEnum(en).optional(),slowMoMs:te.number().optional().refine(r=>r===void 0||r<=pf&&r>=-1,{message:`Slow motion must be between 0 and ${pf} milliseconds`}),basicAuthorization:te.object({username:te.string().optional(),password:te.string().optional()}).optional(),geolocation:te.object({latitude:te.coerce.number().refine(r=>r>=-90&&r<=90,{message:"Latitude must be between -90 and 90 degrees"}),longitude:te.coerce.number().refine(r=>r>=-180&&r<=180,{message:"Longitude must be between -180 and 180 degrees"})}).optional(),disableJavaScript:te.boolean().optional(),locale:te.string().optional(),timezone:te.enum(df).optional(),colorScheme:te.enum(["light","dark"]).optional()});var $u=te.object({useMemory:te.boolean().optional(),failureRecovery:te.boolean().optional().describe("undefined means inherit org settings")}),NM=$u.extend({disableAICaching:te.boolean().optional(),failureRecoveryInstructions:te.string().optional()}),DM=te.object({viewport:vs.optional()}),$i=DM.merge(NM).merge(LM),_o=te.object({cron:te.string().refine(r=>OM(r),{message:"Invalid cron expression."}).default("0 0 */1 * *"),enabled:te.boolean().default(!1),env:te.string().optional(),timeZone:te.string().default("America/Los_Angeles"),jobKey:te.string().optional()}),Io=te.object({onSuccess:te.boolean().default(!1),failureMessage:te.string().optional(),onFailure:te.boolean().default(!0),successMessage:te.string().optional()}),kM=te.object({name:te.string(),required:te.boolean().optional(),defaultValue:te.string().describe("this is not optional because we need a value when the editor is first loaded")}),As=kM.array(),UM=te.object({name:te.string(),value:te.string()}),mf=UM.array(),ws=te.object({name:te.string(),default:te.boolean().optional(),fixtures:rf.array().optional()});FM(k);var Jt={WEBHOOK:"WEBHOOK",CRON:"CRON",MANUAL:"MANUAL",CLI:"CLI"},ve=(l=>(l.PENDING="PENDING",l.RUNNING="RUNNING",l.PASSED="PASSED",l.FAILED="FAILED",l.CANCELLED="CANCELLED",l.RETRYING="RETRYING",l.WAITING_FOR_USER="WAITING_FOR_USER",l))(ve||{}),Rs=(t=>(t.BEFORE_ALL="BEFORE_ALL",t.AFTER_ALL="AFTER_ALL",t))(Rs||{});var Ye=k.string().pipe(k.coerce.date()).or(k.date()),qi=k.object({id:k.string(),runKey:k.string(),organizationId:k.string(),executionType:k.nativeEnum(Mo).optional().default("WEB"),createdAt:Ye,createdBy:k.string(),flake:k.boolean().nullish(),scheduledAt:Ye.or(k.null()),startedAt:Ye.or(k.null()),updatedAt:Ye.nullish(),finishedAt:Ye.or(k.null()),resolvedBaseUrl:k.string().nullish(),environmentName:k.string().nullish(),gitBranchName:k.string().nullish(),githubRepository:k.string().nullish(),gitlabProjectPath:k.string().nullish(),labels:k.array(k.string()).optional(),gitOriginUrl:k.string().nullish(),gitCommitSha:k.string().nullish(),gitCommitShaShort:k.string().nullish(),gitCommitAuthorName:k.string().nullish(),cliVersion:k.string().nullish(),section:k.nativeEnum(Rs).nullish(),status:k.nativeEnum(ve),trigger:k.nativeEnum(Jt),attempts:k.number(),runAttempts:k.array(k.object({id:k.string(),status:k.nativeEnum(ve),startedAt:Ye.or(k.null()),finishedAt:Ye.or(k.null())})).optional(),videos:k.array(k.string()).optional(),failureReason:k.nativeEnum(we).nullish(),failureDetails:gs.nullish(),failureRecoveryDetails:k.record(k.string(),k.unknown()).nullish(),pipelineId:k.string().nullish(),resolvedInputs:k.record(k.string(),k.string()).nullish(),quarantined:k.boolean().nullish().default(!1),quarantinedReason:k.string().nullish(),localTestId:k.string().nullish(),testId:k.string().nullish(),testName:k.string().nullish(),description:k.string().nullish(),test:k.object({name:k.string(),id:k.string()}).nullish().default(null),suiteId:k.string().nullish()}).openapi({ref:"RunMetadata"}),BM={id:!0,status:!0,testName:!0,localTestId:!0,testId:!0,test:{select:{name:!0,id:!0}},finishedAt:!0,failureReason:!0,failureDetails:!0},Cs=qi.pick({...BM,test:!0}),gf=qi.omit({failureReason:!0,failureDetails:!0,test:!0}),qu=qi.extend({stepsSnapshot:k.array(k.record(k.unknown())).nullish(),resolvedInputs:k.record(k.string(),k.string()).nullish(),test:k.object({name:k.string(),id:k.string(),description:k.string().nullish(),baseUrl:k.string().nullish(),advanced:$i.nullish()}).nullish()}).merge(ju);var zM=Ki.object({id:Ki.string().uuid(),startedAt:Ye.or(Ki.null()),finishedAt:Ye.or(Ki.null()),status:Ki.nativeEnum(ve)}).merge(Wi),_q=zM.array();import{z as Xe}from"zod";var HM=Xe.object({id:Xe.string(),status:Xe.nativeEnum(ve),trigger:Xe.nativeEnum(Jt),createdAt:Ye,startedAt:Ye.nullish(),finishedAt:Ye.nullish(),gitCommitSha:Xe.string().nullish(),gitCommitShaShort:Xe.string().nullish(),gitCommitTimestamp:Ye.nullish(),gitBranchName:Xe.string().nullish(),gitOriginUrl:Xe.string().nullish(),gitCommitMessage:Xe.string().nullish(),gitCommitAuthorName:Xe.string().nullish(),githubRepository:Xe.string().nullish(),gitlabProjectPath:Xe.string().nullish(),pipelineId:Xe.string().nullish(),cliVersion:Xe.string().nullish(),labels:Xe.string().array().optional(),suite:Xe.object({id:Xe.string(),name:Xe.string()}).nullish(),runs:Xe.object({status:Xe.nativeEnum(ve)}).array()}).openapi({ref:"RunGroup"}),hf=HM.pick({id:!0,createdAt:!0,startedAt:!0,finishedAt:!0,status:!0,trigger:!0,suite:!0}).extend({runs:Cs.array()});import{z as lt}from"zod";var GM=lt.object({type:lt.literal("TARGETING"),name:lt.string().optional().describe("Target name to disambiguate for steps with multiple targets"),elementLocationDecisions:Qh.array(),pageState:lt.string().optional(),targetSource:lt.nativeEnum(qr).optional(),targetUpdateTime:lt.string().optional()}),VM=lt.object({type:lt.literal("AI_LOCATION"),matched:lt.boolean(),pageState:lt.string().optional(),ragUsed:lt.boolean().optional(),thoughts:lt.string().optional()}),jM=lt.object({type:lt.literal("ASSERTION"),relevantElementsSerialized:lt.string().array().optional(),pageState:lt.string().optional(),ragUsed:lt.boolean().optional()}),WM=lt.discriminatedUnion("type",[GM,VM,jM]);import{z as We}from"zod";var $M=We.object({id:We.string(),name:We.string()}),Vq=$M.merge(We.object({createdAt:Ye,createdBy:We.string(),schedule:_o,notification:Io,environment:We.object({name:We.string()}).nullish(),beforeTests:We.object({id:We.string()}).array().nullish(),afterTests:We.object({id:We.string()}).array().nullish()})),ff=We.object({id:We.string().uuid(),orgId:We.string(),createdAt:Ye,startedAt:Ye.or(We.null()),finishedAt:Ye.or(We.null()),status:We.nativeEnum(ve),trigger:We.nativeEnum(Jt),suite:We.object({id:We.string(),name:We.string()}).nullish(),runs:qi.array()}),jq=ff.pick({id:!0,createdAt:!0,startedAt:!0,finishedAt:!0,status:!0,trigger:!0,suite:!0}),Sf=ff.extend({runs:Cs.array()});import{z as Zt}from"zod";import{cloneDeep as qq}from"lodash-es";import{z as ye}from"zod";var Qq=ye.object({thoughts:ye.string(),subGoals:ye.object({instruction:ye.string()}).array()}),e2=ye.object({thoughts:ye.string(),newPlanMarkdown:ye.string()}),t2=ye.object({thoughts:ye.string(),correct:ye.boolean(),failedActionIndex:ye.number().optional()}),qM=ye.object({type:ye.literal("PLANNING"),beforePlan:ye.string(),goalDecision:ye.string(),thoughts:ye.string()}),KM=ye.object({type:ye.literal("RUNNING"),stepDisplayName:ye.string(),status:ye.nativeEnum(Ge),results:st.array()}),YM=ye.object({type:ye.literal("REVISING"),beforePlan:ye.string(),afterPlan:ye.string(),errString:ye.string(),diffs:ye.string(),thoughts:ye.string()}),XM=ye.object({type:ye.literal("SYSTEM"),message:ye.string()}),JM=ye.discriminatedUnion("type",[qM,KM,YM,XM]),yf=JM.array();var a2=Zt.object({id:Zt.string(),scheduledAt:Zt.coerce.date().nullable(),startedAt:Zt.coerce.date().nullable(),finishedAt:Zt.coerce.date().nullable(),status:Zt.nativeEnum(ve),history:yf.nullable(),testPlan:Zt.object({id:Zt.string(),name:Zt.string()}).nullable(),test:Zt.object({id:Zt.string(),name:Zt.string()}).nullable()});import{z as Mt}from"zod";var Ku=Mt.object({content:Mt.string(),ids:Mt.string().array(),tokenLength:Mt.number()}),ZM=Mt.object({chunks:Ku.array()}),A2=Mt.object({ids:Mt.string().array(),score:Mt.number(),tokenLength:Mt.number()}),w2=ZM.extend({description:Mt.string().describe("Input to pass to RAG engine"),tokenLimit:Mt.number()}),bf=Mt.object({ids:Mt.number().array()}),Ef=Mt.object({indices:Mt.number().array()});var yt=I.object({disableCache:I.boolean().optional(),useMemory:I.boolean().optional(),loggerTags:I.record(I.string(),I.string()).optional(),langfuseSessionId:I.string().optional(),agentConfigVersion:I.string().optional()}),O2=yt.extend({chunks:Ku.array(),description:I.string().describe("Input to pass to AI"),type:I.union([I.literal("locator"),I.literal("assertion"),I.literal("ai-action")]),softTokenLimit:I.number(),hardTokenLimit:I.number(),callId:I.string().optional()}),QM=I.object({screenshotBase64AfterCommand:I.string(),urlAfterCommand:I.string(),serializedCommand:I.string(),elementInteracted:I.string().optional(),thoughts:I.string().optional()}),Tf=I.object({goal:I.string(),browserState:I.string(),screenshot:I.string(),source:Zh.optional().catch(void 0),memory:I.discriminatedUnion("type",[rs,I.object({type:I.literal("RESOLVED_TRACES"),traces:I.unknown().array()})]).optional()}),vf=I.object({target:I.string().or(I.number()),browserState:I.string().optional(),screenshot:I.string().optional(),boundingBox:I.object({x:I.number(),y:I.number(),height:I.number(),width:I.number()}).optional()}),Af=I.object({goal:I.string(),browserState:I.string(),screenshot:I.string().optional(),returnSchema:I.string().optional()}),e_=I.literal("NEGATED_CHECK"),wf=I.object({goal:I.string(),browserState:I.string(),screenshot:I.string(),url:I.string(),contextChoice:mu.optional(),memory:I.discriminatedUnion("type",[lu,I.object({type:I.literal("RESOLVED_TRACES"),traces:I.unknown().array()})]).optional(),source:e_.optional()}),Rf=I.object({command:Eo}),Cf=I.object({message:I.string()}),Yu=I.object({goal:I.string(),browserState:I.string(),startingScreenshot:I.string().optional(),screenshot:I.string(),url:I.string(),history:QM.array(),actionHint:I.string().optional(),lastError:I.string().optional()}),xf=I.object({results:Ts.array(),errorMessage:I.string(),errorStack:I.string().optional()}),Mf=I.object({results:Ts.array(),goal:I.string(),errorMessage:I.string()}),_f=I.object({failedResults:Ts.array(),nextStepsSerialized:I.string().array(),currentUrl:I.string(),currentPageState:I.string(),currentScreenshot:I.string(),customInstructions:I.string().optional(),testDescription:I.string().optional()}),L2=I.object({description:I.string(),type:I.union([I.literal("locator"),I.literal("assertion"),I.literal("ai-action")]),excerpt:I.string()}),If=I.object({type:I.string(),browserContext:I.string(),currentStep:I.string(),screenshot:I.string()});import{z as Yi}from"zod";var k2=Yi.object({goal:Yi.string()}),Pf=Yi.object({keywords:Yi.array(Yi.string())});import{z as Xu}from"zod";var xs=(o=>(o.LOCATOR="locator",o.ASSERTION="assertion",o.VISUAL_ASSERTION="visual-assertion",o.TEXT_EXTRACTION="text-extraction",o))(xs||{}),B2=Xu.nativeEnum(xs),t_=Xu.enum(["v1","v2"]),z2=t_.or(Xu.string().describe("for people with special configurations"));import{z as ke}from"zod";var Of=ke.object({attributesRequired:ke.array(ke.string()).optional(),textRequired:ke.boolean().optional(),boundsRequired:ke.boolean().optional()}),Lf=ke.object({id:ke.number(),thoughts:ke.string(),inWebview:ke.boolean().optional(),requirements:Of.optional(),additionalElements:ke.object({id:ke.number(),requirements:Of}).array().optional()}),Nf=ke.object({description:ke.string(),screenXml:ke.string(),screenshot:ke.string()}),Df=ke.object({assertion:ke.string(),screenXml:ke.string(),screenshot:ke.string()}),kf=ke.object({thoughts:ke.string(),result:ke.boolean(),relevantElements:ke.array(ke.number()).optional()});import{z as Bn}from"zod";var Uf=Bn.object({id:Bn.string().uuid(),skipped:Bn.boolean().optional(),envKey:Bn.string().optional().describe("key in the environment to save the result of this step to")}),Ju=Uf.merge(go).extend({type:Bn.literal("REQUEST")}),Zu=Uf.merge(os).extend({type:Bn.literal("JAVASCRIPT")}),Qu=Bn.discriminatedUnion("type",[Zu,Ju]);import{z as Qt}from"zod";var Ff=Qt.object({id:Qt.string(),name:Ro,description:Qt.string().optional().nullish(),baseUrl:bs.nullish(),schemaVersion:Qt.string(),advanced:Qt.unknown().optional(),retries:Qt.number(),envs:Qt.array(ws).nullish(),parameters:As.nullish()}),r_=Qt.object({createdAt:Qt.coerce.date(),updatedAt:Qt.coerce.date(),schedule:_o.nullish(),notification:Io.nullish(),createdBy:Qt.string(),organizationId:Qt.string()}),n_=Ff.merge(r_),uK=n_.extend({steps:Qu.array()}),dK=Ff.extend({steps:Qu.array()});import{z as Lt}from"zod";var Bf=Lt.object({startedAt:Lt.coerce.date(),finishedAt:Lt.coerce.date(),status:Lt.nativeEnum(Ge),message:Lt.string().optional(),data:Lt.unknown().optional()}),o_=Bf.merge(Zu).extend({type:Lt.literal("JAVASCRIPT")}),i_=Bf.merge(Ju).extend({type:Lt.literal("REQUEST")}),a_=Lt.discriminatedUnion("type",[o_,i_]),zf=Lt.object({startedAt:Lt.coerce.date(),finishedAt:Lt.coerce.date().nullish(),status:Lt.nativeEnum(ve),results:a_.array(),failureReason:Lt.string().nullish(),failureDetails:gs.nullish()});import{z as Nt}from"zod";var s_=Nt.object({id:Nt.string(),organizationId:Nt.string(),createdAt:Nt.coerce.date(),updatedAt:Nt.coerce.date(),createdBy:Nt.string(),scheduledAt:Nt.coerce.date().nullish(),startedAt:Nt.coerce.date().nullish(),finishedAt:Nt.coerce.date().nullish(),status:Nt.nativeEnum(ve),trigger:Nt.nativeEnum(Jt),results:zf.array().nullish(),apiTestName:Nt.string().nullish(),apiTestPath:Nt.string().nullish(),apiTestId:Nt.string().nullish()}),TK=s_.pick({status:!0,startedAt:!0,finishedAt:!0});var Xi=(o=>(o.TestRun="test-run",o.MobileTestRun="mobile-test-run",o.CreditsUsed="credits-used",o.CreditsUsedV2="credits-used-v2",o))(Xi||{}),Hf=3;function l_(r){return r==="MODULE"||r==="CONDITIONAL"||r==="SECTION"||r==="RESOLVED_MODULE"}function ed(r){if(!l_(r))switch(r){case"PRESET_ACTION":return 0;case"AI_ACTION":return 3;case"AI_ACTION_DYNAMIC":return 5;default:(t=>{throw"If Typescript complains about the line below, you missed a case or break in the switch above"})(r)}}function td(r){switch(r.type){case"AI_EXTRACT":case"AI_ASSERTION":return Hf;case"CAPTCHA":return 3;case"CLICK":case"TYPE":case"SELECT_OPTION":case"HOVER":case"ELEMENT_CHECK":case"FOCUS":case"BLUR":case"SCROLL_DOWN":case"SCROLL_LEFT":case"SCROLL_RIGHT":case"SCROLL_UP":case"MOUSE_DRAG":return r.useSelector||!r.target||r.target.type!=="description"?0:1;case"DRAG":return r.useSelector?0:1;case"VISUAL_DIFF":case"TAB":case"JAVASCRIPT":case"NAVIGATE":case"WAIT":case"SUCCESS":case"AUTH_LOAD":case"AUTH_SAVE":case"COOKIE":case"DIALOG":case"FILE_UPLOAD":case"GO_BACK":case"GO_FORWARD":case"LOCAL_STORAGE":case"NEW_TAB":case"PAGE_CHECK":case"PRESS":case"KEY_DOWN":case"KEY_UP":case"COPY":case"PASTE":case"REFRESH":case"REQUEST":case"GRAPHQL_REQUEST":case"WAIT_FOR_URL":case"REGISTER_REQUEST_LISTENER":case"AWAIT_LISTENER":case"RECORD_REQUESTS":case"GET_RECORDED_REQUESTS":case"SET_HEADER":case"MOCK_ROUTE":case"REMOVE_ROUTE_MOCK":case"OFFLINE_MODE":return 0;default:(t=>{throw"If Typescript complains about the line below, you missed a case or break in the switch above"})(r)}}var Ms=class{trackStepExecution(){}async flush(){}};import{parseString as c_,splitCookiesString as u_}from"set-cookie-parser";import{z as Te}from"zod";var rd=Te.object({name:Te.string(),value:Te.string(),url:Te.string().optional(),domain:Te.string().optional(),path:Te.string().optional(),expires:Te.number().default(Date.now()/1e3+60*60*24*365),httpOnly:Te.boolean().optional(),secure:Te.boolean().default(!0),sameSite:Te.union([Te.literal("Strict"),Te.literal("Lax"),Te.literal("None")]).default("None")});function _s(r,e){let t=[],n=u_(r);for(let o of n){let i=c_(o,{decodeValues:!1});if(!i.name)throw new Error("Name missing from cookie");if(!i.value)continue;let a;if(i.sameSite){let u=i.sameSite.trim().toLowerCase();if(u==="strict")a="Strict";else if(u==="lax")a="Lax";else if(u==="none")a="None";else throw new Error(`Invalid sameSite setting in cookie: ${u}`)}i.httpOnly===void 0&&(i.httpOnly=!1),!i.path&&i.domain&&(i.path="/"),!i.domain&&e&&(i.domain=e);let l=rd.parse({...i,expires:i.expires?i.expires.getTime()/1e3:void 0,sameSite:a});t.push(l);let c=[l.name,...Object.keys(l)].map(u=>u.toLowerCase()),s=o.match(/\b(\S+)=([^;]*)/g);if(s)for(let u of s){let[d,p]=u.split("=");if(!d||!p)throw new Error(`Invalid key-value pair in cookie: ${u}`);c.includes(d.toLowerCase())||t.push({...l,name:d,value:p})}}return t}var d_=Te.object({origin:Te.string(),localStorage:Te.array(Te.object({name:Te.string(),value:Te.string()}))}),p_=Te.object({entries:Te.record(Te.string(),Te.array(Te.tuple([Te.unknown(),Te.unknown()]))),version:Te.number().optional()}),Gf=Te.object({cookies:rd.array().optional(),origins:d_.array().optional(),idb:Te.record(Te.string(),p_).optional().describe("key is db name")});function Is(r,e){let t=[];return r.cloneSync()?.serializeSync()?.cookies.forEach(n=>{let o=rd.safeParse({name:n.key,...n});if(!o.success)return;let i=o.data;!i.domain&&!i.url&&(i.domain=e),t.push(i)}),t}import{v4 as Os}from"uuid";import Ue from"zod";import{v4 as jK}from"uuid";import{z as F}from"zod";import*as xe from"zod";var Vf=xe.object({requiredText:xe.string().optional(),requiredAttributes:xe.record(xe.string(),xe.string()).optional(),requiredBounds:xe.boolean().optional()}),m_=xe.object({xPath:xe.string(),requirements:Vf.optional()}),g_=xe.object({type:xe.literal("NATIVE"),bounds:xe.number().array(),resolvedDescription:xe.string(),xPath:xe.string(),elementOnlySerializedXml:xe.string(),requirements:Vf.optional(),requiredRelatedElements:m_.array().optional()}),h_=xe.object({type:xe.literal("WEBVIEW"),resolvedDescription:xe.string(),xPath:xe.string(),browserCache:Kr.optional()}),Ps=xe.discriminatedUnion("type",[g_,h_]);var rn=(g=>(g.AI_CHECK="AI_CHECK",g.TAP="TAP",g.TYPE="TYPE",g.PRESS="PRESS",g.PRESS_KEYBOARD="PRESS_KEYBOARD",g.OPEN_APP="OPEN_APP",g.OPEN_NOTIFICATION_DRAWER="OPEN_NOTIFICATION_DRAWER",g.SWIPE="SWIPE",g.JAVASCRIPT="JAVASCRIPT",g.REQUEST="REQUEST",g.WAIT="WAIT",g.ADD_FILE="ADD_FILE",g.ADB="ADB",g.STATE="STATE",g))(rn||{}),Ji=(c=>(c.BACK="BACK",c.HOME="HOME",c.APP_SWITCHER="APP_SWITCHER",c.POWER="POWER",c.SEARCH="SEARCH",c.VOLUME_UP="VOLUME_UP",c.VOLUME_DOWN="VOLUME_DOWN",c.VOLUME_MUTE="VOLUME_MUTE",c))(Ji||{}),nd=(n=>(n.CLOSE_KEYBOARD="CLOSE_KEYBOARD",n.ENTER="ENTER",n.BACKSPACE="BACKSPACE",n))(nd||{}),jf=F.object({type:F.literal("description"),description:F.string()}),f_=F.object({type:F.literal("coordinates"),xPercent:F.number(),yPercent:F.number()}),Wf=F.discriminatedUnion("type",[jf,f_]),S_=F.object({updatedAt:F.coerce.date().optional()}),Dt=F.object({id:F.string().uuid(),disableCache:F.boolean().optional()}),y_=Dt.extend({type:F.literal("STATE")}),$f=S_.extend({target:Ps}),b_=Dt.extend({type:F.literal("AI_CHECK"),assertion:F.string(),timeoutSecs:F.number().optional()}),od=Dt.extend({type:F.literal("TAP"),target:Wf,cache:$f.optional(),longPress:F.boolean().optional(),longPressDurationMs:F.number().optional(),doubleTap:F.boolean().optional(),doubleTapDelayMs:F.number().optional(),relativePosition:F.object({x:F.number(),y:F.number()}).optional()}),id=Dt.extend({type:F.literal("TYPE"),target:Wf.optional(),cache:$f.optional(),keyPressDelayMs:F.number().optional(),text:F.string(),clearContent:F.boolean().optional()}),E_=Dt.extend({type:F.literal("PRESS"),key:F.nativeEnum(Ji),longPress:F.boolean().optional()}),T_=Dt.extend({type:F.literal("PRESS_KEYBOARD"),key:F.nativeEnum(nd)}),v_=Dt.extend({type:F.literal("OPEN_APP"),packageName:F.string(),activityName:F.string().optional(),intentExtras:F.string().optional()}),A_=Dt.extend({type:F.literal("OPEN_NOTIFICATION_DRAWER")}),w_=F.discriminatedUnion("type",[F.object({type:F.literal("SCREEN")}),F.object({type:F.literal("OPEN_APP")}),F.object({type:F.literal("CUSTOM"),target:jf})]),R_=Dt.extend({type:F.literal("SWIPE"),direction:F.enum(["up","down","left","right"]),scrollableElement:w_,viewportPercent:F.number().optional(),durationMs:F.number().optional()}),C_=Dt.extend({type:F.literal("JAVASCRIPT"),code:F.string(),timeout:F.number().int().max(60).optional().describe("Max seconds for the code to complete")}),x_=Dt.extend({type:F.literal("REQUEST")}).merge(go),M_=Dt.extend({type:F.literal("WAIT"),timeoutSecs:F.number()}),__=Dt.extend({type:F.literal("ADB"),command:F.string(),jsonArgs:F.string().optional()}),I_=Dt.extend({type:F.literal("ADD_FILE"),file:F.string(),storageLocation:F.string()}),qf=F.discriminatedUnion("type",[b_,od,id,E_,v_,A_,T_,R_,C_,x_,M_,I_,__,y_]);var ad=r=>{switch(r.type){case"description":return r.description;case"coordinates":return`${r.xPercent}%, ${r.yPercent}%`}};var P_=Ue.object({type:Ue.literal("TAP"),description:Ue.string().describe("Description of the element to tap."),longPress:Ue.boolean().describe("Whether to hold the tap down before releasing. Useful for triggering context menus."),doubleTap:Ue.boolean().describe("Whether to tap twice in quick succession."),relativePosition:Ue.null().or(Ue.object({x:Ue.number(),y:Ue.number()})).describe("Specific position to tap within the bounding box of the element, specified in pixels. E.g. 0,0 is the top left corner.")}).describe(`
|
|
10
|
+
Tap on an element on the screen.
|
|
11
|
+
`),O_=Ue.object({type:Ue.literal("PRESS"),key:Ue.nativeEnum(Ji)}).describe(`
|
|
12
|
+
Press a button on the device. Some buttons are physical (volume) while others are virtual (Back/Home/App Switcher).
|
|
13
|
+
`),L_=Ue.object({type:Ue.literal("AI_CHECK"),assertion:Ue.string().describe("A natural language assertion to validate. On each attempt, Momentic's AI agents will evaluate the assertion by analyzing the current emulator XML and screenshot. Thus, the assertion must be verifiable based on a single point in time. The assertion will be automatically retried until it is true or the timeout is reached."),timeoutSecs:Ue.number().describe("Maximum number of seconds to wait for the assertion to be true.")}).describe(`
|
|
14
|
+
Use AI to verify a statement about the current state of the emulator or wait until a statement is true.
|
|
15
|
+
`),N_=Ue.object({type:Ue.literal("TYPE"),text:Ue.string().describe("Exact type to text, which will be passed to appium's driver.keys() method."),keyPressDelayMs:Ue.number().or(Ue.null()).describe("Milliseconds to wait between each key press. Useful for triggering auto-complete and other event listeners."),clearContent:Ue.boolean().or(Ue.null()).describe("Clear the content of the input before typing. Do not set to true if the input is already empty.")}),sd=Ue.discriminatedUnion("type",[P_,O_,L_,N_]),Kf=r=>{let e=sd.parse(r);switch(e.type){case"TAP":return{id:Os(),type:"TAP",target:{type:"description",description:e.description},longPress:e.longPress??void 0,doubleTap:e.doubleTap??void 0,relativePosition:e.relativePosition??void 0};case"PRESS":return{id:Os(),...e};case"AI_CHECK":return{id:Os(),...e};case"TYPE":return{id:Os(),type:"TYPE",text:e.text,keyPressDelayMs:e.keyPressDelayMs??void 0,clearContent:e.clearContent??void 0};default:{let t=e;throw new Error("Unreachable")}}};import D_ from"zod";var Yf={type:!0,cache:!0},nn=D_.discriminatedUnion("type",[od.pick(Yf),id.pick(Yf)]),k_=Object.values(rn).filter(r=>nn.options.some(e=>e.shape.type.safeParse(r).success));function Ls(r){return k_.includes(r.type)}var Xf=Di(nn),Jf=ki(nn),oY=cs(nn);import{cloneDeep as Zi}from"lodash-es";import Zf from"truncate-json";var U_="\u2022\u2022\u2022\u2022\u2022\u2022\u2022\u2022\u2022\u2022\u2022\u2022\u2022\u2022\u2022",F_=[kn,xo],Qf=[kn,xo],Po=class r{env={};varsFromMomenticEnvironment={};constructor(e){this.reset(e)}static dummyContext(e=void 0,t=void 0,n={}){return new r({testName:e,envName:t,variablesFromEnvironment:n})}static fromSnapshot({snapshot:e,environmentVariables:t}){let n=e.env[kn],o=e.env[xo],i={};for(let[l,c]of Object.entries(e.env))Qf.includes(l)||(t??{})[l]===void 0&&(i[l]=c);return new r({dynamicVariables:i,envName:n,testName:o,variablesFromEnvironment:t??{}})}setEnvVariables(e){let t=Zi(e);this.env=Object.assign(this.env,t)}setInputs(e){e&&this.setEnvVariables(e)}setMomenticSystemVariable(e,t){this.varsFromMomenticEnvironment[e]=t}getVariable(e){return this.env[e]}setVariable(e,t){F_.includes(e)||(this.env[e]=t)}getEnvName(){return this.env[kn]}toObjectCopy(){let e={env:Object.assign({},this.env,this.varsFromMomenticEnvironment)};return Zi(e)}toEditorDisplayCopy(){return this.toObjectCopy()}toRedactedDisplayCopy(){let e=this.toObjectCopy();e.env=Object.fromEntries(Object.entries(e.env).map(([n,o])=>Qf.includes(n)||this.varsFromMomenticEnvironment[n]===void 0?[n,o]:[n,U_]));for(let[n,o]of Object.entries(e.env)){if(!o){e.env[n]=o;continue}let{jsonString:i}=Zf(JSON.stringify(o),1e3);try{e.env[n]=JSON.parse(i)}catch{e.env[n]=void 0}}let{jsonString:t}=Zf(JSON.stringify(e.env),5e3);try{e.env=JSON.parse(t)}catch{e.env={}}return e}reset(e){this.env={},this.varsFromMomenticEnvironment={},this.setEnvVariables(e.dynamicVariables??{}),this.varsFromMomenticEnvironment=Zi(e.variablesFromEnvironment),e.envName&&this.setMomenticSystemVariable(kn,e.envName),e.testName&&this.setMomenticSystemVariable(xo,e.testName)}getDynamicVariablesCopy(){return Zi(this.env)}getVariablesFromEnvironmentCopy(){return Zi(this.varsFromMomenticEnvironment)}};var Qi=(t=>(t.USWest1="us-west1",t.EUNorth1="eu-north1",t))(Qi||{});import Je from"zod";import{z as pr}from"zod";import{z as Fe}from"zod";var dr=Fe.object({id:Fe.string(),name:Ro,baseUrl:bs,description:Fe.string().optional().nullish(),schemaVersion:Fe.string(),advanced:$i,retries:Fe.number(),envs:Fe.array(ws).nullish(),parameters:As.nullish(),disabled:Fe.boolean().optional(),labels:Fe.array(Fe.string()).optional().catch([])}),hY=Fe.enum(["INHERIT","ENABLED","DISABLED"]);var B_=$i.extend({failureRecovery:Fe.boolean().or(Fe.string()).optional().transform(r=>typeof r=="string"?r:r===void 0?"INHERIT":r?"ENABLED":"DISABLED"),useMemory:Fe.boolean().or(Fe.string()).optional().transform(r=>typeof r=="string"?r:r===void 0?"INHERIT":r?"ENABLED":"DISABLED")});var fY=dr.pick({name:!0,description:!0,baseUrl:!0,retries:!0,disabled:!0,parameters:!0}).extend({advanced:B_}),SY=dr.pick({name:!0,description:!0,baseUrl:!0,retries:!0,disabled:!0,advanced:!0,parameters:!0}),z_=Fe.object({labels:Fe.array(Fe.string()).optional(),outputs:mf.nullish()}),Oo=dr.merge(z_),H_=Fe.object({createdAt:Fe.coerce.date(),updatedAt:Fe.coerce.date(),updatedBy:Fe.string().nullable(),schedule:_o,notification:Io,createdBy:Fe.string(),organizationId:Fe.string(),folderId:Fe.string().nullable().optional()}),G_=dr.merge(H_),yY=G_.merge(Pn),Ns=dr.merge(Pn),bY=dr.merge(On);var V_="test",j_="module",W_="mobile-test",$_="mobile-module";var Me=(o=>(o.TEST=`momentic/${V_}`,o.MODULE=`momentic/${j_}`,o.MOBILE_TEST=`momentic/${W_}`,o.MOBILE_MODULE=`momentic/${$_}`,o))(Me||{}),CY=dr.merge(On),eS=Kt.extend({steps:pr.array(pr.record(pr.string(),pr.unknown())),schemaVersion:pr.string()}),xY=eS.extend({fileType:pr.literal(Me.MODULE)}),MY=pr.object({test:pr.string().describe("YAML for the test, including metadata and steps"),modules:pr.record(pr.string(),pr.string()).describe("Map of module name to YAML for the module")});var ld=Je.object({parameterNames:Je.string().array(),defaultParameters:Je.record(Je.string(),Je.string()).optional(),parameterEnums:Je.record(Je.string(),Je.string().array()).optional()}),q_=Je.object({moduleId:Je.string().uuid(),name:Je.string(),description:Je.string().nullish(),parameters:ld.optional(),enabled:Je.boolean().nullish(),schemaVersion:Je.string()}),ea=q_.omit({name:!0}),Ds=ea.extend({steps:Je.array(Je.record(Je.string(),Je.unknown()))}),K_=Je.object({fileType:Je.literal(Me.MOBILE_MODULE)}).merge(Ds);import bt from"zod";var kt=(n=>(n.PRESET="MOBILE_PRESET_STEP",n.MODULE="MOBILE_MODULE_STEP",n.AI_ACTION="MOBILE_AI_ACTION_STEP",n))(kt||{}),ta=bt.object({id:bt.string().uuid(),envKey:bt.string().optional(),skipped:bt.boolean().optional()}),ra=ta.extend({type:bt.literal("MOBILE_PRESET_STEP"),command:qf,keyPressDelayMs:bt.number().optional()}),Lo=bt.object({moduleId:bt.string(),inputs:bt.record(bt.string(),bt.string()).optional(),parameters:ld.optional()}),na=ta.merge(Lo.extend({type:bt.literal("MOBILE_MODULE_STEP")})),UY=Lo.extend({steps:bt.lazy(()=>mr.array())}),oa=ta.extend({type:bt.literal("MOBILE_AI_ACTION_STEP"),text:bt.string()}),mr=bt.discriminatedUnion("type",[ra,na,oa]);import Ze from"zod";import ks from"zod";var zr=(e=>(e.MODULE="RESOLVED_MOBILE_MODULE",e))(zr||{}),Y_=Lo.extend({steps:ks.lazy(()=>ia.array()),name:ks.string().describe("name of the module")}),X_=ta.merge(Y_).extend({type:ks.literal("RESOLVED_MOBILE_MODULE")}),ia=ks.discriminatedUnion("type",[X_,ra,oa]);function tS(r){return Object.values(zr).includes(r)||Object.values(kt).includes(r)}var J_=Ze.object({disableMomenticAccessibilityTree:Ze.boolean().optional(),autoGrantPermissions:Ze.boolean().optional()}),cd=J_.extend({region:Ze.nativeEnum(Qi).optional()}),aa=Ze.object({retries:Ze.number().optional().describe("number of retries to run"),defaultChannel:Ze.string().optional().describe("default channel to use"),defaultTag:Ze.string().optional().describe("default tag to use, if not set uses latest"),defaultEnv:Ze.string().optional(),emulator:cd.optional()}),vr=Ze.object({id:Ze.string().uuid(),description:Ze.string(),schemaVersion:Ze.string(),settings:aa.optional()}),Z_=vr.merge(Ze.object({steps:Ze.array(mr)})),Us=Ze.object({fileType:Ze.literal(Me.MOBILE_TEST)}).merge(Z_),ZY=Ze.object({name:Ze.string(),steps:Ze.array(mr).optional(),settings:aa.optional()}),Q_=vr.extend({steps:ia.array()});import de from"zod";var on=de.object({startTime:de.number(),endTime:de.number().optional(),durationMs:de.number().optional(),error:de.string().optional(),result:de.unknown().optional(),attributes:de.record(de.string(),de.unknown())});var eI=on.extend({type:de.literal("SECTION"),name:de.string(),subSpans:de.lazy(()=>ud.array())}),tI=on.extend({type:de.literal("AI_LOCATOR_CALL"),result:de.object({id:de.number(),thoughts:de.string()}).optional()}),rI=on.extend({type:de.literal("AI_ASSERTION_CALL"),result:de.object({thoughts:de.string(),result:de.boolean()}).optional()}),nI=on.extend({type:de.literal("TARGET_RESOLUTION"),result:de.object({serializedElement:de.string()}).optional()}),oI=on.extend({type:de.literal("WAIT_FOR_STABILITY"),reason:de.string()}),iI=on.extend({type:de.literal("EMULATOR_INTERACTION"),name:de.string(),withinWebview:de.boolean().optional()}),aI=on.extend({type:de.literal("EMULATOR_READ_STATE"),name:de.string()}),sI=on.extend({type:de.literal("GENERIC"),name:de.string()}),ud=de.discriminatedUnion("type",[eI,tI,rI,nI,oI,iI,aI,sI]);import er from"zod";var dd=er.object({message:er.string().optional(),startTime:er.number(),endTime:er.number(),status:er.nativeEnum(Ge),trace:er.unknown(),beforeSnapshot:er.string().optional(),afterSnapshot:er.string().optional(),data:er.unknown().optional().describe("output data from the step")}),lI=dd.merge(ra),cI=dd.merge(na).extend({steps:er.lazy(()=>tr.array())}),uI=dd.merge(oa).extend({steps:er.lazy(()=>tr.array())}),tr=er.discriminatedUnion("type",[lI,cI,uI]);var I5=new Set(Object.values(nt));var dI={AI_ACTION:"AI action",AI_ACTION_DYNAMIC:"AI action",RESOLVED_MODULE:"Module",AI_ASSERTION:"AI check",AI_EXTRACT:"AI extract",CLICK:"Click",TYPE:"Type",JAVASCRIPT:"JavaScript",SELECT_OPTION:"Select",PRESS:"Press",KEY_DOWN:"Key down",KEY_UP:"Key up",NAVIGATE:"Navigate",SCROLL_UP:"Scroll up",SCROLL_DOWN:"Scroll down",SCROLL_LEFT:"Scroll left",SCROLL_RIGHT:"Scroll right",HOVER:"Hover",BLUR:"Blur",FILE_UPLOAD:"File upload",FOCUS:"Focus",GO_BACK:"Go back",GO_FORWARD:"Go forward",WAIT:"Wait",REFRESH:"Refresh",TAB:"Switch tab",NEW_TAB:"New tab",COOKIE:"Cookie",LOCAL_STORAGE:"localStorage",REQUEST:"API request",GRAPHQL_REQUEST:"GraphQL request",CAPTCHA:"CAPTCHA",DRAG:"Drag & drop",VISUAL_DIFF:"Visual diff",DIALOG:"Dialog",MOUSE_DRAG:"Mouse drag",AUTH_LOAD:"Load auth state",AUTH_SAVE:"Save auth state",ELEMENT_CHECK:"Element check",PAGE_CHECK:"Page check",WAIT_FOR_URL:"Wait for URL",COPY:"Copy",PASTE:"Paste",REGISTER_REQUEST_LISTENER:"Register request listener",AWAIT_LISTENER:"Await listener",RECORD_REQUESTS:"Record requests",GET_RECORDED_REQUESTS:"Get recorded requests",SET_HEADER:"Set header",MOCK_ROUTE:"Mock route",REMOVE_ROUTE_MOCK:"Remove route mock",OFFLINE_MODE:"Offline mode",SUCCESS:"Done"},P5={AI_ACTION:["ai","action","agent"],AI_ACTION_DYNAMIC:["ai","action","dynamic","agent"],RESOLVED_MODULE:[],AI_ASSERTION:["ai","check","assert","make sure","ensure"],AI_EXTRACT:["ai","extract","data"],CLICK:["click","press"],TYPE:["type","input","write","press"],JAVASCRIPT:["js","javascript","code","execute"],SELECT_OPTION:["select","option","choose"],PRESS:["keyboard","type","key"],KEY_DOWN:["keyboard","type","key","down","press"],KEY_UP:["keyboard","type","key","up","press"],NAVIGATE:["go to","visit"],SCROLL_UP:[],SCROLL_DOWN:[],SCROLL_LEFT:[],SCROLL_RIGHT:[],HOVER:["scroll into view","go to"],BLUR:[],FILE_UPLOAD:[],FOCUS:[],GO_BACK:[],GO_FORWARD:[],WAIT:[],REFRESH:[],TAB:[],NEW_TAB:[],COOKIE:[],LOCAL_STORAGE:[],REQUEST:[],GRAPHQL_REQUEST:[],CAPTCHA:[],DRAG:[],VISUAL_DIFF:[],DIALOG:[],MOUSE_DRAG:[],AUTH_LOAD:[],AUTH_SAVE:[],ELEMENT_CHECK:[],PAGE_CHECK:[],WAIT_FOR_URL:[],COPY:[],PASTE:[],REGISTER_REQUEST_LISTENER:[],AWAIT_LISTENER:[],RECORD_REQUESTS:[],GET_RECORDED_REQUESTS:[],SET_HEADER:[],MOCK_ROUTE:[],REMOVE_ROUTE_MOCK:[],OFFLINE_MODE:[],SUCCESS:[]},O5={AI_ACTION:"Ask AI achieve a specific goal. Saves the steps for reuse. Please use Dynamic AI action instead.",AI_ACTION_DYNAMIC:"Ask AI achieve a specific goal. Fully dynamic and does not save the steps for reuse. Our most capable AI agent.",RESOLVED_MODULE:"A list of steps that can be reused in multiple tests.",AI_ASSERTION:"Ask AI to verify whether something is true on the page.",CLICK:"Click on an element on the page.",DIALOG:"Specify how native browser dialogs should be handled.",AI_EXTRACT:"Ask AI to extract data from the page.",HOVER:"Hover over an element on the page.",FILE_UPLOAD:"Automatically upload a file when the native file upload dialog is activated.",FOCUS:"Focus an element on the page.",BLUR:"Remove focus from an element on the page.",SELECT_OPTION:"Select an option from an HTML Select <select> element.",TYPE:"Type the specified text into an element.",PRESS:"Press the specified keys using the keyboard. (e.g. Control+A)",KEY_DOWN:"Hold down the specified keys on the keyboard. (e.g. Control+A)",KEY_UP:"Release the specified keys on the keyboard. (e.g. Control+A)",NAVIGATE:"Navigate to the specified URL.",SCROLL_UP:"Scroll up by a specified height.",SCROLL_DOWN:"Scroll down by a specified height.",SCROLL_LEFT:"Scroll left by a specified width.",SCROLL_RIGHT:"Scroll right by a specified width.",GO_BACK:"Go back in browser history.",GO_FORWARD:"Go forward in browser history.",WAIT:"Wait for the specified number of seconds.",REFRESH:"Refresh the page. This will not clear cookies or session data.",TAB:"Switch to different tab in the browser.",NEW_TAB:"Create and switch to a new tab in the browser.",COOKIE:"Set a cookie that will persist throughout the browser session.",LOCAL_STORAGE:"Set a localStorage value that will persist throughout the browser session",CAPTCHA:"Solve CAPTCHAs on the page. This feature is only available on Momentic Cloud and may take up to 60 seconds. Disabling CAPTCHAs in non-production environments is strongly advised.",REQUEST:"Make an API request to a URL.",GRAPHQL_REQUEST:"Make a GraphQL request to a URL.",JAVASCRIPT:"Run JavaScript code in the browser or a Node.js environment.",DRAG:"Click and drag an element to another location.",VISUAL_DIFF:"Compare a screenshot of the page or a specific element to a baseline image.",MOUSE_DRAG:"Click and drag the mouse by a specified distance.",AUTH_LOAD:"Load or clear session state using a JavaScript object including cookies, localStorage, and IndexDB entries.",AUTH_SAVE:"Save authentication state (cookies, localStorage) into a JavaScript object.",ELEMENT_CHECK:"Assert on an element's state using pre-built conditions, including content, visibility, attribute value checks.",PAGE_CHECK:"Assert on the active page's contents using pre-built conditions.",WAIT_FOR_URL:"Wait for the active page's URL to match a target value or pattern.",COPY:"Copy the specified value to the browser clipboard.",PASTE:"Paste the browser clipboard contents.",REGISTER_REQUEST_LISTENER:"Register a listener for network requests.",AWAIT_LISTENER:"Wait for a listener to fire, and return the response data.",RECORD_REQUESTS:"Record network requests that match a given pattern.",GET_RECORDED_REQUESTS:"Get recorded requests that matched the pattern.",SET_HEADER:"Set a header.",MOCK_ROUTE:"Mock network requests to a specific URL.",REMOVE_ROUTE_MOCK:"Remove a previously set route mock.",OFFLINE_MODE:"Configure offline mode.",SUCCESS:"Indicate the entire AI action has succeeded, optionally based on a condition."},L5={AI_CHECK:"AI check",RESOLVED_MOBILE_MODULE:"Module",MOBILE_AI_ACTION_STEP:"AI action",TAP:"Tap",TYPE:"Type",PRESS:"Press button",PRESS_KEYBOARD:"Press keyboard",SWIPE:"Swipe",OPEN_APP:"Open app",OPEN_NOTIFICATION_DRAWER:"Open notification drawer",JAVASCRIPT:"JavaScript",REQUEST:"API request",WAIT:"Wait",ADD_FILE:"Add file",ADB:"ADB command",STATE:"Debug state"},N5={MOBILE_AI_ACTION_STEP:"Ask AI to accomplish a high-level goal by generating other steps.",AI_CHECK:"Ask AI to verify whether something is true on the screen.",RESOLVED_MOBILE_MODULE:"A list of steps that can be reused in multiple tests.",TAP:"Tap on an element on the screen.",TYPE:"Type the specified text into an element.",PRESS:"Press a physical button on the device.",PRESS_KEYBOARD:"Press a special key on the keyboard.",SWIPE:"Swipe on the screen.",OPEN_APP:"Open an app on the device.",OPEN_NOTIFICATION_DRAWER:"Open the notification drawer.",JAVASCRIPT:"Execute JavaScript code in a NodeJS context.",REQUEST:"Make an HTTP request to a URL.",WAIT:"Wait for a specified amount of time.",ADD_FILE:"Add a file to the device's disk.",ADB:"Execute an ADB command on the device.",STATE:"Get the debug state of the device."};import pI from"semver";import{z as mI}from"zod";var F5=mI.string().refine(r=>pI.valid(r),{message:"must be a valid semver string"});import{Faker as H5,en as G5}from"@faker-js/faker";import{z as L}from"zod";var j5=L.object({body:L.string(),to:L.string(),from:L.string()}),W5=L.object({from:L.string().optional(),to:L.string(),timeout:L.number().optional(),beforeDate:L.string().pipe(L.coerce.date()).or(L.date()).optional(),afterDate:L.string().pipe(L.coerce.date()).or(L.date()).optional()}),$5=L.object({to:L.string().email(),from:L.string(),subject:L.string(),body:L.string(),html:L.string().optional()}),q5=L.object({inbox:L.string().transform(r=>r.toLowerCase()),afterDate:L.string().pipe(L.coerce.date()).or(L.date()).optional(),timeout:L.number().optional(),trimWhitespace:L.boolean().optional()}),K5=L.object({inbox:L.string(),limit:L.number().optional(),afterDate:L.string().pipe(L.coerce.date()).or(L.date()).optional(),trimWhitespace:L.boolean().optional()});var Fs=(t=>(t.RAW="RAW",t.RESPONSE="RESPONSE",t))(Fs||{}),rS=L.object({body:L.string().nullish(),status:L.number().optional(),headers:L.array(L.tuple([L.string(),L.string()])).optional()}),gI=L.object({url:L.string(),options:L.object({method:L.string(),body:L.string().nullish(),headers:L.array(L.tuple([L.string(),L.string()])).optional()}).optional()}).optional(),hI=L.object({body:L.string().nullish(),options:L.object({status:L.number(),statusText:L.string().optional(),headers:L.array(L.tuple([L.string(),L.string()])).optional()}).optional()}).optional(),nS=L.object({result:L.unknown(),variableUpdates:L.record(L.string(),L.unknown()).optional(),persistentVariableUpdates:L.record(L.string(),L.unknown()).optional(),error:L.string().optional(),success:L.boolean()}),Y5=L.object({id:L.string().optional(),orgId:L.string(),momenticLambdaAuthHash:L.string(),code:L.string(),fragment:L.boolean(),state:L.object({env:L.record(L.string(),L.unknown()),request:gI,response:hI,additionalBindings:L.record(L.string(),L.unknown()).optional()}),timeoutMs:L.number().optional(),disallowVariableUpdates:L.boolean().optional(),responseSerialization:L.nativeEnum(Fs).optional()}),an=15e3;import*as Et from"zod";import{extendZodWithOpenApi as fI}from"zod-openapi";fI(Et);var SI=Et.object({url:Et.string(),lineNumber:Et.number(),columnNumber:Et.number()}).openapi({ref:"CodeLocation"}),Bs=Et.object({timestamp:Et.number(),text:Et.string(),type:Et.string(),tabIndex:Et.number(),args:Et.unknown().array().optional(),url:Et.string().optional(),location:SI.optional()}).openapi({ref:"ConsoleLog"}),oS=Bs.array(),yI=oS.array();import*as pd from"zod";import{extendZodWithOpenApi as FI}from"zod-openapi";import{z as x}from"zod";var bI=x.object({name:x.string(),version:x.string(),comment:x.string().optional()}),EI=x.object({name:x.string(),version:x.string(),comment:x.string().optional()}),TI=x.object({onContentLoad:x.number().optional(),onLoad:x.number().optional(),comment:x.string().optional()}),aS=x.object({startedDateTime:x.string(),id:x.string(),title:x.string().optional(),pageTimings:TI,comment:x.string().optional()}),vI=x.array(aS),AI=x.object({name:x.string(),value:x.string(),path:x.string().optional(),domain:x.string().optional(),expires:x.string().optional(),httpOnly:x.boolean().optional(),secure:x.boolean().optional(),comment:x.string().optional()}),sS=x.array(AI),wI=x.object({name:x.string(),value:x.string(),comment:x.string().optional()}),lS=x.array(wI),RI=x.object({name:x.string(),value:x.string(),comment:x.string().optional()}),CI=x.array(RI),xI=x.object({name:x.string(),value:x.string().optional(),fileName:x.string().optional(),contentType:x.string().optional(),comment:x.string().optional()}),MI=x.array(xI),_I=x.object({mimeType:x.string(),params:MI,text:x.string(),comment:x.string().optional()}),II=x.object({method:x.string(),url:x.string(),httpVersion:x.string().optional(),cookies:sS,headers:lS,queryString:CI,postData:_I.optional(),headersSize:x.number().optional(),bodySize:x.number().optional(),comment:x.string().optional()}),PI=x.object({size:x.number().optional(),compression:x.number().optional(),mimeType:x.string().optional(),text:x.string().optional(),encoding:x.string().optional(),comment:x.string().optional()}),OI=x.object({status:x.number(),statusText:x.string(),httpVersion:x.string().optional(),cookies:sS,headers:lS,content:PI,redirectURL:x.string().optional(),headersSize:x.number().optional(),bodySize:x.number().optional(),comment:x.string().optional(),_mocked:x.boolean().optional()}),iS=x.object({expires:x.string().optional(),lastAccess:x.string(),eTag:x.string(),hitCount:x.number(),comment:x.string().optional()}),LI=x.object({beforeRequest:iS.optional(),afterRequest:iS.optional(),comment:x.string().optional()}),NI=x.object({blocked:x.number().optional(),dns:x.number().optional(),connect:x.number().optional(),send:x.number(),wait:x.number(),receive:x.number(),ssl:x.number().optional(),comment:x.string().optional()}),cS=x.object({pageref:x.string().optional(),startedDateTime:x.string(),time:x.number().optional(),request:II,response:OI.optional(),cache:LI.optional(),timings:NI,serverIPAddress:x.string().optional(),connection:x.string().optional(),comment:x.string().optional(),_resourceType:x.string().optional()}),DI=x.array(cS),kI=x.object({version:x.string().default("1.1"),creator:bI.optional(),browser:EI.optional(),pages:vI.optional(),entries:DI,comment:x.string().optional()}),UI=x.object({log:kI}),uS=x.record(x.string(),aS),dS=x.record(x.string(),cS);FI(pd);var BI=pd.object({logsPerPage:Bs.array().array(),harPages:uS.optional(),harEntries:dS.optional()}).openapi({ref:"DebugData"});import{cloneDeep as zI}from"lodash-es";import{z as Ar}from"zod";var mS=(c=>(c.DisableClickhouseCaches="disable_clickhouse_caches",c.ShowZeroOpacityElements="show_zero_opacity_elements",c.VisualActions="visual_actions",c.RagV2="rag_v2",c.DisableSecondaryCacheResolution="disable_secondary_cache_resolution",c.GlobalLocatorRedirect="global_locator_redirect",c.FakerConstantSeed="faker_constant_seed",c.AutoExpandIframes="auto_expand_iframes",c))(mS||{});var pS=Ar.union([Ar.string(),Ar.number(),Ar.boolean(),Ar.null(),Ar.record(Ar.string(),Ar.lazy(()=>pS)),Ar.array(Ar.lazy(()=>pS))]),zs=class{flags;payloads;constructor(e,t){this.flags=e,this.payloads=t}isBooleanFlagEnabled(e){return process.env&&process.env[`MOMENTIC_FLAG_OVERRIDE_${e.toUpperCase()}`]==="true"?!0:process.env&&process.env[`MOMENTIC_FLAG_OVERRIDE_${e.toUpperCase()}`]==="false"?!1:this.flags[e]===!0}getAllFlags(){let e=zI(this.flags);return Object.entries(e).forEach(([t,n])=>{typeof n=="boolean"&&Object.values(mS).includes(t)&&(e[t]=this.isBooleanFlagEnabled(t))}),e}getFlagPayload(e){let t=this.payloads[e];if(t!==void 0){if(typeof t=="string")try{return JSON.parse(t)}catch{return t}return t}}refresh(){throw new Error("Not implemented")}},FX=new zs({},{});var md={".123":"application/vnd.lotus-1-2-3",".3dml":"text/vnd.in3d.3dml",".3g2":"video/3gpp2",".3gp":"video/3gpp",".a":"application/octet-stream",".aab":"application/x-authorware-bin",".aac":"audio/x-aac",".aam":"application/x-authorware-map",".aas":"application/x-authorware-seg",".abw":"application/x-abiword",".acc":"application/vnd.americandynamics.acc",".ace":"application/x-ace-compressed",".acu":"application/vnd.acucobol",".acutc":"application/vnd.acucorp",".adp":"audio/adpcm",".aep":"application/vnd.audiograph",".afm":"application/x-font-type1",".afp":"application/vnd.ibm.modcap",".ai":"application/postscript",".aif":"audio/x-aiff",".aifc":"audio/x-aiff",".aiff":"audio/x-aiff",".air":"application/vnd.adobe.air-application-installer-package+zip",".ami":"application/vnd.amiga.ami",".apk":"application/vnd.android.package-archive",".application":"application/x-ms-application",".apr":"application/vnd.lotus-approach",".asc":"application/pgp-signature",".asf":"video/x-ms-asf",".asm":"text/x-asm",".aso":"application/vnd.accpac.simply.aso",".asx":"video/x-ms-asf",".atc":"application/vnd.acucorp",".atom":"application/atom+xml",".atomcat":"application/atomcat+xml",".atomsvc":"application/atomsvc+xml",".atx":"application/vnd.antix.game-component",".au":"audio/basic",".avi":"video/x-msvideo",".aw":"application/applixware",".azf":"application/vnd.airzip.filesecure.azf",".azs":"application/vnd.airzip.filesecure.azs",".azw":"application/vnd.amazon.ebook",".bat":"application/x-msdownload",".bcpio":"application/x-bcpio",".bdf":"application/x-font-bdf",".bdm":"application/vnd.syncml.dm+wbxml",".bh2":"application/vnd.fujitsu.oasysprs",".bin":"application/octet-stream",".bmi":"application/vnd.bmi",".bmp":"image/bmp",".book":"application/vnd.framemaker",".box":"application/vnd.previewsystems.box",".boz":"application/x-bzip2",".bpk":"application/octet-stream",".btif":"image/prs.btif",".bz":"application/x-bzip",".bz2":"application/x-bzip2",".c":"text/x-c",".c4d":"application/vnd.clonk.c4group",".c4f":"application/vnd.clonk.c4group",".c4g":"application/vnd.clonk.c4group",".c4p":"application/vnd.clonk.c4group",".c4u":"application/vnd.clonk.c4group",".cab":"application/vnd.ms-cab-compressed",".car":"application/vnd.curl.car",".cat":"application/vnd.ms-pki.seccat",".cc":"text/x-c",".cct":"application/x-director",".ccxml":"application/ccxml+xml",".cdbcmsg":"application/vnd.contact.cmsg",".cdf":"application/x-netcdf",".cdkey":"application/vnd.mediastation.cdkey",".cdx":"chemical/x-cdx",".cdxml":"application/vnd.chemdraw+xml",".cdy":"application/vnd.cinderella",".cer":"application/pkix-cert",".cgm":"image/cgm",".chat":"application/x-chat",".chm":"application/vnd.ms-htmlhelp",".chrt":"application/vnd.kde.kchart",".cif":"chemical/x-cif",".cii":"application/vnd.anser-web-certificate-issue-initiation",".cil":"application/vnd.ms-artgalry",".cla":"application/vnd.claymore",".class":"application/java-vm",".clkk":"application/vnd.crick.clicker.keyboard",".clkp":"application/vnd.crick.clicker.palette",".clkt":"application/vnd.crick.clicker.template",".clkw":"application/vnd.crick.clicker.wordbank",".clkx":"application/vnd.crick.clicker",".clp":"application/x-msclip",".cmc":"application/vnd.cosmocaller",".cmdf":"chemical/x-cmdf",".cml":"chemical/x-cml",".cmp":"application/vnd.yellowriver-custom-menu",".cmx":"image/x-cmx",".cod":"application/vnd.rim.cod",".com":"application/x-msdownload",".conf":"text/plain",".cpio":"application/x-cpio",".cpp":"text/x-c",".cpt":"application/mac-compactpro",".crd":"application/x-mscardfile",".crl":"application/pkix-crl",".crt":"application/x-x509-ca-cert",".csh":"application/x-csh",".csml":"chemical/x-csml",".csp":"application/vnd.commonspace",".css":"text/css",".cst":"application/x-director",".csv":"text/csv",".cu":"application/cu-seeme",".curl":"text/vnd.curl",".cww":"application/prs.cww",".cxt":"application/x-director",".cxx":"text/x-c",".daf":"application/vnd.mobius.daf",".dataless":"application/vnd.fdsn.seed",".davmount":"application/davmount+xml",".dcr":"application/x-director",".dcurl":"text/vnd.curl.dcurl",".dd2":"application/vnd.oma.dd2+xml",".ddd":"application/vnd.fujixerox.ddd",".deb":"application/x-debian-package",".def":"text/plain",".deploy":"application/octet-stream",".der":"application/x-x509-ca-cert",".dfac":"application/vnd.dreamfactory",".dic":"text/x-c",".diff":"text/plain",".dir":"application/x-director",".dis":"application/vnd.mobius.dis",".dist":"application/octet-stream",".distz":"application/octet-stream",".djv":"image/vnd.djvu",".djvu":"image/vnd.djvu",".dll":"application/x-msdownload",".dmg":"application/octet-stream",".dms":"application/octet-stream",".dna":"application/vnd.dna",".doc":"application/msword",".docm":"application/vnd.ms-word.document.macroenabled.12",".docx":"application/vnd.openxmlformats-officedocument.wordprocessingml.document",".dot":"application/msword",".dotm":"application/vnd.ms-word.template.macroenabled.12",".dotx":"application/vnd.openxmlformats-officedocument.wordprocessingml.template",".dp":"application/vnd.osgi.dp",".dpg":"application/vnd.dpgraph",".dsc":"text/prs.lines.tag",".dtb":"application/x-dtbook+xml",".dtd":"application/xml-dtd",".dts":"audio/vnd.dts",".dtshd":"audio/vnd.dts.hd",".dump":"application/octet-stream",".dvi":"application/x-dvi",".dwf":"model/vnd.dwf",".dwg":"image/vnd.dwg",".dxf":"image/vnd.dxf",".dxp":"application/vnd.spotfire.dxp",".dxr":"application/x-director",".ecelp4800":"audio/vnd.nuera.ecelp4800",".ecelp7470":"audio/vnd.nuera.ecelp7470",".ecelp9600":"audio/vnd.nuera.ecelp9600",".ecma":"application/ecmascript",".edm":"application/vnd.novadigm.edm",".edx":"application/vnd.novadigm.edx",".efif":"application/vnd.picsel",".ei6":"application/vnd.pg.osasli",".elc":"application/octet-stream",".eml":"message/rfc822",".emma":"application/emma+xml",".eol":"audio/vnd.digital-winds",".eot":"application/vnd.ms-fontobject",".eps":"application/postscript",".epub":"application/epub+zip",".es3":"application/vnd.eszigno3+xml",".esf":"application/vnd.epson.esf",".et3":"application/vnd.eszigno3+xml",".etx":"text/x-setext",".exe":"application/x-msdownload",".ext":"application/vnd.novadigm.ext",".ez":"application/andrew-inset",".ez2":"application/vnd.ezpix-album",".ez3":"application/vnd.ezpix-package",".f":"text/x-fortran",".f4v":"video/x-f4v",".f77":"text/x-fortran",".f90":"text/x-fortran",".fbs":"image/vnd.fastbidsheet",".fdf":"application/vnd.fdf",".fe_launch":"application/vnd.denovo.fcselayout-link",".fg5":"application/vnd.fujitsu.oasysgp",".fgd":"application/x-director",".fh":"image/x-freehand",".fh4":"image/x-freehand",".fh5":"image/x-freehand",".fh7":"image/x-freehand",".fhc":"image/x-freehand",".fig":"application/x-xfig",".fli":"video/x-fli",".flo":"application/vnd.micrografx.flo",".flv":"video/x-flv",".flw":"application/vnd.kde.kivio",".flx":"text/vnd.fmi.flexstor",".fly":"text/vnd.fly",".fm":"application/vnd.framemaker",".fnc":"application/vnd.frogans.fnc",".for":"text/x-fortran",".fpx":"image/vnd.fpx",".frame":"application/vnd.framemaker",".fsc":"application/vnd.fsc.weblaunch",".fst":"image/vnd.fst",".ftc":"application/vnd.fluxtime.clip",".fti":"application/vnd.anser-web-funds-transfer-initiation",".fvt":"video/vnd.fvt",".fzs":"application/vnd.fuzzysheet",".g3":"image/g3fax",".gac":"application/vnd.groove-account",".gdl":"model/vnd.gdl",".geo":"application/vnd.dynageo",".gex":"application/vnd.geometry-explorer",".ggb":"application/vnd.geogebra.file",".ggt":"application/vnd.geogebra.tool",".ghf":"application/vnd.groove-help",".gif":"image/gif",".gim":"application/vnd.groove-identity-message",".gmx":"application/vnd.gmx",".gnumeric":"application/x-gnumeric",".gph":"application/vnd.flographit",".gqf":"application/vnd.grafeq",".gqs":"application/vnd.grafeq",".gram":"application/srgs",".gre":"application/vnd.geometry-explorer",".grv":"application/vnd.groove-injector",".grxml":"application/srgs+xml",".gsf":"application/x-font-ghostscript",".gtar":"application/x-gtar",".gtm":"application/vnd.groove-tool-message",".gtw":"model/vnd.gtw",".gv":"text/vnd.graphviz",".gz":"application/x-gzip",".h":"text/x-c",".h261":"video/h261",".h263":"video/h263",".h264":"video/h264",".hbci":"application/vnd.hbci",".hdf":"application/x-hdf",".hh":"text/x-c",".hlp":"application/winhlp",".hpgl":"application/vnd.hp-hpgl",".hpid":"application/vnd.hp-hpid",".hps":"application/vnd.hp-hps",".hqx":"application/mac-binhex40",".htke":"application/vnd.kenameaapp",".htm":"text/html",".html":"text/html",".hvd":"application/vnd.yamaha.hv-dic",".hvp":"application/vnd.yamaha.hv-voice",".hvs":"application/vnd.yamaha.hv-script",".icc":"application/vnd.iccprofile",".ice":"x-conference/x-cooltalk",".icm":"application/vnd.iccprofile",".ico":"image/x-icon",".ics":"text/calendar",".ief":"image/ief",".ifb":"text/calendar",".ifm":"application/vnd.shana.informed.formdata",".iges":"model/iges",".igl":"application/vnd.igloader",".igs":"model/iges",".igx":"application/vnd.micrografx.igx",".iif":"application/vnd.shana.informed.interchange",".imp":"application/vnd.accpac.simply.imp",".ims":"application/vnd.ms-ims",".in":"text/plain",".ipk":"application/vnd.shana.informed.package",".irm":"application/vnd.ibm.rights-management",".irp":"application/vnd.irepository.package+xml",".iso":"application/octet-stream",".itp":"application/vnd.shana.informed.formtemplate",".ivp":"application/vnd.immervision-ivp",".ivu":"application/vnd.immervision-ivu",".jad":"text/vnd.sun.j2me.app-descriptor",".jam":"application/vnd.jam",".jar":"application/java-archive",".java":"text/x-java-source",".jisp":"application/vnd.jisp",".jlt":"application/vnd.hp-jlyt",".jnlp":"application/x-java-jnlp-file",".joda":"application/vnd.joost.joda-archive",".jpe":"image/jpeg",".jpeg":"image/jpeg",".jpg":"image/jpeg",".jpgm":"video/jpm",".jpgv":"video/jpeg",".jpm":"video/jpm",".js":"application/javascript",".json":"application/json",".kar":"audio/midi",".karbon":"application/vnd.kde.karbon",".kfo":"application/vnd.kde.kformula",".kia":"application/vnd.kidspiration",".kil":"application/x-killustrator",".kml":"application/vnd.google-earth.kml+xml",".kmz":"application/vnd.google-earth.kmz",".kne":"application/vnd.kinar",".knp":"application/vnd.kinar",".kon":"application/vnd.kde.kontour",".kpr":"application/vnd.kde.kpresenter",".kpt":"application/vnd.kde.kpresenter",".ksh":"text/plain",".ksp":"application/vnd.kde.kspread",".ktr":"application/vnd.kahootz",".ktz":"application/vnd.kahootz",".kwd":"application/vnd.kde.kword",".kwt":"application/vnd.kde.kword",".latex":"application/x-latex",".lbd":"application/vnd.llamagraphics.life-balance.desktop",".lbe":"application/vnd.llamagraphics.life-balance.exchange+xml",".les":"application/vnd.hhe.lesson-player",".lha":"application/octet-stream",".link66":"application/vnd.route66.link66+xml",".list":"text/plain",".list3820":"application/vnd.ibm.modcap",".listafp":"application/vnd.ibm.modcap",".log":"text/plain",".lostxml":"application/lost+xml",".lrf":"application/octet-stream",".lrm":"application/vnd.ms-lrm",".ltf":"application/vnd.frogans.ltf",".lvp":"audio/vnd.lucent.voice",".lwp":"application/vnd.lotus-wordpro",".lzh":"application/octet-stream",".m13":"application/x-msmediaview",".m14":"application/x-msmediaview",".m1v":"video/mpeg",".m2a":"audio/mpeg",".m2v":"video/mpeg",".m3a":"audio/mpeg",".m3u":"audio/x-mpegurl",".m4u":"video/vnd.mpegurl",".m4v":"video/x-m4v",".ma":"application/mathematica",".mag":"application/vnd.ecowin.chart",".maker":"application/vnd.framemaker",".man":"text/troff",".mathml":"application/mathml+xml",".mb":"application/mathematica",".mbk":"application/vnd.mobius.mbk",".mbox":"application/mbox",".mc1":"application/vnd.medcalcdata",".mcd":"application/vnd.mcd",".mcurl":"text/vnd.curl.mcurl",".mdb":"application/x-msaccess",".mdi":"image/vnd.ms-modi",".me":"text/troff",".mesh":"model/mesh",".mfm":"application/vnd.mfmp",".mgz":"application/vnd.proteus.magazine",".mht":"message/rfc822",".mhtml":"message/rfc822",".mid":"audio/midi",".midi":"audio/midi",".mif":"application/vnd.mif",".mime":"message/rfc822",".mj2":"video/mj2",".mjp2":"video/mj2",".mkv":"video/x-matroska",".mlp":"application/vnd.dolby.mlp",".mmd":"application/vnd.chipnuts.karaoke-mmd",".mmf":"application/vnd.smaf",".mmr":"image/vnd.fujixerox.edmics-mmr",".mny":"application/x-msmoney",".mobi":"application/x-mobipocket-ebook",".mov":"video/quicktime",".movie":"video/x-sgi-movie",".mp2":"audio/mpeg",".mp2a":"audio/mpeg",".mp3":"audio/mpeg",".mp4":"video/mp4",".mp4a":"audio/mp4",".mp4s":"application/mp4",".mp4v":"video/mp4",".mpa":"video/mpeg",".mpc":"application/vnd.mophun.certificate",".mpe":"video/mpeg",".mpeg":"video/mpeg",".mpg":"video/mpeg",".mpg4":"video/mp4",".mpga":"audio/mpeg",".mpkg":"application/vnd.apple.installer+xml",".mpm":"application/vnd.blueice.multipass",".mpn":"application/vnd.mophun.application",".mpp":"application/vnd.ms-project",".mpt":"application/vnd.ms-project",".mpy":"application/vnd.ibm.minipay",".mqy":"application/vnd.mobius.mqy",".mrc":"application/marc",".ms":"text/troff",".mscml":"application/mediaservercontrol+xml",".mseed":"application/vnd.fdsn.mseed",".mseq":"application/vnd.mseq",".msf":"application/vnd.epson.msf",".msh":"model/mesh",".msi":"application/x-msdownload",".msl":"application/vnd.mobius.msl",".msty":"application/vnd.muvee.style",".mts":"model/vnd.mts",".mus":"application/vnd.musician",".musicxml":"application/vnd.recordare.musicxml+xml",".mvb":"application/x-msmediaview",".mwf":"application/vnd.mfer",".mxf":"application/mxf",".mxl":"application/vnd.recordare.musicxml",".mxml":"application/xv+xml",".mxs":"application/vnd.triscape.mxs",".mxu":"video/vnd.mpegurl",".n-gage":"application/vnd.nokia.n-gage.symbian.install",".nb":"application/mathematica",".nc":"application/x-netcdf",".ncx":"application/x-dtbncx+xml",".ngdat":"application/vnd.nokia.n-gage.data",".nlu":"application/vnd.neurolanguage.nlu",".nml":"application/vnd.enliven",".nnd":"application/vnd.noblenet-directory",".nns":"application/vnd.noblenet-sealer",".nnw":"application/vnd.noblenet-web",".npx":"image/vnd.net-fpx",".nsf":"application/vnd.lotus-notes",".nws":"message/rfc822",".o":"application/octet-stream",".oa2":"application/vnd.fujitsu.oasys2",".oa3":"application/vnd.fujitsu.oasys3",".oas":"application/vnd.fujitsu.oasys",".obd":"application/x-msbinder",".obj":"application/octet-stream",".oda":"application/oda",".odb":"application/vnd.oasis.opendocument.database",".odc":"application/vnd.oasis.opendocument.chart",".odf":"application/vnd.oasis.opendocument.formula",".odft":"application/vnd.oasis.opendocument.formula-template",".odg":"application/vnd.oasis.opendocument.graphics",".odi":"application/vnd.oasis.opendocument.image",".odp":"application/vnd.oasis.opendocument.presentation",".ods":"application/vnd.oasis.opendocument.spreadsheet",".odt":"application/vnd.oasis.opendocument.text",".oga":"audio/ogg",".ogg":"audio/ogg",".ogv":"video/ogg",".ogx":"application/ogg",".onepkg":"application/onenote",".onetmp":"application/onenote",".onetoc":"application/onenote",".onetoc2":"application/onenote",".opf":"application/oebps-package+xml",".oprc":"application/vnd.palm",".org":"application/vnd.lotus-organizer",".osf":"application/vnd.yamaha.openscoreformat",".osfpvg":"application/vnd.yamaha.openscoreformat.osfpvg+xml",".otc":"application/vnd.oasis.opendocument.chart-template",".otf":"application/x-font-otf",".otg":"application/vnd.oasis.opendocument.graphics-template",".oth":"application/vnd.oasis.opendocument.text-web",".oti":"application/vnd.oasis.opendocument.image-template",".otm":"application/vnd.oasis.opendocument.text-master",".otp":"application/vnd.oasis.opendocument.presentation-template",".ots":"application/vnd.oasis.opendocument.spreadsheet-template",".ott":"application/vnd.oasis.opendocument.text-template",".oxt":"application/vnd.openofficeorg.extension",".p":"text/x-pascal",".p10":"application/pkcs10",".p12":"application/x-pkcs12",".p7b":"application/x-pkcs7-certificates",".p7c":"application/pkcs7-mime",".p7m":"application/pkcs7-mime",".p7r":"application/x-pkcs7-certreqresp",".p7s":"application/pkcs7-signature",".pas":"text/x-pascal",".pbd":"application/vnd.powerbuilder6",".pbm":"image/x-portable-bitmap",".pcf":"application/x-font-pcf",".pcl":"application/vnd.hp-pcl",".pclxl":"application/vnd.hp-pclxl",".pct":"image/x-pict",".pcurl":"application/vnd.curl.pcurl",".pcx":"image/x-pcx",".pdb":"application/vnd.palm",".pdf":"application/pdf",".pfa":"application/x-font-type1",".pfb":"application/x-font-type1",".pfm":"application/x-font-type1",".pfr":"application/font-tdpfr",".pfx":"application/x-pkcs12",".pgm":"image/x-portable-graymap",".pgn":"application/x-chess-pgn",".pgp":"application/pgp-encrypted",".pic":"image/x-pict",".pkg":"application/octet-stream",".pki":"application/pkixcmp",".pkipath":"application/pkix-pkipath",".pl":"text/plain",".plb":"application/vnd.3gpp.pic-bw-large",".plc":"application/vnd.mobius.plc",".plf":"application/vnd.pocketlearn",".pls":"application/pls+xml",".pml":"application/vnd.ctc-posml",".png":"image/png",".pnm":"image/x-portable-anymap",".portpkg":"application/vnd.macports.portpkg",".pot":"application/vnd.ms-powerpoint",".potm":"application/vnd.ms-powerpoint.template.macroenabled.12",".potx":"application/vnd.openxmlformats-officedocument.presentationml.template",".ppa":"application/vnd.ms-powerpoint",".ppam":"application/vnd.ms-powerpoint.addin.macroenabled.12",".ppd":"application/vnd.cups-ppd",".ppm":"image/x-portable-pixmap",".pps":"application/vnd.ms-powerpoint",".ppsm":"application/vnd.ms-powerpoint.slideshow.macroenabled.12",".ppsx":"application/vnd.openxmlformats-officedocument.presentationml.slideshow",".ppt":"application/vnd.ms-powerpoint",".pptm":"application/vnd.ms-powerpoint.presentation.macroenabled.12",".pptx":"application/vnd.openxmlformats-officedocument.presentationml.presentation",".pqa":"application/vnd.palm",".prc":"application/x-mobipocket-ebook",".pre":"application/vnd.lotus-freelance",".prf":"application/pics-rules",".ps":"application/postscript",".psb":"application/vnd.3gpp.pic-bw-small",".psd":"image/vnd.adobe.photoshop",".psf":"application/x-font-linux-psf",".ptid":"application/vnd.pvi.ptid1",".pub":"application/x-mspublisher",".pvb":"application/vnd.3gpp.pic-bw-var",".pwn":"application/vnd.3m.post-it-notes",".pwz":"application/vnd.ms-powerpoint",".py":"text/x-python",".pya":"audio/vnd.ms-playready.media.pya",".pyc":"application/x-python-code",".pyo":"application/x-python-code",".pyv":"video/vnd.ms-playready.media.pyv",".qam":"application/vnd.epson.quickanime",".qbo":"application/vnd.intu.qbo",".qfx":"application/vnd.intu.qfx",".qps":"application/vnd.publishare-delta-tree",".qt":"video/quicktime",".qwd":"application/vnd.quark.quarkxpress",".qwt":"application/vnd.quark.quarkxpress",".qxb":"application/vnd.quark.quarkxpress",".qxd":"application/vnd.quark.quarkxpress",".qxl":"application/vnd.quark.quarkxpress",".qxt":"application/vnd.quark.quarkxpress",".ra":"audio/x-pn-realaudio",".ram":"audio/x-pn-realaudio",".rar":"application/x-rar-compressed",".ras":"image/x-cmu-raster",".rcprofile":"application/vnd.ipunplugged.rcprofile",".rdf":"application/rdf+xml",".rdz":"application/vnd.data-vision.rdz",".rep":"application/vnd.businessobjects",".res":"application/x-dtbresource+xml",".rgb":"image/x-rgb",".rif":"application/reginfo+xml",".rl":"application/resource-lists+xml",".rlc":"image/vnd.fujixerox.edmics-rlc",".rld":"application/resource-lists-diff+xml",".rm":"application/vnd.rn-realmedia",".rmi":"audio/midi",".rmp":"audio/x-pn-realaudio-plugin",".rms":"application/vnd.jcp.javame.midlet-rms",".rnc":"application/relax-ng-compact-syntax",".roff":"text/troff",".rpm":"application/x-rpm",".rpss":"application/vnd.nokia.radio-presets",".rpst":"application/vnd.nokia.radio-preset",".rq":"application/sparql-query",".rs":"application/rls-services+xml",".rsd":"application/rsd+xml",".rss":"application/rss+xml",".rtf":"application/rtf",".rtx":"text/richtext",".s":"text/x-asm",".saf":"application/vnd.yamaha.smaf-audio",".sbml":"application/sbml+xml",".sc":"application/vnd.ibm.secure-container",".scd":"application/x-msschedule",".scm":"application/vnd.lotus-screencam",".scq":"application/scvp-cv-request",".scs":"application/scvp-cv-response",".scurl":"text/vnd.curl.scurl",".sda":"application/vnd.stardivision.draw",".sdc":"application/vnd.stardivision.calc",".sdd":"application/vnd.stardivision.impress",".sdkd":"application/vnd.solent.sdkm+xml",".sdkm":"application/vnd.solent.sdkm+xml",".sdp":"application/sdp",".sdw":"application/vnd.stardivision.writer",".see":"application/vnd.seemail",".seed":"application/vnd.fdsn.seed",".sema":"application/vnd.sema",".semd":"application/vnd.semd",".semf":"application/vnd.semf",".ser":"application/java-serialized-object",".setpay":"application/set-payment-initiation",".setreg":"application/set-registration-initiation",".sfd-hdstx":"application/vnd.hydrostatix.sof-data",".sfs":"application/vnd.spotfire.sfs",".sgl":"application/vnd.stardivision.writer-global",".sgm":"text/sgml",".sgml":"text/sgml",".sh":"application/x-sh",".shar":"application/x-shar",".shf":"application/shf+xml",".si":"text/vnd.wap.si",".sic":"application/vnd.wap.sic",".sig":"application/pgp-signature",".silo":"model/mesh",".sis":"application/vnd.symbian.install",".sisx":"application/vnd.symbian.install",".sit":"application/x-stuffit",".sitx":"application/x-stuffitx",".skd":"application/vnd.koan",".skm":"application/vnd.koan",".skp":"application/vnd.koan",".skt":"application/vnd.koan",".sl":"text/vnd.wap.sl",".slc":"application/vnd.wap.slc",".sldm":"application/vnd.ms-powerpoint.slide.macroenabled.12",".sldx":"application/vnd.openxmlformats-officedocument.presentationml.slide",".slt":"application/vnd.epson.salt",".smf":"application/vnd.stardivision.math",".smi":"application/smil+xml",".smil":"application/smil+xml",".snd":"audio/basic",".snf":"application/x-font-snf",".so":"application/octet-stream",".spc":"application/x-pkcs7-certificates",".spf":"application/vnd.yamaha.smaf-phrase",".spl":"application/x-futuresplash",".spot":"text/vnd.in3d.spot",".spp":"application/scvp-vp-response",".spq":"application/scvp-vp-request",".spx":"audio/ogg",".src":"application/x-wais-source",".srx":"application/sparql-results+xml",".sse":"application/vnd.kodak-descriptor",".ssf":"application/vnd.epson.ssf",".ssml":"application/ssml+xml",".stc":"application/vnd.sun.xml.calc.template",".std":"application/vnd.sun.xml.draw.template",".stf":"application/vnd.wt.stf",".sti":"application/vnd.sun.xml.impress.template",".stk":"application/hyperstudio",".stl":"application/vnd.ms-pki.stl",".str":"application/vnd.pg.format",".stw":"application/vnd.sun.xml.writer.template",".sus":"application/vnd.sus-calendar",".susp":"application/vnd.sus-calendar",".sv4cpio":"application/x-sv4cpio",".sv4crc":"application/x-sv4crc",".svd":"application/vnd.svd",".svg":"image/svg+xml",".svgz":"image/svg+xml",".swa":"application/x-director",".swf":"application/x-shockwave-flash",".swi":"application/vnd.arastra.swi",".sxc":"application/vnd.sun.xml.calc",".sxd":"application/vnd.sun.xml.draw",".sxg":"application/vnd.sun.xml.writer.global",".sxi":"application/vnd.sun.xml.impress",".sxm":"application/vnd.sun.xml.math",".sxw":"application/vnd.sun.xml.writer",".t":"text/troff",".tao":"application/vnd.tao.intent-module-archive",".tar":"application/x-tar",".tcap":"application/vnd.3gpp2.tcap",".tcl":"application/x-tcl",".teacher":"application/vnd.smart.teacher",".tex":"application/x-tex",".texi":"application/x-texinfo",".texinfo":"application/x-texinfo",".text":"text/plain",".tfm":"application/x-tex-tfm",".tgz":"application/x-gzip",".tif":"image/tiff",".tiff":"image/tiff",".tmo":"application/vnd.tmobile-livetv",".torrent":"application/x-bittorrent",".tpl":"application/vnd.groove-tool-template",".tpt":"application/vnd.trid.tpt",".tr":"text/troff",".tra":"application/vnd.trueapp",".trm":"application/x-msterminal",".tsv":"text/tab-separated-values",".ttc":"application/x-font-ttf",".ttf":"application/x-font-ttf",".twd":"application/vnd.simtech-mindmapper",".twds":"application/vnd.simtech-mindmapper",".txd":"application/vnd.genomatix.tuxedo",".txf":"application/vnd.mobius.txf",".txt":"text/plain",".u32":"application/x-authorware-bin",".udeb":"application/x-debian-package",".ufd":"application/vnd.ufdl",".ufdl":"application/vnd.ufdl",".umj":"application/vnd.umajin",".unityweb":"application/vnd.unity",".uoml":"application/vnd.uoml+xml",".uri":"text/uri-list",".uris":"text/uri-list",".urls":"text/uri-list",".ustar":"application/x-ustar",".utz":"application/vnd.uiq.theme",".uu":"text/x-uuencode",".vcd":"application/x-cdlink",".vcf":"text/x-vcard",".vcg":"application/vnd.groove-vcard",".vcs":"text/x-vcalendar",".vcx":"application/vnd.vcx",".vis":"application/vnd.visionary",".viv":"video/vnd.vivo",".vor":"application/vnd.stardivision.writer",".vox":"application/x-authorware-bin",".vrml":"model/vrml",".vsd":"application/vnd.visio",".vsf":"application/vnd.vsf",".vss":"application/vnd.visio",".vst":"application/vnd.visio",".vsw":"application/vnd.visio",".vtu":"model/vnd.vtu",".vxml":"application/voicexml+xml",".w3d":"application/x-director",".webm":"video/webm",".wad":"application/x-doom",".wav":"audio/x-wav",".wax":"audio/x-ms-wax",".wbmp":"image/vnd.wap.wbmp",".wbs":"application/vnd.criticaltools.wbs+xml",".wbxml":"application/vnd.wap.wbxml",".wcm":"application/vnd.ms-works",".wdb":"application/vnd.ms-works",".wiz":"application/msword",".wks":"application/vnd.ms-works",".wm":"video/x-ms-wm",".wma":"audio/x-ms-wma",".wmd":"application/x-ms-wmd",".wmf":"application/x-msmetafile",".wml":"text/vnd.wap.wml",".wmlc":"application/vnd.wap.wmlc",".wmls":"text/vnd.wap.wmlscript",".wmlsc":"application/vnd.wap.wmlscriptc",".wmv":"video/x-ms-wmv",".wmx":"video/x-ms-wmx",".wmz":"application/x-ms-wmz",".wpd":"application/vnd.wordperfect",".wpl":"application/vnd.ms-wpl",".wps":"application/vnd.ms-works",".wqd":"application/vnd.wqd",".wri":"application/x-mswrite",".wrl":"model/vrml",".wsdl":"application/wsdl+xml",".wspolicy":"application/wspolicy+xml",".wtb":"application/vnd.webturbo",".wvx":"video/x-ms-wvx",".x32":"application/x-authorware-bin",".x3d":"application/vnd.hzn-3d-crossword",".xap":"application/x-silverlight-app",".xar":"application/vnd.xara",".xbap":"application/x-ms-xbap",".xbd":"application/vnd.fujixerox.docuworks.binder",".xbm":"image/x-xbitmap",".xdm":"application/vnd.syncml.dm+xml",".xdp":"application/vnd.adobe.xdp+xml",".xdw":"application/vnd.fujixerox.docuworks",".xenc":"application/xenc+xml",".xer":"application/patch-ops-error+xml",".xfdf":"application/vnd.adobe.xfdf",".xfdl":"application/vnd.xfdl",".xht":"application/xhtml+xml",".xhtml":"application/xhtml+xml",".xhvml":"application/xv+xml",".xif":"image/vnd.xiff",".xla":"application/vnd.ms-excel",".xlam":"application/vnd.ms-excel.addin.macroenabled.12",".xlb":"application/vnd.ms-excel",".xlc":"application/vnd.ms-excel",".xlm":"application/vnd.ms-excel",".xls":"application/vnd.ms-excel",".xlsb":"application/vnd.ms-excel.sheet.binary.macroenabled.12",".xlsm":"application/vnd.ms-excel.sheet.macroenabled.12",".xlsx":"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",".xlt":"application/vnd.ms-excel",".xltm":"application/vnd.ms-excel.template.macroenabled.12",".xltx":"application/vnd.openxmlformats-officedocument.spreadsheetml.template",".xlw":"application/vnd.ms-excel",".xml":"application/xml",".xo":"application/vnd.olpc-sugar",".xop":"application/xop+xml",".xpdl":"application/xml",".xpi":"application/x-xpinstall",".xpm":"image/x-xpixmap",".xpr":"application/vnd.is-xpr",".xps":"application/vnd.ms-xpsdocument",".xpw":"application/vnd.intercon.formnet",".xpx":"application/vnd.intercon.formnet",".xsl":"application/xml",".xslt":"application/xslt+xml",".xsm":"application/vnd.syncml+xml",".xspf":"application/xspf+xml",".xul":"application/vnd.mozilla.xul+xml",".xvm":"application/xv+xml",".xvml":"application/xv+xml",".xwd":"image/x-xwindowdump",".xyz":"chemical/x-xyz",".zaz":"application/vnd.zzazz.deck+xml",".zip":"application/zip",".zir":"application/vnd.zul",".zirz":"application/vnd.zul",".zmm":"application/vnd.handheld-entertainment+xml"},gS=[".sh",".exe",".app",".bat",".cmd",".msi",".apk",".jar",".py",".js",".cron",".php",".asp"],zX=Object.keys(md);import*as hS from"zod";var GX=hS.custom().refine(r=>r&&r.length>0).refine(r=>r&&r[0]instanceof File,{message:"Please upload a valid file."});import{z as sn}from"zod";var WX=sn.object({id:sn.string(),name:sn.string(),createdAt:sn.coerce.date(),createdBy:sn.string(),updatedAt:sn.coerce.date(),updatedBy:sn.string().nullable(),organizationId:sn.string()});import{z as O}from"zod";import ln from"zod";var No=ln.object({platformSep:ln.string(),fullPathSegments:ln.string().array(),relativePathSegments:ln.string().array(),relativePath:ln.string().describe("path relative to the root test directory, i.e. my-folder/my-test.yaml"),fileName:ln.string().describe("base name of the file including the extension, e.g. my-module.module.yaml"),lastModified:ln.coerce.date(),createdAt:ln.coerce.date()});var HI=O.array(No.extend({id:O.string(),name:O.string(),description:O.string().optional(),labels:O.string().array().optional()})),GI=O.array(No.extend({id:O.string(),name:O.string(),description:O.string().optional(),content:Gi})),o4=O.object({tests:HI,modules:GI,labels:O.string().array()}),i4=Ns.merge(Oo),a4=O.object({schemaVersion:O.string(),stepLists:Pn}),s4=Oo.partial().merge(dr.pick({id:!0})),VI={name:O.string().min(1).max(255).describe("1-255 chars; Only letters/numbers/dashes. Cannot start/end with '-'. Not '.yaml', 'none', or UUID."),description:O.string().optional(),baseUrl:O.string().url().optional().describe("For LLM: Ask the user for the base URL if they don't provide it."),environment:O.string().optional().describe("For LLM: Do not include the variable unless the user explicitly asks for it and use the environment lookup tool to get the correct one before passing here."),browserType:O.nativeEnum(en).optional().describe("For LLM: Never assign this variable unless the user explicitly asks for it."),viewport:vs.optional().describe("For LLM: Never assign this variable unless the user explicitly asks for it."),pathSegments:O.string().array().optional().describe("For LLM: Only use if explicitly called for by the user. Used to create the test in the correct folder.")},l4=O.object(VI),c4=Ns.merge(O.object({relativeFilePath:O.string().describe("relative to project root")})),u4=O.object({name:O.string()}),d4=O.object({relativeFilePath:O.string()}),p4=O.object({name:O.string()}),m4=O.object({relativeFilePath:O.string()}),g4=O.object({name:O.string(),description:O.string(),enabled:O.boolean(),steps:O.lazy(()=>ot.array()),testFilePath:O.string().describe("relative to the project root"),folderPath:O.string().optional().describe("user selected folder path")}),h4=O.object({name:O.string(),description:O.string(),enabled:O.boolean()}).partial();var f4=O.array(of),S4=O.object({defaultEnv:O.string().optional().describe("name of the default env, or undefined to unset")}),y4=O.object({configFilePath:O.string().describe("full path on disk")}),b4=O.string().array(),E4=O.object({message:O.string(),newRelativeTestPath:O.string().optional()}),gd=O.object({name:O.string(),absolutePath:O.string(),relativePath:O.string(),pathSegments:O.array(O.string()),isDirectory:O.boolean(),size:O.number(),createdAt:O.coerce.date(),modifiedAt:O.coerce.date(),accessedAt:O.coerce.date()}),fS=O.object({pathSegments:O.array(O.string())}),T4=O.object({absolutePath:O.string(),pathSegments:O.array(O.string()),contents:O.array(gd)}),SS=O.object({pathSegments:O.array(O.string())}),yS=O.object({pathSegments:O.array(O.string()),newPathSegments:O.array(O.string())}),bS=O.object({pathSegments:O.array(O.string()),recursive:O.boolean().optional()}),v4=O.object({success:O.boolean(),message:O.string(),pathSegments:O.array(O.string()).optional()});var Hs=["node_modules","dist","bin",".git",".npm",".next","out",".yarn","__pycache__","build",".env",".venv","venv","env","wheels"],Gs=Hs.map(r=>`**/${r}/**`),ES=!0,cn=!1;import wr from"chalk";import jI from"safe-stable-stringify";import WI from"truncate-json";import $I from"zod";var Do=jI.configure({deterministic:!1});function TS(r){let e=Do(r),{jsonString:t}=WI(e,5e4);return t}var qI=["app","version","env","namespace","host"];function pe(r){let e=r.bindings()??{},t={};for(let n of Object.keys(e)){let o=e[n];!qI.includes(n)&&typeof o=="string"&&(t[n]=o)}return t}var js=$I.enum(["debug","info","warn","error"]);var sa={debug:20,info:30,warn:40,error:50},Ws={20:"debug",30:"info",40:"warn",50:"error"},hd=class r{minLogLevel;logBindings;constructor(e,t){typeof e=="string"?this.minLogLevel=sa[e]:this.minLogLevel=e,this.logBindings=t}logWithLevel(e,t,...n){try{this.logWithLevelHelper(e,t,...n)}catch(o){console.error(`Failed to log to console: ${o}`)}}logWithLevelHelper(e,t,...n){if(e<this.minLogLevel)return;let o;Array.isArray(n[0])?(o=n[0],n=n.slice(1)):typeof n[0]=="object"&&!(n[0]instanceof Error)&&Object.entries(n[0]).length&&(o={...n[0],...this.logBindings},n=n.slice(1));let i=[];if(i.push(...n),console.log(t(...i)),o&&!Array.isArray(o)){let a=Object.entries(o);for(let[l,c]of a){let s=c;c instanceof Error?(s=c.message,console.log(t(` ${l}:`,s)),console.log(t(" stack:",c.stack))):typeof c=="object"?(s=Do(c,void 0,2),s=s.split(`
|
|
22
16
|
`).map((u,d)=>d>0?` ${u}`:u).join(`
|
|
23
|
-
`),console.log(t(` ${
|
|
24
|
-
`).map((c,
|
|
25
|
-
`)),console.log(" ",t(s))}}getLevel(){return Ql[this.minLogLevel]}setMinLevel(e){typeof e=="string"?this.minLogLevel=Fa[e]:this.minLogLevel=e}log(...e){this.logWithLevel(30,Nr.reset,...e)}info(...e){this.logWithLevel(30,Nr.white,...e)}debug(...e){this.logWithLevel(20,Nr.dim,...e)}warn(...e){this.logWithLevel(40,Nr.yellow,...e)}error(...e){this.logWithLevel(50,Nr.red,...e)}success(...e){this.logWithLevel(1/0,Nr.green,...e)}dimmed(...e){this.logWithLevel(30,Nr.dim,...e)}underline(...e){this.logWithLevel(40,Nr.underline,...e)}bold(...e){this.logWithLevel(40,Nr.bold,...e)}grey(...e){this.logWithLevel(20,Nr.grey,...e)}child(e){return new r(this.minLogLevel,{...this.logBindings,...e})}flush(){}bindings(){return this.logBindings}},Np=class{debug(){}info(){}warn(){}error(){}success(){}dimmed(){}underline(){}bold(){}grey(){}child(){return this}getLevel(){return"error"}flush(){}bindings(){return{}}},sre=new Np,A0=typeof window>"u"&&typeof process<"u"&&Zl.safeParse(process?.env?.MOMENTIC_DEV_LOG_LEVEL).success?Zl.parse(process.env.MOMENTIC_DEV_LOG_LEVEL):30,x=new Lp(A0,{}),Rn={info:()=>{},error:()=>{},debug:()=>{},warn:()=>{},child:()=>Rn,flush:()=>{},bindings:()=>({}),getLevel:()=>"error"},Jl={},ec=({logger:r,logKey:e,maxCount:t,intervalMs:n},o,i,...a)=>{let s=Jl[e];s?clearTimeout(s.timer):(s={count:0,totalCount:0},Jl[e]=s),s.totalCount++,s.count<t&&(s.count++,r.debug(o,i,...a)),s.timer=setTimeout(()=>{let c=Jl[e];c?.totalCount!==c?.count&&r.debug({logKey:e,totalCount:c?.totalCount,count:c?.count},`Debug logs were rate-limited for ${e}`),delete Jl[e]},n)};import{z as Ee}from"zod";var w0=Ee.array(li.extend({id:Ee.string(),name:Ee.string(),description:Ee.string().optional(),labels:Ee.string().array().optional()})),R0=Ee.array(li.extend({id:Ee.string(),name:Ee.string(),description:Ee.string().optional(),content:va})),JE=Ee.object({name:Ee.string(),description:Ee.string().optional(),settings:Ua.optional(),pathSegments:Ee.string().array()}),mre=Ee.object({id:Ee.string(),fileName:Ee.string(),fullPath:Ee.string(),relativeFilePath:Ee.string().describe("relative to project root")});var ZE=Ee.object({steps:Da.array().optional(),settings:Ua.optional()}),gre=Ee.object({message:Ee.literal("ok")}),QE=Ee.object({tag:Ee.string(),channel:Ee.string(),filePath:Ee.string()}),hre=Ee.object({tests:w0,modules:R0,labels:Ee.string().array()}),eT=Ee.object({name:Ee.string(),description:Ee.string(),enabled:Ee.boolean()}).partial();import{z as $e}from"zod";var tT=$e.object({id:$e.string(),createdAt:$e.coerce.date(),createdBy:$e.string(),organizationId:$e.string(),name:$e.string(),description:$e.string().nullish(),enabled:$e.boolean(),schemaVersion:$e.string().describe("Schema version for steps"),parameters:$e.string().array().nullish().describe("Parameter list"),parameterEnums:$e.record($e.string(),$e.string().array()).nullish(),defaultParameters:$e.record($e.string(),$e.string()).nullish(),defaultCacheKey:$e.string().nullish(),defaultCacheTtl:$e.number().nullish(),defaultCacheAllInvocations:$e.boolean().nullish(),autoAuth:$e.boolean().nullish(),advanced:Xd.nullish()}),wre=tT.extend({steps:$e.lazy(()=>_t.array())}),Rre=5*60*1e3,C0=tr.merge(tT.omit({id:!0,createdAt:!0,createdBy:!0,organizationId:!0,enabled:!0}));import{formatInTimeZone as _re}from"date-fns-tz";import{z as Me}from"zod";var kp=dp.extend({aiAction:Me.boolean().optional(),stepLintSuggestions:Me.boolean().optional(),agentConfig:Me.record(Me.string(),Me.string()).optional(),aiFailureAnalysis:Me.boolean().optional(),aiPageFiltering:Me.boolean().optional().describe("rag v2 feature flag")}),Dp=Me.object({fakerConstantSeed:Me.boolean().optional()}),Nre=Me.object({ai:kp.optional(),githubAppInstallationId:Me.number().nullish(),githubAppSummaryMessageEnabled:Me.boolean().nullish(),githubReleaseAppInstallationId:Me.number().nullish(),gitlabAppAccessToken:Me.string().nullish(),gitlabAppBaseUrl:Me.string().nullish(),qaseAccessToken:Me.string().nullish(),testSuggestionsEnabled:Me.boolean().nullish(),browser:op.optional(),advanced:Dp.optional()}),kre=Me.object({globalOverrides:Me.record(Me.string()).optional(),agentConfig:Me.record(Me.string(),Me.string()).optional()}),Dre=Me.record(Me.string(),Me.string()).nullish();import*as y from"zod";import{z as je}from"zod";var Up=(e=>(e.TEST_REVIEW="TEST_REVIEW",e))(Up||{});var x0=je.object({type:je.literal("DESCRIPTION_UPDATE"),thoughts:je.string()}),tc=je.discriminatedUnion("type",[x0]),_0=je.object({testId:je.string(),name:je.string(),orgId:je.string(),runId:je.string(),steps:ot.array(),purpose:je.nativeEnum(Up),details:tc.or(tc.array()).optional()});var zre=_0.pick({name:!0,orgId:!0}),M0=je.object({id:je.string(),name:je.string().nullish(),createdAt:je.string().pipe(je.coerce.date()).or(je.date()),organizationId:je.string(),schemaVersion:je.string(),runId:je.string().nullish(),purpose:je.nativeEnum(Up),details:tc.or(tc.array()).optional(),applied:je.boolean().nullish(),appliedAt:je.coerce.date().nullish()}),rT=M0.extend({steps:ot.array()});var rc="x-momentic-cli-version",nT="x-momentic-cli-type",oT="x-momentic-logger-tags",I0="x-momentic-main-branch-name",P0="x-momentic-branch-name",O0="x-momentic-commit-timestamp",L0="x-momentic-last-commit-on-main",N0="x-momentic-last-commit-on-main-timestamp",k0="x-momentic-merged-branch-name",iT="x-momentic-session-id",nne=y.object({error:y.boolean(),reason:y.string(),message:y.string()}),one=Tt.merge(gp),aT=fl,ine=Tt.merge(gp);var ane=Tt.merge(Qb).extend({useConsensus:y.boolean().optional(),attemptNumber:y.number().optional()}),Fp=hy,sne=Tt.merge(tE),sT=vb,lne=Tt.merge(eE),lT=Tb,cne=Tt.merge(Xb),cT=bb,une=Tt.merge(Jb),uT=Sb,dne=Tt.merge(Zb);var pne=Tt.merge(iE),mne=y.object({testPaths:y.string().array().describe("can be either hyphenated, lowercase test names or UUIDs"),env:y.string().optional(),all:y.boolean().optional(),urlOverride:y.string().optional(),customHeaders:y.record(y.string(),y.string()).optional(),testInputMatrix:y.record(y.string(),y.string()).array().optional()}),dT=y.object({queuedTests:y.unknown().array(),runIds:y.string().uuid().array(),runGroupId:y.string().optional()});var gne=y.string().array(),hne=y.union([y.object({paths:y.string().array().describe("run specific test paths (e.g. todo-test)"),all:y.boolean().describe("run all tests").optional()}),y.object({path:y.string().describe("deprecated; present for backcompat")})]),pT=y.object({tests:y.record(y.string().describe("Test name"),y.string().describe("Test YAML")),modules:y.record(y.string().describe("Module name"),y.string().describe("Module YAML"))}),D0=y.object({test:y.string().describe("test YAML"),modules:y.record(y.string().describe("moduleId"),y.string().describe("module YAML"))}),fne=D0.array(),Sne=y.object({testId:y.string(),schemaVersion:y.string()}).merge(Xn);function Bp(r){let{gitMainBranch:e,gitBranchName:t,gitCommitTimestamp:n,lastCommitOnMainSha:o,lastCommitOnMainTimestamp:i}=r,a={};return e&&(a[I0]=encodeURIComponent(e)),t&&(a[P0]=encodeURIComponent(t)),n&&(a[O0]=n.toISOString()),o&&(a[L0]=encodeURIComponent(o)),i&&(a[N0]=i.toISOString()),r.mergedGitBranchName&&(a[k0]=encodeURIComponent(r.mergedGitBranchName)),a}var yne=y.object({entries:y.array(Py),testId:y.string()}),bne=y.object({entries:y.array(wE),testId:y.string()}),Ene=y.object({testId:y.string()});function mT(r){return y.record(y.unknown()).transform(e=>{let t={};for(let[n,o]of Object.entries(e)){let i=r.safeParse(o);i.success&&(t[n]=i.data)}return t})}var gT=mT(Oy),hT=mT(RE),fT=y.object({trigger:y.nativeEnum(or),status:y.nativeEnum(Ae),startedAt:y.coerce.date().optional(),gitCommitSha:y.string().optional(),gitCommitShaShort:y.string().optional(),gitCommitTimestamp:y.coerce.date().optional(),gitBranchName:y.string().optional(),gitOriginUrl:y.string().optional(),gitCommitMessage:y.string().optional(),gitCommitAuthorName:y.string().optional(),githubRepository:y.string().optional(),gitlabProjectPath:y.string().optional(),pipelineId:y.string().optional(),cliVersion:y.string().optional()}),Tne=y.object({id:y.string()}),ST=y.object({status:y.nativeEnum(Ae),updatedAt:y.coerce.date().optional(),finishedAt:y.coerce.date().optional()}),yT=y.object({stepsSnapshot:y.array(y.record(y.unknown())).optional(),runGroupId:y.string().optional(),testId:y.string(),testName:y.string(),resolvedBaseUrl:y.string().optional(),environmentName:y.string().optional(),labels:y.array(y.string()).optional(),cliVersion:y.string().optional(),trigger:y.nativeEnum(or),schemaVersion:y.string().optional(),section:y.nativeEnum(Ll).optional(),resolvedInputs:y.record(y.string(),y.string()).optional(),quarantined:y.boolean().optional().default(!1),quarantinedReason:y.string().optional()}),vne=y.object({id:y.string()}),U0=pp.pick({id:!0,status:!0,testName:!0,testId:!0,test:!0,failureReason:!0,failureDetails:!0}),bT=U0.array(),ET=pp.pick({startedAt:!0,finishedAt:!0,updatedAt:!0,results:!0,beforeResults:!0,afterResults:!0,status:!0,failureDetails:!0,failureReason:!0,resolvedBaseUrl:!0,environmentName:!0,labels:!0,cliVersion:!0,resolvedInputs:!0,attempts:!0,flake:!0}).partial(),Ane=y.object({id:y.string()}),TT=y.object({status:y.nativeEnum(Ae),finishedAt:y.coerce.date().optional(),schemaVersion:y.string().optional().default("1.0.19"),results:y.record(y.string(),y.unknown()).array().optional(),beforeResults:y.record(y.string(),y.unknown()).array().optional(),afterResults:y.record(y.string(),y.unknown()).array().optional()}),wne=y.object({screenshot:y.string()}),vT=y.object({key:y.string()}),AT=y.object({orgId:y.string(),userId:y.string()}),wT=y.array(Lb),Rne=y.record(y.string(),y.union([y.string(),y.boolean()])),Cne=y.object({paths:y.string().array(),env:y.string().optional(),urlOverride:y.string().optional(),customHeaders:y.record(y.string(),y.string()).optional()}),RT=y.object({suiteRunIds:y.string().array(),runGroupIds:y.string().array()}),xne=y.object({suiteRunIds:y.string().array()}),_ne=$b.array(),Mne=y.object({runGroupIds:y.string().array()}),F0=y.object({uploadUrl:y.string()}),Ine=Tt.merge(rE),Pne=Tt.merge(oE),One=Tt.merge(nE),B0=y.object({testId:y.string().optional().default(""),testName:y.string().optional().default(""),suiteId:y.string().optional().default(""),suiteName:y.string().optional().default(""),creditsUsed:y.number().optional()}),z0=y.object({transactionId:y.string(),timestamp:y.string(),event:y.nativeEnum(Ia),properties:B0}),Lne=z0.array(),CT=rT.omit({steps:!0}).extend({steps:y.array(y.record(y.string(),y.unknown())).describe("unparsed ResolvedStep[]")}),Nne=y.object({limit:y.number().max(10).optional(),afterTime:y.number().optional()}),xT=jb.array(),kne=y.object({applied:y.boolean().optional(),appliedAt:y.coerce.date().optional()}),_T=F0.extend({id:y.string()}),Dne=y.object({runGroupId:y.string().uuid().optional()}),MT=y.object({runGroupId:y.string().uuid()}),IT=y.object({quarantined:y.object({testId:y.string().uuid(),quarantinedAt:y.coerce.date(),quarantinedBy:y.string().optional(),quarantinedReason:y.string()}).array()}),Une=y.object({testId:y.string().uuid(),testName:y.string().optional(),reason:y.string(),gitLocalUsername:y.string().optional(),gitLocalEmail:y.string().optional(),gitLocalName:y.string().optional()}),Fne=y.object({testName:y.string().optional(),reason:y.string().optional(),gitLocalUsername:y.string().optional(),gitLocalEmail:y.string().optional(),gitLocalName:y.string().optional()}),Bne=Tt.merge(cE),zne=Tt.merge(uE),Hne=y.object({apkToInstall:y.object({channel:y.string(),tag:y.string().optional()}).optional(),hostname:y.string().optional(),region:y.nativeEnum(Oa).optional()}),PT=y.object({name:y.string(),webRtcUrl:y.string(),adbUrl:y.string(),token:y.string(),apkDownloadUrl:y.string().optional(),region:y.string().optional()}),Gne=y.object({channel:y.string(),tag:y.string(),md5:y.string()}),OT=y.object({id:y.string(),uploadUrl:y.string().optional(),downloadUrl:y.string(),md5:y.string().optional()}),LT=y.object({assets:y.array(y.object({channel:y.string(),tag:y.string(),md5:y.string(),createdAt:y.number().describe("Unix timestamp in milliseconds")}))});import{z as Q}from"zod";var NT=7,H0=3,Wne=Q.object({localTestId:Q.string(),quarantinedAt:Q.date(),quarantinedBy:Q.string().optional(),quarantinedReason:Q.string(),quarantinedByGitEmail:Q.string().optional(),quarantinedByGitName:Q.string().optional(),quarantinedByGitUsername:Q.string().optional()}).or(Q.object({cloudTestId:Q.string(),quarantinedAt:Q.date(),quarantinedBy:Q.string().optional(),quarantinedReason:Q.string(),quarantinedByGitEmail:Q.string().optional(),quarantinedByGitName:Q.string().optional(),quarantinedByGitUsername:Q.string().optional()})),kT=(t=>(t.QUARANTINE="QUARANTINE",t.UNQUARANTINE="UNQUARANTINE",t))(kT||{});var zp=Q.object({name:Q.string(),description:Q.string().nullish(),effect:Q.nativeEnum(kT),labels:Q.array(Q.string()).nullish(),githubRepository:Q.string().nullish(),gitlabProjectPath:Q.string().nullish(),gitBranchName:Q.string().nullish()}),G0=Q.object({type:Q.literal("LAST_N_RUNS"),lastN:Q.number().min(H0)}),j0=Q.object({type:Q.literal("LAST_N_HOURS"),lastN:Q.number().min(1).max(NT*24)}),V0=Q.object({type:Q.literal("LAST_N_DAYS"),lastN:Q.number().min(1).max(NT)}),Hp=Q.discriminatedUnion("type",[G0,j0,V0]),W0=Q.object({flakeRateThreshold:Q.number().min(1).max(100),evaluationWindow:Hp}),$0=zp.extend({type:Q.literal("FLAKE_RATE"),config:W0}),q0=Q.object({passRateThreshold:Q.number().min(1).max(100),evaluationWindow:Hp}),K0=zp.extend({type:Q.literal("PASS_RATE"),config:q0}),Y0=Q.object({failureCountThreshold:Q.number().min(0),evaluationWindow:Hp}),X0=zp.extend({type:Q.literal("FAILURE_COUNT"),config:Y0}),$ne=Q.discriminatedUnion("type",[$0,K0,X0]);import{z as qe}from"zod";var Yne=qe.object({repositoriesIndexed:qe.boolean(),indexingInProgress:qe.boolean(),indexesOutdated:qe.boolean()}),DT=(a=>(a.Queued="queued",a.InProgress="in_progress",a.Completed="completed",a.Waiting="waiting",a.Requested="requested",a.Pending="pending",a))(DT||{}),UT=(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))(UT||{}),Xne=qe.object({name:qe.string(),status:qe.nativeEnum(DT),conclusion:qe.nativeEnum(UT).nullable()}),Ba=qe.object({sha:qe.string(),message:qe.string(),author:qe.object({name:qe.string().optional(),email:qe.string().optional(),date:qe.coerce.date().optional()}),committer:qe.object({name:qe.string().optional(),email:qe.string().optional(),date:qe.coerce.date().optional()})}),Gp=qe.object({mergedBranch:qe.string().optional()});import{z as Be}from"zod";var FT=Be.object({orgId:Be.string(),cacheKeys:Be.string().array()}),Qne=Be.object({keyParams:FT,clientMetadata:Be.string(),lockAcquisitionTimeoutMs:Be.number().optional()}),BT=Be.object({acquired:Be.boolean(),acquiredByMetadata:Be.string(),keyPrefix:Be.string()}),eoe=Be.object({keyPrefix:Be.string(),result:Be.string(),ttlMs:Be.number()}),toe=Be.union([Be.object({keyPrefix:Be.string()}),FT]),J0=Be.object({remainingTtlMs:Be.number(),value:Be.string().nullish()}),roe=Be.object({results:Be.record(Be.string(),J0),activeLocks:Be.string().array()});var noe=5*60*1e3;var soe=90*24*60*60*1e3,loe=7*24*60*60*1e3;import{z as zT}from"zod";var doe=zT.object({quarantineNotifications:zT.string().nullish()});import{z as gt}from"zod";var Z0=gt.object({version:gt.string(),json:gt.record(gt.unknown()),hash:gt.string()}),HT=gt.record(gt.unknown()),hoe=gt.object({newSvgs:gt.array(Z0),metadata:HT.optional()}),Q0=gt.object({version:gt.string(),json:gt.record(gt.unknown()).nullish(),hash:gt.string(),description:gt.string().nullish(),metadata:HT.nullish()}),GT=gt.record(gt.string().describe("icon hash"),Q0);import{z as Ge}from"zod";var jp=Ge.object({assertion:Ge.string().describe("A human readable assertion that evaluates to either true or false depending on the state of the system.")}),ek=Ge.object({instruction:Ge.string().describe("Human readable instruction to execute the step. Instructions should only describe concrete actions that need to be taken. Any checks or assertions should be described in the preConditions, postConditions, or expectedResults."),expectedResults:jp.array().optional().describe("Human readable description of the expected results after the step is executed. Each expected result should contain a single assertion that evaluates to true or false.")}),jT=ek.extend({subSteps:Ge.lazy(()=>jT.array().optional()).describe("More granular steps to be take to achieve the current step's higher level objective.")}),VT=Ge.object({name:Ge.string().describe("Short name describing the test plan"),description:Ge.string().nullish().transform(r=>r??void 0).describe("Longer form description of the high level goal of the test plan")}),WT=VT.extend({id:Ge.string(),createdAt:Ge.coerce.date(),updatedAt:Ge.coerce.date(),updatedBy:Ge.string(),createdBy:Ge.string(),test:Ge.object({id:Ge.string(),name:Ge.string()}).nullish().transform(r=>r??void 0)}),boe=WT.extend({testGenRuns:Ge.tuple([]).or(Ge.tuple([Ge.object({id:Ge.string(),startedAt:Ge.coerce.date(),status:Ge.nativeEnum(Ae)})]))}),$T=Ge.object({preConditions:jp.array().nullish().transform(r=>r??[]),postConditions:jp.array().nullish().transform(r=>r??[]),steps:jT.array().nullish().transform(r=>r??[])}),Eoe=WT.extend({plan:$T.nullish().transform(r=>r??{preConditions:[],postConditions:[],steps:[]})}),tk=VT.extend({plan:$T.nullish().transform(r=>r??{preConditions:[],postConditions:[],steps:[]})}),Toe=tk.array().nullish().transform(r=>r??[]);import{validator as rk}from"@exodus/schemasafe";function qT(r){let e;try{e=JSON.parse(r)}catch(t){return`The schema is not valid JSON. ${t}`}try{rk(e)}catch(t){return`The schema is not a valid JSON schema. ${t}`}}var KT=r=>{r.extraHeaders&&(r.extraHeaders=Object.fromEntries(Object.entries(r.extraHeaders).filter(([e,t])=>e.trim()&&t.trim())))};var nc=class{async prepareGoldenScreenshotForComparison(e,t,n){return n}};import{z as Foe}from"zod";var oc=class{async resolveEntries(){}async saveEntries(){}};import{z as Vp}from"zod";var YT=Vp.object({parentStepIdChain:Vp.array(Vp.string()),result:Er});import{z as Z}from"zod";var nk=Z.object({step:ot,status:Z.nativeEnum(it),startedAt:Z.coerce.date(),finishedAt:Z.coerce.date().optional(),healMetadata:Z.object({healType:Z.nativeEnum(wa).or(Z.literal("AI")),healedAt:Z.coerce.date()}).optional(),beforeSnapshotId:Z.string().uuid().optional(),afterSnapshotId:Z.string().uuid().optional(),message:Z.string().optional()}),ok=nk.extend({finishedAt:Z.coerce.date().optional().transform(r=>r??new Date)}),rie=ok.extend({step:Z.unknown()}),XT="1.0.0",Wp=TT.extend({id:Z.string().uuid().optional(),startedAt:Z.coerce.date(),runAttemptSchemaVersion:Z.string().optional(),schemaVersion:Z.string().optional().default("1.0.19"),results:Z.record(Z.string(),Z.unknown()).array().optional(),beforeResults:Z.record(Z.string(),Z.unknown()).array().optional(),afterResults:Z.record(Z.string(),Z.unknown()).array().optional()}),JT=Wp.extend({finishedAt:Z.coerce.date().optional().transform(r=>r??new Date)}),nie=Wp.merge(Ra),oie=JT.merge(Ra),ZT=Z.object({results:Z.array(Er),beforeResults:Z.array(Er).optional(),afterResults:Z.array(Er).optional()}),iie=Wp.merge(ZT),aie=JT.merge(ZT),ik=ET.merge(yT).extend({executionType:Z.nativeEnum(ri).optional().default("WEB"),testId:Z.string().uuid(),testDescription:Z.string().optional(),runGroupId:Z.string().uuid(),status:Z.nativeEnum(Ae),startedAt:Z.coerce.date(),attempts:Z.number(),failureRecoveryDetails:Z.record(Z.unknown()).optional()}),sie=ik.extend({finishedAt:Z.coerce.date().optional().transform(r=>r??new Date)}),ak=fT.merge(ST).extend({id:Z.string().uuid().optional(),startedAt:Z.coerce.date(),cliVersion:Z.string(),labels:Z.string().array().optional().default([])}),za=ak.extend({updatedAt:Z.coerce.date().optional().transform(r=>r??new Date),finishedAt:Z.coerce.date().optional().transform(r=>r??new Date)});import{fileURLToPath as dk}from"url";var tv,pk=dk(import.meta.url),mk=lk(pk);tv=uk(mk,"..");var Ha=tv;x.info(`Setting APPIUM_HOME to ${Ha}`);process.env.APPIUM_HOME=Ha;var gk="If you do not have Java installed, please download the JDK 24 from https://www.oracle.com/java/technologies/downloads/, move it to your home directory, and then set the JAVA_HOME environment variable in your shell profile to the JDK path.",hk="If you do not have Android Studio installed, please download it first from https://developer.android.com/studio and then follow all setup instructions in the Android Studio app.",fk="Follow the instructions at https://developer.android.com/tools/variables to set the ANDROID_HOME environment variable.",rv="On Mac OS, the SDK is typically installed at /Users/<username>/Library/Android/sdk.",nv="On Windows, the SDK is typically installed at C:\\Users\\<username>\\AppData\\Local\\Android\\Sdk.";function Sk(){if(!process.env.JAVA_HOME)x.warn("JAVA_HOME is not set. Some Appium drivers and Android tools may not work as expected.");else{process.platform==="darwin"&&/\.jdk\/?$/.test(process.env.JAVA_HOME)&&x.warn("JAVA_HOME appears to point at a *.jdk bundle, which is incorrect. The correct path should be formatted like '<bundle>/Contents/Home'.");let e=((t,n)=>ck(t,"bin",process.platform==="win32"?`${n}.exe`:n))(process.env.JAVA_HOME,"java");sk(e)||x.warn(`JAVA_HOME does not appear to point to a valid Java installation: expected the 'java' binary to exist at ${e}`)}try{QT("java --version",{stdio:"pipe",encoding:"utf-8"})||(x.error(`Could not find a Java installation. ${gk}`),process.exit(1))}catch(r){x.error(`Got error while checking if the Java JDK is installed: ${r}`),process.exit(1)}}function yk(){process.env.ANDROID_HOME||(x.error(`The ANDROID_HOME environment variable is not set. ${fk} ${ev()==="darwin"?rv:nv}`),process.exit(1))}function bk(){let r=process.env.ANDROID_HOME?`${process.env.ANDROID_HOME}/platform-tools/adb`:"adb";try{QT(`${r} version`,{stdio:"pipe",encoding:"utf-8"})||(x.error(`Could not find the Android Debug Bridge (ADB) tool locally. This tool is included with Android Studio. ${hk} Finally, ensure that the 'adb' command is available in your shell. ${ev()==="darwin"?rv:nv}`),process.exit(1))}catch(e){x.error(`Got error while checking if ADB is installed: ${e}`),process.exit(1)}}function ov(){Sk(),yk(),bk()}import{create as Ek,windowedFiniteBatchScheduler as Tk}from"@yornaath/batshit";import vk from"ws";var Ak=100,wk=2500,iv=4e3,Rk="\u2026";async function ic({driver:r,onLogs:e}){await r.execute("mobile: startLogsBroadcast");let t=Ek({fetcher:async l=>{e(l)},resolver:()=>{},scheduler:Tk({windowMs:wk,maxBatchSize:Ak})}),{hostname:n="localhost",port:o=4723,protocol:i="http"}=r.options,s=`${i==="https"?"wss":"ws"}://${n}:${o}/ws/session/${r.sessionId}/appium/device/logcat`,c=new vk(s);return c.on("message",l=>{let u=l.toString().trim();u.length!==0&&(u.length>iv&&(u=u.slice(0,iv)+Rk),t.fetch(u).catch(()=>{}))}),async()=>{try{c.close()}catch{}try{await r.execute("mobile: stopLogsBroadcast")}catch{}}}import{Server as IB}from"socket.io";import{randomUUID as Dk}from"crypto";import{faker as Ck}from"@faker-js/faker";import xk from"assert";import _k from"axios";import*as Mk from"child_process";import Ik from"moment";import*as Pk from"otpauth";import Ok from"pg";var Cn=class extends Error{constructor(e){super(e),this.name="TimeoutError"}};var av=r=>{let e=r.reason===void 0?new DOMException("This operation was aborted.","AbortError"):r.reason;return e instanceof Error?e:new DOMException(e,"AbortError")};function V(r,e){let{milliseconds:t,fallback:n,message:o,customTimers:i={setTimeout,clearTimeout}}=e,a;if(typeof t!="number"||Math.sign(t)!==1)throw new TypeError(`Expected \`milliseconds\` to be a positive number, got \`${t}\``);return new Promise((s,c)=>{let l;if(e.signal){let{signal:p}=e;if(p.aborted)return c(av(p));l=()=>c(av(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 r.cancel=="function"&&Promise.resolve().then(()=>r.cancel()).catch(()=>{});let p=o instanceof Error?o:new Cn(o??`Promise timed out after ${t}ms`);c(p)}};t<1/0&&(a=i.setTimeout(u,t));let d=()=>{i.clearTimeout(a),e.signal&&e.signal.removeEventListener("abort",l)};Promise.resolve(r).then(p=>{d(),s(p)}).catch(p=>{d(),c(p)})})}async function sv(r){let e;try{e=new URL(r.url).hostname}catch{}let t=[];return r.headers.getSetCookie()?.forEach(n=>{let o=Ul(n,e);t.push(...o)}),t}function Lk(r,e){if(!r&&!e)return;let t;if(r){let{url:o,options:i}=r;t=new Request(o,i)}let n;if(e){let{body:o,options:i}=e;n=new Response(o??null,i)}return{request:t,response:n}}async function Nk(r,e){switch(r){case"RAW":return e;case"RESPONSE":if(e instanceof Response){let t=[];return e.headers.forEach((o,i)=>{t.push([i,o])}),{status:e.status,headers:t,body:await e.text()}}else throw new Error("Result is not a Response object")}}var kk=Object.getPrototypeOf(async function(){}).constructor;async function lv(r,e,t){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=(A,C)=>{o[A]=C,l[A]=C},d={},p=(A,C)=>{o[A]=C,d[A]=C},g;n.includes("Octokit")&&(g=(await import("@octokit/rest")).Octokit);let m;n.includes("createAppAuth")&&(m=(await import("@octokit/auth-app")).createAppAuth);let h=async()=>await Promise.resolve(new kk("axios","moment","faker","assert","pg","Octokit","createAppAuth","OTPAuth","child_process","extractCookiesFromResponse","env","setVariable","setPersistentVariable","sendSms","waitForLatestSms","email","sms","ai","mock",...Object.keys(i??{}),n)(_k,Ik,c.fakerInstance??Ck,xk,Ok,g,m,Pk,Mk,sv,o,e.options.disallowVariableUpdates?void 0:u,e.options.disallowVariableUpdates?void 0:p,C=>c.sms.send(C),C=>c.sms.fetchLatest(C),c.email,c.sms,c.ai,Lk(a,s),...Object.values(i??{}))),f=!0,E,S;try{let A=await V(h(),{milliseconds:e.options.timeoutMs,message:`Timeout of ${e.options.timeoutMs}ms exceeded for code execution`,signal:e.signal});E=await Nk(e.options.responseSerialization??"RAW",A)}catch(A){t.error({err:A,env:o,evalCode:n},`[${r}] Error executing code: ${A}`),f=!1,A instanceof Cn?S=`Timeout of ${e.options.timeoutMs}ms exceeded for code execution`:S=A instanceof Error?A.message:`${A}`}return{result:E,variableUpdates:l,persistentVariableUpdates:d,success:f,error:S}}async function cv({code:r,fragment:e,context:t,localTools:n,logger:o,signal:i,timeoutMs:a=Tn,disallowVariableUpdates:s,additionalBindings:c,responseSerialization:l,mock:u}){let d=Dk(),p=await lv(d,{code:r,options:{fragment:e,timeoutMs:a,disallowVariableUpdates:s,responseSerialization:l},bindings:{...t.toObjectCopy(),...u,additionalBindings:c},tools:n,signal:i},o);return x.debug(`[${d}] Got execution result: ${JSON.stringify(p)}`),p}import{createHmac as Uk,randomUUID as Fk}from"crypto";import Bk from"fetch-retry";var zk=Bk(global.fetch,{retries:3,retryOn:function(r,e,t){return!!(e!==null||t&&t.status>=500)},retryDelay:function(r){return Math.pow(2,r)*500}}),uv=process.env.GCP_JS_EVAL_FUNCTION_ENDPOINT,dv=process.env.MOMENTIC_LAMBDA_AUTH_SECRET;async function pv({orgId:r,code:e,fragment:t,context:n,timeoutMs:o=Tn,retries:i=2,signal:a,logger:s,additionalBindings:c,disallowVariableUpdates:l,responseSerialization:u,mock:d}){if(!uv)throw new Error("GCP_JS_EVAL_FUNCTION_ENDPOINT environment variable not set");let p,g,m=0;if(!dv)throw new Error("Missing lambda auth secret.");let h=Uk("sha256",dv).update(r).digest("hex");for(;m<=i;){m++,a?.throwIfAborted();let E={id:Fk(),orgId:r,momenticLambdaAuthHash:h,code:e,fragment:t,state:{...n.toObjectCopy(),...d,additionalBindings:c},timeoutMs:o,disallowVariableUpdates:l,responseSerialization:u};try{if(p=await V(zk(uv,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(E)}),{milliseconds:o,message:`Timeout of ${o}ms exceeded for code execution`,signal:a}),!p)throw new Error("Got empty response from code evaluation server");if(!p.ok)throw new Error(`Code evaluation server returned error code ${p.status}`);g=void 0;break}catch(S){g=S}}if(g)throw s.error({err:g},"Failed to evaluate code remotely"),g;if(!p)throw new Error(`An unexpected code evaluation error occurred${g?`: ${g}`:""}`);let f;try{f=OE.parse(await p.json())}catch(E){throw new Error(`Code evaluation server returned invalid response: ${E}`)}if(f.error)throw new Error(`Code evaluation error: ${f.error}`);return f}async function kr(r){let e;if(process.env.GCP_JS_EVAL_FUNCTION_ENDPOINT)e=await pv(r);else if(r.localTools)e=await cv({...r,localTools:r.localTools});else throw new Error("No code evaluation environment available");if(e.error){let t=`Failed to evaluate code:
|
|
17
|
+
`),console.log(t(` ${l}:`,s))):console.log(t(` ${l}:`,s))}}else if(o)for(let a of o){let l=a;typeof a=="object"&&(l=Do(a,void 0,2),l=l.split(`
|
|
18
|
+
`).map((c,s)=>s>0?` ${c}`:c).join(`
|
|
19
|
+
`)),console.log(" ",t(l))}}getLevel(){return Ws[this.minLogLevel]}setMinLevel(e){typeof e=="string"?this.minLogLevel=sa[e]:this.minLogLevel=e}log(...e){this.logWithLevel(30,wr.reset,...e)}info(...e){this.logWithLevel(30,wr.white,...e)}debug(...e){this.logWithLevel(20,wr.dim,...e)}warn(...e){this.logWithLevel(40,wr.yellow,...e)}error(...e){this.logWithLevel(50,wr.red,...e)}success(...e){this.logWithLevel(1/0,wr.green,...e)}dimmed(...e){this.logWithLevel(30,wr.dim,...e)}underline(...e){this.logWithLevel(40,wr.underline,...e)}bold(...e){this.logWithLevel(40,wr.bold,...e)}grey(...e){this.logWithLevel(20,wr.grey,...e)}child(e){return new r(this.minLogLevel,{...this.logBindings,...e})}flush(){}bindings(){return this.logBindings}},fd=class{debug(){}info(){}warn(){}error(){}success(){}dimmed(){}underline(){}bold(){}grey(){}child(){return this}getLevel(){return"error"}flush(){}bindings(){return{}}},I4=new fd,KI=typeof window>"u"&&typeof process<"u"&&js.safeParse(process?.env?.MOMENTIC_DEV_LOG_LEVEL).success?js.parse(process.env.MOMENTIC_DEV_LOG_LEVEL):30,A=new hd(KI,{}),un={info:()=>{},error:()=>{},debug:()=>{},warn:()=>{},child:()=>un,flush:()=>{},bindings:()=>({}),getLevel:()=>"error"},Vs={},$s=({logger:r,logKey:e,maxCount:t,intervalMs:n},o,i,...a)=>{let l=Vs[e];l?clearTimeout(l.timer):(l={count:0,totalCount:0},Vs[e]=l),l.totalCount++,l.count<t&&(l.count++,r.debug(o,i,...a)),l.timer=setTimeout(()=>{let c=Vs[e];c?.totalCount!==c?.count&&r.debug({logKey:e,totalCount:c?.totalCount,count:c?.count},`Debug logs were rate-limited for ${e}`),delete Vs[e]},n)};import{z as be}from"zod";var YI=be.array(No.extend({id:be.string(),name:be.string(),description:be.string().optional(),labels:be.string().array().optional()})),XI=be.array(No.extend({id:be.string(),name:be.string(),description:be.string().optional(),content:Gi})),vS=be.object({name:be.string(),description:be.string().optional(),settings:aa.optional(),pathSegments:be.string().array()}),k4=be.object({id:be.string(),fileName:be.string(),fullPath:be.string(),relativeFilePath:be.string().describe("relative to project root")});var AS=be.object({steps:ia.array().optional(),settings:aa.optional()}),U4=be.object({message:be.literal("ok")}),wS=be.object({tag:be.string(),channel:be.string(),filePath:be.string()}),F4=be.object({tests:YI,modules:XI,labels:be.string().array()}),RS=be.object({name:be.string(),description:be.string(),enabled:be.boolean()}).partial();import{z as $e}from"zod";var CS=$e.object({id:$e.string(),createdAt:$e.coerce.date(),createdBy:$e.string(),organizationId:$e.string(),name:$e.string(),description:$e.string().nullish(),enabled:$e.boolean(),schemaVersion:$e.string().describe("Schema version for steps"),parameters:$e.string().array().nullish().describe("Parameter list"),parameterEnums:$e.record($e.string(),$e.string().array()).nullish(),defaultParameters:$e.record($e.string(),$e.string()).nullish(),defaultCacheKey:$e.string().nullish(),defaultCacheTtl:$e.number().nullish(),defaultCacheAllInvocations:$e.boolean().nullish(),autoAuth:$e.boolean().nullish(),advanced:Pu.nullish()}),q4=CS.extend({steps:$e.lazy(()=>xt.array())}),K4=5*60*1e3,JI=Kt.merge(CS.omit({id:!0,createdAt:!0,createdBy:!0,organizationId:!0,enabled:!0}));import{formatInTimeZone as J4}from"date-fns-tz";import{z as _e}from"zod";var Sd=$u.extend({aiAction:_e.boolean().optional(),stepLintSuggestions:_e.boolean().optional(),agentConfig:_e.record(_e.string(),_e.string()).optional(),aiFailureAnalysis:_e.boolean().optional(),aiPageFiltering:_e.boolean().optional().describe("rag v2 feature flag")}),yd=_e.object({fakerConstantSeed:_e.boolean().optional()}),n3=_e.object({ai:Sd.optional(),githubAppInstallationId:_e.number().nullish(),githubAppSummaryMessageEnabled:_e.boolean().nullish(),githubReleaseAppInstallationId:_e.number().nullish(),gitlabAppAccessToken:_e.string().nullish(),gitlabAppBaseUrl:_e.string().nullish(),qaseAccessToken:_e.string().nullish(),testSuggestionsEnabled:_e.boolean().nullish(),browser:Bu.optional(),advanced:yd.optional()}),o3=_e.object({globalOverrides:_e.record(_e.string()).optional(),agentConfig:_e.record(_e.string(),_e.string()).optional()}),i3=_e.record(_e.string(),_e.string()).nullish();import*as S from"zod";import{z as Ve}from"zod";var bd=(e=>(e.TEST_REVIEW="TEST_REVIEW",e))(bd||{});var ZI=Ve.object({type:Ve.literal("DESCRIPTION_UPDATE"),thoughts:Ve.string()}),qs=Ve.discriminatedUnion("type",[ZI]),QI=Ve.object({testId:Ve.string(),name:Ve.string(),orgId:Ve.string(),runId:Ve.string(),steps:ot.array(),purpose:Ve.nativeEnum(bd),details:qs.or(qs.array()).optional()});var c3=QI.pick({name:!0,orgId:!0}),eP=Ve.object({id:Ve.string(),name:Ve.string().nullish(),createdAt:Ve.string().pipe(Ve.coerce.date()).or(Ve.date()),organizationId:Ve.string(),schemaVersion:Ve.string(),runId:Ve.string().nullish(),purpose:Ve.nativeEnum(bd),details:qs.or(qs.array()).optional(),applied:Ve.boolean().nullish(),appliedAt:Ve.coerce.date().nullish()}),xS=eP.extend({steps:ot.array()});var Ks="x-momentic-cli-version",MS="x-momentic-cli-type",_S="x-momentic-logger-tags",tP="x-momentic-main-branch-name",rP="x-momentic-branch-name",nP="x-momentic-commit-timestamp",oP="x-momentic-last-commit-on-main",iP="x-momentic-last-commit-on-main-timestamp",aP="x-momentic-merged-branch-name",IS="x-momentic-session-id",C3=S.object({error:S.boolean(),reason:S.string(),message:S.string()}),x3=yt.merge(Yu),PS=ls,M3=yt.merge(Yu);var _3=yt.merge(wf).extend({useConsensus:S.boolean().optional(),attemptNumber:S.number().optional()}),Ed=Bg,I3=yt.merge(Cf),OS=$h,P3=yt.merge(Rf),LS=Wh,O3=yt.merge(Tf),NS=Vh,L3=yt.merge(vf),DS=Hh,N3=yt.merge(Af);var D3=yt.merge(If),k3=S.object({testPaths:S.string().array().describe("can be either hyphenated, lowercase test names or UUIDs"),env:S.string().optional(),all:S.boolean().optional(),urlOverride:S.string().optional(),customHeaders:S.record(S.string(),S.string()).optional(),testInputMatrix:S.record(S.string(),S.string()).array().optional()}),kS=S.object({queuedTests:S.unknown().array(),runIds:S.string().uuid().array(),runGroupId:S.string().optional()});var U3=S.string().array(),F3=S.union([S.object({paths:S.string().array().describe("run specific test paths (e.g. todo-test)"),all:S.boolean().describe("run all tests").optional()}),S.object({path:S.string().describe("deprecated; present for backcompat")})]),US=S.object({tests:S.record(S.string().describe("Test name"),S.string().describe("Test YAML")),modules:S.record(S.string().describe("Module name"),S.string().describe("Module YAML"))}),sP=S.object({test:S.string().describe("test YAML"),modules:S.record(S.string().describe("moduleId"),S.string().describe("module YAML"))}),B3=sP.array(),z3=S.object({testId:S.string(),schemaVersion:S.string()}).merge(On);function Td(r){let{gitMainBranch:e,gitBranchName:t,gitCommitTimestamp:n,lastCommitOnMainSha:o,lastCommitOnMainTimestamp:i}=r,a={};return e&&(a[tP]=encodeURIComponent(e)),t&&(a[rP]=encodeURIComponent(t)),n&&(a[nP]=n.toISOString()),o&&(a[oP]=encodeURIComponent(o)),i&&(a[iP]=i.toISOString()),r.mergedGitBranchName&&(a[aP]=encodeURIComponent(r.mergedGitBranchName)),a}var H3=S.object({entries:S.array(th),testId:S.string()}),G3=S.object({entries:S.array(Xf),testId:S.string()}),V3=S.object({testId:S.string()});function FS(r){return S.record(S.unknown()).transform(e=>{let t={};for(let[n,o]of Object.entries(e)){let i=r.safeParse(o);i.success&&(t[n]=i.data)}return t})}var BS=FS(rh),zS=FS(Jf),HS=S.object({trigger:S.nativeEnum(Jt),status:S.nativeEnum(ve),startedAt:S.coerce.date().optional(),gitCommitSha:S.string().optional(),gitCommitShaShort:S.string().optional(),gitCommitTimestamp:S.coerce.date().optional(),gitBranchName:S.string().optional(),gitOriginUrl:S.string().optional(),gitCommitMessage:S.string().optional(),gitCommitAuthorName:S.string().optional(),githubRepository:S.string().optional(),gitlabProjectPath:S.string().optional(),pipelineId:S.string().optional(),cliVersion:S.string().optional()}),j3=S.object({id:S.string()}),GS=S.object({status:S.nativeEnum(ve),updatedAt:S.coerce.date().optional(),finishedAt:S.coerce.date().optional()}),VS=S.object({stepsSnapshot:S.array(S.record(S.unknown())).optional(),runGroupId:S.string().optional(),testId:S.string(),testName:S.string(),resolvedBaseUrl:S.string().optional(),environmentName:S.string().optional(),labels:S.array(S.string()).optional(),cliVersion:S.string().optional(),trigger:S.nativeEnum(Jt),schemaVersion:S.string().optional(),section:S.nativeEnum(Rs).optional(),resolvedInputs:S.record(S.string(),S.string()).optional(),quarantined:S.boolean().optional().default(!1),quarantinedReason:S.string().optional()}),W3=S.object({id:S.string()}),lP=qu.pick({id:!0,status:!0,testName:!0,testId:!0,test:!0,failureReason:!0,failureDetails:!0}),jS=lP.array(),WS=qu.pick({startedAt:!0,finishedAt:!0,updatedAt:!0,results:!0,beforeResults:!0,afterResults:!0,status:!0,failureDetails:!0,failureReason:!0,resolvedBaseUrl:!0,environmentName:!0,labels:!0,cliVersion:!0,resolvedInputs:!0,attempts:!0,flake:!0}).partial(),$3=S.object({id:S.string()}),$S=S.object({status:S.nativeEnum(ve),finishedAt:S.coerce.date().optional(),schemaVersion:S.string().optional().default("1.0.19"),results:S.record(S.string(),S.unknown()).array().optional(),beforeResults:S.record(S.string(),S.unknown()).array().optional(),afterResults:S.record(S.string(),S.unknown()).array().optional()}),q3=S.object({screenshot:S.string()}),qS=S.object({key:S.string()}),KS=S.object({orgId:S.string(),userId:S.string()}),YS=S.array(nf),K3=S.record(S.string(),S.union([S.string(),S.boolean()])),Y3=S.object({paths:S.string().array(),env:S.string().optional(),urlOverride:S.string().optional(),customHeaders:S.record(S.string(),S.string()).optional()}),XS=S.object({suiteRunIds:S.string().array(),runGroupIds:S.string().array()}),X3=S.object({suiteRunIds:S.string().array()}),J3=Sf.array(),Z3=S.object({runGroupIds:S.string().array()}),cP=S.object({uploadUrl:S.string()}),Q3=yt.merge(xf),eJ=yt.merge(_f),tJ=yt.merge(Mf),uP=S.object({testId:S.string().optional().default(""),testName:S.string().optional().default(""),suiteId:S.string().optional().default(""),suiteName:S.string().optional().default(""),creditsUsed:S.number().optional()}),dP=S.object({transactionId:S.string(),timestamp:S.string(),event:S.nativeEnum(Xi),properties:uP}),rJ=dP.array(),JS=xS.omit({steps:!0}).extend({steps:S.array(S.record(S.string(),S.unknown())).describe("unparsed ResolvedStep[]")}),nJ=S.object({limit:S.number().max(10).optional(),afterTime:S.number().optional()}),ZS=gf.array(),oJ=S.object({applied:S.boolean().optional(),appliedAt:S.coerce.date().optional()}),QS=cP.extend({id:S.string()}),iJ=S.object({runGroupId:S.string().uuid().optional()}),ey=S.object({runGroupId:S.string().uuid()}),ty=S.object({quarantined:S.object({testId:S.string().uuid(),quarantinedAt:S.coerce.date(),quarantinedBy:S.string().optional(),quarantinedReason:S.string()}).array()}),aJ=S.object({testId:S.string().uuid(),testName:S.string().optional(),reason:S.string(),gitLocalUsername:S.string().optional(),gitLocalEmail:S.string().optional(),gitLocalName:S.string().optional()}),sJ=S.object({testName:S.string().optional(),reason:S.string().optional(),gitLocalUsername:S.string().optional(),gitLocalEmail:S.string().optional(),gitLocalName:S.string().optional()}),lJ=yt.merge(Nf),cJ=yt.merge(Df),uJ=S.object({apkToInstall:S.object({channel:S.string(),tag:S.string().optional()}).optional(),hostname:S.string().optional(),region:S.nativeEnum(Qi).optional()}),ry=S.object({name:S.string(),webRtcUrl:S.string(),adbUrl:S.string(),token:S.string(),apkDownloadUrl:S.string().optional(),region:S.string().optional()}),dJ=S.object({channel:S.string(),tag:S.string(),md5:S.string()}),ny=S.object({id:S.string(),uploadUrl:S.string().optional(),downloadUrl:S.string(),md5:S.string().optional()}),oy=S.object({assets:S.array(S.object({channel:S.string(),tag:S.string(),md5:S.string(),createdAt:S.number().describe("Unix timestamp in milliseconds")}))});import{z as K}from"zod";var iy=7,pP=3,gJ=K.object({localTestId:K.string(),quarantinedAt:K.date(),quarantinedBy:K.string().optional(),quarantinedReason:K.string(),quarantinedByGitEmail:K.string().optional(),quarantinedByGitName:K.string().optional(),quarantinedByGitUsername:K.string().optional()}).or(K.object({cloudTestId:K.string(),quarantinedAt:K.date(),quarantinedBy:K.string().optional(),quarantinedReason:K.string(),quarantinedByGitEmail:K.string().optional(),quarantinedByGitName:K.string().optional(),quarantinedByGitUsername:K.string().optional()})),ay=(t=>(t.QUARANTINE="QUARANTINE",t.UNQUARANTINE="UNQUARANTINE",t))(ay||{});var vd=K.object({name:K.string(),description:K.string().nullish(),effect:K.nativeEnum(ay),labels:K.array(K.string()).nullish(),githubRepository:K.string().nullish(),gitlabProjectPath:K.string().nullish(),gitBranchName:K.string().nullish()}),mP=K.object({type:K.literal("LAST_N_RUNS"),lastN:K.number().min(pP)}),gP=K.object({type:K.literal("LAST_N_HOURS"),lastN:K.number().min(1).max(iy*24)}),hP=K.object({type:K.literal("LAST_N_DAYS"),lastN:K.number().min(1).max(iy)}),Ad=K.discriminatedUnion("type",[mP,gP,hP]),fP=K.object({flakeRateThreshold:K.number().min(1).max(100),evaluationWindow:Ad}),SP=vd.extend({type:K.literal("FLAKE_RATE"),config:fP}),yP=K.object({passRateThreshold:K.number().min(1).max(100),evaluationWindow:Ad}),bP=vd.extend({type:K.literal("PASS_RATE"),config:yP}),EP=K.object({failureCountThreshold:K.number().min(0),evaluationWindow:Ad}),TP=vd.extend({type:K.literal("FAILURE_COUNT"),config:EP}),hJ=K.discriminatedUnion("type",[SP,bP,TP]);import{z as qe}from"zod";var yJ=qe.object({repositoriesIndexed:qe.boolean(),indexingInProgress:qe.boolean(),indexesOutdated:qe.boolean()}),sy=(a=>(a.Queued="queued",a.InProgress="in_progress",a.Completed="completed",a.Waiting="waiting",a.Requested="requested",a.Pending="pending",a))(sy||{}),ly=(l=>(l.Success="success",l.Failure="failure",l.Neutral="neutral",l.Cancelled="cancelled",l.Skipped="skipped",l.TimedOut="timed_out",l.ActionRequired="action_required",l))(ly||{}),bJ=qe.object({name:qe.string(),status:qe.nativeEnum(sy),conclusion:qe.nativeEnum(ly).nullable()}),la=qe.object({sha:qe.string(),message:qe.string(),author:qe.object({name:qe.string().optional(),email:qe.string().optional(),date:qe.coerce.date().optional()}),committer:qe.object({name:qe.string().optional(),email:qe.string().optional(),date:qe.coerce.date().optional()})}),wd=qe.object({mergedBranch:qe.string().optional()});import{z as Be}from"zod";var cy=Be.object({orgId:Be.string(),cacheKeys:Be.string().array()}),vJ=Be.object({keyParams:cy,clientMetadata:Be.string(),lockAcquisitionTimeoutMs:Be.number().optional()}),uy=Be.object({acquired:Be.boolean(),acquiredByMetadata:Be.string(),keyPrefix:Be.string()}),AJ=Be.object({keyPrefix:Be.string(),result:Be.string(),ttlMs:Be.number()}),wJ=Be.union([Be.object({keyPrefix:Be.string()}),cy]),vP=Be.object({remainingTtlMs:Be.number(),value:Be.string().nullish()}),RJ=Be.object({results:Be.record(Be.string(),vP),activeLocks:Be.string().array()});var CJ=5*60*1e3;var IJ=90*24*60*60*1e3,PJ=7*24*60*60*1e3;import{z as dy}from"zod";var NJ=dy.object({quarantineNotifications:dy.string().nullish()});import{z as pt}from"zod";var AP=pt.object({version:pt.string(),json:pt.record(pt.unknown()),hash:pt.string()}),py=pt.record(pt.unknown()),FJ=pt.object({newSvgs:pt.array(AP),metadata:py.optional()}),wP=pt.object({version:pt.string(),json:pt.record(pt.unknown()).nullish(),hash:pt.string(),description:pt.string().nullish(),metadata:py.nullish()}),my=pt.record(pt.string().describe("icon hash"),wP);import{z as He}from"zod";var Rd=He.object({assertion:He.string().describe("A human readable assertion that evaluates to either true or false depending on the state of the system.")}),RP=He.object({instruction:He.string().describe("Human readable instruction to execute the step. Instructions should only describe concrete actions that need to be taken. Any checks or assertions should be described in the preConditions, postConditions, or expectedResults."),expectedResults:Rd.array().optional().describe("Human readable description of the expected results after the step is executed. Each expected result should contain a single assertion that evaluates to true or false.")}),gy=RP.extend({subSteps:He.lazy(()=>gy.array().optional()).describe("More granular steps to be take to achieve the current step's higher level objective.")}),hy=He.object({name:He.string().describe("Short name describing the test plan"),description:He.string().nullish().transform(r=>r??void 0).describe("Longer form description of the high level goal of the test plan")}),fy=hy.extend({id:He.string(),createdAt:He.coerce.date(),updatedAt:He.coerce.date(),updatedBy:He.string(),createdBy:He.string(),test:He.object({id:He.string(),name:He.string()}).nullish().transform(r=>r??void 0)}),GJ=fy.extend({testGenRuns:He.tuple([]).or(He.tuple([He.object({id:He.string(),startedAt:He.coerce.date(),status:He.nativeEnum(ve)})]))}),Sy=He.object({preConditions:Rd.array().nullish().transform(r=>r??[]),postConditions:Rd.array().nullish().transform(r=>r??[]),steps:gy.array().nullish().transform(r=>r??[])}),VJ=fy.extend({plan:Sy.nullish().transform(r=>r??{preConditions:[],postConditions:[],steps:[]})}),CP=hy.extend({plan:Sy.nullish().transform(r=>r??{preConditions:[],postConditions:[],steps:[]})}),jJ=CP.array().nullish().transform(r=>r??[]);import{validator as xP}from"@exodus/schemasafe";function yy(r){let e;try{e=JSON.parse(r)}catch(t){return`The schema is not valid JSON. ${t}`}try{xP(e)}catch(t){return`The schema is not a valid JSON schema. ${t}`}}var by=r=>{r.extraHeaders&&(r.extraHeaders=Object.fromEntries(Object.entries(r.extraHeaders).filter(([e,t])=>e.trim()&&t.trim())))};var Ys=class{async prepareGoldenScreenshotForComparison(e,t,n){return n}};import{z as s6}from"zod";var Xs=class{async resolveEntries(){}async saveEntries(){}};import{z as Cd}from"zod";var Ey=Cd.object({parentStepIdChain:Cd.array(Cd.string()),result:tr});import{z as q}from"zod";var MP=q.object({step:ot,status:q.nativeEnum(Ge),startedAt:q.coerce.date(),finishedAt:q.coerce.date().optional(),healMetadata:q.object({healType:q.nativeEnum(ji).or(q.literal("AI")),healedAt:q.coerce.date()}).optional(),beforeSnapshotId:q.string().uuid().optional(),afterSnapshotId:q.string().uuid().optional(),message:q.string().optional()}),_P=MP.extend({finishedAt:q.coerce.date().optional().transform(r=>r??new Date)}),R6=_P.extend({step:q.unknown()}),Ty="1.0.0",xd=$S.extend({id:q.string().uuid().optional(),startedAt:q.coerce.date(),runAttemptSchemaVersion:q.string().optional(),schemaVersion:q.string().optional().default("1.0.19"),results:q.record(q.string(),q.unknown()).array().optional(),beforeResults:q.record(q.string(),q.unknown()).array().optional(),afterResults:q.record(q.string(),q.unknown()).array().optional()}),vy=xd.extend({finishedAt:q.coerce.date().optional().transform(r=>r??new Date)}),C6=xd.merge(Wi),x6=vy.merge(Wi),Ay=q.object({results:q.array(tr),beforeResults:q.array(tr).optional(),afterResults:q.array(tr).optional()}),M6=xd.merge(Ay),_6=vy.merge(Ay),IP=WS.merge(VS).extend({executionType:q.nativeEnum(Mo).optional().default("WEB"),testId:q.string().uuid(),testDescription:q.string().optional(),runGroupId:q.string().uuid(),status:q.nativeEnum(ve),startedAt:q.coerce.date(),attempts:q.number(),failureRecoveryDetails:q.record(q.unknown()).optional()}),I6=IP.extend({finishedAt:q.coerce.date().optional().transform(r=>r??new Date)}),PP=HS.merge(GS).extend({id:q.string().uuid().optional(),startedAt:q.coerce.date(),cliVersion:q.string(),labels:q.string().array().optional().default([])}),Js=PP.extend({updatedAt:q.coerce.date().optional().transform(r=>r??new Date),finishedAt:q.coerce.date().optional().transform(r=>r??new Date)});import OP from"fetch-retry";import LP from"os";import wy,{multistream as NP}from"pino";import DP from"pino-pretty";import kP from"pino-std-serializers";var ko=new Map,UP=!0,Ry="Log throttle exceeded",FP=100,BP=5e3,zP=OP(global.fetch,{retries:2,retryOn:function(r,e,t){return!!(e!==null||t&&t.status>=500)},retryDelay:function(r){return Math.pow(2,r)*500}}),Md=class r{consoleLogger;hostname;bindingAttributes;disableConsoleLogs;minLevelValue=20;logsInCurrentWindow=0;droppedLogsInWindow=!1;lastWindowStart=Date.now();site="https://ingest.us.signoz.cloud:443/logs/json";flushIntervalMs;maxBatchSize;buffer=[];flushTimer;constructor({bindings:e,hostname:t,disableConsoleLogs:n,flushIntervalMs:o,maxBatchSize:i}){this.hostname=t??LP.hostname(),this.disableConsoleLogs=n,this.bindingAttributes={...e,env:"production"},this.flushIntervalMs=o??5e3,this.maxBatchSize=i??10;let a={base:this.bindingAttributes,errorKey:"err",level:"debug"};this.consoleLogger=UP?wy(a):wy(a,NP([{stream:DP({colorize:!0})}]))}getLevel(){return Ws[this.minLevelValue]}child(e){return new r({bindings:{...this.bindingAttributes,...e},hostname:this.hostname,disableConsoleLogs:this.disableConsoleLogs,flushIntervalMs:this.flushIntervalMs,maxBatchSize:this.maxBatchSize})}flush(e){this.flushBuffer(),this.disableConsoleLogs||this.consoleLogger.flush(e)}scheduleFlush(){this.flushTimer||(this.flushTimer=setTimeout(()=>{this.flushTimer=void 0,this.flushBuffer()},this.flushIntervalMs))}async flushBuffer(){if(this.buffer.length===0)return;let e=this.buffer;this.buffer=[];try{let t=await zP(this.site,{method:"POST",headers:{"Content-Type":"application/json","signoz-access-token":"CumAaTMUcwjt05OddAmefKgshbhfRmWxzxih"},body:Do(e),signal:AbortSignal.timeout(5e3)});if(!t.ok)throw new Error(`Got error status (${t.statusText}) from SigNoz`)}catch(t){this.consoleLogger.warn({err:t},"Failed to log to SigNoz")}}shouldAllowLog(e){if(e===Ry)return!0;let t=Date.now();return t-this.lastWindowStart>BP&&(this.logsInCurrentWindow=0,this.droppedLogsInWindow&&this.log("error",void 0,Ry),this.droppedLogsInWindow=!1,this.lastWindowStart=t),this.logsInCurrentWindow<FP?(this.logsInCurrentWindow++,!0):(this.droppedLogsInWindow=!0,!1)}log(e,t,n,...o){try{this.logHelper(e,t,n,...o)}catch(i){this.consoleLogger.warn(`Failed to log to Signoz: ${i}`)}}logHelper(e,t,n,...o){if(sa[e]<this.minLevelValue||!this.shouldAllowLog(n))return;typeof t=="string"&&!n&&(t={message:t}),typeof t=="object"&&t&&"err"in t&&t.err instanceof Error&&(t.err=kP.err(t.err));let i={...this.bindingAttributes,...t&&typeof t=="object"?t:{},...o.length>0?{args:o}:{}},a={host:this.hostname,env:this.bindingAttributes.env};this.disableConsoleLogs||this.consoleLogger[e](i,n,...o);let l={timestamp:Math.round(Date.now()*1e6),severity_text:e.toUpperCase(),resources:a,attributes:{},body:TS({message:n||"",...i})};this.buffer.push(l),this.buffer.length>=this.maxBatchSize?(this.flushTimer&&(clearTimeout(this.flushTimer),this.flushTimer=void 0),this.flushBuffer()):this.scheduleFlush()}setApp(e){let t=this.bindingAttributes.app;this.bindingAttributes.app=e,ko.set("app",this),ko.delete(t)}debug(e,t,...n){this.log("debug",e,t,...n)}info(e,t,...n){this.log("info",e,t,...n)}warn(e,t,...n){this.log("warn",e,t,...n)}error(e,t,...n){this.log("error",e,t,...n)}bindings(){return this.bindingAttributes}addBinding(e,t){this.bindingAttributes[e]=t}setMinLevel(e){typeof e=="number"?(this.minLevelValue=e,this.consoleLogger.level=Ws[e]):(this.minLevelValue=sa[e],this.consoleLogger.level=e)}enableConsoleLogs(){this.disableConsoleLogs=!1}},Zs=({app:r,hostname:e,disableConsoleLogs:t})=>(ko.has(r)||ko.set(r,new Md({bindings:{app:r},hostname:e,disableConsoleLogs:t})),ko.get(r));function Cy(){for(let r of ko.values())r.flush()}import{PostHog as C9}from"posthog-node";var dn=class extends Error{constructor(e){super(e),this.name="TimeoutError"}};var xy=r=>{let e=r.reason===void 0?new DOMException("This operation was aborted.","AbortError"):r.reason;return e instanceof Error?e:new DOMException(e,"AbortError")};function B(r,e){let{milliseconds:t,fallback:n,message:o,customTimers:i={setTimeout,clearTimeout}}=e,a;if(typeof t!="number"||Math.sign(t)!==1)throw new TypeError(`Expected \`milliseconds\` to be a positive number, got \`${t}\``);return new Promise((l,c)=>{let s;if(e.signal){let{signal:p}=e;if(p.aborted)return c(xy(p));s=()=>c(xy(p)),p.addEventListener("abort",s,{once:!0})}let u=()=>{if(e.signal&&e.signal.removeEventListener("abort",s),n)try{l(n())}catch(p){c(p)}else{typeof r.cancel=="function"&&Promise.resolve().then(()=>r.cancel()).catch(()=>{});let p=o instanceof Error?o:new dn(o??`Promise timed out after ${t}ms`);c(p)}};t<1/0&&(a=i.setTimeout(u,t));let d=()=>{i.clearTimeout(a),e.signal&&e.signal.removeEventListener("abort",s)};Promise.resolve(r).then(p=>{d(),l(p)}).catch(p=>{d(),c(p)})})}import{PostHog as D9}from"posthog-node";import{execSync as HP}from"child_process";import Uo from"os";import GP from"v8";var zn=!!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 My,Rr,Iy=Uo.platform(),VP=Uo.cpus().map(r=>({model:r.model,speed:r.speed})).reduce((r,e)=>(r[e.model]={speed:e.speed},r.totalCores=(r.totalCores??0)+1,r),{}),_y=r=>{try{let e=!1,t=jP(),n=WP(),o=`${Math.round(t.freePercentage*100)}%`;t.freePercentage<.05&&(e=!0);let i=`${n?Math.round(n.idle):"unknown"}%`;n&&n?.total>70&&(e=!0);let a=GP.getHeapStatistics(),l=a.used_heap_size,c=a.heap_size_limit;l/c>.9&&(e=!0),e?(r.warn({memory:t,cpu:n,heapStats:a},"Critical resource usage metrics detected"),zn&&A.warn(`Low machine resources detected (memory: ${o} free, cpu: ${i} free)`)):r.debug({memory:t,cpu:n},"Got machine resource usage metrics")}catch{}};function Py(r){if(!cn)return _y(r),{interval:setInterval(()=>_y(r),2e4),cpuMetadata:VP,platform:Iy}}function jP(){let r=Uo.totalmem(),e=Iy==="darwin"?$P():(()=>{let n=Uo.freemem();return{availableMemory:n,rawFreeMemory:n,cachedMemory:0}})(),t=e.availableMemory/r;return{totalMemory:r,freeMemory:e.availableMemory,freePercentage:t}}function WP(){let r=Uo.cpus(),e=Date.now(),t={measurementTime:e,user:0,nice:0,sys:0,idle:0,irq:0,total:0};for(let o of r)t.user+=o.times.user,t.nice+=o.times.nice,t.sys+=o.times.sys,t.idle+=o.times.idle,t.irq+=o.times.irq;if(t.total=t.user+t.nice+t.sys+t.idle+t.irq,!Rr)return Rr=t,null;let n={user:t.user-Rr.user,nice:t.nice-Rr.nice,sys:t.sys-Rr.sys,idle:t.idle-Rr.idle,irq:t.irq-Rr.irq,total:t.total-Rr.total};return My={measurementTime:e,intervalMs:e-Rr.measurementTime,user:n.user/n.total*100,nice:n.nice/n.total*100,sys:n.sys/n.total*100,idle:n.idle/n.total*100,irq:n.irq/n.total*100,total:100-n.idle/n.total*100},Rr=t,My}function $P(){try{let r=HP("/usr/sbin/sysctl -n vm.page_free_count vm.page_inactive_count vm.page_speculative_count hw.pagesize",{encoding:"utf8",stdio:["pipe","pipe","ignore"]}).trim().split(/\s+/).map(l=>parseInt(l,10)),[e,t,n,o]=r;if(!e||!t||!n||!o)throw new Error("Failed to get darwin memory usage");let i=e*o,a=(t+n)*o;return{availableMemory:i+a,rawFreeMemory:i,cachedMemory:a}}catch{let r=Uo.freemem();return{availableMemory:r,rawFreeMemory:r,cachedMemory:0}}}var Qs=class{increment(e,t,n){}gauge(e,t){}distribution(e,t,n){}async flush(){}async recordDuration({fn:e}){return await e()}};function qP(r){if(!r||r.length===0)return{};let e={};for(let t of r){let n=t.indexOf(":");if(n>-1){let o=t.slice(0,n).trim(),i=t.slice(n+1).trim();o&&(e[o]=i);continue}e[t]=!0}return e}function el(r,e){let t=qP(r);return!e||Object.keys(e).length===0?t:{...e,...t}}var ob="=",ol=";",zd=",";var ib=8192;var Ho={};gC(Ho,{getKeyPairs:()=>CO,parseKeyPairsIntoRecord:()=>xO,parsePairKeyValue:()=>ab,serializeKeyPairs:()=>RO});Ce();var wO=function(r,e){var t=typeof Symbol=="function"&&r[Symbol.iterator];if(!t)return r;var n=t.call(r),o,i=[],a;try{for(;(e===void 0||e-- >0)&&!(o=n.next()).done;)i.push(o.value)}catch(l){a={error:l}}finally{try{o&&!o.done&&(t=n.return)&&t.call(n)}finally{if(a)throw a.error}}return i};function RO(r){return r.reduce(function(e,t){var n=""+e+(e!==""?zd:"")+t;return n.length>ib?e:n},"")}function CO(r){return r.getAllEntries().map(function(e){var t=wO(e,2),n=t[0],o=t[1],i=encodeURIComponent(n)+"="+encodeURIComponent(o.value);return o.metadata!==void 0&&(i+=ol+o.metadata.toString()),i})}function ab(r){var e=r.split(ol);if(!(e.length<=0)){var t=e.shift();if(t){var n=t.indexOf(ob);if(!(n<=0)){var o=decodeURIComponent(t.substring(0,n).trim()),i=decodeURIComponent(t.substring(n+1).trim()),a;return e.length>0&&(a=Id(e.join(ol))),{key:o,value:i,metadata:a}}}}}function xO(r){return typeof r!="string"||r.length===0?{}:r.split(zd).map(function(e){return ab(e)}).filter(function(e){return e!==void 0&&e.value.length>0}).reduce(function(e,t){return e[t.key]=t.value,e},{})}Ce();var il;(function(r){r.AlwaysOff="always_off",r.AlwaysOn="always_on",r.ParentBasedAlwaysOff="parentbased_always_off",r.ParentBasedAlwaysOn="parentbased_always_on",r.ParentBasedTraceIdRatio="parentbased_traceidratio",r.TraceIdRatio="traceidratio"})(il||(il={}));var MO=",",_O=["OTEL_SDK_DISABLED"];function IO(r){return _O.indexOf(r)>-1}var PO=["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 OO(r){return PO.indexOf(r)>-1}var LO=["OTEL_NO_PATCH_MODULES","OTEL_PROPAGATORS"];function NO(r){return LO.indexOf(r)>-1}var Hd=1/0,Gd=128,DO=128,kO=128,Vd={OTEL_SDK_DISABLED:!1,CONTAINER_NAME:"",ECS_CONTAINER_METADATA_URI_V4:"",ECS_CONTAINER_METADATA_URI:"",HOSTNAME:"",KUBERNETES_SERVICE_HOST:"",NAMESPACE:"",OTEL_BSP_EXPORT_TIMEOUT:3e4,OTEL_BSP_MAX_EXPORT_BATCH_SIZE:512,OTEL_BSP_MAX_QUEUE_SIZE:2048,OTEL_BSP_SCHEDULE_DELAY:5e3,OTEL_BLRP_EXPORT_TIMEOUT:3e4,OTEL_BLRP_MAX_EXPORT_BATCH_SIZE:512,OTEL_BLRP_MAX_QUEUE_SIZE:2048,OTEL_BLRP_SCHEDULE_DELAY:5e3,OTEL_EXPORTER_JAEGER_AGENT_HOST:"",OTEL_EXPORTER_JAEGER_AGENT_PORT:6832,OTEL_EXPORTER_JAEGER_ENDPOINT:"",OTEL_EXPORTER_JAEGER_PASSWORD:"",OTEL_EXPORTER_JAEGER_USER:"",OTEL_EXPORTER_OTLP_ENDPOINT:"",OTEL_EXPORTER_OTLP_TRACES_ENDPOINT:"",OTEL_EXPORTER_OTLP_METRICS_ENDPOINT:"",OTEL_EXPORTER_OTLP_LOGS_ENDPOINT:"",OTEL_EXPORTER_OTLP_HEADERS:"",OTEL_EXPORTER_OTLP_TRACES_HEADERS:"",OTEL_EXPORTER_OTLP_METRICS_HEADERS:"",OTEL_EXPORTER_OTLP_LOGS_HEADERS:"",OTEL_EXPORTER_OTLP_TIMEOUT:1e4,OTEL_EXPORTER_OTLP_TRACES_TIMEOUT:1e4,OTEL_EXPORTER_OTLP_METRICS_TIMEOUT:1e4,OTEL_EXPORTER_OTLP_LOGS_TIMEOUT:1e4,OTEL_EXPORTER_ZIPKIN_ENDPOINT:"http://localhost:9411/api/v2/spans",OTEL_LOG_LEVEL:Le.INFO,OTEL_NO_PATCH_MODULES:[],OTEL_PROPAGATORS:["tracecontext","baggage"],OTEL_RESOURCE_ATTRIBUTES:"",OTEL_SERVICE_NAME:"",OTEL_ATTRIBUTE_VALUE_LENGTH_LIMIT:Hd,OTEL_ATTRIBUTE_COUNT_LIMIT:Gd,OTEL_SPAN_ATTRIBUTE_VALUE_LENGTH_LIMIT:Hd,OTEL_SPAN_ATTRIBUTE_COUNT_LIMIT:Gd,OTEL_LOGRECORD_ATTRIBUTE_VALUE_LENGTH_LIMIT:Hd,OTEL_LOGRECORD_ATTRIBUTE_COUNT_LIMIT:Gd,OTEL_SPAN_EVENT_COUNT_LIMIT:128,OTEL_SPAN_LINK_COUNT_LIMIT:128,OTEL_SPAN_ATTRIBUTE_PER_EVENT_COUNT_LIMIT:DO,OTEL_SPAN_ATTRIBUTE_PER_LINK_COUNT_LIMIT:kO,OTEL_TRACES_EXPORTER:"",OTEL_TRACES_SAMPLER:il.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 UO(r,e,t){if(!(typeof t[r]>"u")){var n=String(t[r]);e[r]=n.toLowerCase()==="true"}}function FO(r,e,t,n,o){if(n===void 0&&(n=-1/0),o===void 0&&(o=1/0),typeof t[r]<"u"){var i=Number(t[r]);isNaN(i)||(i<n?e[r]=n:i>o?e[r]=o:e[r]=i)}}function BO(r,e,t,n){n===void 0&&(n=MO);var o=t[r];typeof o=="string"&&(e[r]=o.split(n).map(function(i){return i.trim()}))}var zO={ALL:Le.ALL,VERBOSE:Le.VERBOSE,DEBUG:Le.DEBUG,INFO:Le.INFO,WARN:Le.WARN,ERROR:Le.ERROR,NONE:Le.NONE};function HO(r,e,t){var n=t[r];if(typeof n=="string"){var o=zO[n.toUpperCase()];o!=null&&(e[r]=o)}}function sb(r){var e={};for(var t in Vd){var n=t;switch(n){case"OTEL_LOG_LEVEL":HO(n,e,r);break;default:if(IO(n))UO(n,e,r);else if(OO(n))FO(n,e,r);else if(NO(n))BO(n,e,r);else{var o=r[n];typeof o<"u"&&o!==null&&(e[n]=String(o))}}}return e}function mt(){var r=sb(process.env);return Object.assign({},Vd,r)}function lb(r){return r>=48&&r<=57?r-48:r>=97&&r<=102?r-87:r-55}function al(r){for(var e=new Uint8Array(r.length/2),t=0,n=0;n<r.length;n+=2){var o=lb(r.charCodeAt(n)),i=lb(r.charCodeAt(n+1));e[t++]=o<<4|i}return e}var cb="1.25.1";var GO="deployment.environment";var VO="process.runtime.name";var jO="service.name";var WO="service.instance.id";var $O="telemetry.sdk.name",qO="telemetry.sdk.language",KO="telemetry.sdk.version";var ub=GO;var db=VO;var sl=jO;var pb=WO;var ha=$O,fa=qO,Sa=KO;var YO="nodejs";var mb=YO;var Go,ll=(Go={},Go[ha]="opentelemetry",Go[db]="node",Go[fa]=mb,Go[Sa]=cb,Go);var XO=9,JO=6,ZO=Math.pow(10,JO),QO=Math.pow(10,XO);function gb(r){var e=r/1e3,t=Math.trunc(e),n=Math.round(r%1e3*ZO);return[t,n]}function hb(r){return r[0]*QO+r[1]}function ya(r){return r[0]*1e6+r[1]/1e3}var Gn;(function(r){r[r.SUCCESS=0]="SUCCESS",r[r.FAILED=1]="FAILED"})(Gn||(Gn={}));var fb=function(){function r(){var e=this;this._promise=new Promise(function(t,n){e._resolve=t,e._reject=n})}return Object.defineProperty(r.prototype,"promise",{get:function(){return this._promise},enumerable:!1,configurable:!0}),r.prototype.resolve=function(e){this._resolve(e)},r.prototype.reject=function(e){this._reject(e)},r}();var eL=function(r,e){var t=typeof Symbol=="function"&&r[Symbol.iterator];if(!t)return r;var n=t.call(r),o,i=[],a;try{for(;(e===void 0||e-- >0)&&!(o=n.next()).done;)i.push(o.value)}catch(l){a={error:l}}finally{try{o&&!o.done&&(t=n.return)&&t.call(n)}finally{if(a)throw a.error}}return i},tL=function(r,e,t){if(t||arguments.length===2)for(var n=0,o=e.length,i;n<o;n++)(i||!(n in e))&&(i||(i=Array.prototype.slice.call(e,0,n)),i[n]=e[n]);return r.concat(i||Array.prototype.slice.call(e))},Sb=function(){function r(e,t){this._callback=e,this._that=t,this._isCalled=!1,this._deferred=new fb}return Object.defineProperty(r.prototype,"isCalled",{get:function(){return this._isCalled},enumerable:!1,configurable:!0}),Object.defineProperty(r.prototype,"promise",{get:function(){return this._deferred.promise},enumerable:!1,configurable:!0}),r.prototype.call=function(){for(var e,t=this,n=[],o=0;o<arguments.length;o++)n[o]=arguments[o];if(!this._isCalled){this._isCalled=!0;try{Promise.resolve((e=this._callback).call.apply(e,tL([this._that],eL(n),!1))).then(function(i){return t._deferred.resolve(i)},function(i){return t._deferred.reject(i)})}catch(i){this._deferred.reject(i)}}return this._deferred.promise},r}();var rr;(function(r){r[r.DELTA=0]="DELTA",r[r.CUMULATIVE=1]="CUMULATIVE"})(rr||(rr={}));var Tt;(function(r){r[r.HISTOGRAM=0]="HISTOGRAM",r[r.EXPONENTIAL_HISTOGRAM=1]="EXPONENTIAL_HISTOGRAM",r[r.GAUGE=2]="GAUGE",r[r.SUM=3]="SUM"})(Tt||(Tt={}));var rL=function(){var r=function(e,t){return r=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(n,o){n.__proto__=o}||function(n,o){for(var i in o)Object.prototype.hasOwnProperty.call(o,i)&&(n[i]=o[i])},r(e,t)};return function(e,t){if(typeof t!="function"&&t!==null)throw new TypeError("Class extends value "+String(t)+" is not a constructor or null");r(e,t);function n(){this.constructor=e}e.prototype=t===null?Object.create(t):(n.prototype=t.prototype,new n)}}();var a7=function(r){rL(e,r);function e(t){var n=r.call(this,t)||this;return Object.setPrototypeOf(n,e.prototype),n}return e}(Error);function yb(r,e){for(var t=0,n=r.length-1;n-t>1;){var o=Math.trunc((n+t)/2);r[o]<=e?t=o:n=o-1}return r[n]<=e?n:r[t]<=e?t:-1}Ce();var nr;(function(r){r[r.DROP=0]="DROP",r[r.SUM=1]="SUM",r[r.LAST_VALUE=2]="LAST_VALUE",r[r.HISTOGRAM=3]="HISTOGRAM",r[r.EXPONENTIAL_HISTOGRAM=4]="EXPONENTIAL_HISTOGRAM"})(nr||(nr={}));var bb=function(){function r(){this.kind=nr.DROP}return r.prototype.createAccumulation=function(){},r.prototype.merge=function(e,t){},r.prototype.diff=function(e,t){},r.prototype.toMetricData=function(e,t,n,o){},r}();var re;(function(r){r.COUNTER="COUNTER",r.GAUGE="GAUGE",r.HISTOGRAM="HISTOGRAM",r.UP_DOWN_COUNTER="UP_DOWN_COUNTER",r.OBSERVABLE_COUNTER="OBSERVABLE_COUNTER",r.OBSERVABLE_GAUGE="OBSERVABLE_GAUGE",r.OBSERVABLE_UP_DOWN_COUNTER="OBSERVABLE_UP_DOWN_COUNTER"})(re||(re={}));var nL=function(r,e){var t=typeof Symbol=="function"&&r[Symbol.iterator];if(!t)return r;var n=t.call(r),o,i=[],a;try{for(;(e===void 0||e-- >0)&&!(o=n.next()).done;)i.push(o.value)}catch(l){a={error:l}}finally{try{o&&!o.done&&(t=n.return)&&t.call(n)}finally{if(a)throw a.error}}return i};function oL(r){var e=r.map(function(){return 0});return e.push(0),{buckets:{boundaries:r,counts:e},sum:0,count:0,hasMinMax:!1,min:1/0,max:-1/0}}var jd=function(){function r(e,t,n,o){n===void 0&&(n=!0),o===void 0&&(o=oL(t)),this.startTime=e,this._boundaries=t,this._recordMinMax=n,this._current=o}return r.prototype.record=function(e){if(!Number.isNaN(e)){this._current.count+=1,this._current.sum+=e,this._recordMinMax&&(this._current.min=Math.min(e,this._current.min),this._current.max=Math.max(e,this._current.max),this._current.hasMinMax=!0);var t=yb(this._boundaries,e);this._current.buckets.counts[t+1]+=1}},r.prototype.setStartTime=function(e){this.startTime=e},r.prototype.toPointValue=function(){return this._current},r}();var Wd=function(){function r(e,t){this._boundaries=e,this._recordMinMax=t,this.kind=nr.HISTOGRAM}return r.prototype.createAccumulation=function(e){return new jd(e,this._boundaries,this._recordMinMax)},r.prototype.merge=function(e,t){for(var n=e.toPointValue(),o=t.toPointValue(),i=n.buckets.counts,a=o.buckets.counts,l=new Array(i.length),c=0;c<i.length;c++)l[c]=i[c]+a[c];var s=1/0,u=-1/0;return this._recordMinMax&&(n.hasMinMax&&o.hasMinMax?(s=Math.min(n.min,o.min),u=Math.max(n.max,o.max)):n.hasMinMax?(s=n.min,u=n.max):o.hasMinMax&&(s=o.min,u=o.max)),new jd(e.startTime,n.buckets.boundaries,this._recordMinMax,{buckets:{boundaries:n.buckets.boundaries,counts:l},count:n.count+o.count,sum:n.sum+o.sum,hasMinMax:this._recordMinMax&&(n.hasMinMax||o.hasMinMax),min:s,max:u})},r.prototype.diff=function(e,t){for(var n=e.toPointValue(),o=t.toPointValue(),i=n.buckets.counts,a=o.buckets.counts,l=new Array(i.length),c=0;c<i.length;c++)l[c]=a[c]-i[c];return new jd(t.startTime,n.buckets.boundaries,this._recordMinMax,{buckets:{boundaries:n.buckets.boundaries,counts:l},count:o.count-n.count,sum:o.sum-n.sum,hasMinMax:!1,min:1/0,max:-1/0})},r.prototype.toMetricData=function(e,t,n,o){return{descriptor:e,aggregationTemporality:t,dataPointType:Tt.HISTOGRAM,dataPoints:n.map(function(i){var a=nL(i,2),l=a[0],c=a[1],s=c.toPointValue(),u=e.type===re.GAUGE||e.type===re.UP_DOWN_COUNTER||e.type===re.OBSERVABLE_GAUGE||e.type===re.OBSERVABLE_UP_DOWN_COUNTER;return{attributes:l,startTime:c.startTime,endTime:o,value:{min:s.hasMinMax?s.min:void 0,max:s.hasMinMax?s.max:void 0,sum:u?void 0:s.sum,buckets:s.buckets,count:s.count}}})}},r}();Ce();var $d=function(r,e){var t=typeof Symbol=="function"&&r[Symbol.iterator];if(!t)return r;var n=t.call(r),o,i=[],a;try{for(;(e===void 0||e-- >0)&&!(o=n.next()).done;)i.push(o.value)}catch(l){a={error:l}}finally{try{o&&!o.done&&(t=n.return)&&t.call(n)}finally{if(a)throw a.error}}return i},qd=function(r,e,t){if(t||arguments.length===2)for(var n=0,o=e.length,i;n<o;n++)(i||!(n in e))&&(i||(i=Array.prototype.slice.call(e,0,n)),i[n]=e[n]);return r.concat(i||Array.prototype.slice.call(e))},Kd=function(){function r(e,t,n,o){e===void 0&&(e=new iL),t===void 0&&(t=0),n===void 0&&(n=0),o===void 0&&(o=0),this.backing=e,this.indexBase=t,this.indexStart=n,this.indexEnd=o}return Object.defineProperty(r.prototype,"offset",{get:function(){return this.indexStart},enumerable:!1,configurable:!0}),Object.defineProperty(r.prototype,"length",{get:function(){return this.backing.length===0||this.indexEnd===this.indexStart&&this.at(0)===0?0:this.indexEnd-this.indexStart+1},enumerable:!1,configurable:!0}),r.prototype.counts=function(){var e=this;return Array.from({length:this.length},function(t,n){return e.at(n)})},r.prototype.at=function(e){var t=this.indexBase-this.indexStart;return e<t&&(e+=this.backing.length),e-=t,this.backing.countAt(e)},r.prototype.incrementBucket=function(e,t){this.backing.increment(e,t)},r.prototype.decrementBucket=function(e,t){this.backing.decrement(e,t)},r.prototype.trim=function(){for(var e=0;e<this.length;e++)if(this.at(e)!==0){this.indexStart+=e;break}else if(e===this.length-1){this.indexStart=this.indexEnd=this.indexBase=0;return}for(var e=this.length-1;e>=0;e--)if(this.at(e)!==0){this.indexEnd-=this.length-e-1;break}this._rotate()},r.prototype.downscale=function(e){this._rotate();for(var t=1+this.indexEnd-this.indexStart,n=1<<e,o=0,i=0,a=this.indexStart;a<=this.indexEnd;){var l=a%n;l<0&&(l+=n);for(var c=l;c<n&&o<t;c++)this._relocateBucket(i,o),o++,a++;i++}this.indexStart>>=e,this.indexEnd>>=e,this.indexBase=this.indexStart},r.prototype.clone=function(){return new r(this.backing.clone(),this.indexBase,this.indexStart,this.indexEnd)},r.prototype._rotate=function(){var e=this.indexBase-this.indexStart;e!==0&&(e>0?(this.backing.reverse(0,this.backing.length),this.backing.reverse(0,e),this.backing.reverse(e,this.backing.length)):(this.backing.reverse(0,this.backing.length),this.backing.reverse(0,this.backing.length+e)),this.indexBase=this.indexStart)},r.prototype._relocateBucket=function(e,t){e!==t&&this.incrementBucket(e,this.backing.emptyBucket(t))},r}();var iL=function(){function r(e){e===void 0&&(e=[0]),this._counts=e}return Object.defineProperty(r.prototype,"length",{get:function(){return this._counts.length},enumerable:!1,configurable:!0}),r.prototype.countAt=function(e){return this._counts[e]},r.prototype.growTo=function(e,t,n){var o=new Array(e).fill(0);o.splice.apply(o,qd([n,this._counts.length-t],$d(this._counts.slice(t)),!1)),o.splice.apply(o,qd([0,t],$d(this._counts.slice(0,t)),!1)),this._counts=o},r.prototype.reverse=function(e,t){for(var n=Math.floor((e+t)/2)-e,o=0;o<n;o++){var i=this._counts[e+o];this._counts[e+o]=this._counts[t-o-1],this._counts[t-o-1]=i}},r.prototype.emptyBucket=function(e){var t=this._counts[e];return this._counts[e]=0,t},r.prototype.increment=function(e,t){this._counts[e]+=t},r.prototype.decrement=function(e,t){this._counts[e]>=t?this._counts[e]-=t:this._counts[e]=0},r.prototype.clone=function(){return new r(qd([],$d(this._counts),!1))},r}();var Eb=52,aL=2146435072,sL=1048575,Yd=1023,cl=-Yd+1,ul=Yd,ba=Math.pow(2,-1022);function dl(r){var e=new DataView(new ArrayBuffer(8));e.setFloat64(0,r);var t=e.getUint32(0),n=(t&aL)>>20;return n-Yd}function pl(r){var e=new DataView(new ArrayBuffer(8));e.setFloat64(0,r);var t=e.getUint32(0),n=e.getUint32(4),o=(t&sL)*Math.pow(2,32);return o+n}function Ea(r,e){return r===0||r===Number.POSITIVE_INFINITY||r===Number.NEGATIVE_INFINITY||Number.isNaN(r)?r:r*Math.pow(2,e)}function vb(r){return r--,r|=r>>1,r|=r>>2,r|=r>>4,r|=r>>8,r|=r>>16,r++,r}var lL=function(){var r=function(e,t){return r=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(n,o){n.__proto__=o}||function(n,o){for(var i in o)Object.prototype.hasOwnProperty.call(o,i)&&(n[i]=o[i])},r(e,t)};return function(e,t){if(typeof t!="function"&&t!==null)throw new TypeError("Class extends value "+String(t)+" is not a constructor or null");r(e,t);function n(){this.constructor=e}e.prototype=t===null?Object.create(t):(n.prototype=t.prototype,new n)}}(),pn=function(r){lL(e,r);function e(){return r!==null&&r.apply(this,arguments)||this}return e}(Error);var wb=function(){function r(e){this._shift=-e}return r.prototype.mapToIndex=function(e){if(e<ba)return this._minNormalLowerBoundaryIndex();var t=dl(e),n=this._rightShift(pl(e)-1,Eb);return t+n>>this._shift},r.prototype.lowerBoundary=function(e){var t=this._minNormalLowerBoundaryIndex();if(e<t)throw new pn("underflow: "+e+" is < minimum lower boundary: "+t);var n=this._maxNormalLowerBoundaryIndex();if(e>n)throw new pn("overflow: "+e+" is > maximum lower boundary: "+n);return Ea(1,e<<this._shift)},Object.defineProperty(r.prototype,"scale",{get:function(){return this._shift===0?0:-this._shift},enumerable:!1,configurable:!0}),r.prototype._minNormalLowerBoundaryIndex=function(){var e=cl>>this._shift;return this._shift<2&&e--,e},r.prototype._maxNormalLowerBoundaryIndex=function(){return ul>>this._shift},r.prototype._rightShift=function(e,t){return Math.floor(e*Math.pow(2,-t))},r}();var Rb=function(){function r(e){this._scale=e,this._scaleFactor=Ea(Math.LOG2E,e),this._inverseFactor=Ea(Math.LN2,-e)}return r.prototype.mapToIndex=function(e){if(e<=ba)return this._minNormalLowerBoundaryIndex()-1;if(pl(e)===0){var t=dl(e);return(t<<this._scale)-1}var n=Math.floor(Math.log(e)*this._scaleFactor),o=this._maxNormalLowerBoundaryIndex();return n>=o?o:n},r.prototype.lowerBoundary=function(e){var t=this._maxNormalLowerBoundaryIndex();if(e>=t){if(e===t)return 2*Math.exp((e-(1<<this._scale))/this._scaleFactor);throw new pn("overflow: "+e+" is > maximum lower boundary: "+t)}var n=this._minNormalLowerBoundaryIndex();if(e<=n){if(e===n)return ba;if(e===n-1)return Math.exp((e+(1<<this._scale))/this._scaleFactor)/2;throw new pn("overflow: "+e+" is < minimum lower boundary: "+n)}return Math.exp(e*this._inverseFactor)},Object.defineProperty(r.prototype,"scale",{get:function(){return this._scale},enumerable:!1,configurable:!0}),r.prototype._minNormalLowerBoundaryIndex=function(){return cl<<this._scale},r.prototype._maxNormalLowerBoundaryIndex=function(){return(ul+1<<this._scale)-1},r}();var Cb=-10,xb=20,cL=Array.from({length:31},function(r,e){return e>10?new Rb(e-10):new wb(e-10)});function Xd(r){if(r>xb||r<Cb)throw new pn("expected scale >= "+Cb+" && <= "+xb+", got: "+r);return cL[r+10]}var uL=function(r,e){var t=typeof Symbol=="function"&&r[Symbol.iterator];if(!t)return r;var n=t.call(r),o,i=[],a;try{for(;(e===void 0||e-- >0)&&!(o=n.next()).done;)i.push(o.value)}catch(l){a={error:l}}finally{try{o&&!o.done&&(t=n.return)&&t.call(n)}finally{if(a)throw a.error}}return i},ml=function(){function r(e,t){this.low=e,this.high=t}return r.combine=function(e,t){return new r(Math.min(e.low,t.low),Math.max(e.high,t.high))},r}(),dL=20,pL=160,Jd=2,mL=function(){function r(e,t,n,o,i,a,l,c,s,u,d){e===void 0&&(e=e),t===void 0&&(t=pL),n===void 0&&(n=!0),o===void 0&&(o=0),i===void 0&&(i=0),a===void 0&&(a=0),l===void 0&&(l=Number.POSITIVE_INFINITY),c===void 0&&(c=Number.NEGATIVE_INFINITY),s===void 0&&(s=new Kd),u===void 0&&(u=new Kd),d===void 0&&(d=Xd(dL)),this.startTime=e,this._maxSize=t,this._recordMinMax=n,this._sum=o,this._count=i,this._zeroCount=a,this._min=l,this._max=c,this._positive=s,this._negative=u,this._mapping=d,this._maxSize<Jd&&(H.warn("Exponential Histogram Max Size set to "+this._maxSize+", changing to the minimum size of: "+Jd),this._maxSize=Jd)}return r.prototype.record=function(e){this.updateByIncrement(e,1)},r.prototype.setStartTime=function(e){this.startTime=e},r.prototype.toPointValue=function(){return{hasMinMax:this._recordMinMax,min:this.min,max:this.max,sum:this.sum,positive:{offset:this.positive.offset,bucketCounts:this.positive.counts()},negative:{offset:this.negative.offset,bucketCounts:this.negative.counts()},count:this.count,scale:this.scale,zeroCount:this.zeroCount}},Object.defineProperty(r.prototype,"sum",{get:function(){return this._sum},enumerable:!1,configurable:!0}),Object.defineProperty(r.prototype,"min",{get:function(){return this._min},enumerable:!1,configurable:!0}),Object.defineProperty(r.prototype,"max",{get:function(){return this._max},enumerable:!1,configurable:!0}),Object.defineProperty(r.prototype,"count",{get:function(){return this._count},enumerable:!1,configurable:!0}),Object.defineProperty(r.prototype,"zeroCount",{get:function(){return this._zeroCount},enumerable:!1,configurable:!0}),Object.defineProperty(r.prototype,"scale",{get:function(){return this._count===this._zeroCount?0:this._mapping.scale},enumerable:!1,configurable:!0}),Object.defineProperty(r.prototype,"positive",{get:function(){return this._positive},enumerable:!1,configurable:!0}),Object.defineProperty(r.prototype,"negative",{get:function(){return this._negative},enumerable:!1,configurable:!0}),r.prototype.updateByIncrement=function(e,t){if(!Number.isNaN(e)){if(e>this._max&&(this._max=e),e<this._min&&(this._min=e),this._count+=t,e===0){this._zeroCount+=t;return}this._sum+=e*t,e>0?this._updateBuckets(this._positive,e,t):this._updateBuckets(this._negative,-e,t)}},r.prototype.merge=function(e){this._count===0?(this._min=e.min,this._max=e.max):e.count!==0&&(e.min<this.min&&(this._min=e.min),e.max>this.max&&(this._max=e.max)),this.startTime=e.startTime,this._sum+=e.sum,this._count+=e.count,this._zeroCount+=e.zeroCount;var t=this._minScale(e);this._downscale(this.scale-t),this._mergeBuckets(this.positive,e,e.positive,t),this._mergeBuckets(this.negative,e,e.negative,t)},r.prototype.diff=function(e){this._min=1/0,this._max=-1/0,this._sum-=e.sum,this._count-=e.count,this._zeroCount-=e.zeroCount;var t=this._minScale(e);this._downscale(this.scale-t),this._diffBuckets(this.positive,e,e.positive,t),this._diffBuckets(this.negative,e,e.negative,t)},r.prototype.clone=function(){return new r(this.startTime,this._maxSize,this._recordMinMax,this._sum,this._count,this._zeroCount,this._min,this._max,this.positive.clone(),this.negative.clone(),this._mapping)},r.prototype._updateBuckets=function(e,t,n){var o=this._mapping.mapToIndex(t),i=!1,a=0,l=0;if(e.length===0?(e.indexStart=o,e.indexEnd=e.indexStart,e.indexBase=e.indexStart):o<e.indexStart&&e.indexEnd-o>=this._maxSize?(i=!0,l=o,a=e.indexEnd):o>e.indexEnd&&o-e.indexStart>=this._maxSize&&(i=!0,l=e.indexStart,a=o),i){var c=this._changeScale(a,l);this._downscale(c),o=this._mapping.mapToIndex(t)}this._incrementIndexBy(e,o,n)},r.prototype._incrementIndexBy=function(e,t,n){if(n!==0){if(e.length===0&&(e.indexStart=e.indexEnd=e.indexBase=t),t<e.indexStart){var o=e.indexEnd-t;o>=e.backing.length&&this._grow(e,o+1),e.indexStart=t}else if(t>e.indexEnd){var o=t-e.indexStart;o>=e.backing.length&&this._grow(e,o+1),e.indexEnd=t}var i=t-e.indexBase;i<0&&(i+=e.backing.length),e.incrementBucket(i,n)}},r.prototype._grow=function(e,t){var n=e.backing.length,o=e.indexBase-e.indexStart,i=n-o,a=vb(t);a>this._maxSize&&(a=this._maxSize);var l=a-o;e.backing.growTo(a,i,l)},r.prototype._changeScale=function(e,t){for(var n=0;e-t>=this._maxSize;)e>>=1,t>>=1,n++;return n},r.prototype._downscale=function(e){if(e!==0){if(e<0)throw new Error("impossible change of scale: "+this.scale);var t=this._mapping.scale-e;this._positive.downscale(e),this._negative.downscale(e),this._mapping=Xd(t)}},r.prototype._minScale=function(e){var t=Math.min(this.scale,e.scale),n=ml.combine(this._highLowAtScale(this.positive,this.scale,t),this._highLowAtScale(e.positive,e.scale,t)),o=ml.combine(this._highLowAtScale(this.negative,this.scale,t),this._highLowAtScale(e.negative,e.scale,t));return Math.min(t-this._changeScale(n.high,n.low),t-this._changeScale(o.high,o.low))},r.prototype._highLowAtScale=function(e,t,n){if(e.length===0)return new ml(0,-1);var o=t-n;return new ml(e.indexStart>>o,e.indexEnd>>o)},r.prototype._mergeBuckets=function(e,t,n,o){for(var i=n.offset,a=t.scale-o,l=0;l<n.length;l++)this._incrementIndexBy(e,i+l>>a,n.at(l))},r.prototype._diffBuckets=function(e,t,n,o){for(var i=n.offset,a=t.scale-o,l=0;l<n.length;l++){var c=i+l>>a,s=c-e.indexBase;s<0&&(s+=e.backing.length),e.decrementBucket(s,n.at(l))}e.trim()},r}();var Mb=function(){function r(e,t){this._maxSize=e,this._recordMinMax=t,this.kind=nr.EXPONENTIAL_HISTOGRAM}return r.prototype.createAccumulation=function(e){return new mL(e,this._maxSize,this._recordMinMax)},r.prototype.merge=function(e,t){var n=t.clone();return n.merge(e),n},r.prototype.diff=function(e,t){var n=t.clone();return n.diff(e),n},r.prototype.toMetricData=function(e,t,n,o){return{descriptor:e,aggregationTemporality:t,dataPointType:Tt.EXPONENTIAL_HISTOGRAM,dataPoints:n.map(function(i){var a=uL(i,2),l=a[0],c=a[1],s=c.toPointValue(),u=e.type===re.GAUGE||e.type===re.UP_DOWN_COUNTER||e.type===re.OBSERVABLE_GAUGE||e.type===re.OBSERVABLE_UP_DOWN_COUNTER;return{attributes:l,startTime:c.startTime,endTime:o,value:{min:s.hasMinMax?s.min:void 0,max:s.hasMinMax?s.max:void 0,sum:u?void 0:s.sum,positive:{offset:s.positive.offset,bucketCounts:s.positive.bucketCounts},negative:{offset:s.negative.offset,bucketCounts:s.negative.bucketCounts},count:s.count,scale:s.scale,zeroCount:s.zeroCount}}})}},r}();var gL=function(r,e){var t=typeof Symbol=="function"&&r[Symbol.iterator];if(!t)return r;var n=t.call(r),o,i=[],a;try{for(;(e===void 0||e-- >0)&&!(o=n.next()).done;)i.push(o.value)}catch(l){a={error:l}}finally{try{o&&!o.done&&(t=n.return)&&t.call(n)}finally{if(a)throw a.error}}return i},Zd=function(){function r(e,t,n){t===void 0&&(t=0),n===void 0&&(n=[0,0]),this.startTime=e,this._current=t,this.sampleTime=n}return r.prototype.record=function(e){this._current=e,this.sampleTime=gb(Date.now())},r.prototype.setStartTime=function(e){this.startTime=e},r.prototype.toPointValue=function(){return this._current},r}();var _b=function(){function r(){this.kind=nr.LAST_VALUE}return r.prototype.createAccumulation=function(e){return new Zd(e)},r.prototype.merge=function(e,t){var n=ya(t.sampleTime)>=ya(e.sampleTime)?t:e;return new Zd(e.startTime,n.toPointValue(),n.sampleTime)},r.prototype.diff=function(e,t){var n=ya(t.sampleTime)>=ya(e.sampleTime)?t:e;return new Zd(t.startTime,n.toPointValue(),n.sampleTime)},r.prototype.toMetricData=function(e,t,n,o){return{descriptor:e,aggregationTemporality:t,dataPointType:Tt.GAUGE,dataPoints:n.map(function(i){var a=gL(i,2),l=a[0],c=a[1];return{attributes:l,startTime:c.startTime,endTime:o,value:c.toPointValue()}})}},r}();var hL=function(r,e){var t=typeof Symbol=="function"&&r[Symbol.iterator];if(!t)return r;var n=t.call(r),o,i=[],a;try{for(;(e===void 0||e-- >0)&&!(o=n.next()).done;)i.push(o.value)}catch(l){a={error:l}}finally{try{o&&!o.done&&(t=n.return)&&t.call(n)}finally{if(a)throw a.error}}return i},Ta=function(){function r(e,t,n,o){n===void 0&&(n=0),o===void 0&&(o=!1),this.startTime=e,this.monotonic=t,this._current=n,this.reset=o}return r.prototype.record=function(e){this.monotonic&&e<0||(this._current+=e)},r.prototype.setStartTime=function(e){this.startTime=e},r.prototype.toPointValue=function(){return this._current},r}();var Qd=function(){function r(e){this.monotonic=e,this.kind=nr.SUM}return r.prototype.createAccumulation=function(e){return new Ta(e,this.monotonic)},r.prototype.merge=function(e,t){var n=e.toPointValue(),o=t.toPointValue();return t.reset?new Ta(t.startTime,this.monotonic,o,t.reset):new Ta(e.startTime,this.monotonic,n+o)},r.prototype.diff=function(e,t){var n=e.toPointValue(),o=t.toPointValue();return this.monotonic&&n>o?new Ta(t.startTime,this.monotonic,o,!0):new Ta(t.startTime,this.monotonic,o-n)},r.prototype.toMetricData=function(e,t,n,o){return{descriptor:e,aggregationTemporality:t,dataPointType:Tt.SUM,dataPoints:n.map(function(i){var a=hL(i,2),l=a[0],c=a[1];return{attributes:l,startTime:c.startTime,endTime:o,value:c.toPointValue()}}),isMonotonic:this.monotonic}},r}();var Vn=function(){var r=function(e,t){return r=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(n,o){n.__proto__=o}||function(n,o){for(var i in o)Object.prototype.hasOwnProperty.call(o,i)&&(n[i]=o[i])},r(e,t)};return function(e,t){if(typeof t!="function"&&t!==null)throw new TypeError("Class extends value "+String(t)+" is not a constructor or null");r(e,t);function n(){this.constructor=e}e.prototype=t===null?Object.create(t):(n.prototype=t.prototype,new n)}}(),xr=function(){function r(){}return r.Drop=function(){return Ub},r.Sum=function(){return Fb},r.LastValue=function(){return Bb},r.Histogram=function(){return zb},r.ExponentialHistogram=function(){return fL},r.Default=function(){return SL},r}();var Ib=function(r){Vn(e,r);function e(){return r!==null&&r.apply(this,arguments)||this}return e.prototype.createAggregator=function(t){return e.DEFAULT_INSTANCE},e.DEFAULT_INSTANCE=new bb,e}(xr);var Pb=function(r){Vn(e,r);function e(){return r!==null&&r.apply(this,arguments)||this}return e.prototype.createAggregator=function(t){switch(t.type){case re.COUNTER:case re.OBSERVABLE_COUNTER:case re.HISTOGRAM:return e.MONOTONIC_INSTANCE;default:return e.NON_MONOTONIC_INSTANCE}},e.MONOTONIC_INSTANCE=new Qd(!0),e.NON_MONOTONIC_INSTANCE=new Qd(!1),e}(xr);var Ob=function(r){Vn(e,r);function e(){return r!==null&&r.apply(this,arguments)||this}return e.prototype.createAggregator=function(t){return e.DEFAULT_INSTANCE},e.DEFAULT_INSTANCE=new _b,e}(xr);var Lb=function(r){Vn(e,r);function e(){return r!==null&&r.apply(this,arguments)||this}return e.prototype.createAggregator=function(t){return e.DEFAULT_INSTANCE},e.DEFAULT_INSTANCE=new Wd([0,5,10,25,50,75,100,250,500,750,1e3,2500,5e3,7500,1e4],!0),e}(xr);var Nb=function(r){Vn(e,r);function e(t,n){n===void 0&&(n=!0);var o=r.call(this)||this;if(o._recordMinMax=n,t==null)throw new Error("ExplicitBucketHistogramAggregation should be created with explicit boundaries, if a single bucket histogram is required, please pass an empty array");t=t.concat(),t=t.sort(function(l,c){return l-c});var i=t.lastIndexOf(-1/0),a=t.indexOf(1/0);return a===-1&&(a=void 0),o._boundaries=t.slice(i+1,a),o}return e.prototype.createAggregator=function(t){return new Wd(this._boundaries,this._recordMinMax)},e}(xr);var Db=function(r){Vn(e,r);function e(t,n){t===void 0&&(t=160),n===void 0&&(n=!0);var o=r.call(this)||this;return o._maxSize=t,o._recordMinMax=n,o}return e.prototype.createAggregator=function(t){return new Mb(this._maxSize,this._recordMinMax)},e}(xr);var kb=function(r){Vn(e,r);function e(){return r!==null&&r.apply(this,arguments)||this}return e.prototype._resolve=function(t){switch(t.type){case re.COUNTER:case re.UP_DOWN_COUNTER:case re.OBSERVABLE_COUNTER:case re.OBSERVABLE_UP_DOWN_COUNTER:return Fb;case re.GAUGE:case re.OBSERVABLE_GAUGE:return Bb;case re.HISTOGRAM:return t.advice.explicitBucketBoundaries?new Nb(t.advice.explicitBucketBoundaries):zb}return H.warn("Unable to recognize instrument type: "+t.type),Ub},e.prototype.createAggregator=function(t){return this._resolve(t).createAggregator(t)},e}(xr);var Ub=new Ib,Fb=new Pb,Bb=new Ob,zb=new Lb,fL=new Db,SL=new kb;Ce();function gl(){return"unknown_service:"+process.argv0}var mn=function(){return mn=Object.assign||function(r){for(var e,t=1,n=arguments.length;t<n;t++){e=arguments[t];for(var o in e)Object.prototype.hasOwnProperty.call(e,o)&&(r[o]=e[o])}return r},mn.apply(this,arguments)},yL=function(r,e,t,n){function o(i){return i instanceof t?i:new t(function(a){a(i)})}return new(t||(t=Promise))(function(i,a){function l(u){try{s(n.next(u))}catch(d){a(d)}}function c(u){try{s(n.throw(u))}catch(d){a(d)}}function s(u){u.done?i(u.value):o(u.value).then(l,c)}s((n=n.apply(r,e||[])).next())})},bL=function(r,e){var t={label:0,sent:function(){if(i[0]&1)throw i[1];return i[1]},trys:[],ops:[]},n,o,i,a;return a={next:l(0),throw:l(1),return:l(2)},typeof Symbol=="function"&&(a[Symbol.iterator]=function(){return this}),a;function l(s){return function(u){return c([s,u])}}function c(s){if(n)throw new TypeError("Generator is already executing.");for(;t;)try{if(n=1,o&&(i=s[0]&2?o.return:s[0]?o.throw||((i=o.return)&&i.call(o),0):o.next)&&!(i=i.call(o,s[1])).done)return i;switch(o=0,i&&(s=[s[0]&2,i.value]),s[0]){case 0:case 1:i=s;break;case 4:return t.label++,{value:s[1],done:!1};case 5:t.label++,o=s[1],s=[0];continue;case 7:s=t.ops.pop(),t.trys.pop();continue;default:if(i=t.trys,!(i=i.length>0&&i[i.length-1])&&(s[0]===6||s[0]===2)){t=0;continue}if(s[0]===3&&(!i||s[1]>i[0]&&s[1]<i[3])){t.label=s[1];break}if(s[0]===6&&t.label<i[1]){t.label=i[1],i=s;break}if(i&&t.label<i[2]){t.label=i[2],t.ops.push(s);break}i[2]&&t.ops.pop(),t.trys.pop();continue}s=e.call(r,t)}catch(u){s=[6,u],o=0}finally{n=i=0}if(s[0]&5)throw s[1];return{value:s[0]?s[1]:void 0,done:!0}}},EL=function(r,e){var t=typeof Symbol=="function"&&r[Symbol.iterator];if(!t)return r;var n=t.call(r),o,i=[],a;try{for(;(e===void 0||e-- >0)&&!(o=n.next()).done;)i.push(o.value)}catch(l){a={error:l}}finally{try{o&&!o.done&&(t=n.return)&&t.call(n)}finally{if(a)throw a.error}}return i},ep=function(){function r(e,t){var n=this,o;this._attributes=e,this.asyncAttributesPending=t!=null,this._syncAttributes=(o=this._attributes)!==null&&o!==void 0?o:{},this._asyncAttributesPromise=t?.then(function(i){return n._attributes=Object.assign({},n._attributes,i),n.asyncAttributesPending=!1,i},function(i){return H.debug("a resource's async attributes promise rejected: %s",i),n.asyncAttributesPending=!1,{}})}return r.empty=function(){return r.EMPTY},r.default=function(){var e;return new r((e={},e[sl]=gl(),e[fa]=ll[fa],e[ha]=ll[ha],e[Sa]=ll[Sa],e))},Object.defineProperty(r.prototype,"attributes",{get:function(){var e;return this.asyncAttributesPending&&H.error("Accessing resource attributes before async attributes settled"),(e=this._attributes)!==null&&e!==void 0?e:{}},enumerable:!1,configurable:!0}),r.prototype.waitForAsyncAttributes=function(){return yL(this,void 0,void 0,function(){return bL(this,function(e){switch(e.label){case 0:return this.asyncAttributesPending?[4,this._asyncAttributesPromise]:[3,2];case 1:e.sent(),e.label=2;case 2:return[2]}})})},r.prototype.merge=function(e){var t=this,n;if(!e)return this;var o=mn(mn({},this._syncAttributes),(n=e._syncAttributes)!==null&&n!==void 0?n:e.attributes);if(!this._asyncAttributesPromise&&!e._asyncAttributesPromise)return new r(o);var i=Promise.all([this._asyncAttributesPromise,e._asyncAttributesPromise]).then(function(a){var l,c=EL(a,2),s=c[0],u=c[1];return mn(mn(mn(mn({},t._syncAttributes),s),(l=e._syncAttributes)!==null&&l!==void 0?l:e.attributes),u)});return new r(o,i)},r.EMPTY=new r({}),r}();var jn;(function(r){r[r.DELTA=0]="DELTA",r[r.CUMULATIVE=1]="CUMULATIVE",r[r.LOWMEMORY=2]="LOWMEMORY"})(jn||(jn={}));Ce();var TL=function(r,e,t,n){function o(i){return i instanceof t?i:new t(function(a){a(i)})}return new(t||(t=Promise))(function(i,a){function l(u){try{s(n.next(u))}catch(d){a(d)}}function c(u){try{s(n.throw(u))}catch(d){a(d)}}function s(u){u.done?i(u.value):o(u.value).then(l,c)}s((n=n.apply(r,e||[])).next())})},vL=function(r,e){var t={label:0,sent:function(){if(i[0]&1)throw i[1];return i[1]},trys:[],ops:[]},n,o,i,a;return a={next:l(0),throw:l(1),return:l(2)},typeof Symbol=="function"&&(a[Symbol.iterator]=function(){return this}),a;function l(s){return function(u){return c([s,u])}}function c(s){if(n)throw new TypeError("Generator is already executing.");for(;t;)try{if(n=1,o&&(i=s[0]&2?o.return:s[0]?o.throw||((i=o.return)&&i.call(o),0):o.next)&&!(i=i.call(o,s[1])).done)return i;switch(o=0,i&&(s=[s[0]&2,i.value]),s[0]){case 0:case 1:i=s;break;case 4:return t.label++,{value:s[1],done:!1};case 5:t.label++,o=s[1],s=[0];continue;case 7:s=t.ops.pop(),t.trys.pop();continue;default:if(i=t.trys,!(i=i.length>0&&i[i.length-1])&&(s[0]===6||s[0]===2)){t=0;continue}if(s[0]===3&&(!i||s[1]>i[0]&&s[1]<i[3])){t.label=s[1];break}if(s[0]===6&&t.label<i[1]){t.label=i[1],i=s;break}if(i&&t.label<i[2]){t.label=i[2],t.ops.push(s);break}i[2]&&t.ops.pop(),t.trys.pop();continue}s=e.call(r,t)}catch(u){s=[6,u],o=0}finally{n=i=0}if(s[0]&5)throw s[1];return{value:s[0]?s[1]:void 0,done:!0}}},tp=function(){return rr.CUMULATIVE},Hb=function(r){switch(r){case re.COUNTER:case re.OBSERVABLE_COUNTER:case re.GAUGE:case re.HISTOGRAM:case re.OBSERVABLE_GAUGE:return rr.DELTA;case re.UP_DOWN_COUNTER:case re.OBSERVABLE_UP_DOWN_COUNTER:return rr.CUMULATIVE}},Gb=function(r){switch(r){case re.COUNTER:case re.HISTOGRAM:return rr.DELTA;case re.GAUGE:case re.UP_DOWN_COUNTER:case re.OBSERVABLE_UP_DOWN_COUNTER:case re.OBSERVABLE_COUNTER:case re.OBSERVABLE_GAUGE:return rr.CUMULATIVE}};function AL(){var r=mt(),e=r.OTEL_EXPORTER_OTLP_METRICS_TEMPORALITY_PREFERENCE.trim().toLowerCase();return e==="cumulative"?tp:e==="delta"?Hb:e==="lowmemory"?Gb:(H.warn("OTEL_EXPORTER_OTLP_METRICS_TEMPORALITY_PREFERENCE is set to '"+r.OTEL_EXPORTER_OTLP_METRICS_TEMPORALITY_PREFERENCE+"', but only 'cumulative' and 'delta' are allowed. Using default ('cumulative') instead."),tp)}function wL(r){return r!=null?r===jn.DELTA?Hb:r===jn.LOWMEMORY?Gb:tp:AL()}function RL(r){return r?.aggregationPreference?r.aggregationPreference:function(e){return xr.Default()}}var Vb=function(){function r(e,t){this._otlpExporter=e,this._aggregationSelector=RL(t),this._aggregationTemporalitySelector=wL(t?.temporalityPreference)}return r.prototype.export=function(e,t){this._otlpExporter.export([e],t)},r.prototype.shutdown=function(){return TL(this,void 0,void 0,function(){return vL(this,function(e){switch(e.label){case 0:return[4,this._otlpExporter.shutdown()];case 1:return e.sent(),[2]}})})},r.prototype.forceFlush=function(){return Promise.resolve()},r.prototype.selectAggregation=function(e){return this._aggregationSelector(e)},r.prototype.selectAggregationTemporality=function(e){return this._aggregationTemporalitySelector(e)},r}();Ce();Ce();var CL=function(r,e){var t=typeof Symbol=="function"&&r[Symbol.iterator];if(!t)return r;var n=t.call(r),o,i=[],a;try{for(;(e===void 0||e-- >0)&&!(o=n.next()).done;)i.push(o.value)}catch(l){a={error:l}}finally{try{o&&!o.done&&(t=n.return)&&t.call(n)}finally{if(a)throw a.error}}return i},jb=1e4,Wb=5,$b=1e3,qb=5e3,Kb=1.5;function va(r){r===void 0&&(r={});var e={};return Object.entries(r).forEach(function(t){var n=CL(t,2),o=n[0],i=n[1];typeof i<"u"?e[o]=String(i):H.warn('Header "'+o+'" has invalid value ('+i+") and will be ignored")}),e}function rp(r,e){return r.endsWith("/")||(r=r+"/"),r+e}function np(r){try{var e=new URL(r);return e.pathname===""&&(e.pathname=e.pathname+"/"),e.toString()}catch{return H.warn("Could not parse export URL: '"+r+"'"),r}}function op(r){return typeof r=="number"?r<=0?ip(r,jb):r:xL()}function xL(){var r,e=Number((r=mt().OTEL_EXPORTER_OTLP_TRACES_TIMEOUT)!==null&&r!==void 0?r:mt().OTEL_EXPORTER_OTLP_TIMEOUT);return e<=0?ip(e,jb):e}function ip(r,e){return H.warn("Timeout must be greater than 0",r),e}function Yb(r){var e=[429,502,503,504];return e.includes(r)}function Xb(r){if(r==null)return-1;var e=Number.parseInt(r,10);if(Number.isInteger(e))return e>0?e*1e3:-1;var t=new Date(r).getTime()-Date.now();return t>=0?t:0}var Jb=function(){function r(e){e===void 0&&(e={}),this._sendingPromises=[],this.url=this.getDefaultUrl(e),typeof e.hostname=="string"&&(this.hostname=e.hostname),this.shutdown=this.shutdown.bind(this),this._shutdownOnce=new Sb(this._shutdown,this),this._concurrencyLimit=typeof e.concurrencyLimit=="number"?e.concurrencyLimit:30,this.timeoutMillis=op(e.timeoutMillis),this.onInit(e)}return r.prototype.export=function(e,t){if(this._shutdownOnce.isCalled){t({code:Gn.FAILED,error:new Error("Exporter has been shutdown")});return}if(this._sendingPromises.length>=this._concurrencyLimit){t({code:Gn.FAILED,error:new Error("Concurrent export limit reached")});return}this._export(e).then(function(){t({code:Gn.SUCCESS})}).catch(function(n){t({code:Gn.FAILED,error:n})})},r.prototype._export=function(e){var t=this;return new Promise(function(n,o){try{H.debug("items to be sent",e),t.send(e,n,o)}catch(i){o(i)}})},r.prototype.shutdown=function(){return this._shutdownOnce.call()},r.prototype.forceFlush=function(){return Promise.all(this._sendingPromises).then(function(){})},r.prototype._shutdown=function(){return H.debug("shutdown started"),this.onShutdown(),this.forceFlush()},r}();Ce();import*as ap from"url";import*as fl from"http";import*as Sl from"https";import*as Zb from"zlib";import{Readable as _L}from"stream";var gn;(function(r){r.NONE="none",r.GZIP="gzip"})(gn||(gn={}));var ML=function(){var r=function(e,t){return r=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(n,o){n.__proto__=o}||function(n,o){for(var i in o)Object.prototype.hasOwnProperty.call(o,i)&&(n[i]=o[i])},r(e,t)};return function(e,t){if(typeof t!="function"&&t!==null)throw new TypeError("Class extends value "+String(t)+" is not a constructor or null");r(e,t);function n(){this.constructor=e}e.prototype=t===null?Object.create(t):(n.prototype=t.prototype,new n)}}(),Vo=function(r){ML(e,r);function e(t,n,o){var i=r.call(this,t)||this;return i.name="OTLPExporterError",i.data=o,i.code=n,i}return e}(Error);var hl=function(){return hl=Object.assign||function(r){for(var e,t=1,n=arguments.length;t<n;t++){e=arguments[t];for(var o in e)Object.prototype.hasOwnProperty.call(e,o)&&(r[o]=e[o])}return r},hl.apply(this,arguments)};function sp(r,e,t,n,o){var i=r.timeoutMillis,a=new ap.URL(r.url),l=Number(process.versions.node.split(".")[0]),c,s,u=!1,d=setTimeout(function(){if(clearTimeout(c),u=!0,s.destroyed){var h=new Vo("Request Timeout");o(h)}else l>=14?s.destroy():s.abort()},i),p={hostname:a.hostname,port:a.port,path:a.pathname,method:"POST",headers:hl({"Content-Type":t},r.headers),agent:r.agent},m=a.protocol==="http:"?fl.request:Sl.request,g=function(h,f){switch(h===void 0&&(h=Wb),f===void 0&&(f=$b),s=m(p,function(E){var v="";E.on("data",function(R){return v+=R}),E.on("aborted",function(){if(u){var R=new Vo("Request Timeout");o(R)}}),E.on("end",function(){if(u===!1)if(E.statusCode&&E.statusCode<299)H.debug("statusCode: "+E.statusCode,v),n(),clearTimeout(d),clearTimeout(c);else if(E.statusCode&&Yb(E.statusCode)&&h>0){var R=void 0;f=Kb*f,E.headers["retry-after"]?R=Xb(E.headers["retry-after"]):R=Math.round(Math.random()*(qb-f)+f),c=setTimeout(function(){g(h-1,f)},R)}else{var T=new Vo(E.statusMessage,E.statusCode,v);o(T),clearTimeout(d),clearTimeout(c)}})}),s.on("error",function(E){if(u){var v=new Vo("Request Timeout",E.code);o(v)}else o(E);clearTimeout(d),clearTimeout(c)}),s.on("abort",function(){if(u){var E=new Vo("Request Timeout");o(E)}clearTimeout(d),clearTimeout(c)}),r.compression){case gn.GZIP:{s.setHeader("Content-Encoding","gzip");var b=IL(e);b.on("error",o).pipe(Zb.createGzip()).on("error",o).pipe(s);break}default:s.end(Buffer.from(e));break}};g()}function IL(r){var e=new _L;return e.push(r),e.push(null),e}function lp(r){if(r.httpAgentOptions&&r.keepAlive===!1){H.warn("httpAgentOptions is used only when keepAlive is true");return}if(!(r.keepAlive===!1||!r.url))try{var e=new ap.URL(r.url),t=e.protocol==="http:"?fl.Agent:Sl.Agent;return new t(hl({keepAlive:!0},r.httpAgentOptions))}catch(n){H.error("collector exporter failed to create http agent. err: "+n.message);return}}function cp(r){if(r)return r;var e=mt().OTEL_EXPORTER_OTLP_TRACES_COMPRESSION||mt().OTEL_EXPORTER_OTLP_COMPRESSION;return e===gn.GZIP?gn.GZIP:gn.NONE}Ce();var PL=function(){var r=function(e,t){return r=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(n,o){n.__proto__=o}||function(n,o){for(var i in o)Object.prototype.hasOwnProperty.call(o,i)&&(n[i]=o[i])},r(e,t)};return function(e,t){if(typeof t!="function"&&t!==null)throw new TypeError("Class extends value "+String(t)+" is not a constructor or null");r(e,t);function n(){this.constructor=e}e.prototype=t===null?Object.create(t):(n.prototype=t.prototype,new n)}}(),yl=function(r){PL(e,r);function e(t,n,o){t===void 0&&(t={});var i=r.call(this,t)||this;return i.DEFAULT_HEADERS={},i._contentType=o,t.metadata&&H.warn("Metadata cannot be set when using http"),i.headers=Object.assign(i.DEFAULT_HEADERS,va(t.headers),Ho.parseKeyPairsIntoRecord(mt().OTEL_EXPORTER_OTLP_HEADERS)),i.agent=lp(t),i.compression=cp(t.compression),i._serializer=n,i}return e.prototype.onInit=function(t){},e.prototype.send=function(t,n,o){var i=this;if(this._shutdownOnce.isCalled){H.debug("Shutdown already started. Cannot send objects");return}var a=new Promise(function(c,s){var u;sp(i,(u=i._serializer.serializeRequest(t))!==null&&u!==void 0?u:new Uint8Array,i._contentType,c,s)}).then(n,o);this._sendingPromises.push(a);var l=function(){var c=i._sendingPromises.indexOf(a);i._sendingPromises.splice(c,1)};a.then(l,l)},e.prototype.onShutdown=function(){},e}(Jb);function eE(r){var e=BigInt(1e9);return BigInt(r[0])*e+BigInt(r[1])}function OL(r){var e=Number(BigInt.asUintN(32,r)),t=Number(BigInt.asUintN(32,r>>BigInt(32)));return{low:e,high:t}}function tE(r){var e=eE(r);return OL(e)}function LL(r){var e=eE(r);return e.toString()}var NL=typeof BigInt<"u"?LL:hb;function Qb(r){return r}function rE(r){if(r!==void 0)return al(r)}var DL={encodeHrTime:tE,encodeSpanContext:al,encodeOptionalSpanContext:rE};function nE(r){var e,t;if(r===void 0)return DL;var n=(e=r.useLongBits)!==null&&e!==void 0?e:!0,o=(t=r.useHex)!==null&&t!==void 0?t:!1;return{encodeHrTime:n?tE:NL,encodeSpanContext:o?Qb:al,encodeOptionalSpanContext:o?Qb:rE}}var kL=function(r,e){var t=typeof Symbol=="function"&&r[Symbol.iterator];if(!t)return r;var n=t.call(r),o,i=[],a;try{for(;(e===void 0||e-- >0)&&!(o=n.next()).done;)i.push(o.value)}catch(l){a={error:l}}finally{try{o&&!o.done&&(t=n.return)&&t.call(n)}finally{if(a)throw a.error}}return i};function oE(r){return{name:r.name,version:r.version}}function jo(r){return Object.keys(r).map(function(e){return iE(e,r[e])})}function iE(r,e){return{key:r,value:aE(e)}}function aE(r){var e=typeof r;return e==="string"?{stringValue:r}:e==="number"?Number.isInteger(r)?{intValue:r}:{doubleValue:r}:e==="boolean"?{boolValue:r}:r instanceof Uint8Array?{bytesValue:r}:Array.isArray(r)?{arrayValue:{values:r.map(aE)}}:e==="object"&&r!=null?{kvlistValue:{values:Object.entries(r).map(function(t){var n=kL(t,2),o=n[0],i=n[1];return iE(o,i)})}}:{}}function sE(r){return{attributes:jo(r.attributes),droppedAttributesCount:0}}Ce();function cE(r,e){var t=nE(e);return{resource:sE(r.resource),schemaUrl:void 0,scopeMetrics:UL(r.scopeMetrics,t)}}function UL(r,e){return Array.from(r.map(function(t){return{scope:oE(t.scope),metrics:t.metrics.map(function(n){return FL(n,e)}),schemaUrl:t.scope.schemaUrl}}))}function FL(r,e){var t={name:r.descriptor.name,description:r.descriptor.description,unit:r.descriptor.unit},n=GL(r.aggregationTemporality);switch(r.dataPointType){case Tt.SUM:t.sum={aggregationTemporality:n,isMonotonic:r.isMonotonic,dataPoints:lE(r,e)};break;case Tt.GAUGE:t.gauge={dataPoints:lE(r,e)};break;case Tt.HISTOGRAM:t.histogram={aggregationTemporality:n,dataPoints:zL(r,e)};break;case Tt.EXPONENTIAL_HISTOGRAM:t.exponentialHistogram={aggregationTemporality:n,dataPoints:HL(r,e)};break}return t}function BL(r,e,t){var n={attributes:jo(r.attributes),startTimeUnixNano:t.encodeHrTime(r.startTime),timeUnixNano:t.encodeHrTime(r.endTime)};switch(e){case Bt.INT:n.asInt=r.value;break;case Bt.DOUBLE:n.asDouble=r.value;break}return n}function lE(r,e){return r.dataPoints.map(function(t){return BL(t,r.descriptor.valueType,e)})}function zL(r,e){return r.dataPoints.map(function(t){var n=t.value;return{attributes:jo(t.attributes),bucketCounts:n.buckets.counts,explicitBounds:n.buckets.boundaries,count:n.count,sum:n.sum,min:n.min,max:n.max,startTimeUnixNano:e.encodeHrTime(t.startTime),timeUnixNano:e.encodeHrTime(t.endTime)}})}function HL(r,e){return r.dataPoints.map(function(t){var n=t.value;return{attributes:jo(t.attributes),count:n.count,min:n.min,max:n.max,sum:n.sum,positive:{offset:n.positive.offset,bucketCounts:n.positive.bucketCounts},negative:{offset:n.negative.offset,bucketCounts:n.negative.bucketCounts},scale:n.scale,zeroCount:n.zeroCount,startTimeUnixNano:e.encodeHrTime(t.startTime),timeUnixNano:e.encodeHrTime(t.endTime)}})}function GL(r){switch(r){case rr.DELTA:return 1;case rr.CUMULATIVE:return 2}}function uE(r,e){return{resourceMetrics:r.map(function(t){return cE(t,e)})}}var up={serializeRequest:function(r){var e=uE(r,{useLongBits:!1}),t=new TextEncoder;return t.encode(JSON.stringify(e))},deserializeResponse:function(r){var e=new TextDecoder;return JSON.parse(e.decode(r))}};var dE="0.52.1";var pE=function(){var r=function(e,t){return r=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(n,o){n.__proto__=o}||function(n,o){for(var i in o)Object.prototype.hasOwnProperty.call(o,i)&&(n[i]=o[i])},r(e,t)};return function(e,t){if(typeof t!="function"&&t!==null)throw new TypeError("Class extends value "+String(t)+" is not a constructor or null");r(e,t);function n(){this.constructor=e}e.prototype=t===null?Object.create(t):(n.prototype=t.prototype,new n)}}(),Wo=function(){return Wo=Object.assign||function(r){for(var e,t=1,n=arguments.length;t<n;t++){e=arguments[t];for(var o in e)Object.prototype.hasOwnProperty.call(e,o)&&(r[o]=e[o])}return r},Wo.apply(this,arguments)},mE="v1/metrics",VL="http://localhost:4318/"+mE,jL={"User-Agent":"OTel-OTLP-Exporter-JavaScript/"+dE},WL=function(r){pE(e,r);function e(t){var n=r.call(this,t,up,"application/json")||this;return n.headers=Wo(Wo(Wo(Wo({},n.headers),jL),Ho.parseKeyPairsIntoRecord(mt().OTEL_EXPORTER_OTLP_METRICS_HEADERS)),va(t?.headers)),n}return e.prototype.getDefaultUrl=function(t){return typeof t.url=="string"?t.url:mt().OTEL_EXPORTER_OTLP_METRICS_ENDPOINT.length>0?np(mt().OTEL_EXPORTER_OTLP_METRICS_ENDPOINT):mt().OTEL_EXPORTER_OTLP_ENDPOINT.length>0?rp(mt().OTEL_EXPORTER_OTLP_ENDPOINT,mE):VL},e}(yl),gE=function(r){pE(e,r);function e(t){return r.call(this,new WL(t),t)||this}return e}(Vb);var $o;(function(r){r[r.DELTA=0]="DELTA",r[r.CUMULATIVE=1]="CUMULATIVE"})($o||($o={}));var Mr;(function(r){r[r.HISTOGRAM=0]="HISTOGRAM",r[r.EXPONENTIAL_HISTOGRAM=1]="EXPONENTIAL_HISTOGRAM",r[r.GAUGE=2]="GAUGE",r[r.SUM=3]="SUM"})(Mr||(Mr={}));Ce();var $L=function(){var r=function(e,t){return r=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(n,o){n.__proto__=o}||function(n,o){for(var i in o)Object.prototype.hasOwnProperty.call(o,i)&&(n[i]=o[i])},r(e,t)};return function(e,t){if(typeof t!="function"&&t!==null)throw new TypeError("Class extends value "+String(t)+" is not a constructor or null");r(e,t);function n(){this.constructor=e}e.prototype=t===null?Object.create(t):(n.prototype=t.prototype,new n)}}(),hE=function(r,e,t,n){function o(i){return i instanceof t?i:new t(function(a){a(i)})}return new(t||(t=Promise))(function(i,a){function l(u){try{s(n.next(u))}catch(d){a(d)}}function c(u){try{s(n.throw(u))}catch(d){a(d)}}function s(u){u.done?i(u.value):o(u.value).then(l,c)}s((n=n.apply(r,e||[])).next())})},fE=function(r,e){var t={label:0,sent:function(){if(i[0]&1)throw i[1];return i[1]},trys:[],ops:[]},n,o,i,a;return a={next:l(0),throw:l(1),return:l(2)},typeof Symbol=="function"&&(a[Symbol.iterator]=function(){return this}),a;function l(s){return function(u){return c([s,u])}}function c(s){if(n)throw new TypeError("Generator is already executing.");for(;t;)try{if(n=1,o&&(i=s[0]&2?o.return:s[0]?o.throw||((i=o.return)&&i.call(o),0):o.next)&&!(i=i.call(o,s[1])).done)return i;switch(o=0,i&&(s=[s[0]&2,i.value]),s[0]){case 0:case 1:i=s;break;case 4:return t.label++,{value:s[1],done:!1};case 5:t.label++,o=s[1],s=[0];continue;case 7:s=t.ops.pop(),t.trys.pop();continue;default:if(i=t.trys,!(i=i.length>0&&i[i.length-1])&&(s[0]===6||s[0]===2)){t=0;continue}if(s[0]===3&&(!i||s[1]>i[0]&&s[1]<i[3])){t.label=s[1];break}if(s[0]===6&&t.label<i[1]){t.label=i[1],i=s;break}if(i&&t.label<i[2]){t.label=i[2],t.ops.push(s);break}i[2]&&t.ops.pop(),t.trys.pop();continue}s=e.call(r,t)}catch(u){s=[6,u],o=0}finally{n=i=0}if(s[0]&5)throw s[1];return{value:s[0]?s[1]:void 0,done:!0}}},qL=function(r,e){var t=typeof Symbol=="function"&&r[Symbol.iterator];if(!t)return r;var n=t.call(r),o,i=[],a;try{for(;(e===void 0||e-- >0)&&!(o=n.next()).done;)i.push(o.value)}catch(l){a={error:l}}finally{try{o&&!o.done&&(t=n.return)&&t.call(n)}finally{if(a)throw a.error}}return i},KL=function(r,e,t){if(t||arguments.length===2)for(var n=0,o=e.length,i;n<o;n++)(i||!(n in e))&&(i||(i=Array.prototype.slice.call(e,0,n)),i[n]=e[n]);return r.concat(i||Array.prototype.slice.call(e))},YL=function(r){var e=typeof Symbol=="function"&&Symbol.iterator,t=e&&r[e],n=0;if(t)return t.call(r);if(r&&typeof r.length=="number")return{next:function(){return r&&n>=r.length&&(r=void 0),{value:r&&r[n++],done:!r}}};throw new TypeError(e?"Object is not iterable.":"Symbol.iterator is not defined.")};function SE(r){return r!=null}function bl(r){var e=Object.keys(r);return e.length===0?"":(e=e.sort(),JSON.stringify(e.map(function(t){return[t,r[t]]})))}function yE(r){var e,t;return r.name+":"+((e=r.version)!==null&&e!==void 0?e:"")+":"+((t=r.schemaUrl)!==null&&t!==void 0?t:"")}var dp=function(r){$L(e,r);function e(t){var n=r.call(this,t)||this;return Object.setPrototypeOf(n,e.prototype),n}return e}(Error);function hn(r,e){var t,n=new Promise(function(i,a){t=setTimeout(function(){a(new dp("Operation timed out."))},e)});return Promise.race([r,n]).then(function(o){return clearTimeout(t),o},function(o){throw clearTimeout(t),o})}function bE(r){return hE(this,void 0,void 0,function(){var e=this;return fE(this,function(t){return[2,Promise.all(r.map(function(n){return hE(e,void 0,void 0,function(){var o,i;return fE(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 EE(r){return r.status==="rejected"}function pp(r,e){var t=[];return r.forEach(function(n){t.push.apply(t,KL([],qL(e(n)),!1))}),t}function TE(r,e){var t,n;if(r.size!==e.size)return!1;try{for(var o=YL(r),i=o.next();!i.done;i=o.next()){var a=i.value;if(!e.has(a))return!1}}catch(l){t={error:l}}finally{try{i&&!i.done&&(n=o.return)&&n.call(o)}finally{if(t)throw t.error}}return!0}function vE(r,e){for(var t=0,n=r.length-1,o=r.length;n>=t;){var i=t+Math.trunc((n-t)/2);r[i]<e?t=i+1:(o=i,n=i-1)}return o}function AE(r,e){return r.toLowerCase()===e.toLowerCase()}Ce();var or;(function(r){r[r.DROP=0]="DROP",r[r.SUM=1]="SUM",r[r.LAST_VALUE=2]="LAST_VALUE",r[r.HISTOGRAM=3]="HISTOGRAM",r[r.EXPONENTIAL_HISTOGRAM=4]="EXPONENTIAL_HISTOGRAM"})(or||(or={}));var mp=function(){function r(){this.kind=or.DROP}return r.prototype.createAccumulation=function(){},r.prototype.merge=function(e,t){},r.prototype.diff=function(e,t){},r.prototype.toMetricData=function(e,t,n,o){},r}();Ce();var ce;(function(r){r.COUNTER="COUNTER",r.GAUGE="GAUGE",r.HISTOGRAM="HISTOGRAM",r.UP_DOWN_COUNTER="UP_DOWN_COUNTER",r.OBSERVABLE_COUNTER="OBSERVABLE_COUNTER",r.OBSERVABLE_GAUGE="OBSERVABLE_GAUGE",r.OBSERVABLE_UP_DOWN_COUNTER="OBSERVABLE_UP_DOWN_COUNTER"})(ce||(ce={}));function _r(r,e,t){var n,o,i,a;return JL(r)||H.warn('Invalid metric name: "'+r+'". The metric name should be a ASCII string with a length no greater than 255 characters.'),{name:r,type:e,description:(n=t?.description)!==null&&n!==void 0?n:"",unit:(o=t?.unit)!==null&&o!==void 0?o:"",valueType:(i=t?.valueType)!==null&&i!==void 0?i:Bt.DOUBLE,advice:(a=t?.advice)!==null&&a!==void 0?a:{}}}function wE(r,e){var t,n;return{name:(t=r.name)!==null&&t!==void 0?t:e.name,description:(n=r.description)!==null&&n!==void 0?n:e.description,type:e.type,unit:e.unit,valueType:e.valueType,advice:e.advice}}function RE(r,e){return AE(r.name,e.name)&&r.unit===e.unit&&r.type===e.type&&r.valueType===e.valueType}var XL=/^[a-z][a-z0-9_.\-/]{0,254}$/i;function JL(r){return r.match(XL)!=null}var ZL=function(r,e){var t=typeof Symbol=="function"&&r[Symbol.iterator];if(!t)return r;var n=t.call(r),o,i=[],a;try{for(;(e===void 0||e-- >0)&&!(o=n.next()).done;)i.push(o.value)}catch(l){a={error:l}}finally{try{o&&!o.done&&(t=n.return)&&t.call(n)}finally{if(a)throw a.error}}return i};function QL(r){var e=r.map(function(){return 0});return e.push(0),{buckets:{boundaries:r,counts:e},sum:0,count:0,hasMinMax:!1,min:1/0,max:-1/0}}var El=function(){function r(e,t,n,o){n===void 0&&(n=!0),o===void 0&&(o=QL(t)),this.startTime=e,this._boundaries=t,this._recordMinMax=n,this._current=o}return r.prototype.record=function(e){if(!Number.isNaN(e)){this._current.count+=1,this._current.sum+=e,this._recordMinMax&&(this._current.min=Math.min(e,this._current.min),this._current.max=Math.max(e,this._current.max),this._current.hasMinMax=!0);var t=vE(this._boundaries,e);this._current.buckets.counts[t]+=1}},r.prototype.setStartTime=function(e){this.startTime=e},r.prototype.toPointValue=function(){return this._current},r}();var Tl=function(){function r(e,t){this._boundaries=e,this._recordMinMax=t,this.kind=or.HISTOGRAM}return r.prototype.createAccumulation=function(e){return new El(e,this._boundaries,this._recordMinMax)},r.prototype.merge=function(e,t){for(var n=e.toPointValue(),o=t.toPointValue(),i=n.buckets.counts,a=o.buckets.counts,l=new Array(i.length),c=0;c<i.length;c++)l[c]=i[c]+a[c];var s=1/0,u=-1/0;return this._recordMinMax&&(n.hasMinMax&&o.hasMinMax?(s=Math.min(n.min,o.min),u=Math.max(n.max,o.max)):n.hasMinMax?(s=n.min,u=n.max):o.hasMinMax&&(s=o.min,u=o.max)),new El(e.startTime,n.buckets.boundaries,this._recordMinMax,{buckets:{boundaries:n.buckets.boundaries,counts:l},count:n.count+o.count,sum:n.sum+o.sum,hasMinMax:this._recordMinMax&&(n.hasMinMax||o.hasMinMax),min:s,max:u})},r.prototype.diff=function(e,t){for(var n=e.toPointValue(),o=t.toPointValue(),i=n.buckets.counts,a=o.buckets.counts,l=new Array(i.length),c=0;c<i.length;c++)l[c]=a[c]-i[c];return new El(t.startTime,n.buckets.boundaries,this._recordMinMax,{buckets:{boundaries:n.buckets.boundaries,counts:l},count:o.count-n.count,sum:o.sum-n.sum,hasMinMax:!1,min:1/0,max:-1/0})},r.prototype.toMetricData=function(e,t,n,o){return{descriptor:e,aggregationTemporality:t,dataPointType:Mr.HISTOGRAM,dataPoints:n.map(function(i){var a=ZL(i,2),l=a[0],c=a[1],s=c.toPointValue(),u=e.type===ce.GAUGE||e.type===ce.UP_DOWN_COUNTER||e.type===ce.OBSERVABLE_GAUGE||e.type===ce.OBSERVABLE_UP_DOWN_COUNTER;return{attributes:l,startTime:c.startTime,endTime:o,value:{min:s.hasMinMax?s.min:void 0,max:s.hasMinMax?s.max:void 0,sum:u?void 0:s.sum,buckets:s.buckets,count:s.count}}})}},r}();Ce();var gp=function(r,e){var t=typeof Symbol=="function"&&r[Symbol.iterator];if(!t)return r;var n=t.call(r),o,i=[],a;try{for(;(e===void 0||e-- >0)&&!(o=n.next()).done;)i.push(o.value)}catch(l){a={error:l}}finally{try{o&&!o.done&&(t=n.return)&&t.call(n)}finally{if(a)throw a.error}}return i},hp=function(r,e,t){if(t||arguments.length===2)for(var n=0,o=e.length,i;n<o;n++)(i||!(n in e))&&(i||(i=Array.prototype.slice.call(e,0,n)),i[n]=e[n]);return r.concat(i||Array.prototype.slice.call(e))},fp=function(){function r(e,t,n,o){e===void 0&&(e=new eN),t===void 0&&(t=0),n===void 0&&(n=0),o===void 0&&(o=0),this.backing=e,this.indexBase=t,this.indexStart=n,this.indexEnd=o}return Object.defineProperty(r.prototype,"offset",{get:function(){return this.indexStart},enumerable:!1,configurable:!0}),Object.defineProperty(r.prototype,"length",{get:function(){return this.backing.length===0||this.indexEnd===this.indexStart&&this.at(0)===0?0:this.indexEnd-this.indexStart+1},enumerable:!1,configurable:!0}),r.prototype.counts=function(){var e=this;return Array.from({length:this.length},function(t,n){return e.at(n)})},r.prototype.at=function(e){var t=this.indexBase-this.indexStart;return e<t&&(e+=this.backing.length),e-=t,this.backing.countAt(e)},r.prototype.incrementBucket=function(e,t){this.backing.increment(e,t)},r.prototype.decrementBucket=function(e,t){this.backing.decrement(e,t)},r.prototype.trim=function(){for(var e=0;e<this.length;e++)if(this.at(e)!==0){this.indexStart+=e;break}else if(e===this.length-1){this.indexStart=this.indexEnd=this.indexBase=0;return}for(var e=this.length-1;e>=0;e--)if(this.at(e)!==0){this.indexEnd-=this.length-e-1;break}this._rotate()},r.prototype.downscale=function(e){this._rotate();for(var t=1+this.indexEnd-this.indexStart,n=1<<e,o=0,i=0,a=this.indexStart;a<=this.indexEnd;){var l=a%n;l<0&&(l+=n);for(var c=l;c<n&&o<t;c++)this._relocateBucket(i,o),o++,a++;i++}this.indexStart>>=e,this.indexEnd>>=e,this.indexBase=this.indexStart},r.prototype.clone=function(){return new r(this.backing.clone(),this.indexBase,this.indexStart,this.indexEnd)},r.prototype._rotate=function(){var e=this.indexBase-this.indexStart;e!==0&&(e>0?(this.backing.reverse(0,this.backing.length),this.backing.reverse(0,e),this.backing.reverse(e,this.backing.length)):(this.backing.reverse(0,this.backing.length),this.backing.reverse(0,this.backing.length+e)),this.indexBase=this.indexStart)},r.prototype._relocateBucket=function(e,t){e!==t&&this.incrementBucket(e,this.backing.emptyBucket(t))},r}();var eN=function(){function r(e){e===void 0&&(e=[0]),this._counts=e}return Object.defineProperty(r.prototype,"length",{get:function(){return this._counts.length},enumerable:!1,configurable:!0}),r.prototype.countAt=function(e){return this._counts[e]},r.prototype.growTo=function(e,t,n){var o=new Array(e).fill(0);o.splice.apply(o,hp([n,this._counts.length-t],gp(this._counts.slice(t)),!1)),o.splice.apply(o,hp([0,t],gp(this._counts.slice(0,t)),!1)),this._counts=o},r.prototype.reverse=function(e,t){for(var n=Math.floor((e+t)/2)-e,o=0;o<n;o++){var i=this._counts[e+o];this._counts[e+o]=this._counts[t-o-1],this._counts[t-o-1]=i}},r.prototype.emptyBucket=function(e){var t=this._counts[e];return this._counts[e]=0,t},r.prototype.increment=function(e,t){this._counts[e]+=t},r.prototype.decrement=function(e,t){this._counts[e]>=t?this._counts[e]-=t:this._counts[e]=0},r.prototype.clone=function(){return new r(hp([],gp(this._counts),!1))},r}();var CE=52,tN=2146435072,rN=1048575,Sp=1023,vl=-Sp+1,Al=Sp,Aa=Math.pow(2,-1022);function wl(r){var e=new DataView(new ArrayBuffer(8));e.setFloat64(0,r);var t=e.getUint32(0),n=(t&tN)>>20;return n-Sp}function Rl(r){var e=new DataView(new ArrayBuffer(8));e.setFloat64(0,r);var t=e.getUint32(0),n=e.getUint32(4),o=(t&rN)*Math.pow(2,32);return o+n}function wa(r,e){return r===0||r===Number.POSITIVE_INFINITY||r===Number.NEGATIVE_INFINITY||Number.isNaN(r)?r:r*Math.pow(2,e)}function ME(r){return r--,r|=r>>1,r|=r>>2,r|=r>>4,r|=r>>8,r|=r>>16,r++,r}var nN=function(){var r=function(e,t){return r=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(n,o){n.__proto__=o}||function(n,o){for(var i in o)Object.prototype.hasOwnProperty.call(o,i)&&(n[i]=o[i])},r(e,t)};return function(e,t){if(typeof t!="function"&&t!==null)throw new TypeError("Class extends value "+String(t)+" is not a constructor or null");r(e,t);function n(){this.constructor=e}e.prototype=t===null?Object.create(t):(n.prototype=t.prototype,new n)}}(),fn=function(r){nN(e,r);function e(){return r!==null&&r.apply(this,arguments)||this}return e}(Error);var IE=function(){function r(e){this._shift=-e}return r.prototype.mapToIndex=function(e){if(e<Aa)return this._minNormalLowerBoundaryIndex();var t=wl(e),n=this._rightShift(Rl(e)-1,CE);return t+n>>this._shift},r.prototype.lowerBoundary=function(e){var t=this._minNormalLowerBoundaryIndex();if(e<t)throw new fn("underflow: "+e+" is < minimum lower boundary: "+t);var n=this._maxNormalLowerBoundaryIndex();if(e>n)throw new fn("overflow: "+e+" is > maximum lower boundary: "+n);return wa(1,e<<this._shift)},Object.defineProperty(r.prototype,"scale",{get:function(){return this._shift===0?0:-this._shift},enumerable:!1,configurable:!0}),r.prototype._minNormalLowerBoundaryIndex=function(){var e=vl>>this._shift;return this._shift<2&&e--,e},r.prototype._maxNormalLowerBoundaryIndex=function(){return Al>>this._shift},r.prototype._rightShift=function(e,t){return Math.floor(e*Math.pow(2,-t))},r}();var PE=function(){function r(e){this._scale=e,this._scaleFactor=wa(Math.LOG2E,e),this._inverseFactor=wa(Math.LN2,-e)}return r.prototype.mapToIndex=function(e){if(e<=Aa)return this._minNormalLowerBoundaryIndex()-1;if(Rl(e)===0){var t=wl(e);return(t<<this._scale)-1}var n=Math.floor(Math.log(e)*this._scaleFactor),o=this._maxNormalLowerBoundaryIndex();return n>=o?o:n},r.prototype.lowerBoundary=function(e){var t=this._maxNormalLowerBoundaryIndex();if(e>=t){if(e===t)return 2*Math.exp((e-(1<<this._scale))/this._scaleFactor);throw new fn("overflow: "+e+" is > maximum lower boundary: "+t)}var n=this._minNormalLowerBoundaryIndex();if(e<=n){if(e===n)return Aa;if(e===n-1)return Math.exp((e+(1<<this._scale))/this._scaleFactor)/2;throw new fn("overflow: "+e+" is < minimum lower boundary: "+n)}return Math.exp(e*this._inverseFactor)},Object.defineProperty(r.prototype,"scale",{get:function(){return this._scale},enumerable:!1,configurable:!0}),r.prototype._minNormalLowerBoundaryIndex=function(){return vl<<this._scale},r.prototype._maxNormalLowerBoundaryIndex=function(){return(Al+1<<this._scale)-1},r}();var OE=-10,LE=20,oN=Array.from({length:31},function(r,e){return e>10?new PE(e-10):new IE(e-10)});function yp(r){if(r>LE||r<OE)throw new fn("expected scale >= "+OE+" && <= "+LE+", got: "+r);return oN[r+10]}var iN=function(r,e){var t=typeof Symbol=="function"&&r[Symbol.iterator];if(!t)return r;var n=t.call(r),o,i=[],a;try{for(;(e===void 0||e-- >0)&&!(o=n.next()).done;)i.push(o.value)}catch(l){a={error:l}}finally{try{o&&!o.done&&(t=n.return)&&t.call(n)}finally{if(a)throw a.error}}return i},Cl=function(){function r(e,t){this.low=e,this.high=t}return r.combine=function(e,t){return new r(Math.min(e.low,t.low),Math.max(e.high,t.high))},r}(),aN=20,sN=160,bp=2,NE=function(){function r(e,t,n,o,i,a,l,c,s,u,d){e===void 0&&(e=e),t===void 0&&(t=sN),n===void 0&&(n=!0),o===void 0&&(o=0),i===void 0&&(i=0),a===void 0&&(a=0),l===void 0&&(l=Number.POSITIVE_INFINITY),c===void 0&&(c=Number.NEGATIVE_INFINITY),s===void 0&&(s=new fp),u===void 0&&(u=new fp),d===void 0&&(d=yp(aN)),this.startTime=e,this._maxSize=t,this._recordMinMax=n,this._sum=o,this._count=i,this._zeroCount=a,this._min=l,this._max=c,this._positive=s,this._negative=u,this._mapping=d,this._maxSize<bp&&(H.warn("Exponential Histogram Max Size set to "+this._maxSize+", changing to the minimum size of: "+bp),this._maxSize=bp)}return r.prototype.record=function(e){this.updateByIncrement(e,1)},r.prototype.setStartTime=function(e){this.startTime=e},r.prototype.toPointValue=function(){return{hasMinMax:this._recordMinMax,min:this.min,max:this.max,sum:this.sum,positive:{offset:this.positive.offset,bucketCounts:this.positive.counts()},negative:{offset:this.negative.offset,bucketCounts:this.negative.counts()},count:this.count,scale:this.scale,zeroCount:this.zeroCount}},Object.defineProperty(r.prototype,"sum",{get:function(){return this._sum},enumerable:!1,configurable:!0}),Object.defineProperty(r.prototype,"min",{get:function(){return this._min},enumerable:!1,configurable:!0}),Object.defineProperty(r.prototype,"max",{get:function(){return this._max},enumerable:!1,configurable:!0}),Object.defineProperty(r.prototype,"count",{get:function(){return this._count},enumerable:!1,configurable:!0}),Object.defineProperty(r.prototype,"zeroCount",{get:function(){return this._zeroCount},enumerable:!1,configurable:!0}),Object.defineProperty(r.prototype,"scale",{get:function(){return this._count===this._zeroCount?0:this._mapping.scale},enumerable:!1,configurable:!0}),Object.defineProperty(r.prototype,"positive",{get:function(){return this._positive},enumerable:!1,configurable:!0}),Object.defineProperty(r.prototype,"negative",{get:function(){return this._negative},enumerable:!1,configurable:!0}),r.prototype.updateByIncrement=function(e,t){if(!Number.isNaN(e)){if(e>this._max&&(this._max=e),e<this._min&&(this._min=e),this._count+=t,e===0){this._zeroCount+=t;return}this._sum+=e*t,e>0?this._updateBuckets(this._positive,e,t):this._updateBuckets(this._negative,-e,t)}},r.prototype.merge=function(e){this._count===0?(this._min=e.min,this._max=e.max):e.count!==0&&(e.min<this.min&&(this._min=e.min),e.max>this.max&&(this._max=e.max)),this.startTime=e.startTime,this._sum+=e.sum,this._count+=e.count,this._zeroCount+=e.zeroCount;var t=this._minScale(e);this._downscale(this.scale-t),this._mergeBuckets(this.positive,e,e.positive,t),this._mergeBuckets(this.negative,e,e.negative,t)},r.prototype.diff=function(e){this._min=1/0,this._max=-1/0,this._sum-=e.sum,this._count-=e.count,this._zeroCount-=e.zeroCount;var t=this._minScale(e);this._downscale(this.scale-t),this._diffBuckets(this.positive,e,e.positive,t),this._diffBuckets(this.negative,e,e.negative,t)},r.prototype.clone=function(){return new r(this.startTime,this._maxSize,this._recordMinMax,this._sum,this._count,this._zeroCount,this._min,this._max,this.positive.clone(),this.negative.clone(),this._mapping)},r.prototype._updateBuckets=function(e,t,n){var o=this._mapping.mapToIndex(t),i=!1,a=0,l=0;if(e.length===0?(e.indexStart=o,e.indexEnd=e.indexStart,e.indexBase=e.indexStart):o<e.indexStart&&e.indexEnd-o>=this._maxSize?(i=!0,l=o,a=e.indexEnd):o>e.indexEnd&&o-e.indexStart>=this._maxSize&&(i=!0,l=e.indexStart,a=o),i){var c=this._changeScale(a,l);this._downscale(c),o=this._mapping.mapToIndex(t)}this._incrementIndexBy(e,o,n)},r.prototype._incrementIndexBy=function(e,t,n){if(n!==0){if(e.length===0&&(e.indexStart=e.indexEnd=e.indexBase=t),t<e.indexStart){var o=e.indexEnd-t;o>=e.backing.length&&this._grow(e,o+1),e.indexStart=t}else if(t>e.indexEnd){var o=t-e.indexStart;o>=e.backing.length&&this._grow(e,o+1),e.indexEnd=t}var i=t-e.indexBase;i<0&&(i+=e.backing.length),e.incrementBucket(i,n)}},r.prototype._grow=function(e,t){var n=e.backing.length,o=e.indexBase-e.indexStart,i=n-o,a=ME(t);a>this._maxSize&&(a=this._maxSize);var l=a-o;e.backing.growTo(a,i,l)},r.prototype._changeScale=function(e,t){for(var n=0;e-t>=this._maxSize;)e>>=1,t>>=1,n++;return n},r.prototype._downscale=function(e){if(e!==0){if(e<0)throw new Error("impossible change of scale: "+this.scale);var t=this._mapping.scale-e;this._positive.downscale(e),this._negative.downscale(e),this._mapping=yp(t)}},r.prototype._minScale=function(e){var t=Math.min(this.scale,e.scale),n=Cl.combine(this._highLowAtScale(this.positive,this.scale,t),this._highLowAtScale(e.positive,e.scale,t)),o=Cl.combine(this._highLowAtScale(this.negative,this.scale,t),this._highLowAtScale(e.negative,e.scale,t));return Math.min(t-this._changeScale(n.high,n.low),t-this._changeScale(o.high,o.low))},r.prototype._highLowAtScale=function(e,t,n){if(e.length===0)return new Cl(0,-1);var o=t-n;return new Cl(e.indexStart>>o,e.indexEnd>>o)},r.prototype._mergeBuckets=function(e,t,n,o){for(var i=n.offset,a=t.scale-o,l=0;l<n.length;l++)this._incrementIndexBy(e,i+l>>a,n.at(l))},r.prototype._diffBuckets=function(e,t,n,o){for(var i=n.offset,a=t.scale-o,l=0;l<n.length;l++){var c=i+l>>a,s=c-e.indexBase;s<0&&(s+=e.backing.length),e.decrementBucket(s,n.at(l))}e.trim()},r}();var Ep=function(){function r(e,t){this._maxSize=e,this._recordMinMax=t,this.kind=or.EXPONENTIAL_HISTOGRAM}return r.prototype.createAccumulation=function(e){return new NE(e,this._maxSize,this._recordMinMax)},r.prototype.merge=function(e,t){var n=t.clone();return n.merge(e),n},r.prototype.diff=function(e,t){var n=t.clone();return n.diff(e),n},r.prototype.toMetricData=function(e,t,n,o){return{descriptor:e,aggregationTemporality:t,dataPointType:Mr.EXPONENTIAL_HISTOGRAM,dataPoints:n.map(function(i){var a=iN(i,2),l=a[0],c=a[1],s=c.toPointValue(),u=e.type===ce.GAUGE||e.type===ce.UP_DOWN_COUNTER||e.type===ce.OBSERVABLE_GAUGE||e.type===ce.OBSERVABLE_UP_DOWN_COUNTER;return{attributes:l,startTime:c.startTime,endTime:o,value:{min:s.hasMinMax?s.min:void 0,max:s.hasMinMax?s.max:void 0,sum:u?void 0:s.sum,positive:{offset:s.positive.offset,bucketCounts:s.positive.bucketCounts},negative:{offset:s.negative.offset,bucketCounts:s.negative.bucketCounts},count:s.count,scale:s.scale,zeroCount:s.zeroCount}}})}},r}();Ce();var lN=Pd("OpenTelemetry SDK Context Key SUPPRESS_TRACING");function DE(r){return r.setValue(lN,!0)}Ce();function kE(){return function(r){H.error(cN(r))}}function cN(r){return typeof r=="string"?r:JSON.stringify(uN(r))}function uN(r){for(var e={},t=r;t!==null;)Object.getOwnPropertyNames(t).forEach(function(n){if(!e[n]){var o=t[n];o&&(e[n]=String(o))}}),t=Object.getPrototypeOf(t);return e}var dN=kE();function xl(r){try{dN(r)}catch{}}var UE="1.30.1";var pN="process.runtime.name";var mN="service.name";var gN="telemetry.sdk.name",hN="telemetry.sdk.language",fN="telemetry.sdk.version";var FE=pN;var BE=mN;var Ra=gN,Ca=hN,xa=fN;var SN="nodejs";var zE=SN;var qo,Wn=(qo={},qo[Ra]="opentelemetry",qo[FE]="node",qo[Ca]=zE,qo[xa]=UE,qo);function Ma(r){r.unref()}var wN=9,RN=6,CN=Math.pow(10,RN),ure=Math.pow(10,wN);function $n(r){var e=r/1e3,t=Math.trunc(e),n=Math.round(r%1e3*CN);return[t,n]}function Ko(r){return r[0]*1e6+r[1]/1e3}var _a;(function(r){r[r.SUCCESS=0]="SUCCESS",r[r.FAILED=1]="FAILED"})(_a||(_a={}));Ce();function HE(r,e){return new Promise(function(t){zo.with(DE(zo.active()),function(){r.export(e,function(n){t(n)})})})}var GE={_export:HE};var xN=function(r,e){var t=typeof Symbol=="function"&&r[Symbol.iterator];if(!t)return r;var n=t.call(r),o,i=[],a;try{for(;(e===void 0||e-- >0)&&!(o=n.next()).done;)i.push(o.value)}catch(l){a={error:l}}finally{try{o&&!o.done&&(t=n.return)&&t.call(n)}finally{if(a)throw a.error}}return i},Ml=function(){function r(e,t,n){t===void 0&&(t=0),n===void 0&&(n=[0,0]),this.startTime=e,this._current=t,this.sampleTime=n}return r.prototype.record=function(e){this._current=e,this.sampleTime=$n(Date.now())},r.prototype.setStartTime=function(e){this.startTime=e},r.prototype.toPointValue=function(){return this._current},r}();var Tp=function(){function r(){this.kind=or.LAST_VALUE}return r.prototype.createAccumulation=function(e){return new Ml(e)},r.prototype.merge=function(e,t){var n=Ko(t.sampleTime)>=Ko(e.sampleTime)?t:e;return new Ml(e.startTime,n.toPointValue(),n.sampleTime)},r.prototype.diff=function(e,t){var n=Ko(t.sampleTime)>=Ko(e.sampleTime)?t:e;return new Ml(t.startTime,n.toPointValue(),n.sampleTime)},r.prototype.toMetricData=function(e,t,n,o){return{descriptor:e,aggregationTemporality:t,dataPointType:Mr.GAUGE,dataPoints:n.map(function(i){var a=xN(i,2),l=a[0],c=a[1];return{attributes:l,startTime:c.startTime,endTime:o,value:c.toPointValue()}})}},r}();var MN=function(r,e){var t=typeof Symbol=="function"&&r[Symbol.iterator];if(!t)return r;var n=t.call(r),o,i=[],a;try{for(;(e===void 0||e-- >0)&&!(o=n.next()).done;)i.push(o.value)}catch(l){a={error:l}}finally{try{o&&!o.done&&(t=n.return)&&t.call(n)}finally{if(a)throw a.error}}return i},Yo=function(){function r(e,t,n,o){n===void 0&&(n=0),o===void 0&&(o=!1),this.startTime=e,this.monotonic=t,this._current=n,this.reset=o}return r.prototype.record=function(e){this.monotonic&&e<0||(this._current+=e)},r.prototype.setStartTime=function(e){this.startTime=e},r.prototype.toPointValue=function(){return this._current},r}();var _l=function(){function r(e){this.monotonic=e,this.kind=or.SUM}return r.prototype.createAccumulation=function(e){return new Yo(e,this.monotonic)},r.prototype.merge=function(e,t){var n=e.toPointValue(),o=t.toPointValue();return t.reset?new Yo(t.startTime,this.monotonic,o,t.reset):new Yo(e.startTime,this.monotonic,n+o)},r.prototype.diff=function(e,t){var n=e.toPointValue(),o=t.toPointValue();return this.monotonic&&n>o?new Yo(t.startTime,this.monotonic,o,!0):new Yo(t.startTime,this.monotonic,o-n)},r.prototype.toMetricData=function(e,t,n,o){return{descriptor:e,aggregationTemporality:t,dataPointType:Mr.SUM,dataPoints:n.map(function(i){var a=MN(i,2),l=a[0],c=a[1];return{attributes:l,startTime:c.startTime,endTime:o,value:c.toPointValue()}}),isMonotonic:this.monotonic}},r}();var qn=function(){var r=function(e,t){return r=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(n,o){n.__proto__=o}||function(n,o){for(var i in o)Object.prototype.hasOwnProperty.call(o,i)&&(n[i]=o[i])},r(e,t)};return function(e,t){if(typeof t!="function"&&t!==null)throw new TypeError("Class extends value "+String(t)+" is not a constructor or null");r(e,t);function n(){this.constructor=e}e.prototype=t===null?Object.create(t):(n.prototype=t.prototype,new n)}}(),ir=function(){function r(){}return r.Drop=function(){return YE},r.Sum=function(){return XE},r.LastValue=function(){return JE},r.Histogram=function(){return ZE},r.ExponentialHistogram=function(){return _N},r.Default=function(){return IN},r}();var VE=function(r){qn(e,r);function e(){return r!==null&&r.apply(this,arguments)||this}return e.prototype.createAggregator=function(t){return e.DEFAULT_INSTANCE},e.DEFAULT_INSTANCE=new mp,e}(ir);var jE=function(r){qn(e,r);function e(){return r!==null&&r.apply(this,arguments)||this}return e.prototype.createAggregator=function(t){switch(t.type){case ce.COUNTER:case ce.OBSERVABLE_COUNTER:case ce.HISTOGRAM:return e.MONOTONIC_INSTANCE;default:return e.NON_MONOTONIC_INSTANCE}},e.MONOTONIC_INSTANCE=new _l(!0),e.NON_MONOTONIC_INSTANCE=new _l(!1),e}(ir);var WE=function(r){qn(e,r);function e(){return r!==null&&r.apply(this,arguments)||this}return e.prototype.createAggregator=function(t){return e.DEFAULT_INSTANCE},e.DEFAULT_INSTANCE=new Tp,e}(ir);var $E=function(r){qn(e,r);function e(){return r!==null&&r.apply(this,arguments)||this}return e.prototype.createAggregator=function(t){return e.DEFAULT_INSTANCE},e.DEFAULT_INSTANCE=new Tl([0,5,10,25,50,75,100,250,500,750,1e3,2500,5e3,7500,1e4],!0),e}(ir);var Ia=function(r){qn(e,r);function e(t,n){n===void 0&&(n=!0);var o=r.call(this)||this;if(o._recordMinMax=n,t==null)throw new Error("ExplicitBucketHistogramAggregation should be created with explicit boundaries, if a single bucket histogram is required, please pass an empty array");t=t.concat(),t=t.sort(function(l,c){return l-c});var i=t.lastIndexOf(-1/0),a=t.indexOf(1/0);return a===-1&&(a=void 0),o._boundaries=t.slice(i+1,a),o}return e.prototype.createAggregator=function(t){return new Tl(this._boundaries,this._recordMinMax)},e}(ir);var qE=function(r){qn(e,r);function e(t,n){t===void 0&&(t=160),n===void 0&&(n=!0);var o=r.call(this)||this;return o._maxSize=t,o._recordMinMax=n,o}return e.prototype.createAggregator=function(t){return new Ep(this._maxSize,this._recordMinMax)},e}(ir);var KE=function(r){qn(e,r);function e(){return r!==null&&r.apply(this,arguments)||this}return e.prototype._resolve=function(t){switch(t.type){case ce.COUNTER:case ce.UP_DOWN_COUNTER:case ce.OBSERVABLE_COUNTER:case ce.OBSERVABLE_UP_DOWN_COUNTER:return XE;case ce.GAUGE:case ce.OBSERVABLE_GAUGE:return JE;case ce.HISTOGRAM:return t.advice.explicitBucketBoundaries?new Ia(t.advice.explicitBucketBoundaries):ZE}return H.warn("Unable to recognize instrument type: "+t.type),YE},e.prototype.createAggregator=function(t){return this._resolve(t).createAggregator(t)},e}(ir);var YE=new VE,XE=new jE,JE=new WE,ZE=new $E,_N=new qE,IN=new KE;var QE=function(r){return ir.Default()},eT=function(r){return $o.CUMULATIVE};var vp=function(r,e,t,n){function o(i){return i instanceof t?i:new t(function(a){a(i)})}return new(t||(t=Promise))(function(i,a){function l(u){try{s(n.next(u))}catch(d){a(d)}}function c(u){try{s(n.throw(u))}catch(d){a(d)}}function s(u){u.done?i(u.value):o(u.value).then(l,c)}s((n=n.apply(r,e||[])).next())})},Ap=function(r,e){var t={label:0,sent:function(){if(i[0]&1)throw i[1];return i[1]},trys:[],ops:[]},n,o,i,a;return a={next:l(0),throw:l(1),return:l(2)},typeof Symbol=="function"&&(a[Symbol.iterator]=function(){return this}),a;function l(s){return function(u){return c([s,u])}}function c(s){if(n)throw new TypeError("Generator is already executing.");for(;t;)try{if(n=1,o&&(i=s[0]&2?o.return:s[0]?o.throw||((i=o.return)&&i.call(o),0):o.next)&&!(i=i.call(o,s[1])).done)return i;switch(o=0,i&&(s=[s[0]&2,i.value]),s[0]){case 0:case 1:i=s;break;case 4:return t.label++,{value:s[1],done:!1};case 5:t.label++,o=s[1],s=[0];continue;case 7:s=t.ops.pop(),t.trys.pop();continue;default:if(i=t.trys,!(i=i.length>0&&i[i.length-1])&&(s[0]===6||s[0]===2)){t=0;continue}if(s[0]===3&&(!i||s[1]>i[0]&&s[1]<i[3])){t.label=s[1];break}if(s[0]===6&&t.label<i[1]){t.label=i[1],i=s;break}if(i&&t.label<i[2]){t.label=i[2],t.ops.push(s);break}i[2]&&t.ops.pop(),t.trys.pop();continue}s=e.call(r,t)}catch(u){s=[6,u],o=0}finally{n=i=0}if(s[0]&5)throw s[1];return{value:s[0]?s[1]:void 0,done:!0}}},tT=function(r,e){var t=typeof Symbol=="function"&&r[Symbol.iterator];if(!t)return r;var n=t.call(r),o,i=[],a;try{for(;(e===void 0||e-- >0)&&!(o=n.next()).done;)i.push(o.value)}catch(l){a={error:l}}finally{try{o&&!o.done&&(t=n.return)&&t.call(n)}finally{if(a)throw a.error}}return i},PN=function(r,e,t){if(t||arguments.length===2)for(var n=0,o=e.length,i;n<o;n++)(i||!(n in e))&&(i||(i=Array.prototype.slice.call(e,0,n)),i[n]=e[n]);return r.concat(i||Array.prototype.slice.call(e))},rT=function(){function r(e){var t,n,o;this._shutdown=!1,this._aggregationSelector=(t=e?.aggregationSelector)!==null&&t!==void 0?t:QE,this._aggregationTemporalitySelector=(n=e?.aggregationTemporalitySelector)!==null&&n!==void 0?n:eT,this._metricProducers=(o=e?.metricProducers)!==null&&o!==void 0?o:[],this._cardinalitySelector=e?.cardinalitySelector}return r.prototype.setMetricProducer=function(e){if(this._sdkMetricProducer)throw new Error("MetricReader can not be bound to a MeterProvider again.");this._sdkMetricProducer=e,this.onInitialized()},r.prototype.selectAggregation=function(e){return this._aggregationSelector(e)},r.prototype.selectAggregationTemporality=function(e){return this._aggregationTemporalitySelector(e)},r.prototype.selectCardinalityLimit=function(e){return this._cardinalitySelector?this._cardinalitySelector(e):2e3},r.prototype.onInitialized=function(){},r.prototype.collect=function(e){return vp(this,void 0,void 0,function(){var t,n,o,i,a,l;return Ap(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(PN([this._sdkMetricProducer.collect({timeoutMillis:e?.timeoutMillis})],tT(this._metricProducers.map(function(s){return s.collect({timeoutMillis:e?.timeoutMillis})})),!1))];case 1:return t=tT.apply(void 0,[c.sent()]),n=t[0],o=t.slice(1),i=n.errors.concat(pp(o,function(s){return s.errors})),a=n.resourceMetrics.resource,l=n.resourceMetrics.scopeMetrics.concat(pp(o,function(s){return s.resourceMetrics.scopeMetrics})),[2,{resourceMetrics:{resource:a,scopeMetrics:l},errors:i}]}})})},r.prototype.shutdown=function(e){return vp(this,void 0,void 0,function(){return Ap(this,function(t){switch(t.label){case 0:return this._shutdown?(H.error("Cannot call shutdown twice."),[2]):e?.timeoutMillis!=null?[3,2]:[4,this.onShutdown()];case 1:return t.sent(),[3,4];case 2:return[4,hn(this.onShutdown(),e.timeoutMillis)];case 3:t.sent(),t.label=4;case 4:return this._shutdown=!0,[2]}})})},r.prototype.forceFlush=function(e){return vp(this,void 0,void 0,function(){return Ap(this,function(t){switch(t.label){case 0:return this._shutdown?(H.warn("Cannot forceFlush on already shutdown MetricReader."),[2]):e?.timeoutMillis!=null?[3,2]:[4,this.onForceFlush()];case 1:return t.sent(),[2];case 2:return[4,hn(this.onForceFlush(),e.timeoutMillis)];case 3:return t.sent(),[2]}})})},r}();Ce();var ON=function(){var r=function(e,t){return r=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(n,o){n.__proto__=o}||function(n,o){for(var i in o)Object.prototype.hasOwnProperty.call(o,i)&&(n[i]=o[i])},r(e,t)};return function(e,t){if(typeof t!="function"&&t!==null)throw new TypeError("Class extends value "+String(t)+" is not a constructor or null");r(e,t);function n(){this.constructor=e}e.prototype=t===null?Object.create(t):(n.prototype=t.prototype,new n)}}(),Il=function(r,e,t,n){function o(i){return i instanceof t?i:new t(function(a){a(i)})}return new(t||(t=Promise))(function(i,a){function l(u){try{s(n.next(u))}catch(d){a(d)}}function c(u){try{s(n.throw(u))}catch(d){a(d)}}function s(u){u.done?i(u.value):o(u.value).then(l,c)}s((n=n.apply(r,e||[])).next())})},Pl=function(r,e){var t={label:0,sent:function(){if(i[0]&1)throw i[1];return i[1]},trys:[],ops:[]},n,o,i,a;return a={next:l(0),throw:l(1),return:l(2)},typeof Symbol=="function"&&(a[Symbol.iterator]=function(){return this}),a;function l(s){return function(u){return c([s,u])}}function c(s){if(n)throw new TypeError("Generator is already executing.");for(;t;)try{if(n=1,o&&(i=s[0]&2?o.return:s[0]?o.throw||((i=o.return)&&i.call(o),0):o.next)&&!(i=i.call(o,s[1])).done)return i;switch(o=0,i&&(s=[s[0]&2,i.value]),s[0]){case 0:case 1:i=s;break;case 4:return t.label++,{value:s[1],done:!1};case 5:t.label++,o=s[1],s=[0];continue;case 7:s=t.ops.pop(),t.trys.pop();continue;default:if(i=t.trys,!(i=i.length>0&&i[i.length-1])&&(s[0]===6||s[0]===2)){t=0;continue}if(s[0]===3&&(!i||s[1]>i[0]&&s[1]<i[3])){t.label=s[1];break}if(s[0]===6&&t.label<i[1]){t.label=i[1],i=s;break}if(i&&t.label<i[2]){t.label=i[2],t.ops.push(s);break}i[2]&&t.ops.pop(),t.trys.pop();continue}s=e.call(r,t)}catch(u){s=[6,u],o=0}finally{n=i=0}if(s[0]&5)throw s[1];return{value:s[0]?s[1]:void 0,done:!0}}},LN=function(r,e){var t=typeof Symbol=="function"&&r[Symbol.iterator];if(!t)return r;var n=t.call(r),o,i=[],a;try{for(;(e===void 0||e-- >0)&&!(o=n.next()).done;)i.push(o.value)}catch(l){a={error:l}}finally{try{o&&!o.done&&(t=n.return)&&t.call(n)}finally{if(a)throw a.error}}return i},NN=function(r,e,t){if(t||arguments.length===2)for(var n=0,o=e.length,i;n<o;n++)(i||!(n in e))&&(i||(i=Array.prototype.slice.call(e,0,n)),i[n]=e[n]);return r.concat(i||Array.prototype.slice.call(e))},wp=function(r){ON(e,r);function e(t){var n,o,i,a,l=r.call(this,{aggregationSelector:(n=t.exporter.selectAggregation)===null||n===void 0?void 0:n.bind(t.exporter),aggregationTemporalitySelector:(o=t.exporter.selectAggregationTemporality)===null||o===void 0?void 0:o.bind(t.exporter),metricProducers:t.metricProducers})||this;if(t.exportIntervalMillis!==void 0&&t.exportIntervalMillis<=0)throw Error("exportIntervalMillis must be greater than 0");if(t.exportTimeoutMillis!==void 0&&t.exportTimeoutMillis<=0)throw Error("exportTimeoutMillis must be greater than 0");if(t.exportTimeoutMillis!==void 0&&t.exportIntervalMillis!==void 0&&t.exportIntervalMillis<t.exportTimeoutMillis)throw Error("exportIntervalMillis must be greater than or equal to exportTimeoutMillis");return l._exportInterval=(i=t.exportIntervalMillis)!==null&&i!==void 0?i:6e4,l._exportTimeout=(a=t.exportTimeoutMillis)!==null&&a!==void 0?a:3e4,l._exporter=t.exporter,l}return e.prototype._runOnce=function(){return Il(this,void 0,void 0,function(){var t;return Pl(this,function(n){switch(n.label){case 0:return n.trys.push([0,2,,3]),[4,hn(this._doRun(),this._exportTimeout)];case 1:return n.sent(),[3,3];case 2:return t=n.sent(),t instanceof dp?(H.error("Export took longer than %s milliseconds and timed out.",this._exportTimeout),[2]):(xl(t),[3,3]);case 3:return[2]}})})},e.prototype._doRun=function(){var t,n;return Il(this,void 0,void 0,function(){var o,i,a,l,c,s;return Pl(this,function(u){switch(u.label){case 0:return[4,this.collect({timeoutMillis:this._exportTimeout})];case 1:if(o=u.sent(),i=o.resourceMetrics,a=o.errors,a.length>0&&(s=H).error.apply(s,NN(["PeriodicExportingMetricReader: metrics collection errors"],LN(a),!1)),!i.resource.asyncAttributesPending)return[3,5];u.label=2;case 2:return u.trys.push([2,4,,5]),[4,(n=(t=i.resource).waitForAsyncAttributes)===null||n===void 0?void 0:n.call(t)];case 3:return u.sent(),[3,5];case 4:return l=u.sent(),H.debug("Error while resolving async portion of resource: ",l),xl(l),[3,5];case 5:return i.scopeMetrics.length===0?[2]:[4,GE._export(this._exporter,i)];case 6:if(c=u.sent(),c.code!==_a.SUCCESS)throw new Error("PeriodicExportingMetricReader: metrics export failed (error "+c.error+")");return[2]}})})},e.prototype.onInitialized=function(){var t=this;this._interval=setInterval(function(){t._runOnce()},this._exportInterval),Ma(this._interval)},e.prototype.onForceFlush=function(){return Il(this,void 0,void 0,function(){return Pl(this,function(t){switch(t.label){case 0:return[4,this._runOnce()];case 1:return t.sent(),[4,this._exporter.forceFlush()];case 2:return t.sent(),[2]}})})},e.prototype.onShutdown=function(){return Il(this,void 0,void 0,function(){return Pl(this,function(t){switch(t.label){case 0:return this._interval&&clearInterval(this._interval),[4,this.onForceFlush()];case 1:return t.sent(),[4,this._exporter.shutdown()];case 2:return t.sent(),[2]}})})},e}(rT);Ce();Ce();function Ol(){return"unknown_service:"+process.argv0}var Sn=function(){return Sn=Object.assign||function(r){for(var e,t=1,n=arguments.length;t<n;t++){e=arguments[t];for(var o in e)Object.prototype.hasOwnProperty.call(e,o)&&(r[o]=e[o])}return r},Sn.apply(this,arguments)},DN=function(r,e,t,n){function o(i){return i instanceof t?i:new t(function(a){a(i)})}return new(t||(t=Promise))(function(i,a){function l(u){try{s(n.next(u))}catch(d){a(d)}}function c(u){try{s(n.throw(u))}catch(d){a(d)}}function s(u){u.done?i(u.value):o(u.value).then(l,c)}s((n=n.apply(r,e||[])).next())})},kN=function(r,e){var t={label:0,sent:function(){if(i[0]&1)throw i[1];return i[1]},trys:[],ops:[]},n,o,i,a;return a={next:l(0),throw:l(1),return:l(2)},typeof Symbol=="function"&&(a[Symbol.iterator]=function(){return this}),a;function l(s){return function(u){return c([s,u])}}function c(s){if(n)throw new TypeError("Generator is already executing.");for(;t;)try{if(n=1,o&&(i=s[0]&2?o.return:s[0]?o.throw||((i=o.return)&&i.call(o),0):o.next)&&!(i=i.call(o,s[1])).done)return i;switch(o=0,i&&(s=[s[0]&2,i.value]),s[0]){case 0:case 1:i=s;break;case 4:return t.label++,{value:s[1],done:!1};case 5:t.label++,o=s[1],s=[0];continue;case 7:s=t.ops.pop(),t.trys.pop();continue;default:if(i=t.trys,!(i=i.length>0&&i[i.length-1])&&(s[0]===6||s[0]===2)){t=0;continue}if(s[0]===3&&(!i||s[1]>i[0]&&s[1]<i[3])){t.label=s[1];break}if(s[0]===6&&t.label<i[1]){t.label=i[1],i=s;break}if(i&&t.label<i[2]){t.label=i[2],t.ops.push(s);break}i[2]&&t.ops.pop(),t.trys.pop();continue}s=e.call(r,t)}catch(u){s=[6,u],o=0}finally{n=i=0}if(s[0]&5)throw s[1];return{value:s[0]?s[1]:void 0,done:!0}}},UN=function(r,e){var t=typeof Symbol=="function"&&r[Symbol.iterator];if(!t)return r;var n=t.call(r),o,i=[],a;try{for(;(e===void 0||e-- >0)&&!(o=n.next()).done;)i.push(o.value)}catch(l){a={error:l}}finally{try{o&&!o.done&&(t=n.return)&&t.call(n)}finally{if(a)throw a.error}}return i},Ll=function(){function r(e,t){var n=this,o;this._attributes=e,this.asyncAttributesPending=t!=null,this._syncAttributes=(o=this._attributes)!==null&&o!==void 0?o:{},this._asyncAttributesPromise=t?.then(function(i){return n._attributes=Object.assign({},n._attributes,i),n.asyncAttributesPending=!1,i},function(i){return H.debug("a resource's async attributes promise rejected: %s",i),n.asyncAttributesPending=!1,{}})}return r.empty=function(){return r.EMPTY},r.default=function(){var e;return new r((e={},e[BE]=Ol(),e[Ca]=Wn[Ca],e[Ra]=Wn[Ra],e[xa]=Wn[xa],e))},Object.defineProperty(r.prototype,"attributes",{get:function(){var e;return this.asyncAttributesPending&&H.error("Accessing resource attributes before async attributes settled"),(e=this._attributes)!==null&&e!==void 0?e:{}},enumerable:!1,configurable:!0}),r.prototype.waitForAsyncAttributes=function(){return DN(this,void 0,void 0,function(){return kN(this,function(e){switch(e.label){case 0:return this.asyncAttributesPending?[4,this._asyncAttributesPromise]:[3,2];case 1:e.sent(),e.label=2;case 2:return[2]}})})},r.prototype.merge=function(e){var t=this,n;if(!e)return this;var o=Sn(Sn({},this._syncAttributes),(n=e._syncAttributes)!==null&&n!==void 0?n:e.attributes);if(!this._asyncAttributesPromise&&!e._asyncAttributesPromise)return new r(o);var i=Promise.all([this._asyncAttributesPromise,e._asyncAttributesPromise]).then(function(a){var l,c=UN(a,2),s=c[0],u=c[1];return Sn(Sn(Sn(Sn({},t._syncAttributes),s),(l=e._syncAttributes)!==null&&l!==void 0?l:e.attributes),u)});return new r(o,i)},r.EMPTY=new r({}),r}();var nT=function(){function r(){this._registeredViews=[]}return r.prototype.addView=function(e){this._registeredViews.push(e)},r.prototype.findViews=function(e,t){var n=this,o=this._registeredViews.filter(function(i){return n._matchInstrument(i.instrumentSelector,e)&&n._matchMeter(i.meterSelector,t)});return o},r.prototype._matchInstrument=function(e,t){return(e.getType()===void 0||t.type===e.getType())&&e.getNameFilter().match(t.name)&&e.getUnitFilter().match(t.unit)},r.prototype._matchMeter=function(e,t){return e.getNameFilter().match(t.name)&&(t.version===void 0||e.getVersionFilter().match(t.version))&&(t.schemaUrl===void 0||e.getSchemaUrlFilter().match(t.schemaUrl))},r}();Ce();var Kn=function(){var r=function(e,t){return r=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(n,o){n.__proto__=o}||function(n,o){for(var i in o)Object.prototype.hasOwnProperty.call(o,i)&&(n[i]=o[i])},r(e,t)};return function(e,t){if(typeof t!="function"&&t!==null)throw new TypeError("Class extends value "+String(t)+" is not a constructor or null");r(e,t);function n(){this.constructor=e}e.prototype=t===null?Object.create(t):(n.prototype=t.prototype,new n)}}(),Nl=function(){function r(e,t){this._writableMetricStorage=e,this._descriptor=t}return r.prototype._record=function(e,t,n){if(t===void 0&&(t={}),n===void 0&&(n=zo.active()),typeof e!="number"){H.warn("non-number value provided to metric "+this._descriptor.name+": "+e);return}this._descriptor.valueType===Bt.INT&&!Number.isInteger(e)&&(H.warn("INT value type cannot accept a floating-point value for "+this._descriptor.name+", ignoring the fractional digits."),e=Math.trunc(e),!Number.isInteger(e))||this._writableMetricStorage.record(e,t,n,$n(Date.now()))},r}();var oT=function(r){Kn(e,r);function e(){return r!==null&&r.apply(this,arguments)||this}return e.prototype.add=function(t,n,o){this._record(t,n,o)},e}(Nl);var iT=function(r){Kn(e,r);function e(){return r!==null&&r.apply(this,arguments)||this}return e.prototype.add=function(t,n,o){if(t<0){H.warn("negative value provided to counter "+this._descriptor.name+": "+t);return}this._record(t,n,o)},e}(Nl);var aT=function(r){Kn(e,r);function e(){return r!==null&&r.apply(this,arguments)||this}return e.prototype.record=function(t,n,o){this._record(t,n,o)},e}(Nl);var sT=function(r){Kn(e,r);function e(){return r!==null&&r.apply(this,arguments)||this}return e.prototype.record=function(t,n,o){if(t<0){H.warn("negative value provided to histogram "+this._descriptor.name+": "+t);return}this._record(t,n,o)},e}(Nl);var Dl=function(){function r(e,t,n){this._observableRegistry=n,this._descriptor=e,this._metricStorages=t}return r.prototype.addCallback=function(e){this._observableRegistry.addCallback(e,this)},r.prototype.removeCallback=function(e){this._observableRegistry.removeCallback(e,this)},r}();var lT=function(r){Kn(e,r);function e(){return r!==null&&r.apply(this,arguments)||this}return e}(Dl);var cT=function(r){Kn(e,r);function e(){return r!==null&&r.apply(this,arguments)||this}return e}(Dl);var uT=function(r){Kn(e,r);function e(){return r!==null&&r.apply(this,arguments)||this}return e}(Dl);function Pa(r){return r instanceof Dl}var dT=function(){function r(e){this._meterSharedState=e}return r.prototype.createGauge=function(e,t){var n=_r(e,ce.GAUGE,t),o=this._meterSharedState.registerMetricStorage(n);return new aT(o,n)},r.prototype.createHistogram=function(e,t){var n=_r(e,ce.HISTOGRAM,t),o=this._meterSharedState.registerMetricStorage(n);return new sT(o,n)},r.prototype.createCounter=function(e,t){var n=_r(e,ce.COUNTER,t),o=this._meterSharedState.registerMetricStorage(n);return new iT(o,n)},r.prototype.createUpDownCounter=function(e,t){var n=_r(e,ce.UP_DOWN_COUNTER,t),o=this._meterSharedState.registerMetricStorage(n);return new oT(o,n)},r.prototype.createObservableGauge=function(e,t){var n=_r(e,ce.OBSERVABLE_GAUGE,t),o=this._meterSharedState.registerAsyncMetricStorage(n);return new cT(n,o,this._meterSharedState.observableRegistry)},r.prototype.createObservableCounter=function(e,t){var n=_r(e,ce.OBSERVABLE_COUNTER,t),o=this._meterSharedState.registerAsyncMetricStorage(n);return new lT(n,o,this._meterSharedState.observableRegistry)},r.prototype.createObservableUpDownCounter=function(e,t){var n=_r(e,ce.OBSERVABLE_UP_DOWN_COUNTER,t),o=this._meterSharedState.registerAsyncMetricStorage(n);return new uT(n,o,this._meterSharedState.observableRegistry)},r.prototype.addBatchObservableCallback=function(e,t){this._meterSharedState.observableRegistry.addBatchCallback(e,t)},r.prototype.removeBatchObservableCallback=function(e,t){this._meterSharedState.observableRegistry.removeBatchCallback(e,t)},r}();var kl=function(){function r(e){this._instrumentDescriptor=e}return r.prototype.getInstrumentDescriptor=function(){return this._instrumentDescriptor},r.prototype.updateDescription=function(e){this._instrumentDescriptor=_r(this._instrumentDescriptor.name,this._instrumentDescriptor.type,{description:e,valueType:this._instrumentDescriptor.valueType,unit:this._instrumentDescriptor.unit,advice:this._instrumentDescriptor.advice})},r}();var FN=function(){var r=function(e,t){return r=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(n,o){n.__proto__=o}||function(n,o){for(var i in o)Object.prototype.hasOwnProperty.call(o,i)&&(n[i]=o[i])},r(e,t)};return function(e,t){if(typeof t!="function"&&t!==null)throw new TypeError("Class extends value "+String(t)+" is not a constructor or null");r(e,t);function n(){this.constructor=e}e.prototype=t===null?Object.create(t):(n.prototype=t.prototype,new n)}}(),pT=function(r,e){var t={label:0,sent:function(){if(i[0]&1)throw i[1];return i[1]},trys:[],ops:[]},n,o,i,a;return a={next:l(0),throw:l(1),return:l(2)},typeof Symbol=="function"&&(a[Symbol.iterator]=function(){return this}),a;function l(s){return function(u){return c([s,u])}}function c(s){if(n)throw new TypeError("Generator is already executing.");for(;t;)try{if(n=1,o&&(i=s[0]&2?o.return:s[0]?o.throw||((i=o.return)&&i.call(o),0):o.next)&&!(i=i.call(o,s[1])).done)return i;switch(o=0,i&&(s=[s[0]&2,i.value]),s[0]){case 0:case 1:i=s;break;case 4:return t.label++,{value:s[1],done:!1};case 5:t.label++,o=s[1],s=[0];continue;case 7:s=t.ops.pop(),t.trys.pop();continue;default:if(i=t.trys,!(i=i.length>0&&i[i.length-1])&&(s[0]===6||s[0]===2)){t=0;continue}if(s[0]===3&&(!i||s[1]>i[0]&&s[1]<i[3])){t.label=s[1];break}if(s[0]===6&&t.label<i[1]){t.label=i[1],i=s;break}if(i&&t.label<i[2]){t.label=i[2],t.ops.push(s);break}i[2]&&t.ops.pop(),t.trys.pop();continue}s=e.call(r,t)}catch(u){s=[6,u],o=0}finally{n=i=0}if(s[0]&5)throw s[1];return{value:s[0]?s[1]:void 0,done:!0}}},BN=function(){function r(e){this._hash=e,this._valueMap=new Map,this._keyMap=new Map}return r.prototype.get=function(e,t){return t??(t=this._hash(e)),this._valueMap.get(t)},r.prototype.getOrDefault=function(e,t){var n=this._hash(e);if(this._valueMap.has(n))return this._valueMap.get(n);var o=t();return this._keyMap.has(n)||this._keyMap.set(n,e),this._valueMap.set(n,o),o},r.prototype.set=function(e,t,n){n??(n=this._hash(e)),this._keyMap.has(n)||this._keyMap.set(n,e),this._valueMap.set(n,t)},r.prototype.has=function(e,t){return t??(t=this._hash(e)),this._valueMap.has(t)},r.prototype.keys=function(){var e,t;return pT(this,function(n){switch(n.label){case 0:e=this._keyMap.entries(),t=e.next(),n.label=1;case 1:return t.done===!0?[3,3]:[4,[t.value[1],t.value[0]]];case 2:return n.sent(),t=e.next(),[3,1];case 3:return[2]}})},r.prototype.entries=function(){var e,t;return pT(this,function(n){switch(n.label){case 0:e=this._valueMap.entries(),t=e.next(),n.label=1;case 1:return t.done===!0?[3,3]:[4,[this._keyMap.get(t.value[0]),t.value[1],t.value[0]]];case 2:return n.sent(),t=e.next(),[3,1];case 3:return[2]}})},Object.defineProperty(r.prototype,"size",{get:function(){return this._valueMap.size},enumerable:!1,configurable:!0}),r}();var gr=function(r){FN(e,r);function e(){return r.call(this,bl)||this}return e}(BN);var zN=function(r,e){var t=typeof Symbol=="function"&&r[Symbol.iterator];if(!t)return r;var n=t.call(r),o,i=[],a;try{for(;(e===void 0||e-- >0)&&!(o=n.next()).done;)i.push(o.value)}catch(l){a={error:l}}finally{try{o&&!o.done&&(t=n.return)&&t.call(n)}finally{if(a)throw a.error}}return i},Ul=function(){function r(e,t){this._aggregator=e,this._activeCollectionStorage=new gr,this._cumulativeMemoStorage=new gr,this._overflowAttributes={"otel.metric.overflow":!0},this._cardinalityLimit=(t??2e3)-1,this._overflowHashCode=bl(this._overflowAttributes)}return r.prototype.record=function(e,t,n,o){var i=this,a=this._activeCollectionStorage.get(t);if(!a){if(this._activeCollectionStorage.size>=this._cardinalityLimit){var l=this._activeCollectionStorage.getOrDefault(this._overflowAttributes,function(){return i._aggregator.createAccumulation(o)});l?.record(e);return}a=this._aggregator.createAccumulation(o),this._activeCollectionStorage.set(t,a)}a?.record(e)},r.prototype.batchCumulate=function(e,t){var n=this;Array.from(e.entries()).forEach(function(o){var i=zN(o,3),a=i[0],l=i[1],c=i[2],s=n._aggregator.createAccumulation(t);s?.record(l);var u=s;if(n._cumulativeMemoStorage.has(a,c)){var d=n._cumulativeMemoStorage.get(a,c);u=n._aggregator.diff(d,s)}else if(n._cumulativeMemoStorage.size>=n._cardinalityLimit&&(a=n._overflowAttributes,c=n._overflowHashCode,n._cumulativeMemoStorage.has(a,c))){var d=n._cumulativeMemoStorage.get(a,c);u=n._aggregator.diff(d,s)}if(n._activeCollectionStorage.has(a,c)){var p=n._activeCollectionStorage.get(a,c);u=n._aggregator.merge(p,u)}n._cumulativeMemoStorage.set(a,s,c),n._activeCollectionStorage.set(a,u,c)})},r.prototype.collect=function(){var e=this._activeCollectionStorage;return this._activeCollectionStorage=new gr,e},r}();var Rp=function(r){var e=typeof Symbol=="function"&&Symbol.iterator,t=e&&r[e],n=0;if(t)return t.call(r);if(r&&typeof r.length=="number")return{next:function(){return r&&n>=r.length&&(r=void 0),{value:r&&r[n++],done:!r}}};throw new TypeError(e?"Object is not iterable.":"Symbol.iterator is not defined.")},mT=function(r,e){var t=typeof Symbol=="function"&&r[Symbol.iterator];if(!t)return r;var n=t.call(r),o,i=[],a;try{for(;(e===void 0||e-- >0)&&!(o=n.next()).done;)i.push(o.value)}catch(l){a={error:l}}finally{try{o&&!o.done&&(t=n.return)&&t.call(n)}finally{if(a)throw a.error}}return i},Fl=function(){function r(e,t){var n=this;this._aggregator=e,this._unreportedAccumulations=new Map,this._reportHistory=new Map,t.forEach(function(o){n._unreportedAccumulations.set(o,[])})}return r.prototype.buildMetrics=function(e,t,n,o){this._stashAccumulations(n);var i=this._getMergedUnreportedAccumulations(e),a=i,l;if(this._reportHistory.has(e)){var c=this._reportHistory.get(e),s=c.collectionTime;l=c.aggregationTemporality,l===$o.CUMULATIVE?a=r.merge(c.accumulations,i,this._aggregator):a=r.calibrateStartTime(c.accumulations,i,s)}else l=e.selectAggregationTemporality(t.type);this._reportHistory.set(e,{accumulations:a,collectionTime:o,aggregationTemporality:l});var u=HN(a);if(u.length!==0)return this._aggregator.toMetricData(t,l,u,o)},r.prototype._stashAccumulations=function(e){var t,n,o=this._unreportedAccumulations.keys();try{for(var i=Rp(o),a=i.next();!a.done;a=i.next()){var l=a.value,c=this._unreportedAccumulations.get(l);c===void 0&&(c=[],this._unreportedAccumulations.set(l,c)),c.push(e)}}catch(s){t={error:s}}finally{try{a&&!a.done&&(n=i.return)&&n.call(i)}finally{if(t)throw t.error}}},r.prototype._getMergedUnreportedAccumulations=function(e){var t,n,o=new gr,i=this._unreportedAccumulations.get(e);if(this._unreportedAccumulations.set(e,[]),i===void 0)return o;try{for(var a=Rp(i),l=a.next();!l.done;l=a.next()){var c=l.value;o=r.merge(o,c,this._aggregator)}}catch(s){t={error:s}}finally{try{l&&!l.done&&(n=a.return)&&n.call(a)}finally{if(t)throw t.error}}return o},r.merge=function(e,t,n){for(var o=e,i=t.entries(),a=i.next();a.done!==!0;){var l=mT(a.value,3),c=l[0],s=l[1],u=l[2];if(e.has(c,u)){var d=e.get(c,u),p=n.merge(d,s);o.set(c,p,u)}else o.set(c,s,u);a=i.next()}return o},r.calibrateStartTime=function(e,t,n){var o,i;try{for(var a=Rp(e.keys()),l=a.next();!l.done;l=a.next()){var c=mT(l.value,2),s=c[0],u=c[1],d=t.get(s,u);d?.setStartTime(n)}}catch(p){o={error:p}}finally{try{l&&!l.done&&(i=a.return)&&i.call(a)}finally{if(o)throw o.error}}return t},r}();function HN(r){return Array.from(r.entries())}var GN=function(){var r=function(e,t){return r=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(n,o){n.__proto__=o}||function(n,o){for(var i in o)Object.prototype.hasOwnProperty.call(o,i)&&(n[i]=o[i])},r(e,t)};return function(e,t){if(typeof t!="function"&&t!==null)throw new TypeError("Class extends value "+String(t)+" is not a constructor or null");r(e,t);function n(){this.constructor=e}e.prototype=t===null?Object.create(t):(n.prototype=t.prototype,new n)}}(),VN=function(r,e){var t=typeof Symbol=="function"&&r[Symbol.iterator];if(!t)return r;var n=t.call(r),o,i=[],a;try{for(;(e===void 0||e-- >0)&&!(o=n.next()).done;)i.push(o.value)}catch(l){a={error:l}}finally{try{o&&!o.done&&(t=n.return)&&t.call(n)}finally{if(a)throw a.error}}return i},gT=function(r){GN(e,r);function e(t,n,o,i,a){var l=r.call(this,t)||this;return l._attributesProcessor=o,l._aggregationCardinalityLimit=a,l._deltaMetricStorage=new Ul(n,l._aggregationCardinalityLimit),l._temporalMetricStorage=new Fl(n,i),l}return e.prototype.record=function(t,n){var o=this,i=new gr;Array.from(t.entries()).forEach(function(a){var l=VN(a,2),c=l[0],s=l[1];i.set(o._attributesProcessor.process(c),s)}),this._deltaMetricStorage.batchCumulate(i,n)},e.prototype.collect=function(t,n){var o=this._deltaMetricStorage.collect();return this._temporalMetricStorage.buildMetrics(t,this._instrumentDescriptor,o,n)},e}(kl);Ce();function Cp(r,e){var t="";return r.unit!==e.unit&&(t+=" - Unit '"+r.unit+"' does not match '"+e.unit+`'
|
|
20
|
+
`),r.type!==e.type&&(t+=" - Type '"+r.type+"' does not match '"+e.type+`'
|
|
21
|
+
`),r.valueType!==e.valueType&&(t+=" - Value Type '"+r.valueType+"' does not match '"+e.valueType+`'
|
|
22
|
+
`),r.description!==e.description&&(t+=" - Description '"+r.description+"' does not match '"+e.description+`'
|
|
23
|
+
`),t}function jN(r,e){return" - use valueType '"+r.valueType+"' on instrument creation or use an instrument name other than '"+e.name+"'"}function WN(r,e){return" - use unit '"+r.unit+"' on instrument creation or use an instrument name other than '"+e.name+"'"}function $N(r,e){var t={name:e.name,type:e.type,unit:e.unit},n=JSON.stringify(t);return" - create a new view with a name other than '"+r.name+"' and InstrumentSelector '"+n+"'"}function qN(r,e){var t={name:e.name,type:e.type,unit:e.unit},n=JSON.stringify(t);return" - create a new view with a name other than '"+r.name+"' and InstrumentSelector '"+n+`'
|
|
24
|
+
- OR - create a new view with the name `+r.name+" and description '"+r.description+"' and InstrumentSelector "+n+`
|
|
25
|
+
- OR - create a new view with the name `+e.name+" and description '"+r.description+"' and InstrumentSelector "+n}function xp(r,e){return r.valueType!==e.valueType?jN(r,e):r.unit!==e.unit?WN(r,e):r.type!==e.type?$N(r,e):r.description!==e.description?qN(r,e):""}var Mp=function(r){var e=typeof Symbol=="function"&&Symbol.iterator,t=e&&r[e],n=0;if(t)return t.call(r);if(r&&typeof r.length=="number")return{next:function(){return r&&n>=r.length&&(r=void 0),{value:r&&r[n++],done:!r}}};throw new TypeError(e?"Object is not iterable.":"Symbol.iterator is not defined.")},hT=function(){function r(){this._sharedRegistry=new Map,this._perCollectorRegistry=new Map}return r.create=function(){return new r},r.prototype.getStorages=function(e){var t,n,o,i,a=[];try{for(var l=Mp(this._sharedRegistry.values()),c=l.next();!c.done;c=l.next()){var s=c.value;a=a.concat(s)}}catch(m){t={error:m}}finally{try{c&&!c.done&&(n=l.return)&&n.call(l)}finally{if(t)throw t.error}}var u=this._perCollectorRegistry.get(e);if(u!=null)try{for(var d=Mp(u.values()),p=d.next();!p.done;p=d.next()){var s=p.value;a=a.concat(s)}}catch(m){o={error:m}}finally{try{p&&!p.done&&(i=d.return)&&i.call(d)}finally{if(o)throw o.error}}return a},r.prototype.register=function(e){this._registerStorage(e,this._sharedRegistry)},r.prototype.registerForCollector=function(e,t){var n=this._perCollectorRegistry.get(e);n==null&&(n=new Map,this._perCollectorRegistry.set(e,n)),this._registerStorage(t,n)},r.prototype.findOrUpdateCompatibleStorage=function(e){var t=this._sharedRegistry.get(e.name);return t===void 0?null:this._findOrUpdateCompatibleStorage(e,t)},r.prototype.findOrUpdateCompatibleCollectorStorage=function(e,t){var n=this._perCollectorRegistry.get(e);if(n===void 0)return null;var o=n.get(t.name);return o===void 0?null:this._findOrUpdateCompatibleStorage(t,o)},r.prototype._registerStorage=function(e,t){var n=e.getInstrumentDescriptor(),o=t.get(n.name);if(o===void 0){t.set(n.name,[e]);return}o.push(e)},r.prototype._findOrUpdateCompatibleStorage=function(e,t){var n,o,i=null;try{for(var a=Mp(t),l=a.next();!l.done;l=a.next()){var c=l.value,s=c.getInstrumentDescriptor();RE(s,e)?(s.description!==e.description&&(e.description.length>s.description.length&&c.updateDescription(e.description),H.warn("A view or instrument with the name ",e.name,` has already been registered, but has a different description and is incompatible with another registered view.
|
|
26
|
+
`,`Details:
|
|
27
|
+
`,Cp(s,e),`The longer description will be used.
|
|
28
|
+
To resolve the conflict:`,xp(s,e))),i=c):H.warn("A view or instrument with the name ",e.name,` has already been registered and is incompatible with another registered view.
|
|
29
|
+
`,`Details:
|
|
30
|
+
`,Cp(s,e),`To resolve the conflict:
|
|
31
|
+
`,xp(s,e))}}catch(u){n={error:u}}finally{try{l&&!l.done&&(o=a.return)&&o.call(a)}finally{if(n)throw n.error}}return i},r}();var fT=function(){function r(e){this._backingStorages=e}return r.prototype.record=function(e,t,n,o){this._backingStorages.forEach(function(i){i.record(e,t,n,o)})},r}();Ce();Ce();var ST=function(){function r(e,t){this._instrumentName=e,this._valueType=t,this._buffer=new gr}return r.prototype.observe=function(e,t){if(t===void 0&&(t={}),typeof e!="number"){H.warn("non-number value provided to metric "+this._instrumentName+": "+e);return}this._valueType===Bt.INT&&!Number.isInteger(e)&&(H.warn("INT value type cannot accept a floating-point value for "+this._instrumentName+", ignoring the fractional digits."),e=Math.trunc(e),!Number.isInteger(e))||this._buffer.set(t,e)},r}();var yT=function(){function r(){this._buffer=new Map}return r.prototype.observe=function(e,t,n){if(n===void 0&&(n={}),!!Pa(e)){var o=this._buffer.get(e);if(o==null&&(o=new gr,this._buffer.set(e,o)),typeof t!="number"){H.warn("non-number value provided to metric "+e._descriptor.name+": "+t);return}e._descriptor.valueType===Bt.INT&&!Number.isInteger(t)&&(H.warn("INT value type cannot accept a floating-point value for "+e._descriptor.name+", ignoring the fractional digits."),t=Math.trunc(t),!Number.isInteger(t))||o.set(n,t)}},r}();var _p=function(r,e,t,n){function o(i){return i instanceof t?i:new t(function(a){a(i)})}return new(t||(t=Promise))(function(i,a){function l(u){try{s(n.next(u))}catch(d){a(d)}}function c(u){try{s(n.throw(u))}catch(d){a(d)}}function s(u){u.done?i(u.value):o(u.value).then(l,c)}s((n=n.apply(r,e||[])).next())})},Ip=function(r,e){var t={label:0,sent:function(){if(i[0]&1)throw i[1];return i[1]},trys:[],ops:[]},n,o,i,a;return a={next:l(0),throw:l(1),return:l(2)},typeof Symbol=="function"&&(a[Symbol.iterator]=function(){return this}),a;function l(s){return function(u){return c([s,u])}}function c(s){if(n)throw new TypeError("Generator is already executing.");for(;t;)try{if(n=1,o&&(i=s[0]&2?o.return:s[0]?o.throw||((i=o.return)&&i.call(o),0):o.next)&&!(i=i.call(o,s[1])).done)return i;switch(o=0,i&&(s=[s[0]&2,i.value]),s[0]){case 0:case 1:i=s;break;case 4:return t.label++,{value:s[1],done:!1};case 5:t.label++,o=s[1],s=[0];continue;case 7:s=t.ops.pop(),t.trys.pop();continue;default:if(i=t.trys,!(i=i.length>0&&i[i.length-1])&&(s[0]===6||s[0]===2)){t=0;continue}if(s[0]===3&&(!i||s[1]>i[0]&&s[1]<i[3])){t.label=s[1];break}if(s[0]===6&&t.label<i[1]){t.label=i[1],i=s;break}if(i&&t.label<i[2]){t.label=i[2],t.ops.push(s);break}i[2]&&t.ops.pop(),t.trys.pop();continue}s=e.call(r,t)}catch(u){s=[6,u],o=0}finally{n=i=0}if(s[0]&5)throw s[1];return{value:s[0]?s[1]:void 0,done:!0}}},bT=function(r,e){var t=typeof Symbol=="function"&&r[Symbol.iterator];if(!t)return r;var n=t.call(r),o,i=[],a;try{for(;(e===void 0||e-- >0)&&!(o=n.next()).done;)i.push(o.value)}catch(l){a={error:l}}finally{try{o&&!o.done&&(t=n.return)&&t.call(n)}finally{if(a)throw a.error}}return i},ET=function(r,e,t){if(t||arguments.length===2)for(var n=0,o=e.length,i;n<o;n++)(i||!(n in e))&&(i||(i=Array.prototype.slice.call(e,0,n)),i[n]=e[n]);return r.concat(i||Array.prototype.slice.call(e))},TT=function(){function r(){this._callbacks=[],this._batchCallbacks=[]}return r.prototype.addCallback=function(e,t){var n=this._findCallback(e,t);n>=0||this._callbacks.push({callback:e,instrument:t})},r.prototype.removeCallback=function(e,t){var n=this._findCallback(e,t);n<0||this._callbacks.splice(n,1)},r.prototype.addBatchCallback=function(e,t){var n=new Set(t.filter(Pa));if(n.size===0){H.error("BatchObservableCallback is not associated with valid instruments",t);return}var o=this._findBatchCallback(e,n);o>=0||this._batchCallbacks.push({callback:e,instruments:n})},r.prototype.removeBatchCallback=function(e,t){var n=new Set(t.filter(Pa)),o=this._findBatchCallback(e,n);o<0||this._batchCallbacks.splice(o,1)},r.prototype.observe=function(e,t){return _p(this,void 0,void 0,function(){var n,o,i,a;return Ip(this,function(l){switch(l.label){case 0:return n=this._observeCallbacks(e,t),o=this._observeBatchCallbacks(e,t),[4,bE(ET(ET([],bT(n),!1),bT(o),!1))];case 1:return i=l.sent(),a=i.filter(EE).map(function(c){return c.reason}),[2,a]}})})},r.prototype._observeCallbacks=function(e,t){var n=this;return this._callbacks.map(function(o){var i=o.callback,a=o.instrument;return _p(n,void 0,void 0,function(){var l,c;return Ip(this,function(s){switch(s.label){case 0:return l=new ST(a._descriptor.name,a._descriptor.valueType),c=Promise.resolve(i(l)),t!=null&&(c=hn(c,t)),[4,c];case 1:return s.sent(),a._metricStorages.forEach(function(u){u.record(l._buffer,e)}),[2]}})})})},r.prototype._observeBatchCallbacks=function(e,t){var n=this;return this._batchCallbacks.map(function(o){var i=o.callback,a=o.instruments;return _p(n,void 0,void 0,function(){var l,c;return Ip(this,function(s){switch(s.label){case 0:return l=new yT,c=Promise.resolve(i(l)),t!=null&&(c=hn(c,t)),[4,c];case 1:return s.sent(),a.forEach(function(u){var d=l._buffer.get(u);d!=null&&u._metricStorages.forEach(function(p){p.record(d,e)})}),[2]}})})})},r.prototype._findCallback=function(e,t){return this._callbacks.findIndex(function(n){return n.callback===e&&n.instrument===t})},r.prototype._findBatchCallback=function(e,t){return this._batchCallbacks.findIndex(function(n){return n.callback===e&&TE(n.instruments,t)})},r}();var KN=function(){var r=function(e,t){return r=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(n,o){n.__proto__=o}||function(n,o){for(var i in o)Object.prototype.hasOwnProperty.call(o,i)&&(n[i]=o[i])},r(e,t)};return function(e,t){if(typeof t!="function"&&t!==null)throw new TypeError("Class extends value "+String(t)+" is not a constructor or null");r(e,t);function n(){this.constructor=e}e.prototype=t===null?Object.create(t):(n.prototype=t.prototype,new n)}}(),vT=function(r){KN(e,r);function e(t,n,o,i,a){var l=r.call(this,t)||this;return l._attributesProcessor=o,l._aggregationCardinalityLimit=a,l._deltaMetricStorage=new Ul(n,l._aggregationCardinalityLimit),l._temporalMetricStorage=new Fl(n,i),l}return e.prototype.record=function(t,n,o,i){n=this._attributesProcessor.process(n,o),this._deltaMetricStorage.record(t,n,o,i)},e.prototype.collect=function(t,n){var o=this._deltaMetricStorage.collect();return this._temporalMetricStorage.buildMetrics(t,this._instrumentDescriptor,o,n)},e}(kl);var AT=function(){var r=function(e,t){return r=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(n,o){n.__proto__=o}||function(n,o){for(var i in o)Object.prototype.hasOwnProperty.call(o,i)&&(n[i]=o[i])},r(e,t)};return function(e,t){if(typeof t!="function"&&t!==null)throw new TypeError("Class extends value "+String(t)+" is not a constructor or null");r(e,t);function n(){this.constructor=e}e.prototype=t===null?Object.create(t):(n.prototype=t.prototype,new n)}}(),Xo=function(){function r(){}return r.Noop=function(){return XN},r}();var YN=function(r){AT(e,r);function e(){return r!==null&&r.apply(this,arguments)||this}return e.prototype.process=function(t,n){return t},e}(Xo);var wT=function(r){AT(e,r);function e(t){var n=r.call(this)||this;return n._allowedAttributeNames=t,n}return e.prototype.process=function(t,n){var o=this,i={};return Object.keys(t).filter(function(a){return o._allowedAttributeNames.includes(a)}).forEach(function(a){return i[a]=t[a]}),i},e}(Xo);var XN=new YN;var JN=function(r,e,t,n){function o(i){return i instanceof t?i:new t(function(a){a(i)})}return new(t||(t=Promise))(function(i,a){function l(u){try{s(n.next(u))}catch(d){a(d)}}function c(u){try{s(n.throw(u))}catch(d){a(d)}}function s(u){u.done?i(u.value):o(u.value).then(l,c)}s((n=n.apply(r,e||[])).next())})},ZN=function(r,e){var t={label:0,sent:function(){if(i[0]&1)throw i[1];return i[1]},trys:[],ops:[]},n,o,i,a;return a={next:l(0),throw:l(1),return:l(2)},typeof Symbol=="function"&&(a[Symbol.iterator]=function(){return this}),a;function l(s){return function(u){return c([s,u])}}function c(s){if(n)throw new TypeError("Generator is already executing.");for(;t;)try{if(n=1,o&&(i=s[0]&2?o.return:s[0]?o.throw||((i=o.return)&&i.call(o),0):o.next)&&!(i=i.call(o,s[1])).done)return i;switch(o=0,i&&(s=[s[0]&2,i.value]),s[0]){case 0:case 1:i=s;break;case 4:return t.label++,{value:s[1],done:!1};case 5:t.label++,o=s[1],s=[0];continue;case 7:s=t.ops.pop(),t.trys.pop();continue;default:if(i=t.trys,!(i=i.length>0&&i[i.length-1])&&(s[0]===6||s[0]===2)){t=0;continue}if(s[0]===3&&(!i||s[1]>i[0]&&s[1]<i[3])){t.label=s[1];break}if(s[0]===6&&t.label<i[1]){t.label=i[1],i=s;break}if(i&&t.label<i[2]){t.label=i[2],t.ops.push(s);break}i[2]&&t.ops.pop(),t.trys.pop();continue}s=e.call(r,t)}catch(u){s=[6,u],o=0}finally{n=i=0}if(s[0]&5)throw s[1];return{value:s[0]?s[1]:void 0,done:!0}}},QN=function(r,e){var t=typeof Symbol=="function"&&r[Symbol.iterator];if(!t)return r;var n=t.call(r),o,i=[],a;try{for(;(e===void 0||e-- >0)&&!(o=n.next()).done;)i.push(o.value)}catch(l){a={error:l}}finally{try{o&&!o.done&&(t=n.return)&&t.call(n)}finally{if(a)throw a.error}}return i},RT=function(){function r(e,t){this._meterProviderSharedState=e,this._instrumentationScope=t,this.metricStorageRegistry=new hT,this.observableRegistry=new TT,this.meter=new dT(this)}return r.prototype.registerMetricStorage=function(e){var t=this._registerMetricStorage(e,vT);return t.length===1?t[0]:new fT(t)},r.prototype.registerAsyncMetricStorage=function(e){var t=this._registerMetricStorage(e,gT);return t},r.prototype.collect=function(e,t,n){return JN(this,void 0,void 0,function(){var o,i,a;return ZN(this,function(l){switch(l.label){case 0:return[4,this.observableRegistry.observe(t,n?.timeoutMillis)];case 1:return o=l.sent(),i=this.metricStorageRegistry.getStorages(e),i.length===0?[2,null]:(a=i.map(function(c){return c.collect(e,t)}).filter(SE),a.length===0?[2,{errors:o}]:[2,{scopeMetrics:{scope:this._instrumentationScope,metrics:a},errors:o}])}})})},r.prototype._registerMetricStorage=function(e,t){var n=this,o=this._meterProviderSharedState.viewRegistry.findViews(e,this._instrumentationScope),i=o.map(function(c){var s=wE(c,e),u=n.metricStorageRegistry.findOrUpdateCompatibleStorage(s);if(u!=null)return u;var d=c.aggregation.createAggregator(s),p=new t(s,d,c.attributesProcessor,n._meterProviderSharedState.metricCollectors,c.aggregationCardinalityLimit);return n.metricStorageRegistry.register(p),p});if(i.length===0){var a=this._meterProviderSharedState.selectAggregations(e.type),l=a.map(function(c){var s=QN(c,2),u=s[0],d=s[1],p=n.metricStorageRegistry.findOrUpdateCompatibleCollectorStorage(u,e);if(p!=null)return p;var m=d.createAggregator(e),g=u.selectCardinalityLimit(e.type),h=new t(e,m,Xo.Noop(),[u],g);return n.metricStorageRegistry.registerForCollector(u,h),h});i=i.concat(l)}return i},r}();var eD=function(r){var e=typeof Symbol=="function"&&Symbol.iterator,t=e&&r[e],n=0;if(t)return t.call(r);if(r&&typeof r.length=="number")return{next:function(){return r&&n>=r.length&&(r=void 0),{value:r&&r[n++],done:!r}}};throw new TypeError(e?"Object is not iterable.":"Symbol.iterator is not defined.")},CT=function(){function r(e){this.resource=e,this.viewRegistry=new nT,this.metricCollectors=[],this.meterSharedStates=new Map}return r.prototype.getMeterSharedState=function(e){var t=yE(e),n=this.meterSharedStates.get(t);return n==null&&(n=new RT(this,e),this.meterSharedStates.set(t,n)),n},r.prototype.selectAggregations=function(e){var t,n,o=[];try{for(var i=eD(this.metricCollectors),a=i.next();!a.done;a=i.next()){var l=a.value;o.push([l,l.selectAggregation(e)])}}catch(c){t={error:c}}finally{try{a&&!a.done&&(n=i.return)&&n.call(i)}finally{if(t)throw t.error}}return o},r}();var Bl=function(r,e,t,n){function o(i){return i instanceof t?i:new t(function(a){a(i)})}return new(t||(t=Promise))(function(i,a){function l(u){try{s(n.next(u))}catch(d){a(d)}}function c(u){try{s(n.throw(u))}catch(d){a(d)}}function s(u){u.done?i(u.value):o(u.value).then(l,c)}s((n=n.apply(r,e||[])).next())})},zl=function(r,e){var t={label:0,sent:function(){if(i[0]&1)throw i[1];return i[1]},trys:[],ops:[]},n,o,i,a;return a={next:l(0),throw:l(1),return:l(2)},typeof Symbol=="function"&&(a[Symbol.iterator]=function(){return this}),a;function l(s){return function(u){return c([s,u])}}function c(s){if(n)throw new TypeError("Generator is already executing.");for(;t;)try{if(n=1,o&&(i=s[0]&2?o.return:s[0]?o.throw||((i=o.return)&&i.call(o),0):o.next)&&!(i=i.call(o,s[1])).done)return i;switch(o=0,i&&(s=[s[0]&2,i.value]),s[0]){case 0:case 1:i=s;break;case 4:return t.label++,{value:s[1],done:!1};case 5:t.label++,o=s[1],s=[0];continue;case 7:s=t.ops.pop(),t.trys.pop();continue;default:if(i=t.trys,!(i=i.length>0&&i[i.length-1])&&(s[0]===6||s[0]===2)){t=0;continue}if(s[0]===3&&(!i||s[1]>i[0]&&s[1]<i[3])){t.label=s[1];break}if(s[0]===6&&t.label<i[1]){t.label=i[1],i=s;break}if(i&&t.label<i[2]){t.label=i[2],t.ops.push(s);break}i[2]&&t.ops.pop(),t.trys.pop();continue}s=e.call(r,t)}catch(u){s=[6,u],o=0}finally{n=i=0}if(s[0]&5)throw s[1];return{value:s[0]?s[1]:void 0,done:!0}}},tD=function(r,e){var t=typeof Symbol=="function"&&r[Symbol.iterator];if(!t)return r;var n=t.call(r),o,i=[],a;try{for(;(e===void 0||e-- >0)&&!(o=n.next()).done;)i.push(o.value)}catch(l){a={error:l}}finally{try{o&&!o.done&&(t=n.return)&&t.call(n)}finally{if(a)throw a.error}}return i},rD=function(r,e,t){if(t||arguments.length===2)for(var n=0,o=e.length,i;n<o;n++)(i||!(n in e))&&(i||(i=Array.prototype.slice.call(e,0,n)),i[n]=e[n]);return r.concat(i||Array.prototype.slice.call(e))},xT=function(){function r(e,t){this._sharedState=e,this._metricReader=t}return r.prototype.collect=function(e){return Bl(this,void 0,void 0,function(){var t,n,o,i,a=this;return zl(this,function(l){switch(l.label){case 0:return t=$n(Date.now()),n=[],o=[],i=Array.from(this._sharedState.meterSharedStates.values()).map(function(c){return Bl(a,void 0,void 0,function(){var s;return zl(this,function(u){switch(u.label){case 0:return[4,c.collect(this,t,e)];case 1:return s=u.sent(),s?.scopeMetrics!=null&&n.push(s.scopeMetrics),s?.errors!=null&&o.push.apply(o,rD([],tD(s.errors),!1)),[2]}})})}),[4,Promise.all(i)];case 1:return l.sent(),[2,{resourceMetrics:{resource:this._sharedState.resource,scopeMetrics:n},errors:o}]}})})},r.prototype.forceFlush=function(e){return Bl(this,void 0,void 0,function(){return zl(this,function(t){switch(t.label){case 0:return[4,this._metricReader.forceFlush(e)];case 1:return t.sent(),[2]}})})},r.prototype.shutdown=function(e){return Bl(this,void 0,void 0,function(){return zl(this,function(t){switch(t.label){case 0:return[4,this._metricReader.shutdown(e)];case 1:return t.sent(),[2]}})})},r.prototype.selectAggregationTemporality=function(e){return this._metricReader.selectAggregationTemporality(e)},r.prototype.selectAggregation=function(e){return this._metricReader.selectAggregation(e)},r.prototype.selectCardinalityLimit=function(e){var t,n,o;return(o=(n=(t=this._metricReader).selectCardinalityLimit)===null||n===void 0?void 0:n.call(t,e))!==null&&o!==void 0?o:2e3},r}();var MT=function(r,e,t,n){function o(i){return i instanceof t?i:new t(function(a){a(i)})}return new(t||(t=Promise))(function(i,a){function l(u){try{s(n.next(u))}catch(d){a(d)}}function c(u){try{s(n.throw(u))}catch(d){a(d)}}function s(u){u.done?i(u.value):o(u.value).then(l,c)}s((n=n.apply(r,e||[])).next())})},_T=function(r,e){var t={label:0,sent:function(){if(i[0]&1)throw i[1];return i[1]},trys:[],ops:[]},n,o,i,a;return a={next:l(0),throw:l(1),return:l(2)},typeof Symbol=="function"&&(a[Symbol.iterator]=function(){return this}),a;function l(s){return function(u){return c([s,u])}}function c(s){if(n)throw new TypeError("Generator is already executing.");for(;t;)try{if(n=1,o&&(i=s[0]&2?o.return:s[0]?o.throw||((i=o.return)&&i.call(o),0):o.next)&&!(i=i.call(o,s[1])).done)return i;switch(o=0,i&&(s=[s[0]&2,i.value]),s[0]){case 0:case 1:i=s;break;case 4:return t.label++,{value:s[1],done:!1};case 5:t.label++,o=s[1],s=[0];continue;case 7:s=t.ops.pop(),t.trys.pop();continue;default:if(i=t.trys,!(i=i.length>0&&i[i.length-1])&&(s[0]===6||s[0]===2)){t=0;continue}if(s[0]===3&&(!i||s[1]>i[0]&&s[1]<i[3])){t.label=s[1];break}if(s[0]===6&&t.label<i[1]){t.label=i[1],i=s;break}if(i&&t.label<i[2]){t.label=i[2],t.ops.push(s);break}i[2]&&t.ops.pop(),t.trys.pop();continue}s=e.call(r,t)}catch(u){s=[6,u],o=0}finally{n=i=0}if(s[0]&5)throw s[1];return{value:s[0]?s[1]:void 0,done:!0}}},IT=function(r){var e=typeof Symbol=="function"&&Symbol.iterator,t=e&&r[e],n=0;if(t)return t.call(r);if(r&&typeof r.length=="number")return{next:function(){return r&&n>=r.length&&(r=void 0),{value:r&&r[n++],done:!r}}};throw new TypeError(e?"Object is not iterable.":"Symbol.iterator is not defined.")};function nD(r,e){var t=e??Ll.empty();return r?Ll.default().merge(t):t}var Pp=function(){function r(e){var t,n,o,i,a;if(this._shutdown=!1,this._sharedState=new CT(nD((a=e?.mergeResourceWithDefaults)!==null&&a!==void 0?a:!0,e?.resource)),e?.views!=null&&e.views.length>0)try{for(var l=IT(e.views),c=l.next();!c.done;c=l.next()){var s=c.value;this._sharedState.viewRegistry.addView(s)}}catch(m){t={error:m}}finally{try{c&&!c.done&&(n=l.return)&&n.call(l)}finally{if(t)throw t.error}}if(e?.readers!=null&&e.readers.length>0)try{for(var u=IT(e.readers),d=u.next();!d.done;d=u.next()){var p=d.value;this.addMetricReader(p)}}catch(m){o={error:m}}finally{try{d&&!d.done&&(i=u.return)&&i.call(u)}finally{if(o)throw o.error}}}return r.prototype.getMeter=function(e,t,n){return t===void 0&&(t=""),n===void 0&&(n={}),this._shutdown?(H.warn("A shutdown MeterProvider cannot provide a Meter"),kd()):this._sharedState.getMeterSharedState({name:e,version:t,schemaUrl:n.schemaUrl}).meter},r.prototype.addMetricReader=function(e){var t=new xT(this._sharedState,e);e.setMetricProducer(t),this._sharedState.metricCollectors.push(t)},r.prototype.shutdown=function(e){return MT(this,void 0,void 0,function(){return _T(this,function(t){switch(t.label){case 0:return this._shutdown?(H.warn("shutdown may only be called once per MeterProvider"),[2]):(this._shutdown=!0,[4,Promise.all(this._sharedState.metricCollectors.map(function(n){return n.shutdown(e)}))]);case 1:return t.sent(),[2]}})})},r.prototype.forceFlush=function(e){return MT(this,void 0,void 0,function(){return _T(this,function(t){switch(t.label){case 0:return this._shutdown?(H.warn("invalid attempt to force flush after MeterProvider shutdown"),[2]):[4,Promise.all(this._sharedState.metricCollectors.map(function(n){return n.forceFlush(e)}))];case 1:return t.sent(),[2]}})})},r}();var oD=/[\^$\\.+?()[\]{}|]/g,Hl=function(){function r(e){e==="*"?(this._matchAll=!0,this._regexp=/.*/):(this._matchAll=!1,this._regexp=new RegExp(r.escapePattern(e)))}return r.prototype.match=function(e){return this._matchAll?!0:this._regexp.test(e)},r.escapePattern=function(e){return"^"+e.replace(oD,"\\$&").replace("*",".*")+"$"},r.hasWildcard=function(e){return e.includes("*")},r}();var Jo=function(){function r(e){this._matchAll=e===void 0,this._pattern=e}return r.prototype.match=function(e){return!!(this._matchAll||e===this._pattern)},r}();var PT=function(){function r(e){var t;this._nameFilter=new Hl((t=e?.name)!==null&&t!==void 0?t:"*"),this._type=e?.type,this._unitFilter=new Jo(e?.unit)}return r.prototype.getType=function(){return this._type},r.prototype.getNameFilter=function(){return this._nameFilter},r.prototype.getUnitFilter=function(){return this._unitFilter},r}();var OT=function(){function r(e){this._nameFilter=new Jo(e?.name),this._versionFilter=new Jo(e?.version),this._schemaUrlFilter=new Jo(e?.schemaUrl)}return r.prototype.getNameFilter=function(){return this._nameFilter},r.prototype.getVersionFilter=function(){return this._versionFilter},r.prototype.getSchemaUrlFilter=function(){return this._schemaUrlFilter},r}();function iD(r){return r.instrumentName==null&&r.instrumentType==null&&r.instrumentUnit==null&&r.meterName==null&&r.meterVersion==null&&r.meterSchemaUrl==null}var Gl=function(){function r(e){var t;if(iD(e))throw new Error("Cannot create view with no selector arguments supplied");if(e.name!=null&&(e?.instrumentName==null||Hl.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 wT(e.attributeKeys):this.attributesProcessor=Xo.Noop(),this.name=e.name,this.description=e.description,this.aggregation=(t=e.aggregation)!==null&&t!==void 0?t:ir.Default(),this.instrumentSelector=new PT({name:e.instrumentName,type:e.instrumentType,unit:e.instrumentUnit}),this.meterSelector=new OT({name:e.meterName,version:e.meterVersion,schemaUrl:e.meterSchemaUrl}),this.aggregationCardinalityLimit=e.aggregationCardinalityLimit}return r}();var Woe=process.env.APP||"unknown";Ce();import{v4 as aD}from"uuid";function sD(){return new gE({url:"https://us-west.metrics.momentic.ai/v1/metrics",headers:{"x-momentic-metrics-api-key":"c60c6a0f-60da-41a7-a61b-07969a0aa303"},temporalityPreference:jn.DELTA})}var lD=[new Gl({instrumentName:"test_event_duration",instrumentType:ce.HISTOGRAM,aggregation:new Ia([100,500,1e3,5e3,7500,1e4,15e3,2e4])}),new Gl({instrumentName:"test_step_duration",instrumentType:ce.HISTOGRAM,aggregation:new Ia([100,500,1e3,5e3,7500,1e4,15e3,2e4])})],jl=class{globalAttributes;provider;meter;counterCache=new Map;histogramCache=new Map;observableGaugeCache=new Map;gaugeValues=new Map;getCounter(e){let t=this.counterCache.get(e);if(t)return t;let n=this.meter.createCounter(e);return this.counterCache.set(e,n),n}getHistogram(e){let t=this.histogramCache.get(e);if(t)return t;let n=this.meter.createHistogram(e);return this.histogramCache.set(e,n),n}ensureObservableGauge(e){let t=this.observableGaugeCache.get(e);if(t)return t;let n=this.meter.createObservableGauge(e);return n.addCallback(o=>{let i=this.gaugeValues.get(e);i!==void 0&&o.observe(i,this.globalAttributes)}),this.observableGaugeCache.set(e,n),n}constructor(e){this.globalAttributes={...e.globalAttributes??{}};let t=typeof process<"u"?"production":"unknown",n=new ep({[sl]:e.serviceName,[ub]:t,[pb]:typeof process<"u"&&process.env.SERVICE_INSTANCE_ID?process.env.SERVICE_INSTANCE_ID:aD()}),o=sD(),i=new wp({exporter:o,exportIntervalMillis:e.exportIntervalMs??15e3});this.provider=new Pp({resource:n,readers:[i],views:lD}),nl.setGlobalMeterProvider(this.provider),this.meter=nl.getMeter("momentic-serverless")}increment(e,t,n){try{let o=el(n,this.globalAttributes);this.getCounter(e).add(typeof t=="number"?t:1,o)}catch{}}gauge(e,t){try{this.ensureObservableGauge(e),this.gaugeValues.set(e,t)}catch{}}distribution(e,t,n){try{let o=el(n,this.globalAttributes);this.getHistogram(e).record(t,o)}catch{}}async flush(){try{await this.provider.forceFlush()}catch{}}async recordDuration({fn:e,name:t,tags:n}){let o=Date.now();try{return await Promise.resolve(e())}finally{this.distribution(t,Date.now()-o,n)}}};var vt=new Qs;function LT(r){r.disabled||(vt=new jl(r))}import{hostname as dD}from"os";import pD from"path";async function NT(r){let{apiClient:e,logger:t,creationOpts:n,onStatusUpdate:o,logLevel:i,orgId:a}=r,{token:l,webRtcUrl:c,adbUrl:s,name:u,apkDownloadUrl:d,region:p}=await e.createAndroidEmulator({...n,hostname:dD()}),m;try{uD("adb --version"),m="adb"}catch{if(process.env.ANDROID_HOME)m=pD.join(process.env.ANDROID_HOME,"platform-tools","adb");else throw new Error("The adb binary was not found in PATH and ANDROID_HOME is not set either")}t.info({emulatorName:u,apkToInstall:n.apkToInstall,region:p,apkDownloadUrl:d},"Android instance creation ok");let g=await vt.recordDuration({fn:async()=>await cD({adbUrl:s,endpointUrl:c,token:l,logLevel:i,adbPath:m}),name:"test_event_duration",tags:["name:limbar-client-creation",`orgId:${a}`]}),h=["https://github.com/appium/appium-uiautomator2-server/releases/download/v7.6.2/appium-uiautomator2-server-v7.6.2.apk","https://github.com/appium/appium-uiautomator2-server/releases/download/v7.6.2/appium-uiautomator2-server-debug-androidTest.apk","https://github.com/appium/io.appium.settings/releases/download/v5.14.15/settings_apk-debug.apk"];d&&h.push(d);let f=n.apkToInstall?.channel,b=n.apkToInstall?.tag;o(`Installing APK${f?` with channel ${f}`:""}${b?` and tag ${b}`:""}`),await Promise.all(h.map(v=>g.sendAsset(v))),o("Starting tunnel");let E=await vt.recordDuration({fn:async()=>await g.startAdbTunnel(),name:"test_event_duration",tags:["name:limbar-tunnel-connect",`orgId:${a}`]});return{port:E.address.port,close:E.close,token:l,webRtcUrl:c,emulatorName:u}}async function Wl({onStatusUpdate:r,creationOpts:e,apiClient:t,logger:n,driverLogLevel:o,appiumPort:i,socket:a,orgId:l}){let c=Date.now(),{close:s,port:u,limbarToken:d,limbarUrl:p,emulatorName:m}=await yD({apiClient:t,logger:n,creationOpts:e,onStatusUpdate:r,orgId:l}),g=[()=>t.deleteAndroidEmulator(m),s],h=async()=>{for(let b=g.length-1;b>=0;b-=1)try{await g[b]()}catch(E){if(E instanceof Error&&E.message.includes("ECONNREFUSED"))return;n.warn({err:E},"Error running cleanup task")}},f=async()=>{if(a&&!a.connected)throw await h(),new Error("Client disconnected before Appium driver could be started")};await f();try{let b=await fD({logger:n,driverLogLevel:o,appiumPort:i,port:u,limbarStart:c,emulatorName:m,apiClient:t,onStatusUpdate:r,creationOpts:e,orgId:l});return g.push(b.appiumClose),g.push(async()=>b.driver.deleteSession()),await f(),{...b,emulatorName:m,limbarToken:d,limbarUrl:p,adbTunnelPort:u,cleanup:h,appiumPort:i}}catch(b){throw await h(),new Error(`Failed to start Appium driver: ${b}`)}}async function fD({logger:r,driverLogLevel:e="warn",port:t,limbarStart:n,emulatorName:o,appiumPort:i,orgId:a}){let l=Date.now(),{close:c,logFile:s}=await SD({logger:r,logLevel:e,appiumPort:i}),u={platformName:"Android","appium:automationName":"UiAutomator2","appium:deviceName":"Android","appium:udid":`127.0.0.1:${t}`,"appium:adbExecTimeout":3e4,"appium:newCommandTimeout":600,"appium:skipDeviceInitialization":!0,"appium:skipServerInstallation":!0,"appium:androidInstallTimeout":6e4,"appium:autoWebview":!1,"appium:autoWebviewTimeout":0,"appium:clearDeviceLogsOnStart":!0},d={hostname:"localhost",port:i,logLevel:e,capabilities:u,connectionRetryTimeout:3e4,connectionRetryCount:2},p=Date.now(),m=await hD(d);await m.updateSettings({enableMultiWindows:!0});let g=new Map;return m.on("command",h=>{g.set(h.command,Date.now())}),m.on("result",h=>{let f=g.get(h.command);if(!f)return;let b=Date.now()-f;h.result instanceof Error?r.warn({err:h.result,command:h.command,args:h.body,durationMs:b},"Appium cmd failed"):b>1e4&&r.warn({command:h.command,args:h.body,durationMs:b},"Appium cmd took very long"),g.delete(h.command)}),r.info({timings:{limbarDuration:l-n,appiumDuration:p-l,wdioDuration:Date.now()-p},capabilities:u,emulatorName:o},"Started Appium driver"),{driver:m,appiumClose:c,appiumPort:i,appiumLogFile:s}}async function SD({logger:r,logLevel:e,appiumPort:t}){let n=`${gD()}/appium-port-${Date.now()}.log`,o=await mD.main({port:t,address:"localhost",relaxedSecurityEnabled:!0,longStacktrace:e==="debug",logFormat:"json",loglevel:e,logFile:n});return{logFile:n,close:async()=>{await o.close()}}}async function yD({apiClient:r,logger:e,onStatusUpdate:t,creationOpts:n,orgId:o}){let{close:i,port:a,token:l,webRtcUrl:c,emulatorName:s}=await NT({apiClient:r,logger:e,creationOpts:n,onStatusUpdate:t,orgId:o});return{port:a,close:i,limbarToken:l,limbarUrl:c,emulatorName:s}}import DT from"crypto";import bD from"fs";async function $l({tag:r,channel:e,filePath:t,apiClient:n,logger:o}){let i=await bD.promises.readFile(t),a=DT.createHash("md5").update(i).digest("base64"),l=DT.createHash("md5").update(i).digest("hex"),c=await n.generateAndroidAssetUrls({channel:e,tag:r??"latest",md5:a});if(c.md5&&(c.md5===a||c.md5===l)){o.info({channel:e,tag:r,md5:a,md5Hex:l},`Asset ${t} already exists on emulator platform`);return}if(c.uploadUrl){o.info({channel:e,tag:r,md5:a,uploadUrl:c.uploadUrl},`Uploading asset ${t} to emulator platform...`);try{let s=await fetch(c.uploadUrl,{headers:{"Content-Length":i.length.toString(),"Content-Type":"application/octet-stream"},method:"PUT",body:i});if(s.status!==200)throw new Error(`Got error response from emulator platform: ${s.status} ${await s.text()}`);o.info({channel:e,tag:r,md5:a},`Asset ${t} was uploaded successfully!`);return}catch(s){try{await n.deleteAndroidAsset(e,r??"latest")}catch(u){o.warn({err:u,tag:r,channel:e},"Failed to cleanup asset metadata for failed upload. Please contact Momentic support.")}throw o.error({err:s},"Failed to upload asset"),s}}throw new Error(`No upload URL was given for asset ${t}`)}import{execSync as kT}from"child_process";import{existsSync as ED}from"fs";import{platform as UT}from"os";import{dirname as TD,join as vD,resolve as AD}from"path";import{fileURLToPath as wD}from"url";var FT,RD=wD(import.meta.url),CD=TD(RD);FT=AD(CD,"..");var Oa=FT;A.info(`Setting APPIUM_HOME to ${Oa}`);process.env.APPIUM_HOME=Oa;var xD="If you do not have Java installed, please download the JDK 24 from https://www.oracle.com/java/technologies/downloads/, move it to your home directory, and then set the JAVA_HOME environment variable in your shell profile to the JDK path.",MD="If you do not have Android Studio installed, please download it first from https://developer.android.com/studio and then follow all setup instructions in the Android Studio app.",_D="Follow the instructions at https://developer.android.com/tools/variables to set the ANDROID_HOME environment variable.",BT="On Mac OS, the SDK is typically installed at /Users/<username>/Library/Android/sdk.",zT="On Windows, the SDK is typically installed at C:\\Users\\<username>\\AppData\\Local\\Android\\Sdk.";function ID(){if(!process.env.JAVA_HOME)A.warn("JAVA_HOME is not set. Some Appium drivers and Android tools may not work as expected.");else{process.platform==="darwin"&&/\.jdk\/?$/.test(process.env.JAVA_HOME)&&A.warn("JAVA_HOME appears to point at a *.jdk bundle, which is incorrect. The correct path should be formatted like '<bundle>/Contents/Home'.");let e=((t,n)=>vD(t,"bin",process.platform==="win32"?`${n}.exe`:n))(process.env.JAVA_HOME,"java");ED(e)||A.warn(`JAVA_HOME does not appear to point to a valid Java installation: expected the 'java' binary to exist at ${e}`)}try{kT("java --version",{stdio:"pipe",encoding:"utf-8"})||(A.error(`Could not find a Java installation. ${xD}`),process.exit(1))}catch(r){A.error(`Got error while checking if the Java JDK is installed: ${r}`),process.exit(1)}}function PD(){process.env.ANDROID_HOME||(A.error(`The ANDROID_HOME environment variable is not set. ${_D} ${UT()==="darwin"?BT:zT}`),process.exit(1))}function OD(){let r=process.env.ANDROID_HOME?`${process.env.ANDROID_HOME}/platform-tools/adb`:"adb";try{kT(`${r} version`,{stdio:"pipe",encoding:"utf-8"})||(A.error(`Could not find the Android Debug Bridge (ADB) tool locally. This tool is included with Android Studio. ${MD} Finally, ensure that the 'adb' command is available in your shell. ${UT()==="darwin"?BT:zT}`),process.exit(1))}catch(e){A.error(`Got error while checking if ADB is installed: ${e}`),process.exit(1)}}function HT(){ID(),PD(),OD()}import{create as LD,windowedFiniteBatchScheduler as ND}from"@yornaath/batshit";import DD from"ws";var kD=100,UD=2500,GT=4e3,FD="\u2026";async function ql({driver:r,onLogs:e}){await r.execute("mobile: startLogsBroadcast");let t=LD({fetcher:async s=>{e(s)},resolver:()=>{},scheduler:ND({windowMs:UD,maxBatchSize:kD})}),{hostname:n="localhost",port:o=4723,protocol:i="http"}=r.options,l=`${i==="https"?"wss":"ws"}://${n}:${o}/ws/session/${r.sessionId}/appium/device/logcat`,c=new DD(l);return c.on("message",s=>{let u=s.toString().trim();u.length!==0&&(u.length>GT&&(u=u.slice(0,GT)+FD),t.fetch(u).catch(()=>{}))}),async()=>{try{c.close()}catch{}try{await r.execute("mobile: stopLogsBroadcast")}catch{}}}import{Server as VF}from"socket.io";import{randomUUID as YD}from"crypto";import{faker as BD}from"@faker-js/faker";import zD from"assert";import HD from"axios";import*as GD from"child_process";import VD from"moment";import*as jD from"otpauth";import WD from"pg";async function VT(r){let e;try{e=new URL(r.url).hostname}catch{}let t=[];return r.headers.getSetCookie()?.forEach(n=>{let o=_s(n,e);t.push(...o)}),t}function $D(r,e){if(!r&&!e)return;let t;if(r){let{url:o,options:i}=r;t=new Request(o,i)}let n;if(e){let{body:o,options:i}=e;n=new Response(o??null,i)}return{request:t,response:n}}async function qD(r,e){switch(r){case"RAW":return e;case"RESPONSE":if(e instanceof Response){let t=[];return e.headers.forEach((o,i)=>{t.push([i,o])}),{status:e.status,headers:t,body:await e.text()}}else throw new Error("Result is not a Response object")}}var KD=Object.getPrototypeOf(async function(){}).constructor;async function jT(r,e,t){let n=e.code;e.options.fragment&&(n=`return ${e.code}`);let{env:o,additionalBindings:i,request:a,response:l}=e.bindings,c=e.tools,s={},u=(v,R)=>{o[v]=R,s[v]=R},d={},p=(v,R)=>{o[v]=R,d[v]=R},m;n.includes("Octokit")&&(m=(await import("@octokit/rest")).Octokit);let g;n.includes("createAppAuth")&&(g=(await import("@octokit/auth-app")).createAppAuth);let h=async()=>await Promise.resolve(new KD("axios","moment","faker","assert","pg","Octokit","createAppAuth","OTPAuth","child_process","extractCookiesFromResponse","env","setVariable","setPersistentVariable","sendSms","waitForLatestSms","email","sms","ai","mock",...Object.keys(i??{}),n)(HD,VD,c.fakerInstance??BD,zD,WD,m,g,jD,GD,VT,o,e.options.disallowVariableUpdates?void 0:u,e.options.disallowVariableUpdates?void 0:p,R=>c.sms.send(R),R=>c.sms.fetchLatest(R),c.email,c.sms,c.ai,$D(a,l),...Object.values(i??{}))),f=!0,b,E;try{let v=await B(h(),{milliseconds:e.options.timeoutMs,message:`Timeout of ${e.options.timeoutMs}ms exceeded for code execution`,signal:e.signal});b=await qD(e.options.responseSerialization??"RAW",v)}catch(v){t.error({err:v,env:o,evalCode:n},`[${r}] Error executing code: ${v}`),f=!1,v instanceof dn?E=`Timeout of ${e.options.timeoutMs}ms exceeded for code execution`:E=v instanceof Error?v.message:`${v}`}return{result:b,variableUpdates:s,persistentVariableUpdates:d,success:f,error:E}}async function WT({code:r,fragment:e,context:t,localTools:n,logger:o,signal:i,timeoutMs:a=an,disallowVariableUpdates:l,additionalBindings:c,responseSerialization:s,mock:u}){let d=YD(),p=await jT(d,{code:r,options:{fragment:e,timeoutMs:a,disallowVariableUpdates:l,responseSerialization:s},bindings:{...t.toObjectCopy(),...u,additionalBindings:c},tools:n,signal:i},o);return A.debug(`[${d}] Got execution result: ${JSON.stringify(p)}`),p}import{createHmac as XD,randomUUID as JD}from"crypto";import ZD from"fetch-retry";var QD=ZD(global.fetch,{retries:3,retryOn:function(r,e,t){return!!(e!==null||t&&t.status>=500)},retryDelay:function(r){return Math.pow(2,r)*500}}),$T=process.env.GCP_JS_EVAL_FUNCTION_ENDPOINT,qT=process.env.MOMENTIC_LAMBDA_AUTH_SECRET;async function KT({orgId:r,code:e,fragment:t,context:n,timeoutMs:o=an,retries:i=2,signal:a,logger:l,additionalBindings:c,disallowVariableUpdates:s,responseSerialization:u,mock:d}){if(!$T)throw new Error("GCP_JS_EVAL_FUNCTION_ENDPOINT environment variable not set");let p,m,g=0;if(!qT)throw new Error("Missing lambda auth secret.");let h=XD("sha256",qT).update(r).digest("hex");for(;g<=i;){g++,a?.throwIfAborted();let b={id:JD(),orgId:r,momenticLambdaAuthHash:h,code:e,fragment:t,state:{...n.toObjectCopy(),...d,additionalBindings:c},timeoutMs:o,disallowVariableUpdates:s,responseSerialization:u};try{if(p=await B(QD($T,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(b)}),{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 l.error({err:m},"Failed to evaluate code remotely"),m;if(!p)throw new Error(`An unexpected code evaluation error occurred${m?`: ${m}`:""}`);let f;try{f=nS.parse(await p.json())}catch(b){throw new Error(`Code evaluation server returned invalid response: ${b}`)}if(f.error)throw new Error(`Code evaluation error: ${f.error}`);return f}async function Ir(r){let e;if(process.env.GCP_JS_EVAL_FUNCTION_ENDPOINT)e=await KT(r);else if(r.localTools)e=await WT({...r,localTools:r.localTools});else throw new Error("No code evaluation environment available");if(e.error){let t=`Failed to evaluate code:
|
|
26
32
|
${e.error}
|
|
27
33
|
Code received:
|
|
28
|
-
${r.code}`;throw r.logger.error({err:e.error,code:r.code,env:r.context.toObjectCopy()},t),new Error(t)}if(e.variableUpdates)for(let[t,n]of Object.entries(e.variableUpdates))r.context.setVariable(t,n);if(e.persistentVariableUpdates&&Object.keys(e.persistentVariableUpdates).length>0){await r.callbacks?.onPersistentVariableUpdates?.(e.persistentVariableUpdates);for(let[t,n]of Object.entries(e.persistentVariableUpdates))r.context.setVariable(t,n)}return e.result}import{set as
|
|
29
|
-
${JSON.stringify(t)}`);let n=[];return n.push({key:Wk(r.id,e.join(":")),organizationId:r.orgId,value:r.value,testId:r.testId}),n}function lc({cmd:r,newTarget:e,key:t,logger:n,updatedWithAI:o}){if(r.type==="DRAG")if(t!=="fromTarget"&&t!=="toTarget")n.error({cmd:r,newTarget:e,key:t},"Attempted to apply invalid cache to DRAG command");else{let i=r.cache?.updatedAt;r.cache={...r.cache,[t]:e,updatedAt:i&&!o?i:new Date}}else if(t==="target"&&Iy(r)){let i=r.cache?.updatedAt;r.cache={...r.cache,target:e,updatedAt:i&&!o?i:new Date}}else n.error({cmd:r,newTarget:e,key:t},"Invalid target cache application")}function cc(r,e,t){let n=r.cache&&"memory"in r.cache?r.cache.memory?.traces:void 0;return gv(n,e)?(t.info({updatedTraces:e,oldCmd:r},"Wrote new memory to assertion command"),r.cache={...r.cache,memory:{type:"GCS_TRACES",traces:e},updatedAt:new Date},{changed:!0}):{changed:!1}}function Yp(r){return{...r,serializedHtml:void 0,nodeOnlySerializedHtml:void 0,screenshotUrl:void 0,boundingBox:void 0,selector:void 0,hybridSelector:void 0,generatedSelectors:void 0,id:-1}}function hv(r,e){return r?gv(r.target.memory,e.target.memory)?{target:{...r.target,memory:e.target.memory},updatedAt:e.updatedAt}:r:{target:Yp(e.target),updatedAt:e.updatedAt}}function It(r,e,t=!1){return r.length<e?r:r.slice(0,e-3)+(t?"...TRUNCATED...":"[...]")}var ao={EQUALS:"equals",CONTAINS:"contains",STARTS_WITH:"starts with",EXISTS:"exists"},so={EQUALS:"does not equal",CONTAINS:"does not contain",STARTS_WITH:"does not start with",EXISTS:"does not exist"},fv={EXISTS:"exists",VISIBLE:"is visible",ENABLED:"is enabled",EDITABLE:"is editable",FOCUSED:"is focused"},Sv={EXISTS:"does not exist",VISIBLE:"is not visible",ENABLED:"is disabled",EDITABLE:"is not editable",FOCUSED:"is not focused"};var Jle={CONTENT:"The page"};function yv(r){switch(r.type){case"SUBSTRING":return`match substring '${r.url}'`;case"REGEX":return`match regex '${r.regex}'`;case"GLOB":return`match glob '${r.glob}'`;case"DOMAIN":return`match domain '${r.domain}'`;default:return(t=>{throw"If Typescript complains about the line below, you missed a case or break in the switch above"})(r)}}function qk(r){return typeof r=="object"&&r!==null}function io(r){if(Array.isArray(r))return r.map(io);if(qk(r)){let e={};return Object.entries(r).forEach(([t,n])=>{n!==void 0&&(e[t]=io(n))}),e}return r}function Kk(r){switch(r.type){case"AI_CHECK":return`AI check: ${r.assertion}`;case"TAP":return`Tap on element: ${Cp(r.target)}`;case"TYPE":return`Type ${r.text} ${r.target?`into ${Cp(r.target)}`:""}`;case"PRESS":return`Press the ${r.key} button`;case"PRESS_KEYBOARD":return`Press the ${r.key} key`;case"SWIPE":return r.scrollableElement.type==="CUSTOM"?`Swipe ${r.direction} in container: ${r.scrollableElement.target.description}`:`Swipe ${r.direction} in the ${r.scrollableElement.type.toLowerCase()}`;case"OPEN_APP":return`Open app: ${r.packageName}`;case"OPEN_NOTIFICATION_DRAWER":return"Open notification drawer";case"JAVASCRIPT":return`Execute JavaScript: ${r.code}`;case"REQUEST":return`Make API request to ${r.url}`;case"WAIT":return`Wait ${r.timeoutSecs} seconds`;case"ADD_FILE":return`Add file: ${r.file} to ${r.storageLocation}`;case"ADB":return`ADB command: ${r.command}`;case"STATE":return"Get state";default:{let e=r;throw new Error("If Typescript complains about the line above, you missed a case or break in the switch above")}}}function bv(r){switch(r.type){case"MOBILE_PRESET_STEP":return Kk(r.command);case"MOBILE_MODULE_STEP":return`Module ${r.moduleId}`;case"RESOLVED_MOBILE_MODULE":return`Module ${r.name}`;default:{let e=r;throw new Error("If Typescript complains about the line above, you missed a case or break in the switch above")}}}import{cloneDeep as Ev}from"lodash-es";async function Tv(r){let e={},{resolvedSteps:t,newSchemaVersion:n}=await uc({rawSteps:r.rawStepLists.steps,onFetchModule:r.onFetchModule,logger:r.logger,metadata:r.testMetadata,resolvedModuleCache:e}),o={steps:t};for(let i of["beforeSteps","afterSteps"]){let a=r.rawStepLists[i];if(!a)continue;let{resolvedSteps:s}=await uc({rawSteps:a,onFetchModule:r.onFetchModule,logger:r.logger,metadata:r.testMetadata,resolvedModuleCache:e});o[i]=s}return{resolvedStepLists:o,moduleIds:Array.from(Object.keys(e))}}async function uc({rawSteps:r,onFetchModule:e,logger:t,metadata:n,resolvedModuleCache:o={}}){let i=[];for(let a of r)i.push(await vv({rawStep:yr.parse(a),onFetchModule:e,logger:t,resolvedModuleCache:o}));return{resolvedSteps:i,newSchemaVersion:n.schemaVersion}}async function vv({rawStep:r,onFetchModule:e,logger:t,resolvedModuleCache:n}){switch(r.type){case"MOBILE_MODULE_STEP":{let o=r.moduleId,i=n[o];if(i)return{...Ev(i),...r,type:"RESOLVED_MOBILE_MODULE"};let a=await e(o);if(!a)throw new Error(`Could not find module with id ${o}`);let s;try{s=yr.array().parse(a.steps)}catch(u){throw t.error({err:u,steps:a.steps,moduleId:o},"Module failed to parse (mobile)"),u}let c=await Promise.all(s.map(u=>vv({rawStep:u,onFetchModule:e,logger:t,resolvedModuleCache:n}))),l={...a,steps:c};return n[o]=Ev(l),{...l,...r,type:"RESOLVED_MOBILE_MODULE"}}case"MOBILE_PRESET_STEP":return r}}import{cloneDeep as Yk}from"lodash-es";import{v4 as Xp}from"uuid";async function lo(r){let e=new Map,t=new Set,n=Yk(r.steps),o=await Av({...r,steps:n,moduleStepParents:[],moduleIdParents:[],moduleIdReplacements:e,seenModules:t});return{stepsToSave:o.stepsToSave,cachesToSave:o.cachesToSave,moduleUpdates:o.moduleUpdates}}async function Av({steps:r,...e}){let{seenModules:t,cacheCreationParams:n,moduleIdParents:o,moduleStepParents:i,moduleIdReplacements:a,shouldCreateNewModuleId:s,createNewCacheIds:c}=e,l={cachesToSave:[],stepsToSave:[],moduleUpdates:[]};for(let u of r)switch(u.id=c?Xp():u.id,u.type){case"MOBILE_PRESET_STEP":{let d=u.command;d.id=c?Xp():d.id,"cache"in d&&d.cache&&(n&&(l.cachesToSave=l.cachesToSave.concat(Kp({id:d.id,orgId:n.orgId,testId:n.testId,value:bn.parse(d),moduleIdParents:o,moduleStepParents:i}))),delete d.cache),l.stepsToSave.push({...u,command:d});break}case"RESOLVED_MOBILE_MODULE":{let d=c?Xp():u.id,p=u.moduleId;a.has(p)?p=a.get(p):s!==void 0&&(p=await s(u),a.set(u.moduleId,p));let{cachesToSave:g,stepsToSave:m,moduleUpdates:h}=await Av({...e,steps:u.steps,cacheCreationParams:n?{...n}:void 0,createNewCacheIds:!1,moduleStepParents:[...i,d],moduleIdParents:[...o,p],skipCacheIntermediateEntries:c});l.moduleUpdates=l.moduleUpdates.concat(h),l.cachesToSave=l.cachesToSave.concat(g),t.has(p)||(t.add(p),l.moduleUpdates.push({...si.parse(u),steps:yr.array().parse(m),moduleId:p}));let f=ka.parse({...u,type:"MOBILE_MODULE_STEP",moduleId:p,inputs:u.inputs,id:d});l.stepsToSave.push(f);break}default:{let d=u}}return l}function Xk(r){let e={parentChain:[]};return wv(r,e),e}function wv(r,e){let{onPreset:t,onModule:n,earlyStop:o}=r;for(let i of r.steps){if(i.type==="RESOLVED_MOBILE_MODULE"){if(n?.(i,e)&&o||(e.parentChain.push(i),wv({...r,steps:i.steps},e)&&o))return!0;e.parentChain.pop();continue}if(t(i,e)&&o)return!0}return!1}function Jk(r,e,t=[]){let n,o=[],i=(a,s)=>{let c=JSON.stringify(s.parentChain.map(u=>u.id)),l=t.length===0?!0:JSON.stringify(t)===c;return a.id===e&&l?(n=a,o=s.parentChain,!0):!1};return Xk({steps:r,earlyStop:!0,onPreset:i,onModule:i}),{result:n,parentChain:o}}function Rv({currentStep:r,currentParentChain:e,desiredStepId:t,desiredStepParentChain:n}){let o=Array.from(e),i=Array.from(n);for(let s=0;s<o.length;s++){if(o[s]!==i[s])return!1;i.shift()}return!!Jk([r],t,i).result}function Cv(r){let e=r[0],t=r[0],n=!1;for(;!n&&t;)switch(t.type){case"MOBILE_MODULE_STEP":if(!t.steps.length){e=t,n=!0;break}t=t.steps[0];break;case"MOBILE_PRESET_STEP":e=t,n=!0;break;default:{let s=t}}let o=r[r.length-1],i=r[r.length-1],a=!1;for(;!a&&i;)switch(i.type){case"MOBILE_MODULE_STEP":if(!i.steps.length){o=i,a=!0;break}i=i.steps[i.steps.length-1];break;case"MOBILE_PRESET_STEP":o=i,a=!0;break;default:{let s=i}}return{firstMetadata:e,lastMetadata:o}}function xv({result:r,firstMetadata:e,lastMetadata:t}){e&&(r.beforeSnapshot=e.beforeSnapshot),t&&(r.data=t.data,r.afterSnapshot=t.afterSnapshot,t.status!=="SUCCESS"&&(r.message=t.message))}import{cloneDeep as qce}from"lodash-es";import Yce from"truncate-json";import{v4 as oue}from"uuid";import{cloneDeep as Uce,unset as Fce}from"lodash-es";import{cloneDeep as cue}from"lodash-es";import{cloneDeep as Ode}from"lodash-es";import Que from"diff-lines";import Jp,{gte as tde}from"semver";var _v={name:"Migrate to ai step v2",fromVersion:"1.0.4",toVersion:"1.0.5",recursiveKeys:new Set(["results","commands"]),stopOnFailure:!0,execute:async r=>(r=r.filter(e=>!(e.status!==void 0&&e.type==="AI_ACTION")),r=r.map(e=>(e.status===void 0||e.type==="PRESET_ACTION"&&(e.results=e.commands??e.results??[]),e)),r)};var Mv={name:"Make sure ai step v2 has done command",fromVersion:"1.0.5",toVersion:"1.0.6",recursiveKeys:new Set(["results","commands"]),stopOnFailure:!0,execute:async r=>r.map(e=>{if(e.type!=="AI_ACTION"||e.status!==void 0||!e.commands||!e.commands.length)return e;let t=e.commands,n=t[t.length-1];return n&&n.type!=="SUCCESS"&&t.push({type:"SUCCESS"}),e})};var Zk=["target","fromTarget","toTarget"];function Iv(r){for(let e of Zk){if(r[e]===void 0)continue;let t=r[e];t.elementDescriptor!==void 0?t.type="description":r[e]={type:"description",elementDescriptor:""}}}var Pv={name:"Migrate element target to discriminated union",fromVersion:"1.0.6",toVersion:"1.0.7",recursiveKeys:new Set(["results","steps"]),stopOnFailure:!0,execute:async r=>r.map(e=>{switch(e.type){case"PRESET_ACTION":return Iv(e.command),e;case"AI_ACTION":{let t=e.commands;for(let n of t??[])Iv(n);return e}default:return e}})};import{v4 as Qk}from"uuid";var Ov={name:"Ensure module steps have ids",fromVersion:"1.0.7",toVersion:"1.0.8",recursiveKeys:new Set(["results","steps"]),stopOnFailure:!0,execute:async r=>r.map(e=>{switch(e.type){case"MODULE":return e.id||(e.id=Qk()),e;default:return e}})};import{v4 as Lv}from"uuid";var Nv={name:"Ensure module steps have ids",fromVersion:"1.0.8",toVersion:"1.0.9",recursiveKeys:new Set(["results","steps"]),stopOnFailure:!0,execute:async r=>r.map(e=>{switch(e.type){case"PRESET_ACTION":{if(!e.command)return e;let t=e.command;return t.id=t.id??Lv(),e}case"AI_ACTION":return e.commands&&(e.steps=e.commands.map(t=>({type:"PRESET_ACTION",command:{...t,id:t.id??Lv()}})),delete e.commands),e;default:return e}})};var kv={name:"Migrate ai waits to checks",fromVersion:"1.0.9",toVersion:"1.0.10",recursiveKeys:new Set(["results","steps","blocks","elseSteps"]),stopOnFailure:!0,execute:async r=>r.map(e=>{switch(e.type){case"PRESET_ACTION":{if(!e.command)return e;let t=e.command;return typeof t.type!="string"||t.type!=="AI_WAIT"||(t.type="AI_ASSERTION",t.timeout||(t.timeout=10)),e}default:return e}})};import{v4 as eD}from"uuid";var Dv={name:"Add ids to all steps",fromVersion:"1.0.10",toVersion:"1.0.11",recursiveKeys:new Set(["results","steps","blocks","elseSteps"]),stopOnFailure:!0,execute:async r=>r.map(e=>("id"in e&&typeof e.id=="string"||(e.id=eD()),e))};import{v4 as Uv}from"uuid";var Fv={name:"Add ids to all steps",fromVersion:"1.0.11",toVersion:"1.0.12",recursiveKeys:new Set(["results","steps","blocks","elseSteps"]),stopOnFailure:!0,execute:async r=>r.map(e=>{if("id"in e&&typeof e.id=="string")return e;if("condition"in e&&typeof e.condition=="object"&&e.condition){let t=e.condition;t.id||(t.id=Uv())}return e.id=Uv(),e})};var Bv={name:"Move env key to steps",fromVersion:"1.0.12",toVersion:"1.0.13",recursiveKeys:new Set(["results","steps","blocks","elseSteps"]),stopOnFailure:!0,execute:async r=>r.map(e=>{if(e.type!=="PRESET_ACTION")return e;let t=e.command;return!t||typeof t.envKey!="string"||(e.envKey=t.envKey,delete t.envKey),e})};import{v4 as tD}from"uuid";var zv={name:"Redo last two migrations",fromVersion:"1.0.13",toVersion:"1.0.14",recursiveKeys:new Set(["results","steps","blocks","elseSteps"]),stopOnFailure:!0,execute:async r=>r.map(e=>{if((!("id"in e)||typeof e.id!="string")&&(e.id=tD()),e.type!=="PRESET_ACTION")return e;let t=e.command;return!t||typeof t.envKey!="string"||(e.envKey=t.envKey,delete t.envKey),e})};var Hv={name:"Migrate select choice",fromVersion:"1.0.14",toVersion:"1.0.15",recursiveKeys:new Set(["results","steps","blocks","elseSteps"]),stopOnFailure:!0,execute:async r=>r.map(e=>{if(e.type!=="PRESET_ACTION")return e;let t=e.command;return!t||t.type!=="SELECT_OPTION"||e.option===void 0||(e.choice={type:"VALUE",value:t.option},e.option=void 0),e})};var Gv={name:"Migrate select choice",fromVersion:"1.0.15",toVersion:"1.0.16",recursiveKeys:new Set(["results","steps","blocks","elseSteps"]),stopOnFailure:!0,execute:async r=>r.map(e=>{if(e.type!=="PRESET_ACTION")return e;let t=e.command;return t&&jv(t),e})};function jv(r){r&&Object.keys(r).forEach(e=>{if(typeof r[e]=="object"&&r[e]){jv(r[e]);return}if(typeof r[e]!="string")return;let t=r[e];e==="code"?r[e]=t.replace(/inputs\./g,"env."):t.includes("{{")&&t.includes("}}")&&(r[e]=t.replace(/inputs\./g,"env."))})}var Vv={name:"Migrate switch tab choice",fromVersion:"1.0.16",toVersion:"1.0.17",recursiveKeys:new Set(["results","steps","blocks","elseSteps"]),stopOnFailure:!0,execute:async r=>r.map(e=>{if(e.type!=="PRESET_ACTION")return e;let t=e.command;return!t||t.type!=="TAB"||t.url===void 0||(t.action={type:"SUBSTRING",substring:t.url},t.url=void 0),e})};var Wv={name:"Remove press keys sequentially",fromVersion:"1.0.17",toVersion:"1.0.18",recursiveKeys:new Set(["results","steps","blocks","elseSteps"]),stopOnFailure:!1,execute:async r=>r.map(e=>{if(e.type!=="PRESET_ACTION")return e;let t=e.command;return!t||t.type!=="TYPE"?e:t.pressKeysSequentially===void 0?(t.delay=0,e):(t.pressKeysSequentially&&(t.pressKeysSequentially=void 0,t.delay=50),e)})};var $v={name:"Migrate wait for URL to matcher",fromVersion:"1.0.18",toVersion:"1.0.19",recursiveKeys:new Set(["results","steps","blocks","elseSteps"]),stopOnFailure:!1,execute:async r=>r.map(e=>{if(e.type!=="PRESET_ACTION")return e;let t=e.command;return!t||t.type!=="WAIT_FOR_URL"||t.url===void 0||(t.matcher={type:"GLOB",glob:t.url},t.url=void 0),e})};var qv={name:"Migrate select choice round 2",fromVersion:"1.0.19",toVersion:"1.0.20",recursiveKeys:new Set(["results","steps","blocks","elseSteps"]),stopOnFailure:!0,execute:async r=>r.map(e=>{if(e.type!=="PRESET_ACTION")return e;let t=e.command;if(!t)return e;if(t.type==="SELECT_OPTION"){if(t.option===void 0)return e;t.choice={type:"VALUE",value:t.option},t.option=void 0}else if(t.type==="TAB"){if(t.url===void 0)return e;t.action={type:"SUBSTRING",substring:t.url},t.url=void 0}else if(t.type==="WAIT_FOR_URL"){if(t.url===void 0)return e;t.matcher={type:"GLOB",glob:t.url},t.url=void 0}else t.type==="AI_WAIT"&&(t.type="AI_ASSERTION",t.timeout||(t.timeout=10));return e})};var Kv={name:"Migrate ",fromVersion:"1.0.20",toVersion:"1.0.21",recursiveKeys:new Set(["results","steps","blocks","elseSteps"]),stopOnFailure:!1,execute:async r=>r.map(e=>{if(e.type!=="PRESET_ACTION")return e;let t=e.command;return!t||t.type!=="MOCK_ROUTE"&&t.type!=="SET_HEADER"&&t.type!=="RECORD_REQUESTS"&&t.type!=="REGISTER_REQUEST_LISTENER"||(t.type==="REGISTER_REQUEST_LISTENER"||t.type==="RECORD_REQUESTS"?t.requestMatcher={urlMatcher:{type:"REGEX",regex:t.pattern}}:(t.type==="SET_HEADER"||t.type==="MOCK_ROUTE")&&t.urlPattern&&(t.requestMatcher={urlMatcher:{type:"REGEX",regex:t.urlPattern}})),e})};var Yv={name:"Migrate AI checks to preset actions",fromVersion:"1.0.0",toVersion:"1.0.1",recursiveKeys:new Set,execute:async r=>r.map(e=>{if(e.type!=="AI_ASSERTION")return e;let n={type:"PRESET_ACTION",command:{type:"AI_ASSERTION",assertion:e.text,useVision:!1,disableCache:!0}},o={...e,...n};return delete o.text,o}),stopOnFailure:!0};var dc=new Set(["CLICK","TYPE","SELECT_OPTION"]),Xv={name:"Migrate element descriptor to live in a target object",fromVersion:"1.0.3",toVersion:"1.0.4",recursiveKeys:new Set,execute:async r=>r.map(e=>{let t=e.command,n=t?.type,o=t?.elementDescriptor;return(o!==void 0||dc.has(n))&&(t.target={elementDescriptor:o??""}),e.commands&&Array.isArray(e.commands)&&e.commands.forEach(a=>{let s=a?.elementDescriptor,c=a?.type;(s!==void 0||dc.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||dc.has(l))&&(s.target={elementDescriptor:c??""}),a.commands&&Array.isArray(a.commands)&&a.commands.forEach(d=>{let p=d?.elementDescriptor,g=d?.type;(p!==void 0||dc.has(g))&&(d.target={elementDescriptor:p??""})})}),e}),stopOnFailure:!0};var Jv={name:"Migrate FAILURE status to FAILED",fromVersion:"1.0.1",toVersion:"1.0.2",recursiveKeys:new Set,execute:async r=>r.map(e=>{let t=e;return t.status==="FAILURE"&&(t.status="FAILED"),typeof t.commands=="object"&&Array.isArray(t.commands)&&t.commands.forEach(n=>{if(n&&typeof n=="object"){let o=n;o?.status==="FAILURE"&&(o.status="FAILED")}}),t}),stopOnFailure:!0};var Zv={name:"Migrate preset step types to use the same",fromVersion:"1.0.2",toVersion:"1.0.3",recursiveKeys:new Set,execute:async r=>r.map(e=>{let t=e.command,n=t?.type;return n?.startsWith("PRESET_")&&(t.type=n.slice(7)),e.commands&&Array.isArray(e.commands)&&e.commands.forEach(i=>{let a=i.type;a?.startsWith("PRESET_")&&(i.type=a.slice(7))}),e.results&&Array.isArray(e.results)&&e.results.forEach(i=>{let a=i.command,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 pc=[Yv,Jv,Zv,Xv,_v,Mv,Pv,Ov,Nv,kv,Dv,Fv,Bv,zv,Hv,Gv,Vv,Wv,$v,qv,Kv];if(Jn!==pc[pc.length-1].toVersion)throw new Error("Please bump LATEST_SCHEMA_VERSION in types package after adding a migration");pc.forEach((r,e)=>{if(!Jp.valid(r.toVersion)||!Jp.valid(r.fromVersion))throw new Error(`Migration '${r.name}' has invalid version`);if(!Jp.gt(r.toVersion,r.fromVersion))throw new Error(`Migration '${r.name}' has toVersion <= fromVersion`);if(e===0)return;if(pc[e-1].toVersion!==r.fromVersion)throw new Error(`Migration '${r.name}' at index ${e} is not contiguous with previous migration`)});import{diff as Xde}from"deep-object-diff";import{cloneDeep as Zde}from"lodash-es";import{v4 as mpe}from"uuid";import{cloneDeep as Spe}from"lodash-es";import{stringify as Mpe}from"yaml";async function ee(r,e){if(!(r<=0))return new Promise((t,n)=>{if(e?.aborted){n(e.reason);return}e?.addEventListener("abort",i,{once:!0});let o=setTimeout(()=>{e?.removeEventListener("abort",i),t()},r);function i(){clearTimeout(o),e?.removeEventListener("abort",i),n(e?.reason)}})}async function Zp({promiseGenerator:r,signal:e,codePath:t,logger:n}){let i=Date.now(),a=setInterval(()=>{if(e?.aborted){clearInterval(a);return}n?.warn({codePath:t,startTime:i,elapsedMilliseconds:Date.now()-i},`Asynchronous operation is taking a long time (${t})`)},5e3);return new Promise((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 r())}catch(u){c(u)}finally{clearInterval(a),e?.removeEventListener("abort",l)}})()})}async function Ga({promiseGenerator:r,timeoutMs:e,codePath:t,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 Zp({promiseGenerator:r,signal:a.signal,codePath:t,logger:n})}finally{i=!0,o?.removeEventListener("abort",s),clearTimeout(c)}}function mc(r){let e;return r>10*60*1e3?e=2*60*1e3:r>60*1e3?e=20*1e3:r>10*1e3?e=2*1e3:e=1e3,e}import rD from"picomatch";var gc=(r,e,t)=>{t?.caseInsensitive&&(r=r.toLowerCase());let n;switch(e.type){case"SUBSTRING":{let o=t?.caseInsensitive?e.url.toLowerCase():e.url;n=r.includes(o);break}case"GLOB":{let o=t?.caseInsensitive?e.glob.toLowerCase():e.glob;n=r===e.glob||rD(o)(r);break}case"REGEX":{n=new RegExp(e.regex).test(r);break}case"DOMAIN":{let o=t?.caseInsensitive?e.domain.toLowerCase():e.domain;n=new URL(r).hostname===o;break}}return t?.negated?!n:n},hc=(r,e)=>{try{let{hostname:t,pathname:n}=new URL(r),{hostname:o,pathname:i}=new URL(e);return t!==o||n!==i}catch{return!1}},ui=r=>{try{return new URL(r),!0}catch{return!1}},eA=r=>!r.toLowerCase().startsWith("http"),di=(r,e)=>{try{return new URL(r,e),!0}catch{return!1}};function co(r,e){try{return!!new URL(r).origin.trim()}catch(t){return e?.error({url:r,err:t},"Invalid URL in check"),!1}}import{v4 as tA}from"uuid";function Qp(r,e){return{...r,testId:e?.testId??"",testName:e?.testName??"",suiteId:e?.suiteId??"",suiteName:e?.suiteName??""}}var fc=class{reporter;asyncWork;metadata;creditsUsedV1=0;creditsUsedV2=0;constructor({logger:e,reporter:t,runType:n,runId:o,testMetadata:i,suiteMetadata:a}){this.reporter=t,this.metadata={testId:i.id,testName:i.name,suiteId:a?.id,suiteName:a?.name},this.asyncWork=[t.reportBillableEvents(e,[{event:n,timestamp:new Date().toISOString(),transactionId:o,properties:Qp({},this.metadata)}]).catch(s=>e.error({err:s},"Failed to report billable event"))]}trackStepExecution(e){if(ME(e.type)){this.creditsUsedV2+=1;return}let t=bp(e.type);if(this.creditsUsedV1+=t??0,e.type==="PRESET_ACTION"){this.creditsUsedV2+=1;let n=Ep(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:tA(),properties:Qp({creditsUsed:this.creditsUsedV1},this.metadata)}]).catch(t=>e.error({err:t},"Failed to report credits used"))),this.creditsUsedV2>0&&this.asyncWork.push(this.reporter.reportBillableEvents(e,[{event:"credits-used-v2",timestamp:new Date().toISOString(),transactionId:tA(),properties:Qp({creditsUsed:this.creditsUsedV2},this.metadata)}]).catch(t=>e.error({err:t},"Failed to report credits used"))),await Promise.allSettled(this.asyncWork)}};import{CookieJar as oB}from"tough-cookie";var em={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
|
|
34
|
+
${r.code}`;throw r.logger.error({err:e.error,code:r.code,env:r.context.toObjectCopy()},t),new Error(t)}if(e.variableUpdates)for(let[t,n]of Object.entries(e.variableUpdates))r.context.setVariable(t,n);if(e.persistentVariableUpdates&&Object.keys(e.persistentVariableUpdates).length>0){await r.callbacks?.onPersistentVariableUpdates?.(e.persistentVariableUpdates);for(let[t,n]of Object.entries(e.persistentVariableUpdates))r.context.setVariable(t,n)}return e.result}import{set as e0}from"lodash-es";async function Op(r){let{orgId:e,s:t,context:n,logger:o,signal:i,retries:a=2,timeoutMs:l=an,allowUndefined:c=!1}=r,s=/{{(.*?)}}/g,u=t.matchAll(s),d=t;for(let p of u){if(p.length<2)continue;let m=p[1].trim(),g;try{g=await Ir({orgId:e,code:m,fragment:!0,context:n,timeoutMs:l,logger:o,retries:a,localTools:r.localTools,signal:i})}catch(f){throw o.error({err:f,value:t},"Error evaluating template string"),f}if(g===void 0&&!c)throw new w("UserConfigurationError",`Template fragment '${m}' evaluated to undefined. Please ensure that the variable name is spelled correctly and it is only referenced after being assigned a value.`);let h=typeof g=="string"?g:`${g}`;h=h.replaceAll(/\$/g,"$$$$"),d=d.replace(p[0],h)}return d}async function Kl(r){return YT(r)}async function YT({obj:r,bannedKeys:e,allowList:t,context:n,prefixPath:o=[],replacements:i=[],...a}){for(let l in r){if(e.includes(l))continue;let c=!1;if(t)if(t.includes(l))c=!0;else continue;let s=r[l],u=[...o,l];if(typeof s=="string"&&s.includes("{{")){let d=await Op({s,context:n,...a});if(s===d)continue;i.push({path:u,original:s}),r[l]=d}else typeof s=="object"&&s!==null&&!Array.isArray(s)&&await YT({obj:s,bannedKeys:e,context:n,prefixPath:u,replacements:i,allowList:c?void 0:t,...a})}return i}function Yl(r,e){for(let{path:t,original:n}of e)e0(r,t,n)}import t0 from"fetch-retry";var Qae=process.env.MAILINATOR_API_KEY,ese=t0(global.fetch,{retryOn:function(r,e,t){return r>3?!1:!!(e!==null||t&&t.status>=400)},retryDelay:function(r){return 500}});import fF from"fetch-cookie";import SF from"path";import{diff as n0}from"deep-object-diff";import{cloneDeep as Rse}from"lodash-es";function XT(r,e){return!r&&!e?!1:!r||!e?!0:Object.keys(n0(r,e)).length>0}function Lp({steps:r,topLevel:e=!0,...t}){let{stepCacheEntries:n,logger:o,keyPrefix:i}=t,a=[],l=[],c=[],s=0,u=(p,m)=>{try{let g=nn.parse(m.value);if(g.type!==p.type){o.warn({parsedCacheEntry:g,command:p},"Not using step cache due to type mismatch"),l.push(m.key);return}p.cache=g.cache,a.push(m.key),c.push(m.uniqueKey)}catch(g){l.push(m.key),o.error({err:g,cacheEntry:m},"Not using step cache due to parsing error")}},d=(p,m)=>{let g=i0(p.id,m),h=g.find(f=>!!n[f]);if(h)u(p,n[h]);else{if(p.type==="AI_CHECK")return;l.push(g[0])}};for(let p of r)switch(p.type){case"MOBILE_PRESET_STEP":{if(!Ls(p.command)||p.command.type==="TYPE"&&!p.command.target||"cache"in p.command&&p.command.cache)continue;s++,d(p.command,i);break}case"RESOLVED_MOBILE_MODULE":{s+=p.steps.length;let{cacheKeysHit:m,cacheKeysMissed:g,uniqueKeysHit:h}=Lp({...t,steps:p.steps,keyPrefix:i?`${i}:${p.id}`:p.id,topLevel:!1});a.push(...m),l.push(...g),c.push(...h);break}case"MOBILE_AI_ACTION_STEP":{s++;break}default:{let m=p}}return e&&s&&l.length>0&&o.warn({totalSteps:s,cacheKeysMissed:l,cacheKeysHit:a,uniqueKeysHit:c,cacheEntries:n.length},"Step cache did not fully resolve"),{cacheKeysHit:a,cacheKeysMissed:l,uniqueKeysHit:c}}function o0(r,e){return e?`${e}:${r}`:r}function i0(r,e){let t=[],n=e?.split(":")??[];for(let o=n.length;o>=0;o--){let i=[...n.slice(o),r];t.push(i.join(":"))}return t.reverse(),t}function Np(r){let{moduleStepParents:e=[],moduleIdParents:t=[]}=r;if(e.length!==t.length)throw new Error(`Invalid cache entry parent length: ${JSON.stringify(e)}
|
|
35
|
+
${JSON.stringify(t)}`);let n=[];return n.push({key:o0(r.id,e.join(":")),organizationId:r.orgId,value:r.value,testId:r.testId}),n}function Xl({cmd:r,newTarget:e,key:t,logger:n,updatedWithAI:o}){if(r.type==="DRAG")if(t!=="fromTarget"&&t!=="toTarget")n.error({cmd:r,newTarget:e,key:t},"Attempted to apply invalid cache to DRAG command");else{let i=r.cache?.updatedAt;r.cache={...r.cache,[t]:e,updatedAt:i&&!o?i:new Date}}else if(t==="target"&&eh(r)){let i=r.cache?.updatedAt;r.cache={...r.cache,target:e,updatedAt:i&&!o?i:new Date}}else n.error({cmd:r,newTarget:e,key:t},"Invalid target cache application")}function Jl(r,e,t){let n=r.cache&&"memory"in r.cache?r.cache.memory?.traces:void 0;return XT(n,e)?(t.info({updatedTraces:e,oldCmd:r},"Wrote new memory to assertion command"),r.cache={...r.cache,memory:{type:"GCS_TRACES",traces:e},updatedAt:new Date},{changed:!0}):{changed:!1}}function Dp(r){return{...r,serializedHtml:void 0,nodeOnlySerializedHtml:void 0,screenshotUrl:void 0,boundingBox:void 0,selector:void 0,hybridSelector:void 0,generatedSelectors:void 0,id:-1}}function JT(r,e){return r?XT(r.target.memory,e.target.memory)?{target:{...r.target,memory:e.target.memory},updatedAt:e.updatedAt}:r:{target:Dp(e.target),updatedAt:e.updatedAt}}function _t(r,e,t=!1){return r.length<e?r:r.slice(0,e-3)+(t?"...TRUNCATED...":"[...]")}var Xn={EQUALS:"equals",CONTAINS:"contains",STARTS_WITH:"starts with",EXISTS:"exists"},Jn={EQUALS:"does not equal",CONTAINS:"does not contain",STARTS_WITH:"does not start with",EXISTS:"does not exist"},ZT={EXISTS:"exists",VISIBLE:"is visible",ENABLED:"is enabled",EDITABLE:"is editable",FOCUSED:"is focused"},QT={EXISTS:"does not exist",VISIBLE:"is not visible",ENABLED:"is disabled",EDITABLE:"is not editable",FOCUSED:"is not focused"};var ele={CONTENT:"The page"};function ev(r){switch(r.type){case"SUBSTRING":return`match substring '${r.url}'`;case"REGEX":return`match regex '${r.regex}'`;case"GLOB":return`match glob '${r.glob}'`;case"DOMAIN":return`match domain '${r.domain}'`;default:return(t=>{throw"If Typescript complains about the line below, you missed a case or break in the switch above"})(r)}}function a0(r){return typeof r=="object"&&r!==null}function Yn(r){if(Array.isArray(r))return r.map(Yn);if(a0(r)){let e={};return Object.entries(r).forEach(([t,n])=>{n!==void 0&&(e[t]=Yn(n))}),e}return r}function s0(r){switch(r.type){case"AI_CHECK":return`AI check: ${r.assertion}`;case"TAP":return`Tap on element: ${ad(r.target)}`;case"TYPE":return`Type ${r.text} ${r.target?`into ${ad(r.target)}`:""}`;case"PRESS":return`Press the ${r.key} button`;case"PRESS_KEYBOARD":return`Press the ${r.key} key`;case"SWIPE":return r.scrollableElement.type==="CUSTOM"?`Swipe ${r.direction} in container: ${r.scrollableElement.target.description}`:`Swipe ${r.direction} in the ${r.scrollableElement.type.toLowerCase()}`;case"OPEN_APP":return`Open app: ${r.packageName}`;case"OPEN_NOTIFICATION_DRAWER":return"Open notification drawer";case"JAVASCRIPT":return`Execute JavaScript: ${r.code}`;case"REQUEST":return`Make API request to ${r.url}`;case"WAIT":return`Wait ${r.timeoutSecs} seconds`;case"ADD_FILE":return`Add file: ${r.file} to ${r.storageLocation}`;case"ADB":return`ADB command: ${r.command}`;case"STATE":return"Get state";default:{let e=r;throw new Error("If Typescript complains about the line above, you missed a case or break in the switch above")}}}function tv(r){switch(r.type){case"MOBILE_PRESET_STEP":return s0(r.command);case"MOBILE_MODULE_STEP":return`Module ${r.moduleId}`;case"RESOLVED_MOBILE_MODULE":return`Module ${r.name}`;case"MOBILE_AI_ACTION_STEP":return`AI action: ${r.text}`;default:{let e=r;throw new Error("If Typescript complains about the line above, you missed a case or break in the switch above")}}}import{cloneDeep as rv}from"lodash-es";async function nv(r){let e={},{resolvedSteps:t,newSchemaVersion:n}=await Zl({rawSteps:r.rawStepLists.steps,onFetchModule:r.onFetchModule,logger:r.logger,metadata:r.testMetadata,resolvedModuleCache:e}),o={steps:t};for(let i of["beforeSteps","afterSteps"]){let a=r.rawStepLists[i];if(!a)continue;let{resolvedSteps:l}=await Zl({rawSteps:a,onFetchModule:r.onFetchModule,logger:r.logger,metadata:r.testMetadata,resolvedModuleCache:e});o[i]=l}return{resolvedStepLists:o,moduleIds:Array.from(Object.keys(e))}}async function Zl({rawSteps:r,onFetchModule:e,logger:t,metadata:n,resolvedModuleCache:o={}}){let i=[];for(let a of r)i.push(await ov({rawStep:mr.parse(a),onFetchModule:e,logger:t,resolvedModuleCache:o}));return{resolvedSteps:i,newSchemaVersion:n.schemaVersion}}async function ov({rawStep:r,onFetchModule:e,logger:t,resolvedModuleCache:n}){switch(r.type){case"MOBILE_MODULE_STEP":{let o=r.moduleId,i=n[o];if(i)return{...rv(i),...r,type:"RESOLVED_MOBILE_MODULE"};let a=await e(o);if(!a)throw new Error(`Could not find module with id ${o}`);let l;try{l=mr.array().parse(a.steps)}catch(u){throw t.error({err:u,steps:a.steps,moduleId:o},"Module failed to parse (mobile)"),u}let c=await Promise.all(l.map(u=>ov({rawStep:u,onFetchModule:e,logger:t,resolvedModuleCache:n}))),s={...a,steps:c};return n[o]=rv(s),{...s,...r,type:"RESOLVED_MOBILE_MODULE"}}case"MOBILE_AI_ACTION_STEP":case"MOBILE_PRESET_STEP":return r}}import{cloneDeep as l0}from"lodash-es";import{v4 as kp}from"uuid";async function Zn(r){let e=new Map,t=new Set,n=l0(r.steps),o=await iv({...r,steps:n,moduleStepParents:[],moduleIdParents:[],moduleIdReplacements:e,seenModules:t});return{stepsToSave:o.stepsToSave,cachesToSave:o.cachesToSave,moduleUpdates:o.moduleUpdates}}async function iv({steps:r,...e}){let{seenModules:t,cacheCreationParams:n,moduleIdParents:o,moduleStepParents:i,moduleIdReplacements:a,shouldCreateNewModuleId:l,createNewCacheIds:c}=e,s={cachesToSave:[],stepsToSave:[],moduleUpdates:[]};for(let u of r)switch(u.id=c?kp():u.id,u.type){case"MOBILE_PRESET_STEP":{let d=u.command;d.id=c?kp():d.id,"cache"in d&&d.cache&&(n&&(s.cachesToSave=s.cachesToSave.concat(Np({id:d.id,orgId:n.orgId,testId:n.testId,value:nn.parse(d),moduleIdParents:o,moduleStepParents:i}))),delete d.cache),s.stepsToSave.push({...u,command:d});break}case"RESOLVED_MOBILE_MODULE":{let d=c?kp():u.id,p=u.moduleId;a.has(p)?p=a.get(p):l!==void 0&&(p=await l(u),a.set(u.moduleId,p));let{cachesToSave:m,stepsToSave:g,moduleUpdates:h}=await iv({...e,steps:u.steps,cacheCreationParams:n?{...n}:void 0,createNewCacheIds:!1,moduleStepParents:[...i,d],moduleIdParents:[...o,p],skipCacheIntermediateEntries:c});s.moduleUpdates=s.moduleUpdates.concat(h),s.cachesToSave=s.cachesToSave.concat(m),t.has(p)||(t.add(p),s.moduleUpdates.push({...Lo.parse(u),steps:mr.array().parse(g),moduleId:p}));let f=na.parse({...u,type:"MOBILE_MODULE_STEP",moduleId:p,inputs:u.inputs,id:d});s.stepsToSave.push(f);break}case"MOBILE_AI_ACTION_STEP":{s.stepsToSave.push(u);break}default:{let d=u}}return s}function c0(r){let e={parentChain:[]};return av(r,e),e}function av(r,e){let{onPreset:t,onModule:n,earlyStop:o}=r;for(let i of r.steps){if(i.type==="RESOLVED_MOBILE_MODULE"){if(n?.(i,e)&&o||(e.parentChain.push(i),av({...r,steps:i.steps},e)&&o))return!0;e.parentChain.pop();continue}if(t(i,e)&&o)return!0}return!1}function u0(r,e,t=[]){let n,o=[],i=(a,l)=>{let c=JSON.stringify(l.parentChain.map(u=>u.id)),s=t.length===0?!0:JSON.stringify(t)===c;return a.id===e&&s?(n=a,o=l.parentChain,!0):!1};return c0({steps:r,earlyStop:!0,onPreset:i,onModule:i}),{result:n,parentChain:o}}function sv({currentStep:r,currentParentChain:e,desiredStepId:t,desiredStepParentChain:n}){let o=Array.from(e),i=Array.from(n);for(let l=0;l<o.length;l++){if(o[l]!==i[l])return!1;i.shift()}return!!u0([r],t,i).result}function lv(r){let e=r[0],t=r[0],n=!1;for(;!n&&t;)switch(t.type){case"MOBILE_AI_ACTION_STEP":case"MOBILE_MODULE_STEP":if(!t.steps.length){e=t,n=!0;break}t=t.steps[0];break;case"MOBILE_PRESET_STEP":e=t,n=!0;break;default:{let l=t}}let o=r[r.length-1],i=r[r.length-1],a=!1;for(;!a&&i;)switch(i.type){case"MOBILE_AI_ACTION_STEP":case"MOBILE_MODULE_STEP":if(!i.steps.length){o=i,a=!0;break}i=i.steps[i.steps.length-1];break;case"MOBILE_PRESET_STEP":o=i,a=!0;break;default:{let l=i}}return{firstMetadata:e,lastMetadata:o}}function cv({result:r,firstMetadata:e,lastMetadata:t}){e&&(r.beforeSnapshot=e.beforeSnapshot),t&&(r.data=t.data,r.afterSnapshot=t.afterSnapshot,t.status!=="SUCCESS"&&(r.message=t.message))}import{cloneDeep as Xle}from"lodash-es";import Zle from"truncate-json";import{v4 as sce}from"uuid";import{cloneDeep as zle,unset as Hle}from"lodash-es";import{cloneDeep as pce}from"lodash-es";import{cloneDeep as Due}from"lodash-es";import rue from"diff-lines";import Up,{gte as oue}from"semver";var uv={name:"Migrate to ai step v2",fromVersion:"1.0.4",toVersion:"1.0.5",recursiveKeys:new Set(["results","commands"]),stopOnFailure:!0,execute:async r=>(r=r.filter(e=>!(e.status!==void 0&&e.type==="AI_ACTION")),r=r.map(e=>(e.status===void 0||e.type==="PRESET_ACTION"&&(e.results=e.commands??e.results??[]),e)),r)};var dv={name:"Make sure ai step v2 has done command",fromVersion:"1.0.5",toVersion:"1.0.6",recursiveKeys:new Set(["results","commands"]),stopOnFailure:!0,execute:async r=>r.map(e=>{if(e.type!=="AI_ACTION"||e.status!==void 0||!e.commands||!e.commands.length)return e;let t=e.commands,n=t[t.length-1];return n&&n.type!=="SUCCESS"&&t.push({type:"SUCCESS"}),e})};var d0=["target","fromTarget","toTarget"];function pv(r){for(let e of d0){if(r[e]===void 0)continue;let t=r[e];t.elementDescriptor!==void 0?t.type="description":r[e]={type:"description",elementDescriptor:""}}}var mv={name:"Migrate element target to discriminated union",fromVersion:"1.0.6",toVersion:"1.0.7",recursiveKeys:new Set(["results","steps"]),stopOnFailure:!0,execute:async r=>r.map(e=>{switch(e.type){case"PRESET_ACTION":return pv(e.command),e;case"AI_ACTION":{let t=e.commands;for(let n of t??[])pv(n);return e}default:return e}})};import{v4 as p0}from"uuid";var gv={name:"Ensure module steps have ids",fromVersion:"1.0.7",toVersion:"1.0.8",recursiveKeys:new Set(["results","steps"]),stopOnFailure:!0,execute:async r=>r.map(e=>{switch(e.type){case"MODULE":return e.id||(e.id=p0()),e;default:return e}})};import{v4 as hv}from"uuid";var fv={name:"Ensure module steps have ids",fromVersion:"1.0.8",toVersion:"1.0.9",recursiveKeys:new Set(["results","steps"]),stopOnFailure:!0,execute:async r=>r.map(e=>{switch(e.type){case"PRESET_ACTION":{if(!e.command)return e;let t=e.command;return t.id=t.id??hv(),e}case"AI_ACTION":return e.commands&&(e.steps=e.commands.map(t=>({type:"PRESET_ACTION",command:{...t,id:t.id??hv()}})),delete e.commands),e;default:return e}})};var Sv={name:"Migrate ai waits to checks",fromVersion:"1.0.9",toVersion:"1.0.10",recursiveKeys:new Set(["results","steps","blocks","elseSteps"]),stopOnFailure:!0,execute:async r=>r.map(e=>{switch(e.type){case"PRESET_ACTION":{if(!e.command)return e;let t=e.command;return typeof t.type!="string"||t.type!=="AI_WAIT"||(t.type="AI_ASSERTION",t.timeout||(t.timeout=10)),e}default:return e}})};import{v4 as m0}from"uuid";var yv={name:"Add ids to all steps",fromVersion:"1.0.10",toVersion:"1.0.11",recursiveKeys:new Set(["results","steps","blocks","elseSteps"]),stopOnFailure:!0,execute:async r=>r.map(e=>("id"in e&&typeof e.id=="string"||(e.id=m0()),e))};import{v4 as bv}from"uuid";var Ev={name:"Add ids to all steps",fromVersion:"1.0.11",toVersion:"1.0.12",recursiveKeys:new Set(["results","steps","blocks","elseSteps"]),stopOnFailure:!0,execute:async r=>r.map(e=>{if("id"in e&&typeof e.id=="string")return e;if("condition"in e&&typeof e.condition=="object"&&e.condition){let t=e.condition;t.id||(t.id=bv())}return e.id=bv(),e})};var Tv={name:"Move env key to steps",fromVersion:"1.0.12",toVersion:"1.0.13",recursiveKeys:new Set(["results","steps","blocks","elseSteps"]),stopOnFailure:!0,execute:async r=>r.map(e=>{if(e.type!=="PRESET_ACTION")return e;let t=e.command;return!t||typeof t.envKey!="string"||(e.envKey=t.envKey,delete t.envKey),e})};import{v4 as g0}from"uuid";var vv={name:"Redo last two migrations",fromVersion:"1.0.13",toVersion:"1.0.14",recursiveKeys:new Set(["results","steps","blocks","elseSteps"]),stopOnFailure:!0,execute:async r=>r.map(e=>{if((!("id"in e)||typeof e.id!="string")&&(e.id=g0()),e.type!=="PRESET_ACTION")return e;let t=e.command;return!t||typeof t.envKey!="string"||(e.envKey=t.envKey,delete t.envKey),e})};var Av={name:"Migrate select choice",fromVersion:"1.0.14",toVersion:"1.0.15",recursiveKeys:new Set(["results","steps","blocks","elseSteps"]),stopOnFailure:!0,execute:async r=>r.map(e=>{if(e.type!=="PRESET_ACTION")return e;let t=e.command;return!t||t.type!=="SELECT_OPTION"||e.option===void 0||(e.choice={type:"VALUE",value:t.option},e.option=void 0),e})};var wv={name:"Migrate select choice",fromVersion:"1.0.15",toVersion:"1.0.16",recursiveKeys:new Set(["results","steps","blocks","elseSteps"]),stopOnFailure:!0,execute:async r=>r.map(e=>{if(e.type!=="PRESET_ACTION")return e;let t=e.command;return t&&Rv(t),e})};function Rv(r){r&&Object.keys(r).forEach(e=>{if(typeof r[e]=="object"&&r[e]){Rv(r[e]);return}if(typeof r[e]!="string")return;let t=r[e];e==="code"?r[e]=t.replace(/inputs\./g,"env."):t.includes("{{")&&t.includes("}}")&&(r[e]=t.replace(/inputs\./g,"env."))})}var Cv={name:"Migrate switch tab choice",fromVersion:"1.0.16",toVersion:"1.0.17",recursiveKeys:new Set(["results","steps","blocks","elseSteps"]),stopOnFailure:!0,execute:async r=>r.map(e=>{if(e.type!=="PRESET_ACTION")return e;let t=e.command;return!t||t.type!=="TAB"||t.url===void 0||(t.action={type:"SUBSTRING",substring:t.url},t.url=void 0),e})};var xv={name:"Remove press keys sequentially",fromVersion:"1.0.17",toVersion:"1.0.18",recursiveKeys:new Set(["results","steps","blocks","elseSteps"]),stopOnFailure:!1,execute:async r=>r.map(e=>{if(e.type!=="PRESET_ACTION")return e;let t=e.command;return!t||t.type!=="TYPE"?e:t.pressKeysSequentially===void 0?(t.delay=0,e):(t.pressKeysSequentially&&(t.pressKeysSequentially=void 0,t.delay=50),e)})};var Mv={name:"Migrate wait for URL to matcher",fromVersion:"1.0.18",toVersion:"1.0.19",recursiveKeys:new Set(["results","steps","blocks","elseSteps"]),stopOnFailure:!1,execute:async r=>r.map(e=>{if(e.type!=="PRESET_ACTION")return e;let t=e.command;return!t||t.type!=="WAIT_FOR_URL"||t.url===void 0||(t.matcher={type:"GLOB",glob:t.url},t.url=void 0),e})};var _v={name:"Migrate select choice round 2",fromVersion:"1.0.19",toVersion:"1.0.20",recursiveKeys:new Set(["results","steps","blocks","elseSteps"]),stopOnFailure:!0,execute:async r=>r.map(e=>{if(e.type!=="PRESET_ACTION")return e;let t=e.command;if(!t)return e;if(t.type==="SELECT_OPTION"){if(t.option===void 0)return e;t.choice={type:"VALUE",value:t.option},t.option=void 0}else if(t.type==="TAB"){if(t.url===void 0)return e;t.action={type:"SUBSTRING",substring:t.url},t.url=void 0}else if(t.type==="WAIT_FOR_URL"){if(t.url===void 0)return e;t.matcher={type:"GLOB",glob:t.url},t.url=void 0}else t.type==="AI_WAIT"&&(t.type="AI_ASSERTION",t.timeout||(t.timeout=10));return e})};var Iv={name:"Migrate ",fromVersion:"1.0.20",toVersion:"1.0.21",recursiveKeys:new Set(["results","steps","blocks","elseSteps"]),stopOnFailure:!1,execute:async r=>r.map(e=>{if(e.type!=="PRESET_ACTION")return e;let t=e.command;return!t||t.type!=="MOCK_ROUTE"&&t.type!=="SET_HEADER"&&t.type!=="RECORD_REQUESTS"&&t.type!=="REGISTER_REQUEST_LISTENER"||(t.type==="REGISTER_REQUEST_LISTENER"||t.type==="RECORD_REQUESTS"?t.requestMatcher={urlMatcher:{type:"REGEX",regex:t.pattern}}:(t.type==="SET_HEADER"||t.type==="MOCK_ROUTE")&&t.urlPattern&&(t.requestMatcher={urlMatcher:{type:"REGEX",regex:t.urlPattern}})),e})};var Pv={name:"Migrate AI checks to preset actions",fromVersion:"1.0.0",toVersion:"1.0.1",recursiveKeys:new Set,execute:async r=>r.map(e=>{if(e.type!=="AI_ASSERTION")return e;let n={type:"PRESET_ACTION",command:{type:"AI_ASSERTION",assertion:e.text,useVision:!1,disableCache:!0}},o={...e,...n};return delete o.text,o}),stopOnFailure:!0};var Ql=new Set(["CLICK","TYPE","SELECT_OPTION"]),Ov={name:"Migrate element descriptor to live in a target object",fromVersion:"1.0.3",toVersion:"1.0.4",recursiveKeys:new Set,execute:async r=>r.map(e=>{let t=e.command,n=t?.type,o=t?.elementDescriptor;return(o!==void 0||Ql.has(n))&&(t.target={elementDescriptor:o??""}),e.commands&&Array.isArray(e.commands)&&e.commands.forEach(a=>{let l=a?.elementDescriptor,c=a?.type;(l!==void 0||Ql.has(c))&&(a.target={elementDescriptor:l??""})}),e.results&&Array.isArray(e.results)&&e.results.forEach(a=>{let l=a.command,c=l?.elementDescriptor,s=l?.type;(c!==void 0||Ql.has(s))&&(l.target={elementDescriptor:c??""}),a.commands&&Array.isArray(a.commands)&&a.commands.forEach(d=>{let p=d?.elementDescriptor,m=d?.type;(p!==void 0||Ql.has(m))&&(d.target={elementDescriptor:p??""})})}),e}),stopOnFailure:!0};var Lv={name:"Migrate FAILURE status to FAILED",fromVersion:"1.0.1",toVersion:"1.0.2",recursiveKeys:new Set,execute:async r=>r.map(e=>{let t=e;return t.status==="FAILURE"&&(t.status="FAILED"),typeof t.commands=="object"&&Array.isArray(t.commands)&&t.commands.forEach(n=>{if(n&&typeof n=="object"){let o=n;o?.status==="FAILURE"&&(o.status="FAILED")}}),t}),stopOnFailure:!0};var Nv={name:"Migrate preset step types to use the same",fromVersion:"1.0.2",toVersion:"1.0.3",recursiveKeys:new Set,execute:async r=>r.map(e=>{let t=e.command,n=t?.type;return n?.startsWith("PRESET_")&&(t.type=n.slice(7)),e.commands&&Array.isArray(e.commands)&&e.commands.forEach(i=>{let a=i.type;a?.startsWith("PRESET_")&&(i.type=a.slice(7))}),e.results&&Array.isArray(e.results)&&e.results.forEach(i=>{let a=i.command,l=a?.type;l?.startsWith("PRESET_")&&(a.type=l.slice(7)),i.commands&&Array.isArray(i.commands)&&i.commands.forEach(s=>{let u=s.type;u?.startsWith("PRESET_")&&(s.type=u.slice(7))})}),e}),stopOnFailure:!0};var ec=[Pv,Lv,Nv,Ov,uv,dv,mv,gv,fv,Sv,yv,Ev,Tv,vv,Av,wv,Cv,xv,Mv,_v,Iv];if(Ln!==ec[ec.length-1].toVersion)throw new Error("Please bump LATEST_SCHEMA_VERSION in types package after adding a migration");ec.forEach((r,e)=>{if(!Up.valid(r.toVersion)||!Up.valid(r.fromVersion))throw new Error(`Migration '${r.name}' has invalid version`);if(!Up.gt(r.toVersion,r.fromVersion))throw new Error(`Migration '${r.name}' has toVersion <= fromVersion`);if(e===0)return;if(ec[e-1].toVersion!==r.fromVersion)throw new Error(`Migration '${r.name}' at index ${e} is not contiguous with previous migration`)});import{diff as Que}from"deep-object-diff";import{cloneDeep as tde}from"lodash-es";import{v4 as fde}from"uuid";import{cloneDeep as Ede}from"lodash-es";import{stringify as Ode}from"yaml";async function X(r,e){if(!(r<=0))return new Promise((t,n)=>{if(e?.aborted){n(e.reason);return}e?.addEventListener("abort",i,{once:!0});let o=setTimeout(()=>{e?.removeEventListener("abort",i),t()},r);function i(){clearTimeout(o),e?.removeEventListener("abort",i),n(e?.reason)}})}async function Fp({promiseGenerator:r,signal:e,codePath:t,logger:n}){let i=Date.now(),a=setInterval(()=>{if(e?.aborted){clearInterval(a);return}n?.warn({codePath:t,startTime:i,elapsedMilliseconds:Date.now()-i},`Asynchronous operation is taking a long time (${t})`)},5e3);return new Promise((l,c)=>{function s(){clearInterval(a),e?.removeEventListener("abort",s),c(e?.reason)}if(e?.aborted){c(e?.reason),clearInterval(a);return}e?.addEventListener("abort",s,{once:!0}),(async()=>{try{l(await r())}catch(u){c(u)}finally{clearInterval(a),e?.removeEventListener("abort",s)}})()})}async function La({promiseGenerator:r,timeoutMs:e,codePath:t,logger:n,signal:o}){let i=!1,a=new AbortController,l=()=>{a.abort()},c=setTimeout(()=>{o?.removeEventListener("abort",l),!i&&a.abort()},e);o?.addEventListener("abort",l,{once:!0});try{return await Fp({promiseGenerator:r,signal:a.signal,codePath:t,logger:n})}finally{i=!0,o?.removeEventListener("abort",l),clearTimeout(c)}}function tc(r){let e;return r>10*60*1e3?e=2*60*1e3:r>60*1e3?e=20*1e3:r>10*1e3?e=2*1e3:e=1e3,e}import h0 from"picomatch";var rc=(r,e,t)=>{t?.caseInsensitive&&(r=r.toLowerCase());let n;switch(e.type){case"SUBSTRING":{let o=t?.caseInsensitive?e.url.toLowerCase():e.url;n=r.includes(o);break}case"GLOB":{let o=t?.caseInsensitive?e.glob.toLowerCase():e.glob;n=r===e.glob||h0(o)(r);break}case"REGEX":{n=new RegExp(e.regex).test(r);break}case"DOMAIN":{let o=t?.caseInsensitive?e.domain.toLowerCase():e.domain;n=new URL(r).hostname===o;break}}return t?.negated?!n:n},nc=(r,e)=>{try{let{hostname:t,pathname:n}=new URL(r),{hostname:o,pathname:i}=new URL(e);return t!==o||n!==i}catch{return!1}},Zo=r=>{try{return new URL(r),!0}catch{return!1}},kv=r=>!r.toLowerCase().startsWith("http"),Qo=(r,e)=>{try{return new URL(r,e),!0}catch{return!1}};function Qn(r,e){try{return!!new URL(r).origin.trim()}catch(t){return e?.error({url:r,err:t},"Invalid URL in check"),!1}}import{v4 as Uv}from"uuid";function Bp(r,e){return{...r,testId:e?.testId??"",testName:e?.testName??"",suiteId:e?.suiteId??"",suiteName:e?.suiteName??""}}var oc=class{reporter;asyncWork;metadata;creditsUsedV1=0;creditsUsedV2=0;constructor({logger:e,reporter:t,runType:n,runId:o,testMetadata:i,suiteMetadata:a}){this.reporter=t,this.metadata={testId:i.id,testName:i.name,suiteId:a?.id,suiteName:a?.name},this.asyncWork=[t.reportBillableEvents(e,[{event:n,timestamp:new Date().toISOString(),transactionId:o,properties:Bp({},this.metadata)}]).catch(l=>e.error({err:l},"Failed to report billable event"))]}trackStepExecution(e){if(tS(e.type)){this.creditsUsedV2+=1;return}let t=ed(e.type);if(this.creditsUsedV1+=t??0,e.type==="PRESET_ACTION"){this.creditsUsedV2+=1;let n=td(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:Uv(),properties:Bp({creditsUsed:this.creditsUsedV1},this.metadata)}]).catch(t=>e.error({err:t},"Failed to report credits used"))),this.creditsUsedV2>0&&this.asyncWork.push(this.reporter.reportBillableEvents(e,[{event:"credits-used-v2",timestamp:new Date().toISOString(),transactionId:Uv(),properties:Bp({creditsUsed:this.creditsUsedV2},this.metadata)}]).catch(t=>e.error({err:t},"Failed to report credits used"))),await Promise.allSettled(this.asyncWork)}};import{CookieJar as yF}from"tough-cookie";var zp={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
|
|
30
36
|
var momenticConstants = {
|
|
31
37
|
bannedClassSubstrings: [
|
|
32
38
|
"relative",
|
|
@@ -3822,6 +3828,12 @@ function findVisibleMomenticIdAndPoint(documentRoot, originalElement, logs) {
|
|
|
3822
3828
|
absoluteX,
|
|
3823
3829
|
absoluteY
|
|
3824
3830
|
);
|
|
3831
|
+
if (!candidateElementsAtPoint.length) {
|
|
3832
|
+
logs.push(
|
|
3833
|
+
\`No candidates were found at point \${absoluteX}, \${absoluteY}\`
|
|
3834
|
+
);
|
|
3835
|
+
continue;
|
|
3836
|
+
}
|
|
3825
3837
|
let candidateElement = null;
|
|
3826
3838
|
for (const candidate of candidateElementsAtPoint) {
|
|
3827
3839
|
if (!candidate.checkVisibility({
|
|
@@ -3852,7 +3864,7 @@ function findVisibleMomenticIdAndPoint(documentRoot, originalElement, logs) {
|
|
|
3852
3864
|
}
|
|
3853
3865
|
if (!candidateElement) {
|
|
3854
3866
|
logs.push(
|
|
3855
|
-
\`No candidate element was found was found at \${absoluteX}, \${absoluteY}\`
|
|
3867
|
+
\`No eligible candidate element was found was found at \${absoluteX}, \${absoluteY}\`
|
|
3856
3868
|
);
|
|
3857
3869
|
continue;
|
|
3858
3870
|
}
|
|
@@ -3999,55 +4011,82 @@ function registerAllMomenticListeners() {
|
|
|
3999
4011
|
|
|
4000
4012
|
// src/html/index.ts
|
|
4001
4013
|
registerAllMomenticListeners();
|
|
4002
|
-
`};var
|
|
4003
|
-
`,o);a>0&&a<n&&(o=a);let
|
|
4004
|
-
`;)c++,
|
|
4005
|
-
`&&(i=
|
|
4006
|
-
`,""),t=t.replaceAll(" ","");let n=
|
|
4007
|
-
`,";").replace(/\s+/g," ");let a="",
|
|
4008
|
-
${c}`,{errOptions:{cause:r}})}if(i.includes("element is not visible")){let c="The element you attempted to interact with has no bounding box or is explicitly hidden.";try{let l=await e.boundingBox({timeout:te});l?l.height===0?c="The element you attempted to interact with has zero height.":l.width===0&&(c="The element you attempted to interact with has zero width."):c="The element you attempted to interact with has no bounding box."}catch{}return new _("ActionFailureError",`${c} Please explicitly wait for the element to be visible or turn on the 'disable stability checks' option. ${a}`,{errOptions:{cause:r}})}return i.includes("element is outside of the viewport")?new _("ActionFailureError",`The element requested was outside of the browser viewport for the entire duration of the action. Please ensure you are not using non-standard zoom settings and the element is visible on the page. ${a}`):r}function ID(r){let e=r.message;if(e.includes("waiting for locator")&&e.includes("data-momentic-id")&&!e.match(/attempting \w+ action/)&&!e.includes("locator.evaluate"))throw new _("ActionFailureError",`Interacting with the element timed out. This is usually caused by the web page itself performing too many CPU-intensive operations or a lack of resources on your machine. Error: ${e}`,{errOptions:{cause:r}});return r}import{existsSync as $a,mkdirSync as Am,readdirSync as UD,rmSync as MA}from"fs";import{homedir as Rm}from"os";import{join as Zr,resolve as FD}from"path";import{chromium as IA}from"playwright-core";import{addExtra as BD}from"playwright-extra";import zD from"puppeteer-extra-plugin-recaptcha";function RA(r,e){return async(t,n)=>{try{let o=await n.allHeaders();for(let{key:i,value:a,matcher:s}of r)(!s||s.matches({url:n.url(),method:n.method()}))&&(o[i]=a);await t.fallback({headers:o})}catch(o){e.warn({err:o},"Failed to apply custom headers to request, continuing")}}}import{randomUUID as OD}from"crypto";function CA(r,e){for(let t of Object.values(e))if(t.matcher.matches({url:r.url(),method:r.method()}))return t}async function xA(r){let{route:e,mock:t,entry:n,debugData:o,requestId:i,requestRecorders:a,logger:s}=r,c={url:n.request.url,options:{method:n.request.method,headers:n.request.headers.map(g=>[g.name,g.value]),body:n.request.postData?.text}},l;if(t.fetchOriginalResponse){let g=await e.fetch();l={body:await g.text(),options:{status:g.status(),statusText:g.statusText(),headers:Object.entries(await g.headers())}}}let u=await PD(t,c,l),d={};u.headers.forEach((g,m)=>{d[m]=g});let p={body:await u.text(),contentType:u.headers.get("content-type")||"text/plain",headers:d,status:u.status};await e.fulfill(p);try{n.response={status:p.status,statusText:u.statusText,headers:Object.entries(p.headers).map(([g,m])=>({name:g,value:m})),cookies:[],content:{mimeType:p.contentType,text:p.body},_mocked:!0},Va(o,n,i);for(let g of Object.values(a))g.onRequestComplete(i,n)}catch(g){g.message.includes("has been closed")||s.warn({err:g},"Failed to add response to HAR")}}async function PD(r,e,t){try{return await r.generateResponse(e,t)}catch(n){let o=n instanceof Error?n.message:`${n}`;return new Response(o,{status:500,headers:{"Content-Type":"text/plain"}})}}async function ym(r){try{await LD(r)}catch(e){r.logger.warn({err:e},"Error handling intercepted request, continuing...")}}async function LD(r){let{pageId:e,route:t,request:n,debugData:o,logger:i,requestRecorders:a,mocks:s}=r,c=OD(),l=await fm(e,n);try{Va(o,l,c);for(let d of Object.values(a))d.onRequestStart(c,l)}catch(d){i.warn({err:d},"Failed to add request to HAR")}let u=CA(n,s);u?await xA({logger:i,route:t,mock:u,entry:l,debugData:o,requestId:c,requestRecorders:a}):await ND({route:t,request:n,debugData:o,logger:i,requestRecorders:a,entry:l,requestId:c})}async function ND({route:r,request:e,debugData:t,logger:n,requestRecorders:o,entry:i,requestId:a}){await r.continue();try{let s=await e.response();if(!s||!i)return;await TA(i,e,s),Va(t,i,a);for(let c of Object.values(o))c.onRequestComplete(a,i)}catch(s){s.message.includes("has been closed")||n.warn({err:s},"Failed to add response to HAR")}}async function kD(r){let e=r.postData();if(e){if((await r.headerValue("content-type"))?.includes("json"))try{return{json:r.postDataJSON()}}catch{return{}}else if((await r.headerValue("content-type"))?.includes("text"))return{text:e}}return{}}async function DD(r){let e=await r.text();if(e){if((await r.headerValue("content-type"))?.includes("json"))try{return{json:await r.json()}}catch{return{}}else if((await r.headerValue("content-type"))?.includes("text"))return{text:e}}return{}}function Ec(r){return{request:{url:r.request.url,method:r.request.method,headers:r.request.headers.reduce((e,t)=>({...e,[t.name]:t.value}),{}),...r.request.postData?r.request.postData.mimeType.includes("json")?{json:JSON.parse(r.request.postData.text)}:{text:r.request.postData.text}:{}},response:r.response?{status:r.response.status,headers:r.response.headers.reduce((e,t)=>({...e,[t.name]:t.value}),{}),...r.response.content?r.response.content.mimeType?.includes("json")&&r.response.content.text?{json:JSON.parse(r.response.content.text)}:{text:r.response.content.text}:{}}:void 0}}async function bm(r){let e=r.request(),t=r.status(),n=r.headers(),o=await DD(r);return{request:{url:e.url(),method:e.method(),headers:e.headers(),...await kD(e)},response:{status:t,headers:n,...o},status:t,headers:n,...o}}var _n=class{requestMatcher;constructor(e){this.requestMatcher=e}matches(e){let{url:t,method:n}=e;return this.requestMatcher.method&&this.requestMatcher.method.toLowerCase()!==n.toLowerCase()?!1:gc(t,this.requestMatcher.urlMatcher)}};function Wa(r){let e=new URL(r.request().url());return/^127\./.test(e.hostname)||/^192\.168\./.test(e.hostname)||/^10\./.test(e.hostname)||/^172\.(1[6-9]|2\d|3[0-1])\./.test(e.hostname)||e.hostname==="localhost"?r.abort():r.fallback()}import{homedir as Em,platform as Tm}from"os";import{join as vm}from"path";function Tc(){let r=[];if(Tm()==="linux"){let e=Em();["chromium","google-chrome","chrome-canary"].forEach(t=>{r.push(vm(e,".config",t,"Crash Reports"))})}else if(Tm()==="darwin"){let e=Em();["Chromium","Google","Chrome for Testing"].forEach(t=>{r.push(vm(e,"Library","Application Support",t,"Crashpad"))})}else if(Tm()==="win32"){let e=Em();["Chromium","Google","Google Chrome Canary"].forEach(t=>{r.push(vm(e,"AppData","Local",t,"User Data","Crashpad","reports"))})}return r}function _A(){return{name:"fs_optout",value:"1",domain:".fullstory.com",path:"/",expires:Date.now()/1e3+365*24*60*60,httpOnly:!1,secure:!0,sameSite:"None"}}var wm=Zr(Rm(),"momentic","chromium"),HD=Zr(Rm(),"video"),PA=BD(IA);PA.use(zD({provider:{id:"2captcha",token:mi},visualFeedback:!0}));var GD=["--enable-crashpad","--crash-on-hang-threads=UI:18,IO:18"],jD=["--disable-dev-shm-usage","--no-first-run","--renderer-process-limit=3","--browser-test","--disable-site-isolation-for-policy","--disable-site-isolation-trials","--disable-backgrounding-occluded-windows","--disable-background-timer-throttling","--disable-renderer-backgrounding","--autoplay-policy=user-gesture-required","--disable-add-to-shelf","--disable-desktop-notifications","--use-fake-device-for-media-stream","--use-fake-ui-for-media-stream","--enable-logging=stderr","--log-level=2"],VD=["--disable-3d-apis","--disable-gpu","--disable-software-rasterizer","--disable-accelerated-2d-canvas","--disable-accelerated-mjpeg-decode","--disable-accelerated-video-decode","--disable-accelerated-video-encode","--disable-gl-drawing-for-tests","--disable-webgl","--disable-webgl2","--disable-audio-input","--disable-audio-output"];async function OA({baseUrl:r,logger:e,storage:t,enricher:n,userBrowserSettings:o,contextArgs:i,recordVideo:a,iconKnowledgeBase:s,callbacks:c}){process.env.PW_TEST_SCREENSHOT_NO_FONTS_READY="1";let l;switch(o.browserType){case"Google Chrome":l="chrome";break;case"Chrome for Testing":l=void 0;break;case"Chromium":l="chromium";break;default:l="chromium";break}let u=[...jD],d={headless:process.env.MOMENTIC_HEADFUL_BROWSER!=="true",handleSIGTERM:!1,chromiumSandbox:!1,channel:l},p={...i??{},geolocation:i?.geolocation||Bb,locale:i?.locale||Ub,timezoneId:i?.timezoneId||Fb,colorScheme:i?.colorScheme,httpCredentials:o.basicAuthorization?{username:o.basicAuthorization.username??"",password:o.basicAuthorization.password??""}:void 0,javaScriptEnabled:o.disableJavaScript?!1:void 0,ignoreHTTPSErrors:o.ignoreHttpsErrors??!1,userAgent:o.userAgent??yc,viewport:i?.viewport??yn,serviceWorkers:"block",storageState:{cookies:[_A()],origins:[]}};o.initialLocalStorage&&(p.storageState.origins=Object.entries(o.initialLocalStorage).map(([S,A])=>({origin:S,localStorage:Object.entries(A).map(([C,T])=>({name:C,value:T}))}))),process.env.MOMENTIC_CHROME_EXTRA_ARGS&&u.push(...process.env.MOMENTIC_CHROME_EXTRA_ARGS.split(","));let g=null,m,h,f={systemDevicePixelRatio:i?.deviceScaleFactor,recordVideo:a,isNewHeadless:!1};(l==="chrome"||l==="chromium")&&(f.isNewHeadless=!0,d.headless&&u.push("--headless=new")),process.env.BROWSER_MEMORY_MB&&u.push(`--js-flags=--max_old_space_size=${process.env.BROWSER_MEMORY_MB}`);try{let S=Tc();S.forEach(A=>{if(!$a(A))return;["new","pending","completed"].forEach(T=>{let I=Zr(A,T);if(!$a(I))return;let R=UD(I);for(let w=0;w<R.length;w++){let B=Zr(I,R[w]);MA(B,{force:!0})}})}),S.forEach(A=>{$a(A)||Am(A,{recursive:!0});let C=Zr(A,`write-test-${Date.now()}`);Am(C,{recursive:!0}),MA(C,{recursive:!0,force:!0})}),u.push(...GD)}catch(S){e.warn({err:S},"Could not create Chrome crash report directory, not enabling crashpad")}o.disableGpu&&u.push(...VD);let E=o.localChromeExtensionPaths?.map(S=>S.startsWith("~")?Zr(Rm(),S.slice(1)):S);if(E?.length){if(l===void 0)throw new _("UserConfigurationError","Chrome extensions are only supported on Chromium and Google Chrome.");for(let T of E){let I=Zr(T,"manifest.json");if(!$a(I))throw new _("UserConfigurationError",`Chrome extension path ${I} does not exist.`)}if(wn)throw new _("UserConfigurationError","Cannot use persistent browser context on Momentic Cloud");let S=Zr(wm,`momentic-session-${Date.now()}`);if(!$a(S))try{Am(S,{recursive:!0})}catch(T){throw new _("UserConfigurationError",`Failed to create browser cache directory. Please make sure you have sufficient permissions to create the ${wm} folder: ${T}`)}let A=[...u],C=E.map(T=>FD(T)).join(",");A.push(`--disable-extensions-except=${C}`),p?.deviceScaleFactor&&A.push(`--force-device-scale-factor=${p.deviceScaleFactor}`,`--device-scale-factor=${p.deviceScaleFactor}`),p.viewport&&A.push(`--window-size=${p.viewport.width},${p.viewport.height}`),m=await IA.launchPersistentContext(Zr(wm,`momentic-session-${Date.now()}`),{...d,...p,ignoreDefaultArgs:["--disable-extensions","--disable-component-extensions-with-background-pages"],args:A,baseURL:r}),e.info({sharedContextOptions:p,sharedBrowserOptions:d,userBrowserSettings:o,chromeArgs:A,properties:f,baseUrl:r},"Browser initialization context args (persistent)"),h=m.pages()[0]}else{g=await PA.launch({...d,args:u});let S={...p,baseURL:r,recordVideo:a?{dir:HD}:void 0};m=await g.newContext(S),e.info({contextArgs:S,sharedBrowserOptions:d,chromeArgs:u,userBrowserSettings:o,properties:f,baseUrl:r},"Browser initialization context args (standard)"),h=await m.newPage()}return wn&&await m.route("**",Wa),{browser:g,context:m,page:h,baseUrl:r,logger:e,storage:t,enricher:n,userBrowserSettings:o,viewport:p.viewport||yn,properties:f,clientCallbacks:c,iconKnowledgeBase:s}}async function LA(r){try{return await WD(r)}catch(e){r.logger.warn({err:e},"Failed to transform locator for Chakra click, continuing...");return}}async function WD({locator:r,logger:e}){let[t,n]=await r.evaluate(c=>[c.id,c.tagName.toLowerCase()],{timeout:re}),o=await Jr(r,e),i=await r.boundingBox({timeout:re});if(i===null){e.warn({elementDisplayString:o},"Attempting to click on element with no bounding box, not performing Chakra redirection");return}if(i.width>5||i.height>5||n!=="input")return;if(t)try{let c=r.page().locator(`label[for=${JSON.stringify(t)}]`);return await c.waitFor({state:"visible",timeout:re}),{locator:c,relativePoint:void 0}}catch{}let a=await r.evaluate(c=>{let l=window,u=c.parentElement;if(!u)return{type:"error",error:"Input click target has no parent for redirection"};let d=c.getBoundingClientRect(),p=u.getBoundingClientRect();if(p.width===0||p.height===0)return{type:"error",error:"Parent element has no width or height"};let g={x:Math.min(Math.max(1,d.left-p.left),p.width-1),y:Math.min(Math.max(1,d.top-p.top),p.height-1)},m=l._MOMENTIC_FEATURE_FLAGS?.[Sc],h=c.getAttribute(Xr),f=!m&&h?Tr(h):l.getMPath?.(c)?.join(" >");return f?{type:"result",selector:f,relativePoint:g,serializedForm:u.outerHTML.slice(0,500)}:{type:"error",error:"Could not generate selector for parent element"}},{timeout:re});if(a.type==="error")throw new Error(a.error);let s=r.page().locator(a.selector);return await s.waitFor({state:"visible",timeout:re}),e.info({parentElementResult:a,originalElementDisplayString:o},`Redirected click to parent element with selector: ${a.selector}`),{locator:s,relativePoint:a.relativePoint}}var kA=["date","datetime-local","month","time","week"],NA={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 DA(r){try{await V($D(r),{milliseconds:te})}catch(e){r.logger.warn({err:e},"Failed to transform native datetime input, continuing...")}}async function $D({root:r,text:e,options:t,logger:n,callbacks:o}){let i=(await et({root:r,fn:()=>document.activeElement?.getAttribute("type")??"",timeout:re,arg:void 0,waitForPageLoad:o.waitForPageLoad,codePath:"transforming native datetime input"})).toLowerCase();if(!NA[i])return;NA[i].test(e)&&n.warn(`Detected datetime input (${e}) in normalized format - this may fail to fill correctly as it is not how the user would input the value`),t.clearContent=!1,n.info("Transforming datetime input to use sequential key presses")}import{z as Ft}from"zod";var UA=Ft.object({doubleClick:Ft.boolean().optional(),rightClick:Ft.boolean().optional(),force:Ft.boolean().optional(),waitForDownload:Ft.boolean().optional(),delayMs:Ft.number().optional(),downloadTimeoutMs:Ft.number().optional(),relativePosition:Ft.object({x:Ft.number(),y:Ft.number()}).optional()}),zhe=Ft.object({repeat:Ft.number().optional(),convertMeta:Ft.boolean().optional().describe("misleading name due to backcompat. converts keyshortcuts + meta/control to platform-specific combos. defaults to true"),delayMs:Ft.number().optional()});async function vc({locator:r,callbacks:e,logger:t,timeoutMs:n=re}){try{await Cm(e,n);let o=r.evaluate(i=>{let a=window;a.momenticIsEligible=d=>{let g=window.getComputedStyle(d,null).getPropertyValue("display");if(g==="none"||g==="contents")return!1;let m=d.getBoundingClientRect();return!(!m.height||!m.width)},a.removeHighlightTimers=a.removeHighlightTimers||[],a.removeHighlightFunctions=a.removeHighlightFunctions||{};let s=0;for(;!a.momenticIsEligible(i)&&s<3;){if(!i.parentElement)throw new Error("No eligible non-empty parent found for highlighting");i=i.parentElement,s++}let c=i.style.getPropertyValue("outline"),l=i.style.getPropertyPriority("outline");i.style.setProperty("outline","5px dashed rgb(255, 0, 153)","important");let u=`momentic${Math.floor(Math.random()*1e7)}`;a[u]=()=>{i.style.removeProperty("outline"),i.style.setProperty("outline",c,l),i.getAttribute("style")||i.removeAttribute("style")},a.removeHighlightTimers.push(setTimeout(()=>{a[u](),a.removeHighlightFunctions?.[u]&&delete a.removeHighlightFunctions[u]},5e3)),a.removeHighlightFunctions[u]=a[u]},void 0,{timeout:n});return await V(o,{milliseconds:n}),!0}catch(o){return t.debug({err:o},"Failed to add node highlight, a page navigation likely occurred. This is non-fatal for tests."),!1}}async function Cm(r,e=re){let t=await r.state.getRoot();await et({root:t,fn:()=>{let o=window,i=o.removeHighlightTimers||[];for(;i.length;){let a=i.pop();clearTimeout(a)}Object.values(o.removeHighlightFunctions??{}).forEach(a=>{a()})},timeout:e,arg:void 0,waitForPageLoad:r.waitForPageLoad,codePath:"removing element highlights"})}async function xm(r){let e=!!r.browserCallbacks.state.userBrowserSettings.visualActions;return mo({action:"clicking element",targetingResult:r.targetingResult,logger:r.logger,retryTimeoutMs:r.retryTimeoutMs,callbacks:r.browserCallbacks,func:async t=>BA({...r,targetingResult:t,useVisualClick:e})})}async function XD(r,e){let{redirectionAttempts:t=0}=e;if(t>=2)throw r;try{return await JD(r,e)}catch(n){throw e.redirectionAttempts===0?(e.logger.error({redirectionAttemptError:n,originalError:r},"Error handling click error, rethrowing original error"),r):n}}async function JD(r,e){let{logger:t,redirectionAttempts:n=0}=e,o=e.targetingResult.locator;if(r.message.includes("label")&&r.message.includes("for=")&&r.message.includes("intercepts pointer events")){let i=await o.getAttribute("id",{timeout:re});if(!i)throw r;let a=o.page().locator(`[for=${JSON.stringify(i)}]`);return await a.waitFor({state:"visible",timeout:re}),t.warn({err:r},"Attempting locator redirection due to input being covered by label"),BA({...e,targetingResult:{locator:a},redirectionAttempts:n+1})}else throw t.error({err:r},"Click error does not match any known recoverable patterns, rethrowing"),r}async function ZD(r){let{logger:e,targetingResult:t,position:n,options:o}=r,i=UA.safeParse(o),a=Date.now(),{clickX:s,clickY:c,reason:l}=await tU({targetingResult:t,position:n,options:o});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 QD(r){let{actionSource:e,targetingResult:t,options:n,logger:o}=r,i=r.targetingResult.locator,a=n?.relativePosition??r.position;if(e==="click"&&!a){let l=await LA({locator:i,logger:o});l&&(i=l.locator,a=l.relativePoint??a)}let s=n?.force||t.hints?.force||!1;s&&!a&&t.hints?.relativeXYToLocator&&(a=t.hints.relativeXYToLocator);let c=i.toString();try{o.info({locator:c},"Locator click"),n?.doubleClick?await i.dblclick({button:n.rightClick?"right":"left",timeout:te,position:a,delay:n?.delayMs??25,force:s}):await i.click({button:n?.rightClick?"right":"left",timeout:te,position:a,delay:n?.delayMs??25,force:s})}catch(l){let u=l;if(nU(u))o.warn({err:u},"Click action timed out while waiting for navigation after completion, continuing...");else return o.error({err:u},"Error clicking on locator, attempting to recover..."),XD(u,{...r,targetingResult:{...i,locator:i}})}return{locatorSource:c}}async function BA(r){let{options:e,logger:t,browserCallbacks:n,controllerCallbacks:o,useVisualClick:i,targetingResult:a}=r,s;e?.waitForDownload&&(s=(async()=>{let u=e.downloadTimeoutMs??rm;try{return await a.locator.page().waitForEvent("download",{timeout:u})}catch(d){return d instanceof YD.TimeoutError?new _("ActionFailureError",`Download did not complete in ${u}ms`):new _("ActionFailureError",`Download failed: ${d.message}`)}})());try{await vc({locator:a.locator,callbacks:n,logger:t,timeoutMs:re})}catch(u){t.warn({err:u},"Error highlighting locator in click, continuing...")}let c,l;if(i?c=await ZD(r):l=(await QD(r)).locatorSource,e?.waitForDownload)if(s){if(!o?.createIsolatedFolder)throw new _("InternalWebAgentError","Cannot wait for download without a callback to create an isolated folder");t.info("Waiting for download to start and complete");let u=await V(s,{milliseconds:e.downloadTimeoutMs??rm});if(u instanceof Error)throw u;return{downloadedFile:await rU(u,o.createIsolatedFolder,t),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 eU(r){let e=await r.locator.boundingBox({timeout:te});if(!e)throw new _("ActionFailureError","Element does not have a bounding box");if(r.hints?.relativeXYToLocator){let o=e.x+r.hints.relativeXYToLocator.x,i=e.y+r.hints.relativeXYToLocator.y;return[{x:o,y:i},"targeting hint"]}let t=e.x+e.width/2,n=e.y+e.height/2;return[{x:t,y:n},"halfway point"]}async function tU({options:r,targetingResult:e,position:t}){let n,o,i;if(r?.relativePosition){let l=await e.locator.boundingBox({timeout:te}),u=r.relativePosition.x,d=r.relativePosition.y;l?.width&&(u=Math.max(0,Math.min(r.relativePosition.x,l.width))),l?.height&&(d=Math.max(0,Math.min(r.relativePosition.y,l.height))),n=(l?.x??0)+u,o=(l?.y??0)+d,i="relative position from user"}else if(t){let l=await e.locator.boundingBox({timeout:te});n=(l?.x??0)+t.x,o=(l?.y??0)+t.y,i="predefined position"}else{let[l,u]=await eU(e);n=l.x,o=l.y,i=u}let a=e.locator.page(),s=r?.rightClick?"right":"left",c=r?.delayMs??25;return r?.doubleClick?await a.mouse.dblclick(n,o,{button:s,delay:c}):await a.mouse.click(n,o,{button:s,delay:c}),{clickX:n,clickY:o,reason:i}}async function rU(r,e,t){t.info("Download detected, saving file to disk");let n=await r.path(),o=mm(r.suggestedFilename()),i=e();await r.saveAs(KD(i,o)),FA(n,{force:!0}),setTimeout(()=>{FA(i,{recursive:!0,force:!0})},5*60*1e3);let a=mA(qD(i),o);return t.info({uri:a,downloadFolder:i},"Saved download to isolated folder"),a}function nU(r){return r.message.includes("locator.click: Timeout")&&r.message.includes("click action done")}import{platform as oU}from"os";var iU={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 aU(){let r=oU();return r==="win32"?"win32":r==="darwin"?"darwin":"linux"}function zA(r){return JSON.stringify(r.split("+").sort())}function Ac(r,e){let t=aU(),n=zA(r);for(let o of Object.values(iU))if(Object.values(o).some(i=>zA(i)===n))return o[t];return process.platform==="darwin"&&!e?r=r.replaceAll("Control","Meta"):r=r.replaceAll("Meta","Control"),r}async function _m({frame:r,page:e,deltaX:t,directionX:n,deltaY:o,directionY:i,signal:a,callbacks:s,logger:c}){if(!t&&!o)return;let l=n==="left"?-1:1,u=i==="up"?-1:1;if(r)await et({root:r,fn:([d,p,g,m])=>window.scrollTo(window.scrollX+(d??window.innerWidth)*g,window.scrollY+(p??window.innerHeight)*m),arg:[t,o,l,u],waitForPageLoad:s.waitForPageLoad,timeout:he,codePath:"scrolling page"});else{let d=e.viewportSize()||yn,p=await et({root:e,fn:()=>document.body.scrollHeight,arg:void 0,waitForPageLoad:s.waitForPageLoad,timeout:he,codePath:"computing page height"}),[g,m,h]=await et({root:e,fn:()=>{let f=document.activeElement;if(!f)return[void 0,void 0,void 0];let E=f.getBoundingClientRect();return[f.scrollTop,E.x,E.y]},arg:void 0,waitForPageLoad:s.waitForPageLoad,timeout:he,codePath:"computing active element position"});await e.mouse.wheel((t??d.width)*l,(o??d.height)*u);try{let f=Date.now();for(;Date.now()-f<he;){a?.throwIfAborted();let E=await V(e.evaluate(()=>document.body.scrollHeight),{milliseconds:re}),[S,A,C]=await V(e.evaluate(()=>{let T=document.activeElement;if(!T)return[void 0,void 0,void 0];let I=T.getBoundingClientRect();return[T.scrollTop,I.x,I.y]}),{milliseconds:re});if(E===p&&S===g&&A===m&&C===h)break;p=E,g=S,m=A,h=C,await ee(at)}}catch(f){c.warn({err:f},"Failed to wait for scroll to complete, continuing...")}}}async function Mm(r,e){let t,n;for(let o=0;o<4;o++)try{return t=r.pages(),await Promise.all(t.map(async i=>{let a="";try{a=e?.getTitles?await i.title():""}catch{a="Unknown page"}return{title:a,url:i.url()}}))}catch(i){n=i,await ee(at)}throw new Error(`Failed to get tab titles after all retries: ${n?.message}`)}import{randomUUID as gU}from"crypto";import{cloneDeep as Om}from"lodash-es";function Mn(r,e){let t=r.findIndex(n=>n===e);if(!(t===-1||!r[t+1]))return r[t+1]}import{createHash as sU}from"crypto";var lU="v1";function Im(r,e){if(r.tagName.toLowerCase()==="svg"&&!uU(r))try{let t=HA(r,e),n=cU(JSON.stringify(t));return{version:lU,json:t,hash:n}}catch{return}}function cU(r){return sU("md5").update(r).digest("hex")}function HA(r,e){let t=r.tagName.toLowerCase(),n=dU(r);if(t==="image"&&n["xlink:href"])throw new Error("Image tags within SVGs are not supported");let o={type:t,props:n,children:[]};for(let i of r.childrenBackendIds){let a=e.backendIdToNode[i];if(a&&a.nodeType===1){let s=HA(a,e);s&&o.children.push(s)}}return o}function uU(r){let e=r.computedStyles.display,t=r.computedStyles.visibility,n=r.computedStyles.opacity;return e==="none"||t==="hidden"||n==="0"}function dU(r){let e={},t=r.attributes;for(let n of Object.keys(t))sr.visualAttributesForSvgSerialization.includes(n)&&(e[n]=t[n]);return t.id&&r.tagName.toLowerCase()!=="svg"&&(e.id=t.id),e}var go={r:147,g:196,b:125,a:.55},jA={showRulers:!1,showStyles:!1,showExtensionLines:!1,contrastAlgorithm:"aa",contentColor:go,paddingColor:go,borderColor:go,marginColor:go,eventTargetColor:go,shapeColor:go,shapeMarginColor:go,showInfo:!0,showAccessibilityInfo:!0};function VA({snapshot:r,devicePixelRatio:e,computedStylesToFetch:t,logger:n}){let o=r.strings,i=r.documents,a={},s={},c={roots:[],backendIdToNode:a,frameIndexToIframeNode:s};return i.forEach((l,u)=>{let d=pU({allDocuments:i,stringConstants:o,computedStylesToFetch:t,devicePixelRatio:e,frameIndex:u,backendIdToNode:a,frameIndexToIframeNode:s,logger:n});c.roots.push(d)}),c}function pU({allDocuments:r,stringConstants:e,computedStylesToFetch:t,devicePixelRatio:n,frameIndex:o,frameIndexToIframeNode:i,backendIdToNode:a,logger:s}){let c=r[o],l=c.layout,u={};l.nodeIndex.forEach((R,w)=>{u[R]=w});let d=l.styles,p=l.bounds??[],g=c.nodes,m=g.contentDocumentIndex??{index:[],value:[]},h=g.backendNodeId??[],f=g.attributes??[],E=g.parentIndex??[],S=g.nodeName??[],A=g.nodeType??[],C=g.pseudoType??{index:[],value:[]},T=g.inputChecked??{index:[]},I=e[c.frameId];for(let R=0;R<h.length;R++){let w=h[R],B=A[R],D=f[R]??[],U=E[R]!==void 0&&E[R]>=0?E[R]:void 0,J=U!==void 0?h[U]:void 0,Le=J!==void 0?a[J]:void 0,K=C.index.indexOf(R),G=K!==-1?e[C.value[K]]:void 0,se=u[R],ce;se?ce=p[se]??[]:ce=[];let ke=S[R]!==void 0?e[S[R]]?.toLowerCase():void 0;if(!ke){s.warn({backendNodeId:w,frameId:I,frameIndex:o,nodeBounds:ce},"DOM node has no tag name");continue}let fe={backendNodeId:w,psuedoType:G,nodeType:B,frameIndex:o,parentFrameId:I,ownedFrameId:void 0,bounds:{x:ce[0]??null,y:ce[1]??null,width:ce[2]??null,height:ce[3]??null},computedStyles:{},attributes:{},parentBackendNodeId:J??null,tagName:ke,parent:Le??void 0,childrenBackendIds:[],momenticIgnored:void 0,mPathSelector:void 0};Le&&Le.childrenBackendIds.push(w);let pt=m.index.indexOf(R);if(pt!==-1){let we=m.value[pt];i[we]=fe;let tt=r[we]?.frameId;fe.ownedFrameId=tt!==void 0?e[tt]:void 0}for(let we of Object.keys(fe.bounds)){let tt=we;fe.bounds[tt]!==null&&(fe.bounds[tt]/=n)}let Wt=se!==void 0?d[se]??[]:[];for(let we=0;we<Wt.length&&!(we>=t.length);we++){let tt=Wt[we];if(tt===void 0||isNaN(tt))continue;let $t=e[tt];if($t===void 0)continue;let xo=t[we];fe.computedStyles[xo]=$t}for(let we=0;we<D.length;we+=2){let tt=D[we],$t=D[we+1];if(!tt||!$t)continue;let xo=e[tt],Dn=e[$t];!xo||!Dn||(fe.attributes[xo]=Dn)}T.index.includes(R)&&(fe.attributes.checked="true"),a[fe.backendNodeId]=fe}return a[h[0]]}function Pm(r,e){if(r.mPathSelector)return r.mPathSelector;let t=r.parent,n;if(!t)n=r.tagName;else if(r.tagName==="body")n="body";else{let i=t.childrenBackendIds.filter(c=>e.backendIdToNode[c]?.nodeType===1&&!e.backendIdToNode[c]?.psuedoType).indexOf(r.backendNodeId),a=` > ${r.tagName}:nth-child(${i+1})`;n=`${Pm(t,e)}${a}`}return r.mPathSelector=n,n}function GA(r,e){return r.parentBackendNodeId!==null?e.backendIdToNode[r.parentBackendNodeId]:r.frameIndex===0?void 0:e.frameIndexToIframeNode[r.frameIndex]}var mU=["html","#document","#document-fragment"];function WA({node:r,domGraph:e}){let t=[],n=r,o=GA(r,e);if(!o)return[r.tagName];let i=()=>{if(n=o,o=GA(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++,mU.includes(n.tagName)){i();continue}if(n.tagName==="body")t.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){t.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 t.reverse()}function $A(r,e){let t=r.locator("html"),n=[];for(let o=0;o<e.length;o++){let i=e[o];if(n.push(i),i.startsWith("iframe")){let a=n.join(" > ");n=[],o<e.length-1?t=t.frameLocator(a):t=t.locator(a)}}if(n.length&&(t=t.locator(n.join(" > "))),"owner"in t)throw new Error("Final locator from mpath is a frame locator");return t}async function qA(r,e){await r.send({method:"DOM.getDocument",params:{depth:0},timeout:he});let t=await r.send({method:"DOM.requestNode",params:{objectId:e},timeout:he}),o=(await r.send({method:"DOM.getAttributes",params:{nodeId:t.nodeId},timeout:he})).attributes,i=Mn(o,Xr);if(!i)throw new Error(`Could not find attribute ${Xr} for object ${e}`);return i}var hU=["focusable","keyshortcuts","controls","live","relevant","orientation"],fU=["selected","readonly","modal","required","invalid"],SU=["id","name","role","content"],KA=["absolute","fixed","sticky"],yU=["i"],bU=["path"],EU=["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"],JA=["ariaHiddenElement","ariaHiddenSubtree","hiddenByChildTree","inertElement","inertSubtree","notRendered","notVisible"],ZA=["activeAriaModalDialog","activeFullscreenElement","activeModalDialog"],TU=["menulistpopup","statictext","inlinetextbox"],vU=80,YA=100,QA=50,km=["StaticText","ListMarker","RootWebArea","LineBreak","emphasis","::before","::after"],AU=["cite"],wU={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"]},RU={name:!0,value:!0,title:!0,alt:!0,placeholder:!0,checked:!0,selected:!0,contenteditable:!0},XA={indentLevel:0},Lm=class r{id;role;name;nameSources;tagName;content;properties;internalProperties;ignoredReasons;dataMomenticId;importantProperties;pathFromRoot;mPathSelector;parent;children;parentFrame;domNode;backendNodeId;ignoredByCDP;flagNotActionableNodes;constructor(e){if(this.id=e.id,this.role=e.role,this.name=e.name,this.nameSources=e.nameSources,this.content=e.content,this.properties={},this.pathFromRoot=e.pathFromRoot,this.children=e.children,this.backendNodeId=e.backendNodeID,this.ignoredByCDP=e.ignoredByCDP,this.internalProperties=e.internalProperties??{},this.parentFrame=e.parentFrame,this.ignoredReasons=e.ignoredReasons,this.importantProperties=e.importantProperties,this.flagNotActionableNodes=e.flagNotActionableNodes,e.properties&&e.properties.forEach(t=>{t.name==="keyshortcuts"?this.dataMomenticId=parseInt(t.value.value):this.properties[t.name]=t.value.value}),e.domNode){this.domNode=e.domNode,this.tagName=e.domNode.tagName||void 0;let t=e.domNode.attributes.id;this.name=this.name||e.domNode.attributes.name||(t&&t.length<QA?t:""),this.role=this.role||(e.domNode.attributes.role??""),MU(this.properties,e.domNode,e.importantProperties)}PU(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&&bU.includes(this.domNode.tagName)||this.domNode?.computedStyles.display==="contents"||this.ignoredReasons.some(n=>ZA.includes(n)))return!1;if(e){if(Object.keys(this.domNode?.attributes??{}).some(o=>ow(o,e)))return!0;let n=this.domNode?.attributes.class?.split(" ");if(n&&n.length>0&&n.some(o=>iw(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&&yU.includes(this.domNode.tagName)||EU.includes(this.role.toLowerCase())||this.role.toLowerCase()==="inlinetextbox"&&this.tagName||!this.properties.hidden&&(this.properties.focusable||this.properties.settable)||sr.alwaysInterestingTruthyPropertyNames.some(n=>!!this.properties[n]))return!0;let t=this.properties.class;return typeof t=="string"&&t.split(" ").some(n=>nw(n))?!0:this.children.every(n=>n.role==="StaticText")&&this.internalProperties?.inCodeMirrorEditor?!1:this.children.some(n=>n.role==="StaticText")||this.children.length>1&&this.children.some(n=>n.tagName==="input")?!0:this.domNode&&(this.domNode.bounds.x===null||this.domNode.bounds.y===null||!this.domNode.bounds.width||!this.domNode.bounds.height)?!1:!!this.name.trim()||!!this.content||Object.keys(this.properties).some(n=>n.startsWith("data"))}shouldSerializeBounds(){let e=this.domNode?.computedStyles.position;return!!(e&&(e==="absolute"||e==="fixed"||e==="sticky"))}isNotActionable(){return!!(this.domNode?.computedStyles.display==="contents"||this.domNode&&(this.domNode.bounds.x===null||this.domNode.bounds.y===null||!this.domNode.bounds.width||!this.domNode.bounds.height))}serialize(e=XA){let t=Object.assign({},XA,e),{indentLevel:n,noChildren:o,noProperties:i,noId:a,noContent:s,condensedMode:c}=t,l=Om(this.properties),u=" ".repeat(n),d=this.role||"",p=this.tagName??"unknown",g=this.name;d==="heading"&&g==="heading"&&(g=""),this.nameSources?.find(T=>!T.superseded&&T.type==="contents")&&this.children.length>0&&(g="");let h=this.nameSources?.find(T=>!T.superseded);if(h&&!h.nativeSource&&h.type==="relatedElement"){let T=h.attributeValue?.relatedNodes??[];T.length===1&&T[0].text&&T[0].text===g&&(g="")}let f=km.includes(this.role)||AU.includes(this.tagName||"");if(this.role==="StaticText"||this.role==="ListMarker")return`${u}${g}
|
|
4009
|
-
`;let
|
|
4010
|
-
`;else{let T="";for(let
|
|
4011
|
-
`)?
|
|
4012
|
-
`:
|
|
4014
|
+
`};var ar={bannedClassSubstrings:["relative","flex","center","justify","auto","sticky","absolute","top","right","left","bottom","items-center","notion-selectable","notion-page-block","notion-collection-item","MuiSvgIcon","css-","rt-"],nonDynamicInputTypes:["button","file","hidden","image","radio","reset","submit"],generalStateAttributes:["aria-expanded","aria-haspopup","aria-checked","aria-pressed","aria-selected","aria-invalid","checked","open","aria-busy"],bannedElementTagNames:["html","head","meta","script","style","path","br","::marker","noscript","polygon","defs"],bannedElementAttributes:["data-momentic-id","aria-keyshortcuts","data-ved","aria-controls","d"],relevantElementAttributes:["name","id","value","type","class","height","width","target","title","href","src","alt","role","headers","scope","checked","required","action","tooltip","min","max","minlength","maxlength","multiple","pattern","placeholder","accept","contenteditable","data-value","data-testid","data-cy","data-pw","data-test-id","data-test","data-role","data-type","data-key","data-action","data-qa","data-aria-hidden","data-hidden","data-automation-id","data-overlay","data-content-editable-leaf","data-wf-icon","data-tns","data-sticky-stack-name","data-popup-origin","data-handleid","data-handlepos","data-col-index","data-row-index","data-row","data-index","data-col","col-index","row-index","row","col","data-momentic-description","aria-label","aria-role","aria-selected","aria-disabled","aria-hidden","aria-describedby","aria-labelledby","aria-valuenow","aria-valuemin","aria-valuemax"],alwaysUsefulAttributesForCssSelectorGeneration:["src","href","aria-describedby","aria-labelledby","aria-label"],stronglyIdentifyingAttributes:["data-test-id","data-testid","id","name","href","aria-describedby","aria-labelledby","aria-description","data-row","data-col","data-index","data-row-index","data-col-index","for","title","alt","aria-label","aria-modal"],alwaysInterestingClassNames:["cm-line","cm-activeLine","cm-content"],alwaysInterestingClassPrefixes:["notion-",".w-"],alwaysInterestingTruthyPropertyNames:["contenteditable"],visualAttributesForSvgSerialization:["fill","stroke","color","patternContentUnits","xlink:href","transform","path","d","points","viewBox","preserveAspectRatio","r","rx","ry","cx","cy","x1","y1","x2","y2","font","text-anchor","dominant-baseline","gradient","pattern","stop-color"],bannedAiRequiredCacheAttributes:["id","data-momentic-id","href","name","x","y","width","height","data-momentic-id","aria-keyshortcuts","data-ved","aria-controls","d"],ineligibleElementAttribute:"momentic-ineligible"};var Fv="BoundingBoxMovedError",Bv="ZeroOpacityError",ic="visual_actions",Vr="data-momentic-id";function zv(r,e,t){if(r.length<t)return r;let n=r.indexOf(e);if(n===-1)return r;let o=Math.max(0,n-t/3),i=Math.min(n+t/3,r.length),a=r.indexOf(`
|
|
4015
|
+
`,o);a>0&&a<n&&(o=a);let l=i,c=0;for(;c<1e3&&l>n&&r[l]!==`
|
|
4016
|
+
`;)c++,l--;return l>n&&r[l]===`
|
|
4017
|
+
`&&(i=l),r.slice(o,i)}function hr(r){let e=typeof r=="string"?r:r.toString();return`[${Vr}="${e}"]`}import{execSync as Zk}from"child_process";import{randomUUID as Rm}from"crypto";import{diff as Cm}from"deep-object-diff";import{existsSync as fc,readFileSync as Qk,readdirSync as eU,statSync as XA,writeFileSync as tU}from"fs";import{Jimp as JA}from"jimp";import rU from"js-beautify";import{cloneDeep as oi}from"lodash-es";import nU from"mime";import{platform as oU}from"os";import{basename as iU,extname as aU,join as sU}from"path";import{v4 as lU}from"uuid";import{rmSync as EA}from"fs";import{basename as ak,join as sk}from"path";import{errors as lk}from"playwright-core";import{devices as S0}from"playwright-core";var Hv=2,Hp=8e3;var ei=250,it=500;var Gv=5e3,Vv=250,J=3e3,me=2e3,Z=1e3,Gp=3e4,Vp=8e3,jv=10,jp=.05;var Wv=6e4,$v=new Set(["about:blank","chrome-error://chromewebdata/"]);var Wp=["button","image","generic","graphics-symbol","tab","link","menuitem","group"],$p=1e4,Na=500,ac=S0["Desktop Chrome"].userAgent,ti=process.env.TWO_CAPTCHA_KEY;import{mkdirSync as y0,rmSync as qv,statSync as b0}from"fs";import*as Xp from"node:fs";import E0 from"nodejs-file-downloader";import{tmpdir as T0}from"os";import yn,{basename as v0,dirname as A0}from"path";var Jp="file://",Yp=yn.join(T0(),"momentic","downloads"),Kp=1e4,w0=50*1024*1024;async function Kv(r){let{uri:e}=r;if(e.startsWith(Jp))return C0(r);if(e.startsWith("http"))return M0(r);if(ES)return x0(r);throw new w("UserConfigurationError","The source URI for the file upload step must be a valid URL or a previously downloaded file beginning with 'file://'")}function R0(r,e){let t=yn.join(Yp,r,e.slice(Jp.length)),n=yn.join(Yp,r),o=t.startsWith(n);if(!Xp.existsSync(t)||!o)throw new w("UserConfigurationError",`The referenced file (${e}) does not exist. Please make sure that it has been downloaded successfully.`);return t}async function C0({uri:r,orgId:e}){let t=R0(e,r);return{filePath:t,cleanup:()=>{qv(A0(t),{recursive:!0,force:!0})}}}async function x0({uri:r}){let e=yn.resolve(r);if(!Xp.existsSync(e))throw new w("UserConfigurationError",`The referenced file (${r}) does not exist on disk. Please make sure that it has been downloaded successfully.`);return{filePath:e,cleanup:()=>{}}}async function M0({uri:r,logger:e,orgId:t}){let n=new URL(r);n.search&&(n.search="");let o=v0(n.href),i=Qp(o),a=yn.extname(i);if(gS.includes(a))throw new Error(`Downloading files with extension ${a} is not allowed.`);let l=Zp(t),c,s;for(let g=1;g<=3;g++){let h=new E0({url:r,fileName:i,directory:l,maxAttempts:1,headers:{"User-Agent":"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/93.0.4577.82 Safari/537.36"},timeout:Kp});try{let{downloadStatus:f,filePath:b}=await B(h.download(),{milliseconds:Kp,message:`Download timed out after ${Kp}ms`});if(f!=="COMPLETE"||!b)throw new Error(`Download ended in non-success status: ${f}`);c=b;break}catch(f){s=f}}if(!c)throw new Error(`Download failed after 3 attempts. Last error: ${s instanceof Error?s.message:s}`);let u=c,p=b0(u).size;if(p>w0)throw new Error("File size exceeds the maximum limit of 50MB");e.info({fileSizeInBytes:p,filePath:u,fileName:i},"Downloaded file to disk");let m;return{filePath:u,cleanup:()=>{clearTimeout(m),m=setTimeout(()=>qv(l,{recursive:!0,force:!0}),10*60*1e3)}}}function Yv(r,e){return`${Jp}${r}/${e}`}function Zp(r){let e=Math.random().toString(36).substring(4),t=yn.join(Yp,r,e);return y0(t,{recursive:!0}),t}function Qp(r){let e=yn.extname(r),t=yn.basename(r,e);return r=(t.length>100?t.slice(t.length-100):t)+e,r=r.trim().replaceAll(" ","_"),r}async function jr(r,e){try{return await r.evaluate(n=>window.serializeElementOnlyWithText?.(n,{truncateToLength:500}),void 0,{timeout:Z})}catch(t){e.debug({err:t},"Failed to get HTML from locator for Playwright error translation");return}}var bn=3.1783027;function _0(r){let e=0;for(let t=0;t<r.length;t++){let n=r.charCodeAt(t);!(n>=48&&n<=57)&&!(n>=65&&n<=90)&&!(n>=97&&n<=122)&&e++}return e}function Pr(r){return Math.ceil(em(r)/bn)}function em(r){let e=0;if(typeof r=="string"){let t=r;t=t.replaceAll(`
|
|
4018
|
+
`,""),t=t.replaceAll(" ","");let n=_0(t);return t.length-n+bn*n}if(typeof r>"u"||r===null)return 0;if(typeof r=="number")return String(r).length;if(Array.isArray(r))return r.forEach(t=>{e+=em(t)}),e;if(typeof r=="object"){let t=r;return Object.keys(t).forEach(n=>{e+=String(n).length,n==="image_url"?(t[n]??{}).detail==="high"?e+=1105*bn:e+=85*bn:n==="source"&&typeof t[n]=="object"&&t[n]?.type==="base64"?e+=1600*bn:e+=em(t[n])}),e}if(typeof r=="boolean")return r?4:5;throw new Error(`Unsupported type passed to token length calculator '${typeof r}': ${r}`)}var sc=class{limit;windowMs;userActions;constructor(e,t){this.limit=e,this.windowMs=t,this.userActions=new Map}_cleanup(e,t="DEFAULT_USER"){let n=Date.now(),o=`${t}:${e}`;if(this.userActions.has(o)){let a=this.userActions.get(o)?.filter(l=>n-l<=this.windowMs)??[];a.length>0?this.userActions.set(o,a):this.userActions.delete(o)}}increment(e,t="DEFAULT_USER"){let n=Date.now(),o=`${t}:${e}`;this._cleanup(t,e),this.userActions.has(o)||this.userActions.set(o,[]);let i=this.userActions.get(o);return i.length>=this.limit?!0:(i.push(n),!1)}};async function Xv(r,e){let t=r.evaluate(async()=>{let i=window,a={};try{let l=await indexedDB.databases();for(let c of l){if(!c.name)continue;let s=await i.exportIdbToObject?.(c.name,c.version);s&&(a[c.name]=s)}return[a,void 0]}catch(l){return[void 0,l.message]}}),[n,o]=await B(t,{milliseconds:J});return o&&e.warn({err:o},"Failed to fetch indexedDB data"),n}async function Jv(r,e,t){if(e){t.debug("Importing indexedDB data");try{let n=r.evaluate(async o=>{let i=window;for(let[a,l]of Object.entries(o))await i.importObjectToIdb?.(a,l)},e);await B(n,{milliseconds:J})}catch(n){t.warn({err:n},"Failed to import indexedDB data")}}}async function Zv(r,e){try{let t=r.evaluate(async()=>{window.localStorage.clear(),window.sessionStorage.clear(),await indexedDB.databases().then(n=>{n.forEach(o=>{o.name&&indexedDB.deleteDatabase(o.name)})})});await B(t,{milliseconds:J})}catch(t){e.debug({err:t},"Failed clearing index db data, continuing...")}}async function Qv(r,e,t,n,o){try{await I0(r,e,t,n)}catch(i){o.error({err:i,tabIndex:e},"Error handling new console log")}}async function I0(r,e,t,n){let o=n.text();o.length>Na&&(o=o.slice(0,Na)+"...(TRUNCATED)");let i=[];for(let a of n.args())try{let l=await a.jsonValue(),c=JSON.stringify(l);c.length>Na?i.push(c.slice(0,Na)+"...(TRUNCATED)"):(typeof l!="object"||Object.keys(l).length>0)&&i.push(l)}catch{}tm(r,t,e,{url:r.url(),location:n.location(),type:n.type(),text:n.text(),args:i})}function tm(r,e,t,n){let o=Date.now(),i=e.logsPerPage;if(i.length<=t||i[t]===void 0){i[t]=[];for(let a=0;a<t;a++)i[a]===void 0&&(i[a]=[])}i[t].length>$p&&(i[t]=i[t].slice(Math.floor($p/2)),i[t]?.push({url:r.url(),timestamp:o,type:"warning",text:"[MOMENTIC] Truncated console logs due to buffer overflow",tabIndex:t})),i[t].push({...n,tabIndex:t,timestamp:o})}async function sr({fn:r,codePath:e,logObject:t,signal:n,logger:o}){n?.throwIfAborted();let i=Date.now(),a=await Fp({promiseGenerator:r,signal:n,codePath:e,logger:o}),l=Date.now();return t[e]=l-i,a}import P0 from"truncate-json";var O0="[redacted due to size]",eA=5e3,L0=5e3;async function rA(r,e,t){let n=new Date().toISOString();e.harPages||(e.harPages={}),e.harPages[r]={id:r,startedDateTime:n,title:void 0,pageTimings:{}}}async function rm(r,e){let t=e.timing(),n=new URL(e.url()),o=[...n.searchParams.entries()].map(([l,c])=>({name:l,value:c})),i={...await oA(e),url:n.toString(),method:e.method(),queryString:o,postData:await D0(e)};return{pageref:r,_resourceType:e.resourceType(),startedDateTime:new Date().toISOString(),request:i,timings:iA(t).timings}}async function nA(r,e,t){await t.finished();let n={};try{n=await B0(t)}catch{}let o={...await oA(t),status:t.status(),statusText:t.statusText(),content:n,redirectURL:t.headers().location,_mocked:!1};r.response=o;let i;try{i=await e.sizes(),r.request.bodySize=i.requestBodySize,r.request.headersSize=i.requestHeadersSize}catch{}r.response&&i&&(r.response.bodySize=i.responseBodySize,r.response.headersSize=i.responseHeadersSize,r.response.content.size=i.responseBodySize);let a=e.timing();r.startedDateTime=new Date(a.startTime).toISOString();let{timings:l,total:c}=iA(a);r.time=c,r.timings=l}function Da(r,e,t){r.harEntries||(r.harEntries={}),r.harEntries[t]=e}function tA(r){try{return new Date(r).toISOString()}catch{return}}function N0(r){let e={name:"",value:""},t=!0;for(let n of r.split(/; */)){let o=n.indexOf("="),i=o!==-1?n.substring(0,o).trim():n.trim(),a=o!==-1?n.substring(o+1,n.length).trim():"";if(t){t=!1,e.name=Or(i),e.value=Or(a);continue}i==="Domain"&&(e.domain=Or(a)),i==="Expires"&&(e.expires=tA(a)),i==="HttpOnly"&&(e.httpOnly=!0),i==="Max-Age"&&(e.expires=tA(Date.now()+ +a*1e3)),i==="Path"&&(e.path=Or(a)),i==="Secure"&&(e.secure=!0)}return e}async function oA(r){let e=await r.allHeaders(),t=e.cookie?.split(";").map(N0)??[];return{headers:Object.entries(e).map(([n,o])=>({name:Or(n),value:Or(o)})),cookies:t}}async function D0(r){let e=r.postData();if(!e)return;let t=await r.headerValue("content-type"),n={mimeType:t??"application/octet-stream",text:Or(e),params:[]};if(t==="application/x-www-form-urlencoded"){let o=new URLSearchParams(e.toString());for(let[i,a]of o.entries())n.params.push({name:Or(i),value:a?Or(a):void 0})}return n}var k0=["text"],U0=["json","xml","html","javascript"];function F0(r){let[e,t]=r.split("/");return e?k0.includes(e)?!0:t?!!U0.some(n=>t?.includes(n)):!1:!1}async function B0(r){let t=((await r.headerValue("content-type"))?.toLowerCase()??void 0)?.split(";")[0]??void 0,n={mimeType:t,encoding:await r.headerValue("content-encoding")??void 0};return t&&F0(t)&&(n.text=Or(await r.text())),n}function Or(r){try{let e=JSON.parse(r),{jsonString:t}=P0(r,L0);return t}catch{return r.length>eA?r.slice(0,eA)+O0:r}}function eo(r){return r<0?0:r}function iA(r){return{timings:{blocked:eo(r.domainLookupStart),dns:eo(r.domainLookupEnd-r.domainLookupStart),connect:eo(r.connectEnd-r.connectStart),send:eo(r.responseStart-r.requestStart),wait:0,receive:eo(r.responseEnd-r.responseStart),ssl:eo(r.connectEnd-r.secureConnectionStart)},total:eo(r.responseEnd)}}function aA(){return async r=>{let{fragment:e,code:t,context:n}=r,{env:o}=n||{},i=Object.getPrototypeOf(async function(){}).constructor;return{result:await Promise.resolve(new i("env",e?`return ${t}`:t)(o))}}}async function Qe({root:r,fn:e,arg:t,timeout:n,waitForPageLoad:o,codePath:i}){return await o(),await B(r.evaluate(e,t),{milliseconds:n,message:`Timed out ${i} after ${n}ms. This indicates that either the page is unresponsive or your machine is severely resource constrained.`})}function nm(){return window.lastCursorPos}import{errors as z0}from"playwright-core";async function to({func:r,action:e,logger:t,callbacks:n,retryTimeoutMs:o,targetingResult:i}){let a=Date.now(),l;for(;Date.now()-a<o;)try{return await r(i)}catch(c){if(c instanceof z0.TimeoutError)t.warn({err:c,rootUrl:(await n.state.getRoot()).url()},`Encountered Playwright error while performing ${e}`),l=await H0(c,i.locator,n,t);else throw c}throw l instanceof w?l:new w("ActionFailureError",`Failed to interact with targeted element. Error: ${l.message}`,{errOptions:{cause:l}})}async function H0(r,e,t,n){return r.message.includes("attempt #")?G0(r,e,t,n):V0(r)}async function G0(r,e,t,n){let o=r.message.split(/- retrying \w+ action, attempt #\d+/).filter(c=>c.length>0);if(!o.length)return n.warn({err:r},"Failed to parse Playwright error message for translation, returning raw message"),r;let i=o.length>2?o[o.length-2]:o[0];i=i.replace(/[\u001b\u009b][[()#;?]*(?:[0-9]{1,4}(?:;[0-9]{0,4})*)?[0-9A-ORZcf-nqry=><]/g,"").replaceAll(" - ","").trim().replaceAll(`
|
|
4019
|
+
`,";").replace(/\s+/g," ");let a="",l=await jr(e,n);if(l&&(a=`Target element HTML: ${_t(l,100,!0)}`),i.includes("element is not enabled"))return new w("ActionFailureError",`The element you attempted to interact with was disabled for the entire timeout duration. Please explicitly wait for the element to be enabled, change the element description to target an interactive element, or turn on the 'disable stability checks' option. ${a}`,{errOptions:{cause:r}});if(i.includes("intercepts pointer events")){let c="",s=i.match(/<.*?data-momentic-id="(\d+)".*?intercepts pointer events/)?.[1];if(s){let u=(await t.state.getRoot()).locator(hr(s)),d=await jr(u,n);d&&(c=`Covering element HTML: ${_t(d,100,!0)}`)}return new w("ActionFailureError",`The element you attempted to interact with was covered by another element such as dropdown, popup, or dialog for the entire timeout duration. Please add a step to hide the covering element or turn on the 'disable stability checks' option. ${a}
|
|
4020
|
+
${c}`,{errOptions:{cause:r}})}if(i.includes("element is not visible")){let c="The element you attempted to interact with has no bounding box or is explicitly hidden.";try{let s=await e.boundingBox({timeout:J});s?s.height===0?c="The element you attempted to interact with has zero height.":s.width===0&&(c="The element you attempted to interact with has zero width."):c="The element you attempted to interact with has no bounding box."}catch{}return new w("ActionFailureError",`${c} Please explicitly wait for the element to be visible or turn on the 'disable stability checks' option. ${a}`,{errOptions:{cause:r}})}return i.includes("element is outside of the viewport")?new w("ActionFailureError",`The element requested was outside of the browser viewport for the entire duration of the action. Please ensure you are not using non-standard zoom settings and the element is visible on the page. ${a}`):r}function V0(r){let e=r.message;if(e.includes("waiting for locator")&&e.includes("data-momentic-id")&&!e.match(/attempting \w+ action/)&&!e.includes("locator.evaluate"))throw new w("ActionFailureError",`Interacting with the element timed out. This is usually caused by the web page itself performing too many CPU-intensive operations or a lack of resources on your machine. Error: ${e}`,{errOptions:{cause:r}});return r}import{existsSync as Ua,mkdirSync as cm,readdirSync as X0,rmSync as dA}from"fs";import{homedir as dm}from"os";import{join as Wr,resolve as J0}from"path";import{chromium as pA}from"playwright-core";import{addExtra as Z0}from"playwright-extra";import Q0 from"puppeteer-extra-plugin-recaptcha";function sA(r,e){return async(t,n)=>{try{let o=await n.allHeaders();for(let{key:i,value:a,matcher:l}of r)(!l||l.matches({url:n.url(),method:n.method()}))&&(o[i]=a);await t.fallback({headers:o})}catch(o){e.warn({err:o},"Failed to apply custom headers to request, continuing")}}}import{randomUUID as W0}from"crypto";function lA(r,e){for(let t of Object.values(e))if(t.matcher.matches({url:r.url(),method:r.method()}))return t}async function cA(r){let{route:e,mock:t,entry:n,debugData:o,requestId:i,requestRecorders:a,logger:l}=r,c={url:n.request.url,options:{method:n.request.method,headers:n.request.headers.map(m=>[m.name,m.value]),body:n.request.postData?.text}},s;if(t.fetchOriginalResponse){let m=await e.fetch();s={body:await m.text(),options:{status:m.status(),statusText:m.statusText(),headers:Object.entries(await m.headers())}}}let u=await j0(t,c,s),d={};u.headers.forEach((m,g)=>{d[g]=m});let p={body:await u.text(),contentType:u.headers.get("content-type")||"text/plain",headers:d,status:u.status};await e.fulfill(p);try{n.response={status:p.status,statusText:u.statusText,headers:Object.entries(p.headers).map(([m,g])=>({name:m,value:g})),cookies:[],content:{mimeType:p.contentType,text:p.body},_mocked:!0},Da(o,n,i);for(let m of Object.values(a))m.onRequestComplete(i,n)}catch(m){m.message.includes("has been closed")||l.warn({err:m},"Failed to add response to HAR")}}async function j0(r,e,t){try{return await r.generateResponse(e,t)}catch(n){let o=n instanceof Error?n.message:`${n}`;return new Response(o,{status:500,headers:{"Content-Type":"text/plain"}})}}async function om(r){try{await $0(r)}catch(e){r.logger.warn({err:e},"Error handling intercepted request, continuing...")}}async function $0(r){let{pageId:e,route:t,request:n,debugData:o,logger:i,requestRecorders:a,mocks:l}=r,c=W0(),s=await rm(e,n);try{Da(o,s,c);for(let d of Object.values(a))d.onRequestStart(c,s)}catch(d){i.warn({err:d},"Failed to add request to HAR")}let u=lA(n,l);u?await cA({logger:i,route:t,mock:u,entry:s,debugData:o,requestId:c,requestRecorders:a}):await q0({route:t,request:n,debugData:o,logger:i,requestRecorders:a,entry:s,requestId:c})}async function q0({route:r,request:e,debugData:t,logger:n,requestRecorders:o,entry:i,requestId:a}){await r.continue();try{let l=await e.response();if(!l||!i)return;await nA(i,e,l),Da(t,i,a);for(let c of Object.values(o))c.onRequestComplete(a,i)}catch(l){l.message.includes("has been closed")||n.warn({err:l},"Failed to add response to HAR")}}async function K0(r){let e=r.postData();if(e){if((await r.headerValue("content-type"))?.includes("json"))try{return{json:r.postDataJSON()}}catch{return{}}else if((await r.headerValue("content-type"))?.includes("text"))return{text:e}}return{}}async function Y0(r){let e=await r.text();if(e){if((await r.headerValue("content-type"))?.includes("json"))try{return{json:await r.json()}}catch{return{}}else if((await r.headerValue("content-type"))?.includes("text"))return{text:e}}return{}}function lc(r){return{request:{url:r.request.url,method:r.request.method,headers:r.request.headers.reduce((e,t)=>({...e,[t.name]:t.value}),{}),...r.request.postData?r.request.postData.mimeType.includes("json")?{json:JSON.parse(r.request.postData.text)}:{text:r.request.postData.text}:{}},response:r.response?{status:r.response.status,headers:r.response.headers.reduce((e,t)=>({...e,[t.name]:t.value}),{}),...r.response.content?r.response.content.mimeType?.includes("json")&&r.response.content.text?{json:JSON.parse(r.response.content.text)}:{text:r.response.content.text}:{}}:void 0}}async function im(r){let e=r.request(),t=r.status(),n=r.headers(),o=await Y0(r);return{request:{url:e.url(),method:e.method(),headers:e.headers(),...await K0(e)},response:{status:t,headers:n,...o},status:t,headers:n,...o}}var En=class{requestMatcher;constructor(e){this.requestMatcher=e}matches(e){let{url:t,method:n}=e;return this.requestMatcher.method&&this.requestMatcher.method.toLowerCase()!==n.toLowerCase()?!1:rc(t,this.requestMatcher.urlMatcher)}};function ka(r){let e=new URL(r.request().url());return/^127\./.test(e.hostname)||/^192\.168\./.test(e.hostname)||/^10\./.test(e.hostname)||/^172\.(1[6-9]|2\d|3[0-1])\./.test(e.hostname)||e.hostname==="localhost"?r.abort():r.fallback()}import{homedir as am,platform as sm}from"os";import{join as lm}from"path";function cc(){let r=[];if(sm()==="linux"){let e=am();["chromium","google-chrome","chrome-canary"].forEach(t=>{r.push(lm(e,".config",t,"Crash Reports"))})}else if(sm()==="darwin"){let e=am();["Chromium","Google","Chrome for Testing"].forEach(t=>{r.push(lm(e,"Library","Application Support",t,"Crashpad"))})}else if(sm()==="win32"){let e=am();["Chromium","Google","Google Chrome Canary"].forEach(t=>{r.push(lm(e,"AppData","Local",t,"User Data","Crashpad","reports"))})}return r}function uA(){return{name:"fs_optout",value:"1",domain:".fullstory.com",path:"/",expires:Date.now()/1e3+365*24*60*60,httpOnly:!1,secure:!0,sameSite:"None"}}var um=Wr(dm(),"momentic","chromium"),ek=Wr(dm(),"video"),mA=Z0(pA);mA.use(Q0({provider:{id:"2captcha",token:ti},visualFeedback:!0}));var tk=["--enable-crashpad","--crash-on-hang-threads=UI:18,IO:18"],rk=["--disable-dev-shm-usage","--no-first-run","--renderer-process-limit=3","--browser-test","--disable-site-isolation-for-policy","--disable-site-isolation-trials","--disable-backgrounding-occluded-windows","--disable-background-timer-throttling","--disable-renderer-backgrounding","--autoplay-policy=user-gesture-required","--disable-add-to-shelf","--disable-desktop-notifications","--use-fake-device-for-media-stream","--use-fake-ui-for-media-stream","--enable-logging=stderr","--log-level=2"],nk=["--disable-3d-apis","--disable-gpu","--disable-software-rasterizer","--disable-accelerated-2d-canvas","--disable-accelerated-mjpeg-decode","--disable-accelerated-video-decode","--disable-accelerated-video-encode","--disable-gl-drawing-for-tests","--disable-webgl","--disable-webgl2","--disable-audio-input","--disable-audio-output"];async function gA({baseUrl:r,logger:e,storage:t,enricher:n,userBrowserSettings:o,contextArgs:i,recordVideo:a,iconKnowledgeBase:l,callbacks:c}){process.env.PW_TEST_SCREENSHOT_NO_FONTS_READY="1";let s;switch(o.browserType){case"Google Chrome":s="chrome";break;case"Chrome for Testing":s=void 0;break;case"Chromium":s="chromium";break;default:s="chromium";break}let u=[...rk],d={headless:process.env.MOMENTIC_HEADFUL_BROWSER!=="true",handleSIGTERM:!1,chromiumSandbox:!1,channel:s},p={...i??{},geolocation:i?.geolocation||uf,locale:i?.locale||lf,timezoneId:i?.timezoneId||cf,colorScheme:i?.colorScheme,httpCredentials:o.basicAuthorization?{username:o.basicAuthorization.username??"",password:o.basicAuthorization.password??""}:void 0,javaScriptEnabled:o.disableJavaScript?!1:void 0,ignoreHTTPSErrors:o.ignoreHttpsErrors??!1,userAgent:o.userAgent??ac,viewport:i?.viewport??tn,serviceWorkers:"block",storageState:{cookies:[uA()],origins:[]}};o.initialLocalStorage&&(p.storageState.origins=Object.entries(o.initialLocalStorage).map(([E,v])=>({origin:E,localStorage:Object.entries(v).map(([R,T])=>({name:R,value:T}))}))),process.env.MOMENTIC_CHROME_EXTRA_ARGS&&u.push(...process.env.MOMENTIC_CHROME_EXTRA_ARGS.split(","));let m=null,g,h,f={systemDevicePixelRatio:i?.deviceScaleFactor,recordVideo:a,isNewHeadless:!1};(s==="chrome"||s==="chromium")&&(f.isNewHeadless=!0,d.headless&&u.push("--headless=new")),process.env.BROWSER_MEMORY_MB&&u.push(`--js-flags=--max_old_space_size=${process.env.BROWSER_MEMORY_MB}`);try{let E=cc();E.forEach(v=>{if(!Ua(v))return;["new","pending","completed"].forEach(T=>{let _=Wr(v,T);if(!Ua(_))return;let M=X0(_);for(let z=0;z<M.length;z++){let Y=Wr(_,M[z]);dA(Y,{force:!0})}})}),E.forEach(v=>{Ua(v)||cm(v,{recursive:!0});let R=Wr(v,`write-test-${Date.now()}`);cm(R,{recursive:!0}),dA(R,{recursive:!0,force:!0})}),u.push(...tk)}catch(E){e.warn({err:E},"Could not create Chrome crash report directory, not enabling crashpad")}o.disableGpu&&u.push(...nk);let b=o.localChromeExtensionPaths?.map(E=>E.startsWith("~")?Wr(dm(),E.slice(1)):E);if(b?.length){if(s===void 0)throw new w("UserConfigurationError","Chrome extensions are only supported on Chromium and Google Chrome.");for(let T of b){let _=Wr(T,"manifest.json");if(!Ua(_))throw new w("UserConfigurationError",`Chrome extension path ${_} does not exist.`)}if(cn)throw new w("UserConfigurationError","Cannot use persistent browser context on Momentic Cloud");let E=Wr(um,`momentic-session-${Date.now()}`);if(!Ua(E))try{cm(E,{recursive:!0})}catch(T){throw new w("UserConfigurationError",`Failed to create browser cache directory. Please make sure you have sufficient permissions to create the ${um} folder: ${T}`)}let v=[...u],R=b.map(T=>J0(T)).join(",");v.push(`--disable-extensions-except=${R}`),p?.deviceScaleFactor&&v.push(`--force-device-scale-factor=${p.deviceScaleFactor}`,`--device-scale-factor=${p.deviceScaleFactor}`),p.viewport&&v.push(`--window-size=${p.viewport.width},${p.viewport.height}`),g=await pA.launchPersistentContext(Wr(um,`momentic-session-${Date.now()}`),{...d,...p,ignoreDefaultArgs:["--disable-extensions","--disable-component-extensions-with-background-pages"],args:v,baseURL:r}),e.info({sharedContextOptions:p,sharedBrowserOptions:d,userBrowserSettings:o,chromeArgs:v,properties:f,baseUrl:r},"Browser initialization context args (persistent)"),h=g.pages()[0]}else{m=await mA.launch({...d,args:u});let E={...p,baseURL:r,recordVideo:a?{dir:ek}:void 0};g=await m.newContext(E),e.info({contextArgs:E,sharedBrowserOptions:d,chromeArgs:u,userBrowserSettings:o,properties:f,baseUrl:r},"Browser initialization context args (standard)"),h=await g.newPage()}return cn&&await g.route("**",ka),{browser:m,context:g,page:h,baseUrl:r,logger:e,storage:t,enricher:n,userBrowserSettings:o,viewport:p.viewport||tn,properties:f,clientCallbacks:c,iconKnowledgeBase:l}}async function hA(r){try{return await ok(r)}catch(e){r.logger.warn({err:e},"Failed to transform locator for Chakra click, continuing...");return}}async function ok({locator:r,logger:e}){let[t,n]=await r.evaluate(c=>[c.id,c.tagName.toLowerCase()],{timeout:Z}),o=await jr(r,e),i=await r.boundingBox({timeout:Z});if(i===null){e.warn({elementDisplayString:o},"Attempting to click on element with no bounding box, not performing Chakra redirection");return}if(i.width>5||i.height>5||n!=="input")return;if(t)try{let c=r.page().locator(`label[for=${JSON.stringify(t)}]`);return await c.waitFor({state:"visible",timeout:Z}),{locator:c,relativePoint:void 0}}catch{}let a=await r.evaluate(c=>{let s=window,u=c.parentElement;if(!u)return{type:"error",error:"Input click target has no parent for redirection"};let d=c.getBoundingClientRect(),p=u.getBoundingClientRect();if(p.width===0||p.height===0)return{type:"error",error:"Parent element has no width or height"};let m={x:Math.min(Math.max(1,d.left-p.left),p.width-1),y:Math.min(Math.max(1,d.top-p.top),p.height-1)},g=s._MOMENTIC_FEATURE_FLAGS?.[ic],h=c.getAttribute(Vr),f=!g&&h?hr(h):s.getMPath?.(c)?.join(" >");return f?{type:"result",selector:f,relativePoint:m,serializedForm:u.outerHTML.slice(0,500)}:{type:"error",error:"Could not generate selector for parent element"}},{timeout:Z});if(a.type==="error")throw new Error(a.error);let l=r.page().locator(a.selector);return await l.waitFor({state:"visible",timeout:Z}),e.info({parentElementResult:a,originalElementDisplayString:o},`Redirected click to parent element with selector: ${a.selector}`),{locator:l,relativePoint:a.relativePoint}}var SA=["date","datetime-local","month","time","week"],fA={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 yA(r){try{await B(ik(r),{milliseconds:J})}catch(e){r.logger.warn({err:e},"Failed to transform native datetime input, continuing...")}}async function ik({root:r,text:e,options:t,logger:n,callbacks:o}){let i=(await Qe({root:r,fn:()=>document.activeElement?.getAttribute("type")??"",timeout:Z,arg:void 0,waitForPageLoad:o.waitForPageLoad,codePath:"transforming native datetime input"})).toLowerCase();if(!fA[i])return;fA[i].test(e)&&n.warn(`Detected datetime input (${e}) in normalized format - this may fail to fill correctly as it is not how the user would input the value`),t.clearContent=!1,n.info("Transforming datetime input to use sequential key presses")}import{z as Ut}from"zod";var bA=Ut.object({doubleClick:Ut.boolean().optional(),rightClick:Ut.boolean().optional(),force:Ut.boolean().optional(),waitForDownload:Ut.boolean().optional(),delayMs:Ut.number().optional(),downloadTimeoutMs:Ut.number().optional(),relativePosition:Ut.object({x:Ut.number(),y:Ut.number()}).optional()}),Vge=Ut.object({repeat:Ut.number().optional(),convertMeta:Ut.boolean().optional().describe("misleading name due to backcompat. converts keyshortcuts + meta/control to platform-specific combos. defaults to true"),delayMs:Ut.number().optional()});async function uc({locator:r,callbacks:e,logger:t,timeoutMs:n=Z}){try{await pm(e,n);let o=r.evaluate(i=>{let a=window;a.momenticIsEligible=d=>{let m=window.getComputedStyle(d,null).getPropertyValue("display");if(m==="none"||m==="contents")return!1;let g=d.getBoundingClientRect();return!(!g.height||!g.width)},a.removeHighlightTimers=a.removeHighlightTimers||[],a.removeHighlightFunctions=a.removeHighlightFunctions||{};let l=0;for(;!a.momenticIsEligible(i)&&l<3;){if(!i.parentElement)throw new Error("No eligible non-empty parent found for highlighting");i=i.parentElement,l++}let c=i.style.getPropertyValue("outline"),s=i.style.getPropertyPriority("outline");i.style.setProperty("outline","5px dashed rgb(255, 0, 153)","important");let u=`momentic${Math.floor(Math.random()*1e7)}`;a[u]=()=>{i.style.removeProperty("outline"),i.style.setProperty("outline",c,s),i.getAttribute("style")||i.removeAttribute("style")},a.removeHighlightTimers.push(setTimeout(()=>{a[u](),a.removeHighlightFunctions?.[u]&&delete a.removeHighlightFunctions[u]},5e3)),a.removeHighlightFunctions[u]=a[u]},void 0,{timeout:n});return await B(o,{milliseconds:n}),!0}catch(o){return t.debug({err:o},"Failed to add node highlight, a page navigation likely occurred. This is non-fatal for tests."),!1}}async function pm(r,e=Z){let t=await r.state.getRoot();await Qe({root:t,fn:()=>{let o=window,i=o.removeHighlightTimers||[];for(;i.length;){let a=i.pop();clearTimeout(a)}Object.values(o.removeHighlightFunctions??{}).forEach(a=>{a()})},timeout:e,arg:void 0,waitForPageLoad:r.waitForPageLoad,codePath:"removing element highlights"})}async function mm(r){let e=!!r.browserCallbacks.state.userBrowserSettings.visualActions;return to({action:"clicking element",targetingResult:r.targetingResult,logger:r.logger,retryTimeoutMs:r.retryTimeoutMs,callbacks:r.browserCallbacks,func:async t=>TA({...r,targetingResult:t,useVisualClick:e})})}async function ck(r,e){let{redirectionAttempts:t=0}=e;if(t>=2)throw r;try{return await uk(r,e)}catch(n){throw e.redirectionAttempts===0?(e.logger.error({redirectionAttemptError:n,originalError:r},"Error handling click error, rethrowing original error"),r):n}}async function uk(r,e){let{logger:t,redirectionAttempts:n=0}=e,o=e.targetingResult.locator;if(r.message.includes("label")&&r.message.includes("for=")&&r.message.includes("intercepts pointer events")){let i=await o.getAttribute("id",{timeout:Z});if(!i)throw r;let a=o.page().locator(`[for=${JSON.stringify(i)}]`);return await a.waitFor({state:"visible",timeout:Z}),t.warn({err:r},"Attempting locator redirection due to input being covered by label"),TA({...e,targetingResult:{locator:a},redirectionAttempts:n+1})}else throw t.error({err:r},"Click error does not match any known recoverable patterns, rethrowing"),r}async function dk(r){let{logger:e,targetingResult:t,position:n,options:o}=r,i=bA.safeParse(o),a=Date.now(),{clickX:l,clickY:c,reason:s}=await gk({targetingResult:t,position:n,options:o});return e.info({position:n,options:i.success?i.data:void 0,clickLocation:{clickX:l,clickY:c,reason:s},duration:Date.now()-a},"Visual click"),{x:l,y:c}}async function pk(r){let{actionSource:e,targetingResult:t,options:n,logger:o}=r,i=r.targetingResult.locator,a=n?.relativePosition??r.position;if(e==="click"&&!a){let s=await hA({locator:i,logger:o});s&&(i=s.locator,a=s.relativePoint??a)}let l=n?.force||t.hints?.force||!1;l&&!a&&t.hints?.relativeXYToLocator&&(a=t.hints.relativeXYToLocator);let c=i.toString();try{o.info({locator:c},"Locator click"),n?.doubleClick?await i.dblclick({button:n.rightClick?"right":"left",timeout:J,position:a,delay:n?.delayMs??25,force:l}):await i.click({button:n?.rightClick?"right":"left",timeout:J,position:a,delay:n?.delayMs??25,force:l})}catch(s){let u=s;if(fk(u))o.warn({err:u},"Click action timed out while waiting for navigation after completion, continuing...");else return o.error({err:u},"Error clicking on locator, attempting to recover..."),ck(u,{...r,targetingResult:{...i,locator:i}})}return{locatorSource:c}}async function TA(r){let{options:e,logger:t,browserCallbacks:n,controllerCallbacks:o,useVisualClick:i,targetingResult:a}=r,l;e?.waitForDownload&&(l=(async()=>{let u=e.downloadTimeoutMs??Gp;try{return await a.locator.page().waitForEvent("download",{timeout:u})}catch(d){return d instanceof lk.TimeoutError?new w("ActionFailureError",`Download did not complete in ${u}ms`):new w("ActionFailureError",`Download failed: ${d.message}`)}})());try{await uc({locator:a.locator,callbacks:n,logger:t,timeoutMs:Z})}catch(u){t.warn({err:u},"Error highlighting locator in click, continuing...")}let c,s;if(i?c=await dk(r):s=(await pk(r)).locatorSource,e?.waitForDownload)if(l){if(!o?.createIsolatedFolder)throw new w("InternalWebAgentError","Cannot wait for download without a callback to create an isolated folder");t.info("Waiting for download to start and complete");let u=await B(l,{milliseconds:e.downloadTimeoutMs??Gp});if(u instanceof Error)throw u;return{downloadedFile:await hk(u,o.createIsolatedFolder,t),coordinates:c,locatorSource:s}}else throw new Error("No download promise or error but the step requested to wait for a download");return{coordinates:c,locatorSource:s}}async function mk(r){let e=await r.locator.boundingBox({timeout:J});if(!e)throw new w("ActionFailureError","Element does not have a bounding box");if(r.hints?.relativeXYToLocator){let o=e.x+r.hints.relativeXYToLocator.x,i=e.y+r.hints.relativeXYToLocator.y;return[{x:o,y:i},"targeting hint"]}let t=e.x+e.width/2,n=e.y+e.height/2;return[{x:t,y:n},"halfway point"]}async function gk({options:r,targetingResult:e,position:t}){let n,o,i;if(r?.relativePosition){let s=await e.locator.boundingBox({timeout:J}),u=r.relativePosition.x,d=r.relativePosition.y;s?.width&&(u=Math.max(0,Math.min(r.relativePosition.x,s.width))),s?.height&&(d=Math.max(0,Math.min(r.relativePosition.y,s.height))),n=(s?.x??0)+u,o=(s?.y??0)+d,i="relative position from user"}else if(t){let s=await e.locator.boundingBox({timeout:J});n=(s?.x??0)+t.x,o=(s?.y??0)+t.y,i="predefined position"}else{let[s,u]=await mk(e);n=s.x,o=s.y,i=u}let a=e.locator.page(),l=r?.rightClick?"right":"left",c=r?.delayMs??25;return r?.doubleClick?await a.mouse.dblclick(n,o,{button:l,delay:c}):await a.mouse.click(n,o,{button:l,delay:c}),{clickX:n,clickY:o,reason:i}}async function hk(r,e,t){t.info("Download detected, saving file to disk");let n=await r.path(),o=Qp(r.suggestedFilename()),i=e();await r.saveAs(sk(i,o)),EA(n,{force:!0}),setTimeout(()=>{EA(i,{recursive:!0,force:!0})},5*60*1e3);let a=Yv(ak(i),o);return t.info({uri:a,downloadFolder:i},"Saved download to isolated folder"),a}function fk(r){return r.message.includes("locator.click: Timeout")&&r.message.includes("click action done")}import{platform as Sk}from"os";var yk={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 bk(){let r=Sk();return r==="win32"?"win32":r==="darwin"?"darwin":"linux"}function vA(r){return JSON.stringify(r.split("+").sort())}function dc(r,e){let t=bk(),n=vA(r);for(let o of Object.values(yk))if(Object.values(o).some(i=>vA(i)===n))return o[t];return process.platform==="darwin"&&!e?r=r.replaceAll("Control","Meta"):r=r.replaceAll("Meta","Control"),r}async function gm({frame:r,page:e,deltaX:t,directionX:n,deltaY:o,directionY:i,signal:a,callbacks:l,logger:c}){if(!t&&!o)return;let s=n==="left"?-1:1,u=i==="up"?-1:1;if(r)await Qe({root:r,fn:([d,p,m,g])=>window.scrollTo(window.scrollX+(d??window.innerWidth)*m,window.scrollY+(p??window.innerHeight)*g),arg:[t,o,s,u],waitForPageLoad:l.waitForPageLoad,timeout:me,codePath:"scrolling page"});else{let d=e.viewportSize()||tn,p=await Qe({root:e,fn:()=>document.body.scrollHeight,arg:void 0,waitForPageLoad:l.waitForPageLoad,timeout:me,codePath:"computing page height"}),[m,g,h]=await Qe({root:e,fn:()=>{let f=document.activeElement;if(!f)return[void 0,void 0,void 0];let b=f.getBoundingClientRect();return[f.scrollTop,b.x,b.y]},arg:void 0,waitForPageLoad:l.waitForPageLoad,timeout:me,codePath:"computing active element position"});await e.mouse.wheel((t??d.width)*s,(o??d.height)*u);try{let f=Date.now();for(;Date.now()-f<me;){a?.throwIfAborted();let b=await B(e.evaluate(()=>document.body.scrollHeight),{milliseconds:Z}),[E,v,R]=await B(e.evaluate(()=>{let T=document.activeElement;if(!T)return[void 0,void 0,void 0];let _=T.getBoundingClientRect();return[T.scrollTop,_.x,_.y]}),{milliseconds:Z});if(b===p&&E===m&&v===g&&R===h)break;p=b,m=E,g=v,h=R,await X(it)}}catch(f){c.warn({err:f},"Failed to wait for scroll to complete, continuing...")}}}async function hm(r,e){let t,n;for(let o=0;o<4;o++)try{return t=r.pages(),await Promise.all(t.map(async i=>{let a="";try{a=e?.getTitles?await i.title():""}catch{a="Unknown page"}return{title:a,url:i.url()}}))}catch(i){n=i,await X(it)}throw new Error(`Failed to get tab titles after all retries: ${n?.message}`)}import{randomUUID as xk}from"crypto";import{cloneDeep as ym}from"lodash-es";function Tn(r,e){let t=r.findIndex(n=>n===e);if(!(t===-1||!r[t+1]))return r[t+1]}import{createHash as Ek}from"crypto";var Tk="v1";function fm(r,e){if(r.tagName.toLowerCase()==="svg"&&!Ak(r))try{let t=AA(r,e),n=vk(JSON.stringify(t));return{version:Tk,json:t,hash:n}}catch{return}}function vk(r){return Ek("md5").update(r).digest("hex")}function AA(r,e){let t=r.tagName.toLowerCase(),n=wk(r);if(t==="image"&&n["xlink:href"])throw new Error("Image tags within SVGs are not supported");let o={type:t,props:n,children:[]};for(let i of r.childrenBackendIds){let a=e.backendIdToNode[i];if(a&&a.nodeType===1){let l=AA(a,e);l&&o.children.push(l)}}return o}function Ak(r){let e=r.computedStyles.display,t=r.computedStyles.visibility,n=r.computedStyles.opacity;return e==="none"||t==="hidden"||n==="0"}function wk(r){let e={},t=r.attributes;for(let n of Object.keys(t))ar.visualAttributesForSvgSerialization.includes(n)&&(e[n]=t[n]);return t.id&&r.tagName.toLowerCase()!=="svg"&&(e.id=t.id),e}var ro={r:147,g:196,b:125,a:.55},RA={showRulers:!1,showStyles:!1,showExtensionLines:!1,contrastAlgorithm:"aa",contentColor:ro,paddingColor:ro,borderColor:ro,marginColor:ro,eventTargetColor:ro,shapeColor:ro,shapeMarginColor:ro,showInfo:!0,showAccessibilityInfo:!0};function CA({snapshot:r,devicePixelRatio:e,computedStylesToFetch:t,logger:n}){let o=r.strings,i=r.documents,a={},l={},c={roots:[],backendIdToNode:a,frameIndexToIframeNode:l};return i.forEach((s,u)=>{let d=Rk({allDocuments:i,stringConstants:o,computedStylesToFetch:t,devicePixelRatio:e,frameIndex:u,backendIdToNode:a,frameIndexToIframeNode:l,logger:n});c.roots.push(d)}),c}function Rk({allDocuments:r,stringConstants:e,computedStylesToFetch:t,devicePixelRatio:n,frameIndex:o,frameIndexToIframeNode:i,backendIdToNode:a,logger:l}){let c=r[o],s=c.layout,u={};s.nodeIndex.forEach((M,z)=>{u[M]=z});let d=s.styles,p=s.bounds??[],m=c.nodes,g=m.contentDocumentIndex??{index:[],value:[]},h=m.backendNodeId??[],f=m.attributes??[],b=m.parentIndex??[],E=m.nodeName??[],v=m.nodeType??[],R=m.pseudoType??{index:[],value:[]},T=m.inputChecked??{index:[]},_=e[c.frameId];for(let M=0;M<h.length;M++){let z=h[M],Y=v[M],Ee=f[M]??[],oe=b[M]!==void 0&&b[M]>=0?b[M]:void 0,ge=oe!==void 0?h[oe]:void 0,et=ge!==void 0?a[ge]:void 0,j=R.index.indexOf(M),U=j!==-1?e[R.value[j]]:void 0,ne=u[M],ae;ne?ae=p[ne]??[]:ae=[];let Ne=E[M]!==void 0?e[E[M]]?.toLowerCase():void 0;if(!Ne){l.warn({backendNodeId:z,frameId:_,frameIndex:o,nodeBounds:ae},"DOM node has no tag name");continue}let he={backendNodeId:z,psuedoType:U,nodeType:Y,frameIndex:o,parentFrameId:_,ownedFrameId:void 0,bounds:{x:ae[0]??null,y:ae[1]??null,width:ae[2]??null,height:ae[3]??null},computedStyles:{},attributes:{},parentBackendNodeId:ge??null,tagName:Ne,parent:et??void 0,childrenBackendIds:[],momenticIgnored:void 0,mPathSelector:void 0};et&&et.childrenBackendIds.push(z);let dt=g.index.indexOf(M);if(dt!==-1){let Ae=g.value[dt];i[Ae]=he;let tt=r[Ae]?.frameId;he.ownedFrameId=tt!==void 0?e[tt]:void 0}for(let Ae of Object.keys(he.bounds)){let tt=Ae;he.bounds[tt]!==null&&(he.bounds[tt]/=n)}let Gt=ne!==void 0?d[ne]??[]:[];for(let Ae=0;Ae<Gt.length&&!(Ae>=t.length);Ae++){let tt=Gt[Ae];if(tt===void 0||isNaN(tt))continue;let Vt=e[tt];if(Vt===void 0)continue;let mo=t[Ae];he.computedStyles[mo]=Vt}for(let Ae=0;Ae<Ee.length;Ae+=2){let tt=Ee[Ae],Vt=Ee[Ae+1];if(!tt||!Vt)continue;let mo=e[tt],Cn=e[Vt];!mo||!Cn||(he.attributes[mo]=Cn)}T.index.includes(M)&&(he.attributes.checked="true"),a[he.backendNodeId]=he}return a[h[0]]}function Sm(r,e){if(r.mPathSelector)return r.mPathSelector;let t=r.parent,n;if(!t)n=r.tagName;else if(r.tagName==="body")n="body";else{let i=t.childrenBackendIds.filter(c=>e.backendIdToNode[c]?.nodeType===1&&!e.backendIdToNode[c]?.psuedoType).indexOf(r.backendNodeId),a=` > ${r.tagName}:nth-child(${i+1})`;n=`${Sm(t,e)}${a}`}return r.mPathSelector=n,n}function wA(r,e){return r.parentBackendNodeId!==null?e.backendIdToNode[r.parentBackendNodeId]:r.frameIndex===0?void 0:e.frameIndexToIframeNode[r.frameIndex]}var Ck=["html","#document","#document-fragment"];function xA({node:r,domGraph:e}){let t=[],n=r,o=wA(r,e);if(!o)return[r.tagName];let i=()=>{if(n=o,o=wA(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++,Ck.includes(n.tagName)){i();continue}if(n.tagName==="body")t.push("body");else{let c=!1,s=1;for(let u=0;u<o.childrenBackendIds.length;u++){let d=o.childrenBackendIds[u],p=e.backendIdToNode[d];if(d===n.backendNodeId){t.push(`${n.tagName}:nth-child(${s})`),c=!0;break}else p?.nodeType===1&&!p.psuedoType&&s++}if(!c)throw new Error(`Could not find child (${n.tagName}) in parent's children list (${o.tagName})`)}i()}return t.reverse()}function MA(r,e){let t=r.locator("html"),n=[];for(let o=0;o<e.length;o++){let i=e[o];if(n.push(i),i.startsWith("iframe")){let a=n.join(" > ");n=[],o<e.length-1?t=t.frameLocator(a):t=t.locator(a)}}if(n.length&&(t=t.locator(n.join(" > "))),"owner"in t)throw new Error("Final locator from mpath is a frame locator");return t}async function _A(r,e){await r.send({method:"DOM.getDocument",params:{depth:0},timeout:me});let t=await r.send({method:"DOM.requestNode",params:{objectId:e},timeout:me}),o=(await r.send({method:"DOM.getAttributes",params:{nodeId:t.nodeId},timeout:me})).attributes,i=Tn(o,Vr);if(!i)throw new Error(`Could not find attribute ${Vr} for object ${e}`);return i}var Mk=["focusable","keyshortcuts","controls","live","relevant","orientation"],_k=["selected","readonly","modal","required","invalid"],Ik=["id","name","role","content"],IA=["absolute","fixed","sticky"],Pk=["i"],Ok=["path"],Lk=["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"],LA=["ariaHiddenElement","ariaHiddenSubtree","hiddenByChildTree","inertElement","inertSubtree","notRendered","notVisible"],NA=["activeAriaModalDialog","activeFullscreenElement","activeModalDialog"],Nk=["menulistpopup","statictext","inlinetextbox"],Dk=80,PA=100,DA=50,Tm=["StaticText","ListMarker","RootWebArea","LineBreak","emphasis","::before","::after"],kk=["cite"],Uk={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"]},Fk={name:!0,value:!0,title:!0,alt:!0,placeholder:!0,checked:!0,selected:!0,contenteditable:!0},OA={indentLevel:0},bm=class r{id;role;name;nameSources;tagName;content;properties;internalProperties;ignoredReasons;dataMomenticId;importantProperties;pathFromRoot;mPathSelector;parent;children;parentFrame;domNode;backendNodeId;ignoredByCDP;flagNotActionableNodes;constructor(e){if(this.id=e.id,this.role=e.role,this.name=e.name,this.nameSources=e.nameSources,this.content=e.content,this.properties={},this.pathFromRoot=e.pathFromRoot,this.children=e.children,this.backendNodeId=e.backendNodeID,this.ignoredByCDP=e.ignoredByCDP,this.internalProperties=e.internalProperties??{},this.parentFrame=e.parentFrame,this.ignoredReasons=e.ignoredReasons,this.importantProperties=e.importantProperties,this.flagNotActionableNodes=e.flagNotActionableNodes,e.properties&&e.properties.forEach(t=>{t.name==="keyshortcuts"?this.dataMomenticId=parseInt(t.value.value):this.properties[t.name]=t.value.value}),e.domNode){this.domNode=e.domNode,this.tagName=e.domNode.tagName||void 0;let t=e.domNode.attributes.id;this.name=this.name||e.domNode.attributes.name||(t&&t.length<DA?t:""),this.role=this.role||(e.domNode.attributes.role??""),Gk(this.properties,e.domNode,e.importantProperties)}jk(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&&Ok.includes(this.domNode.tagName)||this.domNode?.computedStyles.display==="contents"||this.ignoredReasons.some(n=>NA.includes(n)))return!1;if(e){if(Object.keys(this.domNode?.attributes??{}).some(o=>zA(o,e)))return!0;let n=this.domNode?.attributes.class?.split(" ");if(n&&n.length>0&&n.some(o=>HA(o,e))||e.styles?.some(o=>{let i=o.split(":");if(i.length!==2)return!1;let a=i[0]?.trim(),l=i[1]?.trim();if(a===void 0||l===void 0)return!1;let c=this.domNode?.computedStyles[a];return c!==void 0&&(c===l||l==="*")}))return!0}if(this.domNode&&Pk.includes(this.domNode.tagName)||Lk.includes(this.role.toLowerCase())||this.role.toLowerCase()==="inlinetextbox"&&this.tagName||!this.properties.hidden&&(this.properties.focusable||this.properties.settable)||ar.alwaysInterestingTruthyPropertyNames.some(n=>!!this.properties[n]))return!0;let t=this.properties.class;return typeof t=="string"&&t.split(" ").some(n=>BA(n))?!0:this.children.every(n=>n.role==="StaticText")&&this.internalProperties?.inCodeMirrorEditor?!1:this.children.some(n=>n.role==="StaticText")||this.children.length>1&&this.children.some(n=>n.tagName==="input")?!0:this.domNode&&(this.domNode.bounds.x===null||this.domNode.bounds.y===null||!this.domNode.bounds.width||!this.domNode.bounds.height)?!1:!!this.name.trim()||!!this.content||Object.keys(this.properties).some(n=>n.startsWith("data"))}shouldSerializeBounds(){let e=this.domNode?.computedStyles.position;return!!(e&&(e==="absolute"||e==="fixed"||e==="sticky"))}isNotActionable(){return!!(this.domNode?.computedStyles.display==="contents"||this.domNode&&(this.domNode.bounds.x===null||this.domNode.bounds.y===null||!this.domNode.bounds.width||!this.domNode.bounds.height))}serialize(e=OA){let t=Object.assign({},OA,e),{indentLevel:n,noChildren:o,noProperties:i,noId:a,noContent:l,condensedMode:c}=t,s=ym(this.properties),u=" ".repeat(n),d=this.role||"",p=this.tagName??"unknown",m=this.name;d==="heading"&&m==="heading"&&(m=""),this.nameSources?.find(T=>!T.superseded&&T.type==="contents")&&this.children.length>0&&(m="");let h=this.nameSources?.find(T=>!T.superseded);if(h&&!h.nativeSource&&h.type==="relatedElement"){let T=h.attributeValue?.relatedNodes??[];T.length===1&&T[0].text&&T[0].text===m&&(m="")}let f=Tm.includes(this.role)||kk.includes(this.tagName||"");if(this.role==="StaticText"||this.role==="ListMarker")return`${u}${m}
|
|
4021
|
+
`;let b=`${u}<${p}`;!a&&!f&&(b+=` id="${this.id}"`);let E=l??!1;if((s.multiline||s.contenteditable)&&this.children.length>0&&(E=!0),d&&d!=="generic"&&d!==p&&!(Uk[d]??[]).includes(p)&&(b+=` role=${JSON.stringify(d)}`),m&&(b+=` name=${JSON.stringify(m)}`),this.content&&!E&&(b+=` content=${JSON.stringify(this.content)}`),this.flagNotActionableNodes&&this.tagName!=="#document"&&this.isNotActionable()&&(b+=` ${ar.ineligibleElementAttribute}`),this.shouldSerializeBounds()&&this.domNode?.bounds){let T=this.domNode.bounds,_=Math.round(T.x??0),M=Math.round(T.y??0),z=Math.round((T.x??0)+(T.width??0)),Y=Math.round((T.y??0)+(T.height??0));b+=` bounds=[${_} ${M} ${z} ${Y}]`}let v=Date.now();if(Object.keys(s).length>0&&!i){if(Date.now()-v>1e3)throw new Error(`Serialization for the HTML element with tag ${p} and internal ID ${this.id} took too long. Please ensure your machine has enough resources to run Momentic.`);Object.entries(s).forEach(([T,_])=>{if(!Mk.includes(T)){{if(_k.includes(T)&&(!_||_==="false"))return;if(T==="value"&&E&&(s.type==="text"||this.role==="textbox"))return;if(T==="level"&&`${_}`=="1")return;if(T==="url"&&s.src&&p==="img")return;if(T==="url"&&s.href&&p==="a")return;if(T==="editable"&&_==="plaintext")return;if(T==="type"&&_===p)return;if(c&&!Fk[T])return}typeof _=="string"?b+=` ${T}="${_t(_,PA,!0)}"`:typeof _=="boolean"?_?b+=` ${T}`:b+=` ${T}={false}`:typeof _<"u"&&(b+=` ${T}={${_t(JSON.stringify(_),PA,!0)}}`)}})}if(p==="::before"||p==="::after"){let T="";for(let _ of this.children)T+=_.serialize({...e,indentLevel:n,neighbors:0});return T}let R=e.maxLevel!==void 0&&n/2>=e.maxLevel;if(this.children.length===0||o||R)b+=` />
|
|
4022
|
+
`;else{let T="";for(let M of this.children)T+=M.serialize({...e,indentLevel:n+2,neighbors:0});let _=T.trim();_.length<=Dk&&!_.includes(`
|
|
4023
|
+
`)?b+=`>${_}</${p}>
|
|
4024
|
+
`:b+=`>
|
|
4013
4025
|
${T}${u}</${p}>
|
|
4014
|
-
`}if(e.neighbors!==void 0&&e.neighbors>0&&this.parent){let T=this.parent.children.findIndex(
|
|
4015
|
-
${
|
|
4016
|
-
${R||""}`}return E}shallowClone(){let e=new r({id:this.id,role:this.role,name:this.name,nameSources:this.nameSources,content:this.content,properties:[],pathFromRoot:this.pathFromRoot,children:[],ignoredReasons:this.ignoredReasons,backendNodeID:this.backendNodeId,ignoredByCDP:this.ignoredByCDP,internalProperties:Om(this.internalProperties),importantProperties:this.importantProperties,parentFrame:this.parentFrame,flagNotActionableNodes:this.flagNotActionableNodes});return e.tagName=this.tagName,e.dataMomenticId=this.dataMomenticId,e.properties=Om(this.properties),e}},Nm=class r{constructor(e,t,n,o){this.root=e;this.a11yIdNodeMap=t;this.dataMomenticIdMap=n;this.selectorToNodeMap=o}serialize(e){return this.root.serialize(e)}pruneUsingSummaries(e){let t=this.root;if(!t)throw new Error("Cannot prune a11y tree with no root");let n={},o={},i={},a=c=>{let 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(t);return new r(s,n,o,i)}pruneUsingRelevantIds(e){let t=this.root;if(!t)throw new Error("Cannot prune a11y tree with no root");function n(i,a=!1){let s=e.has(`${i.id}`)||i.id===t?.id,c=i.shallowClone(),l=i.children,u=!1,d=[];for(let p of l){let g=n(p,s||u);g&&(d.push(g),g.parent=c,u=!0)}if(c.children=d,s||u)return c;if(km.includes(i.role)&&a)return c}let o=n(t);return new r(o,this.a11yIdNodeMap,this.dataMomenticIdMap,this.selectorToNodeMap)}pruneToSerializedCharLimit(e){let t=this.root;if(!t)throw new Error("Cannot prune a11y tree with no root");let n=c=>c.role==="StaticText"||c.role==="ListMarker",o=new WeakMap,i=(c,l)=>{if(o.has(c))return o.get(c);let u=c.serialize({indentLevel:l,noChildren:!0});return o.set(c,u),u},a=(c,l,u)=>{let d=c.shallowClone();d.children=[];let p=i(c,l).length;if(u<=p)return{clone:d,used:p};if(n(c)||c.children.length===0)return{clone:d,used:p};let g=p,m=u-g;for(let h of c.children){let f=l+2,E=i(h,f).length;if(m<E)break;let{clone:S,used:A}=a(h,f,m);if(A>m)break;d.children.push(S),S.parent=d,g+=A,m-=A}return{clone:d,used:g}},{clone:s}=a(t,0,Math.max(1e4,e));return new r(s,this.a11yIdNodeMap,this.dataMomenticIdMap,this.selectorToNodeMap)}};function CU(r){return r.name?.value?`"${r.name.value}"`:r.role?.value&&r.role.value!=="none"&&r.role.value!=="generic"?`"${r.role.value}"`:`"${r.nodeId}"`}function xU(r,e,t,n){return r.bounds.x===null||r.bounds.y===null||r.bounds.height===null||r.bounds.width===null||r.bounds.width===0||r.bounds.height===0?!0:r.bounds.x+r.bounds.width<e.leftBound||r.bounds.x>e.rightBound?(ec({logger:t,logKey:n,maxCount:5,intervalMs:3e3},{domNode:r,logKey:n},"Filtering out node since it is not in the viewport horizontally"),!1):r.bounds.y+r.bounds.height<e.upperBound||r.bounds.y>e.lowerBound?(ec({logger:t,logKey:n,maxCount:5,intervalMs:3e3},{domNode:r,logKey:n},"Filtering out node since it is not in the viewport vertically"),!1):r.computedStyles.display==="none"?(t.debug({domNode:r},"Filtering out node since it has display none"),!1):!0}async function ew({node:r,parent:e,frameId:t,frameContext:n,axGraph:o,domGraph:i,inputNodeMap:a,flagNotActionableNodes:s,showZeroOpacityElements:c,filterByViewport:l,viewportDetails:u,useMPaths:d,importantProperties:p,allowedA11yIgnoreReasonsOverride:g,cdpClient:m,logger:h,callId:f}){if(!e&&r.parentId)throw new Error(`Got no parent for accessibility node ${r.nodeId}: ${JSON.stringify(r)}`);let E=(G,se={})=>{},S=r.backendDOMNodeId,A=TU.includes(r.role?.value?.toLowerCase()??"");if(!A&&S===void 0)return E("Filtering out node since it doesn't exist in the DOM"),[];let C=S?i.backendIdToNode[S]:void 0;if(!A&&!C)try{let G=await V(m.send({method:"DOM.describeNode",params:{backendNodeId:S}}),{milliseconds:750,fallback:()=>{h.debug("Timeout getting node from CDP while processing a11y tree")}});if(G&&G.node.nodeName.toLowerCase()==="slot"&&G.node.distributedNodes?.length)h.debug({redirectedDomNode:C,parentAXNode:e?.getNodeOnlySerializedForm(),originalAXNode:r,cdpResult:G},"Redirecting node to assigned slot");else return E("Filtering out node since it doesn't exist in the DOM",{cdpResult:G}),[]}catch(G){return E("Filtering out node since it doesn't exist in the DOM",{err:G}),[]}if(C&&e&&l&&u&&r.backendDOMNodeId&&!xU(C,u,h,f))return C.momenticIgnored=!0,[];if(C&&C.computedStyles.display==="none")return C.momenticIgnored=!0,[];if(C&&C.computedStyles.opacity==="0"&&c!==!0){if(c==="inputs-only"&&C.tagName.toLowerCase()!=="input")return C.momenticIgnored=!0,[];if(c===!1)return C.momenticIgnored=!0,[]}let T=r.name?.value?typeof r.name.value=="string"?r.name.value:`${r.name.value}`:"",I=r.value?.value?typeof r.value.value=="string"?r.value.value:`${r.value.value}`:"",R=new Lm({domNode:C,id:parseInt(r.nodeId),role:r.role?.value||"",name:T,nameSources:r.name?.sources,content:I,properties:r.properties,children:[],ignoredReasons:r.ignoredReasons?.filter(G=>(g??JA).includes(G.name)||ZA.includes(G.name))??[],pathFromRoot:(e?`${e.pathFromRoot} `:"")+CU(r),backendNodeID:r.backendDOMNodeId,ignoredByCDP:r.ignored,internalProperties:{inCodeMirrorEditor:e?.internalProperties?.inCodeMirrorEditor},importantProperties:p,parentFrame:n.type==="root"?void 0:n,flagNotActionableNodes:s}),w=n,B=a[t],D=t;if(C?.tagName.toLowerCase()==="iframe"&&C.ownedFrameId){let G=n.childFrames.find(ke=>ke.frameId===C.ownedFrameId),se=o[G?.frameId??""]?.root,ce=a[G?.frameId??""];if(G&&se&&ce){r.childIds&&r.childIds.length>0&&h.debug("Replacing existing node's children with children from the iframe");let ke=se;r.childIds=ke.childIds,w=G,B=ce,D=G.frameId}}let U=C?.childrenBackendIds?.length??0,J=(r.childIds??[]).filter(G=>!!B.get(parseInt(G))).length;if(U>J){let G=r.childIds?.map(ce=>B.get(parseInt(ce))).filter(Boolean).map(ce=>ce?.backendDOMNodeId).filter(ce=>ce!==void 0)??[],se=0;for(let ce of C?.childrenBackendIds??[]){if(G.includes(ce)){se=(r.childIds?.findIndex(we=>B.get(parseInt(we))?.backendDOMNodeId===ce)??0)+1;continue}let ke=i.backendIdToNode[ce];if(!ke||ke?.tagName.toLowerCase()!=="svg")continue;let fe=Math.floor(-1*Math.random()*1e7),pt={nodeId:fe.toString(),parentId:r.nodeId,ignored:!1,backendDOMNodeId:ce,frameId:D,role:{type:"string",value:"graphics-symbol"}};B.set(fe,pt),r.childIds||(r.childIds=[]),r.childIds.splice(se,0,fe.toString()),se++}}if(r.childIds?.length===1&&C){let G=B.get(parseInt(r.childIds[0])),se=G?.role?.value,ce=C.childrenBackendIds;if(G&&se==="StaticText"&&ce.length===1){let ke=i.backendIdToNode[ce[0]];if(ke?.tagName?.toLowerCase()==="span"){let fe=Math.floor(-1*Math.random()*1e7).toString(),pt={nodeId:fe,parentId:r.nodeId,ignored:!1,backendDOMNodeId:ke.backendNodeId,frameId:D,childIds:[G.nodeId]};G.parentId=fe,B.set(parseInt(fe),pt),r.childIds=[fe]}}}for(let G of r.childIds??[]){if(!G)continue;let se=B.get(parseInt(G));if(!se)continue;let ce=await ew({node:se,parent:R,domGraph:i,axGraph:o,frameId:D,frameContext:w,inputNodeMap:a,cdpClient:m,logger:h,callId:f,filterByViewport:l,showZeroOpacityElements:c,importantProperties:p,viewportDetails:u,useMPaths:d,flagNotActionableNodes:s});ce.length&&(R.children=R.children.concat(ce))}if(R.role==="StaticText"&&(R.children=[]),R.children.length===1&&R.children[0].role==="StaticText"){let G=R.name,se=R.children[0]?.name;(G===se||!se)&&(R.children=[])}let Le=[];for(let G=R.children.length-1;G>=0;G--){let se=R.children[G];if(se.role!=="StaticText"){Le.push(se);continue}if(G===0||R.children[G-1].role!=="StaticText"){Le.push(se);continue}R.children[G-1].name+=se.name}if(R.children=Le.reverse(),!R.isInteresting(p)&&r.parentId)return C&&(C.momenticIgnored=!0),R.children;for(let G of R.children)G.parent=R;return IU(R),C&&d&&Pm(C,i),[R]}function tw({node:r,a11yIdNodeMap:e,dataMomenticIdMap:t,logger:n,callId:o,domGraph:i,useMPaths:a,selectorToNodeMap:s,iconKnowledgeBase:c,startId:l=1}){r.id=l,l+=1,e[r.id]=r,r.dataMomenticId?t[r.dataMomenticId]=r:km.includes(r.role);let u=r.backendNodeId,d=u!==void 0?i.backendIdToNode[u]:void 0;if(a&&d&&d.mPathSelector&&(s[d.mPathSelector]=r,r.mPathSelector=d.mPathSelector),c&&d&&d.tagName?.toLowerCase()==="svg"){let p=Im(d,i),g=p?c[p.hash]:void 0,m=g?g.description:void 0;g&&(r.properties["data-momentic-description"]=m)}for(let p of r.children)l=tw({node:p,a11yIdNodeMap:e,dataMomenticIdMap:t,logger:n,callId:o,startId:l,useMPaths:a,domGraph:i,selectorToNodeMap:s,iconKnowledgeBase:c});return l}async function rw({rawA11yGraph:r,domGraph:e,startingFrameId:t,logger:n,cdpClient:o,filterByViewport:i,showZeroOpacityElements:a,flagNotActionableNodes:s,importantProperties:c,viewportDetails:l,useMPaths:u,frameContext:d,iconKnowledgeBase:p,allowedA11yIgnoreReasonsOverride:g}){let m=t??"root",h=r[m]?.root;if(!h)throw new Error("A11y tree has no root");let f=gU(),E=R=>{let w=R.allNodes.filter(D=>!D.ignoredReasons?.find(J=>(g??JA).includes(J.name))),B=new Map;return w.forEach(D=>{B.set(parseInt(D.nodeId),D)}),B},S={};Object.entries(r).forEach(([R,w])=>{S[R]=E(w)});let A=await ew({node:h,domGraph:e,parent:null,inputNodeMap:S,axGraph:r,frameId:m,frameContext:d,cdpClient:o,logger:n,callId:f,showZeroOpacityElements:a,importantProperties:c,filterByViewport:i,viewportDetails:l,useMPaths:u,flagNotActionableNodes:s,allowedA11yIgnoreReasonsOverride:g});if(A.length>1)throw new Error(`Something went horribly wrong processing the a11y tree, we got: ${JSON.stringify(A)}`);if(A.length===0)throw new Error("There are no accessible elements on this page or frame. Are you sure this website loads properly?");let C={},T={},I={};return tw({node:A[0],a11yIdNodeMap:C,dataMomenticIdMap:T,selectorToNodeMap:I,domGraph:e,logger:n,callId:f,useMPaths:u,iconKnowledgeBase:p}),new Nm(A[0],C,T,I)}function _U(r,e,t,n){if(r==="class"){if(t.tagName?.toLowerCase()==="svg")return e.split(" ").filter(a=>a.length<QA&&!sr.bannedClassSubstrings.some(s=>a.includes(s))).slice(0,3).join(" ");let o=e.split(" "),i=[];for(let a of o)if(nw(a,n)){i.push(a);continue}return i.length?i.join(" "):null}if(e==="true")return!0;if(e==="false")return!1;try{let o=parseInt(e);if(!isNaN(o))return o}catch{}return r==="src"&&e.includes("base64")?e.slice(0,e.indexOf("base64")+6)+"...":e.length>60?e.slice(0,50)+"...":e}function MU(r,e,t){if(!e)return;Object.entries(e.attributes).forEach(([a,s])=>{let c=r[a]||a.startsWith("aria")||SU.includes(a);if((sr.relevantElementAttributes.includes(a)||ow(a,t))&&!c){let u=_U(a,s,e,t);u!==null&&(r[a]=u)}});let n,o=[];if(e.computedStyles.position&&KA.includes(e.computedStyles.position))n=e.computedStyles.position;else if(e.attributes.style){for(let a of KA)if(e.attributes.style.includes(`position: ${a}`)){n=a;break}}n&&o.push(`position: ${n}`);let i;e.computedStyles.opacity&&e.computedStyles.opacity==="0"&&(i="opacity: 0"),i&&o.push(i);for(let a of t?.styles??[]){let 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&&(r.style=o.join("; "))}function IU(r){let e=r.properties.class;if(typeof e=="string"&&e.includes("cm-content")){r.children.forEach((i,a)=>{i.properties["cm-line-number"]=`${a+1}`});return}if(typeof e=="string"&&e.includes("notion-page-content")){r.children.forEach((i,a)=>{i.properties["block-number"]=`${a+1}`}),r.children.length>0&&(r.children[r.children.length-1].properties.description="This is the last block in the document. Click here to add new text to the end.");return}if(r.tagName==="table"){let i=[],a=r.children.find(c=>c.tagName==="thead");if(a){let c=a.children.find(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(It(u.name,100,!1))}),i?.length!==l.length&&(i=void 0)}}let s=0;for(let c of r.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 g=u.children.filter(m=>m.tagName==="th");if(g.length){if(i=g.map(m=>It(m.name,100,!1)),i.length===g.length)continue;i=void 0}}s+=1,u.properties["row-index"]||(u.properties["row-index"]=s);let d=u.children.filter(g=>g.tagName==="td"||g.tagName==="th"),p=d.length===i?.length;d.forEach((g,m)=>{g.tagName!=="th"&&(g.properties["col-index"]||(g.properties["col-index"]=m+1),p&&(g.properties.col||(g.properties.col=i[m])))})}}}function PU(r){let e=r.properties.class,t=typeof e=="string"&&e.includes("cm-content");r.internalProperties.inCodeMirrorEditor=r.internalProperties?.inCodeMirrorEditor||t}function nw(r,e){if(e&&iw(r,e))return!0;if(sr.bannedClassSubstrings.some(t=>r.includes(t)))return!1;if(sr.alwaysInterestingClassNames.includes(r))return!0;for(let t of sr.alwaysInterestingClassPrefixes)if(r.startsWith(t))return!0;return!1}function ow(r,e){if(e?.attributes?.includes(r))return!0;for(let t of e?.attributes??[])if(t.endsWith("*")){let n=t.slice(0,-1);if(r.startsWith(n))return!0}return!1}function iw(r,e){if(e?.classes?.includes(r))return!0;for(let t of e?.classes??[])if(t.endsWith("*")){let n=t.slice(0,-1);if(r.startsWith(n))return!0}return!1}var wc=class r{constructor(e,t,n,o,i){this.session=e;this.logger=t;this.contextGetter=n;this.pageGetter=o;this.defaultTimeoutMs=i}cdpInitializingPromise=void 0;cdpCrashDetails=void 0;cdpFullyDead=!1;loadEventLogs=[];static async init({logger:e,contextGetter:t,pageGetter:n,defaultTimeoutMs:o}){let i=t(),a=n(),s,c;for(let u=0;u<2;u++)try{s=await V(i.newCDPSession(a),{milliseconds:o*u,fallback:()=>{throw new _("UserInfrastructureError",`Failed to initialize Chrome session within the page load timeout (${a.url()})`)}});break}catch(d){await ee(at),c=d}if(!s)throw c;let l=new r(s,e,t,n,o);try{await V(l.registerHandlers(s),{milliseconds:o,message:`CDP handler registration timed out after ${o}ms`})}catch(u){throw l.cdpFullyDead=!0,new _("UserInfrastructureError",`Failed to initialize CDP client: ${u}`)}return l}async registerHandlers(e){e.on("Target.attachedToTarget",async()=>{try{await e.send("Runtime.runIfWaitingForDebugger")}catch(t){this.logger.warn({err:t},"Failed to run Runtime.runIfWaitingForDebugger")}}),e.on("Target.targetCrashed",t=>{this.cdpCrashDetails={...this.cdpCrashDetails??{},targetCrashDetails:JSON.stringify(t)},this.logger.error({payload:t},"CDP session crashed, Momentic will likely not function correctly")}),e.on("Inspector.targetCrashed",t=>{this.cdpCrashDetails={...this.cdpCrashDetails??{},inspectorCrashDetails:JSON.stringify(t)},this.logger.error({payload:t},"CDP inspector session crashed, Momentic will likely not function correctly")}),e.on("Page.frameRequestedNavigation",t=>{this.loadEventLogs.push(`[${new Date(Date.now()).toLocaleString("en-US",{timeZone:"America/Los_Angeles"})}] Frame requested navigation: ${JSON.stringify(t)}`)}),e.on("Page.navigatedWithinDocument",t=>{this.loadEventLogs.push(`[${new Date(Date.now()).toLocaleString("en-US",{timeZone:"America/Los_Angeles"})}] Navigated within document: ${JSON.stringify(t)}`)}),e.on("Page.lifecycleEvent",t=>{this.loadEventLogs.push(`[${new Date(Date.now()).toLocaleString("en-US",{timeZone:"America/Los_Angeles"})}] Page lifecycle event: ${JSON.stringify(t)}`)}),e.on("Page.loadEventFired",()=>{this.loadEventLogs.push(`[${new Date(Date.now()).toLocaleString("en-US",{timeZone:"America/Los_Angeles"})}] Page load event fired`)}),await e.send("Accessibility.enable"),await e.send("Page.enable"),await e.send("DOM.enable"),await e.send("Overlay.enable"),await e.send("DOMSnapshot.enable"),await e.send("CSS.enable")}async send({method:e,params:t,timeout:n=this.defaultTimeoutMs,timeoutMsg:o}){for(;this.cdpInitializingPromise;)await V(this.cdpInitializingPromise,{milliseconds:n});if(this.cdpCrashDetails){if(this.cdpFullyDead)throw new _("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 V(this.session.send(e,t),{milliseconds:n,message:o??`Chrome command ${e} timed out after ${n}ms. This is likely an infrastructure issue caused by a lack of compute resources or a crash at the browser level.`})}catch(i){throw["Internal error","Target crashed"].some(a=>i.message.includes(a))&&!this.cdpInitializingPromise&&(this.logger.warn({err:i},`CDP crashed during CDP method ${e}, re-initializing client`),await this.reinitialize()),i}}async createRawCDPSession(e=this.defaultTimeoutMs){let t=e,n=this.pageGetter(),o=await V(this.contextGetter().newCDPSession(n),{milliseconds:t,fallback:()=>{throw this.logger.error(`Failed to initialize CDP session within the page load timeout (${n.url()})`),new _("UserInfrastructureError",`Failed to initialize CDP session within the page load timeout (${n.url()})`)}});return this.logger.debug(`Created new CDP session for ${n.url()}`),o}async reinitialize(e=this.defaultTimeoutMs){await this.cdpInitializingPromise,this.cdpInitializingPromise=(async()=>{try{let t=this.session;this.session=await this.createRawCDPSession(e),await V(this.registerHandlers(this.session),{milliseconds:e,message:`Failed to register CDP handlers within ${e}ms`}),this.logger.debug("Successfully reinitialized and attached new handlers to CDP session");try{await V(t.detach(),{milliseconds:1e3})}catch(n){this.logger.warn({err:n},"Failed to detach old CDP session after reinitialization, continuing...")}this.cdpCrashDetails=void 0,this.cdpFullyDead=!1}catch(t){this.cdpCrashDetails={...this.cdpCrashDetails??{},reinitializeError:`${t}`},this.cdpFullyDead=!0}finally{this.cdpInitializingPromise=void 0}})(),await this.cdpInitializingPromise}on(e,t){return this.session.on(e,t),this.session}off(e,t){return this.session.off(e,t),this.session}addListener(e,t){return this.session.addListener(e,t),this.session}removeListener(e,t){return this.session.removeListener(e,t),this.session}};var gi="<empty>";function OU(r){return r.includes("doubleclick.net")||r.includes("googletagmanager.com")||r.includes("googlesyndication.com")||r.includes("s.amazon-adsystem.com")||r.includes("smartadserver.com")||r.includes("omnitagjs.com")||r.includes("x.adroll.com")}function sw(r){let e=r.adFrameStatus?.adFrameType;return e==="child"||e==="root"||OU(r.url)}async function LU(r,e){let t=await r.send({timeout:te,method:"DOM.getFrameOwner",params:{frameId:e}}),o=(await r.send({timeout:te,method:"DOM.pushNodesByBackendIdsToFrontend",params:{backendNodeIds:[t.backendNodeId]}})).nodeIds[0],a=(await r.send({timeout:te,method:"DOM.describeNode",params:{backendNodeId:t.backendNodeId}})).node;return a.nodeId=o,a}async function hi({cdpClient:r,page:e,logger:t}){let n={type:"root",childFrames:[],page:e},o=[],[i,a]=await Promise.all([r.send({timeout:te,method:"Page.getFrameTree",params:{}}),r.send({timeout:te,method:"DOM.getDocument",params:{depth:0}})]),l=(i.frameTree.childFrames??[]).map(async(d,p)=>{if(sw(d.frame))return null;try{return await lw({cdpClient:r,rawFrameTree:d,indices:[p],parent:n,warnings:o,logger:t})}catch(g){return o.push(`Failed to get child frame: ${g}`),null}}),u=await Promise.all(l);return n.childFrames=u.filter(d=>d!==null),o.length&&t?.warn({warnings:o},"Got warnings when fetching frame tree"),n}async function lw({cdpClient:r,rawFrameTree:e,indices:t,parent:n,warnings:o,logger:i}){let a=e.frame.id,s=await LU(r,a),c=s.attributes??[],l=null,u=[];for(let m of["src","name","id","title","srcdoc","sandbox"]){let h=Mn(c,m);h&&(u.push(`${m}=${JSON.stringify(h)}`),m==="src"&&(l=h))}let d={type:"frame",cdpFrame:e.frame,url:e.frame.url,frameId:a,locationData:{indices:t,attributeSelectors:u},src:l,childFrames:[],parent:n,domNode:s},g=(e.childFrames??[]).map(async(m,h)=>{if(sw(m.frame))return null;try{return await lw({cdpClient:r,rawFrameTree:m,indices:[...t,h],parent:d,warnings:o,logger:i})}catch(f){return o.push(`Failed to get child frame (child ${h} of frame with url ${e.frame.url}): ${f}`),null}});return d.childFrames=(await Promise.all(g)).filter(m=>m!==null),d}async function NU(r){try{return await r.owner().count()===1}catch{return!1}}async function kU(r){try{return await r.count()===1}catch{return!1}}async function Fr(r,e){let t=[],n=r;for(;n.parent.type==="frame";)t.push(n.parent),n=n.parent;t.reverse();let o=e,i=[];for(let l of t){let u=!1;for(let d of[...l.locationData.attributeSelectors,gi]){let p=o.frameLocator(d===gi?"iframe":`iframe[${d}]`);if(await NU(p)){u=!0,o=p,i.push(d);break}}if(!u)throw new _("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[...r.locationData.attributeSelectors,gi]){let u=o.locator(l===gi?"iframe":`iframe[${l}]`);if(await kU(u)){a=u,i.push(l);break}}if(!a)throw new _("ActionFailureError",`Failed to find a unique attribute to identify target frame with url matching '${r.url}'. Please attach a unique 'id', 'name', 'title', or 'src' attribute to the frame.`);let s=await a.evaluateHandle(l=>l,{timeout:re}),c=await s.asElement().contentFrame();if(!c)throw new _("InternalWebAgentError",`Failed to load Playwright Frame for iframe with url '${r.url}'`);return await s.dispose(),{frame:c,mPathSelectorTokens:i}}function aw(r,e){let t=[...r],n=[];for(;t.length;){let o=t.shift();e(o)&&n.push(o),t.push(...o.childFrames)}return n}async function cw({page:r,frameTree:e,cache:t}){let n,o=e.childFrames,i=[];if(t.mPathSelectorTokens.length){let s=o;for(let u=0;u<t.mPathSelectorTokens.length-1;u++){let d=t.mPathSelectorTokens[u];d===gi?s=s.length===1?s[0].childFrames:[]:s=s.filter(p=>p.locationData.attributeSelectors.includes(d)).map(p=>p.childFrames).flat()}let c=[],l=t.mPathSelectorTokens[t.mPathSelectorTokens.length-1];if(l===gi?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 ${t.mPathSelectorTokens.join(" > ")}`),{resolution:{type:"auto",frame:(await Fr(n,r)).frame,handle:n,mPathSelectorTokens:t.mPathSelectorTokens,frameTree:e},logs:i};i.push(`Found ${c.length} frames with mpath ${t.mPathSelectorTokens.join(" > ")}`)}if(t.frameSrcRegex){let s=new RegExp(t.frameSrcRegex),c=aw(o,l=>!!l.src&&s.test(l.src));if(c.length===1)return n=c[0],i.push(`Found unique frame with src regex ${t.frameSrcRegex}`),{resolution:{type:"auto",frame:(await Fr(n,r)).frame,handle:n,mPathSelectorTokens:t.mPathSelectorTokens,frameTree:e},logs:i};i.push(`Found ${c.length} frames with src regex ${t.frameSrcRegex}`),t.frameSrcRegex=void 0}if(t.frameUrlRegex){let s=new RegExp(t.frameUrlRegex),c=aw(o,l=>!!l.url&&s.test(l.url));if(c.length===1)return n=c[0],i.push(`Found unique frame with url regex ${t.frameUrlRegex}`),{resolution:{type:"auto",frame:(await Fr(n,r)).frame,handle:n,mPathSelectorTokens:t.mPathSelectorTokens,frameTree:e},logs:i};i.push(`Found ${c.length} frames with url regex ${t.frameUrlRegex}`),t.frameUrlRegex=void 0}let a=o;for(let s=0;s<t.indices.length-1;s++)a=a[t.indices[s]]?.childFrames??[];if(n=a[t.indices[t.indices.length-1]],n)return i.push(`Found unique frame with indices ${t.indices.join(" > ")}`),{resolution:{type:"auto",frame:(await Fr(n,r)).frame,handle:n,mPathSelectorTokens:t.mPathSelectorTokens,frameTree:e},logs:i};throw i.push(`Found ${a.length} frames with indices ${t.indices}`),new hn("Failed to find the iframe that previously contained this element",[{type:"AUTO_FRAME",matched:!1,logs:i}])}function Rc(r){return r.type==="auto"?JSON.stringify({type:"auto",frameId:r.handle.frameId}):JSON.stringify(r)}function Dm(r){for(;r.parent.type==="frame";)r=r.parent;return r.parent}function uw(r){let e=Dm(r),t=r.src??"",n=r.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:t,desiredUrl:n}}function dw(r){return r.type==="auto"?{type:"auto",frameId:r.handle.frameId,url:r.handle.url,src:r.handle.src??"",mPathSelectorTokens:r.mPathSelectorTokens.join(" > ")}:{type:"url",url:r.url}}async function pw({frame:r,logger:e,signal:t}){let n;try{n=await r.frameElement(),await DU({frameElementHandle:n,logger:e,signal:t})}catch(o){n?e.warn({err:o},"Failed to scroll iframe into view, trying with raw JS"):e.warn("Failed to scroll iframe into view - no frame element")}finally{await n?.dispose()}}async function DU({frameElementHandle:r,logger:e,signal:t}){let n=await r.boundingBox();await Ga({promiseGenerator:async()=>r.evaluate(async i=>{let a=i.scrollTop;i.scrollIntoView({behavior:"instant",block:"center",inline:"center"}),await new Promise(c=>setTimeout(c,250));let s=Date.now();for(;Date.now()-s<1e3;){let c=i.scrollTop;if(c===a)break;a=c,await new Promise(l=>setTimeout(l,250))}}),timeoutMs:he,codePath:"scrollIframeIntoView",signal:t}),e.info({oldBb:n,newBb:await r.boundingBox()},"Successfully scrolled iframe into view")}async function mw({event:r,transformer:e,enricher:t,frame:n,lastScreenshotForRecording:o,logger:i}){let{warnings:a,error:s,properties:c}=r.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(m=>m.url());i.debug({frameUrl:l,...r},"Passive click event captured on element");let p,g;if(l)try{let m=await n.frameElement();p=await V(m?.boundingBox(),{milliseconds:te})??void 0;let h=await t.constructIframeRegex({urls:d,srcs:[],desiredUrl:l});if(h.urlRegex)g={type:"url",url:`/${h.urlRegex}/`};else throw new Error(`Got no url regex options: ${JSON.stringify(h)}`)}catch(m){i.warn({err:m},"Failed to construct iframe details for recorded action, using hardcoded URL only"),g={type:"url",url:l}}(async()=>{try{await e.recordElementAction({...r,screenshotBase64:o,frameConfig:g,frameBoundingBox:p})}catch(m){i.error({err:m},"Failed to transform passive click action")}})()}import{randomUUID as Br}from"crypto";import UU from"js-beautify";var FU=["Dead"],Cc=class{recordedSteps=new Map;callbacks;signal;generator;testId;orgId;nextStepOffset=0;logger;constructor({signal:e,callbacks:t,generator:n,testId:o,orgId:i,logger:a}){this.signal=e,this.logger=a,this.testId=o,this.orgId=i,this.callbacks={onStepRecorded:(s,c)=>{this.recordedSteps.set(c,{step:s}),t.onStepRecorded(s,c)},onActionReceived:(s,c)=>{this.recordedSteps.set(c,{step:s}),t.onActionReceived?.(s,c)}},this.generator=n}reserveIndexForCommand(e){let t=this.nextStepOffset;return this.recordedSteps.set(t,{step:{id:Br(),type:"PRESET_ACTION",command:qr(e)}}),this.nextStepOffset++,t}async recordElementAction(e){let{type:t,target:n,frameConfig:o}=e;if(this.signal.aborted){this.logger.debug("Transformer was already cleaned up, ignoring click...");return}let i,a,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,t){case"CLICK":{i="CLICK";let h=qr(i);a={id:Br(),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=qr(i);a={id:Br(),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=qr(i);a={id:Br(),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:ve(this.logger),boundingBox:l}}}};break}default:throw new Error(`Unknown action type: ${t}`)}let u;e.offset===void 0?(u=this.nextStepOffset,this.nextStepOffset++):u=e.offset,this.callbacks.onActionReceived?.(a,u);let d=e.target.browserState;try{d=UU.html(d,{indent_size:1,indent_with_tabs:!1,preserve_newlines:!1}),d=oA(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,...ve(this.logger)}})).phrase}catch(h){this.logger.error({err:h},"Error generating reverse mapping description"),p=s}let g=this.recordedSteps.get(u)?.step??a,m=g?.command;m&&"target"in m&&m.target?(m.target={type:"description",elementDescriptor:p},this.callbacks.onStepRecorded({...g,command:m},u)):this.logger.warn("Could not find existing command to update after description mapping")}recordKeystroke(e){let{key:t,combinable:n}=e;if(FU.includes(t)||this.signal.aborted)return;let o="normal";t.length>1&&(o="special");let i;if(o==="normal"){let d=qr("TYPE");i={id:Br(),type:"PRESET_ACTION",command:{...d,target:void 0,value:t,clearContent:!1}}}else{let d=qr("PRESS");i={id:Br(),type:"PRESET_ACTION",command:{...d,value:t}}}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:Br(),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:Br(),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 t=()=>{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=qr(l);u.deltaY=Math.abs(i);let d={id:Br(),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=qr(l);u.deltaX=Math.abs(i);let d={id:Br(),type:"PRESET_ACTION",command:u};this.callbacks.onStepRecorded(d,c)},o=this.recordedSteps.get(this.nextStepOffset-1);o?.step.command.type==="SCROLL_LEFT"||o?.step.command.type==="SCROLL_RIGHT"?(n(),e.deltaY>=20&&t()):(t(),e.deltaX>=20&&n())}};import{z as Um}from"zod";var HSe=Um.object({type:Um.literal("url"),url:Um.string()});var xc=class{smartWaitingTimeoutMs;pageLoadTimeoutMs;allowPartialAccessibilityTree;logger;cdpClient;pageGetter;abortSignalGetter;userControlledBrowserSettings;enricher;iconKnowledgeBase;computedStylesToFetch=["display","opacity","visibility","height","position"];activeFrameCache;activeFrameConfig;lastA11yIdToNodeMap={};lastDataMomenticIdToNodeMap={};lastSelectorToNodeMap={};lastA11yTreeRoot;lastDomGraph;allowedA11yIgnoreReasonsOverride;constructor({smartWaitingTimeoutMs:e,pageLoadTimeoutMs:t,allowPartialAccessibilityTree:n,logger:o,cdpClient:i,pageGetter:a,abortSignalGetter:s,enricher:c,iconKnowledgeBase:l,userBrowserSettings:u,allowedA11yIgnoreReasonsOverride:d}){if(this.smartWaitingTimeoutMs=e,this.pageLoadTimeoutMs=t,this.allowPartialAccessibilityTree=n,this.logger=o,this.cdpClient=i,this.pageGetter=a,this.abortSignalGetter=s,this.enricher=c,this.iconKnowledgeBase=l,this.userControlledBrowserSettings=u,this.allowedA11yIgnoreReasonsOverride=d,this.userControlledBrowserSettings.importantStyles)for(let p of this.userControlledBrowserSettings.importantStyles){let g=p.split(":");if(g.length!==2){this.logger.warn({style:p},"Invalid style property passed to importantStyles");continue}let m=g[0]?.trim(),h=g[1]?.trim();if(m===void 0||h===void 0){this.logger.warn({style:p},"Invalid style property passed to importantStyles");continue}this.computedStylesToFetch.includes(m)||this.computedStylesToFetch.push(m)}}get frameConfig(){return this.activeFrameConfig}get domGraph(){return this.lastDomGraph}get selectorToNodeMap(){return this.lastSelectorToNodeMap}get dataMomenticIdToNodeMap(){return this.lastDataMomenticIdToNodeMap}get a11yIdToNodeMap(){return this.lastA11yIdToNodeMap}get a11yTreeRoot(){return this.lastA11yTreeRoot}setActiveFrameConfig(e){e?(this.activeFrameConfig=e,this.activeFrameCache=void 0):(this.activeFrameConfig=void 0,this.activeFrameCache=void 0)}reset(){this.activeFrameCache=void 0,this.activeFrameConfig=void 0,this.lastA11yIdToNodeMap={},this.lastDataMomenticIdToNodeMap={},this.lastSelectorToNodeMap={},this.lastA11yTreeRoot=void 0,this.lastDomGraph=void 0}saveAutoFrameCacheDetails(e){if(!this.activeFrameConfig||this.activeFrameConfig.type!=="auto"||!this.userControlledBrowserSettings.autoExpandIframes)return;let t={...e,indices:this.activeFrameConfig.handle.locationData.indices,mPathSelectorTokens:this.activeFrameConfig.mPathSelectorTokens};return this.constructIframeRegexAsync(this.activeFrameConfig.handle,t),t}async getAutoFrameDetailsFromHandle(e){let t=this.pageGetter(),n=Dm(e),{frame:o,mPathSelectorTokens:i}=await Fr(e,t),a={indices:e.locationData.indices,mPathSelectorTokens:i};return this.constructIframeRegexAsync(e,a),{cache:a,config:{type:"auto",frame:o,handle:e,mPathSelectorTokens:i,frameTree:n,cache:a}}}async resolveAutoFrameCache(e){let t=this.pageGetter(),n=await hi({cdpClient:this.cdpClient,page:t,logger:this.logger}),{resolution:o,logs:i}=await cw({page:t,frameTree:n,cache:e});return this.logger.info({logs:i},"Resolved auto frame cache"),{...o,cache:e}}async resolveActiveFrameConfig({logger:e=this.logger,signal:t=this.abortSignalGetter()}){if(!this.frameConfig)return null;if(this.activeFrameCache)if(Rc(this.frameConfig)!==this.activeFrameCache.frameIdentifierStringified)this.activeFrameCache=void 0;else if(this.activeFrameCache.frame&&"isDetached"in this.activeFrameCache.frame&&this.activeFrameCache.frame.isDetached())this.activeFrameCache=void 0;else return this.activeFrameCache;let n;return this.frameConfig.type==="url"?n=await this.resolveUrlMatcherFrameConfig({config:this.frameConfig,logger:e,signal:t}):n={source:"auto",frame:this.frameConfig.frame,handle:this.frameConfig.handle,frameIdentifierStringified:Rc(this.frameConfig),cacheTime:Date.now(),frameTree:this.frameConfig.frameTree,mPathSelectorTokens:this.frameConfig.mPathSelectorTokens},await pw({frame:n.frame,logger:e,signal:t}),this.activeFrameCache=n,n}async executeFunctionInAllFrames(e,t){let n=this.pageGetter(),o=await hi({cdpClient:this.cdpClient,page:n,logger:this.logger}),i=[V(n.evaluate(e,t),{milliseconds:he})],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(Fr(c,n).then(({frame:u})=>V(u.evaluate(e,t),{milliseconds:he})).catch(u=>(this.logger.warn({err:u,frameUrl:c.url},"Failed to evaluate function in frame"),"MOMENTIC_FRAME_EVAL_ERROR"))))}return(await Promise.all(i)).filter(c=>c!=="MOMENTIC_FRAME_EVAL_ERROR")}async getAllChildFrameUrls(){let e=this.pageGetter(),t=await hi({cdpClient:this.cdpClient,page:e,logger:this.logger}),n=Array.from(t.childFrames),o=[];for(;n.length>0;){let i=n.shift();n.push(...i.childFrames),o.push(i.src??i.url)}return o}async getDomGraph({devicePixelRatio:e,signal:t,logger:n}){return this.getDOMTree({devicePixelRatio:e??1,signal:t,logger:n??this.logger})}async getA11yTree(e){let t={},n=e.logger??this.logger,o=e.abortSignal??this.abortSignalGetter(),i=this.pageGetter(),a,s,c=null;if(this.frameConfig?.type==="url"){if(a=await lr({fn:()=>this.resolveActiveFrameConfig({logger:n,signal:o}),codePath:"getActiveFrameDetails",logObject:t,signal:o,logger:n})??void 0,!a)throw new _("ActionFailureError","Got null frame details despite active frame config");s=a.handle,c=s.frameId}else this.userControlledBrowserSettings.autoExpandIframes?(s=await lr({fn:()=>hi({cdpClient:this.cdpClient,page:this.pageGetter(),logger:n}),codePath:"getMomenticFrameTree",logObject:t,signal:o,logger:n}),c=null):(s={type:"root",page:i,childFrames:[]},c=null);await lr({fn:async()=>this.addMomenticIds({rootPage:i,childFrames:s.childFrames,frameFilter:a?.frame,logger:n}),codePath:"addIdsToElement",logObject:t,signal:o,logger:n});let l=await lr({fn:()=>this.getDOMTree({devicePixelRatio:e.devicePixelRatio??1,signal:o,logger:n}),codePath:"domFetch",logObject:t,signal:o,logger:n}),u=await lr({fn:()=>this.getRawA11yGraph({cdpClient:this.cdpClient,frameId:c,childFrames:s.childFrames,logTimings:t,logger:n,signal:o}),codePath:"totalA11yFetch",logObject:t,signal:o,logger:n}),{tree:d}=await lr({fn:()=>this.composeA11yDomGraph({opts:e,a11yGraph:u,domGraph:l,startingFrameId:c,frameContext:s,logger:n,iconKnowledgeBase:this.iconKnowledgeBase,showZeroOpacityElements:e.showZeroOpacityElements,flagNotActionableNodes:e.flagNotActionableNodes}),codePath:"a11yProcess",logObject:t,signal:o,logger:n});return Object.values(t).some(p=>p>750)&&n.warn({logTimings:t},"A11y tree fetch component took a long time"),this.lastA11yIdToNodeMap=d.a11yIdNodeMap,this.lastDataMomenticIdToNodeMap=d.dataMomenticIdMap,this.lastA11yTreeRoot=d.root,this.lastDomGraph=l,this.lastSelectorToNodeMap=d.selectorToNodeMap,d}async fetchA11yTreeForRecording(e,t){if(await this.getA11yTree({devicePixelRatio:e,abortSignal:t,logger:Rn,filterByViewport:!1,flagNotActionableNodes:!1}),Math.random()<.1){let n=this.lastA11yTreeRoot?.serialize();this.logger.debug({tree:n&&n.length>4e5?"REDACTED_DUE_TO_SIZE":n},"Refreshed a11y tree during recording")}}async getLocatorFromA11yNode({page:e,root:t,node:n}){if(n.backendNodeId===void 0)throw new Error(`Node with a11y id ${n.id} has no backend node ID: ${n.getNodeOnlySerializedForm()}`);if(this.userControlledBrowserSettings.visualActions){let o=this.domGraph?.backendIdToNode[n.backendNodeId];if(!o)throw new Error(`Could not find DOM node for backend node ID ${n.backendNodeId}`);let i=WA({node:o,domGraph:this.domGraph});return $A(e,i)}else return this.getLocatorFromBackendId(t,n.backendNodeId)}async getLocatorFromBackendId(e,t){let n=await this.cdpClient.send({method:"DOM.resolveNode",params:{backendNodeId:t},timeout:he});if(!n||!n.object.objectId)throw new Error(`Could not resolve backend node ${t}`);let o;try{o=await qA(this.cdpClient,n.object.objectId)}catch(i){throw this.logger.debug({err:i,object:JSON.stringify(n.object)},"Failed to get ID attribute"),i}return e.locator(Tr(o))}getNodeUsingMPathSelector(e){let t=this.selectorToNodeMap[e];if(t)return t;let n=e.split(" > "),o="";for(let i=n.length-1;i>=0;i--){let a=n.slice(i).join(" > ");if(this.selectorToNodeMap[a]){o=a;break}}this.logger.warn({selectorMapSize:Object.keys(this.selectorToNodeMap).length,selector:e,closestSelector:o},"Could not find a11y node using mpath selector")}async resolveUrlMatcherFrameConfig({config:e,signal:t=this.abortSignalGetter(),logger:n=this.logger}){let o=Date.now(),i,a,s,c=0;for(;Date.now()-o<this.smartWaitingTimeoutMs;)try{i=await hi({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.reason==="UserInfrastructureError")throw l;c%3===0&&this.logger.warn({attempt:c,err:l},"Failed to resolve active frame, retrying..."),await ee(at,t)}finally{c++}if(a)return{source:"url",frame:a.frame,handle:a.handle,frameIdentifierStringified:Rc(e),cacheTime:Date.now(),frameTree:i,mPathSelectorTokens:[]};throw s}async getMatchingFrameByUrlWithCdp(e,t){let n=t.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=Mn(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 Fr(s,o)});break}}else if(n.trim()===d.trim()){a.push({handle:s,matchType:"url",...await Fr(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 _("ActionFailureError",`Failed to find frame with src matching: ${n}`)}async composeA11yDomGraph({opts:e,a11yGraph:t,domGraph:n,startingFrameId:o,frameContext:i,logger:a,iconKnowledgeBase:s,showZeroOpacityElements:c,flagNotActionableNodes:l}){let u=await rw({rawA11yGraph:t,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:t,frameFilter:n,logger:o}){if(this.userControlledBrowserSettings.visualActions)return;let i=await this.addMomenticIdsHelper(n??e,1);if(!this.userControlledBrowserSettings.autoExpandIframes||n)return;let a=Array.from(t),s=[];for(;a.length>0;){let c=a.shift();a.push(...c.childFrames);let l=async()=>{try{let{frame:u}=await Fr(c,e);i=await this.addMomenticIdsHelper(u,i)}catch(u){c.url!=="about:blank"&&o.warn({err:u},"Error adding momentic IDs to child frame, continuing...")}};s.push(l())}await Promise.all(s)}async addMomenticIdsHelper(e,t){if(this.userControlledBrowserSettings.visualActions)return t;let n=this.logger;return await et({root:e,fn:i=>window.addIdsToElement?.(document.body,i),arg:t,timeout:he,waitForPageLoad:async()=>{try{await e.waitForLoadState("domcontentloaded",{timeout:this.smartWaitingTimeoutMs})}catch(i){n.warn({err:i},"Error loading frame root adding momentic ids, continuing...")}},codePath:"adding Momentic element IDs to the page"})??t}getPageDomain(e){try{let t=new URL(e);if(!t.hostname)return null;let n=t.hostname.split("."),o=n.length>2?n.slice(-2).join("."):t.hostname;return`${t.protocol}//${o}`}catch{return null}}async decideChildFrameUnrollEligibility({logger:e,warnings:t,handle:n}){try{let{shouldUnroll:o,reason:i}=await this.decideChildFrameUnrollEligibilityHelper({domNode:n.domNode});return{shouldUnroll:o,reason:i}}catch(o){if(o.message.includes("Could not compute box model"))return{shouldUnroll:!1};let i=`Got error when determining whether to filter frame ${n.frameId} with url ${n.url}, allowing it to be fetched: ${o}`;return t?.push(i),e?.warn({err:o},i),{shouldUnroll:!0}}}async decideChildFrameUnrollEligibilityHelper({domNode:e}){let t=e.attributes??[];if(Mn(t,"aria-hidden")==="true")return{shouldUnroll:!1,reason:"aria-hidden"};let n=Mn(t,"style");if(n?.includes("display: none")||n?.includes("visibility: hidden"))return{shouldUnroll:!1,reason:"hidden CSS style"};await this.cdpClient.send({timeout:te,method:"DOM.pushNodesByBackendIdsToFrontend",params:{backendNodeIds:[e.backendNodeId]}});let[o,i]=await Promise.all([this.cdpClient.send({timeout:te,method:"DOM.getBoxModel",params:{backendNodeId:e.backendNodeId}}),this.cdpClient.send({timeout:te,method:"CSS.getComputedStyleForNode",params:{nodeId:e.nodeId}})]);if(!o.model||!o.model.height||!o.model.width)return{shouldUnroll:!1,reason:"no bounding box"};if(o.model.height<10||o.model.width<10)return{shouldUnroll:!1,reason:"small bounding box"};for(let a of i.computedStyle){if(a.name==="display"&&a.value==="none")return{shouldUnroll:!1,reason:"display: none"};if(a.name==="visibility"&&a.value==="hidden")return{shouldUnroll:!1,reason:"visibility: hidden"};if(a.name==="opacity"&&a.value==="0")return{shouldUnroll:!1,reason:"opacity: 0"}}return{shouldUnroll:!0}}async getRawA11yGraph({cdpClient:e,frameId:t,childFrames:n,logTimings:o,logger:i=this.logger,signal:a=this.abortSignalGetter()}){let s=[];try{await this.pageGetter().waitForLoadState("load",{timeout:this.pageLoadTimeoutMs})}catch(g){i.warn({err:g},"Failed to wait for page load event before a11y tree fetch, attempting to continue without it..."),await this.cdpClient.reinitialize()}let c,l;for(let g=0;g<3;g++)try{l=await lr({fn:()=>this.getRawA11yTreeForFrame({frameId:t,timeoutMs:this.pageLoadTimeoutMs,logTimings:o}),codePath:"a11y-tree-fetch-root",logObject:o,logger:i});break}catch(m){c=m,i.warn({err:m},"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[t??"root"]=l,!this.userControlledBrowserSettings.autoExpandIframes)return u;let d=Array.from(n),p=[];for(;d.length>0;){let g=d.shift();try{let{shouldUnroll:h}=await this.decideChildFrameUnrollEligibility({handle:g,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 ${g.frameId} with url ${g.url}, allowing it to be fetched: ${h}`)}d.push(...g.childFrames);let m=async()=>{try{let h=await lr({fn:()=>this.getRawA11yTreeForFrame({frameId:g.frameId,timeoutMs:this.smartWaitingTimeoutMs,logTimings:o}),codePath:`a11y-tree-fetch-child-${g.frameId}`,logObject:o,logger:i});u[g.frameId]=h}catch(h){i.warn({err:h,url:g.url,src:g.src},`Error getting raw a11y tree for child frame ${g.frameId}, continuing...`)}};p.push(m())}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:t,logTimings:n}){let o;if(this.allowPartialAccessibilityTree)o=(await lr({fn:()=>this.cdpClient.send({method:"Accessibility.getFullAXTree",params:{frameId:e??void 0},timeout:t,timeoutMsg:`Fetching the document tree took over ${t}ms. This usually indicates that the current page is too large to be loaded at once, or your machine is severely resource constrained.`}),codePath:"cdp-query-ax-tree",logObject:n,logger:this.logger})).nodes;else{let a=(await lr({fn:()=>this.cdpClient.send({method:"Accessibility.getRootAXNode",params:{frameId:e??void 0},timeout:he}),codePath:"cdp-get-root-ax-node",logObject:n,logger:this.logger})).node.backendDOMNodeId;o=(await lr({fn:()=>this.cdpClient.send({method:"Accessibility.queryAXTree",params:{backendNodeId:a},timeout:t,timeoutMsg:`Fetching the document tree took over ${t}ms. This usually indicates that the current page is too large to be loaded at once, or your machine is severely resource constrained.`}),codePath:"cdp-query-ax-tree",logObject:n,logger:this.logger})).nodes}if(!o||o.length<=1)throw new Error("Document is entirely empty");return{root:o[0],allNodes:o}}async getDOMTree({devicePixelRatio:e,signal:t,logger:n}){let o,i=0,a;for(;!o&&i<3;)try{if(o=await this.cdpClient.send({method:"DOMSnapshot.captureSnapshot",params:{computedStyles:this.computedStylesToFetch},timeout:te}),!o||!o.documents.length)throw new Error("Got empty DOM tree")}catch(s){await ee(at,t),i++,a=s}if(!o||!o.documents.length)throw n.error({err:a},"Fatal error fetching DOM tree"),new _("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 VA({snapshot:o,devicePixelRatio:e,computedStylesToFetch:this.computedStylesToFetch,logger:n})}constructIframeRegexAsync(e,t){if(t.frameSrcRegex||t.frameUrlRegex)return;let n=uw(e);(async()=>{try{let o=await this.enricher?.constructIframeRegex(n);o?.srcRegex&&(t.frameSrcRegex=o.srcRegex),o?.urlRegex&&(t.frameUrlRegex=o.urlRegex),this.logger.debug({result:o,params:n},"Constructed iframe regex for cache")}catch(o){this.logger.warn({err:o},"Failed to construct iframe regex, skipping...")}})()}};function Fm(r){let e=[],t="";for(let n of r)n==="+"&&t?(e.push(t),t=""):t+=n;return e.push(t),e}var qa=class r{static USER_AGENT=yc;abortSignal=void 0;contextInitialized=!1;browser;context;properties;page;userControlledBrowserSettings;pageLoadPromises={};lastTabChangeEventTimeout=void 0;clientCallbacks;iconKnowledgeBase;cdpClient;debugData={logsPerPage:[],harPages:{},harEntries:{}};recentFrameNavigations={};requestRecorders={};mocks={};customHeaders=[];enricher;storage;logger;stateManager;transformer;lastScreenshotForRecording=void 0;originsVisited=new Set;viewport;videos=[];baseUrl;constructor({storage:e,enricher:t,browser:n,context:o,page:i,baseUrl:a,logger:s,userBrowserSettings:c,viewport:l,properties:u,clientCallbacks:d,iconKnowledgeBase:p}){if(KT(c),this.storage=e,this.enricher=t,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,u.recordVideo){let g=this.page.video();g&&this.videos.push(g)}this.iconKnowledgeBase=p}registerAbortSignal(e){this.abortSignal=e}async initialize({grantPermissions:e,runInitScripts:t}){if(this.contextInitialized)return;this.userControlledBrowserSettings.extraHeaders&&await this.context.setExtraHTTPHeaders(this.userControlledBrowserSettings.extraHeaders),e&&await this.context.grantPermissions(["clipboard-read","clipboard-write","microphone","camera","geolocation"]);let n={[Sc]:this.userBrowserSettings.visualActions},o=[this.context.addInitScript({content:em.htmlUtilsLibJs}),this.context.addInitScript({content:`window._MOMENTIC_BROWSER = true; window._MOMENTIC_FEATURE_FLAGS = ${JSON.stringify(n)}; window.addEventListener('load', (event) => { console.log('[MOMENTIC] Page loaded'); });`}),this.exposeRecordingBindings()],i=a=>this.handleNewPageEvent(a);this.context.on("page",i),this.handleNewPageEventHelper(this.page),this.context.on("close",()=>{this.context.off("page",i)}),await Promise.all(o),t&&(await this.page.addScriptTag({content:em.htmlUtilsLibJs}),await this.page.addScriptTag({content:`window._MOMENTIC_BROWSER = true; window._MOMENTIC_FEATURE_FLAGS = ${JSON.stringify(n)}; window.addEventListener('load', (event) => { console.log('[MOMENTIC] Page loaded'); });`})),this.properties.systemDevicePixelRatio||(process.env.MOMENTIC_LOCAL_DEV==="1"&&WU()==="darwin"&&BU("system_profiler SPDisplaysDataType").toString().includes("Retina")?(x.warn("[DEV] Setting device pixel ratio to 2 in local dev since a Retina display was detected"),this.properties.systemDevicePixelRatio=2):this.properties.systemDevicePixelRatio=await this.page.evaluate(()=>window.devicePixelRatio)),this.cdpClient=await wc.init({logger:this.logger,contextGetter:()=>this.context,pageGetter:()=>this.page,defaultTimeoutMs:this.pageLoadTimeout}),await this.initializeScreencast(),this.stateManager=new xc({smartWaitingTimeoutMs:this.smartWaitingTimeout,pageLoadTimeoutMs:this.pageLoadTimeout,allowPartialAccessibilityTree:this.userControlledBrowserSettings.allowPartialAccessibilityTree??!1,logger:this.logger,cdpClient:this.cdpClient,pageGetter:()=>this.page,abortSignalGetter:()=>this.abortSignal,enricher:this.enricher,iconKnowledgeBase:this.iconKnowledgeBase,userBrowserSettings:this.userBrowserSettings,allowedA11yIgnoreReasonsOverride:this.properties.allowedA11yIgnoreReasonsOverride}),this.contextInitialized=!0}async fixViewportForNewHeadless(){this.properties.isNewHeadless&&this.viewport&&await this.cdpClient.send({method:"Emulation.setDeviceMetricsOverride",params:{width:this.viewport.width,height:this.viewport.height,deviceScaleFactor:0,mobile:this.viewport.width<1e3}})}async initializeScreencast(){await this.fixViewportForNewHeadless(),this.clientCallbacks?.onScreencastFrame&&this.viewport&&(await this.cdpClient.send({method:"Page.startScreencast",params:{format:"jpeg",quality:75,maxWidth:this.viewport.width,maxHeight:this.viewport.height}}),this.cdpClient.on("Page.screencastFrame",e=>{let t=e.sessionId,n=Buffer.from(e.data,"base64");this.lastScreenshotForRecording=n,this.clientCallbacks?.onScreencastFrame?.(n,()=>{(async()=>{try{await this.cdpClient.send({method:"Page.screencastFrameAck",params:{sessionId:t}})}catch{}})()})}))}static async init(e){let t=await OA(e),n=new r(t);return await n.initialize({grantPermissions:!0,runInitScripts:!1}),n}static async fromExistingContext({context:e,storage:t,enricher:n,userBrowserSettings:o,properties:i,logger:a}){let s=e.pages()[0];if(!s)throw new Error("No page found in existing context");let c=s.viewportSize();c||(c=await s.evaluate(()=>({width:window.innerWidth,height:window.innerHeight})));let l=s?.url(),u=new r({browser:e.browser(),context:e,page:s,baseUrl:l,logger:a,storage:t,enricher:n,userBrowserSettings:o,viewport:c,properties:i,clientCallbacks:void 0,iconKnowledgeBase:null});return await u.initialize({grantPermissions:!1,runInitScripts:!0}),u}async handleAvailableTabsChangeHelper(){try{let e=await Mm(this.context,{getTitles:!0}),t=this.page.url();this.clientCallbacks?.onTabsChange?.(e,t)}catch(e){this.logger.error({err:e},"Error sending available tabs to frontend")}}handleAvailableTabsChange(){try{clearTimeout(this.lastTabChangeEventTimeout),this.lastTabChangeEventTimeout=setTimeout(()=>this.handleAvailableTabsChangeHelper(),500)}catch(e){this.logger.warn({err:e},"Error handling available tabs change")}}addToPageLoadPromises(e,t){let n=Bm(),o=`${e}-${n}`,i=Date.now(),a=!1,s=async()=>{try{await V(t(),{signal:this.abortSignal,milliseconds:this.pageLoadTimeout,message:`Page load promise for code path ${e} timed out after ${this.pageLoadTimeout}ms`})}catch(c){c.name!=="AbortError"&&this.logger.error({err:c,promiseKey:o,codePath:e,duration:Date.now()-i},`Page load promise for code path ${e} encountered error`)}finally{delete this.pageLoadPromises[o],a=!0}};this.pageLoadPromises[o]=s().catch(()=>{}),a&&delete this.pageLoadPromises[o]}handlePageClosedEvent(e){if(this.page!==e){this.logger.debug({url:e.url()},"Detected background page was closed, just updating available tabs only"),this.handleAvailableTabsChange();return}let t=async()=>{if(this.closed)return;this.logger.info({url:e.url()},"Detected active page was closed, switching to another tab");let n=this.context.pages();for(let o=n.length-1;o>=0;o--){let i=n[o];if(!(!i||i.isClosed()||!co(i.url()))){this.logger.info(`Automatically switching to tab ${o} after close: ${i.url()}`),await this.switchToPage({type:"INDEX",index:String(o)});break}}};this.addToPageLoadPromises("page closed handler",async()=>t())}handleNewPageEvent(e){let t=e.url();if(this.logger.info({url:t},"Detected new page event, registering handlers and waiting for load to complete"),this.properties.recordVideo){let n=e.video();n&&this.videos.push(n)}try{this.handleNewPageEventHelper(e)}catch(n){this.logger.warn({err:n},"Error handling new page open, continuing....")}}handleNewPageEventHelper(e){let t=Bm(),n="new-page-load-handler";e.on("close",a=>this.handlePageClosedEvent(a)),e.on("framenavigated",a=>this.handleFrameNavigationEvent(a)),e.on("crash",()=>{this.logger.error("Page crashed at the Playwright level!")});let o=this.context.pages().indexOf(e);e.on("console",a=>{SA(e,o,this.debugData,a,this.logger)});let i=async()=>{await EA(t,this.debugData,e),await e.route("**/*",async(a,s)=>{await ym({pageId:t,route:a,request:s,debugData:this.debugData,logger:this.logger,requestRecorders:this.requestRecorders,mocks:this.mocks})}),await e.route("**/*",RA(this.customHeaders,this.logger)),wn&&await e.route("**/*",Wa),await this.loadFrameAndRecordUrl({root:e,codePath:n}),this.handleAvailableTabsChange()};this.addToPageLoadPromises(n,async()=>i())}async handleCollectSvgs(e){}handleFrameNavigationEvent(e){let t=e.url(),n=e.parentFrame()?"has-parent":"no-parent",o=`frame-navigation-handler-${t.slice(0,50)} (${n})`;if(!t||t==="about:blank"||!co(t)||this.recentFrameNavigations[o]&&Date.now()-this.recentFrameNavigations[o]<1e3)return;this.recentFrameNavigations[o]=Date.now();let i=async()=>{try{if(e.isDetached())return;await this.loadFrameAndRecordUrl({root:e,codePath:o}),this.handleAvailableTabsChange(),!e.parentFrame()&&!e.isDetached()&&this.clientCallbacks?.onSvgsCollected&&(setTimeout(()=>{(async()=>{try{await this.handleCollectSvgs(e)}catch(s){this.logger.warn({err:s},"Failed to collect SVGs on page, continuing...")}})()},5e3),this.transformer&&await this.injectKnowledgeBaseIntoBrowser(e))}catch(a){a.name!=="AbortError"&&this.logger.warn({err:a,url:t,codePath:o},"Failed to handle frame navigation event, continuing...")}};this.addToPageLoadPromises(o,async()=>i())}async injectKnowledgeBaseIntoBrowser(e){try{if(!this.iconKnowledgeBase||await e.evaluate(()=>!!window._MOMENTIC_ICON_KNOWLEDGE_BASE))return;let n={};Object.keys(this.iconKnowledgeBase).forEach(o=>{this.iconKnowledgeBase[o]?.description&&(n[o]=this.iconKnowledgeBase[o].description)}),await e.evaluate(o=>{let i=window;i._MOMENTIC_ICON_KNOWLEDGE_BASE=o},n)}catch(t){this.logger.warn({err:t},"Failed to inject icon knowledge base into browser, continuing...")}}getBrowserCallbacks(){return{waitForPageLoad:()=>this.waitForPageLoad(),waitForUrl:e=>this.waitForUrl(e),getBrowserState:e=>this.getBrowserState(e),waitForDomStability:e=>this.waitForDOMStability(e),state:{url:()=>this.url(),getDomGraph:()=>this.stateManager.domGraph,getOpenPages:()=>this.getOpenPages(),getRoot:()=>this.getActivePageOrFrame(),userBrowserSettings:this.userBrowserSettings},pageLoadTimeoutMs:this.pageLoadTimeout,signal:this.abortSignal}}ping(){if(this.closed)throw new Error("Page has been closed")}setActiveFrameConfig(e){this.stateManager.setActiveFrameConfig(e)}async reset(e){for(this.abortSignal=void 0,this.debugData.logsPerPage=[],this.debugData.harPages={},this.debugData.harEntries={},this.pageLoadPromises={};this.videos.length>0;)this.videos.pop();await this.clearAuthState({closeNonActiveTabs:!0}),await this.stopScreencast(),await this.reinitializeCDPClient(),await this.navigate({url:e.newUrl??this.baseUrl,initialNavigation:!0,loadTimeoutMs:e.timeout}),this.stateManager.reset()}async clearHighlights(){try{await V(Cm(this.getBrowserCallbacks()),{milliseconds:re})}catch(e){this.logger.debug({err:e},"Failed to clear highlights, continuing...")}}async cleanup(){this.abortSignal=void 0;try{this.originsVisited.clear(),await this.context.close(),await this.browser?.close(),this.browser=null}catch(e){this.logger.warn({err:e},"Error cleaning up browser, continuing...")}finally{this.browser=null}}get closed(){return this.context.pages().every(e=>e.isClosed())||!!this.browser&&!this.browser.isConnected()}async ensureMomenticBrowserScriptsLoaded(e,t,n){let o=Date.now(),i=0,a=0;for(;Date.now()-o<tm;){a++,n?.throwIfAborted();try{if(await et({fn:()=>{let c=window;return!!(c.generateCssSelectors&&c.evaluateCssSelectors&&c.evaluatePrimaryCaches&&c.generateHtmlCacheAttributes&&c.ldist)},timeout:re,arg:void 0,waitForPageLoad:()=>this.waitForPageLoad(),root:e,codePath:"ensuring Momentic system scripts are loaded"}))return}catch(s){if(i++,i>=3){t.warn({err:s},"Multiple errors checking if Momentic scripts are loaded, aborting...");return}}await ee(at),a%2===0&&t.warn("Still waiting for momentic browser scripts to load...")}throw new Error(`Failed to load momentic browser scripts on page ${e.url()}`)}async html(){let e=await this.getActivePageOrFrame();return await this.ensureMomenticBrowserScriptsLoaded(e,this.logger),et({root:e,fn:()=>{let t=window;if(!t?.getFullHtmlTree)throw new Error("Missing Momentic HTML library when fetching page HTML");return t.getFullHtmlTree()},arg:void 0,timeout:te,waitForPageLoad:()=>this.waitForPageLoad(),codePath:"getting the full HTML tree"})}url(){return this.page.url()}async stabilizePageForScreenshot(){try{await this.evaluateFunctionInPage(()=>{let e=window,t=[],n=new Map;document.querySelectorAll("input,textarea,[contenteditable]").forEach(o=>{n.set(o,{value:o.style.getPropertyValue("caret-color"),priority:o.style.getPropertyPriority("caret-color")}),o.style.setProperty("caret-color","transparent","important")}),t.push(()=>{for(let[o,i]of n)o.style.setProperty("caret-color",i.value,i.priority)}),e._MOMENTIC_SCREENSHOT_CLEANUP=()=>{for(let o of t)o();delete e._MOMENTIC_SCREENSHOT_CLEANUP}},void 0,"stabilizing page for screenshot")}catch(e){(!(e instanceof Error)||!e.message.includes("Execution context was destroyed"))&&this.logger.warn({err:e},"Failed to stabilize page before screenshot, continuing...")}}async removeScreenshotStabilization(){try{await this.evaluateFunctionInPage(()=>{window._MOMENTIC_SCREENSHOT_CLEANUP?.()},void 0,"removing screenshot stabilization")}catch{}}async screenshot(e){let{retries:t=1,stabilizeBeforeScreenshot:n=!1}=e,o=this.page.url();n&&await this.stabilizePageForScreenshot();let i=Date.now();try{await this.fixViewportForNewHeadless();let a=await this.screenshotHelper({...e,retries:t});if(a.byteLength>5e6)this.logger.error("Page screenshot is greater than 5MB, which may cause performance issues with some AI models");else if(a.length===0)throw new Error("Got empty screenshot");return a}catch(a){if(t<=0||a.message.includes("has been closed"))throw a;return this.logger.warn({err:a,pageUrl:o},"Failed taking screenshot, retrying..."),await ee(pi),this.screenshot({...e,retries:t-1})}finally{Date.now()-i>1e3&&this.logger.warn({pageUrl:o,duration:Date.now()-i},"Screenshot took longer than expected"),n&&await this.removeScreenshotStabilization()}}async screenshotHelper({locator:e,quality:t,saveToDiskPath:n,timeout:o,respectActiveFrame:i,clearHighlights:a=!1}){a&&await this.clearHighlights(),i&&this.stateManager.frameConfig&&(e=await(await this.getActivePageOrFrame()).frameElement());let s=await this.cdpClient.send({method:"Page.captureScreenshot",params:{format:"jpeg",quality:t,optimizeForSpeed:!0},timeout:o??he}),c=Buffer.from(s.data,"base64"),l=await hw.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&&GU(n,c),this.lastScreenshotForRecording=c,!e)return c;let p=await e.boundingBox({timeout:te});if(!p)throw new Error("Attempted to screenshot an element that is not visible on the page");let{x:g,y:m,width:h,height:f}=p;if(!h||!f)throw new Error("Attempted to screenshot an element with zero width or height");g=Math.floor(g),m=Math.floor(m),h=Math.floor(h),f=Math.floor(f);try{let E=await hw.fromBuffer(c),S=E.bitmap.width,A=E.bitmap.height;g=Math.max(0,Math.min(g,S-1)),m=Math.max(0,Math.min(m,A-1)),h=Math.max(1,Math.min(h,S-g)),f=Math.max(1,Math.min(f,A-m)),c=await E.crop({x:g,y:m,w:h,h:f}).getBuffer("image/jpeg")}catch(E){throw new Error(`Failed taking element screenshot at coordinates (${g}, ${m}) with size (${h}, ${f}): ${E}`)}finally{"dispose"in e&&await e?.dispose()}return c}getViewport(){if(this.viewport)return this.viewport;let e=this.page.viewportSize();return e||null}async navigate({url:e,initialNavigation:t=!1,loadTimeoutMs:n=this.pageLoadTimeout}){eA(e)&&(e=new URL(e,this.baseUrl).toString());let o=Date.now();t||(await this.waitForPageLoad(),await this.waitForDOMStability());let i=!1,a;for(let c=0;c<3;c++)try{await this.page.goto(e,{timeout:n,waitUntil:"domcontentloaded"}),i=!0;break}catch(l){if(a=l,this.abortSignal?.throwIfAborted(),this.logger.warn({err:l},`Error occurred during navigation${c===0?", retrying...":" (fatal)"}`),await ee(at),a.message.includes("Timeout")&&a.message.includes("exceeded")||a.message.includes("net::ERR_CONNECTION_REFUSED"))break;await this.cdpClient.send({method:"Page.stopLoading",params:{},timeout:re})}if(!i)throw new _("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(uA.has(s))throw new _("UserInfrastructureError",`${e} took too long to load \u{1F61E}. Please ensure the site is accessible and returns content within the page load timeout.`);await this.fixViewportForNewHeadless()}async type(e,t={},n=!1){await this.directTypeHelper(e,t,n)}async getActiveElement(e){try{return await et({root:e,fn:()=>{let n=document.activeElement?.textContent??void 0;return n&&n.length>100&&(n=n.slice(0,100)+"...[TRUNCATED]"),document.activeElement?{tag:document.activeElement.tagName.toLowerCase(),contentEditable:document.activeElement.getAttribute("contenteditable")??void 0,textContent:n}:void 0},arg:void 0,timeout:re,waitForPageLoad:()=>this.waitForPageLoad(),codePath:"getting the active element"})}catch(t){this.logger.warn({err:t},"Failed to get active element");return}}async directTypeHelper(e,t={},n=!1){let o=await this.getActivePageOrFrame();await DA({root:o,text:e,options:t,logger:this.logger,callbacks:this.getBrowserCallbacks()});let i=await this.getActiveElement(o);if(n){let a=Date.now();for(;Date.now()-a<this.smartWaitingTimeout&&(!i||i.tag==="body");)await ee(pi),this.abortSignal?.throwIfAborted(),i=await this.getActiveElement(o);i||this.logger.warn("No active element found to type into, attempting anyways")}t.clearContent&&(t.forceClearContent||i?.tag==="input"||i?.tag==="textarea"?(this.properties.isAndroid?await this.page.keyboard.press("Control+A"):process.platform==="darwin"?await this.page.keyboard.press("Meta+A"):await this.page.keyboard.press("Control+A"),await this.page.keyboard.press("Backspace"),await this.page.waitForTimeout(25)):this.logger.info({activeElementDetails:i},"Currently active element is not eligible for replace content, skipping...")),await this.page.keyboard.type(e,{delay:t.delay??Cy}),t.pressEnter&&await this.press("Enter",{})}async scrollIntoViewIfNeeded(e){try{await e.scrollIntoViewIfNeeded({timeout:he})}catch(t){this.logger.warn({err:t},"Failed to scroll into view, trying with raw JS");try{await e.evaluate(async n=>{let o=n.scrollTop;n.scrollIntoView(),await new Promise(a=>setTimeout(a,250));let i=Date.now();for(;Date.now()-i<1e3;){let a=n.scrollTop;if(a===o)break;o=a,await new Promise(s=>setTimeout(s,250))}},void 0,{timeout:he})}catch(n){this.logger.warn({err:n},"Failed to scroll into view using JS, continuing...")}}}async highlightA11yId(e){try{let{resolution:t}=await this.createTargetFromA11yId({id:e,description:null,targetSource:"AI",skipSaveToCache:!0});return await this.highlight(t.locator),!0}catch(t){return this.logger.debug({err:t,id:e},"Failed to highlight target"),!1}}async highlight(e){return vc({locator:e,callbacks:this.getBrowserCallbacks(),logger:this.logger})}recordUrlVisited(e){try{let t=new URL(e).origin;if(t==="null")return;this.originsVisited.add(t)}catch(t){this.logger.warn({err:t},"Failed to record origin visited")}}async waitForPageLoad(){let e=Date.now(),t=Object.values(this.pageLoadPromises),n=Object.keys(this.pageLoadPromises),o=-1,i=0;for(;t.length!==0;){if(Date.now()-e>this.pageLoadTimeout&&this.logger.error({outstandingPromiseKeys:n,outstandingPromises:t},"Still waiting on page load promises"),Date.now()-o<20&&(i++,i>2)){this.logger.error({outstandingPromiseKeys:n,outstandingPromises:t},"Synchronous waiting loop detected, exiting page load wait");return}o=Date.now(),await Promise.allSettled(t),t=Object.values(this.pageLoadPromises),n=Object.keys(this.pageLoadPromises)}}async clearAuthState(e){await this.context.clearCookies();for(let o of this.originsVisited)this.logger.debug({origin:o},`Clearing data using CDP for origin ${o}`),await this.cdpClient.send({method:"Storage.clearDataForOrigin",params:{origin:o,storageTypes:"all"},timeout:re}),this.originsVisited.delete(o);let t=this.context.pages().indexOf(this.page),n=[...this.context.pages()];for(let o=0;o<n.length;o++){let i=n[o];if(i.isClosed())continue;let a=i.url();try{this.originsVisited.delete(new URL(a).origin)}catch{}await fA(i,this.logger),o!==t&&e.closeNonActiveTabs&&(this.logger.info(`Closing tab ${o} with URL ${a}`),await i.close())}}async loadAuthState(e){await this.waitForPageLoad(),await this.waitForDOMStability(),!e||Object.keys(e).length===0?await this.clearAuthState({closeNonActiveTabs:!1}):await this.loadAuthStateHelper(e),await this.refresh(),await this.waitForDOMStability()}async loadAuthStateHelper(e){let t=[];for(let i of e.cookies??[]){let a=await this.setCookie(i);t=t.concat(a)}this.logger.info(`Loaded ${e.cookies?.length??0} cookies`),await this.cdpClient.send({method:"DOMStorage.enable",params:void 0,timeout:re});let n=0;for(let i of e.origins??[])for(let a of i.localStorage)try{await this.cdpClient.send({timeout:re,method:"DOMStorage.setDOMStorageItem",params:{storageId:{securityOrigin:new URL(i.origin).origin,isLocalStorage:!0},key:a.name,value:a.value}}),n++}catch(s){this.logger.warn({err:s,origin:i},"Failed to set local storage entry, continuing...");break}this.logger.info(`Loaded ${n} local storage entries`);let o=e.idb;o&&Object.keys(o).length>0&&(await hA(this.page,o,this.logger),this.logger.info(`Loaded ${Object.keys(o??{}).length} indexedDB databases`))}async saveAuthState(){let t=0,n=null;for(;t<=2;)try{await this.waitForPageLoad(),await this.waitForDOMStability();let o=await this.context.storageState();return o.idb=await gA(this.page,this.logger),o}catch(o){if(n=o,t++,t<=2){this.logger.warn({err:o,retryCount:t,maxRetries:2},`Error saving auth state, retrying (${t}/2)...`);let i=Math.pow(2,t)*100;await new Promise(a=>setTimeout(a,i))}}throw this.logger.error({err:n},"Failed to save auth state after 2 retries"),new _("ActionFailureError",`Failed to save auth state: ${n?.message}`)}async getOpenPages(e){return Mm(this.context,e)}saveA11yDetailsToCache(e,t){t.content=e.content,t.name=e.name,t.role=e.role,t.numChildren=e.children.length,delete t.serializedForm,delete t.nodeOnlySerializedForm}async updateCacheWithNewNodeDetails({node:e,target:t,locator:n,startingBoundingBox:o,allowNotActionableNodesOverride:i,logger:a=this.logger}){if(e&&this.saveA11yDetailsToCache(e,t),t.frameCache=this.stateManager.saveAutoFrameCacheDetails(t.frameCache),n)try{let s=await this.fetchHtmlAttributes({locator:n,logger:a,startingBoundingBox:o,allowNotActionableNodesOverride:i});s?(t.generatedSelectors=s.generatedSelectors,t.serializedHtml=s.serializedHtml,t.nodeOnlySerializedHtml=s.nodeOnlySerializedHtml,t.hybridSelector=s.hybridSelector):a.warn("Got undefined HTML attributes when trying to update cache")}catch(s){if(s instanceof Pr)throw a.warn({err:s},"Cache attributes disqualify found element"),s;a.warn({err:s},"Failed to fetch HTML attributes for target, continuing...")}try{await this.saveElementVisualAttributes({target:t,locator:n,logger:a,boundingBox:o})}catch(s){a.debug({err:s},"Failed to save element visual details, continuing...")}}async saveElementVisualAttributes({target:e,locator:t,logger:n,boundingBox:o}){if(!t)return{scrollPerformed:!1};if(!im.includes(e?.role??""))return{scrollPerformed:!1};if(await this.scrollIntoViewIfNeeded(t),o||(o=await t.boundingBox({timeout:te})),!o||!o.width||!o.height)return n.debug("Skipping visual attributes saving for element with no bounding box after action"),e.boundingBox=void 0,e.screenshotUrl=void 0,{scrollPerformed:!0};let{x:i=0,y:a=0,width:s=0,height:c=0}=o;if(e.boundingBox&&Math.abs(e.boundingBox.width-s)<1&&Math.abs(e.boundingBox.height-c)<1&&Math.abs((e.boundingBox.x??0)-i)<1&&Math.abs((e.boundingBox.y??0)-a)<1)return{scrollPerformed:!0};e.boundingBox=o;let l=await this.screenshot({locator:t,quality:75,retries:0});return e.screenshotUrl=await this.storage.uploadScreenshot(l),{scrollPerformed:!0}}async resolveAutoFrameCache(e){return this.stateManager.resolveAutoFrameCache(e)}async getElementRequiredValues({locator:e,requirements:t}){let n={};if(t?.boundingBox){let o=await e.boundingBox({timeout:te});if(!o||!o.width||!o.height)throw new _("ActionFailureError","Element does not have a bounding box as required");n.boundingBox=o??void 0}if(t?.text){let o=await e.innerText({timeout:te});n.text=o?.trim()}if(t?.attributes&&t.attributes.length>0){let o={};for(let i of t.attributes){let a=i.trim().toLowerCase();if(!(!a||sr.bannedAiRequiredCacheAttributes.includes(a)))try{let s=await e.getAttribute(a,{timeout:te});s!==null&&(o[i]=s)}catch(s){this.logger.warn({err:s,attr:i},"Failed to fetch required attribute, continuing...")}}n.attributes=o}return n}async getAdditionalElementDetails({mainLocator:e,additionalElement:t,root:n,logger:o}){let i=this.stateManager.a11yIdToNodeMap[t.id];if(!i)return;let a=await this.stateManager.getLocatorFromA11yNode({page:this.page,root:n,node:i});if(e.contentFrame!==a.contentFrame)return;let s=await this.fetchHtmlAttributes({locator:a,logger:o});if(!s?.generatedSelectors||s.generatedSelectors.length===0)return;let c={selectors:s.generatedSelectors};return t.requirements&&(c.requirements=await this.getElementRequiredValues({locator:a,requirements:t.requirements})),c}async getAdditionalElementsDetails({mainElementId:e,mainLocator:t,additionalElements:n,root:o,logger:i}){let a=new Set,s=[];for(let c of n)try{if(c.id===e||a.has(c.id))continue;let l=await this.getAdditionalElementDetails({mainLocator:t,additionalElement:c,root:o,logger:i});if(a.add(c.id),!l)continue;s.push(l)}catch(l){this.logger.warn({err:l,additionalElement:c},"Failed to fetch additional element details, continuing...")}return s}async updateCacheWithAdditionalRequirements({mainElementId:e,requirements:t,additionalElements:n,target:o,locator:i,root:a,logger:s}){t&&(o.requirements=await this.getElementRequiredValues({locator:i,requirements:t})),n&&(o.additionalElements=await this.getAdditionalElementsDetails({mainElementId:e,mainLocator:i,additionalElements:n,root:a,logger:s}))}async createTargetFromA11yId({id:e,description:t,targetSource:n,skipSaveToCache:o,logger:i=this.logger,requirements:a,additionalElements:s}){if(e<0)throw new _("InternalWebAgentError","Only positive IDs should be passed to resolveAllyIdToTarget");let c=this.stateManager.a11yIdToNodeMap[e];if(!c)throw new _("InternalWebAgentError",`Resolving target failed because id ${e} does not exist on the page. This generally indicates an incorrect element was targeted.`);let l=this.stateManager.frameConfig,u,d,p,g;if(this.userBrowserSettings.autoExpandIframes&&!l&&c.parentFrame){let S=c.parentFrame,{cache:A,config:C}=await this.stateManager.getAutoFrameDetailsFromHandle(S);d=A,p=C,u=C.frame,g="auto iframe"}else c.parentFrame&&l?(p=l,u=await this.getActivePageOrFrame(),g="hardcoded url already on the state manager"):(u=await this.getActivePageOrFrame(),g="should not be possible");let m=await this.stateManager.getLocatorFromA11yNode({page:this.page,root:u,node:c}),h={id:e,inputDescription:t??void 0,targetSource:n,targetUpdateTime:new Date().toISOString(),targetUpdateLoggerTags:ve(i),frameCache:d},f,E=!1;o||(p&&(i.info({frameConfigSource:g,frameConfig:dw(p)},"A11y node was resolved to a target within an iframe"),f=this.stateManager.frameConfig,this.stateManager.setActiveFrameConfig(p),E=!0),await this.updateCacheWithNewNodeDetails({node:c,target:h,locator:m,logger:i,allowNotActionableNodesOverride:!0}),await this.updateCacheWithAdditionalRequirements({mainElementId:e,requirements:a,additionalElements:s,target:h,root:u,locator:m,logger:i}));try{return{resolution:{locator:m,a11yNode:c,displayString:c.getNodeOnlySerializedForm(),decisions:[]},target:h,frameConfig:p,frameConfigSource:g}}finally{E&&this.stateManager.setActiveFrameConfig(f)}}async resolveTarget(e,t,n={}){let{targetName:o,logger:i=this.logger,signal:a=this.abortSignal,allowNotActionableNodesOverride:s}=n;if(t.frameCache&&this.userBrowserSettings.autoExpandIframes){let g,m=!1,h=Date.now();for(;Date.now()-h<this.smartWaitingTimeout;)try{let f=await this.stateManager.resolveAutoFrameCache(t.frameCache);this.setActiveFrameConfig(f),m=!0;break}catch(f){g=f,await ee(at,a)}if(!m)throw g}let c=await this.getActivePageOrFrame();await this.ensureMomenticBrowserScriptsLoaded(c,i,a);let l=Date.now(),u=0,d=0,p;for(;Date.now()-l<this.smartWaitingTimeout;){this.abortSignal?.throwIfAborted(),u++;let g=u===2||Date.now()-l>this.smartWaitingTimeout-2e3&&u%2===0;try{p=await this.resolveTargetHelper({root:c,target:t,primaryOnly:!0,shouldLogOnFailure:g,logger:i,allowNotActionableNodesOverride:s,signal:a});break}catch(m){if(m instanceof ba)break;if(m instanceof Pr){if(d++,d>2)throw i.error({err:m},"Got multiple cache disqualification errors, giving up"),m;i.warn({err:m},"Got cache disqualification error, waiting and retrying resolution"),await ee(at,a)}a?.throwIfAborted(),g&&i.warn({err:m},`Could not resolve target using primary cache only (x${u})`),await ee(at,a)}}return p||(p=await this.resolveTargetHelper({root:c,target:t,primaryOnly:!1,logger:i,signal:a,allowNotActionableNodesOverride:s}),t.targetSource="HEURISTIC_HEALED",t.targetUpdateTime=new Date().toISOString(),t.targetUpdateLoggerTags=ve(i),i.info({decisions:p.decisions},"Target resolution succeeded after waiting")),e?.details?.push({type:"TARGETING",name:o,elementLocationDecisions:p?.decisions??[],pageState:void 0,targetSource:t.targetSource,targetUpdateTime:t.targetUpdateTime}),p}async resolveTargetHelper({root:e,target:t,primaryOnly:n,logger:o,signal:i,allowNotActionableNodesOverride:a,shouldLogOnFailure:s}){let c=fi(t),l=[],u=(await this.getBrowserState({logger:o,abortSignal:i,skipWait:!0,allowNotActionableNodesOverride:a})).serialize(),d;if(t.generatedSelectors||t.hybridSelector){let p;try{p=await this.resolveTargetWithPrimaryMethods({root:e,target:t,logger:o,allowNotActionableNodesOverride:a,shouldLogOnFailure:s})}catch(g){d=g,g instanceof hn&&l.push(...g.decisions)}if(p)return{...p,pageState:void 0,decisions:[...l,...p.decisions]};n||(l.push({type:"CSS_SELECTOR",matched:!1,reason:d?.message,selectors:fi(t.generatedSelectors??[])}),t.generatedSelectors=void 0,t.hybridSelector=void 0)}if(n)throw d;if(!this.userBrowserSettings.disableSecondaryCacheResolution){let p=await this.resolveTargetWithSecondaryMethods({root:e,tree:u,target:t,decisions:l,logger:o,signal:i,allowNotActionableNodesOverride:a});if(p)return p}throw new hn(`Could not find any relevant node given target: ${JSON.stringify(c)}`,l)}async resolveTargetWithPrimaryMethods({root:e,target:t,logger:n,allowNotActionableNodesOverride:o,shouldLogOnFailure:i}){if(!t.nodeOnlySerializedHtml)throw new ba("Insufficient data to resolve target using primary methods (missing node HTML)");let a=i?n:Rn,s=this.userControlledBrowserSettings.hybridSelectorMode,c={ldistThreshold:om,requireBoundingBox:!o,ignoreHrefForCaching:this.userControlledBrowserSettings.ignoreHrefForCaching,requireMatchingBoundingBox:this.userControlledBrowserSettings.bustCacheOnBoundingBoxChange?t.boundingBox:void 0,requirements:t.requirements,additionalElements:t.additionalElements,importantProperties:{attributes:this.userControlledBrowserSettings.importantAttributes,classes:this.userControlledBrowserSettings.importantClasses,styles:this.userControlledBrowserSettings.importantStyles}},{css:l,hybrid:u}=await et({fn:A=>window.evaluatePrimaryCaches(A),arg:{cssParams:{selectors:t.generatedSelectors??[],cachedElementSerialized:t.nodeOnlySerializedHtml,opts:c},hybridParams:s&&t.hybridSelector?{nodes:t.hybridSelector,cachedElementSerialized:t.nodeOnlySerializedHtml,opts:c}:void 0},root:e,timeout:te,waitForPageLoad:()=>this.waitForPageLoad(),codePath:"evaluating target caches"}),d,p,g=[];if(s==="prefer"&&u?.result){d=u.result;let A={type:"HYBRID_SELECTOR",matched:!0,logs:u.logs,reason:"Discovered a match using Momentic's hybrid text and CSS selector approach"};g.push(A),p="HYBRID_SELECTOR"}else if(l?.result){d=l.result;let A=`${d.workingSelectors.length} CSS selectors matched the following element: ${d.serializedElement}`,C=d.workingSelectors.slice(0,5);g.push({type:"CSS_SELECTOR",matched:!0,logs:l.logs,reason:A,selectors:C}),n.debug({reason:A,workingSelectors:C},"Resolved with CSS selectors"),p="CSS_SELECTOR"}else throw g.push({type:"CSS_SELECTOR",matched:!1,reason:l.logs.length===1?"CSS evaluation failed":"No CSS selectors matched",selectors:[],logs:l.logs}),u&&g.push({type:"HYBRID_SELECTOR",matched:!1,reason:u.logs.length===1?"Hybrid evaluation failed":"No hybrid selectors matched",logs:u.logs}),new hn("Cache evaluation failed",g);let m,h,f;if(this.userBrowserSettings.visualActions){let A=d.mPath;if(!A)throw new Error("Found element did not have an mPath despite using visual actions");let C=A.join(" > ");m=e.locator(C),h=this.stateManager.getNodeUsingMPathSelector(C)}else if(d.dataMomenticId!==void 0)f=parseInt(d.dataMomenticId),h=this.stateManager.dataMomenticIdToNodeMap[f],"workingSelectors"in d?m=e.locator(d.workingSelectors[0]):m=e.locator(Tr(f));else throw new _("InternalWebAgentError","Received an element resolution result with no identifying attributes");s&&t.hybridSelector&&(u?.logs.length===1?a.warn({hybridResult:u,cssResult:l,hybridMode:s},"Hybrid selector resolution rejected, continuing..."):u?.result?l?.result&&u?.result&&u.result.serializedElement!==l.result.serializedElement&&(this.userBrowserSettings.visualActions&&JSON.stringify(l.result.mPath)!==JSON.stringify(u.result.mPath)?n.warn({originalCache:t,hybridResult:u,cssResult:l,hybridMode:s,mode:"visualActions"},"Hybrid selector resolution returned a different element than CSS selector resolution, continuing..."):l.result.dataMomenticId!==u.result.dataMomenticId&&n.warn({originalCache:t,hybridResult:u,cssResult:l,hybridMode:s,mode:"dataMomenticId"},"Hybrid selector resolution returned a different element than CSS selector resolution, continuing...")):a.warn({originalCache:t,hybridResult:u,cssResult:l,hybridMode:s},"Hybrid selector resolution returned no eligible elements while CSS resolution did, continuing..."));let E=fi(t);await this.updateCacheWithNewNodeDetails({node:h,target:t,locator:m,logger:n,startingBoundingBox:d.boundingBox,allowNotActionableNodesOverride:o});let S=zm(E,t);return S&&Object.keys(S).length>0&&(t.cacheResolutionUpdateTime=new Date().toISOString(),t.cacheResolutionUpdateLoggerTags=ve(n),t.cacheResolutionUpdateSource=p,n.debug({diffs:S},"Updated cache")),{a11yNode:h,displayString:d.serializedElement,locator:m,decisions:g}}async resolveHardcodedCssSelector(e){let{ctx:t,selector:n,logger:o=this.logger,signal:i=this.abortSignal,timeoutMs:a=this.smartWaitingTimeout}=e,s=await this.getActivePageOrFrame(),c=Date.now(),l=0,u,d=[];for(;Date.now()-c<a;){i?.throwIfAborted(),l++;let p=s.locator(n),g;try{return await p.waitFor({state:"attached",timeout:re}),g=await Jr(p,o)??"",d.push({type:"USER_SELECTOR",matched:!0,reason:`The user-provided CSS selector ${n} matched an element on the page.`}),t?.details?.push({type:"TARGETING",name:e.targetName,elementLocationDecisions:d,targetSource:"USER_CSS_SELECTOR",targetUpdateTime:new Date().toISOString()}),{locator:p,displayString:g,decisions:d}}catch(m){let h=m.message;u=new _("ActionFailureError",`CSS selector '${n}' failed to resolve after ${l} attempts: ${h.includes("locator.waitFor: Timeout")?"the selector did not match any element on the page":h}`),await ee(at,i)}}throw u}async resolveTargetWithSecondaryMethods(e){if(!e.target.boundingBox)return;let{x:t,y:n,width:o,height:i}=e.target.boundingBox,a=await this.resolveTargetWithSecondaryMethodsHelper(e);if(!a)return;let s=await a.locator.boundingBox({timeout:te});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(!t||!n||!c||!l){this.logger.debug({oldX:t,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-t)>100||Math.abs(l-n)>100){this.logger.debug({newX:c,newY:l,oldX:t,oldY:n,proposedNode:a.displayString},"Rejecting secondary matching result due to large difference in x/y coords");return}return a}async resolveTargetWithSecondaryMethodsHelper({root:e,target:t,decisions:n,logger:o,signal:i,allowNotActionableNodesOverride:a}){if(t.nodeOnlySerializedHtml&&t.nodeOnlySerializedHtml.trim().length<lA){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(t.nodeOnlySerializedHtml&&t.nodeOnlySerializedHtml.length>50)try{let l=await et({fn:d=>window.findClosestElementByLDist?.(d),arg:{nodeOnlySerializedHtml:t.nodeOnlySerializedHtml},timeout:he,root:e,waitForPageLoad:()=>this.waitForPageLoad(),codePath:"finding the closest element on the page"}),u=Math.floor(om*t.nodeOnlySerializedHtml.length);if(l&&l.closestDistance&&l.closestDistance>=u){let d=`Closest HTML candidate still has too far distance (${l.closestDistance}) from threshold (${u})`;n.push({type:"HTML_DISTANCE",matched:!1,reason:d,distance:l.closestDistance,closestElement:l.closestNodeSerialized})}else{if(l?.error)throw new Error(l.error);if(l?.dataMomenticId||l?.mPathSelector){let d=l.dataMomenticId?parseInt(l.dataMomenticId):void 0,p,g;if(d)p=this.stateManager.dataMomenticIdToNodeMap[d],g=e.locator(Tr(d));else if(l.mPathSelector)p=this.stateManager.getNodeUsingMPathSelector(l.mPathSelector),g=e.locator(l.mPathSelector);else throw new Error("HTML ldist comparison returned no error, data momentic id, or mPath selector");let m=l.closestNodeSerialized??await Jr(g,o)??"unknown element";o.warn({result:l,originalTarget:t,displayString:m},"Resolved cached target to new node with pure html levenshtein distance");let h=fi(t);await this.updateCacheWithNewNodeDetails({node:p,target:t,locator:g,logger:o,startingBoundingBox:l.boundingBox,allowNotActionableNodesOverride:a});let f=zm(h,t);return f&&Object.keys(f).length>0&&(t.cacheResolutionUpdateTime=new Date().toISOString(),t.cacheResolutionUpdateLoggerTags=ve(o),t.cacheResolutionUpdateSource="HTML_DISTANCE",o.info({diffs:f,result:l},"Updated cache after l-dist resolution")),n.push({type:"HTML_DISTANCE",matched:!0,reason:`Found an element on the page within ${u} string comparison distance of the saved element.`,logs:l.logs,distance:l.closestDistance,closestElement:m,savedElement:t.nodeOnlySerializedHtml}),{locator:g,a11yNode:p,displayString:m,decisions:n,pageState:void 0}}else throw new Error(`Got invalid HTML evaluation result: ${JSON.stringify(l)}`)}}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 s=t.screenshotUrl,c=t.role??"";if(s&&im.includes(c))try{let l=await this.resolveTargetWithTemplateMatching({root:e,oldTarget:t,screenshotUrl:s,signal:i,allowNotActionableNodesOverride:a});return{...l,decisions:[...n,...l.decisions],pageState:void 0}}catch(l){i?.throwIfAborted(),n.push({type:"TEMPLATE_MATCHING",matched:!1,reason:`Error finding closest element using saved screenshot: ${l}`,elementImageUrl:s}),o.warn({err:l},"Did not find any close element using saved screenshot")}}async resolveTargetWithTemplateMatching({screenshotUrl:e,oldTarget:t,signal:n,allowNotActionableNodesOverride:o}){let i;if(!this.enricher)throw new Error("Enricher not available for screenshot resolution");let a=await this.screenshot({retries:0}),c=await(await fetch(e)).arrayBuffer(),l=YU(),u=await this.enricher.runTemplateMatching({id:l,searchImageBase64String:Buffer.from(c).toString("base64"),pageImageBase64String:a.toString("base64")},{signal:n}),{target:d,locator:p}=await this.getTargetFromPositionPercentages({percentX:u.x,percentY:u.y,allowNotActionableNodesOverride:o}),g=d.boundingBox?.width,m=d.boundingBox?.height;if(!g||!m)throw i="Rejecting target from screenshot due to no bounding box",new Error(i);let h=d.id,f=this.stateManager.a11yIdToNodeMap[h],E=fi(t);await this.updateCacheWithNewNodeDetails({target:t,node:f,locator:p,allowNotActionableNodesOverride:o});let S=zm(E,t);return S&&Object.keys(S).length>0&&(t.cacheResolutionUpdateTime=new Date().toISOString(),t.cacheResolutionUpdateLoggerTags=ve(this.logger),t.cacheResolutionUpdateSource="TEMPLATE_MATCHING",this.logger.info({id:l,diffs:S,templateMatch:u},"Updated cache after template matching resolution")),{locator:p,a11yNode:f,displayString:d.nodeOnlySerializedHtml??"",decisions:[{type:"TEMPLATE_MATCHING",matched:!0,reason:"Found element using screenshot",elementImageUrl:e}]}}async typeIntoTarget(e,t,n={}){await this.highlight(t.locator);let o=await t.locator.getAttribute("type",{timeout:re})??"",i=kA.some(a=>a===o.toLowerCase());return await xm({targetingResult:t,options:{force:n.force,relativePosition:n.relativePosition},logger:this.logger,retryTimeoutMs:this.smartWaitingTimeout,position:i?{x:1,y:1}:void 0,actionSource:"type",browserCallbacks:this.getBrowserCallbacks()}),await this.page.waitForTimeout(150),this.directTypeHelper(e,n)}async click(e,t,n={}){return xm({targetingResult:e,options:n,logger:this.logger,actionSource:"click",retryTimeoutMs:this.smartWaitingTimeout,controllerCallbacks:t,browserCallbacks:this.getBrowserCallbacks()})}async waitForUrl({beforeUrl:e,matcher:t},n){let o=n?.timeout??this.pageLoadTimeout,i=Date.now(),a=!1,s=e;for(;Date.now()-i<o;){if(this.abortSignal?.throwIfAborted(),s=this.url(),gc(s,t,n)){a=!0;break}await ee(at,this.abortSignal)}if(!a)throw new _("ActionFailureError",`The active page URL ${n?.negated?"still does":"does not"} ${yv(t)} in ${o}ms.
|
|
4017
|
-
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,t,n={}){await this.hover({locator:e}),await this.page.mouse.down();let o=await t.boundingBox({timeout:te});if(!o)throw new _("ActionFailureError","Could not get bounding box of target element");let i=o.x+o.width/2,a=o.y+o.height/2,s=n.steps??5;await this.page.mouse.move(i,a,{steps:s}),await ee(n.hoverSeconds?Math.min(n.hoverSeconds*1e3,he):500),await this.page.mouse.up()}async mouseDrag(e,t,n,o){o&&await this.hover({locator:o});let i=await(await this.getActivePageOrFrame()).evaluate(Sm);i||(this.logger.warn("Could not get current mouse position before mouse drag action, defaulting to 0,0"),i={left:0,top:0}),await this.page.mouse.down(),await this.page.mouse.move(e+i.left,t+i.top,{steps:n}),await ee(pi),await this.page.mouse.up()}async hover(e){await this.highlight(e.locator),await mo({func:async t=>{await this.scrollIntoViewIfNeeded(t.locator);let n=await t.locator.boundingBox({timeout:te});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 mo({func:t=>t.locator.focus({timeout:he}),action:"focusing element",logger:this.logger,retryTimeoutMs:this.smartWaitingTimeout,callbacks:this.getBrowserCallbacks(),targetingResult:e})}async blur(e){if(!e){let t=await this.getActivePageOrFrame();await et({fn:()=>{let n=document.activeElement;n&&n.nodeType===1&&n.blur()},root:t,arg:void 0,waitForPageLoad:()=>this.waitForPageLoad(),timeout:re,codePath:"blurring the active element"});return}await this.highlight(e.locator),await mo({func:t=>t.locator.blur({timeout:he}),action:"blurring element",logger:this.logger,retryTimeoutMs:this.smartWaitingTimeout,callbacks:this.getBrowserCallbacks(),targetingResult:e})}async selectOption(e,t,n=!1){await this.highlight(e.locator),await mo({action:"selecting option from dropdown",logger:this.logger,retryTimeoutMs:this.smartWaitingTimeout,callbacks:this.getBrowserCallbacks(),func:async o=>{if(t.type==="INDEX"){let i=Number(t.index);if(isNaN(i))throw new _("UserConfigurationError",`Page index ${t.index} is not a number`)}await o.locator.selectOption({value:t.type==="VALUE"?t.value:void 0,label:t.type==="LABEL"?t.label:void 0,index:t.type==="INDEX"?Number(t.index):void 0},{force:n,timeout:te})},targetingResult:e})}async press(e,t){let n=t.repeat??1;if(t.convertMeta){let o=Ac(e,this.properties.isAndroid);o!==e&&(this.logger.info({key:e,convertedKey:o},"Converted platform dependent keys"),e=o)}for(let o=0;o<n;o++)await this.page.keyboard.press(e,{delay:t.delayMs??0})}async keyDown(e,t){if(t.convertMeta){let n=Ac(e,this.properties.isAndroid);n!==e&&(this.logger.info({keyString:e,convertedKey:n},"Converted platform dependent keys"),e=n)}for(let n of Fm(e))await this.page.keyboard.down(n)}async keyUp(e,t){if(t.convertMeta){let n=Ac(e,this.properties.isAndroid);n!==e&&(this.logger.info({keyString:e,convertedKey:n},"Converted platform dependent keys"),e=n)}for(let n of Fm(e))await this.page.keyboard.up(n)}async refresh(e){let t=e?.loadTimeoutMs??this.pageLoadTimeout;await this.waitForPageLoad();let n=0,o=2;for(;n<o;){n++;try{await this.page.reload({waitUntil:"domcontentloaded",timeout:t});break}catch(i){this.logger.warn({err:i,attempt:n},`Failed to reload page${n<o?", retrying...":", continuing..."}`)}}await this.loadFrameAndRecordUrl({root:this.page,signal:this.abortSignal,codePath:"reload-step"}),await this.waitForDOMStability()}async getBrowserState(e){let{maxAttempts:t=2,logger:n=this.logger,skipWaitForPageLoad:o,allowNotActionableNodesOverride:i,shouldLogOnFailure:a}=e,s=e.abortSignal??this.abortSignal,c=!i,l=i?!0:this.userControlledBrowserSettings.showZeroOpacityElements,u=a?n:Rn;o||await this.waitForPageLoad(),e.skipWait||await this.waitForDOMStability({logger:n,signal:s});let d=0,p;for(;d<t;){d++;try{return await V(this.stateManager.getA11yTree({devicePixelRatio:this.devicePixelRatio,abortSignal:s,logger:n,filterByViewport:e.filterByViewport,showZeroOpacityElements:l,flagNotActionableNodes:c}),{milliseconds:this.pageLoadTimeout*d,signal:s,message:"Getting browser state took too long"})}catch(g){if(s?.throwIfAborted(),p=g instanceof Error?g.message:`${g}`,d>=t)throw g;u.warn({err:g,url:this.url()},"Error getting a11y tree, retrying...")}}throw new _("ActionFailureError",`Getting page content failed after ${t} attempts. Error: ${p}`)}async getViewportOffsetDetails(e){let[t,n,o,i,a]=await et({root:e,fn:()=>[window.scrollY,window.scrollX,window.screen.width,window.screen.height,window.devicePixelRatio],arg:void 0,timeout:te,waitForPageLoad:async()=>{},codePath:"getting current viewport details"});return{upperBound:t,lowerBound:t+i,leftBound:n,rightBound:n+o,width:o,height:i,devicePixelRatio:this.properties.systemDevicePixelRatio??a}}async waitForDOMStability(e){let{logger:t=this.logger,timeout:n=this.smartWaitingTimeout,signal:o}=e??{},i={value:Date.now()},a=p=>{i.value=Date.now()},s=()=>a("DOM.documentUpdated");this.cdpClient.addListener("DOM.documentUpdated",s);let c=()=>a("Page.frameDetached");this.cdpClient.addListener("Page.frameDetached",()=>c);let l=()=>a("Page.frameStartedLoading");this.cdpClient.addListener("Page.frameStartedLoading",l);let u=()=>a("Page.navigatedWithinDocument");this.cdpClient.addListener("Page.navigatedWithinDocument",u);let d=()=>a("frameRequestedNavListener");this.cdpClient.addListener("Page.frameRequestedNavigation",d);try{await this.waitForDOMStabilityHelper(i,t,n,o)}finally{this.cdpClient.removeListener("DOM.documentUpdated",s),this.cdpClient.removeListener("Page.frameDetached",c),this.cdpClient.removeListener("Page.frameStartedLoading",l),this.cdpClient.removeListener("Page.navigatedWithinDocument",u),this.cdpClient.removeListener("Page.frameRequestedNavigation",d)}}async waitForDOMStabilityHelper(e,t,n,o){let i=!1,a=Date.now(),s,c={quality:25,retries:0,stabilizeBeforeScreenshot:!0},l=!1,u=0;for(;Date.now()-a<n;){if(o?.throwIfAborted(),await ee(pi,this.abortSignal),s)try{let d=await this.screenshot(c);if(!d.equals(s)){s=d,l=!1;continue}l=!0}catch(d){u++,u%3===0&&t.warn({err:d,screenshotErrors:u},"Failed to take screenshot for DOM stability check"),o?.throwIfAborted()}else try{s=await this.screenshot(c)}catch(d){u++,u%3===0&&t.warn({err:d,screenshotErrors:u},"Failed to take screenshot for DOM stability check"),o?.throwIfAborted()}if(!(Date.now()-e.value<sA)){i=!0;break}}i||t.warn({duration:Date.now()-a,stable:{a11y:i,screenshot:l}},"A11y wait phase completed due to timeout, continuing...")}async clickUsingVisualCoordinates(e,t){let{x:n,y:o}=e;this.logger.debug({x:n,y:o},"Executing mouse click with visual coordinates"),await this.waitForPageLoad(),await this.page.mouse.click(n,o,{button:t.rightClick?"right":"left",clickCount:t.doubleClick?2:1})}async dragAndDropUsingVisualCoordinates(e,t,n){await this.page.mouse.move(e.x,e.y,{steps:3}),await this.page.mouse.down(),await this.page.mouse.move(t.x,t.y,{steps:3}),await ee(n.hoverSeconds?Math.min(n.hoverSeconds*1e3,nm):500),await this.page.mouse.up()}async hoverUsingVisualCoordinates(e){await this.page.mouse.move(e.x,e.y)}async mouseDragUsingVisualCoordinates(e,t,n,o){await this.hoverUsingVisualCoordinates(o);let i=await(await this.getActivePageOrFrame()).evaluate(Sm);i||(this.logger.warn("Could not get current mouse position before mouse drag action, defaulting to 0,0"),i={left:0,top:0}),await this.page.mouse.down(),await this.page.mouse.move(e+i.left,t+i.top,{steps:n}),await ee(pi),await this.page.mouse.up()}async getElementLocation(e){let t=await this.cdpClient.send({method:"DOMSnapshot.captureSnapshot",params:{computedStyles:[],includeDOMRects:!0,includePaintOrder:!0},timeout:te}),n=await V(this.page.evaluate(()=>window.devicePixelRatio),{milliseconds:he});process.platform==="darwin"&&n===1&&(n=iA);let o=t.documents[0],i=o.layout,a=o.nodes,s=a.nodeName||[],c=a.backendNodeId||[],l=i.nodeIndex,u=i.bounds,d=-1;for(let S=0;S<s.length;S++)if(c[S]===e){d=l.indexOf(S);break}if(d===-1)throw new Error(`Could not find any backend node with ID ${e}`);let[p=0,g=0,m=0,h=0]=u[d];p/=n,g/=n,m/=n,h/=n;let f=p+m/2,E=g+h/2;return{centerX:f,centerY:E}}async scrollVertical(e){return _m({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 _m({frame:this.stateManager.frameConfig?await this.getActivePageOrFrame():null,page:this.page,deltaX:e?Math.abs(e):null,directionX:e&&e>0?"right":"left",deltaY:0,directionY:null,signal:this.abortSignal,callbacks:this.getBrowserCallbacks(),logger:this.logger})}async goForward(){await this.waitForPageLoad(),await this.page.goForward({waitUntil:"domcontentloaded",timeout:this.pageLoadTimeout}),await this.loadFrameAndRecordUrl({root:this.page,signal:this.abortSignal,codePath:"go-forward"})}async goBack(){await this.waitForPageLoad(),await this.page.goBack({waitUntil:"domcontentloaded",timeout:this.pageLoadTimeout}),await this.loadFrameAndRecordUrl({root:this.page,signal:this.abortSignal,codePath:"go-back"})}async reinitializeCDPClient(e){await this.cdpClient.reinitialize(e),await this.initializeScreencast()}async stopScreencast(){if(this.clientCallbacks?.onScreencastFrame)try{await this.cdpClient.send({method:"Page.stopScreencast",params:{}})}catch{}}async changeActivePage(e,t){await this.stopScreencast(),this.recordUrlVisited(e.url()),this.page=e,await this.reinitializeCDPClient(t??this.pageLoadTimeout)}async createNewTab(e,t){let n=await this.context.newPage();await this.changeActivePage(n,t?.loadTimeoutMs),await this.navigate({url:e,initialNavigation:!0,...t}),this.handleAvailableTabsChange()}async switchToPage(e,t){let n=!0,o,i=Date.now();for(;n||t?.retry&&Date.now()-i<this.smartWaitingTimeout;){n=!1;try{await this.switchToPageHelper(e,t);return}catch(a){this.logger.warn({err:a},"Error switching to page, retrying..."),o=a,await ee(at)}}throw o}async switchToPageHelper(e,t){let n=this.context.pages().map((i,a)=>({page:i,url:i.url(),index:a})),o;if(e.type==="INDEX"){let i=Number(e.index);if(isNaN(i))throw new _("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)}.
|
|
4018
|
-
Available pages:${JSON.stringify(n.map(i=>i.url))}`);if(!co(o.url,this.logger)){this.logger.error(`Refusing to switch to page with invalid URL: ${o.url}`);return}this.logger.info(`Switching to tab ${o.index} with url ${o.url}`),await this.changeActivePage(o.page,t?.loadTimeoutMs),await this.loadFrameAndRecordUrl({root:o.page,signal:this.abortSignal,codePath:"switch-to-tab-step"}),this.handleAvailableTabsChange()}async setCookie(e){let t;return typeof e=="string"?t=Ul(e):t=[e],await this.context.addCookies(t),t}async setLocalStorage(e,t){let n;for(let o=0;o<2;o++)try{await this.evaluateFunctionInPage(([i,a])=>{i&&localStorage.setItem(i,a||"")},[e,t],`setting local storage key ${e}`);return}catch(i){n=i}if(n)throw n}async solveCaptcha(){await this.getBrowserState({allowNotActionableNodesOverride:!0});let e;for(let s of Object.values(this.stateManager.a11yIdToNodeMap))if(s.role==="image"&&s.name.toLowerCase().includes("captcha")){if(!s.backendNodeId)continue;e=await this.stateManager.getLocatorFromBackendId(this.page,s.backendNodeId);break}if(!e){let s=await(await this.getActivePageOrFrame()).solveRecaptchas();if(!s.captchas||!s.captchas.length)throw new Error("No captchas found on the page");return}let t=await e.screenshot({type:"jpeg",animations:"allow",caret:"hide",quality:100,timeout:te}),n=await fetch("https://api.2captcha.com/createTask",{method:"POST",body:JSON.stringify({clientKey:mi,task:{type:"ImageToTextTask",body:t.toString("base64"),case:!0},languagePool:"en"})});if(!n.ok){let s=`Captcha solver API returned error response: ${n.statusText}`;throw this.logger.error({text:await n.text()},s),new Error(s)}let{taskId:o}=await n.json(),i=Date.now(),a="";for(;Date.now()-i<cA;){await ee(2500);let s=await fetch("https://api.2captcha.com/getTaskResult",{method:"POST",body:JSON.stringify({clientKey:mi,taskId:o})});if(!s.ok){let l=`Captcha solution API returned error response: ${s.statusText}`;throw this.logger.error({text:await s.text()},l),new Error(l)}let c=await s.json();if(c.errorId){let l=`Captcha solution API returned error ID ${c.errorId}`;throw this.logger.error(l),new Error(l)}if(c.status==="ready"){a=c.solution.text;break}}if(!a)throw new Error("Captcha solution timed out");return a}getActiveFrameConfig(){return this.stateManager.frameConfig}async exposeRecordingBindings(){try{await V(this.exposeRecordingBindingsHelper(),{milliseconds:this.pageLoadTimeout})}catch(e){e instanceof Error&&e.message.includes("already registered")||this.logger.error({err:e},"Failed to install Momentic libraries for action recording")}}async exposeRecordingBindingsHelper(){await this.context.exposeBinding("isRecordingActive",()=>this.transformer!==void 0,{handle:!1}),await this.context.exposeBinding("captureTargetedEvent",({frame:e},t)=>{this.transformer&&mw({event:t,frame:e,transformer:this.transformer,enricher:this.enricher,lastScreenshotForRecording:this.lastScreenshotForRecording?.toString("base64"),logger:this.logger})},{handle:!1}),await this.context.exposeBinding("captureKeystroke",async(e,t)=>{this.transformer&&this.transformer.recordKeystroke(t)})}async startRecordingCrons(e){if(e.aborted)return;let t,n=(await this.getOpenPages()).map(c=>c.url),o=0,i=!1,a=async()=>{if(e.aborted||o>8){clearTimeout(t);return}i=!0;let c;try{c=(await this.getOpenPages()).map(u=>u.url),o=0}catch(u){this.logger.debug({err:u},"Failed getting new open pages during recording tab switch cron, skipping..."),o++;return}let l=this.url();for(let u=c.length-1;u>=n.length;u--){let d=c[u];co(d,this.logger)&&d!==l&&this.logger.info({lastActivePages:n,currentUrl:l,newOpenPages:c},"Auto-following new tab during recording"),await this.switchToPage({type:"INDEX",index:String(u)});break}n=c};t=setInterval(async()=>{if(!i){i=!0;try{await a()}catch(c){this.logger.error({err:c},"Error while checking pages during recording")}finally{i=!1}}},at);let s=async()=>{clearInterval(t)};e.addEventListener("abort",s,{once:!0})}async startRecording(e,t,n){this.logger.debug({isClickToRecord:n},"Starting recording mode in Chrome browser"),await this.startRecordingCrons(e),await this.page.evaluate(i=>{let a=window;a._MOMENTIC_RECORDING_ACTIVE=!0,a._MOMENTIC_CLICK_RECORD_ACTIVE=i},n),this.transformer=t,await this.injectKnowledgeBaseIntoBrowser(this.page);let o=async()=>{this.transformer=void 0,this.lastScreenshotForRecording=void 0;try{await this.page.evaluate(()=>{let i=window;i._MOMENTIC_RECORDING_ACTIVE=!1,i._MOMENTIC_CLICK_RECORD_ACTIVE=!1})}catch{}};e.addEventListener("abort",o,{once:!0})}async getSelectOptions(e){return await e.evaluate(n=>Array.from(n.querySelectorAll("option")).map(i=>({value:i.value,label:i.label})),void 0,{timeout:re})}getActivePage(){return this.page}async getActivePageOrFrame(){let e=await this.stateManager.resolveActiveFrameConfig({});return e?(await this.loadFrameAndRecordUrl({root:e.frame,signal:this.abortSignal,codePath:"get-active-frame-locator"}),e.frame):this.page}async loadFrameAndRecordUrl({root:e,signal:t,codePath:n}){let o=this.pageLoadTimeout,i=e.url();if(!i.includes("chrome-error://")){try{await Ga({promiseGenerator:async()=>e.waitForLoadState("domcontentloaded",{timeout:o}),signal:t,codePath:`loadFrameAndRecordUrlDomContentLoad-${n}`,logger:this.logger,timeoutMs:this.pageLoadTimeout})}catch(a){let s=a;if(s.name==="AbortError")throw new _("UserInfrastructureError",`The page with URL ${It(i,50)} did not load within the configured timeout (${o}ms): ${s}`);if(!s.message.includes("detached"))throw s}try{await Ga({promiseGenerator:async()=>e.waitForLoadState("load",{timeout:o}),signal:t,codePath:`loadFrameAndRecordUrlPageLoad-${n}`,logger:this.logger,timeoutMs:this.pageLoadTimeout})}catch(a){this.logger.warn({err:a,codePath:n,url:i},"Failed waiting for current frame to load, continuing...")}this.recordUrlVisited(e.url())}}async getCondensedHtml(e){let{skipWait:t=!1}=e??{};return t||(await this.waitForPageLoad(),await this.waitForDOMStability()),this.getCondensedHtmlHelper()}async getCondensedHtmlHelper(){let e=await this.getRawCondensedHtml();return jU.html(e,{indent_size:1,indent_with_tabs:!1,preserve_newlines:!1})}async getRawCondensedHtml(){let e=await this.getActivePageOrFrame();await this.ensureMomenticBrowserScriptsLoaded(e,this.logger,this.abortSignal);let{result:t,error:n}=await et({fn:()=>window.getCondensedHtmlTree(),root:e,arg:void 0,timeout:he,waitForPageLoad:()=>this.waitForPageLoad(),codePath:"getting condensed HTML tree"});if(n)throw new Error(`Failed to process page HTML: ${n}`);if(!t)throw new _("InternalWebAgentError","Got empty HTML tree - are you sure the page is fully loaded?");return t}registerDialogHandler(e){let t=async n=>{try{e==="ACCEPT"?await n.accept():await n.dismiss()}catch(o){this.logger.warn({err:o},"Failed to handle dialog")}};this.page.once("dialog",t)}async evaluateFunctionInAllFrames(e,t){return this.stateManager.executeFunctionInAllFrames(e,t)}async evaluateFunctionInPage(e,t,n,o=he){let i=await this.getActivePageOrFrame();return et({root:i,fn:e,arg:t,timeout:o,waitForPageLoad:()=>this.waitForPageLoad(),codePath:n})}async evaluateCodeInPage({code:e,fragment:t,context:n,timeoutMs:o=Tn}){let i=wA(),a={code:e,fragment:t,context:n},{result:s}=await V(this.page.evaluate(i,a),{milliseconds:o,fallback:()=>{throw this.abortSignal?.throwIfAborted(),new _("ActionFailureError",`Code evaluation in browser exceeded the allowed timeout of ${o/1e3} seconds`)},signal:this.abortSignal});return s}async getDomNodeFromPixelPosition(e,t){await this.cdpClient.send({method:"DOM.getDocument",params:{depth:0},timeout:he});let n;try{n=await this.cdpClient.send({method:"DOM.getNodeForLocation",params:{x:e,y:t},timeout:re})}catch(o){throw this.logger.error({err:o,x:e,y:t},"Failed to get DOM node from position percents"),new Error("No element was found at the given location")}return n}async getDomNodeFromPositionPercentages(e,{percentX:t,percentY:n}){if(t<0||t>1||n<0||n>1)throw new _("UserConfigurationError","Invalid percent passed to percentage location");let{width:o,height:i,upperBound:a,leftBound:s}=await this.getViewportOffsetDetails(e),c=Math.round(a),l=Math.round(s),u=Math.ceil(o*t),d=Math.ceil(i*n),p=u+l,g=d+c;return this.getDomNodeFromPixelPosition(p,g)}async highlightFromPositionPercentages(e){let t=await this.getActivePageOrFrame(),n;try{n=await this.getDomNodeFromPositionPercentages(t,e)}catch{}return n?(await this.cdpClient.send({method:"Overlay.highlightNode",timeout:re,params:{highlightConfig:jA,backendNodeId:n.backendNodeId}}),async()=>{try{await this.cdpClient.send({timeout:re,method:"Overlay.hideHighlight",params:{backendNodeId:n?.backendNodeId}})}catch{}}):async()=>{}}async clearAllCdpHighlights(){try{await this.cdpClient.send({method:"Overlay.hideHighlight",params:void 0,timeout:re})}catch{}}async getTargetFromPositionPercentages(e){let t=await this.getActivePageOrFrame(),n=await this.getDomNodeFromPositionPercentages(t,e);return this.getTargetFromBackendNodeId({root:t,backendNodeId:n.backendNodeId,allowNotActionableNodesOverride:e.allowNotActionableNodesOverride})}async getTargetFromBackendNodeId({root:e,backendNodeId:t,allowNotActionableNodesOverride:n}){let o=this.stateManager.domGraph?.backendIdToNode[t];if(!o)throw new Error("No DOM node was found with the given backend ID");let i=o?.attributes[Xr],a=parseInt(i??"");if(!i||isNaN(a))throw new Error("No data-momentic-id was found on the DOM node");let s=e.locator(Tr(a)),c;o.bounds.x!==null&&o.bounds.y!==null&&(c={x:o.bounds.x,y:o.bounds.y,width:o.bounds.width??0,height:o.bounds.height??0});let l=await this.fetchHtmlAttributes({locator:s,logger:this.logger,startingBoundingBox:c,allowNotActionableNodesOverride:n}),u={id:-1,dataMomenticId:a,targetSource:"XY_PERCENT",targetUpdateTime:new Date().toUTCString(),...l};return this.logger.debug({target:u},"Tied backend ID to HTML node"),{target:u,locator:s}}async performTargetRedirection(e,t,n){try{return await this.scrollIntoViewIfNeeded(e),await V(this.performTargetRedirectionHelper(e,t,n),{milliseconds:te})??{locator:e}}catch(o){return t.warn({err:o},"Error performing target redirection, using original element"),{locator:e}}}async performTargetRedirectionHelper(e,t,n){let o=Date.now(),i=await Jr(e,t);if(n===void 0&&(n=await e.boundingBox({timeout:te})??void 0),!n){t.error(`Attempted to click on element with no bounding box: ${i}`);return}let{x:a,y:s,width:c,height:l}=n,u=this.getViewport();if(a<0||s<0||!u||a+c>u.width||s+l>u.height){t.info("Skipping locator redirection because the element is outside the viewport");return}let d=await this.getActivePageOrFrame(),{dataMomenticId:p,mPathSelector:g,error:m,serializedElement:h,foundElementRelativePoint:f,force:E,logs:S}=await e.evaluate(C=>{let T=window;if(!T.performTargetRedirection)throw new Error("performTargetRedirection script is not defined");return T.performTargetRedirection(C)},void 0,{timeout:re}),A=Date.now()-o;if(m){t.warn({error:m,serializedElement:h,duration:A,force:E,logs:S},"Got error from target redirection with bounding box");return}else{if(p)return t.info({newDataMomenticId:p,serializedElement:h,duration:A,force:E,logs:S},"Redirected target to new element with bounding box with data-momentic-id"),{locator:d.locator(Tr(p)),hints:{relativeXYToLocator:f,force:E}};if(g)return t.info({newMPathSelector:g,serializedElement:h,duration:A,force:E,logs:S},"Redirected target to new element with bounding box with mPath"),{locator:d.locator(g),hints:{relativeXYToLocator:f,force:E}};if(f)return t.info({foundElementRelativePoint:f,serializedElement:h,duration:A,force:E,logs:S},"Chose specific visible point on original element"),{locator:e,hints:{relativeXYToLocator:f,force:E}};if(E)return t.info({serializedElement:h,duration:A,force:E,logs:S},"Forcing click on original element"),{locator:e,hints:{force:E}}}}async fetchHtmlAttributes({locator:e,logger:t=this.logger,startingBoundingBox:n,allowNotActionableNodesOverride:o}){let{hybridSelectorMode:i,showZeroOpacityElements:a}=this.userControlledBrowserSettings,s=await e.evaluate((c,l)=>{let u=window;return u.generateHtmlCacheAttributes?u.generateHtmlCacheAttributes(c,l):{warnings:[],error:"generateHtmlCacheAttributes is not defined"}},{generateHybridSelector:i==="test"||i==="prefer",startingBoundingBox:n,showZeroOpacityElements:o?!0:a},{timeout:he});if("error"in s&&s.error)throw s.error.startsWith(rA)?new Al(s.error):s.error.startsWith(nA)?new wl(s.error):new Error(s.error);return s.warnings.length&&t.warn(s,"Got warnings while generating HTML attributes for target"),s.attributes}async moveMouseFromPositionPercentages(e,t){let n=this.getViewport();if(!n)throw new Error("Cannot move mouse using percentages without viewport");let o=Math.ceil(n.width*e),i=Math.ceil(n.height*t);return await this.cdpClient.send({method:"Input.dispatchMouseEvent",params:{type:"mouseMoved",x:o,y:i,button:"left",clickCount:0}}),{x:o,y:i}}async clickMouseFromPositionPercentages(e,t,n){let o=this.getViewport();if(!o)throw new Error("Cannot click mouse using percentages without viewport");let i=Math.ceil(o.width*t),a=Math.ceil(o.height*n);await this.cdpClient.send({method:"Input.dispatchMouseEvent",params:{type:e==="down"?"mousePressed":"mouseReleased",x:i,y:a,button:"left",clickCount:e==="down"?1:0},timeout:re})}async scrollFromPositionPercentages(e,t,n,o){let i=this.getViewport();if(!i)throw new Error("Cannot scroll using percentages without viewport");let a=Math.ceil(i.width*e),s=Math.ceil(i.height*t);return await this.cdpClient.send({method:"Input.dispatchMouseEvent",params:{type:"mouseWheel",deltaX:a,deltaY:s,x:n,y:o}}),{deltaX:a,deltaY:s}}canSolveCaptchas(){return!!mi}async getAllFrameUrls(){return await this.stateManager.getAllChildFrameUrls()}async setFileChooserHandler(e){setTimeout(()=>{try{e.cleanup()}catch(t){this.logger.debug({err:t,filePath:e.filePath},"Failed cleaning up file after upload")}},3e4),await this.setFileChooserHandlerHelper(e)}logToUserConsole(e,t,n,...o){let i=this.context.pages().indexOf(e);i=i===-1?0:i,hm(e,this.debugData,i,{type:t,text:`[MOMENTIC] ${n}`,args:o})}async setFileChooserHandlerHelper({filePath:e,filename:t}){if(!_c(e)){let c=`File chooser triggered after the source file ${e} has been cleaned up, ignoring...`;this.logger.error(c),this.logToUserConsole(this.page,"error",c);return}let n=t?.trim()||$U(e),o=zU(e),i=qU(e),a=Pp[i];this.page.once("filechooser",async c=>{this.logger.info({filePath:e,fileName:n},"File chooser triggered");try{if(!_c(e))throw new Error(`File chooser triggered after the source file ${e} has been cleaned up, ignoring...`);await c.setFiles({name:n,buffer:o,mimeType:VU.getType(e)||"application/octet-stream"},{timeout:nm})}catch(l){this.logger.error({err:l},"Error handling file chooser"),this.logToUserConsole(this.page,"error",l.message)}});let s=o.toString("base64");await this.evaluateFunctionInPage(({fileName:c,base64Data:l,mimeType:u})=>{let d=window;d.momenticFileName=c,d.momenticFileBase64=l;let p=atob(l),g=new Array(p.length);for(let h=0;h<p.length;h++)g[h]=p.charCodeAt(h);let m=new Uint8Array(g);d.MomenticFile=class extends Blob{kind="file";name=d.momenticFileName;constructor(){super([m],{type:u})}isSameEntry(h){return h.name===this.name}queryPermission(h){return console.info("[MOMENTIC] MomenticFile.queryPermission called"),Promise.resolve("granted")}remove(){return console.info("[MOMENTIC] MomenticFile.remove called"),Promise.resolve()}async requestPermission(h){return console.info("[MOMENTIC] MomenticFile.requestPermission called"),Promise.resolve("granted")}async getFile(){console.info("[MOMENTIC] MomenticFile.getFile called");let h=new Blob([m]);return new File([h],d.momenticFileName,{type:u})}async createSyncAccessHandle(){throw console.error("[MOMENTIC] Not implemented"),new Error("Not implemented")}async createWritable(){throw console.error("[MOMENTIC] Not implemented"),new Error("Not implemented")}},d.showOpenFilePicker=async()=>(console.info("[MOMENTIC] showOpenFilePicker called"),[new d.MomenticFile])},{fileName:n,base64Data:s,mimeType:a},"set-file-chooser-handler",5e3)}getSerializedFormFromA11yId(e){return this.stateManager.a11yIdToNodeMap[e]?.getNodeOnlySerializedForm()}retrieveAndClearDebugData(){this.cdpClient.loadEventLogs.length>0&&(this.cdpClient.loadEventLogs=[]);let t={...this.debugData};return this.debugData={logsPerPage:[],harPages:{},harEntries:{}},t}async copy(e){try{await this.evaluateFunctionInPage(t=>navigator.clipboard.writeText(t),e,"copying text to clipboard")}catch(t){if(t instanceof Error&&t.message.includes("Document is not focused")){await this.evaluateFunctionInPage(()=>{document.activeElement||document.body.focus()},void 0,"focusing on body element before copying to clipboard"),await this.press("Tab",{}),await this.press("Shift+Tab",{}),await this.evaluateFunctionInPage(n=>navigator.clipboard.writeText(n),e,"copying text to clipboard");return}throw t}}async paste(){await this.waitForPageLoad(),await this.press("Meta+V",{convertMeta:!0})}async registerRequestListener(e){return this.page.waitForResponse(t=>{let n=t.request();return e.matches({url:n.url(),method:n.method()})})}registerRequestRecorder(e,t,n){this.requestRecorders[e]={onRequestStart:(o,i)=>{t.matches({url:i.request.url,method:i.request.method})&&n.onRequestStart(o,i)},onRequestComplete:(o,i)=>{t.matches({url:i.request.url,method:i.request.method})&&n.onRequestComplete(o,i)}}}removeRequestRecorder(e){delete this.requestRecorders[e]}setHeader(e,t,n){this.customHeaders.push({key:e.toLowerCase(),value:t,matcher:n})}registerMock(e,t,n,o){let i=e??Bm();return this.mocks[i]={matcher:t,generateResponse:n,fetchOriginalResponse:o},i}removeMock(e){if(!e){this.mocks={};return}delete this.mocks[e]}async setOfflineMode(e){await this.context.setOffline(e)}get smartWaitingTimeout(){return this.userControlledBrowserSettings.smartWaitingTimeoutMs??aA}get userBrowserSettings(){return fi(this.userControlledBrowserSettings)}get pageLoadTimeout(){return this.userControlledBrowserSettings.pageLoadTimeoutMs??tm}get isInPageLoad(){return Object.values(this.pageLoadPromises).length>0}get devicePixelRatio(){return this.properties.systemDevicePixelRatio??1}get browserCrashDumpDir(){let e=Tc();for(let t of e)if(!(!_c(t)||!gw(t).isDirectory()||!["new","pending","completed"].some(o=>{let i=KU(t,o);return _c(i)&&gw(i).isDirectory()&&HU(i).length>0})))return t}};import EF from"fetch-cookie";import{cloneDeep as Bw}from"lodash-es";import{CookieJar as TF}from"tough-cookie";async function zr({frameConfig:r,action:e,browser:t}){let n=t.getActiveFrameConfig();r?t.setActiveFrameConfig(r):n?.type==="auto"&&t.setActiveFrameConfig(void 0);try{return await e()}finally{t.setActiveFrameConfig(n)}}var XU=["NAVIGATE","NEW_TAB","TAB","REFRESH","WAIT_FOR_URL"];async function Sw({beforeUrl:r,beforePages:e,browser:t,command:n,logger:o}){if(XU.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 ee(250),l++;let u=(await t.getOpenPages()).map(p=>p.url),d=t.url();if(u.length!==e.length)for(let p=u.length-1;p>=e.length;p--){let g=u[p];if(co(g,o)&&g!==r&&g!==d){o.info({beforePages:e,afterPages:u,beforeUrl:r},"Auto-following new tab after preset action"),await t.switchToPage({type:"INDEX",index:String(p)});break}}}}async function In(r,e={}){let t=await r.getBrowserState(e);return{serializedTree:t.serialize(e.serializationOpts),tree:t}}import{randomUUID as rF}from"crypto";var bw={minChunkTokenCount:500,acceptableChunkTokenCount:3e3,maxChunkTokenCount:8e3,maxLineLength:4e3},Ew={minChunkTokenCount:5e3,acceptableChunkTokenCount:1e4,maxChunkTokenCount:3e4,maxLineLength:500},yw=/<(\S+) id="(\d+)".*?>/g,JU=/(<\/(\S+)>)|(<(\S+).*?\/>)/g,Tw=["h1","h2","section","footer","nav","aside","form","label","dialog"],ZU=[...Tw,"span","div","h3"],QU=["table","select","form","ul","ol","menu","pre","code","dialog"],eF=["table","form","dialog","nav","section","ul","select"];function Mc(r){return tF(r)}function tF({logger:r,serializedTree:e,options:t}){let{minChunkTokenCount:n,acceptableChunkTokenCount:o,maxChunkTokenCount:i,maxLineLength:a}=t,s=[],c=e.split(`
|
|
4019
|
-
`),
|
|
4020
|
-
`),tokenLength:d}),u=[],d=0,p=
|
|
4021
|
-
`),tokenLength:d}),
|
|
4022
|
-
${r}`;case"ELEMENT_CHECK":return`${
|
|
4023
|
-
${r}`;default:return r}}var dF=15;async function Pc({command:r,aiPageFiltering:e,logger:t,fixtures:n,source:o,useMemory:i,maxRetries:a=dF}){if(!r.assertion.trim())throw new _("ActionFailureError","Assertion command is missing the assertion content");let{browser:s}=n,c=r.timeout?r.timeout*1e3:s.smartWaitingTimeout,l=mc(c),u=0,d=Date.now(),p,g,m;try{await zr({action:()=>s.clearHighlights(),frameConfig:r.iframeUrl?{type:"url",url:r.iframeUrl}:void 0,browser:s,logger:t})}catch(f){t.warn({err:f},"Failed to clear highlights before AI check, continuing...")}let h;for(;u<a&&(!h||h-d<c);){n.abortSignal.throwIfAborted(),u!==0&&await ee(l,n.abortSignal),h=Date.now();try{if(p=await zr({action:async()=>{let E=await xw(s,t,n.abortSignal);return g&&g.serializedTree===E.serializedTree&&g.screenshotBuff.equals(E.screenshotBuff)?p:(g=E,_w({command:r,state:E,fixtures:n,useMemory:i,useConsensus:!1,highlightElementsOnFailure:!1,attemptNumber:u,aiPageFiltering:e,logger:t,source:o}))},frameConfig:r.iframeUrl?{type:"url",url:r.iframeUrl}:void 0,logger:t,browser:s}),p?.updatedMemory&&cc(r,p.updatedMemory,t),p?.success)break;throw p?.thoughts?new _("AssertionFailureError",p.thoughts):new _("InternalPlatformError","No thoughts were provided for AI assertion failure")}catch(f){n.abortSignal.throwIfAborted(),m=f instanceof Error?f:new Error(`${f}`),t.info({err:f},`AI check assert attempt ${u} failed, retrying...`)}finally{u++}}if(!p?.success)try{p=await zr({action:async()=>_w({command:r,state:await xw(s,t,n.abortSignal),fixtures:n,useMemory:i,useConsensus:!0,highlightElementsOnFailure:!0,attemptNumber:u,aiPageFiltering:e,logger:t}),frameConfig:r.iframeUrl?{type:"url",url:r.iframeUrl}:void 0,logger:t,browser:s})}catch(f){n.abortSignal.throwIfAborted(),m=f instanceof Error?f:new Error(`${f}`)}finally{u++}if(!p?.success){let f=`AI check still failing after ${u} attempts.`;throw m&&(f+=` Latest result: ${m.message}`),new _("AssertionFailureError",f)}return{...p,succeedImmediately:!1,urlAfterCommand:s.url()}}async function xw(r,e,t){let[n,o]=await Promise.all([In(r,{abortSignal:t,skipWait:!0,skipWaitForPageLoad:!0,logger:e}),r.screenshot({retries:1,respectActiveFrame:!0})]);return{...n,screenshotBuff:o}}async function _w({command:r,state:e,fixtures:t,useConsensus:n,useMemory:o,highlightElementsOnFailure:i,aiPageFiltering:a,attemptNumber:s,source:c,logger:l}){let{browser:u,generator:d,abortSignal:p}=t,g={type:"ASSERTION"},{serializedTree:m,tree:h}=e,f=e.screenshotBuff,E=f.toString("base64"),S=u.url(),A=r.contextChoice??"MULTIMODAL",C=m;A!=="VISION_ONLY"&&(C=await ho({type:"assertion",serializedTree:m,tree:h,description:r.assertion,screenshot:E,options:{aiPageFiltering:a},fixtures:{generator:d,signal:p,logger:l,orgId:t.orgId}}),C!==m&&(g.ragUsed=!0),g.pageState=C);let T={goal:r.assertion,url:S,memory:o?r.cache?.memory:void 0,browserState:C,screenshot:E,contextChoice:A,source:c},R=await(A==="VISION_ONLY"?(w,B)=>d.getVisualAssertionResult(w,B):(w,B)=>d.getAssertionResult(w,B))(T,{useConsensus:n,attemptNumber:s,useMemory:o,disableCache:!!r.disableCache,abortSignal:p,logger:l,loggerTags:ve(l)});return(R.result||i)&&R.relevantElements&&(g.relevantElementsSerialized=R.relevantElements.map(w=>u.getSerializedFormFromA11yId(w)).filter(w=>!!w),await pF(R.relevantElements,u,l)),{success:R.result,thoughts:R.thoughts,afterScreenshotOverride:f,updatedMemory:o?R.updatedMemory:void 0}}async function pF(r,e,t){let n=Date.now();for(let o of r){if(Date.now()-n>2e3){t.debug("Highlighting relevant elements took over 2s, aborting...");return}try{let i=new AbortController;await V(e.highlightA11yId(o),{milliseconds:1e3,fallback:()=>{throw i.abort(),new Error("Timed out waiting for highlighting to complete")}})}catch(i){t.debug({err:i},"Failed to highlight relevant element after assertion, continuing...");return}}}import{cloneDeep as Iw}from"lodash-es";async function Pw(r){let{command:e,timeoutMs:t,fixtures:n}=r,{abortSignal:o}=n,i=by(e.cache)?e.cache:void 0,a=Iw(i),s=()=>{if(i){let g=hv(a,i);i.target=g.target,i.updatedAt=g.updatedAt}},c=Date.now(),l=0,u,d=500,p=!1;for(;l<2||Date.now()-c<t;){l++,l>1&&await ee(d,o),o?.throwIfAborted();let{result:g,elementWasFound:m}=await Mw({cacheToUse:i,params:r});if(u=g,p=m,g.success)break;s(),d=Math.min(d*2,1e4)}if(!u)throw new _("InternalPlatformError",`Failed to evaluate manual element assertion in ${t}ms.`);if(o?.throwIfAborted(),!u.success&&i?.target&&dl(i.target)){let g=i?.target?.memory?{target:{id:-1,memory:i.target.memory}}:void 0,{result:m}=await Mw({cacheToUse:g,params:r});u=m,u.success||s()}return u.success&&i?.target&&!p&&(i.target=Yp(i.target),i.updatedAt=new Date),u}async function Mw({cacheToUse:r,params:e}){let{command:t,disableCache:n,fixtures:o,tracer:i,targetingWrapper:a}=e,{logger:s}=o;if(t.target&&!pn(t.target))throw new Error("Element assertion with x/y is not supported yet");let c=gF(t.assertion),l,u=!1,d=Iw(r);try{let{elementInteractedDisplayString:p,result:g,thoughts:m}=await a({ctx:o.ctx,tracer:i,command:t,target:t.target,cache:d?.target,action:async h=>mF(h.locator,e),options:{...t,allowNotActionableNodesOverride:!0,disableCache:n,memory:d?.target?.memory,disableGlobalLocatorRedirect:!0,source:Aa(t),targetName:"target"}});return l={success:g.success,data:g.data,err:g.err,elementInteractedDisplayString:p,thoughts:m},u=!0,g.success||(s.warn({aiThoughts:m,elementString:p,err:g.err},"Element check found an element but failed"),l={...g,thoughts:m}),{result:l,elementWasFound:u}}catch(p){if(c)return l={success:!0,thoughts:`The element described does not exist on the page: ${p.message}`,err:void 0,data:void 0},{result:l,elementWasFound:u};if(!(p instanceof _)||p.reason!="ActionFailureError")throw p;return l={success:!1,err:p,data:void 0,thoughts:void 0},s.warn({err:p},"Element check did not find an element and failed"),{result:l,elementWasFound:u}}}async function mF(r,{command:e,fixtures:t}){let n=e.assertion;await t.browser.highlight(r);let o=!0,i,a;switch(n.type){case"ELEMENT_CONTENT":{let c=await r.textContent()??"";if(a={elementTextContent:It(c,500,!0)},!Oc(c,n.value,n.operation,!!n.negated)){let l=n.negated?ao[n.operation]:so[n.operation];o=!1,i=new _("AssertionFailureError",`The content ${l} '${n.value}': ${c}`)}break}case"ELEMENT_ATTRIBUTE":{a={elementOuterHtml:It(await r.evaluate(l=>l.cloneNode(!1).outerHTML),500,!0)};let c;try{c=await r.getAttribute(n.attr,{timeout:3e3})??""}catch(l){i=new _("AssertionFailureError",`The element does not have an attribute named ${n.attr}: ${l}`),o=!1;break}if(!Oc(c,n.value,n.operation,!!n.negated)){let l=n.negated?ao[n.operation]:so[n.operation];o=!1,n.operation==="EXISTS"?i=new _("AssertionFailureError",`The attribute ${n.attr} ${l}`):i=new _("AssertionFailureError",`The attribute ${n.attr} ${l} '${n.value}': ${c}`)}break}case"ELEMENT_EXISTENCE":{switch(n.condition){case"VISIBLE":{o=await r.evaluate(async(l,u)=>{let d=Date.now();for(;Date.now()-d<u;){await new Promise(g=>setTimeout(g,250));let p=l.getBoundingClientRect();if(!(p.width===0||p.height===0)&&window.getComputedStyle(l).visibility!=="hidden"&&window.getComputedStyle(l).display!=="none")return!0}return!1},mn*1e3);break}case"EDITABLE":{o=await r.isEditable({timeout:mn*1e3});break}case"EXISTS":{o=!0;break}case"ENABLED":{o=await r.isEnabled({timeout:mn*1e3});break}case"FOCUSED":{o=await r.evaluate(l=>l===document.activeElement);break}default:return(l=>{throw"If Typescript complains about the line below, you missed a case or break in the switch above"})(n.condition)}if(o=n.negated?!o:o,!o){let c=n.negated?fv[n.condition]:Sv[n.condition];i=new _("AssertionFailureError",`The element ${c}`)}break}case"ELEMENT_NAME":{let c=await r.evaluate(l=>l.tagName);if(!Oc(c,n.value,n.operation,!!n.negated)){let l=n.negated?ao[n.operation]:so[n.operation];o=!1,i=new _("AssertionFailureError",`The element tag name ${l} '${n.value}': ${c}`)}break}case"ELEMENT_STYLE":{let c=await r.evaluate((l,u)=>window.getComputedStyle(l).getPropertyValue(u),n.property);if(!Oc(c,n.value,n.operation,!!n.negated)){let l=n.negated?ao[n.operation]:so[n.operation];o=!1,n.operation==="EXISTS"?i=new _("AssertionFailureError",`The style property ${n.property} ${l}`):i=new _("AssertionFailureError",`The style property ${n.property} ${l} '${n.value}': ${c}`)}break}default:return(c=>{throw"If Typescript complains about the line below, you missed a case or break in the switch above"})(n)}return{success:o,data:a,err:i}}function Oc(r,e,t,n){let o;switch(t){case"CONTAINS":{o=r.includes(e);break}case"EQUALS":{o=r.trim()===e.trim();break}case"STARTS_WITH":{o=r.trim().startsWith(e);break}case"EXISTS":{o=r.trim().length>0;break}default:return(a=>{throw"If Typescript complains about the line below, you missed a case or break in the switch above"})(t)}return n?!o:o}function gF(r){return r.type==="ELEMENT_EXISTENCE"&&r.negated&&(r.condition==="EXISTS"||r.condition==="VISIBLE")}function Ow(r){return r.type==="ELEMENT_EXISTENCE"&&r.negated&&r.condition==="EXISTS"}import{Jimp as hF}from"jimp";async function Ka(r,e){let t=await r.screenshot(e),n=await hF.fromBuffer(t);return{buffer:t,width:Math.ceil(n.bitmap.width??0),height:Math.ceil(n.bitmap.height??0)}}import{Jimp as Lw}from"jimp";import jm from"jpeg-js";import fF from"pixelmatch";async function Nw({ctx:r,tracer:e,command:t,disableCache:n,browser:o,targetingWrapper:i,logger:a,screenshotStorage:s}){if(t.target&&!pn(t.target))throw new Error("Visual Diff with x/y is not supported yet");await o.waitForDOMStability({logger:a});let c={clearHighlights:!0,hideCaret:!0},l;t.target?.elementDescriptor?l=(await i({ctx:r,tracer:e,command:t,target:t.target,cache:t.cache?.target,action:async U=>Ka(o,{locator:U.locator,...c}),options:{...t,disableCache:n,disableGlobalLocatorRedirect:!0,memory:t.cache?.target?.memory,targetName:"target"}})).result:l=await Ka(o,c);let u=await s.prepareGoldenScreenshotForComparison(a,t,l);if((l.height!==u.height||l.width!==u.width)&&a.warn({currHeight:l.height,currWidth:l.width,savedHeight:u.height,savedWidth:u.width},"Mismatched before and after visual diff screenshot sizes"),Math.abs(l.height-u.height)>10||Math.abs(l.width-u.width)>10){let D=`${l.width}x${l.height}`,U=`${u.width}x${u.height}`;return{fail:!0,thoughts:`Current screenshot (${D}) does not match saved screenshot dimensions (${U}) - did you change the size of the target or the viewport?`,beforeScreenshotOverride:u.buffer,afterScreenshotOverride:l.buffer,succeedImmediately:!1,urlAfterCommand:o.url()}}let d=await Lw.fromBuffer(l.buffer),p={width:l.width,height:l.height},g=await Lw.fromBuffer(u.buffer),m={width:u.width,height:u.height},h,f=p.width*p.height,E=m.width*m.height,S=Math.abs(p.height-m.height),A=Math.abs(p.width-m.width);if(f>E){let D=d.cover({w:m.width,h:m.height});l.buffer=await D.getBuffer("image/jpeg"),h="current",l.width=m.width,l.height=m.height}else if(E>f){let D=g.cover({w:p.width,h:p.height});u.buffer=await D.getBuffer("image/jpeg"),h="saved"}let C={data:Buffer.alloc(l.width*l.height*4),width:l.width,height:l.height},T=t.threshold??.1,R=fF(jm.decode(u.buffer).data,jm.decode(l.buffer).data,C.data,l.width,l.height,{threshold:T,diffColorAlt:[0,255,0]})/(l.width*l.height)*100,w=R>T*100,B=`Visual diff of ${R.toFixed(2)}% detected, which is ${w?"over":"under"} the threshold of ${T*100}%.`;if(h&&(B+=` The ${h} screenshot was cropped since it was taller by ${S} pixels and wider by ${A} pixels.`),w)throw new _("ActionFailureError",B);return{fail:w,thoughts:B,beforeScreenshotOverride:l.buffer,afterScreenshotOverride:jm.encode(C,75).data,succeedImmediately:!1,urlAfterCommand:o.url()}}var SF=3e4;async function Lc({command:r,logger:e,baseUrl:t,fetchImplementation:n=fetch}){let o=r.timeout??SF/1e3,i=Object.fromEntries(Object.entries(r.headers||{}).filter(([g,m])=>g&&m)),a=new URLSearchParams;Object.entries(r.params||{}).filter(([g,m])=>g&&m).forEach(([g,m])=>{a.append(g,m)});let s=a.toString(),c;if(ui(r.url)&&(c=r.url),t&&di(r.url,t)&&(c=new URL(r.url,t).toString()),!c)throw new _("ActionFailureError",`Invalid URL: ${r.url}`);e.info({url:c,searchParams:s,headers:i,body:r.body,method:r.method},"Making HTTP request");let u=await V((async()=>{let g=s?`${c}?${s}`:c;try{return await n(g,{headers:i,method:r.method,body:r.body})}catch(m){throw e.error({err:m},"Failed to make HTTP request"),new Error(`Failed to make HTTP request: ${m}`)}})(),{milliseconds:o*1e3,fallback:()=>{throw new _("ActionFailureError",`Fetch request timed out after ${o} seconds`)}});if(!u.ok){let g;try{g=await u.text()}catch(m){g=`Failed to read response body: ${m}`}throw new _("ActionFailureError",`Fetch request failed with status ${u.status}: ${g}`)}let d={};u.headers.forEach((g,m)=>{d[m]=g});let p={status:u.status,headers:d};if(u.headers.get("content-type")?.includes("json"))try{p.json=await u.json()}catch{}else u.headers.get("content-type")?.includes("text")&&(p.text=await u.text());return p}var yF=5e3;async function Uw({timeout:r=mn,...e}){let t=Date.now(),n=r*1e3,o=n+1e4,i,a=0,s=500;for(;a-t<n;){if(Date.now()-t>o){e.logger.warn("Exceeded max system timeout for page assertion, exiting...");break}e.signal.throwIfAborted();let c=Date.now();i=await kw(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 ee(s,e.signal),s=Math.min(Math.floor(s*1.5),yF);else return i}return i=await kw(e),i}async function kw({assertion:r,browser:e,autoExpandIframes:t}){switch(r.type){case"CONTENT":{let o,i=!1,a;try{let s;if(t){let c=await e.evaluateFunctionInAllFrames(Dw,{value:r.value,negated:!!r.negated,returnHtml:!1});i=r.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(Dw,{value:r.value,negated:!!r.negated,returnHtml:!0},"checking page content"));if(!i){let c=r.negated?ao.CONTAINS:so.CONTAINS;a=new _("AssertionFailureError",`The page ${c} '${r.value}'.`),o=s}}catch(s){a=new _("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"})(r.type)}}function Dw({value:r,negated:e,returnHtml:t}){let n=document.documentElement.outerHTML,o=n.includes(r)===!e;return n.length>1e4&&(n=n.slice(0,1e4)+"...TRUNCATED"),{evaluation:o,pageHtml:!o&&t?n:void 0}}var bF=3e4;async function Fw({command:r,logger:e,baseUrl:t,fetchImplementation:n=fetch}){let o=r.timeout??bF/1e3,i=new AbortController,a=Object.fromEntries(Object.entries(r.headers||{}).filter(([d,p])=>d&&p));a["Content-Type"]="application/json";let s;if(ui(r.url)&&(s=r.url),t&&di(r.url,t)&&(s=new URL(r.url,t).toString()),!s)throw new _("ActionFailureError",`Invalid URL: ${r.url}`);let l=await V((async()=>{try{return await n(s,{headers:a,method:"POST",body:JSON.stringify({query:r.query,variables:r.variables?JSON.parse(r.variables):void 0}),signal:i.signal})}catch(d){e.error({err:d},"Failed to make HTTP request")}})(),{milliseconds:o*1e3});if(!l)throw new _("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 _("ActionFailureError",`GraphQL request failed with status ${l.status}: ${p}`)}throw d?.errors?.length&&d?.errors[0]?.message?new _("ActionFailureError",`GraphQL request failed with status ${l.status}: ${d.errors[0].message}`):new _("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 Nc=class{orgId;options;storage;localCodeEvalTools;uploadedFileStorage;visualDiffScreenshotStorage;browser;generator;executeAbortController=new AbortController;logger;recordAbortController=null;registeredListeners={};recordedRequests={};constructor({browser:e,generator:t,logger:n,storage:o,orgId:i,localCodeEvalTools:a,uploadedFileStorage: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=t,this.logger=n}setOpen(){this.executeAbortController=new AbortController,this.browser.registerAbortSignal(this.executeAbortController.signal)}setClosed(){this.executeAbortController.abort()}throwIfClosed(){this.executeAbortController.signal.throwIfAborted()}get closed(){return this.executeAbortController.signal.aborted}async evaluateAiAction({goal:e,startingScreenshot:t,history:n,disableCache:o,langfuseSessionId:i,lastError:a,logger:s=this.logger}){let[c,l]=await Promise.all([In(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 ho({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:t,history:n,goal:e,screenshot:u,lastError:a};return await this.generator.getMultiturnAiActionEvaluation(p,{disableCache:o,abortSignal:this.executeAbortController.signal,loggerTags:{...ve(s)},langfuseSessionId:i})}async promptToCommand({goal:e,startingScreenshot:t,history:n,actionHint:o,disableCache:i,logger:a=this.logger,langfuseSessionId:s}){let c=this.browser.url(),[l,u]=await Promise.all([In(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 ho({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}}),g={url:c,browserState:p,startingScreenshot:t,history:n,goal:e,actionHint:o,screenshot:d};try{return await this.generator.getMultiturnAiActionCommand(g,{disableCache:i,abortSignal:this.executeAbortController.signal,loggerTags:{...ve(a)},langfuseSessionId:s})}catch(m){throw new _("InternalWebAgentError",`Error generating command: ${m instanceof Error?m.message:m}`,{errOptions:{cause:m}})}}async getBrowserState(e){return In(this.browser,e)}async locateElement(e){return await Gm({...e,aiPageFiltering:!!this.options?.aiPageFiltering},this.getControllerFixtures())}async locateElementWithSelector(e,t){return zr({action:async()=>{let n=await this.browser.resolveHardcodedCssSelector({ctx:null,selector:e,timeoutMs:2e3,logger:this.logger});return{thoughts:"Located element with selector",target:{id:-1,selector:e,targetSource:"USER_CSS_SELECTOR",targetUpdateTime:new Date().toUTCString()},resolution:n}},frameConfig:t?{type:"url",url:t}:void 0,browser:this.browser,logger:this.logger})}getControllerFixtures(e){return{ctx:e??null,browser:this.browser,generator:this.generator,logger:this.logger,orgId:this.orgId,storage:this.storage,localCodeEvalTools:this.localCodeEvalTools,abortSignal:this.executeAbortController.signal}}shouldUseMemory(){return this.options?.useMemory??(this.orgId==="org_01HMSCJQBCCG51M2ZF65YC5B8W"||this.orgId==="org_01HMJTX4GT1KG94KZRCT8MZ6YB")}async wrapMultiElementTargetingCommand({ctx:e,tracer:t,command:n,targetNames:o,descriptions:i,caches:a,action:s,options:c,retriesWithAI:l=1}){let u=[];for(let d=0;d<i.length;d++){let p=i[d],g=await this.wrapElementTargetingCommand({ctx:e,tracer:t,command:n,target:p,cache:a[d],action:async m=>m,options:{...c,targetName:o[d]}});u.push(g)}try{let d=await s(...u.map(m=>m.result)),p=m=>m==="fromTarget"?"From Target":m==="toTarget"?"To Target":"Target",g=u.map((m,h)=>m.thoughts?`${p(o[h])}: ${m.thoughts}`:void 0).filter(m=>!!m).join(" -------------- ")||void 0;return{result:d,elementInteractedDisplayStrings:u.map(m=>m.elementInteractedDisplayString),thoughts:g}}catch(d){if(this.throwIfClosed(),l>0)return this.logger.warn({err:d},"Failed to execute action with multiple cached targets, retrying with AI"),this.wrapMultiElementTargetingCommand({ctx:e,tracer:t,command:n,targetNames:o,descriptions:i,caches:i.map(()=>{}),action:s,options:c,retriesWithAI:l-1});throw new _("ActionFailureError",d.message,{errOptions:{cause:d}})}}async wrapElementTargetingCommand(e){let t=this.logger.child({commandId:e.command.id}),n;for(let o=0;o<2;o++)try{return await zr({action:()=>this.wrapElementTargetingCommandHelper({...e,originalCache:e.originalCache??e.cache}),frameConfig:e.options.iframeUrl?{type:"url",url:e.options.iframeUrl}:void 0,browser:this.browser,logger:t})}catch(i){if(n=i,this.browser.userBrowserSettings.visualActions&&Gd(i)){t.warn({err:i},"Invalid mpath error, retrying element targeting command");continue}if(!this.browser.userBrowserSettings.visualActions&&(Vd(i)||jd(i))){t.warn({err:i},"Invalid momentic id error, retrying element targeting command");continue}if(Wd(i)){t.warn({err:i},"Invalid backend node id error, retrying element targeting command");continue}if(i instanceof Pr&&i.retryableWithAI){t.warn({err:i},"Element cache disqualification error, retrying element targeting command");continue}throw i}throw n instanceof _?n:new _("ActionFailureError",n?.message??"An unknown error occurred during element targeting")}async wrapHardcodedCssTargetingCommandHelper({ctx:e,target:t,action:n,options:o,command:i}){let a=this.logger.child({commandId:i.id}),{targetName:s}=o;if(t.type!=="description")throw new _("ActionFailureError","Cannot use selector with non-description target");let c,l=Date.now(),u=Date.now();for(;Date.now()-u<this.browser.smartWaitingTimeout;){l=Date.now();try{let d=await this.browser.resolveHardcodedCssSelector({ctx:e,selector:t.elementDescriptor,targetName:s,logger:a});return{result:await n({locator:d.locator}),elementInteractedDisplayString:d.displayString}}catch(d){if(d.name==="AbortError")throw d;c=d,a.warn({err:d},"Failed to action on hardcoded css selector"),Date.now()-l<500&&await ee(500)}}throw c}async wrapElementTargetingCommandHelper(e){let{ctx:t,tracer:n,target:o,originalCache:i,action:a,options:s,command:c}=e,{disableCache:l,useSelector:u,targetName:d,targetHealingInProgress:p,source:g}=s,m=this.logger.child({commandId:c.id}),h=this.shouldUseMemory(),f=s.retriesWithAI??1,E=!1,S=Bw(e.cache);if((!S||l)&&!Rd(o))throw new _("ActionFailureError","Cannot target element with no cached data or element descriptor");if(u)return this.wrapHardcodedCssTargetingCommandHelper(e);l&&(m.info("Cache explicitly disabled for this step"),E=!0,S=void 0),S&&this.browser.userBrowserSettings.disableSecondaryCacheResolution&&S.targetSource==="HEURISTIC_HEALED"&&(E=!0,S=void 0),S?.inputDescription&&!Cw(o.elementDescriptor,S.inputDescription)&&(m.warn({old:S.inputDescription,new:o.elementDescriptor},"Target cache was generated with a different description, clearing it automatically"),E=!0,S=void 0);let A=T=>!!T&&dl(T),C=!0;if(!A(S)){C=!1,m.info({description:o.elementDescriptor,targetHealingInProgress:p,cacheBustedBeforeAction:E,memory:s.memory,useMemory:h},"Prompting AI for an updated element location"),E&&await ee(this.browser.smartWaitingTimeout,this.executeAbortController.signal),f--;let T;try{T=await Gm({description:o.elementDescriptor,disableCache:!!s.disableCache,iframeUrl:s.iframeUrl,source:g,useMemory:h,memory:h?s.memory:void 0,aiPageFiltering:!!this.options?.aiPageFiltering,allowNotActionableNodesOverride:s.allowNotActionableNodesOverride,logger:m},this.getControllerFixtures(t))}catch(w){if(w instanceof Xo&&w.updatedLocatorMemory){let B={id:-1,...i,memory:w.updatedLocatorMemory};lc({cmd:c,key:d,newTarget:B,logger:m,updatedWithAI:!0})}throw new _("ActionFailureError",w.message)}T.frameConfig&&this.browser.setActiveFrameConfig(T.frameConfig);let I=s.disableGlobalLocatorRedirect?{locator:T.resolution.locator}:await this.attemptLocatorRedirect(T.resolution.locator,m),R=await a(I);return lc({cmd:c,key:d,newTarget:T.target,logger:m,updatedWithAI:!0}),p&&(n.recordTargetAutoHeal({healType:"AI"}),T.target.targetSource="AI_HEALED",T.target.targetUpdateTime=new Date().toUTCString(),T.target.targetUpdateLoggerTags=ve(m)),{result:R,elementInteractedDisplayString:T.resolution.displayString,thoughts:T.thoughts}}try{let T=await this.browser.resolveTarget(t,S,{allowNotActionableNodesOverride:s.allowNotActionableNodesOverride,targetName:d,logger:m,signal:this.executeAbortController.signal});(this.browser.userBrowserSettings.visualActions||this.browser.userBrowserSettings.globalLocatorRedirect!==!1)&&await this.browser.scrollIntoViewIfNeeded(T.locator);let I=s.disableGlobalLocatorRedirect?{locator:T.locator}:await this.attemptLocatorRedirect(T.locator,m),R=await a(I);if(St.increment("cache_target_resolution_v2",1,["outcome:hit","platform:web",`hasRequirements:${!!S.requirements}`,`hasAdditionalElements:${!!S.additionalElements}`,`orgId:${this.orgId}`]),lc({cmd:c,key:d,newTarget:S,logger:m,updatedWithAI:!1}),C){let w=T.decisions.filter(B=>B.matched);if(w.length!==1)m.warn({decisions:T.decisions},"Expected exactly 1 matching method for element location, got more or less");else{let B=w[0].type;n.recordTargetAutoHeal({healType:B})}}return{result:R,elementInteractedDisplayString:T.displayString}}catch(T){this.throwIfClosed(),St.increment("cache_target_resolution_v2",1,["outcome:miss","platform:web",`hasRequirements:${!!S.requirements}`,`hasAdditionalElements:${!!S.additionalElements}`,`orgId:${this.orgId}`]);let I=!1;if((T instanceof Pr||Gd(T)||Vd(T)||Wd(T)||db(T)||jd(T))&&(I=!0),T instanceof _&&!I)throw m.error({err:T},"Failed to execute action with cached target (fatal)"),T;if(f>0&&o){m.info({err:T},"Failed to execute action with cached target, retrying with AI");let R;return S.memory&&my(S.memory)&&(R=S.memory),this.wrapElementTargetingCommand({ctx:t,tracer:n,command:c,target:o,cache:void 0,originalCache:i,action:a,options:{...s,memory:R,retriesWithAI:f,targetHealingInProgress:!0}})}throw new _("ActionFailureError",T.message,{errOptions:{cause:T}})}}async attemptLocatorRedirect(e,t){return this.browser.userBrowserSettings.globalLocatorRedirect!==!1?this.browser.performTargetRedirection(e,t):{locator:e}}async screenshotWithDimensions(e){return Ka(this.browser,e)}async executePresetCommand(e,t,n,o,i){this.options?.slowMoMs&&await ee(this.options.slowMoMs);let a=await this.browser.getOpenPages(),s=this.browser.url(),c;try{c=await this.resolveCommandTemplateStrings(n,o)}catch(l){throw this.throwIfClosed(),new _("ActionFailureError",`Failed to substitute template strings in command: ${l.message}`,{errOptions:{cause:l}})}try{let l=await this.executePresetCommandHelper(e,t,n,o,i);return this.browser.userBrowserSettings.visualActions&&My(n)?await this.browser.waitForDOMStability({timeout:he}):!this.browser.userBrowserSettings.visualActions&&["PRESS","TYPE"].includes(n.type)&&await this.browser.waitForDOMStability({timeout:re}),this.options?.autoFollowNewTabs&&await Sw({beforeUrl:s,command:n,beforePages:a.map(u=>u.url),browser:this.browser,logger:this.logger}),l}catch(l){throw l.name!=="AbortError"&&this.logger.error({err:l},"Error thrown in action controller"),l}finally{sc(n,c)}}createCallbacksForBrowser(e){return{createIsolatedFolder:()=>pm(e)}}async resolveCommandTemplateStrings(e,t){return ac({obj:e,context:t,bannedKeys:["type","a11yData","thoughts","cache","code"],orgId:this.orgId,logger:this.logger,signal:this.executeAbortController.signal,localTools:this.localCodeEvalTools})}async executePresetCommandHelper(e,t,n,o,i){i=i||"disableCache"in n&&!!n.disableCache;let a=this.logger.child({commandId:n.id});switch(n.type){case"SUCCESS":let s=n.condition;return s?.assertion.trim()?Pc({command:s,fixtures:this.getControllerFixtures(e),useMemory:this.shouldUseMemory(),aiPageFiltering:!!this.options?.aiPageFiltering,logger:a}):{succeedImmediately:!1,urlAfterCommand:this.browser.url()};case"AI_ASSERTION":{if(!n.assertion.trim())throw new _("ActionFailureError","Missing assertion");if(n.timeout&&n.timeout>1800)throw new _("AssertionFailureError",`AI check timeout of ${n.timeout} exceeds the maximum allowed value of 30 minutes.`);return Pc({command:n,fixtures:this.getControllerFixtures(e),useMemory:this.shouldUseMemory(),aiPageFiltering:!!this.options?.aiPageFiltering,logger:a})}case"AI_EXTRACT":{if(!n.goal.trim())throw new _("ActionFailureError","Cannot perform AI extraction without goal");if(n.schema){let f=qT(n.schema);if(f)throw new _("UserConfigurationError",f)}let m=await this.browser.getCondensedHtml(),h=await this.browser.screenshot({retries:2});try{let f=await this.generator.getTextExtraction({goal:n.goal,browserState:m,returnSchema:n.schema,screenshot:`data:image/jpeg;base64,${h.toString("base64")}`},{disableCache:i,abortSignal:this.executeAbortController.signal,loggerTags:ve(a)});if(f.result==="NOT_FOUND")throw new _("ActionFailureError","No relevant data found for extraction goal on this page");if(f.thoughts?.includes("MaxGenerationLengthExceededError"))throw new _("UserConfigurationError",f.thoughts);return{thoughts:f.thoughts||void 0,data:f.result,succeedImmediately:!1,urlAfterCommand:this.browser.url()}}catch(f){let E=f.message;throw E.includes("MaxGenerationLengthExceededError")?new _("UserConfigurationError","You tried to extract too much data. Please rephrase your query to limit the results returned or use a JavaScript step in the browser instead."):E.includes("AIProviderError")&&E.includes("time")?new _("AIProviderError","The AI provider responded with an error. This may be because you tried to extract too much data. Please limit extraction results to 2000 characters.",{errOptions:{cause:f}}):f}}case"NAVIGATE":if(!ui(n.url)&&!di(n.url,this.browser.baseUrl))throw new _("ActionFailureError",`Invalid URL provided to navigate command: ${n.url}`);await this.browser.navigate({url:n.url,loadTimeoutMs:n.loadTimeout?n.loadTimeout*1e3:void 0});break;case"DIALOG":this.browser.registerDialogHandler(n.action);break;case"CAPTCHA":if(!this.browser.canSolveCaptchas())break;let c=await this.browser.solveCaptcha();c&&(await this.wrapElementTargetingCommand({ctx:e,tracer:t,command:n,target:{type:"description",elementDescriptor:"the captcha image solution input"},cache:void 0,action:m=>this.browser.click(m,this.createCallbacksForBrowser(this.orgId),{}),options:{...n,targetName:"target",disableCache:i}}),await this.browser.type(c,{clearContent:!0,pressEnter:!0},!0));break;case"GO_BACK":await this.browser.goBack();break;case"GO_FORWARD":await this.browser.goForward();break;case"SCROLL_LEFT":case"SCROLL_RIGHT":case"SCROLL_DOWN":case"SCROLL_UP":{let m,h;if(n.target&&Mr(n.target))await this.browser.hoverUsingVisualCoordinates(n.target.pixels);else if(n.target&&n.target.elementDescriptor.trim()){let{elementInteractedDisplayString:S,thoughts:A}=await this.wrapElementTargetingCommand({ctx:e,tracer:t,command:n,target:n.target,cache:n.cache?.target,action:C=>this.browser.hover(C),options:{...n,targetName:"target",disableGlobalLocatorRedirect:!0,disableCache:i}});m=S,h=A}let f=this.browser.getViewport()?.height??yn.height,E=this.browser.getViewport()?.width??yn.width;switch(n.type){case"SCROLL_UP":await this.browser.scrollVertical(-(n.deltaY??f));break;case"SCROLL_DOWN":await this.browser.scrollVertical(n.deltaY??f);break;case"SCROLL_LEFT":await this.browser.scrollHorizontal(-(n.deltaX??E));break;case"SCROLL_RIGHT":await this.browser.scrollHorizontal(n.deltaX??E);break}return{succeedImmediately:!1,urlAfterCommand:this.browser.url(),elementInteracted:m,thoughts:h}}case"WAIT_FOR_URL":{if(n.timeout&&n.timeout>1800)throw new _("UserConfigurationError",`Wait for URL timeout of ${n.timeout} exceeds the maximum allowed value of 30 minutes.`);let m=n.matcher;await this.browser.waitForUrl({beforeUrl:this.browser.url(),matcher:m},{timeout:n.timeout?n.timeout*1e3:void 0,negated:n.negated,caseInsensitive:n.caseInsensitive});break}case"WAIT":if(n.delay>1800)throw new _("UserConfigurationError",`Wait timeout of ${n.delay} seconds exceeds the maximum allowed value of 30 minutes`);let l=n.delay*1e3;await ee(l,this.executeAbortController.signal);break;case"REFRESH":await this.browser.refresh({loadTimeoutMs:n.loadTimeout?n.loadTimeout*1e3:void 0});break;case"CLICK":{if(Mr(n.target)){await this.browser.clickUsingVisualCoordinates(n.target.pixels,n);break}let m=this.browser.url(),{elementInteractedDisplayString:h,result:f,thoughts:E}=await this.wrapElementTargetingCommand({ctx:e,tracer:t,target:n.target,command:n,cache:n.cache?.target,action:A=>this.browser.click(A,this.createCallbacksForBrowser(this.orgId),n),options:{disableCache:i,targetName:"target",...n}}),S={urlAfterCommand:this.browser.url(),succeedImmediately:!1,elementInteracted:h,thoughts:E,data:f.downloadedFile?{downloadedFile:f.downloadedFile}:void 0};return hc(m,S.urlAfterCommand)&&(S.succeedImmediately=!0,S.succeedImmediatelyReason="URL changed"),S}case"COPY":return await this.browser.copy(n.value),{succeedImmediately:!1,data:n.value,urlAfterCommand:this.browser.url()};case"PASTE":{await this.browser.paste();break}case"DRAG":{if(Mr(n.fromTarget)&&Mr(n.toTarget)){await this.browser.dragAndDropUsingVisualCoordinates(n.fromTarget.pixels,n.toTarget.pixels,{hoverSeconds:n.hoverSeconds});break}if(Mr(n.fromTarget)||Mr(n.toTarget))throw new Error("Drag and drop targets must be both coordinates or both descriptions");let{elementInteractedDisplayStrings:m,thoughts:h}=await this.wrapMultiElementTargetingCommand({ctx:e,tracer:t,command:n,targetNames:["fromTarget","toTarget"],descriptions:[n.fromTarget,n.toTarget],caches:[n.cache?.fromTarget,n.cache?.toTarget],action:(f,E)=>this.browser.dragAndDrop(f.locator,E.locator,{hoverSeconds:n.hoverSeconds,steps:n.steps}),options:{useSelector:!!n.useSelector,disableCache:i}});return{succeedImmediately:!1,urlAfterCommand:this.browser.url(),elementInteracted:m[0],thoughts:h}}case"MOUSE_DRAG":{let m=parseInt(n.deltaX),h=parseInt(n.deltaY),f=n.steps??5;if(isNaN(m)||isNaN(h))throw new _("ActionFailureError",`Invalid pixel values passed to mouse drag command: (${n.deltaX}, ${n.deltaY})`);if(n.target&&Mr(n.target)){await this.browser.mouseDragUsingVisualCoordinates(m,h,f,n.target.pixels,{force:n.force});break}let E,S,A;if(n.target?.elementDescriptor){let{elementInteractedDisplayString:C,result:T,thoughts:I}=await this.wrapElementTargetingCommand({ctx:e,tracer:t,command:n,target:n.target,cache:n.cache?.target,action:async R=>R.locator,options:{disableCache:i,targetName:"target",...n}});E=T,S=C,A=I}return await this.browser.mouseDrag(m,h,f,E,{force:n.force}),{succeedImmediately:!1,urlAfterCommand:this.browser.url(),elementInteracted:S,thoughts:A}}case"SELECT_OPTION":{if(!pn(n.target))throw new Error("Select with x/y is not supported yet");let m=n.target.elementDescriptor,h=n.choice,{elementInteractedDisplayString:f,thoughts:E}=await this.wrapElementTargetingCommand({ctx:e,tracer:t,command:n,target:{type:"description",elementDescriptor:m},cache:n.cache?.target,action:S=>this.browser.selectOption(S,h,n.force),options:{...n,targetName:"target",disableCache:i,source:Aa(n)}});return{succeedImmediately:!1,urlAfterCommand:this.browser.url(),elementInteracted:f,thoughts:E}}case"TAB":{let m={loadTimeoutMs:n.loadTimeout?n.loadTimeout*1e3:void 0,retry:!0};await this.browser.switchToPage(n.action,m);break}case"NEW_TAB":await this.browser.createNewTab(n.url,{loadTimeoutMs:n.loadTimeout?n.loadTimeout*1e3:void 0});break;case"COOKIE":if(!n.value)break;let u=await this.browser.setCookie(n.value);a.debug({results:u},"Set cookies");break;case"LOCAL_STORAGE":if(!n.value||!n.key)break;await this.browser.setLocalStorage(n.key,n.value);break;case"JAVASCRIPT":{let m;try{n.environment==="BROWSER"?(m=await this.browser.evaluateCodeInPage({code:n.code,fragment:n.fragment??!1,context:o.toObjectCopy(),timeoutMs:n.timeout?n.timeout*1e3:void 0}),a.info({result:m},"Executed JavaScript in browser")):m=await kr({orgId:this.orgId,code:n.code,fragment:!!n.fragment,context:o,timeoutMs:n.timeout?n.timeout*1e3:void 0,logger:a,localTools:this.localCodeEvalTools,signal:this.executeAbortController.signal,callbacks:{onPersistentVariableUpdates:async h=>{if(!this.options?.scratchPadId){a.warn({updates:h},"Got persistent variable updates but scratch pad is not available");return}await this.storage.savePersistentVariables?.({scratchPadId:this.options?.scratchPadId,orgId:this.orgId,updates:h,logger:a})}}})}catch(h){throw this.throwIfClosed(),new _("ActionFailureError",h instanceof Error?h.message:`${h}`,{errOptions:{cause:h}})}try{JSON.stringify(m)}catch(h){throw new _("ActionFailureError",`Return value is not serializable: ${h instanceof Error?h.message:`${h}`}`,{errOptions:{cause:h}})}return{urlAfterCommand:this.browser.url(),succeedImmediately:!1,data:m}}case"TYPE":{if(n.target&&Mr(n.target)){await this.browser.clickUsingVisualCoordinates(n.target.pixels,n),await this.browser.type(n.value,{force:n.force,clearContent:n.clearContent,forceClearContent:n.forceClearContent,delay:n.delay,pressEnter:n.pressEnter},!0);break}let m=this.browser.url(),h,f,E=Bw(n.target),S=this.browser.userBrowserSettings.globalLocatorRedirect===void 0||this.browser.userBrowserSettings.globalLocatorRedirect==="always";if(E){let{elementInteractedDisplayString:C,thoughts:T}=await this.wrapElementTargetingCommand({ctx:e,tracer:t,command:n,target:E,cache:n.cache?.target,action:I=>this.browser.typeIntoTarget(n.value,I,{force:n.force,clearContent:n.clearContent,forceClearContent:n.forceClearContent,delay:n.delay,pressEnter:n.pressEnter,relativePosition:n.relativePosition}),options:{...n,targetName:"target",disableCache:i,disableGlobalLocatorRedirect:!S,source:Aa(n)}});h=C,f=T}else await this.browser.type(n.value,{force:n.force,clearContent:n.clearContent,forceClearContent:n.forceClearContent,delay:n.delay,pressEnter:n.pressEnter},!0);let A={urlAfterCommand:this.browser.url(),succeedImmediately:!1,elementInteracted:h,thoughts:f};return hc(m,A.urlAfterCommand)&&(A.succeedImmediately=!0,A.succeedImmediatelyReason="URL changed"),A}case"HOVER":{if(Mr(n.target)){await this.browser.hoverUsingVisualCoordinates(n.target.pixels);break}let{elementInteractedDisplayString:m,thoughts:h}=await this.wrapElementTargetingCommand({ctx:e,tracer:t,command:n,target:n.target,cache:n.cache?.target,action:f=>this.browser.hover(f),options:{...n,targetName:"target",disableCache:i}});return{succeedImmediately:!1,urlAfterCommand:this.browser.url(),elementInteracted:m,thoughts:h}}case"FOCUS":{if(!pn(n.target))throw new Error("Focus with x/y is not supported yet");let{elementInteractedDisplayString:m,thoughts:h}=await this.wrapElementTargetingCommand({ctx:e,tracer:t,command:n,target:n.target,cache:n.cache?.target,action:f=>this.browser.focus(f),options:{...n,targetName:"target",disableCache:i}});return{succeedImmediately:!1,urlAfterCommand:this.browser.url(),elementInteracted:m,thoughts:h}}case"BLUR":{if(n.target&&!pn(n.target))throw new Error("Blur with x/y is not supported yet");if(!n.target||!n.target.elementDescriptor)return await this.browser.blur(null),{succeedImmediately:!1,urlAfterCommand:this.browser.url()};let{elementInteractedDisplayString:m,thoughts:h}=await this.wrapElementTargetingCommand({ctx:e,tracer:t,target:n.target,command:n,cache:n.cache?.target,action:f=>this.browser.blur(f),options:{...n,targetName:"target",disableCache:i}});return{succeedImmediately:!1,urlAfterCommand:this.browser.url(),elementInteracted:m,thoughts:h}}case"PRESS":let d=this.browser.url();await this.browser.press(n.value,{repeat:n.repeat,convertMeta:n.convertMeta??!0,delayMs:n.delayMs});let p={urlAfterCommand:this.browser.url(),succeedImmediately:!1};return hc(d,p.urlAfterCommand)&&(p.succeedImmediately=!0,p.succeedImmediatelyReason="URL changed"),p;case"KEY_DOWN":return await this.browser.keyDown(n.value,{convertMeta:n.convertMeta??!0}),{urlAfterCommand:this.browser.url(),succeedImmediately:!1};case"KEY_UP":return await this.browser.keyUp(n.value,{convertMeta:n.convertMeta??!0}),{urlAfterCommand:this.browser.url(),succeedImmediately:!1};case"REQUEST":{let m=new TF,h=EF(fetch,m),f;try{f=new URL(n.url).hostname}catch{}return{data:{...await Lc({command:n,baseUrl:this.browser.baseUrl,logger:a,fetchImplementation:h}),cookies:Fl(m,f)},succeedImmediately:!1,urlAfterCommand:this.browser.url()}}case"GRAPHQL_REQUEST":return{data:await Fw({command:n,baseUrl:this.browser.baseUrl,logger:a}),succeedImmediately:!1,urlAfterCommand:this.browser.url()};case"VISUAL_DIFF":return Nw({ctx:e,tracer:t,command:n,disableCache:i,browser:this.browser,logger:a,storage:this.storage,screenshotStorage:this.visualDiffScreenshotStorage,targetingWrapper:m=>this.wrapElementTargetingCommand(m)});case"FILE_UPLOAD":{let m,h;if(n.fileSource.type==="URL"?(h=n.fileSource.url,m=await pA({uri:n.fileSource.url,logger:a,orgId:this.orgId})):n.fileSource.type==="USER_FILE"&&(h=n.fileSource.name,m=await this.uploadedFileStorage?.getFileForUpload(n.fileSource.name,this.orgId)),!m)throw new _("UserConfigurationError",`Attempted to use non-existent file for upload step: ${h}`);await this.browser.setFileChooserHandler({...m,filename:n.filename});break}case"AUTH_SAVE":return{data:await this.browser.saveAuthState(),succeedImmediately:!1,urlAfterCommand:this.browser.url()};case"AUTH_LOAD":{let m;if(!n.storageState.trim())m=void 0;else if(m=await kr({orgId:this.orgId,code:n.storageState,fragment:!1,context:o,logger:a,localTools:this.localCodeEvalTools,signal:this.executeAbortController.signal}),typeof m!="object")throw new _("ActionFailureError",`Credentials must evaluate to an object (received ${typeof m} instead)`);let h;try{h=SE.optional().parse(m)}catch(f){throw new _("ActionFailureError",`Credentials provided do not follow the required format: ${f}`)}await this.browser.loadAuthState(h);break}case"ELEMENT_CHECK":{let m=(n.timeout??mn)*1e3,h=this.generator.getAgentConfig()?.assertion;if(Ow(n.assertion)&&!n.useSelector&&n.target.type==="description"&&h&&h!=="v1"){let E={id:n.id,type:"AI_ASSERTION",assertion:`There is no element on the page closely matches the following description. If the description has single quotes, remember that requires an exact text substring match. Description: ${n.target.elementDescriptor}`,iframeUrl:n.iframeUrl,timeout:n.timeout,cache:n.cache&&"memory"in n.cache?{memory:n.cache?.memory}:void 0};try{let S=await Pc({command:E,logger:a,aiPageFiltering:!!this.options?.aiPageFiltering,fixtures:this.getControllerFixtures(e),useMemory:this.shouldUseMemory(),source:"NEGATED_CHECK"});return{succeedImmediately:!1,thoughts:`The element described does not exist on the page: ${S.thoughts}`,urlAfterCommand:this.browser.url(),afterScreenshotOverride:S.afterScreenshotOverride}}finally{E.cache?.memory&&cc(n,E.cache?.memory.traces,a)}}let f=await Pw({command:n,tracer:t,timeoutMs:m,targetingWrapper:E=>this.wrapElementTargetingCommand(E),fixtures:this.getControllerFixtures(e),disableCache:i});return{fail:!f.success,data:f.data,elementInteracted:f.elementInteractedDisplayString,thoughts:f.err?.message??f.thoughts??`Element assertion ${f.success?"succeeded":"failed"}.`,succeedImmediately:!1,urlAfterCommand:this.browser.url()}}case"PAGE_CHECK":{let m=await zr({action:async()=>Uw({assertion:n.assertion,browser:this.browser,logger:a,timeout:n.timeout,signal:this.executeAbortController.signal,autoExpandIframes:!!this.browser.userBrowserSettings.autoExpandIframes}),frameConfig:n.iframeUrl?{type:"url",url:n.iframeUrl}:void 0,browser:this.browser,logger:a});return{fail:!m.success,data:m.data,thoughts:m.success?"Page assertion passed.":m.err?.message??`Page assertion still failing after ${n.timeout} seconds.`,urlAfterCommand:this.browser.url(),succeedImmediately:!1}}case"REGISTER_REQUEST_LISTENER":{let m=new _n(n.requestMatcher),h=this.browser.registerRequestListener(m);return this.registeredListeners[n.key]=h.then(async f=>await bm(f)).catch(f=>{a.error({err:f},"Failed to get request listener response")}),{succeedImmediately:!1,urlAfterCommand:this.browser.url()}}case"AWAIT_LISTENER":{let m=this.registeredListeners[n.key];if(!m)throw new _("ActionFailureError",`No listener registered with key: ${n.key}`);let h=n.timeout??10;return{data:await V(m,{milliseconds:h*1e3,message:`Request listener timed out after ${h} seconds`}),succeedImmediately:!1,urlAfterCommand:this.browser.url()}}case"RECORD_REQUESTS":{let m=new _n(n.requestMatcher);return this.recordedRequests[n.key]={},this.browser.registerRequestRecorder(n.key,m,{onRequestStart:(h,f)=>{this.recordedRequests[n.key][h]=Ec(f)},onRequestComplete:(h,f)=>{this.recordedRequests[n.key][h]=Ec(f)}}),{succeedImmediately:!1,urlAfterCommand:this.browser.url()}}case"GET_RECORDED_REQUESTS":{let m=this.recordedRequests[n.key];if(!m)throw new _("ActionFailureError",`No recorder registered with key: ${n.key}`);return delete this.recordedRequests[n.key],{data:Object.values(m),succeedImmediately:!1,urlAfterCommand:this.browser.url()}}case"SET_HEADER":{let m;return n.requestMatcher&&(m=new _n(n.requestMatcher)),this.browser.setHeader(n.name,n.value,m),{succeedImmediately:!1,urlAfterCommand:this.browser.url()}}case"MOCK_ROUTE":return{data:{key:this.browser.registerMock(n.key,new _n(n.requestMatcher),async(h,f)=>{let E=await kr({orgId:this.orgId,code:n.responseGenerator,fragment:!1,context:o,timeoutMs:void 0,logger:a,localTools:this.localCodeEvalTools,mock:{request:h,response:f},disallowVariableUpdates:!0,responseSerialization:"RESPONSE"}),S=PE.parse(E);return new Response(S.body,{status:S.status,headers:S.headers})},n.fetchOriginalResponse??!1)},succeedImmediately:!1,urlAfterCommand:this.browser.url()};case"REMOVE_ROUTE_MOCK":return this.browser.removeMock(n.key),{succeedImmediately:!1,urlAfterCommand:this.browser.url()};case"OFFLINE_MODE":return await this.browser.setOfflineMode(n.enable),{succeedImmediately:!1,urlAfterCommand:this.browser.url()};default:return(m=>{throw"If Typescript complains about the line below, you missed a case or break in the switch above"})(n)}return{succeedImmediately:!1,urlAfterCommand:this.browser.url()}}async getReverseMappedDescription({browserState:e,targetId:t,disableCache:n,screenshot:o}){return(await this.generator.getReverseMappedDescription({browserState:e,target:t,screenshot:o},{disableCache:n,abortSignal:this.executeAbortController.signal,loggerTags:ve(this.logger)})).phrase}async stopRecordMode(){this.recordAbortController?.abort(),await this.browser.clearAllCdpHighlights()}async startRecordMode({params:e,abortController:t,isClickToRecord:n}){this.recordAbortController=t;let o=new Cc({signal:t.signal,...e});return await this.browser.startRecording(this.recordAbortController.signal,o,n),o}async runSectionAutohealing(e){return this.generator.getAutohealingProposal(e,{disableCache:!0,abortSignal:this.executeAbortController.signal,loggerTags:ve(this.logger)})}async getFailureRecoveryPlan(e){return this.generator.getFailureRecoveryPlan(e,{disableCache:!0,abortSignal:this.executeAbortController.signal,loggerTags:ve(this.logger)})}};import{mkdirSync as VF}from"fs";import{tmpdir as WF}from"os";import Qw from"path";import{cloneDeep as vF}from"lodash-es";import Vw from"truncate-json";var zw=1e3,Hw=5e6,AF=5*1024*1024;function Ww(r,e){for(let t=0;t<r.length;t++){let n=r[t];try{if(n.data){let{jsonString:o}=Vw(JSON.stringify(n.data),1e3);n.data=JSON.parse(o)}}catch(o){e.error({err:o},"Failed to serialize individual result output data"),n.data=`Result output data could not be serialized: ${o}`}switch(n.type){case"MOBILE_PRESET_STEP":Gw(n);break;case"MOBILE_MODULE_STEP":Gw(n),Ww(n.steps,e);break;default:return(()=>{throw new Error("If Typescript complains about the line below, you missed a case or break in the switch above")})()}}}function Gw(r){if(r.type==="MOBILE_PRESET_STEP"){let e=r.command;"cache"in e&&e.cache&&(e.cache=void 0)}}function jw(r,e){let t=JSON.stringify(r),n=t.replaceAll("\\u0000","");if(t.length!==n.length){let o=t.indexOf("\\u0000");e.warn({input:t.slice(Math.max(0,o-500),Math.min(t.length,o+500))},"Database content violation: stripped unicode character from input")}return n}function kc(r,e){let t=vF(r);if(Ww(t,e),t.length>zw)return e.error("Database content violation: results too long, truncating before insertion"),t.slice(0,zw);let n=jw(t,e);if(n.length>Hw)for(e.error({serializedLength:n.length,resultsArrayLength:t.length},"Database content violation: results too large, truncating before insertion");n.length>Hw;)t.pop(),n=jw(t,e);let{jsonString:o}=Vw(n,AF);try{return Er.array().parse(JSON.parse(o))}catch(i){throw e.error({serialized:n,err:i},"Could not parse serialized results into JSON structure after processing"),i}}import{AsyncLocalStorage as wF}from"async_hooks";var Ya=new wF;function RF(r){Ya.enterWith({activeTracers:[r]})}function CF(r,e){let t=Ya.getStore()?.activeTracers;if(!t)return e();t.push(r);try{return e()}finally{t.pop()}}async function xF(r,e){let t=Ya.getStore()?.activeTracers;if(!t)return e();let n=[...t,r];return Ya.run({activeTracers:n},e)}var Pn={globalAls:Ya,initializeRootTracerContext:RF,withChildTracer:CF,withChildTracerAsync:xF};var fo=class r{spans;parentSection;finished=!1;startTime;endTime;constructor(e){this.startTime=e?.startTime??Date.now(),this.spans=e?.subSpans??[],this.parentSection=e}startSection(e,t){let n={type:"SECTION",name:e,startTime:Date.now(),endTime:void 0,subSpans:[],attributes:{}},o=new r(n);try{return Pn.withChildTracer(o,()=>t(o,n))}catch(i){throw n.error=i instanceof Error?i.message:String(i),i}finally{o.finish(),this.addSpan(n)}}async startAsyncSection(e,t){let n={type:"SECTION",name:e,startTime:Date.now(),endTime:void 0,subSpans:[],attributes:{}},o=new r(n);this.addSpan(n);try{return await Pn.withChildTracerAsync(o,()=>t(o,n))}catch(i){throw n.error=i instanceof Error?i.message:String(i),i}finally{o.finish()}}finish(){if(!this.finished){this.endTime=Date.now();for(let e of this.spans)e.endTime||(e.endTime=this.endTime,e.durationMs=e.endTime-e.startTime);this.parentSection&&(this.parentSection.endTime=this.endTime,this.parentSection.durationMs=this.parentSection.endTime-this.parentSection.startTime),this.finished=!0}}addSpan(e){this.spans.push(e)}startSpan(e,t,...n){let o={type:e,startTime:Date.now(),endTime:void 0,attributes:{}},i=n[0]??void 0;Object.assign(o,i??{}),this.addSpan(o);let a;try{a=t(o),o.endTime=Date.now(),o.durationMs=o.endTime-o.startTime}catch(s){throw o.error=s instanceof Error?s.message:String(s),o.endTime=Date.now(),o.durationMs=o.endTime-o.startTime,s}return a}async startAsyncSpan(e,t,...n){let o={type:e,startTime:Date.now(),endTime:void 0,attributes:{}},i=n[0]??void 0;Object.assign(o,i??{}),this.addSpan(o);let a;try{i?.signal||i?.timeoutMs?a=await V(t(o),{milliseconds:i?.timeoutMs??1/0,signal:i?.signal}):a=await t(o),o.endTime=Date.now(),o.durationMs=o.endTime-o.startTime}catch(s){throw o.error=s instanceof Error?s.message:String(s),o.endTime=Date.now(),o.durationMs=o.endTime-o.startTime,s}return a}getRootSpan(){return this.finished||this.finish(),{type:"SECTION",name:"root step span",startTime:this.startTime,endTime:this.endTime,subSpans:this.spans,attributes:{},durationMs:this.endTime?this.endTime-this.startTime:void 0}}};function ze(){let r=Pn.globalAls.getStore()?.activeTracers,e;return!r||r.length===0?e=void 0:e=r[r.length-1],e||new fo}import{diff as GF}from"deep-object-diff";import{cloneDeep as jF}from"lodash-es";import Kw from"fontoxpath";import _F from"@prettier/plugin-xml";import MF from"prettier";import{DOMParser as IF,XMLSerializer as PF}from"slimdom";function Vm(r){return r.toLowerCase().endsWith("webview")}function OF(r){let e=["android.widget.","android.view.","android.webkit.","android.app.","android.support.","androidx.","com.android.inputmethod."];for(let t of e)if(r.startsWith(t))return r.substring(t.length);return r}var LF=new Set(["index","package","a11y-important","screen-reader-focusabl"]),NF=new Set(["selected","checked","checkable","clickable","enabled","focusable","focused","long-clickable","password","scrollable","selected","showing-hint","context-clickable","multiline","text-entry-key","heading","dismissable","screen-reader-focusable","content-invalid","a11y-focused"]),kF=new Set(["text","hint"]),DF=new Set(["live-region","drawing-order"]),UF=new Set(["displayed","enabled"]);function FF(r,e){let t={};for(let[n,o]of Object.entries(e))LF.has(n)||n==="class"&&r===o||n==="focusable"&&o==="true"&&e.clickable==="true"||NF.has(n)&&o==="false"||kF.has(n)&&o===""||UF.has(n)&&o==="true"||DF.has(n)&&o==="0"||n!=="id"&&(t[n]=o);return t}function $w(r,e,t){let{prunedDocument:n,idToElement:o,prunedIdToElement:i,idCounter:a,opts:s}=r,c=a.value++;t.setAttribute("id",String(c));let l={};for(let p of e.attributes){let g=p.name,m=p.value;m!=null&&(l[g]=String(m))}let u=FF(e.tagName,l);for(let[p,g]of Object.entries(u))t.setAttribute(p,g);if(o.set(c,e),i.set(c,t),Vm(e.tagName)){let p=s?.injectedWebviewContent??"";if(!s?.disableMomenticAccessibilityTree&&p.trim().length>0){for(;t.firstChild;)t.removeChild(t.firstChild);p.trim().length>0&&t.appendChild(n.createCDATASection(`
|
|
4026
|
+
`}if(e.neighbors!==void 0&&e.neighbors>0&&this.parent){let T=this.parent.children.findIndex(z=>z.id===this.id),_=T>0?this.parent.children[T-1]?.serialize({...e,neighbors:0}):"",M=T<this.parent.children.length-1?this.parent.children[T+1]?.serialize({...e,neighbors:0}):"";return`${_||""}
|
|
4027
|
+
${b}
|
|
4028
|
+
${M||""}`}return b}shallowClone(){let e=new r({id:this.id,role:this.role,name:this.name,nameSources:this.nameSources,content:this.content,properties:[],pathFromRoot:this.pathFromRoot,children:[],ignoredReasons:this.ignoredReasons,backendNodeID:this.backendNodeId,ignoredByCDP:this.ignoredByCDP,internalProperties:ym(this.internalProperties),importantProperties:this.importantProperties,parentFrame:this.parentFrame,flagNotActionableNodes:this.flagNotActionableNodes});return e.tagName=this.tagName,e.dataMomenticId=this.dataMomenticId,e.properties=ym(this.properties),e}},Em=class r{constructor(e,t,n,o){this.root=e;this.a11yIdNodeMap=t;this.dataMomenticIdMap=n;this.selectorToNodeMap=o}serialize(e){return this.root.serialize(e)}pruneUsingSummaries(e){let t=this.root;if(!t)throw new Error("Cannot prune a11y tree with no root");let n={},o={},i={},a=c=>{let s=c.shallowClone();if(e[c.id])return s.properties["data-momentic-summary"]=e[c.id],n[c.id]=s,c.dataMomenticId&&(o[c.dataMomenticId]=s),c.mPathSelector&&(i[c.mPathSelector]=s),s;let u=[];for(let d of c.children){let p=a(d);p&&(u.push(p),p.parent=s)}return s.children=u,n[c.id]=s,c.dataMomenticId&&(o[c.dataMomenticId]=s),c.mPathSelector&&(i[c.mPathSelector]=s),s},l=a(t);return new r(l,n,o,i)}pruneUsingRelevantIds(e){let t=this.root;if(!t)throw new Error("Cannot prune a11y tree with no root");function n(i,a=!1){let l=e.has(`${i.id}`)||i.id===t?.id,c=i.shallowClone(),s=i.children,u=!1,d=[];for(let p of s){let m=n(p,l||u);m&&(d.push(m),m.parent=c,u=!0)}if(c.children=d,l||u)return c;if(Tm.includes(i.role)&&a)return c}let o=n(t);return new r(o,this.a11yIdNodeMap,this.dataMomenticIdMap,this.selectorToNodeMap)}pruneToSerializedCharLimit(e){let t=this.root;if(!t)throw new Error("Cannot prune a11y tree with no root");let n=c=>c.role==="StaticText"||c.role==="ListMarker",o=new WeakMap,i=(c,s)=>{if(o.has(c))return o.get(c);let u=c.serialize({indentLevel:s,noChildren:!0});return o.set(c,u),u},a=(c,s,u)=>{let d=c.shallowClone();d.children=[];let p=i(c,s).length;if(u<=p)return{clone:d,used:p};if(n(c)||c.children.length===0)return{clone:d,used:p};let m=p,g=u-m;for(let h of c.children){let f=s+2,b=i(h,f).length;if(g<b)break;let{clone:E,used:v}=a(h,f,g);if(v>g)break;d.children.push(E),E.parent=d,m+=v,g-=v}return{clone:d,used:m}},{clone:l}=a(t,0,Math.max(1e4,e));return new r(l,this.a11yIdNodeMap,this.dataMomenticIdMap,this.selectorToNodeMap)}};function Bk(r){return r.name?.value?`"${r.name.value}"`:r.role?.value&&r.role.value!=="none"&&r.role.value!=="generic"?`"${r.role.value}"`:`"${r.nodeId}"`}function zk(r,e,t,n){return r.bounds.x===null||r.bounds.y===null||r.bounds.height===null||r.bounds.width===null||r.bounds.width===0||r.bounds.height===0?!0:r.bounds.x+r.bounds.width<e.leftBound||r.bounds.x>e.rightBound?($s({logger:t,logKey:n,maxCount:5,intervalMs:3e3},{domNode:r,logKey:n},"Filtering out node since it is not in the viewport horizontally"),!1):r.bounds.y+r.bounds.height<e.upperBound||r.bounds.y>e.lowerBound?($s({logger:t,logKey:n,maxCount:5,intervalMs:3e3},{domNode:r,logKey:n},"Filtering out node since it is not in the viewport vertically"),!1):r.computedStyles.display==="none"?(t.debug({domNode:r},"Filtering out node since it has display none"),!1):!0}async function kA({node:r,parent:e,frameId:t,frameContext:n,axGraph:o,domGraph:i,inputNodeMap:a,flagNotActionableNodes:l,showZeroOpacityElements:c,filterByViewport:s,viewportDetails:u,useMPaths:d,importantProperties:p,allowedA11yIgnoreReasonsOverride:m,cdpClient:g,logger:h,callId:f}){if(!e&&r.parentId)throw new Error(`Got no parent for accessibility node ${r.nodeId}: ${JSON.stringify(r)}`);let b=(U,ne={})=>{},E=r.backendDOMNodeId,v=Nk.includes(r.role?.value?.toLowerCase()??"");if(!v&&E===void 0)return b("Filtering out node since it doesn't exist in the DOM"),[];let R=E?i.backendIdToNode[E]:void 0;if(!v&&!R)try{let U=await B(g.send({method:"DOM.describeNode",params:{backendNodeId:E}}),{milliseconds:750,fallback:()=>{h.debug("Timeout getting node from CDP while processing a11y tree")}});if(U&&U.node.nodeName.toLowerCase()==="slot"&&U.node.distributedNodes?.length)h.debug({redirectedDomNode:R,parentAXNode:e?.getNodeOnlySerializedForm(),originalAXNode:r,cdpResult:U},"Redirecting node to assigned slot");else return b("Filtering out node since it doesn't exist in the DOM",{cdpResult:U}),[]}catch(U){return b("Filtering out node since it doesn't exist in the DOM",{err:U}),[]}if(R&&e&&s&&u&&r.backendDOMNodeId&&!zk(R,u,h,f))return R.momenticIgnored=!0,[];if(R&&R.computedStyles.display==="none")return R.momenticIgnored=!0,[];if(R&&R.computedStyles.opacity==="0"&&c!==!0){if(c==="inputs-only"&&R.tagName.toLowerCase()!=="input")return R.momenticIgnored=!0,[];if(c===!1)return R.momenticIgnored=!0,[]}let T=r.name?.value?typeof r.name.value=="string"?r.name.value:`${r.name.value}`:"",_=r.value?.value?typeof r.value.value=="string"?r.value.value:`${r.value.value}`:"",M=new bm({domNode:R,id:parseInt(r.nodeId),role:r.role?.value||"",name:T,nameSources:r.name?.sources,content:_,properties:r.properties,children:[],ignoredReasons:r.ignoredReasons?.filter(U=>(m??LA).includes(U.name)||NA.includes(U.name))??[],pathFromRoot:(e?`${e.pathFromRoot} `:"")+Bk(r),backendNodeID:r.backendDOMNodeId,ignoredByCDP:r.ignored,internalProperties:{inCodeMirrorEditor:e?.internalProperties?.inCodeMirrorEditor},importantProperties:p,parentFrame:n.type==="root"?void 0:n,flagNotActionableNodes:l}),z=n,Y=a[t],Ee=t;if(R?.tagName.toLowerCase()==="iframe"&&R.ownedFrameId){let U=n.childFrames.find(Ne=>Ne.frameId===R.ownedFrameId),ne=o[U?.frameId??""]?.root,ae=a[U?.frameId??""];if(U&&ne&&ae){r.childIds&&r.childIds.length>0&&h.debug("Replacing existing node's children with children from the iframe");let Ne=ne;r.childIds=Ne.childIds,z=U,Y=ae,Ee=U.frameId}}let oe=R?.childrenBackendIds?.length??0,ge=(r.childIds??[]).filter(U=>!!Y.get(parseInt(U))).length;if(oe>ge){let U=r.childIds?.map(ae=>Y.get(parseInt(ae))).filter(Boolean).map(ae=>ae?.backendDOMNodeId).filter(ae=>ae!==void 0)??[],ne=0;for(let ae of R?.childrenBackendIds??[]){if(U.includes(ae)){ne=(r.childIds?.findIndex(Ae=>Y.get(parseInt(Ae))?.backendDOMNodeId===ae)??0)+1;continue}let Ne=i.backendIdToNode[ae];if(!Ne||Ne?.tagName.toLowerCase()!=="svg")continue;let he=Math.floor(-1*Math.random()*1e7),dt={nodeId:he.toString(),parentId:r.nodeId,ignored:!1,backendDOMNodeId:ae,frameId:Ee,role:{type:"string",value:"graphics-symbol"}};Y.set(he,dt),r.childIds||(r.childIds=[]),r.childIds.splice(ne,0,he.toString()),ne++}}if(r.childIds?.length===1&&R){let U=Y.get(parseInt(r.childIds[0])),ne=U?.role?.value,ae=R.childrenBackendIds;if(U&&ne==="StaticText"&&ae.length===1){let Ne=i.backendIdToNode[ae[0]];if(Ne?.tagName?.toLowerCase()==="span"){let he=Math.floor(-1*Math.random()*1e7).toString(),dt={nodeId:he,parentId:r.nodeId,ignored:!1,backendDOMNodeId:Ne.backendNodeId,frameId:Ee,childIds:[U.nodeId]};U.parentId=he,Y.set(parseInt(he),dt),r.childIds=[he]}}}for(let U of r.childIds??[]){if(!U)continue;let ne=Y.get(parseInt(U));if(!ne)continue;let ae=await kA({node:ne,parent:M,domGraph:i,axGraph:o,frameId:Ee,frameContext:z,inputNodeMap:a,cdpClient:g,logger:h,callId:f,filterByViewport:s,showZeroOpacityElements:c,importantProperties:p,viewportDetails:u,useMPaths:d,flagNotActionableNodes:l});ae.length&&(M.children=M.children.concat(ae))}if(M.role==="StaticText"&&(M.children=[]),M.children.length===1&&M.children[0].role==="StaticText"){let U=M.name,ne=M.children[0]?.name;(U===ne||!ne)&&(M.children=[])}let et=[];for(let U=M.children.length-1;U>=0;U--){let ne=M.children[U];if(ne.role!=="StaticText"){et.push(ne);continue}if(U===0||M.children[U-1].role!=="StaticText"){et.push(ne);continue}M.children[U-1].name+=ne.name}if(M.children=et.reverse(),!M.isInteresting(p)&&r.parentId)return R&&(R.momenticIgnored=!0),M.children;for(let U of M.children)U.parent=M;return Vk(M),R&&d&&Sm(R,i),[M]}function UA({node:r,a11yIdNodeMap:e,dataMomenticIdMap:t,logger:n,callId:o,domGraph:i,useMPaths:a,selectorToNodeMap:l,iconKnowledgeBase:c,startId:s=1}){r.id=s,s+=1,e[r.id]=r,r.dataMomenticId?t[r.dataMomenticId]=r:Tm.includes(r.role);let u=r.backendNodeId,d=u!==void 0?i.backendIdToNode[u]:void 0;if(a&&d&&d.mPathSelector&&(l[d.mPathSelector]=r,r.mPathSelector=d.mPathSelector),c&&d&&d.tagName?.toLowerCase()==="svg"){let p=fm(d,i),m=p?c[p.hash]:void 0,g=m?m.description:void 0;m&&(r.properties["data-momentic-description"]=g)}for(let p of r.children)s=UA({node:p,a11yIdNodeMap:e,dataMomenticIdMap:t,logger:n,callId:o,startId:s,useMPaths:a,domGraph:i,selectorToNodeMap:l,iconKnowledgeBase:c});return s}async function FA({rawA11yGraph:r,domGraph:e,startingFrameId:t,logger:n,cdpClient:o,filterByViewport:i,showZeroOpacityElements:a,flagNotActionableNodes:l,importantProperties:c,viewportDetails:s,useMPaths:u,frameContext:d,iconKnowledgeBase:p,allowedA11yIgnoreReasonsOverride:m}){let g=t??"root",h=r[g]?.root;if(!h)throw new Error("A11y tree has no root");let f=xk(),b=M=>{let z=M.allNodes.filter(Ee=>!Ee.ignoredReasons?.find(ge=>(m??LA).includes(ge.name))),Y=new Map;return z.forEach(Ee=>{Y.set(parseInt(Ee.nodeId),Ee)}),Y},E={};Object.entries(r).forEach(([M,z])=>{E[M]=b(z)});let v=await kA({node:h,domGraph:e,parent:null,inputNodeMap:E,axGraph:r,frameId:g,frameContext:d,cdpClient:o,logger:n,callId:f,showZeroOpacityElements:a,importantProperties:c,filterByViewport:i,viewportDetails:s,useMPaths:u,flagNotActionableNodes:l,allowedA11yIgnoreReasonsOverride:m});if(v.length>1)throw new Error(`Something went horribly wrong processing the a11y tree, we got: ${JSON.stringify(v)}`);if(v.length===0)throw new Error("There are no accessible elements on this page or frame. Are you sure this website loads properly?");let R={},T={},_={};return UA({node:v[0],a11yIdNodeMap:R,dataMomenticIdMap:T,selectorToNodeMap:_,domGraph:e,logger:n,callId:f,useMPaths:u,iconKnowledgeBase:p}),new Em(v[0],R,T,_)}function Hk(r,e,t,n){if(r==="class"){if(t.tagName?.toLowerCase()==="svg")return e.split(" ").filter(a=>a.length<DA&&!ar.bannedClassSubstrings.some(l=>a.includes(l))).slice(0,3).join(" ");let o=e.split(" "),i=[];for(let a of o)if(BA(a,n)){i.push(a);continue}return i.length?i.join(" "):null}if(e==="true")return!0;if(e==="false")return!1;try{let o=parseInt(e);if(!isNaN(o))return o}catch{}return r==="src"&&e.includes("base64")?e.slice(0,e.indexOf("base64")+6)+"...":e.length>60?e.slice(0,50)+"...":e}function Gk(r,e,t){if(!e)return;Object.entries(e.attributes).forEach(([a,l])=>{let c=r[a]||a.startsWith("aria")||Ik.includes(a);if((ar.relevantElementAttributes.includes(a)||zA(a,t))&&!c){let u=Hk(a,l,e,t);u!==null&&(r[a]=u)}});let n,o=[];if(e.computedStyles.position&&IA.includes(e.computedStyles.position))n=e.computedStyles.position;else if(e.attributes.style){for(let a of IA)if(e.attributes.style.includes(`position: ${a}`)){n=a;break}}n&&o.push(`position: ${n}`);let i;e.computedStyles.opacity&&e.computedStyles.opacity==="0"&&(i="opacity: 0"),i&&o.push(i);for(let a of t?.styles??[]){let l=a.split(":"),c=l[0]?.trim(),s=l[1]?.trim(),u=e.computedStyles[c??""];if(c!==void 0&&s!==void 0&&u!==void 0&&(s==="*"||u===s)){let d=e.computedStyles[c],p=`${c}: ${d}`;o.includes(p)||o.push(p)}}o.length>0&&(r.style=o.join("; "))}function Vk(r){let e=r.properties.class;if(typeof e=="string"&&e.includes("cm-content")){r.children.forEach((i,a)=>{i.properties["cm-line-number"]=`${a+1}`});return}if(typeof e=="string"&&e.includes("notion-page-content")){r.children.forEach((i,a)=>{i.properties["block-number"]=`${a+1}`}),r.children.length>0&&(r.children[r.children.length-1].properties.description="This is the last block in the document. Click here to add new text to the end.");return}if(r.tagName==="table"){let i=[],a=r.children.find(c=>c.tagName==="thead");if(a){let c=a.children.find(s=>s.tagName==="tr");if(c){let s=c.children.filter(u=>u.tagName==="th");s.forEach((u,d)=>{u.properties["col-index"]||(u.properties["col-index"]=d+1),i?.push(_t(u.name,100,!1))}),i?.length!==s.length&&(i=void 0)}}let l=0;for(let c of r.children)if(c.tagName==="tbody")for(let s=0;s<c.children.length;s++){let u=c.children[s];if(u.tagName!=="tr")continue;if(s===0&&!i?.length){let m=u.children.filter(g=>g.tagName==="th");if(m.length){if(i=m.map(g=>_t(g.name,100,!1)),i.length===m.length)continue;i=void 0}}l+=1,u.properties["row-index"]||(u.properties["row-index"]=l);let d=u.children.filter(m=>m.tagName==="td"||m.tagName==="th"),p=d.length===i?.length;d.forEach((m,g)=>{m.tagName!=="th"&&(m.properties["col-index"]||(m.properties["col-index"]=g+1),p&&(m.properties.col||(m.properties.col=i[g])))})}}}function jk(r){let e=r.properties.class,t=typeof e=="string"&&e.includes("cm-content");r.internalProperties.inCodeMirrorEditor=r.internalProperties?.inCodeMirrorEditor||t}function BA(r,e){if(e&&HA(r,e))return!0;if(ar.bannedClassSubstrings.some(t=>r.includes(t)))return!1;if(ar.alwaysInterestingClassNames.includes(r))return!0;for(let t of ar.alwaysInterestingClassPrefixes)if(r.startsWith(t))return!0;return!1}function zA(r,e){if(e?.attributes?.includes(r))return!0;for(let t of e?.attributes??[])if(t.endsWith("*")){let n=t.slice(0,-1);if(r.startsWith(n))return!0}return!1}function HA(r,e){if(e?.classes?.includes(r))return!0;for(let t of e?.classes??[])if(t.endsWith("*")){let n=t.slice(0,-1);if(r.startsWith(n))return!0}return!1}var pc=class r{constructor(e,t,n,o,i){this.session=e;this.logger=t;this.contextGetter=n;this.pageGetter=o;this.defaultTimeoutMs=i}cdpInitializingPromise=void 0;cdpCrashDetails=void 0;cdpFullyDead=!1;loadEventLogs=[];static async init({logger:e,contextGetter:t,pageGetter:n,defaultTimeoutMs:o}){let i=t(),a=n(),l,c;for(let u=0;u<2;u++)try{l=await B(i.newCDPSession(a),{milliseconds:o*u,fallback:()=>{throw new w("UserInfrastructureError",`Failed to initialize Chrome session within the page load timeout (${a.url()})`)}});break}catch(d){await X(it),c=d}if(!l)throw c;let s=new r(l,e,t,n,o);try{await B(s.registerHandlers(l),{milliseconds:o,message:`CDP handler registration timed out after ${o}ms`})}catch(u){throw s.cdpFullyDead=!0,new w("UserInfrastructureError",`Failed to initialize CDP client: ${u}`)}return s}async registerHandlers(e){e.on("Target.attachedToTarget",async()=>{try{await e.send("Runtime.runIfWaitingForDebugger")}catch(t){this.logger.warn({err:t},"Failed to run Runtime.runIfWaitingForDebugger")}}),e.on("Target.targetCrashed",t=>{this.cdpCrashDetails={...this.cdpCrashDetails??{},targetCrashDetails:JSON.stringify(t)},this.logger.error({payload:t},"CDP session crashed, Momentic will likely not function correctly")}),e.on("Inspector.targetCrashed",t=>{this.cdpCrashDetails={...this.cdpCrashDetails??{},inspectorCrashDetails:JSON.stringify(t)},this.logger.error({payload:t},"CDP inspector session crashed, Momentic will likely not function correctly")}),e.on("Page.frameRequestedNavigation",t=>{this.loadEventLogs.push(`[${new Date(Date.now()).toLocaleString("en-US",{timeZone:"America/Los_Angeles"})}] Frame requested navigation: ${JSON.stringify(t)}`)}),e.on("Page.navigatedWithinDocument",t=>{this.loadEventLogs.push(`[${new Date(Date.now()).toLocaleString("en-US",{timeZone:"America/Los_Angeles"})}] Navigated within document: ${JSON.stringify(t)}`)}),e.on("Page.lifecycleEvent",t=>{this.loadEventLogs.push(`[${new Date(Date.now()).toLocaleString("en-US",{timeZone:"America/Los_Angeles"})}] Page lifecycle event: ${JSON.stringify(t)}`)}),e.on("Page.loadEventFired",()=>{this.loadEventLogs.push(`[${new Date(Date.now()).toLocaleString("en-US",{timeZone:"America/Los_Angeles"})}] Page load event fired`)}),await e.send("Accessibility.enable"),await e.send("Page.enable"),await e.send("DOM.enable"),await e.send("Overlay.enable"),await e.send("DOMSnapshot.enable"),await e.send("CSS.enable")}async send({method:e,params:t,timeout:n=this.defaultTimeoutMs,timeoutMsg:o}){for(;this.cdpInitializingPromise;)await B(this.cdpInitializingPromise,{milliseconds:n});if(this.cdpCrashDetails){if(this.cdpFullyDead)throw new w("UserInfrastructureError",`The browser inspector session encountered a critical crash: ${JSON.stringify(this.cdpCrashDetails)}`);this.logger.warn(`Detected crashed CDP client before method ${e}, reinitializing before proceeding...`),await this.reinitialize()}try{return await B(this.session.send(e,t),{milliseconds:n,message:o??`Chrome command ${e} timed out after ${n}ms. This is likely an infrastructure issue caused by a lack of compute resources or a crash at the browser level.`})}catch(i){throw["Internal error","Target crashed"].some(a=>i.message.includes(a))&&!this.cdpInitializingPromise&&(this.logger.warn({err:i},`CDP crashed during CDP method ${e}, re-initializing client`),await this.reinitialize()),i}}async createRawCDPSession(e=this.defaultTimeoutMs){let t=e,n=this.pageGetter(),o=await B(this.contextGetter().newCDPSession(n),{milliseconds:t,fallback:()=>{throw this.logger.error(`Failed to initialize CDP session within the page load timeout (${n.url()})`),new w("UserInfrastructureError",`Failed to initialize CDP session within the page load timeout (${n.url()})`)}});return this.logger.debug(`Created new CDP session for ${n.url()}`),o}async reinitialize(e=this.defaultTimeoutMs){await this.cdpInitializingPromise,this.cdpInitializingPromise=(async()=>{try{let t=this.session;this.session=await this.createRawCDPSession(e),await B(this.registerHandlers(this.session),{milliseconds:e,message:`Failed to register CDP handlers within ${e}ms`}),this.logger.debug("Successfully reinitialized and attached new handlers to CDP session");try{await B(t.detach(),{milliseconds:1e3})}catch(n){this.logger.warn({err:n},"Failed to detach old CDP session after reinitialization, continuing...")}this.cdpCrashDetails=void 0,this.cdpFullyDead=!1}catch(t){this.cdpCrashDetails={...this.cdpCrashDetails??{},reinitializeError:`${t}`},this.cdpFullyDead=!0}finally{this.cdpInitializingPromise=void 0}})(),await this.cdpInitializingPromise}on(e,t){return this.session.on(e,t),this.session}off(e,t){return this.session.off(e,t),this.session}addListener(e,t){return this.session.addListener(e,t),this.session}removeListener(e,t){return this.session.removeListener(e,t),this.session}};var ri="<empty>";function Wk(r){return r.includes("doubleclick.net")||r.includes("googletagmanager.com")||r.includes("googlesyndication.com")||r.includes("s.amazon-adsystem.com")||r.includes("smartadserver.com")||r.includes("omnitagjs.com")||r.includes("x.adroll.com")}function VA(r){let e=r.adFrameStatus?.adFrameType;return e==="child"||e==="root"||Wk(r.url)}async function $k(r,e){let t=await r.send({timeout:J,method:"DOM.getFrameOwner",params:{frameId:e}}),o=(await r.send({timeout:J,method:"DOM.pushNodesByBackendIdsToFrontend",params:{backendNodeIds:[t.backendNodeId]}})).nodeIds[0],a=(await r.send({timeout:J,method:"DOM.describeNode",params:{backendNodeId:t.backendNodeId}})).node;return a.nodeId=o,a}async function ni({cdpClient:r,page:e,logger:t}){let n={type:"root",childFrames:[],page:e},o=[],[i,a]=await Promise.all([r.send({timeout:J,method:"Page.getFrameTree",params:{}}),r.send({timeout:J,method:"DOM.getDocument",params:{depth:0}})]),s=(i.frameTree.childFrames??[]).map(async(d,p)=>{if(VA(d.frame))return null;try{return await jA({cdpClient:r,rawFrameTree:d,indices:[p],parent:n,warnings:o,logger:t})}catch(m){return o.push(`Failed to get child frame: ${m}`),null}}),u=await Promise.all(s);return n.childFrames=u.filter(d=>d!==null),o.length&&t?.warn({warnings:o},"Got warnings when fetching frame tree"),n}async function jA({cdpClient:r,rawFrameTree:e,indices:t,parent:n,warnings:o,logger:i}){let a=e.frame.id,l=await $k(r,a),c=l.attributes??[],s=null,u=[];for(let g of["src","name","id","title","srcdoc","sandbox"]){let h=Tn(c,g);h&&(u.push(`${g}=${JSON.stringify(h)}`),g==="src"&&(s=h))}let d={type:"frame",cdpFrame:e.frame,url:e.frame.url,frameId:a,locationData:{indices:t,attributeSelectors:u},src:s,childFrames:[],parent:n,domNode:l},m=(e.childFrames??[]).map(async(g,h)=>{if(VA(g.frame))return null;try{return await jA({cdpClient:r,rawFrameTree:g,indices:[...t,h],parent:d,warnings:o,logger:i})}catch(f){return o.push(`Failed to get child frame (child ${h} of frame with url ${e.frame.url}): ${f}`),null}});return d.childFrames=(await Promise.all(m)).filter(g=>g!==null),d}async function qk(r){try{return await r.owner().count()===1}catch{return!1}}async function Kk(r){try{return await r.count()===1}catch{return!1}}async function Lr(r,e){let t=[],n=r;for(;n.parent.type==="frame";)t.push(n.parent),n=n.parent;t.reverse();let o=e,i=[];for(let s of t){let u=!1;for(let d of[...s.locationData.attributeSelectors,ri]){let p=o.frameLocator(d===ri?"iframe":`iframe[${d}]`);if(await qk(p)){u=!0,o=p,i.push(d);break}}if(!u)throw new w("ActionFailureError",`Failed to find a unique attribute to identify intermediate frame with url matching '${s.url}'. Please attach a unique 'id', 'name', 'title', or 'src' attribute to the frame.`)}let a;for(let s of[...r.locationData.attributeSelectors,ri]){let u=o.locator(s===ri?"iframe":`iframe[${s}]`);if(await Kk(u)){a=u,i.push(s);break}}if(!a)throw new w("ActionFailureError",`Failed to find a unique attribute to identify target frame with url matching '${r.url}'. Please attach a unique 'id', 'name', 'title', or 'src' attribute to the frame.`);let l=await a.evaluateHandle(s=>s,{timeout:Z}),c=await l.asElement().contentFrame();if(!c)throw new w("InternalWebAgentError",`Failed to load Playwright Frame for iframe with url '${r.url}'`);return await l.dispose(),{frame:c,mPathSelectorTokens:i}}function GA(r,e){let t=[...r],n=[];for(;t.length;){let o=t.shift();e(o)&&n.push(o),t.push(...o.childFrames)}return n}async function WA({page:r,frameTree:e,cache:t}){let n,o=e.childFrames,i=[];if(t.mPathSelectorTokens.length){let l=o;for(let u=0;u<t.mPathSelectorTokens.length-1;u++){let d=t.mPathSelectorTokens[u];d===ri?l=l.length===1?l[0].childFrames:[]:l=l.filter(p=>p.locationData.attributeSelectors.includes(d)).map(p=>p.childFrames).flat()}let c=[],s=t.mPathSelectorTokens[t.mPathSelectorTokens.length-1];if(s===ri?c=l:c=l.filter(u=>u.locationData.attributeSelectors.includes(s)),c.length===1)return n=c[0],i.push(`Found unique frame with mpath ${t.mPathSelectorTokens.join(" > ")}`),{resolution:{type:"auto",frame:(await Lr(n,r)).frame,handle:n,mPathSelectorTokens:t.mPathSelectorTokens,frameTree:e},logs:i};i.push(`Found ${c.length} frames with mpath ${t.mPathSelectorTokens.join(" > ")}`)}if(t.frameSrcRegex){let l=new RegExp(t.frameSrcRegex),c=GA(o,s=>!!s.src&&l.test(s.src));if(c.length===1)return n=c[0],i.push(`Found unique frame with src regex ${t.frameSrcRegex}`),{resolution:{type:"auto",frame:(await Lr(n,r)).frame,handle:n,mPathSelectorTokens:t.mPathSelectorTokens,frameTree:e},logs:i};i.push(`Found ${c.length} frames with src regex ${t.frameSrcRegex}`),t.frameSrcRegex=void 0}if(t.frameUrlRegex){let l=new RegExp(t.frameUrlRegex),c=GA(o,s=>!!s.url&&l.test(s.url));if(c.length===1)return n=c[0],i.push(`Found unique frame with url regex ${t.frameUrlRegex}`),{resolution:{type:"auto",frame:(await Lr(n,r)).frame,handle:n,mPathSelectorTokens:t.mPathSelectorTokens,frameTree:e},logs:i};i.push(`Found ${c.length} frames with url regex ${t.frameUrlRegex}`),t.frameUrlRegex=void 0}let a=o;for(let l=0;l<t.indices.length-1;l++)a=a[t.indices[l]]?.childFrames??[];if(n=a[t.indices[t.indices.length-1]],n)return i.push(`Found unique frame with indices ${t.indices.join(" > ")}`),{resolution:{type:"auto",frame:(await Lr(n,r)).frame,handle:n,mPathSelectorTokens:t.mPathSelectorTokens,frameTree:e},logs:i};throw i.push(`Found ${a.length} frames with indices ${t.indices}`),new Zr("Failed to find the iframe that previously contained this element",[{type:"AUTO_FRAME",matched:!1,logs:i}])}function mc(r){return r.type==="auto"?JSON.stringify({type:"auto",frameId:r.handle.frameId}):JSON.stringify(r)}function vm(r){for(;r.parent.type==="frame";)r=r.parent;return r.parent}function $A(r){let e=vm(r),t=r.src??"",n=r.url??"",o=[],i=[],a=[...e.childFrames];for(;a.length;){let l=a.shift();l.src&&o.push(l.src),l.url&&i.push(l.url),a.push(...l.childFrames)}return{srcs:o,urls:i,desiredSrc:t,desiredUrl:n}}function qA(r){return r.type==="auto"?{type:"auto",frameId:r.handle.frameId,url:r.handle.url,src:r.handle.src??"",mPathSelectorTokens:r.mPathSelectorTokens.join(" > ")}:{type:"url",url:r.url}}async function KA({frame:r,logger:e,signal:t}){let n;try{n=await r.frameElement(),await Yk({frameElementHandle:n,logger:e,signal:t})}catch(o){n?e.warn({err:o},"Failed to scroll iframe into view, trying with raw JS"):e.warn("Failed to scroll iframe into view - no frame element")}finally{await n?.dispose()}}async function Yk({frameElementHandle:r,logger:e,signal:t}){let n=await r.boundingBox();await La({promiseGenerator:async()=>r.evaluate(async i=>{let a=i.scrollTop;i.scrollIntoView({behavior:"instant",block:"center",inline:"center"}),await new Promise(c=>setTimeout(c,250));let l=Date.now();for(;Date.now()-l<1e3;){let c=i.scrollTop;if(c===a)break;a=c,await new Promise(s=>setTimeout(s,250))}}),timeoutMs:me,codePath:"scrollIframeIntoView",signal:t}),e.info({oldBb:n,newBb:await r.boundingBox()},"Successfully scrolled iframe into view")}async function YA({event:r,transformer:e,enricher:t,frame:n,lastScreenshotForRecording:o,logger:i}){let{warnings:a,error:l,properties:c}=r.target;if(l){i.error({error:l,warnings:a},"Error while capturing passive click");return}if(a.length&&i.warn({warnings:a},"Warnings while capturing passive click"),!c)return;let s=n.parentFrame()?n.url():void 0,d=n.page().frames().map(g=>g.url());i.debug({frameUrl:s,...r},"Passive click event captured on element");let p,m;if(s)try{let g=await n.frameElement();p=await B(g?.boundingBox(),{milliseconds:J})??void 0;let h=await t.constructIframeRegex({urls:d,srcs:[],desiredUrl:s});if(h.urlRegex)m={type:"url",url:`/${h.urlRegex}/`};else throw new Error(`Got no url regex options: ${JSON.stringify(h)}`)}catch(g){i.warn({err:g},"Failed to construct iframe details for recorded action, using hardcoded URL only"),m={type:"url",url:s}}(async()=>{try{await e.recordElementAction({...r,screenshotBase64:o,frameConfig:m,frameBoundingBox:p})}catch(g){i.error({err:g},"Failed to transform passive click action")}})()}import{randomUUID as Nr}from"crypto";import Xk from"js-beautify";var Jk=["Dead"],gc=class{recordedSteps=new Map;callbacks;signal;generator;testId;orgId;nextStepOffset=0;logger;constructor({signal:e,callbacks:t,generator:n,testId:o,orgId:i,logger:a}){this.signal=e,this.logger=a,this.testId=o,this.orgId=i,this.callbacks={onStepRecorded:(l,c)=>{this.recordedSteps.set(c,{step:l}),t.onStepRecorded(l,c)},onActionReceived:(l,c)=>{this.recordedSteps.set(c,{step:l}),t.onActionReceived?.(l,c)}},this.generator=n}reserveIndexForCommand(e){let t=this.nextStepOffset;return this.recordedSteps.set(t,{step:{id:Nr(),type:"PRESET_ACTION",command:Fr(e)}}),this.nextStepOffset++,t}async recordElementAction(e){let{type:t,target:n,frameConfig:o}=e;if(this.signal.aborted){this.logger.debug("Transformer was already cleaned up, ignoring click...");return}let i,a,l=n.properties.attributes.nodeOnlySerializedHtml.trim(),c=l,s;switch(e.frameConfig?e.frameBoundingBox?s={x:e.frameBoundingBox.x+n.properties.boundingBox.x,y:e.frameBoundingBox.y+n.properties.boundingBox.y,width:n.properties.boundingBox.width,height:n.properties.boundingBox.height}:this.logger.warn(e,"No frame bounding box found, refusing to write bounding box"):s=n.properties.boundingBox,t){case"CLICK":{i="CLICK";let h=Fr(i);a={id:Nr(),type:"PRESET_ACTION",command:{...h,target:{type:"description",elementDescriptor:c},iframeUrl:o?.url,cache:{target:{id:-1,...n.properties.attributes,targetSource:"RECORDING",targetUpdateTime:new Date().toUTCString(),boundingBox:s}}}};break}case"SELECT":{i="SELECT_OPTION";let h=Fr(i);a={id:Nr(),type:"PRESET_ACTION",command:{...h,type:"SELECT_OPTION",iframeUrl:o?.url,target:{type:"description",elementDescriptor:c},cache:{target:{id:-1,...n.properties.attributes,targetSource:"RECORDING",targetUpdateTime:new Date().toUTCString(),boundingBox:s}},choice:{type:"VALUE",value:e.selectedValue??"Unknown option"}}};break}case"MOUSE_DRAG":{i="MOUSE_DRAG";let h=Fr(i);a={id:Nr(),type:"PRESET_ACTION",command:{...h,target:{type:"description",elementDescriptor:c},deltaX:e.deltaX.toString(),deltaY:e.deltaY.toString(),iframeUrl:o?.url,cache:{target:{id:-1,...n.properties.attributes,targetSource:"RECORDING",targetUpdateTime:new Date().toUTCString(),targetUpdateLoggerTags:pe(this.logger),boundingBox:s}}}};break}default:throw new Error(`Unknown action type: ${t}`)}let u;e.offset===void 0?(u=this.nextStepOffset,this.nextStepOffset++):u=e.offset,this.callbacks.onActionReceived?.(a,u);let d=e.target.browserState;try{d=Xk.html(d,{indent_size:1,indent_with_tabs:!1,preserve_newlines:!1}),d=zv(d,"data-momentic-interacted",4e4)}catch{}let p;try{p=(await this.generator.getReverseMappedDescription({target:d,screenshot:e.screenshotBase64?`data:image/jpeg;base64,${e.screenshotBase64}`:void 0,boundingBox:n.properties.boundingBox},{disableCache:!1,loggerTags:{testId:this.testId,...pe(this.logger)}})).phrase}catch(h){this.logger.error({err:h},"Error generating reverse mapping description"),p=l}let m=this.recordedSteps.get(u)?.step??a,g=m?.command;g&&"target"in g&&g.target?(g.target={type:"description",elementDescriptor:p},this.callbacks.onStepRecorded({...m,command:g},u)):this.logger.warn("Could not find existing command to update after description mapping")}recordKeystroke(e){let{key:t,combinable:n}=e;if(Jk.includes(t)||this.signal.aborted)return;let o="normal";t.length>1&&(o="special");let i;if(o==="normal"){let d=Fr("TYPE");i={id:Nr(),type:"PRESET_ACTION",command:{...d,target:void 0,value:t,clearContent:!1}}}else{let d=Fr("PRESS");i={id:Nr(),type:"PRESET_ACTION",command:{...d,value:t}}}let a,l=this.nextStepOffset-1,c=this.recordedSteps.get(l),s=c?.step,u=s?.command;if(n){if(u?.type===i.command.type){let d=u.value,p=i.command.value;i={id:Nr(),type:"PRESET_ACTION",command:{...u,value:i.command.type==="PRESS"?`${d}+${p}`:`${d}${p}`}},a=l}else if(u?.type==="CLICK"&&i.command.type==="TYPE")s.command={...i.command,target:u.target,cache:u.cache},i=c.step,a=l;else if(u?.type==="TYPE"&&i.command.type==="PRESS"&&i.command.value==="Backspace"){let d=u.value;i={id:Nr(),type:"PRESET_ACTION",command:{...u,value:d.slice(0,d.length-1)}},a=l}}a===void 0&&(a=this.nextStepOffset,this.nextStepOffset++),this.callbacks.onStepRecorded(i,a)}recordScroll(e){if(this.signal.aborted)return;let t=()=>{let{deltaY:i}=e;if(!i)return;let a=this.nextStepOffset-1,l=this.recordedSteps.get(a)?.step.command,c;l?.type==="SCROLL_DOWN"&&l.deltaY?(i+=l.deltaY,c=a):l?.type==="SCROLL_UP"&&l.deltaY?(i-=l.deltaY,c=a):(c=this.nextStepOffset,this.nextStepOffset++);let s=i>0?"SCROLL_DOWN":"SCROLL_UP",u=Fr(s);u.deltaY=Math.abs(i);let d={id:Nr(),type:"PRESET_ACTION",command:u};this.callbacks.onStepRecorded(d,c)},n=()=>{let{deltaX:i}=e;if(!i)return;let a=this.nextStepOffset-1,l=this.recordedSteps.get(a)?.step.command,c;l?.type==="SCROLL_RIGHT"&&l.deltaX?(i+=l.deltaX,c=a):l?.type==="SCROLL_LEFT"&&l.deltaX?(i-=l.deltaX,c=a):(c=this.nextStepOffset,this.nextStepOffset++);let s=i>0?"SCROLL_RIGHT":"SCROLL_LEFT",u=Fr(s);u.deltaX=Math.abs(i);let d={id:Nr(),type:"PRESET_ACTION",command:u};this.callbacks.onStepRecorded(d,c)},o=this.recordedSteps.get(this.nextStepOffset-1);o?.step.command.type==="SCROLL_LEFT"||o?.step.command.type==="SCROLL_RIGHT"?(n(),e.deltaY>=20&&t()):(t(),e.deltaX>=20&&n())}};import{z as Am}from"zod";var jfe=Am.object({type:Am.literal("url"),url:Am.string()});var hc=class{smartWaitingTimeoutMs;pageLoadTimeoutMs;allowPartialAccessibilityTree;logger;cdpClient;pageGetter;abortSignalGetter;userControlledBrowserSettings;enricher;iconKnowledgeBase;computedStylesToFetch=["display","opacity","visibility","height","position"];activeFrameCache;activeFrameConfig;lastA11yIdToNodeMap={};lastDataMomenticIdToNodeMap={};lastSelectorToNodeMap={};lastA11yTreeRoot;lastDomGraph;allowedA11yIgnoreReasonsOverride;constructor({smartWaitingTimeoutMs:e,pageLoadTimeoutMs:t,allowPartialAccessibilityTree:n,logger:o,cdpClient:i,pageGetter:a,abortSignalGetter:l,enricher:c,iconKnowledgeBase:s,userBrowserSettings:u,allowedA11yIgnoreReasonsOverride:d}){if(this.smartWaitingTimeoutMs=e,this.pageLoadTimeoutMs=t,this.allowPartialAccessibilityTree=n,this.logger=o,this.cdpClient=i,this.pageGetter=a,this.abortSignalGetter=l,this.enricher=c,this.iconKnowledgeBase=s,this.userControlledBrowserSettings=u,this.allowedA11yIgnoreReasonsOverride=d,this.userControlledBrowserSettings.importantStyles)for(let p of this.userControlledBrowserSettings.importantStyles){let m=p.split(":");if(m.length!==2){this.logger.warn({style:p},"Invalid style property passed to importantStyles");continue}let g=m[0]?.trim(),h=m[1]?.trim();if(g===void 0||h===void 0){this.logger.warn({style:p},"Invalid style property passed to importantStyles");continue}this.computedStylesToFetch.includes(g)||this.computedStylesToFetch.push(g)}}get frameConfig(){return this.activeFrameConfig}get domGraph(){return this.lastDomGraph}get selectorToNodeMap(){return this.lastSelectorToNodeMap}get dataMomenticIdToNodeMap(){return this.lastDataMomenticIdToNodeMap}get a11yIdToNodeMap(){return this.lastA11yIdToNodeMap}get a11yTreeRoot(){return this.lastA11yTreeRoot}setActiveFrameConfig(e){e?(this.activeFrameConfig=e,this.activeFrameCache=void 0):(this.activeFrameConfig=void 0,this.activeFrameCache=void 0)}reset(){this.activeFrameCache=void 0,this.activeFrameConfig=void 0,this.lastA11yIdToNodeMap={},this.lastDataMomenticIdToNodeMap={},this.lastSelectorToNodeMap={},this.lastA11yTreeRoot=void 0,this.lastDomGraph=void 0}saveAutoFrameCacheDetails(e){if(!this.activeFrameConfig||this.activeFrameConfig.type!=="auto"||!this.userControlledBrowserSettings.autoExpandIframes)return;let t={...e,indices:this.activeFrameConfig.handle.locationData.indices,mPathSelectorTokens:this.activeFrameConfig.mPathSelectorTokens};return this.constructIframeRegexAsync(this.activeFrameConfig.handle,t),t}async getAutoFrameDetailsFromHandle(e){let t=this.pageGetter(),n=vm(e),{frame:o,mPathSelectorTokens:i}=await Lr(e,t),a={indices:e.locationData.indices,mPathSelectorTokens:i};return this.constructIframeRegexAsync(e,a),{cache:a,config:{type:"auto",frame:o,handle:e,mPathSelectorTokens:i,frameTree:n,cache:a}}}async resolveAutoFrameCache(e){let t=this.pageGetter(),n=await ni({cdpClient:this.cdpClient,page:t,logger:this.logger}),{resolution:o,logs:i}=await WA({page:t,frameTree:n,cache:e});return this.logger.info({logs:i},"Resolved auto frame cache"),{...o,cache:e}}async resolveActiveFrameConfig({logger:e=this.logger,signal:t=this.abortSignalGetter()}){if(!this.frameConfig)return null;if(this.activeFrameCache)if(mc(this.frameConfig)!==this.activeFrameCache.frameIdentifierStringified)this.activeFrameCache=void 0;else if(this.activeFrameCache.frame&&"isDetached"in this.activeFrameCache.frame&&this.activeFrameCache.frame.isDetached())this.activeFrameCache=void 0;else return this.activeFrameCache;let n;return this.frameConfig.type==="url"?n=await this.resolveUrlMatcherFrameConfig({config:this.frameConfig,logger:e,signal:t}):n={source:"auto",frame:this.frameConfig.frame,handle:this.frameConfig.handle,frameIdentifierStringified:mc(this.frameConfig),cacheTime:Date.now(),frameTree:this.frameConfig.frameTree,mPathSelectorTokens:this.frameConfig.mPathSelectorTokens},await KA({frame:n.frame,logger:e,signal:t}),this.activeFrameCache=n,n}async executeFunctionInAllFrames(e,t){let n=this.pageGetter(),o=await ni({cdpClient:this.cdpClient,page:n,logger:this.logger}),i=[B(n.evaluate(e,t),{milliseconds:me})],a=Array.from(o.childFrames);for(;a.length>0;){let c=a.shift(),s=c.url;s==="about:blank"||s.startsWith("chrome-error://")||(a.push(...c.childFrames),i.push(Lr(c,n).then(({frame:u})=>B(u.evaluate(e,t),{milliseconds:me})).catch(u=>(this.logger.warn({err:u,frameUrl:c.url},"Failed to evaluate function in frame"),"MOMENTIC_FRAME_EVAL_ERROR"))))}return(await Promise.all(i)).filter(c=>c!=="MOMENTIC_FRAME_EVAL_ERROR")}async getAllChildFrameUrls(){let e=this.pageGetter(),t=await ni({cdpClient:this.cdpClient,page:e,logger:this.logger}),n=Array.from(t.childFrames),o=[];for(;n.length>0;){let i=n.shift();n.push(...i.childFrames),o.push(i.src??i.url)}return o}async getDomGraph({devicePixelRatio:e,signal:t,logger:n}){return this.getDOMTree({devicePixelRatio:e??1,signal:t,logger:n??this.logger})}async getA11yTree(e){let t={},n=e.logger??this.logger,o=e.abortSignal??this.abortSignalGetter(),i=this.pageGetter(),a,l,c=null;if(this.frameConfig?.type==="url"){if(a=await sr({fn:()=>this.resolveActiveFrameConfig({logger:n,signal:o}),codePath:"getActiveFrameDetails",logObject:t,signal:o,logger:n})??void 0,!a)throw new w("ActionFailureError","Got null frame details despite active frame config");l=a.handle,c=l.frameId}else this.userControlledBrowserSettings.autoExpandIframes?(l=await sr({fn:()=>ni({cdpClient:this.cdpClient,page:this.pageGetter(),logger:n}),codePath:"getMomenticFrameTree",logObject:t,signal:o,logger:n}),c=null):(l={type:"root",page:i,childFrames:[]},c=null);await sr({fn:async()=>this.addMomenticIds({rootPage:i,childFrames:l.childFrames,frameFilter:a?.frame,logger:n}),codePath:"addIdsToElement",logObject:t,signal:o,logger:n});let s=await sr({fn:()=>this.getDOMTree({devicePixelRatio:e.devicePixelRatio??1,signal:o,logger:n}),codePath:"domFetch",logObject:t,signal:o,logger:n}),u=await sr({fn:()=>this.getRawA11yGraph({cdpClient:this.cdpClient,frameId:c,childFrames:l.childFrames,logTimings:t,logger:n,signal:o}),codePath:"totalA11yFetch",logObject:t,signal:o,logger:n}),{tree:d}=await sr({fn:()=>this.composeA11yDomGraph({opts:e,a11yGraph:u,domGraph:s,startingFrameId:c,frameContext:l,logger:n,iconKnowledgeBase:this.iconKnowledgeBase,showZeroOpacityElements:e.showZeroOpacityElements,flagNotActionableNodes:e.flagNotActionableNodes}),codePath:"a11yProcess",logObject:t,signal:o,logger:n});return Object.values(t).some(p=>p>750)&&n.warn({logTimings:t},"A11y tree fetch component took a long time"),this.lastA11yIdToNodeMap=d.a11yIdNodeMap,this.lastDataMomenticIdToNodeMap=d.dataMomenticIdMap,this.lastA11yTreeRoot=d.root,this.lastDomGraph=s,this.lastSelectorToNodeMap=d.selectorToNodeMap,d}async fetchA11yTreeForRecording(e,t){if(await this.getA11yTree({devicePixelRatio:e,abortSignal:t,logger:un,filterByViewport:!1,flagNotActionableNodes:!1}),Math.random()<.1){let n=this.lastA11yTreeRoot?.serialize();this.logger.debug({tree:n&&n.length>4e5?"REDACTED_DUE_TO_SIZE":n},"Refreshed a11y tree during recording")}}async getLocatorFromA11yNode({page:e,root:t,node:n}){if(n.backendNodeId===void 0)throw new Error(`Node with a11y id ${n.id} has no backend node ID: ${n.getNodeOnlySerializedForm()}`);if(this.userControlledBrowserSettings.visualActions){let o=this.domGraph?.backendIdToNode[n.backendNodeId];if(!o)throw new Error(`Could not find DOM node for backend node ID ${n.backendNodeId}`);let i=xA({node:o,domGraph:this.domGraph});return MA(e,i)}else return this.getLocatorFromBackendId(t,n.backendNodeId)}async getLocatorFromBackendId(e,t){let n=await this.cdpClient.send({method:"DOM.resolveNode",params:{backendNodeId:t},timeout:me});if(!n||!n.object.objectId)throw new Error(`Could not resolve backend node ${t}`);let o;try{o=await _A(this.cdpClient,n.object.objectId)}catch(i){throw this.logger.debug({err:i,object:JSON.stringify(n.object)},"Failed to get ID attribute"),i}return e.locator(hr(o))}getNodeUsingMPathSelector(e){let t=this.selectorToNodeMap[e];if(t)return t;let n=e.split(" > "),o="";for(let i=n.length-1;i>=0;i--){let a=n.slice(i).join(" > ");if(this.selectorToNodeMap[a]){o=a;break}}this.logger.warn({selectorMapSize:Object.keys(this.selectorToNodeMap).length,selector:e,closestSelector:o},"Could not find a11y node using mpath selector")}async resolveUrlMatcherFrameConfig({config:e,signal:t=this.abortSignalGetter(),logger:n=this.logger}){let o=Date.now(),i,a,l,c=0;for(;Date.now()-o<this.smartWaitingTimeoutMs;)try{i=await ni({cdpClient:this.cdpClient,page:this.pageGetter(),logger:n}),a=await this.getMatchingFrameByUrlWithCdp(i,e),n.info({frameId:a.handle.frameId,url:a.handle.url,src:a.handle.src,locationData:a.handle.locationData},`Found matching frame using ${a.matchType}`);break}catch(s){if(l=s,s instanceof w&&s.reason==="UserInfrastructureError")throw s;c%3===0&&this.logger.warn({attempt:c,err:s},"Failed to resolve active frame, retrying..."),await X(it,t)}finally{c++}if(a)return{source:"url",frame:a.frame,handle:a.handle,frameIdentifierStringified:mc(e),cacheTime:Date.now(),frameTree:i,mPathSelectorTokens:[]};throw l}async getMatchingFrameByUrlWithCdp(e,t){let n=t.url,o=this.pageGetter(),i=Array.from(e.childFrames),a=[];for(;i.length>0;){let l=i.shift(),c=l.domNode;i.push(...l.childFrames);let s=Tn(c.attributes??[],"src"),u=c.contentDocument?.documentURL;if(!s&&!u){this.logger.debug("Skipping frame with no URL or src");continue}for(let d of[s,u])if(d){if(n.startsWith("/")&&n.endsWith("/")){if(new RegExp(n.slice(1,-1)).test(d)){a.push({handle:l,matchType:"regex",...await Lr(l,o)});break}}else if(n.trim()===d.trim()){a.push({handle:l,matchType:"url",...await Lr(l,o)});break}}}if(a.length===1){let l=a[0];return this.userControlledBrowserSettings.autoExpandIframes||(l.handle.childFrames=[]),l}else throw a.length>1?new Error(`Found multiple frames with src matching '${n}'. Please use a more specific selector.`):new w("ActionFailureError",`Failed to find frame with src matching: ${n}`)}async composeA11yDomGraph({opts:e,a11yGraph:t,domGraph:n,startingFrameId:o,frameContext:i,logger:a,iconKnowledgeBase:l,showZeroOpacityElements:c,flagNotActionableNodes:s}){let u=await FA({rawA11yGraph:t,startingFrameId:o,frameContext:i,domGraph:n,logger:a,cdpClient:this.cdpClient,showZeroOpacityElements:c,flagNotActionableNodes:s,filterByViewport:e.filterByViewport,importantProperties:{attributes:this.userControlledBrowserSettings.importantAttributes,classes:this.userControlledBrowserSettings.importantClasses,styles:this.userControlledBrowserSettings.importantStyles},viewportDetails:void 0,iconKnowledgeBase:l,useMPaths:this.userControlledBrowserSettings.visualActions,allowedA11yIgnoreReasonsOverride:this.allowedA11yIgnoreReasonsOverride});if(!u||!u.root)throw new Error("Accessibility tree appears empty");return{tree:u}}async addMomenticIds({rootPage:e,childFrames:t,frameFilter:n,logger:o}){if(this.userControlledBrowserSettings.visualActions)return;let i=await this.addMomenticIdsHelper(n??e,1);if(!this.userControlledBrowserSettings.autoExpandIframes||n)return;let a=Array.from(t),l=[];for(;a.length>0;){let c=a.shift();a.push(...c.childFrames);let s=async()=>{try{let{frame:u}=await Lr(c,e);i=await this.addMomenticIdsHelper(u,i)}catch(u){c.url!=="about:blank"&&o.warn({err:u},"Error adding momentic IDs to child frame, continuing...")}};l.push(s())}await Promise.all(l)}async addMomenticIdsHelper(e,t){if(this.userControlledBrowserSettings.visualActions)return t;let n=this.logger;return await Qe({root:e,fn:i=>window.addIdsToElement?.(document.body,i),arg:t,timeout:me,waitForPageLoad:async()=>{try{await e.waitForLoadState("domcontentloaded",{timeout:this.smartWaitingTimeoutMs})}catch(i){n.warn({err:i},"Error loading frame root adding momentic ids, continuing...")}},codePath:"adding Momentic element IDs to the page"})??t}getPageDomain(e){try{let t=new URL(e);if(!t.hostname)return null;let n=t.hostname.split("."),o=n.length>2?n.slice(-2).join("."):t.hostname;return`${t.protocol}//${o}`}catch{return null}}async decideChildFrameUnrollEligibility({logger:e,warnings:t,handle:n}){try{let{shouldUnroll:o,reason:i}=await this.decideChildFrameUnrollEligibilityHelper({domNode:n.domNode});return{shouldUnroll:o,reason:i}}catch(o){if(o.message.includes("Could not compute box model"))return{shouldUnroll:!1};let i=`Got error when determining whether to filter frame ${n.frameId} with url ${n.url}, allowing it to be fetched: ${o}`;return t?.push(i),e?.warn({err:o},i),{shouldUnroll:!0}}}async decideChildFrameUnrollEligibilityHelper({domNode:e}){let t=e.attributes??[];if(Tn(t,"aria-hidden")==="true")return{shouldUnroll:!1,reason:"aria-hidden"};let n=Tn(t,"style");if(n?.includes("display: none")||n?.includes("visibility: hidden"))return{shouldUnroll:!1,reason:"hidden CSS style"};await this.cdpClient.send({timeout:J,method:"DOM.pushNodesByBackendIdsToFrontend",params:{backendNodeIds:[e.backendNodeId]}});let[o,i]=await Promise.all([this.cdpClient.send({timeout:J,method:"DOM.getBoxModel",params:{backendNodeId:e.backendNodeId}}),this.cdpClient.send({timeout:J,method:"CSS.getComputedStyleForNode",params:{nodeId:e.nodeId}})]);if(!o.model||!o.model.height||!o.model.width)return{shouldUnroll:!1,reason:"no bounding box"};if(o.model.height<10||o.model.width<10)return{shouldUnroll:!1,reason:"small bounding box"};for(let a of i.computedStyle){if(a.name==="display"&&a.value==="none")return{shouldUnroll:!1,reason:"display: none"};if(a.name==="visibility"&&a.value==="hidden")return{shouldUnroll:!1,reason:"visibility: hidden"};if(a.name==="opacity"&&a.value==="0")return{shouldUnroll:!1,reason:"opacity: 0"}}return{shouldUnroll:!0}}async getRawA11yGraph({cdpClient:e,frameId:t,childFrames:n,logTimings:o,logger:i=this.logger,signal:a=this.abortSignalGetter()}){let l=[];try{await this.pageGetter().waitForLoadState("load",{timeout:this.pageLoadTimeoutMs})}catch(m){i.warn({err:m},"Failed to wait for page load event before a11y tree fetch, attempting to continue without it..."),await this.cdpClient.reinitialize()}let c,s;for(let m=0;m<3;m++)try{s=await sr({fn:()=>this.getRawA11yTreeForFrame({frameId:t,timeoutMs:this.pageLoadTimeoutMs,logTimings:o}),codePath:"a11y-tree-fetch-root",logObject:o,logger:i});break}catch(g){c=g,i.warn({err:g},"Reinitializing CDP client before retrying a11y graph fetch"),await this.cdpClient.reinitialize()}if(!s)throw new Error(`Failed to fetch accessibility tree for root page: ${c}`);let u={};if(u[t??"root"]=s,!this.userControlledBrowserSettings.autoExpandIframes)return u;let d=Array.from(n),p=[];for(;d.length>0;){let m=d.shift();try{let{shouldUnroll:h}=await this.decideChildFrameUnrollEligibility({handle:m,warnings:l});if(!h)continue}catch(h){if(h.message.includes("Could not compute box model"))continue;l.push(`Got error when determining whether to filter frame ${m.frameId} with url ${m.url}, allowing it to be fetched: ${h}`)}d.push(...m.childFrames);let g=async()=>{try{let h=await sr({fn:()=>this.getRawA11yTreeForFrame({frameId:m.frameId,timeoutMs:this.smartWaitingTimeoutMs,logTimings:o}),codePath:`a11y-tree-fetch-child-${m.frameId}`,logObject:o,logger:i});u[m.frameId]=h}catch(h){i.warn({err:h,url:m.url,src:m.src},`Error getting raw a11y tree for child frame ${m.frameId}, continuing...`)}};p.push(g())}return await Promise.all(p),l.length>0&&this.logger.warn({warnings:l},"Got warnings when fetching the raw a11y graph"),u}async getRawA11yTreeForFrame({frameId:e,timeoutMs:t,logTimings:n}){let o;if(this.allowPartialAccessibilityTree)o=(await sr({fn:()=>this.cdpClient.send({method:"Accessibility.getFullAXTree",params:{frameId:e??void 0},timeout:t,timeoutMsg:`Fetching the document tree took over ${t}ms. This usually indicates that the current page is too large to be loaded at once, or your machine is severely resource constrained.`}),codePath:"cdp-query-ax-tree",logObject:n,logger:this.logger})).nodes;else{let a=(await sr({fn:()=>this.cdpClient.send({method:"Accessibility.getRootAXNode",params:{frameId:e??void 0},timeout:me}),codePath:"cdp-get-root-ax-node",logObject:n,logger:this.logger})).node.backendDOMNodeId;o=(await sr({fn:()=>this.cdpClient.send({method:"Accessibility.queryAXTree",params:{backendNodeId:a},timeout:t,timeoutMsg:`Fetching the document tree took over ${t}ms. This usually indicates that the current page is too large to be loaded at once, or your machine is severely resource constrained.`}),codePath:"cdp-query-ax-tree",logObject:n,logger:this.logger})).nodes}if(!o||o.length<=1)throw new Error("Document is entirely empty");return{root:o[0],allNodes:o}}async getDOMTree({devicePixelRatio:e,signal:t,logger:n}){let o,i=0,a;for(;!o&&i<3;)try{if(o=await this.cdpClient.send({method:"DOMSnapshot.captureSnapshot",params:{computedStyles:this.computedStylesToFetch},timeout:J}),!o||!o.documents.length)throw new Error("Got empty DOM tree")}catch(l){await X(it,t),i++,a=l}if(!o||!o.documents.length)throw n.error({err:a},"Fatal error fetching DOM tree"),new w("UserInfrastructureError",`Received an empty HTML snapshot from the browser. This usually indicates the page has crashed due to resource consumption issues or hanging client-side JavaScript code: ${a?.message}`);return CA({snapshot:o,devicePixelRatio:e,computedStylesToFetch:this.computedStylesToFetch,logger:n})}constructIframeRegexAsync(e,t){if(t.frameSrcRegex||t.frameUrlRegex)return;let n=$A(e);(async()=>{try{let o=await this.enricher?.constructIframeRegex(n);o?.srcRegex&&(t.frameSrcRegex=o.srcRegex),o?.urlRegex&&(t.frameUrlRegex=o.urlRegex),this.logger.debug({result:o,params:n},"Constructed iframe regex for cache")}catch(o){this.logger.warn({err:o},"Failed to construct iframe regex, skipping...")}})()}};function wm(r){let e=[],t="";for(let n of r)n==="+"&&t?(e.push(t),t=""):t+=n;return e.push(t),e}var Fa=class r{static USER_AGENT=ac;abortSignal=void 0;contextInitialized=!1;browser;context;properties;page;userControlledBrowserSettings;pageLoadPromises={};lastTabChangeEventTimeout=void 0;clientCallbacks;iconKnowledgeBase;cdpClient;debugData={logsPerPage:[],harPages:{},harEntries:{}};recentFrameNavigations={};requestRecorders={};mocks={};customHeaders=[];enricher;storage;logger;stateManager;transformer;lastScreenshotForRecording=void 0;originsVisited=new Set;viewport;videos=[];baseUrl;constructor({storage:e,enricher:t,browser:n,context:o,page:i,baseUrl:a,logger:l,userBrowserSettings:c,viewport:s,properties:u,clientCallbacks:d,iconKnowledgeBase:p}){if(by(c),this.storage=e,this.enricher=t,this.browser=n,this.context=o,this.page=i,this.baseUrl=a,this.logger=l,this.userControlledBrowserSettings=c,this.viewport=s,this.properties=u,this.clientCallbacks=d,u.recordVideo){let m=this.page.video();m&&this.videos.push(m)}this.iconKnowledgeBase=p}registerAbortSignal(e){this.abortSignal=e}async initialize({grantPermissions:e,runInitScripts:t}){if(this.contextInitialized)return;this.userControlledBrowserSettings.extraHeaders&&await this.context.setExtraHTTPHeaders(this.userControlledBrowserSettings.extraHeaders),e&&await this.context.grantPermissions(["clipboard-read","clipboard-write","microphone","camera","geolocation"]);let n={[ic]:this.userBrowserSettings.visualActions},o=[this.context.addInitScript({content:zp.htmlUtilsLibJs}),this.context.addInitScript({content:`window._MOMENTIC_BROWSER = true; window._MOMENTIC_FEATURE_FLAGS = ${JSON.stringify(n)}; window.addEventListener('load', (event) => { console.log('[MOMENTIC] Page loaded'); });`}),this.exposeRecordingBindings()],i=a=>this.handleNewPageEvent(a);this.context.on("page",i),this.handleNewPageEventHelper(this.page),this.context.on("close",()=>{this.context.off("page",i)}),await Promise.all(o),t&&(await this.page.addScriptTag({content:zp.htmlUtilsLibJs}),await this.page.addScriptTag({content:`window._MOMENTIC_BROWSER = true; window._MOMENTIC_FEATURE_FLAGS = ${JSON.stringify(n)}; window.addEventListener('load', (event) => { console.log('[MOMENTIC] Page loaded'); });`})),this.properties.systemDevicePixelRatio||(process.env.MOMENTIC_LOCAL_DEV==="1"&&oU()==="darwin"&&Zk("system_profiler SPDisplaysDataType").toString().includes("Retina")?(A.warn("[DEV] Setting device pixel ratio to 2 in local dev since a Retina display was detected"),this.properties.systemDevicePixelRatio=2):this.properties.systemDevicePixelRatio=await this.page.evaluate(()=>window.devicePixelRatio)),this.cdpClient=await pc.init({logger:this.logger,contextGetter:()=>this.context,pageGetter:()=>this.page,defaultTimeoutMs:this.pageLoadTimeout}),await this.initializeScreencast(),this.stateManager=new hc({smartWaitingTimeoutMs:this.smartWaitingTimeout,pageLoadTimeoutMs:this.pageLoadTimeout,allowPartialAccessibilityTree:this.userControlledBrowserSettings.allowPartialAccessibilityTree??!1,logger:this.logger,cdpClient:this.cdpClient,pageGetter:()=>this.page,abortSignalGetter:()=>this.abortSignal,enricher:this.enricher,iconKnowledgeBase:this.iconKnowledgeBase,userBrowserSettings:this.userBrowserSettings,allowedA11yIgnoreReasonsOverride:this.properties.allowedA11yIgnoreReasonsOverride}),this.contextInitialized=!0}async fixViewportForNewHeadless(){this.properties.isNewHeadless&&this.viewport&&await this.cdpClient.send({method:"Emulation.setDeviceMetricsOverride",params:{width:this.viewport.width,height:this.viewport.height,deviceScaleFactor:0,mobile:this.viewport.width<1e3}})}async initializeScreencast(){await this.fixViewportForNewHeadless(),this.clientCallbacks?.onScreencastFrame&&this.viewport&&(await this.cdpClient.send({method:"Page.startScreencast",params:{format:"jpeg",quality:75,maxWidth:this.viewport.width,maxHeight:this.viewport.height}}),this.cdpClient.on("Page.screencastFrame",e=>{let t=e.sessionId,n=Buffer.from(e.data,"base64");this.lastScreenshotForRecording=n,this.clientCallbacks?.onScreencastFrame?.(n,()=>{(async()=>{try{await this.cdpClient.send({method:"Page.screencastFrameAck",params:{sessionId:t}})}catch{}})()})}))}static async init(e){let t=await gA(e),n=new r(t);return await n.initialize({grantPermissions:!0,runInitScripts:!1}),n}static async fromExistingContext({context:e,storage:t,enricher:n,userBrowserSettings:o,properties:i,logger:a}){let l=e.pages()[0];if(!l)throw new Error("No page found in existing context");let c=l.viewportSize();c||(c=await l.evaluate(()=>({width:window.innerWidth,height:window.innerHeight})));let s=l?.url(),u=new r({browser:e.browser(),context:e,page:l,baseUrl:s,logger:a,storage:t,enricher:n,userBrowserSettings:o,viewport:c,properties:i,clientCallbacks:void 0,iconKnowledgeBase:null});return await u.initialize({grantPermissions:!1,runInitScripts:!0}),u}async handleAvailableTabsChangeHelper(){try{let e=await hm(this.context,{getTitles:!0}),t=this.page.url();this.clientCallbacks?.onTabsChange?.(e,t)}catch(e){this.logger.error({err:e},"Error sending available tabs to frontend")}}handleAvailableTabsChange(){try{clearTimeout(this.lastTabChangeEventTimeout),this.lastTabChangeEventTimeout=setTimeout(()=>this.handleAvailableTabsChangeHelper(),500)}catch(e){this.logger.warn({err:e},"Error handling available tabs change")}}addToPageLoadPromises(e,t){let n=Rm(),o=`${e}-${n}`,i=Date.now(),a=!1,l=async()=>{try{await B(t(),{signal:this.abortSignal,milliseconds:this.pageLoadTimeout,message:`Page load promise for code path ${e} timed out after ${this.pageLoadTimeout}ms`})}catch(c){c.name!=="AbortError"&&this.logger.error({err:c,promiseKey:o,codePath:e,duration:Date.now()-i},`Page load promise for code path ${e} encountered error`)}finally{delete this.pageLoadPromises[o],a=!0}};this.pageLoadPromises[o]=l().catch(()=>{}),a&&delete this.pageLoadPromises[o]}handlePageClosedEvent(e){if(this.page!==e){this.logger.debug({url:e.url()},"Detected background page was closed, just updating available tabs only"),this.handleAvailableTabsChange();return}let t=async()=>{if(this.closed)return;this.logger.info({url:e.url()},"Detected active page was closed, switching to another tab");let n=this.context.pages();for(let o=n.length-1;o>=0;o--){let i=n[o];if(!(!i||i.isClosed()||!Qn(i.url()))){this.logger.info(`Automatically switching to tab ${o} after close: ${i.url()}`),await this.switchToPage({type:"INDEX",index:String(o)});break}}};this.addToPageLoadPromises("page closed handler",async()=>t())}handleNewPageEvent(e){let t=e.url();if(this.logger.info({url:t},"Detected new page event, registering handlers and waiting for load to complete"),this.properties.recordVideo){let n=e.video();n&&this.videos.push(n)}try{this.handleNewPageEventHelper(e)}catch(n){this.logger.warn({err:n},"Error handling new page open, continuing....")}}handleNewPageEventHelper(e){let t=Rm(),n="new-page-load-handler";e.on("close",a=>this.handlePageClosedEvent(a)),e.on("framenavigated",a=>this.handleFrameNavigationEvent(a)),e.on("crash",()=>{this.logger.error("Page crashed at the Playwright level!")});let o=this.context.pages().indexOf(e);e.on("console",a=>{Qv(e,o,this.debugData,a,this.logger)});let i=async()=>{await rA(t,this.debugData,e),await e.route("**/*",async(a,l)=>{await om({pageId:t,route:a,request:l,debugData:this.debugData,logger:this.logger,requestRecorders:this.requestRecorders,mocks:this.mocks})}),await e.route("**/*",sA(this.customHeaders,this.logger)),cn&&await e.route("**/*",ka),await this.loadFrameAndRecordUrl({root:e,codePath:n}),this.handleAvailableTabsChange()};this.addToPageLoadPromises(n,async()=>i())}async handleCollectSvgs(e){}handleFrameNavigationEvent(e){let t=e.url(),n=e.parentFrame()?"has-parent":"no-parent",o=`frame-navigation-handler-${t.slice(0,50)} (${n})`;if(!t||t==="about:blank"||!Qn(t)||this.recentFrameNavigations[o]&&Date.now()-this.recentFrameNavigations[o]<1e3)return;this.recentFrameNavigations[o]=Date.now();let i=async()=>{try{if(e.isDetached())return;await this.loadFrameAndRecordUrl({root:e,codePath:o}),this.handleAvailableTabsChange(),!e.parentFrame()&&!e.isDetached()&&this.clientCallbacks?.onSvgsCollected&&(setTimeout(()=>{(async()=>{try{await this.handleCollectSvgs(e)}catch(l){this.logger.warn({err:l},"Failed to collect SVGs on page, continuing...")}})()},5e3),this.transformer&&await this.injectKnowledgeBaseIntoBrowser(e))}catch(a){a.name!=="AbortError"&&this.logger.warn({err:a,url:t,codePath:o},"Failed to handle frame navigation event, continuing...")}};this.addToPageLoadPromises(o,async()=>i())}async injectKnowledgeBaseIntoBrowser(e){try{if(!this.iconKnowledgeBase||await e.evaluate(()=>!!window._MOMENTIC_ICON_KNOWLEDGE_BASE))return;let n={};Object.keys(this.iconKnowledgeBase).forEach(o=>{this.iconKnowledgeBase[o]?.description&&(n[o]=this.iconKnowledgeBase[o].description)}),await e.evaluate(o=>{let i=window;i._MOMENTIC_ICON_KNOWLEDGE_BASE=o},n)}catch(t){this.logger.warn({err:t},"Failed to inject icon knowledge base into browser, continuing...")}}getBrowserCallbacks(){return{waitForPageLoad:()=>this.waitForPageLoad(),waitForUrl:e=>this.waitForUrl(e),getBrowserState:e=>this.getBrowserState(e),waitForDomStability:e=>this.waitForDOMStability(e),state:{url:()=>this.url(),getDomGraph:()=>this.stateManager.domGraph,getOpenPages:()=>this.getOpenPages(),getRoot:()=>this.getActivePageOrFrame(),userBrowserSettings:this.userBrowserSettings},pageLoadTimeoutMs:this.pageLoadTimeout,signal:this.abortSignal}}ping(){if(this.closed)throw new Error("Page has been closed")}setActiveFrameConfig(e){this.stateManager.setActiveFrameConfig(e)}async reset(e){for(this.abortSignal=void 0,this.debugData.logsPerPage=[],this.debugData.harPages={},this.debugData.harEntries={},this.pageLoadPromises={};this.videos.length>0;)this.videos.pop();await this.clearAuthState({closeNonActiveTabs:!0}),await this.stopScreencast(),await this.reinitializeCDPClient(),await this.navigate({url:e.newUrl??this.baseUrl,initialNavigation:!0,loadTimeoutMs:e.timeout}),this.stateManager.reset()}async clearHighlights(){try{await B(pm(this.getBrowserCallbacks()),{milliseconds:Z})}catch(e){this.logger.debug({err:e},"Failed to clear highlights, continuing...")}}async cleanup(){this.abortSignal=void 0;try{this.originsVisited.clear(),await this.context.close(),await this.browser?.close(),this.browser=null}catch(e){this.logger.warn({err:e},"Error cleaning up browser, continuing...")}finally{this.browser=null}}get closed(){return this.context.pages().every(e=>e.isClosed())||!!this.browser&&!this.browser.isConnected()}async ensureMomenticBrowserScriptsLoaded(e,t,n){let o=Date.now(),i=0,a=0;for(;Date.now()-o<Hp;){a++,n?.throwIfAborted();try{if(await Qe({fn:()=>{let c=window;return!!(c.generateCssSelectors&&c.evaluateCssSelectors&&c.evaluatePrimaryCaches&&c.generateHtmlCacheAttributes&&c.ldist)},timeout:Z,arg:void 0,waitForPageLoad:()=>this.waitForPageLoad(),root:e,codePath:"ensuring Momentic system scripts are loaded"}))return}catch(l){if(i++,i>=3){t.warn({err:l},"Multiple errors checking if Momentic scripts are loaded, aborting...");return}}await X(it),a%2===0&&t.warn("Still waiting for momentic browser scripts to load...")}throw new Error(`Failed to load momentic browser scripts on page ${e.url()}`)}async html(){let e=await this.getActivePageOrFrame();return await this.ensureMomenticBrowserScriptsLoaded(e,this.logger),Qe({root:e,fn:()=>{let t=window;if(!t?.getFullHtmlTree)throw new Error("Missing Momentic HTML library when fetching page HTML");return t.getFullHtmlTree()},arg:void 0,timeout:J,waitForPageLoad:()=>this.waitForPageLoad(),codePath:"getting the full HTML tree"})}url(){return this.page.url()}async stabilizePageForScreenshot(){try{await this.evaluateFunctionInPage(()=>{let e=window,t=[],n=new Map;document.querySelectorAll("input,textarea,[contenteditable]").forEach(o=>{n.set(o,{value:o.style.getPropertyValue("caret-color"),priority:o.style.getPropertyPriority("caret-color")}),o.style.setProperty("caret-color","transparent","important")}),t.push(()=>{for(let[o,i]of n)o.style.setProperty("caret-color",i.value,i.priority)}),e._MOMENTIC_SCREENSHOT_CLEANUP=()=>{for(let o of t)o();delete e._MOMENTIC_SCREENSHOT_CLEANUP}},void 0,"stabilizing page for screenshot")}catch(e){(!(e instanceof Error)||!e.message.includes("Execution context was destroyed"))&&this.logger.warn({err:e},"Failed to stabilize page before screenshot, continuing...")}}async removeScreenshotStabilization(){try{await this.evaluateFunctionInPage(()=>{window._MOMENTIC_SCREENSHOT_CLEANUP?.()},void 0,"removing screenshot stabilization")}catch{}}async screenshot(e){let{retries:t=1,stabilizeBeforeScreenshot:n=!1}=e,o=this.page.url();n&&await this.stabilizePageForScreenshot();let i=Date.now();try{await this.fixViewportForNewHeadless();let a=await this.screenshotHelper({...e,retries:t});if(a.byteLength>5e6)this.logger.error("Page screenshot is greater than 5MB, which may cause performance issues with some AI models");else if(a.length===0)throw new Error("Got empty screenshot");return a}catch(a){if(t<=0||a.message.includes("has been closed"))throw a;return this.logger.warn({err:a,pageUrl:o},"Failed taking screenshot, retrying..."),await X(ei),this.screenshot({...e,retries:t-1})}finally{Date.now()-i>1e3&&this.logger.warn({pageUrl:o,duration:Date.now()-i},"Screenshot took longer than expected"),n&&await this.removeScreenshotStabilization()}}async screenshotHelper({locator:e,quality:t,saveToDiskPath:n,timeout:o,respectActiveFrame:i,clearHighlights:a=!1}){a&&await this.clearHighlights(),i&&this.stateManager.frameConfig&&(e=await(await this.getActivePageOrFrame()).frameElement());let l=await this.cdpClient.send({method:"Page.captureScreenshot",params:{format:"jpeg",quality:t,optimizeForSpeed:!0},timeout:o??me}),c=Buffer.from(l.data,"base64"),s=await JA.fromBuffer(c),{width:u,height:d}=this.getViewport()??{};if(u&&d&&(s.bitmap.width!==u||s.bitmap.height!==d)&&(c=await s.resize({w:u,h:d}).getBuffer("image/jpeg")),n&&tU(n,c),this.lastScreenshotForRecording=c,!e)return c;let p=await e.boundingBox({timeout:J});if(!p)throw new Error("Attempted to screenshot an element that is not visible on the page");let{x:m,y:g,width:h,height:f}=p;if(!h||!f)throw new Error("Attempted to screenshot an element with zero width or height");m=Math.floor(m),g=Math.floor(g),h=Math.floor(h),f=Math.floor(f);try{let b=await JA.fromBuffer(c),E=b.bitmap.width,v=b.bitmap.height;m=Math.max(0,Math.min(m,E-1)),g=Math.max(0,Math.min(g,v-1)),h=Math.max(1,Math.min(h,E-m)),f=Math.max(1,Math.min(f,v-g)),c=await b.crop({x:m,y:g,w:h,h:f}).getBuffer("image/jpeg")}catch(b){throw new Error(`Failed taking element screenshot at coordinates (${m}, ${g}) with size (${h}, ${f}): ${b}`)}finally{"dispose"in e&&await e?.dispose()}return c}getViewport(){if(this.viewport)return this.viewport;let e=this.page.viewportSize();return e||null}async navigate({url:e,initialNavigation:t=!1,loadTimeoutMs:n=this.pageLoadTimeout}){kv(e)&&(e=new URL(e,this.baseUrl).toString());let o=Date.now();t||(await this.waitForPageLoad(),await this.waitForDOMStability());let i=!1,a;for(let c=0;c<3;c++)try{await this.page.goto(e,{timeout:n,waitUntil:"domcontentloaded"}),i=!0;break}catch(s){if(a=s,this.abortSignal?.throwIfAborted(),this.logger.warn({err:s},`Error occurred during navigation${c===0?", retrying...":" (fatal)"}`),await X(it),a.message.includes("Timeout")&&a.message.includes("exceeded")||a.message.includes("net::ERR_CONNECTION_REFUSED"))break;await this.cdpClient.send({method:"Page.stopLoading",params:{},timeout:Z})}if(!i)throw new w("UserInfrastructureError",a?.message??"Failed to load page");await this.loadFrameAndRecordUrl({root:this.page,signal:this.abortSignal,codePath:"navigate-step-wait-for-load"}),this.logger.info({url:e},`Navigation complete in ${Math.floor(Date.now()-o)}ms`);let l=this.url();if($v.has(l))throw new w("UserInfrastructureError",`${e} took too long to load \u{1F61E}. Please ensure the site is accessible and returns content within the page load timeout.`);await this.fixViewportForNewHeadless()}async type(e,t={},n=!1){await this.directTypeHelper(e,t,n)}async getActiveElement(e){try{return await Qe({root:e,fn:()=>{let n=document.activeElement?.textContent??void 0;return n&&n.length>100&&(n=n.slice(0,100)+"...[TRUNCATED]"),document.activeElement?{tag:document.activeElement.tagName.toLowerCase(),contentEditable:document.activeElement.getAttribute("contenteditable")??void 0,textContent:n}:void 0},arg:void 0,timeout:Z,waitForPageLoad:()=>this.waitForPageLoad(),codePath:"getting the active element"})}catch(t){this.logger.warn({err:t},"Failed to get active element");return}}async directTypeHelper(e,t={},n=!1){let o=await this.getActivePageOrFrame();await yA({root:o,text:e,options:t,logger:this.logger,callbacks:this.getBrowserCallbacks()});let i=await this.getActiveElement(o);if(n){let a=Date.now();for(;Date.now()-a<this.smartWaitingTimeout&&(!i||i.tag==="body");)await X(ei),this.abortSignal?.throwIfAborted(),i=await this.getActiveElement(o);i||this.logger.warn("No active element found to type into, attempting anyways")}t.clearContent&&(t.forceClearContent||i?.tag==="input"||i?.tag==="textarea"?(this.properties.isAndroid?await this.page.keyboard.press("Control+A"):process.platform==="darwin"?await this.page.keyboard.press("Meta+A"):await this.page.keyboard.press("Control+A"),await this.page.keyboard.press("Backspace"),await this.page.waitForTimeout(25)):this.logger.info({activeElementDetails:i},"Currently active element is not eligible for replace content, skipping...")),await this.page.keyboard.type(e,{delay:t.delay??Xg}),t.pressEnter&&await this.press("Enter",{})}async scrollIntoViewIfNeeded(e){try{await e.scrollIntoViewIfNeeded({timeout:me})}catch(t){this.logger.warn({err:t},"Failed to scroll into view, trying with raw JS");try{await e.evaluate(async n=>{let o=n.scrollTop;n.scrollIntoView(),await new Promise(a=>setTimeout(a,250));let i=Date.now();for(;Date.now()-i<1e3;){let a=n.scrollTop;if(a===o)break;o=a,await new Promise(l=>setTimeout(l,250))}},void 0,{timeout:me})}catch(n){this.logger.warn({err:n},"Failed to scroll into view using JS, continuing...")}}}async highlightA11yId(e){try{let{resolution:t}=await this.createTargetFromA11yId({id:e,description:null,targetSource:"AI",skipSaveToCache:!0});return await this.highlight(t.locator),!0}catch(t){return this.logger.debug({err:t,id:e},"Failed to highlight target"),!1}}async highlight(e){return uc({locator:e,callbacks:this.getBrowserCallbacks(),logger:this.logger})}recordUrlVisited(e){try{let t=new URL(e).origin;if(t==="null")return;this.originsVisited.add(t)}catch(t){this.logger.warn({err:t},"Failed to record origin visited")}}async waitForPageLoad(){let e=Date.now(),t=Object.values(this.pageLoadPromises),n=Object.keys(this.pageLoadPromises),o=-1,i=0;for(;t.length!==0;){if(Date.now()-e>this.pageLoadTimeout&&this.logger.error({outstandingPromiseKeys:n,outstandingPromises:t},"Still waiting on page load promises"),Date.now()-o<20&&(i++,i>2)){this.logger.error({outstandingPromiseKeys:n,outstandingPromises:t},"Synchronous waiting loop detected, exiting page load wait");return}o=Date.now(),await Promise.allSettled(t),t=Object.values(this.pageLoadPromises),n=Object.keys(this.pageLoadPromises)}}async clearAuthState(e){await this.context.clearCookies();for(let o of this.originsVisited)this.logger.debug({origin:o},`Clearing data using CDP for origin ${o}`),await this.cdpClient.send({method:"Storage.clearDataForOrigin",params:{origin:o,storageTypes:"all"},timeout:Z}),this.originsVisited.delete(o);let t=this.context.pages().indexOf(this.page),n=[...this.context.pages()];for(let o=0;o<n.length;o++){let i=n[o];if(i.isClosed())continue;let a=i.url();try{this.originsVisited.delete(new URL(a).origin)}catch{}await Zv(i,this.logger),o!==t&&e.closeNonActiveTabs&&(this.logger.info(`Closing tab ${o} with URL ${a}`),await i.close())}}async loadAuthState(e){await this.waitForPageLoad(),await this.waitForDOMStability(),!e||Object.keys(e).length===0?await this.clearAuthState({closeNonActiveTabs:!1}):await this.loadAuthStateHelper(e),await this.refresh(),await this.waitForDOMStability()}async loadAuthStateHelper(e){let t=[];for(let i of e.cookies??[]){let a=await this.setCookie(i);t=t.concat(a)}this.logger.info(`Loaded ${e.cookies?.length??0} cookies`),await this.cdpClient.send({method:"DOMStorage.enable",params:void 0,timeout:Z});let n=0;for(let i of e.origins??[])for(let a of i.localStorage)try{await this.cdpClient.send({timeout:Z,method:"DOMStorage.setDOMStorageItem",params:{storageId:{securityOrigin:new URL(i.origin).origin,isLocalStorage:!0},key:a.name,value:a.value}}),n++}catch(l){this.logger.warn({err:l,origin:i},"Failed to set local storage entry, continuing...");break}this.logger.info(`Loaded ${n} local storage entries`);let o=e.idb;o&&Object.keys(o).length>0&&(await Jv(this.page,o,this.logger),this.logger.info(`Loaded ${Object.keys(o??{}).length} indexedDB databases`))}async saveAuthState(){let t=0,n=null;for(;t<=2;)try{await this.waitForPageLoad(),await this.waitForDOMStability();let o=await this.context.storageState();return o.idb=await Xv(this.page,this.logger),o}catch(o){if(n=o,t++,t<=2){this.logger.warn({err:o,retryCount:t,maxRetries:2},`Error saving auth state, retrying (${t}/2)...`);let i=Math.pow(2,t)*100;await new Promise(a=>setTimeout(a,i))}}throw this.logger.error({err:n},"Failed to save auth state after 2 retries"),new w("ActionFailureError",`Failed to save auth state: ${n?.message}`)}async getOpenPages(e){return hm(this.context,e)}saveA11yDetailsToCache(e,t){t.content=e.content,t.name=e.name,t.role=e.role,t.numChildren=e.children.length,delete t.serializedForm,delete t.nodeOnlySerializedForm}async updateCacheWithNewNodeDetails({node:e,target:t,locator:n,startingBoundingBox:o,allowNotActionableNodesOverride:i,logger:a=this.logger}){if(e&&this.saveA11yDetailsToCache(e,t),t.frameCache=this.stateManager.saveAutoFrameCacheDetails(t.frameCache),n)try{let l=await this.fetchHtmlAttributes({locator:n,logger:a,startingBoundingBox:o,allowNotActionableNodesOverride:i});l?(t.generatedSelectors=l.generatedSelectors,t.serializedHtml=l.serializedHtml,t.nodeOnlySerializedHtml=l.nodeOnlySerializedHtml,t.hybridSelector=l.hybridSelector):a.warn("Got undefined HTML attributes when trying to update cache")}catch(l){if(l instanceof Tr)throw a.warn({err:l},"Cache attributes disqualify found element"),l;a.warn({err:l},"Failed to fetch HTML attributes for target, continuing...")}try{await this.saveElementVisualAttributes({target:t,locator:n,logger:a,boundingBox:o})}catch(l){a.debug({err:l},"Failed to save element visual details, continuing...")}}async saveElementVisualAttributes({target:e,locator:t,logger:n,boundingBox:o}){if(!t)return{scrollPerformed:!1};if(!Wp.includes(e?.role??""))return{scrollPerformed:!1};if(await this.scrollIntoViewIfNeeded(t),o||(o=await t.boundingBox({timeout:J})),!o||!o.width||!o.height)return n.debug("Skipping visual attributes saving for element with no bounding box after action"),e.boundingBox=void 0,e.screenshotUrl=void 0,{scrollPerformed:!0};let{x:i=0,y:a=0,width:l=0,height:c=0}=o;if(e.boundingBox&&Math.abs(e.boundingBox.width-l)<1&&Math.abs(e.boundingBox.height-c)<1&&Math.abs((e.boundingBox.x??0)-i)<1&&Math.abs((e.boundingBox.y??0)-a)<1)return{scrollPerformed:!0};e.boundingBox=o;let s=await this.screenshot({locator:t,quality:75,retries:0});return e.screenshotUrl=await this.storage.uploadScreenshot(s),{scrollPerformed:!0}}async resolveAutoFrameCache(e){return this.stateManager.resolveAutoFrameCache(e)}async getElementRequiredValues({locator:e,requirements:t}){let n={};if(t?.boundingBox){let o=await e.boundingBox({timeout:J});if(!o||!o.width||!o.height)throw new w("ActionFailureError","Element does not have a bounding box as required");n.boundingBox=o??void 0}if(t?.text){let o=await e.innerText({timeout:J});n.text=o?.trim()}if(t?.attributes&&t.attributes.length>0){let o={};for(let i of t.attributes){let a=i.trim().toLowerCase();if(!(!a||ar.bannedAiRequiredCacheAttributes.includes(a)))try{let l=await e.getAttribute(a,{timeout:J});l!==null&&(o[i]=l)}catch(l){this.logger.warn({err:l,attr:i},"Failed to fetch required attribute, continuing...")}}n.attributes=o}return n}async getAdditionalElementDetails({mainLocator:e,additionalElement:t,root:n,logger:o}){let i=this.stateManager.a11yIdToNodeMap[t.id];if(!i)return;let a=await this.stateManager.getLocatorFromA11yNode({page:this.page,root:n,node:i});if(e.contentFrame!==a.contentFrame)return;let l=await this.fetchHtmlAttributes({locator:a,logger:o});if(!l?.generatedSelectors||l.generatedSelectors.length===0)return;let c={selectors:l.generatedSelectors};return t.requirements&&(c.requirements=await this.getElementRequiredValues({locator:a,requirements:t.requirements})),c}async getAdditionalElementsDetails({mainElementId:e,mainLocator:t,additionalElements:n,root:o,logger:i}){let a=new Set,l=[];for(let c of n)try{if(c.id===e||a.has(c.id))continue;let s=await this.getAdditionalElementDetails({mainLocator:t,additionalElement:c,root:o,logger:i});if(a.add(c.id),!s)continue;l.push(s)}catch(s){this.logger.warn({err:s,additionalElement:c},"Failed to fetch additional element details, continuing...")}return l}async updateCacheWithAdditionalRequirements({mainElementId:e,requirements:t,additionalElements:n,target:o,locator:i,root:a,logger:l}){t&&(o.requirements=await this.getElementRequiredValues({locator:i,requirements:t})),n&&(o.additionalElements=await this.getAdditionalElementsDetails({mainElementId:e,mainLocator:i,additionalElements:n,root:a,logger:l}))}async createTargetFromA11yId({id:e,description:t,targetSource:n,skipSaveToCache:o,logger:i=this.logger,requirements:a,additionalElements:l}){if(e<0)throw new w("InternalWebAgentError","Only positive IDs should be passed to resolveAllyIdToTarget");let c=this.stateManager.a11yIdToNodeMap[e];if(!c)throw new w("InternalWebAgentError",`Resolving target failed because id ${e} does not exist on the page. This generally indicates an incorrect element was targeted.`);let s=this.stateManager.frameConfig,u,d,p,m;if(this.userBrowserSettings.autoExpandIframes&&!s&&c.parentFrame){let E=c.parentFrame,{cache:v,config:R}=await this.stateManager.getAutoFrameDetailsFromHandle(E);d=v,p=R,u=R.frame,m="auto iframe"}else c.parentFrame&&s?(p=s,u=await this.getActivePageOrFrame(),m="hardcoded url already on the state manager"):(u=await this.getActivePageOrFrame(),m="should not be possible");let g=await this.stateManager.getLocatorFromA11yNode({page:this.page,root:u,node:c}),h={id:e,inputDescription:t??void 0,targetSource:n,targetUpdateTime:new Date().toISOString(),targetUpdateLoggerTags:pe(i),frameCache:d},f,b=!1;o||(p&&(i.info({frameConfigSource:m,frameConfig:qA(p)},"A11y node was resolved to a target within an iframe"),f=this.stateManager.frameConfig,this.stateManager.setActiveFrameConfig(p),b=!0),await this.updateCacheWithNewNodeDetails({node:c,target:h,locator:g,logger:i,allowNotActionableNodesOverride:!0}),await this.updateCacheWithAdditionalRequirements({mainElementId:e,requirements:a,additionalElements:l,target:h,root:u,locator:g,logger:i}));try{return{resolution:{locator:g,a11yNode:c,displayString:c.getNodeOnlySerializedForm(),decisions:[]},target:h,frameConfig:p,frameConfigSource:m}}finally{b&&this.stateManager.setActiveFrameConfig(f)}}async resolveTarget(e,t,n={}){let{targetName:o,logger:i=this.logger,signal:a=this.abortSignal,allowNotActionableNodesOverride:l}=n;if(t.frameCache&&this.userBrowserSettings.autoExpandIframes){let m,g=!1,h=Date.now();for(;Date.now()-h<this.smartWaitingTimeout;)try{let f=await this.stateManager.resolveAutoFrameCache(t.frameCache);this.setActiveFrameConfig(f),g=!0;break}catch(f){m=f,await X(it,a)}if(!g)throw m}let c=await this.getActivePageOrFrame();await this.ensureMomenticBrowserScriptsLoaded(c,i,a);let s=Date.now(),u=0,d=0,p;for(;Date.now()-s<this.smartWaitingTimeout;){this.abortSignal?.throwIfAborted(),u++;let m=u===2||Date.now()-s>this.smartWaitingTimeout-2e3&&u%2===0;try{p=await this.resolveTargetHelper({root:c,target:t,primaryOnly:!0,shouldLogOnFailure:m,logger:i,allowNotActionableNodesOverride:l,signal:a});break}catch(g){if(g instanceof Bi)break;if(g instanceof Tr){if(d++,d>2)throw i.error({err:g},"Got multiple cache disqualification errors, giving up"),g;i.warn({err:g},"Got cache disqualification error, waiting and retrying resolution"),await X(it,a)}a?.throwIfAborted(),m&&i.warn({err:g},`Could not resolve target using primary cache only (x${u})`),await X(it,a)}}return p||(p=await this.resolveTargetHelper({root:c,target:t,primaryOnly:!1,logger:i,signal:a,allowNotActionableNodesOverride:l}),t.targetSource="HEURISTIC_HEALED",t.targetUpdateTime=new Date().toISOString(),t.targetUpdateLoggerTags=pe(i),i.info({decisions:p.decisions},"Target resolution succeeded after waiting")),e?.details?.push({type:"TARGETING",name:o,elementLocationDecisions:p?.decisions??[],pageState:void 0,targetSource:t.targetSource,targetUpdateTime:t.targetUpdateTime}),p}async resolveTargetHelper({root:e,target:t,primaryOnly:n,logger:o,signal:i,allowNotActionableNodesOverride:a,shouldLogOnFailure:l}){let c=oi(t),s=[],u=(await this.getBrowserState({logger:o,abortSignal:i,skipWait:!0,allowNotActionableNodesOverride:a})).serialize(),d;if(t.generatedSelectors||t.hybridSelector){let p;try{p=await this.resolveTargetWithPrimaryMethods({root:e,target:t,logger:o,allowNotActionableNodesOverride:a,shouldLogOnFailure:l})}catch(m){d=m,m instanceof Zr&&s.push(...m.decisions)}if(p)return{...p,pageState:void 0,decisions:[...s,...p.decisions]};n||(s.push({type:"CSS_SELECTOR",matched:!1,reason:d?.message,selectors:oi(t.generatedSelectors??[])}),t.generatedSelectors=void 0,t.hybridSelector=void 0)}if(n)throw d;if(!this.userBrowserSettings.disableSecondaryCacheResolution){let p=await this.resolveTargetWithSecondaryMethods({root:e,tree:u,target:t,decisions:s,logger:o,signal:i,allowNotActionableNodesOverride:a});if(p)return p}throw new Zr(`Could not find any relevant node given target: ${JSON.stringify(c)}`,s)}async resolveTargetWithPrimaryMethods({root:e,target:t,logger:n,allowNotActionableNodesOverride:o,shouldLogOnFailure:i}){if(!t.nodeOnlySerializedHtml)throw new Bi("Insufficient data to resolve target using primary methods (missing node HTML)");let a=i?n:un,l=this.userControlledBrowserSettings.hybridSelectorMode,c={ldistThreshold:jp,requireBoundingBox:!o,ignoreHrefForCaching:this.userControlledBrowserSettings.ignoreHrefForCaching,requireMatchingBoundingBox:this.userControlledBrowserSettings.bustCacheOnBoundingBoxChange?t.boundingBox:void 0,requirements:t.requirements,additionalElements:t.additionalElements,importantProperties:{attributes:this.userControlledBrowserSettings.importantAttributes,classes:this.userControlledBrowserSettings.importantClasses,styles:this.userControlledBrowserSettings.importantStyles}},{css:s,hybrid:u}=await Qe({fn:v=>window.evaluatePrimaryCaches(v),arg:{cssParams:{selectors:t.generatedSelectors??[],cachedElementSerialized:t.nodeOnlySerializedHtml,opts:c},hybridParams:l&&t.hybridSelector?{nodes:t.hybridSelector,cachedElementSerialized:t.nodeOnlySerializedHtml,opts:c}:void 0},root:e,timeout:J,waitForPageLoad:()=>this.waitForPageLoad(),codePath:"evaluating target caches"}),d,p,m=[];if(l==="prefer"&&u?.result){d=u.result;let v={type:"HYBRID_SELECTOR",matched:!0,logs:u.logs,reason:"Discovered a match using Momentic's hybrid text and CSS selector approach"};m.push(v),p="HYBRID_SELECTOR"}else if(s?.result){d=s.result;let v=`${d.workingSelectors.length} CSS selectors matched the following element: ${d.serializedElement}`,R=d.workingSelectors.slice(0,5);m.push({type:"CSS_SELECTOR",matched:!0,logs:s.logs,reason:v,selectors:R}),n.debug({reason:v,workingSelectors:R},"Resolved with CSS selectors"),p="CSS_SELECTOR"}else throw m.push({type:"CSS_SELECTOR",matched:!1,reason:s.logs.length===1?"CSS evaluation failed":"No CSS selectors matched",selectors:[],logs:s.logs}),u&&m.push({type:"HYBRID_SELECTOR",matched:!1,reason:u.logs.length===1?"Hybrid evaluation failed":"No hybrid selectors matched",logs:u.logs}),new Zr("Cache evaluation failed",m);let g,h,f;if(this.userBrowserSettings.visualActions){let v=d.mPath;if(!v)throw new Error("Found element did not have an mPath despite using visual actions");let R=v.join(" > ");g=e.locator(R),h=this.stateManager.getNodeUsingMPathSelector(R)}else if(d.dataMomenticId!==void 0)f=parseInt(d.dataMomenticId),h=this.stateManager.dataMomenticIdToNodeMap[f],"workingSelectors"in d?g=e.locator(d.workingSelectors[0]):g=e.locator(hr(f));else throw new w("InternalWebAgentError","Received an element resolution result with no identifying attributes");l&&t.hybridSelector&&(u?.logs.length===1?a.warn({hybridResult:u,cssResult:s,hybridMode:l},"Hybrid selector resolution rejected, continuing..."):u?.result?s?.result&&u?.result&&u.result.serializedElement!==s.result.serializedElement&&(this.userBrowserSettings.visualActions&&JSON.stringify(s.result.mPath)!==JSON.stringify(u.result.mPath)?n.warn({originalCache:t,hybridResult:u,cssResult:s,hybridMode:l,mode:"visualActions"},"Hybrid selector resolution returned a different element than CSS selector resolution, continuing..."):s.result.dataMomenticId!==u.result.dataMomenticId&&n.warn({originalCache:t,hybridResult:u,cssResult:s,hybridMode:l,mode:"dataMomenticId"},"Hybrid selector resolution returned a different element than CSS selector resolution, continuing...")):a.warn({originalCache:t,hybridResult:u,cssResult:s,hybridMode:l},"Hybrid selector resolution returned no eligible elements while CSS resolution did, continuing..."));let b=oi(t);await this.updateCacheWithNewNodeDetails({node:h,target:t,locator:g,logger:n,startingBoundingBox:d.boundingBox,allowNotActionableNodesOverride:o});let E=Cm(b,t);return E&&Object.keys(E).length>0&&(t.cacheResolutionUpdateTime=new Date().toISOString(),t.cacheResolutionUpdateLoggerTags=pe(n),t.cacheResolutionUpdateSource=p,n.debug({diffs:E},"Updated cache")),{a11yNode:h,displayString:d.serializedElement,locator:g,decisions:m}}async resolveHardcodedCssSelector(e){let{ctx:t,selector:n,logger:o=this.logger,signal:i=this.abortSignal,timeoutMs:a=this.smartWaitingTimeout}=e,l=await this.getActivePageOrFrame(),c=Date.now(),s=0,u,d=[];for(;Date.now()-c<a;){i?.throwIfAborted(),s++;let p=l.locator(n),m;try{return await p.waitFor({state:"attached",timeout:Z}),m=await jr(p,o)??"",d.push({type:"USER_SELECTOR",matched:!0,reason:`The user-provided CSS selector ${n} matched an element on the page.`}),t?.details?.push({type:"TARGETING",name:e.targetName,elementLocationDecisions:d,targetSource:"USER_CSS_SELECTOR",targetUpdateTime:new Date().toISOString()}),{locator:p,displayString:m,decisions:d}}catch(g){let h=g.message;u=new w("ActionFailureError",`CSS selector '${n}' failed to resolve after ${s} attempts: ${h.includes("locator.waitFor: Timeout")?"the selector did not match any element on the page":h}`),await X(it,i)}}throw u}async resolveTargetWithSecondaryMethods(e){if(!e.target.boundingBox)return;let{x:t,y:n,width:o,height:i}=e.target.boundingBox,a=await this.resolveTargetWithSecondaryMethodsHelper(e);if(!a)return;let l=await a.locator.boundingBox({timeout:J});if(!l){this.logger.debug({proposedNode:a.displayString},"Rejecting secondary matching result due to lack of a bounding box");return}let{x:c,y:s,width:u,height:d}=l;if(Math.abs(u-o)>10||Math.abs(d-i)>10){this.logger.debug({newW:u,oldW:o,newH:d,oldH:i,proposedNode:a.displayString},"Rejecting secondary matching result due to difference in dimensions");return}else if(!t||!n||!c||!s){this.logger.debug({oldX:t,oldY:n,newX:c,newY:s,proposedNode:a.displayString},"Rejecting secondary matching result due to missing x/y coords");return}else if(Math.abs(c-t)>100||Math.abs(s-n)>100){this.logger.debug({newX:c,newY:s,oldX:t,oldY:n,proposedNode:a.displayString},"Rejecting secondary matching result due to large difference in x/y coords");return}return a}async resolveTargetWithSecondaryMethodsHelper({root:e,target:t,decisions:n,logger:o,signal:i,allowNotActionableNodesOverride:a}){if(t.nodeOnlySerializedHtml&&t.nodeOnlySerializedHtml.trim().length<jv){let s="Refusing to attempt HTML comparison since the saved element is too short.";n.push({type:"HTML_DISTANCE",matched:!1,reason:s})}else if(t.nodeOnlySerializedHtml&&t.nodeOnlySerializedHtml.length>50)try{let s=await Qe({fn:d=>window.findClosestElementByLDist?.(d),arg:{nodeOnlySerializedHtml:t.nodeOnlySerializedHtml},timeout:me,root:e,waitForPageLoad:()=>this.waitForPageLoad(),codePath:"finding the closest element on the page"}),u=Math.floor(jp*t.nodeOnlySerializedHtml.length);if(s&&s.closestDistance&&s.closestDistance>=u){let d=`Closest HTML candidate still has too far distance (${s.closestDistance}) from threshold (${u})`;n.push({type:"HTML_DISTANCE",matched:!1,reason:d,distance:s.closestDistance,closestElement:s.closestNodeSerialized})}else{if(s?.error)throw new Error(s.error);if(s?.dataMomenticId||s?.mPathSelector){let d=s.dataMomenticId?parseInt(s.dataMomenticId):void 0,p,m;if(d)p=this.stateManager.dataMomenticIdToNodeMap[d],m=e.locator(hr(d));else if(s.mPathSelector)p=this.stateManager.getNodeUsingMPathSelector(s.mPathSelector),m=e.locator(s.mPathSelector);else throw new Error("HTML ldist comparison returned no error, data momentic id, or mPath selector");let g=s.closestNodeSerialized??await jr(m,o)??"unknown element";o.warn({result:s,originalTarget:t,displayString:g},"Resolved cached target to new node with pure html levenshtein distance");let h=oi(t);await this.updateCacheWithNewNodeDetails({node:p,target:t,locator:m,logger:o,startingBoundingBox:s.boundingBox,allowNotActionableNodesOverride:a});let f=Cm(h,t);return f&&Object.keys(f).length>0&&(t.cacheResolutionUpdateTime=new Date().toISOString(),t.cacheResolutionUpdateLoggerTags=pe(o),t.cacheResolutionUpdateSource="HTML_DISTANCE",o.info({diffs:f,result:s},"Updated cache after l-dist resolution")),n.push({type:"HTML_DISTANCE",matched:!0,reason:`Found an element on the page within ${u} string comparison distance of the saved element.`,logs:s.logs,distance:s.closestDistance,closestElement:g,savedElement:t.nodeOnlySerializedHtml}),{locator:m,a11yNode:p,displayString:g,decisions:n,pageState:void 0}}else throw new Error(`Got invalid HTML evaluation result: ${JSON.stringify(s)}`)}}catch(s){o.info({err:s},"Failed to find closest HTML node using levenshtein distance"),n.push({type:"HTML_DISTANCE",matched:!1,reason:`Error finding closest HTML node by string distance: ${s}`})}let l=t.screenshotUrl,c=t.role??"";if(l&&Wp.includes(c))try{let s=await this.resolveTargetWithTemplateMatching({root:e,oldTarget:t,screenshotUrl:l,signal:i,allowNotActionableNodesOverride:a});return{...s,decisions:[...n,...s.decisions],pageState:void 0}}catch(s){i?.throwIfAborted(),n.push({type:"TEMPLATE_MATCHING",matched:!1,reason:`Error finding closest element using saved screenshot: ${s}`,elementImageUrl:l}),o.warn({err:s},"Did not find any close element using saved screenshot")}}async resolveTargetWithTemplateMatching({screenshotUrl:e,oldTarget:t,signal:n,allowNotActionableNodesOverride:o}){let i;if(!this.enricher)throw new Error("Enricher not available for screenshot resolution");let a=await this.screenshot({retries:0}),c=await(await fetch(e)).arrayBuffer(),s=lU(),u=await this.enricher.runTemplateMatching({id:s,searchImageBase64String:Buffer.from(c).toString("base64"),pageImageBase64String:a.toString("base64")},{signal:n}),{target:d,locator:p}=await this.getTargetFromPositionPercentages({percentX:u.x,percentY:u.y,allowNotActionableNodesOverride:o}),m=d.boundingBox?.width,g=d.boundingBox?.height;if(!m||!g)throw i="Rejecting target from screenshot due to no bounding box",new Error(i);let h=d.id,f=this.stateManager.a11yIdToNodeMap[h],b=oi(t);await this.updateCacheWithNewNodeDetails({target:t,node:f,locator:p,allowNotActionableNodesOverride:o});let E=Cm(b,t);return E&&Object.keys(E).length>0&&(t.cacheResolutionUpdateTime=new Date().toISOString(),t.cacheResolutionUpdateLoggerTags=pe(this.logger),t.cacheResolutionUpdateSource="TEMPLATE_MATCHING",this.logger.info({id:s,diffs:E,templateMatch:u},"Updated cache after template matching resolution")),{locator:p,a11yNode:f,displayString:d.nodeOnlySerializedHtml??"",decisions:[{type:"TEMPLATE_MATCHING",matched:!0,reason:"Found element using screenshot",elementImageUrl:e}]}}async typeIntoTarget(e,t,n={}){await this.highlight(t.locator);let o=await t.locator.getAttribute("type",{timeout:Z})??"",i=SA.some(a=>a===o.toLowerCase());return await mm({targetingResult:t,options:{force:n.force,relativePosition:n.relativePosition},logger:this.logger,retryTimeoutMs:this.smartWaitingTimeout,position:i?{x:1,y:1}:void 0,actionSource:"type",browserCallbacks:this.getBrowserCallbacks()}),await this.page.waitForTimeout(150),this.directTypeHelper(e,n)}async click(e,t,n={}){return mm({targetingResult:e,options:n,logger:this.logger,actionSource:"click",retryTimeoutMs:this.smartWaitingTimeout,controllerCallbacks:t,browserCallbacks:this.getBrowserCallbacks()})}async waitForUrl({beforeUrl:e,matcher:t},n){let o=n?.timeout??this.pageLoadTimeout,i=Date.now(),a=!1,l=e;for(;Date.now()-i<o;){if(this.abortSignal?.throwIfAborted(),l=this.url(),rc(l,t,n)){a=!0;break}await X(it,this.abortSignal)}if(!a)throw new w("ActionFailureError",`The active page URL ${n?.negated?"still does":"does not"} ${ev(t)} in ${o}ms.
|
|
4029
|
+
Current tab: ${l}`);try{await this.loadFrameAndRecordUrl({root:this.page,signal:this.abortSignal,codePath:"wait-for-url-step"})}catch(c){this.logger.warn({err:c},"Failed waiting for page load after URL change, continuing...")}}async dragAndDrop(e,t,n={}){await this.hover({locator:e}),await this.page.mouse.down();let o=await t.boundingBox({timeout:J});if(!o)throw new w("ActionFailureError","Could not get bounding box of target element");let i=o.x+o.width/2,a=o.y+o.height/2,l=n.steps??5;await this.page.mouse.move(i,a,{steps:l}),await X(n.hoverSeconds?Math.min(n.hoverSeconds*1e3,me):500),await this.page.mouse.up()}async mouseDrag(e,t,n,o){o&&await this.hover({locator:o});let i=await(await this.getActivePageOrFrame()).evaluate(nm);i||(this.logger.warn("Could not get current mouse position before mouse drag action, defaulting to 0,0"),i={left:0,top:0}),await this.page.mouse.down(),await this.page.mouse.move(e+i.left,t+i.top,{steps:n}),await X(ei),await this.page.mouse.up()}async hover(e){await this.highlight(e.locator),await to({func:async t=>{await this.scrollIntoViewIfNeeded(t.locator);let n=await t.locator.boundingBox({timeout:J});if(!n)throw new Error("Attempted to hover over element with no bounding box");await this.page.mouse.move(n.x+n.width/2,n.y+n.height/2,{steps:3})},action:"hovering over element",logger:this.logger,retryTimeoutMs:this.smartWaitingTimeout,targetingResult:e,callbacks:this.getBrowserCallbacks()})}async focus(e){await this.highlight(e.locator),await to({func:t=>t.locator.focus({timeout:me}),action:"focusing element",logger:this.logger,retryTimeoutMs:this.smartWaitingTimeout,callbacks:this.getBrowserCallbacks(),targetingResult:e})}async blur(e){if(!e){let t=await this.getActivePageOrFrame();await Qe({fn:()=>{let n=document.activeElement;n&&n.nodeType===1&&n.blur()},root:t,arg:void 0,waitForPageLoad:()=>this.waitForPageLoad(),timeout:Z,codePath:"blurring the active element"});return}await this.highlight(e.locator),await to({func:t=>t.locator.blur({timeout:me}),action:"blurring element",logger:this.logger,retryTimeoutMs:this.smartWaitingTimeout,callbacks:this.getBrowserCallbacks(),targetingResult:e})}async selectOption(e,t,n=!1){await this.highlight(e.locator),await to({action:"selecting option from dropdown",logger:this.logger,retryTimeoutMs:this.smartWaitingTimeout,callbacks:this.getBrowserCallbacks(),func:async o=>{if(t.type==="INDEX"){let i=Number(t.index);if(isNaN(i))throw new w("UserConfigurationError",`Page index ${t.index} is not a number`)}await o.locator.selectOption({value:t.type==="VALUE"?t.value:void 0,label:t.type==="LABEL"?t.label:void 0,index:t.type==="INDEX"?Number(t.index):void 0},{force:n,timeout:J})},targetingResult:e})}async press(e,t){let n=t.repeat??1;if(t.convertMeta){let o=dc(e,this.properties.isAndroid);o!==e&&(this.logger.info({key:e,convertedKey:o},"Converted platform dependent keys"),e=o)}for(let o=0;o<n;o++)await this.page.keyboard.press(e,{delay:t.delayMs??0})}async keyDown(e,t){if(t.convertMeta){let n=dc(e,this.properties.isAndroid);n!==e&&(this.logger.info({keyString:e,convertedKey:n},"Converted platform dependent keys"),e=n)}for(let n of wm(e))await this.page.keyboard.down(n)}async keyUp(e,t){if(t.convertMeta){let n=dc(e,this.properties.isAndroid);n!==e&&(this.logger.info({keyString:e,convertedKey:n},"Converted platform dependent keys"),e=n)}for(let n of wm(e))await this.page.keyboard.up(n)}async refresh(e){let t=e?.loadTimeoutMs??this.pageLoadTimeout;await this.waitForPageLoad();let n=0,o=2;for(;n<o;){n++;try{await this.page.reload({waitUntil:"domcontentloaded",timeout:t});break}catch(i){this.logger.warn({err:i,attempt:n},`Failed to reload page${n<o?", retrying...":", continuing..."}`)}}await this.loadFrameAndRecordUrl({root:this.page,signal:this.abortSignal,codePath:"reload-step"}),await this.waitForDOMStability()}async getBrowserState(e){let{maxAttempts:t=2,logger:n=this.logger,skipWaitForPageLoad:o,allowNotActionableNodesOverride:i,shouldLogOnFailure:a}=e,l=e.abortSignal??this.abortSignal,c=!i,s=i?!0:this.userControlledBrowserSettings.showZeroOpacityElements,u=a?n:un;o||await this.waitForPageLoad(),e.skipWait||await this.waitForDOMStability({logger:n,signal:l});let d=0,p;for(;d<t;){d++;try{return await B(this.stateManager.getA11yTree({devicePixelRatio:this.devicePixelRatio,abortSignal:l,logger:n,filterByViewport:e.filterByViewport,showZeroOpacityElements:s,flagNotActionableNodes:c}),{milliseconds:this.pageLoadTimeout*d,signal:l,message:"Getting browser state took too long"})}catch(m){if(l?.throwIfAborted(),p=m instanceof Error?m.message:`${m}`,d>=t)throw m;u.warn({err:m,url:this.url()},"Error getting a11y tree, retrying...")}}throw new w("ActionFailureError",`Getting page content failed after ${t} attempts. Error: ${p}`)}async getViewportOffsetDetails(e){let[t,n,o,i,a]=await Qe({root:e,fn:()=>[window.scrollY,window.scrollX,window.screen.width,window.screen.height,window.devicePixelRatio],arg:void 0,timeout:J,waitForPageLoad:async()=>{},codePath:"getting current viewport details"});return{upperBound:t,lowerBound:t+i,leftBound:n,rightBound:n+o,width:o,height:i,devicePixelRatio:this.properties.systemDevicePixelRatio??a}}async waitForDOMStability(e){let{logger:t=this.logger,timeout:n=this.smartWaitingTimeout,signal:o}=e??{},i={value:Date.now()},a=p=>{i.value=Date.now()},l=()=>a("DOM.documentUpdated");this.cdpClient.addListener("DOM.documentUpdated",l);let c=()=>a("Page.frameDetached");this.cdpClient.addListener("Page.frameDetached",()=>c);let s=()=>a("Page.frameStartedLoading");this.cdpClient.addListener("Page.frameStartedLoading",s);let u=()=>a("Page.navigatedWithinDocument");this.cdpClient.addListener("Page.navigatedWithinDocument",u);let d=()=>a("frameRequestedNavListener");this.cdpClient.addListener("Page.frameRequestedNavigation",d);try{await this.waitForDOMStabilityHelper(i,t,n,o)}finally{this.cdpClient.removeListener("DOM.documentUpdated",l),this.cdpClient.removeListener("Page.frameDetached",c),this.cdpClient.removeListener("Page.frameStartedLoading",s),this.cdpClient.removeListener("Page.navigatedWithinDocument",u),this.cdpClient.removeListener("Page.frameRequestedNavigation",d)}}async waitForDOMStabilityHelper(e,t,n,o){let i=!1,a=Date.now(),l,c={quality:25,retries:0,stabilizeBeforeScreenshot:!0},s=!1,u=0;for(;Date.now()-a<n;){if(o?.throwIfAborted(),await X(ei,this.abortSignal),l)try{let d=await this.screenshot(c);if(!d.equals(l)){l=d,s=!1;continue}s=!0}catch(d){u++,u%3===0&&t.warn({err:d,screenshotErrors:u},"Failed to take screenshot for DOM stability check"),o?.throwIfAborted()}else try{l=await this.screenshot(c)}catch(d){u++,u%3===0&&t.warn({err:d,screenshotErrors:u},"Failed to take screenshot for DOM stability check"),o?.throwIfAborted()}if(!(Date.now()-e.value<Vv)){i=!0;break}}i||t.warn({duration:Date.now()-a,stable:{a11y:i,screenshot:s}},"A11y wait phase completed due to timeout, continuing...")}async clickUsingVisualCoordinates(e,t){let{x:n,y:o}=e;this.logger.debug({x:n,y:o},"Executing mouse click with visual coordinates"),await this.waitForPageLoad(),await this.page.mouse.click(n,o,{button:t.rightClick?"right":"left",clickCount:t.doubleClick?2:1})}async dragAndDropUsingVisualCoordinates(e,t,n){await this.page.mouse.move(e.x,e.y,{steps:3}),await this.page.mouse.down(),await this.page.mouse.move(t.x,t.y,{steps:3}),await X(n.hoverSeconds?Math.min(n.hoverSeconds*1e3,Vp):500),await this.page.mouse.up()}async hoverUsingVisualCoordinates(e){await this.page.mouse.move(e.x,e.y)}async mouseDragUsingVisualCoordinates(e,t,n,o){await this.hoverUsingVisualCoordinates(o);let i=await(await this.getActivePageOrFrame()).evaluate(nm);i||(this.logger.warn("Could not get current mouse position before mouse drag action, defaulting to 0,0"),i={left:0,top:0}),await this.page.mouse.down(),await this.page.mouse.move(e+i.left,t+i.top,{steps:n}),await X(ei),await this.page.mouse.up()}async getElementLocation(e){let t=await this.cdpClient.send({method:"DOMSnapshot.captureSnapshot",params:{computedStyles:[],includeDOMRects:!0,includePaintOrder:!0},timeout:J}),n=await B(this.page.evaluate(()=>window.devicePixelRatio),{milliseconds:me});process.platform==="darwin"&&n===1&&(n=Hv);let o=t.documents[0],i=o.layout,a=o.nodes,l=a.nodeName||[],c=a.backendNodeId||[],s=i.nodeIndex,u=i.bounds,d=-1;for(let E=0;E<l.length;E++)if(c[E]===e){d=s.indexOf(E);break}if(d===-1)throw new Error(`Could not find any backend node with ID ${e}`);let[p=0,m=0,g=0,h=0]=u[d];p/=n,m/=n,g/=n,h/=n;let f=p+g/2,b=m+h/2;return{centerX:f,centerY:b}}async scrollVertical(e){return gm({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 gm({frame:this.stateManager.frameConfig?await this.getActivePageOrFrame():null,page:this.page,deltaX:e?Math.abs(e):null,directionX:e&&e>0?"right":"left",deltaY:0,directionY:null,signal:this.abortSignal,callbacks:this.getBrowserCallbacks(),logger:this.logger})}async goForward(){await this.waitForPageLoad(),await this.page.goForward({waitUntil:"domcontentloaded",timeout:this.pageLoadTimeout}),await this.loadFrameAndRecordUrl({root:this.page,signal:this.abortSignal,codePath:"go-forward"})}async goBack(){await this.waitForPageLoad(),await this.page.goBack({waitUntil:"domcontentloaded",timeout:this.pageLoadTimeout}),await this.loadFrameAndRecordUrl({root:this.page,signal:this.abortSignal,codePath:"go-back"})}async reinitializeCDPClient(e){await this.cdpClient.reinitialize(e),await this.initializeScreencast()}async stopScreencast(){if(this.clientCallbacks?.onScreencastFrame)try{await this.cdpClient.send({method:"Page.stopScreencast",params:{}})}catch{}}async changeActivePage(e,t){await this.stopScreencast(),this.recordUrlVisited(e.url()),this.page=e,await this.reinitializeCDPClient(t??this.pageLoadTimeout)}async createNewTab(e,t){let n=await this.context.newPage();await this.changeActivePage(n,t?.loadTimeoutMs),await this.navigate({url:e,initialNavigation:!0,...t}),this.handleAvailableTabsChange()}async switchToPage(e,t){let n=!0,o,i=Date.now();for(;n||t?.retry&&Date.now()-i<this.smartWaitingTimeout;){n=!1;try{await this.switchToPageHelper(e,t);return}catch(a){this.logger.warn({err:a},"Error switching to page, retrying..."),o=a,await X(it)}}throw o}async switchToPageHelper(e,t){let n=this.context.pages().map((i,a)=>({page:i,url:i.url(),index:a})),o;if(e.type==="INDEX"){let i=Number(e.index);if(isNaN(i))throw new w("UserConfigurationError",`Page index ${e.index} is not a number`);if(i<0||i>=n.length)throw new Error(`Page index ${e.index} exceeds the number of available pages: ${JSON.stringify(n.map(a=>a.url))}`);o=n[i]}else{let i=n.filter(a=>e.type==="SUBSTRING"?a.url.includes(e.substring):a.url.match(e.pattern));i.length>1&&this.logger.warn(`More than one page matches the page switch criteria: ${JSON.stringify(i.map(a=>a.url))}`),o=i[i.length-1]}if(!o)throw new Error(`Could not find matching page using criteria: ${JSON.stringify(e)}.
|
|
4030
|
+
Available pages:${JSON.stringify(n.map(i=>i.url))}`);if(!Qn(o.url,this.logger)){this.logger.error(`Refusing to switch to page with invalid URL: ${o.url}`);return}this.logger.info(`Switching to tab ${o.index} with url ${o.url}`),await this.changeActivePage(o.page,t?.loadTimeoutMs),await this.loadFrameAndRecordUrl({root:o.page,signal:this.abortSignal,codePath:"switch-to-tab-step"}),this.handleAvailableTabsChange()}async setCookie(e){let t;return typeof e=="string"?t=_s(e):t=[e],await this.context.addCookies(t),t}async setLocalStorage(e,t){let n;for(let o=0;o<2;o++)try{await this.evaluateFunctionInPage(([i,a])=>{i&&localStorage.setItem(i,a||"")},[e,t],`setting local storage key ${e}`);return}catch(i){n=i}if(n)throw n}async solveCaptcha(){await this.getBrowserState({allowNotActionableNodesOverride:!0});let e;for(let l of Object.values(this.stateManager.a11yIdToNodeMap))if(l.role==="image"&&l.name.toLowerCase().includes("captcha")){if(!l.backendNodeId)continue;e=await this.stateManager.getLocatorFromBackendId(this.page,l.backendNodeId);break}if(!e){let l=await(await this.getActivePageOrFrame()).solveRecaptchas();if(!l.captchas||!l.captchas.length)throw new Error("No captchas found on the page");return}let t=await e.screenshot({type:"jpeg",animations:"allow",caret:"hide",quality:100,timeout:J}),n=await fetch("https://api.2captcha.com/createTask",{method:"POST",body:JSON.stringify({clientKey:ti,task:{type:"ImageToTextTask",body:t.toString("base64"),case:!0},languagePool:"en"})});if(!n.ok){let l=`Captcha solver API returned error response: ${n.statusText}`;throw this.logger.error({text:await n.text()},l),new Error(l)}let{taskId:o}=await n.json(),i=Date.now(),a="";for(;Date.now()-i<Wv;){await X(2500);let l=await fetch("https://api.2captcha.com/getTaskResult",{method:"POST",body:JSON.stringify({clientKey:ti,taskId:o})});if(!l.ok){let s=`Captcha solution API returned error response: ${l.statusText}`;throw this.logger.error({text:await l.text()},s),new Error(s)}let c=await l.json();if(c.errorId){let s=`Captcha solution API returned error ID ${c.errorId}`;throw this.logger.error(s),new Error(s)}if(c.status==="ready"){a=c.solution.text;break}}if(!a)throw new Error("Captcha solution timed out");return a}getActiveFrameConfig(){return this.stateManager.frameConfig}async exposeRecordingBindings(){try{await B(this.exposeRecordingBindingsHelper(),{milliseconds:this.pageLoadTimeout})}catch(e){e instanceof Error&&e.message.includes("already registered")||this.logger.error({err:e},"Failed to install Momentic libraries for action recording")}}async exposeRecordingBindingsHelper(){await this.context.exposeBinding("isRecordingActive",()=>this.transformer!==void 0,{handle:!1}),await this.context.exposeBinding("captureTargetedEvent",({frame:e},t)=>{this.transformer&&YA({event:t,frame:e,transformer:this.transformer,enricher:this.enricher,lastScreenshotForRecording:this.lastScreenshotForRecording?.toString("base64"),logger:this.logger})},{handle:!1}),await this.context.exposeBinding("captureKeystroke",async(e,t)=>{this.transformer&&this.transformer.recordKeystroke(t)})}async startRecordingCrons(e){if(e.aborted)return;let t,n=(await this.getOpenPages()).map(c=>c.url),o=0,i=!1,a=async()=>{if(e.aborted||o>8){clearTimeout(t);return}i=!0;let c;try{c=(await this.getOpenPages()).map(u=>u.url),o=0}catch(u){this.logger.debug({err:u},"Failed getting new open pages during recording tab switch cron, skipping..."),o++;return}let s=this.url();for(let u=c.length-1;u>=n.length;u--){let d=c[u];Qn(d,this.logger)&&d!==s&&this.logger.info({lastActivePages:n,currentUrl:s,newOpenPages:c},"Auto-following new tab during recording"),await this.switchToPage({type:"INDEX",index:String(u)});break}n=c};t=setInterval(async()=>{if(!i){i=!0;try{await a()}catch(c){this.logger.error({err:c},"Error while checking pages during recording")}finally{i=!1}}},it);let l=async()=>{clearInterval(t)};e.addEventListener("abort",l,{once:!0})}async startRecording(e,t,n){this.logger.debug({isClickToRecord:n},"Starting recording mode in Chrome browser"),await this.startRecordingCrons(e),await this.page.evaluate(i=>{let a=window;a._MOMENTIC_RECORDING_ACTIVE=!0,a._MOMENTIC_CLICK_RECORD_ACTIVE=i},n),this.transformer=t,await this.injectKnowledgeBaseIntoBrowser(this.page);let o=async()=>{this.transformer=void 0,this.lastScreenshotForRecording=void 0;try{await this.page.evaluate(()=>{let i=window;i._MOMENTIC_RECORDING_ACTIVE=!1,i._MOMENTIC_CLICK_RECORD_ACTIVE=!1})}catch{}};e.addEventListener("abort",o,{once:!0})}async getSelectOptions(e){return await e.evaluate(n=>Array.from(n.querySelectorAll("option")).map(i=>({value:i.value,label:i.label})),void 0,{timeout:Z})}getActivePage(){return this.page}async getActivePageOrFrame(){let e=await this.stateManager.resolveActiveFrameConfig({});return e?(await this.loadFrameAndRecordUrl({root:e.frame,signal:this.abortSignal,codePath:"get-active-frame-locator"}),e.frame):this.page}async loadFrameAndRecordUrl({root:e,signal:t,codePath:n}){let o=this.pageLoadTimeout,i=e.url();if(!i.includes("chrome-error://")){try{await La({promiseGenerator:async()=>e.waitForLoadState("domcontentloaded",{timeout:o}),signal:t,codePath:`loadFrameAndRecordUrlDomContentLoad-${n}`,logger:this.logger,timeoutMs:this.pageLoadTimeout})}catch(a){let l=a;if(l.name==="AbortError")throw new w("UserInfrastructureError",`The page with URL ${_t(i,50)} did not load within the configured timeout (${o}ms): ${l}`);if(!l.message.includes("detached"))throw l}try{await La({promiseGenerator:async()=>e.waitForLoadState("load",{timeout:o}),signal:t,codePath:`loadFrameAndRecordUrlPageLoad-${n}`,logger:this.logger,timeoutMs:this.pageLoadTimeout})}catch(a){this.logger.warn({err:a,codePath:n,url:i},"Failed waiting for current frame to load, continuing...")}this.recordUrlVisited(e.url())}}async getCondensedHtml(e){let{skipWait:t=!1}=e??{};return t||(await this.waitForPageLoad(),await this.waitForDOMStability()),this.getCondensedHtmlHelper()}async getCondensedHtmlHelper(){let e=await this.getRawCondensedHtml();return rU.html(e,{indent_size:1,indent_with_tabs:!1,preserve_newlines:!1})}async getRawCondensedHtml(){let e=await this.getActivePageOrFrame();await this.ensureMomenticBrowserScriptsLoaded(e,this.logger,this.abortSignal);let{result:t,error:n}=await Qe({fn:()=>window.getCondensedHtmlTree(),root:e,arg:void 0,timeout:me,waitForPageLoad:()=>this.waitForPageLoad(),codePath:"getting condensed HTML tree"});if(n)throw new Error(`Failed to process page HTML: ${n}`);if(!t)throw new w("InternalWebAgentError","Got empty HTML tree - are you sure the page is fully loaded?");return t}registerDialogHandler(e){let t=async n=>{try{e==="ACCEPT"?await n.accept():await n.dismiss()}catch(o){this.logger.warn({err:o},"Failed to handle dialog")}};this.page.once("dialog",t)}async evaluateFunctionInAllFrames(e,t){return this.stateManager.executeFunctionInAllFrames(e,t)}async evaluateFunctionInPage(e,t,n,o=me){let i=await this.getActivePageOrFrame();return Qe({root:i,fn:e,arg:t,timeout:o,waitForPageLoad:()=>this.waitForPageLoad(),codePath:n})}async evaluateCodeInPage({code:e,fragment:t,context:n,timeoutMs:o=an}){let i=aA(),a={code:e,fragment:t,context:n},{result:l}=await B(this.page.evaluate(i,a),{milliseconds:o,fallback:()=>{throw this.abortSignal?.throwIfAborted(),new w("ActionFailureError",`Code evaluation in browser exceeded the allowed timeout of ${o/1e3} seconds`)},signal:this.abortSignal});return l}async getDomNodeFromPixelPosition(e,t){await this.cdpClient.send({method:"DOM.getDocument",params:{depth:0},timeout:me});let n;try{n=await this.cdpClient.send({method:"DOM.getNodeForLocation",params:{x:e,y:t},timeout:Z})}catch(o){throw this.logger.error({err:o,x:e,y:t},"Failed to get DOM node from position percents"),new Error("No element was found at the given location")}return n}async getDomNodeFromPositionPercentages(e,{percentX:t,percentY:n}){if(t<0||t>1||n<0||n>1)throw new w("UserConfigurationError","Invalid percent passed to percentage location");let{width:o,height:i,upperBound:a,leftBound:l}=await this.getViewportOffsetDetails(e),c=Math.round(a),s=Math.round(l),u=Math.ceil(o*t),d=Math.ceil(i*n),p=u+s,m=d+c;return this.getDomNodeFromPixelPosition(p,m)}async highlightFromPositionPercentages(e){let t=await this.getActivePageOrFrame(),n;try{n=await this.getDomNodeFromPositionPercentages(t,e)}catch{}return n?(await this.cdpClient.send({method:"Overlay.highlightNode",timeout:Z,params:{highlightConfig:RA,backendNodeId:n.backendNodeId}}),async()=>{try{await this.cdpClient.send({timeout:Z,method:"Overlay.hideHighlight",params:{backendNodeId:n?.backendNodeId}})}catch{}}):async()=>{}}async clearAllCdpHighlights(){try{await this.cdpClient.send({method:"Overlay.hideHighlight",params:void 0,timeout:Z})}catch{}}async getTargetFromPositionPercentages(e){let t=await this.getActivePageOrFrame(),n=await this.getDomNodeFromPositionPercentages(t,e);return this.getTargetFromBackendNodeId({root:t,backendNodeId:n.backendNodeId,allowNotActionableNodesOverride:e.allowNotActionableNodesOverride})}async getTargetFromBackendNodeId({root:e,backendNodeId:t,allowNotActionableNodesOverride:n}){let o=this.stateManager.domGraph?.backendIdToNode[t];if(!o)throw new Error("No DOM node was found with the given backend ID");let i=o?.attributes[Vr],a=parseInt(i??"");if(!i||isNaN(a))throw new Error("No data-momentic-id was found on the DOM node");let l=e.locator(hr(a)),c;o.bounds.x!==null&&o.bounds.y!==null&&(c={x:o.bounds.x,y:o.bounds.y,width:o.bounds.width??0,height:o.bounds.height??0});let s=await this.fetchHtmlAttributes({locator:l,logger:this.logger,startingBoundingBox:c,allowNotActionableNodesOverride:n}),u={id:-1,dataMomenticId:a,targetSource:"XY_PERCENT",targetUpdateTime:new Date().toUTCString(),...s};return this.logger.debug({target:u},"Tied backend ID to HTML node"),{target:u,locator:l}}async performTargetRedirection(e,t,n){try{return await this.scrollIntoViewIfNeeded(e),await B(this.performTargetRedirectionHelper(e,t,n),{milliseconds:J})??{locator:e}}catch(o){return t.warn({err:o},"Error performing target redirection, using original element"),{locator:e}}}async performTargetRedirectionHelper(e,t,n){let o=Date.now(),i=await jr(e,t);if(n===void 0&&(n=await e.boundingBox({timeout:J})??void 0),!n){t.error(`Attempted to click on element with no bounding box: ${i}`);return}let{x:a,y:l,width:c,height:s}=n,u=this.getViewport();if(a<0||l<0||!u||a+c>u.width||l+s>u.height){t.info("Skipping locator redirection because the element is outside the viewport");return}let d=await this.getActivePageOrFrame(),{dataMomenticId:p,mPathSelector:m,error:g,serializedElement:h,foundElementRelativePoint:f,force:b,logs:E}=await e.evaluate(R=>{let T=window;if(!T.performTargetRedirection)throw new Error("performTargetRedirection script is not defined");return T.performTargetRedirection(R)},void 0,{timeout:Z}),v=Date.now()-o;if(g){t.warn({error:g,serializedElement:h,duration:v,force:b,logs:E},"Got error from target redirection with bounding box");return}else{if(p)return t.info({newDataMomenticId:p,serializedElement:h,duration:v,force:b,logs:E},"Redirected target to new element with bounding box with data-momentic-id"),{locator:d.locator(hr(p)),hints:{relativeXYToLocator:f,force:b}};if(m)return t.info({newMPathSelector:m,serializedElement:h,duration:v,force:b,logs:E},"Redirected target to new element with bounding box with mPath"),{locator:d.locator(m),hints:{relativeXYToLocator:f,force:b}};if(f)return t.info({foundElementRelativePoint:f,serializedElement:h,duration:v,force:b,logs:E},"Chose specific visible point on original element"),{locator:e,hints:{relativeXYToLocator:f,force:b}};if(b)return t.info({serializedElement:h,duration:v,force:b,logs:E},"Forcing click on original element"),{locator:e,hints:{force:b}}}}async fetchHtmlAttributes({locator:e,logger:t=this.logger,startingBoundingBox:n,allowNotActionableNodesOverride:o}){let{hybridSelectorMode:i,showZeroOpacityElements:a}=this.userControlledBrowserSettings,l=await e.evaluate((c,s)=>{let u=window;return u.generateHtmlCacheAttributes?u.generateHtmlCacheAttributes(c,s):{warnings:[],error:"generateHtmlCacheAttributes is not defined"}},{generateHybridSelector:i==="test"||i==="prefer",startingBoundingBox:n,showZeroOpacityElements:o?!0:a},{timeout:me});if("error"in l&&l.error)throw l.error.startsWith(Fv)?new hs(l.error):l.error.startsWith(Bv)?new fs(l.error):new Error(l.error);return l.warnings.length&&t.warn(l,"Got warnings while generating HTML attributes for target"),l.attributes}async moveMouseFromPositionPercentages(e,t){let n=this.getViewport();if(!n)throw new Error("Cannot move mouse using percentages without viewport");let o=Math.ceil(n.width*e),i=Math.ceil(n.height*t);return await this.cdpClient.send({method:"Input.dispatchMouseEvent",params:{type:"mouseMoved",x:o,y:i,button:"left",clickCount:0}}),{x:o,y:i}}async clickMouseFromPositionPercentages(e,t,n){let o=this.getViewport();if(!o)throw new Error("Cannot click mouse using percentages without viewport");let i=Math.ceil(o.width*t),a=Math.ceil(o.height*n);await this.cdpClient.send({method:"Input.dispatchMouseEvent",params:{type:e==="down"?"mousePressed":"mouseReleased",x:i,y:a,button:"left",clickCount:e==="down"?1:0},timeout:Z})}async scrollFromPositionPercentages(e,t,n,o){let i=this.getViewport();if(!i)throw new Error("Cannot scroll using percentages without viewport");let a=Math.ceil(i.width*e),l=Math.ceil(i.height*t);return await this.cdpClient.send({method:"Input.dispatchMouseEvent",params:{type:"mouseWheel",deltaX:a,deltaY:l,x:n,y:o}}),{deltaX:a,deltaY:l}}canSolveCaptchas(){return!!ti}async getAllFrameUrls(){return await this.stateManager.getAllChildFrameUrls()}async setFileChooserHandler(e){setTimeout(()=>{try{e.cleanup()}catch(t){this.logger.debug({err:t,filePath:e.filePath},"Failed cleaning up file after upload")}},3e4),await this.setFileChooserHandlerHelper(e)}logToUserConsole(e,t,n,...o){let i=this.context.pages().indexOf(e);i=i===-1?0:i,tm(e,this.debugData,i,{type:t,text:`[MOMENTIC] ${n}`,args:o})}async setFileChooserHandlerHelper({filePath:e,filename:t}){if(!fc(e)){let c=`File chooser triggered after the source file ${e} has been cleaned up, ignoring...`;this.logger.error(c),this.logToUserConsole(this.page,"error",c);return}let n=t?.trim()||iU(e),o=Qk(e),i=aU(e),a=md[i];this.page.once("filechooser",async c=>{this.logger.info({filePath:e,fileName:n},"File chooser triggered");try{if(!fc(e))throw new Error(`File chooser triggered after the source file ${e} has been cleaned up, ignoring...`);await c.setFiles({name:n,buffer:o,mimeType:nU.getType(e)||"application/octet-stream"},{timeout:Vp})}catch(s){this.logger.error({err:s},"Error handling file chooser"),this.logToUserConsole(this.page,"error",s.message)}});let l=o.toString("base64");await this.evaluateFunctionInPage(({fileName:c,base64Data:s,mimeType:u})=>{let d=window;d.momenticFileName=c,d.momenticFileBase64=s;let p=atob(s),m=new Array(p.length);for(let h=0;h<p.length;h++)m[h]=p.charCodeAt(h);let g=new Uint8Array(m);d.MomenticFile=class extends Blob{kind="file";name=d.momenticFileName;constructor(){super([g],{type:u})}isSameEntry(h){return h.name===this.name}queryPermission(h){return console.info("[MOMENTIC] MomenticFile.queryPermission called"),Promise.resolve("granted")}remove(){return console.info("[MOMENTIC] MomenticFile.remove called"),Promise.resolve()}async requestPermission(h){return console.info("[MOMENTIC] MomenticFile.requestPermission called"),Promise.resolve("granted")}async getFile(){console.info("[MOMENTIC] MomenticFile.getFile called");let h=new Blob([g]);return new File([h],d.momenticFileName,{type:u})}async createSyncAccessHandle(){throw console.error("[MOMENTIC] Not implemented"),new Error("Not implemented")}async createWritable(){throw console.error("[MOMENTIC] Not implemented"),new Error("Not implemented")}},d.showOpenFilePicker=async()=>(console.info("[MOMENTIC] showOpenFilePicker called"),[new d.MomenticFile])},{fileName:n,base64Data:l,mimeType:a},"set-file-chooser-handler",5e3)}getSerializedFormFromA11yId(e){return this.stateManager.a11yIdToNodeMap[e]?.getNodeOnlySerializedForm()}retrieveAndClearDebugData(){this.cdpClient.loadEventLogs.length>0&&(this.cdpClient.loadEventLogs=[]);let t={...this.debugData};return this.debugData={logsPerPage:[],harPages:{},harEntries:{}},t}async copy(e){try{await this.evaluateFunctionInPage(t=>navigator.clipboard.writeText(t),e,"copying text to clipboard")}catch(t){if(t instanceof Error&&t.message.includes("Document is not focused")){await this.evaluateFunctionInPage(()=>{document.activeElement||document.body.focus()},void 0,"focusing on body element before copying to clipboard"),await this.press("Tab",{}),await this.press("Shift+Tab",{}),await this.evaluateFunctionInPage(n=>navigator.clipboard.writeText(n),e,"copying text to clipboard");return}throw t}}async paste(){await this.waitForPageLoad(),await this.press("Meta+V",{convertMeta:!0})}async registerRequestListener(e){return this.page.waitForResponse(t=>{let n=t.request();return e.matches({url:n.url(),method:n.method()})})}registerRequestRecorder(e,t,n){this.requestRecorders[e]={onRequestStart:(o,i)=>{t.matches({url:i.request.url,method:i.request.method})&&n.onRequestStart(o,i)},onRequestComplete:(o,i)=>{t.matches({url:i.request.url,method:i.request.method})&&n.onRequestComplete(o,i)}}}removeRequestRecorder(e){delete this.requestRecorders[e]}setHeader(e,t,n){this.customHeaders.push({key:e.toLowerCase(),value:t,matcher:n})}registerMock(e,t,n,o){let i=e??Rm();return this.mocks[i]={matcher:t,generateResponse:n,fetchOriginalResponse:o},i}removeMock(e){if(!e){this.mocks={};return}delete this.mocks[e]}async setOfflineMode(e){await this.context.setOffline(e)}get smartWaitingTimeout(){return this.userControlledBrowserSettings.smartWaitingTimeoutMs??Gv}get userBrowserSettings(){return oi(this.userControlledBrowserSettings)}get pageLoadTimeout(){return this.userControlledBrowserSettings.pageLoadTimeoutMs??Hp}get isInPageLoad(){return Object.values(this.pageLoadPromises).length>0}get devicePixelRatio(){return this.properties.systemDevicePixelRatio??1}get browserCrashDumpDir(){let e=cc();for(let t of e)if(!(!fc(t)||!XA(t).isDirectory()||!["new","pending","completed"].some(o=>{let i=sU(t,o);return fc(i)&&XA(i).isDirectory()&&eU(i).length>0})))return t}};import LU from"fetch-cookie";import{cloneDeep as Tw}from"lodash-es";import{CookieJar as NU}from"tough-cookie";async function Dr({frameConfig:r,action:e,browser:t}){let n=t.getActiveFrameConfig();r?t.setActiveFrameConfig(r):n?.type==="auto"&&t.setActiveFrameConfig(void 0);try{return await e()}finally{t.setActiveFrameConfig(n)}}var cU=["NAVIGATE","NEW_TAB","TAB","REFRESH","WAIT_FOR_URL"];async function QA({beforeUrl:r,beforePages:e,browser:t,command:n,logger:o}){if(cU.includes(n.type))return;let l=("cache"in n&&n.cache&&"target"in n.cache?n.cache.target:void 0)?.nodeOnlySerializedHtml?.includes("<a")??!1?300:3e3,c=Date.now(),s=0;for(;s===0||Date.now()-c<l;){await X(250),s++;let u=(await t.getOpenPages()).map(p=>p.url),d=t.url();if(u.length!==e.length)for(let p=u.length-1;p>=e.length;p--){let m=u[p];if(Qn(m,o)&&m!==r&&m!==d){o.info({beforePages:e,afterPages:u,beforeUrl:r},"Auto-following new tab after preset action"),await t.switchToPage({type:"INDEX",index:String(p)});break}}}}async function vn(r,e={}){let t=await r.getBrowserState(e);return{serializedTree:t.serialize(e.serializationOpts),tree:t}}import{randomUUID as hU}from"crypto";var tw={minChunkTokenCount:500,acceptableChunkTokenCount:3e3,maxChunkTokenCount:8e3,maxLineLength:4e3},rw={minChunkTokenCount:5e3,acceptableChunkTokenCount:1e4,maxChunkTokenCount:3e4,maxLineLength:500},ew=/<(\S+) id="(\d+)".*?>/g,uU=/(<\/(\S+)>)|(<(\S+).*?\/>)/g,nw=["h1","h2","section","footer","nav","aside","form","label","dialog"],dU=[...nw,"span","div","h3"],pU=["table","select","form","ul","ol","menu","pre","code","dialog"],mU=["table","form","dialog","nav","section","ul","select"];function Sc(r){return gU(r)}function gU({logger:r,serializedTree:e,options:t}){let{minChunkTokenCount:n,acceptableChunkTokenCount:o,maxChunkTokenCount:i,maxLineLength:a}=t,l=[],c=e.split(`
|
|
4031
|
+
`),s=0,u=[],d=0,p=[],m=[],g=!1;for(;s<c.length;){g&&(l.push({ids:p,content:u.join(`
|
|
4032
|
+
`),tokenLength:d}),u=[],d=0,p=m.length?[m[m.length-1].id]:[],g=!1);let h=c[s],f=Pr(h);d+=f,h.length>a&&(h=h.slice(0,a));let v=Array.from(h.matchAll(ew)).map(j=>j&&j.length>=3?{tagName:j[1],id:j[2]}:void 0).filter(j=>!!j),T=Array.from(h.matchAll(uU)).map(j=>j&&(j[2]||j[4])).filter(j=>!!j);T.reverse();let _=h.replace(/ id="[0-9]+"/g,"");u.push(_);for(let j of v)p.push(j.id),m.push(j);for(let j of T){let U=m[m.length-1];U&&U.tagName===j&&m.pop()}let M=m.some(j=>pU.includes(j.tagName)),z=c[s+1]??"",Y=Pr(z),oe=Array.from(z.matchAll(ew)).map(j=>j&&j.length>2?j[1]:void 0).filter(j=>!!j),ge=oe.some(j=>nw.includes(j)),et=oe.some(j=>dU.includes(j));d+Y>=i&&(g=!0),d>=n&&(ge&&!M||T.some(j=>mU.includes(j)))&&(g=!0),d>=o&&et&&!M&&(g=!0),s++}return u.length&&l.push({ids:p,content:u.join(`
|
|
4033
|
+
`),tokenLength:d}),l.forEach((h,f)=>{let b=h.ids[0],E=h.ids[h.ids.length-1];r.debug({tokenLength:h.tokenLength,minId:b,maxId:E},`Chunk for page filtering (index ${f+1}/${l.length})`)}),{chunks:l}}var fU=75e4,yc=3e5,SU=5e3;async function no(r){let{options:e,fixtures:t,screenshot:n}=r,{aiPageFiltering:o}=e,{logger:i,generator:a,orgId:l,signal:c}=t,s=r.tree,u=r.serializedTree,d=Pr(u);if(d>fU)try{let p=Sc({serializedTree:u,options:{minChunkTokenCount:1e4,maxChunkTokenCount:1e5,acceptableChunkTokenCount:5e4,maxLineLength:4e3},logger:i});s=await bU({...r,tokenLimit:yc-1e4,chunks:p.chunks}),u=s.serialize();let m=Pr(u);i.info({oldTokens:d,newTokens:m},"Filtered page using keywords"),d=m}catch(p){i.warn({err:p},"Error filtering page using keyword matching, using naive truncation"),s=s.pruneToSerializedCharLimit(yc*bn),u=s.serialize();let m=Pr(u);i.info({oldTokens:d,newTokens:m},"Filtered page using naive truncation"),d=m}if(d>yc)try{if(o){let p=Sc({serializedTree:u,options:rw,logger:i}),m=hU();s=await B(yU({...r,chunks:p.chunks,callId:m}),{milliseconds:12e3,signal:c}),u=s.serialize();let g=Pr(u);i.info({oldTokens:d,newTokens:g,langfuseCallId:m},"Filtered page using AI chunk ranking"),d=g}else{let p=Sc({serializedTree:u,options:tw,logger:i});s=await B(EU({...r,chunkResult:p,tokenLimit:4e4}),{milliseconds:12e3,signal:c}),u=s.serialize();let m=Pr(u);i.info({oldTokens:d,newTokens:m},"Filtered page using RAG"),d=m}}catch(p){i.warn({err:p},"Error filtering page using RAG/AI, using naive truncation"),s=s.pruneToSerializedCharLimit(yc*bn),u=s.serialize(),i.info("Filtered page using naive truncation")}if(o&&d>SU&&r.type==="locator"&&(l==="org_01HMSCJQBCCG51M2ZF65YC5B8W"||l==="org_01HMJTX4GT1KG94KZRCT8MZ6YB"))try{let p=await a.getPageSummary({browserContext:u,currentStep:r.description,screenshot:n,type:r.type},{logger:i,loggerTags:pe(i),abortSignal:c});if(i.info(p,"Got AI summaries"),p.category!=="OTHER"){let m=new Set;for(let h of p.relevantSections){let f=Math.min(h.startId,h.endId),b=Math.max(h.startId,h.endId);for(let E=f;E<=b;E++)m.add(E.toString())}s=s.pruneUsingRelevantIds(m),u=s.serialize();let g=Pr(u);i.info({newTokens:g,oldTokens:d},"Filtered page using AI summary"),d=g}}catch(p){i.warn({err:p},"Error filtering page using AI summary, continuing...")}return u}async function yU({type:r,callId:e,chunks:t,description:n,fixtures:o,tree:i}){let{generator:a,signal:l,logger:c}=o,s=await a.rankChunksWithAi({chunks:t,description:n,type:r,softTokenLimit:4e4,hardTokenLimit:8e4,callId:e},{abortSignal:l,logger:c,loggerTags:pe(c)}),u=[];return t.forEach((p,m)=>{s.indices.includes(m)&&(u=u.concat(p.ids))}),i.pruneUsingRelevantIds(new Set(u))}async function bU(r){let{description:e,fixtures:t,tree:n}=r,{generator:o,logger:i,signal:a}=t;if(!e.trim())throw new Error("Empty description passed to page filtering");let l=await o.getExtractedKeywords({goal:e},{logger:i,loggerTags:pe(i),abortSignal:a});i.info({keywordsResult:l},"Got keywords for page filtering");for(let c of l.keywords){let s=r.chunks.filter(m=>m.content.toLowerCase().includes(c.toLowerCase()));if(!s.length||s.reduce((m,g)=>m+g.tokenLength,0)>r.tokenLimit&&s.length>1)continue;let d=s.flatMap(m=>m.ids);return n.pruneUsingRelevantIds(new Set(d))}throw new Error("No keywords were unique enough for page filtering")}async function EU(r){let{description:e,fixtures:t,chunkResult:n,tokenLimit:o,tree:i}=r,{generator:a,logger:l,signal:c}=t,s=await a.rankChunksWithRag({description:e,chunks:n.chunks,tokenLimit:o},{abortSignal:c,logger:l,loggerTags:pe(l)});if(s.ids.length===0)throw new Error("RAG returned no important ids");return i.pruneUsingRelevantIds(new Set(s.ids.map(d=>`${d}`)))}async function Mm(r,e){if(!r.description)throw new w("UserConfigurationError","Cannot locate element with empty description");return Dr({action:async()=>TU(r,e),frameConfig:r.iframeUrl?{type:"url",url:r.iframeUrl}:void 0,browser:e.browser,logger:r.logger})}async function TU(r,e){let{disableCache:t,testContext:n,filterByViewport:o,skipWait:i,source:a,memory:l,aiPageFiltering:c,logger:s,allowNotActionableNodesOverride:u}=r,{ctx:d,orgId:p,browser:m,localCodeEvalTools:g,generator:h,abortSignal:f}=e,b=r.description,E=r.useMemory&&!t;n&&(b=await Op({orgId:p,s:b,context:n,localTools:g,signal:f,logger:s})),a&&(b=AU(b,a));let{serializedTree:v,tree:R}=await vn(m,{allowNotActionableNodesOverride:u,filterByViewport:o,abortSignal:f,skipWait:i,logger:s}),T,_=Date.now(),M;for(;!T&&Date.now()-_<3e3;){f.throwIfAborted();try{T=await m.screenshot({clearHighlights:!0,respectActiveFrame:!0,retries:2})}catch(ae){M=ae}}if(!T)throw new w("ActionFailureError",`Failed to take screenshot of page to locate element. The page may be unresponsive, or your machine might be severely resource constrained. Error: ${M?.message}`);let z=v,Y=!1,oe=`data:image/jpeg;base64,${T.toString("base64")}`;z=await no({type:"locator",description:b,screenshot:oe,serializedTree:v,options:{aiPageFiltering:c},tree:R,fixtures:{generator:h,signal:f,logger:s,orgId:p}}),z!==v&&(Y=!0);let ge=await h.getElementLocation({browserState:z,goal:b,screenshot:oe,source:a,memory:E?l:void 0},{disableCache:t,abortSignal:f,loggerTags:pe(s),useMemory:E});s.debug({usedRag:Y,result:ge},"Got locator result");let et=ge.id>0;if(d?.details?.push({type:"AI_LOCATION",matched:et,pageState:z,ragUsed:Y,thoughts:ge.thoughts}),!et)throw new vo(`Could not find any relevant element: ${ge.thoughts}`,ge.updatedMemory?{type:"GCS_TRACES",traces:ge.updatedMemory}:void 0);let{resolution:j,target:U,frameConfig:ne}=await m.createTargetFromA11yId({id:ge.id,requirements:ge.requirements,additionalElements:ge.additionalElements,description:b,targetSource:"AI",logger:s});if(j.a11yNode?.properties?.hidden&&j.a11yNode?.properties?.hidden!=="false")throw new w("ActionFailureError",`Momentic's AI found a relevant element to interact with, but it is explicitly marked with an 'aria-hidden' attribute. Please remove this attribute or adjust the element description to locate a different element. Element chosen: ${j.displayString}`);return E&&(ge.updatedMemory?U.memory={type:"GCS_TRACES",traces:ge.updatedMemory}:l&&(U.memory=l)),{thoughts:ge.thoughts,target:U,resolution:j,frameConfig:ne,screenshot:oe}}var vU=["Element exactly matching the description below. Interpret the description narrowly and do not assume there are any typos or errors. Err on the side of returning -1 unless there is a perfect match. Description:","Element closely matching the description below. Interpret the description narrowly and do not return elements that are merely loosely related. Description:","Element matching the description below. This element is being located as part of a negative check step (i.e. we are trying to verify the element does not exist). Therefore, interpret the description narrowly, do not assume there are typos, and err on the side of returning -1 unless there is a perfect match. Description:"],ow="<select> element:",iw="text input or contenteditable element:",aw="Element matching the description below. It is possible the element is hidden or doesn't exist. Interpret the description narrowly and do not assume there are typos. Return -1 unless there is an straightforward match. Description:",sw="Element matching the description below. This element is being located as part of a check step (i.e. we are trying to verify certain properties about the element). Interpret the description narrowly and do not return elements that are merely loosely related. Description:",xm=[ow,iw,aw,sw,...vU];function lw(r,e){if(r===e)return!0;for(let t of xm){if(!r.startsWith(t))continue;let n=r.slice(t.length).trim();if(xm.some(o=>e.startsWith(o)&&e.slice(o.length).trim()===n)||n===e.trim())return!0}return!!xm.some(t=>e.startsWith(t)&&e.slice(t.length).trim()===r.trim())}function AU(r,e){if(!r||!e)return r;switch(e){case"SELECT_OPTION":return`${ow} ${r}`;case"TYPE":return`${iw} ${r}`;case"NEGATED_ELEMENT_VISIBLE_CHECK":return`${aw}
|
|
4034
|
+
${r}`;case"ELEMENT_CHECK":return`${sw}
|
|
4035
|
+
${r}`;default:return r}}var wU=15;async function bc({command:r,aiPageFiltering:e,logger:t,fixtures:n,source:o,useMemory:i,maxRetries:a=wU}){if(!r.assertion.trim())throw new w("ActionFailureError","Assertion command is missing the assertion content");let{browser:l}=n,c=r.timeout?r.timeout*1e3:l.smartWaitingTimeout,s=tc(c),u=0,d=Date.now(),p,m,g;try{await Dr({action:()=>l.clearHighlights(),frameConfig:r.iframeUrl?{type:"url",url:r.iframeUrl}:void 0,browser:l,logger:t})}catch(f){t.warn({err:f},"Failed to clear highlights before AI check, continuing...")}let h;for(;u<a&&(!h||h-d<c);){n.abortSignal.throwIfAborted(),u!==0&&await X(s,n.abortSignal),h=Date.now();try{if(p=await Dr({action:async()=>{let b=await cw(l,t,n.abortSignal);return m&&m.serializedTree===b.serializedTree&&m.screenshotBuff.equals(b.screenshotBuff)?p:(m=b,uw({command:r,state:b,fixtures:n,useMemory:i,useConsensus:!1,highlightElementsOnFailure:!1,attemptNumber:u,aiPageFiltering:e,logger:t,source:o}))},frameConfig:r.iframeUrl?{type:"url",url:r.iframeUrl}:void 0,logger:t,browser:l}),p?.updatedMemory&&Jl(r,p.updatedMemory,t),p?.success)break;throw p?.thoughts?new w("AssertionFailureError",p.thoughts):new w("InternalPlatformError","No thoughts were provided for AI assertion failure")}catch(f){n.abortSignal.throwIfAborted(),g=f instanceof Error?f:new Error(`${f}`),t.info({err:f},`AI check assert attempt ${u} failed, retrying...`)}finally{u++}}if(!p?.success)try{p=await Dr({action:async()=>uw({command:r,state:await cw(l,t,n.abortSignal),fixtures:n,useMemory:i,useConsensus:!0,highlightElementsOnFailure:!0,attemptNumber:u,aiPageFiltering:e,logger:t}),frameConfig:r.iframeUrl?{type:"url",url:r.iframeUrl}:void 0,logger:t,browser:l})}catch(f){n.abortSignal.throwIfAborted(),g=f instanceof Error?f:new Error(`${f}`)}finally{u++}if(!p?.success){let f=`AI check still failing after ${u} attempts.`;throw g&&(f+=` Latest result: ${g.message}`),new w("AssertionFailureError",f)}return{...p,succeedImmediately:!1,urlAfterCommand:l.url()}}async function cw(r,e,t){let[n,o]=await Promise.all([vn(r,{abortSignal:t,skipWait:!0,skipWaitForPageLoad:!0,logger:e}),r.screenshot({retries:1,respectActiveFrame:!0})]);return{...n,screenshotBuff:o}}async function uw({command:r,state:e,fixtures:t,useConsensus:n,useMemory:o,highlightElementsOnFailure:i,aiPageFiltering:a,attemptNumber:l,source:c,logger:s}){let{browser:u,generator:d,abortSignal:p}=t,m={type:"ASSERTION"},{serializedTree:g,tree:h}=e,f=e.screenshotBuff,b=f.toString("base64"),E=u.url(),v=r.contextChoice??"MULTIMODAL",R=g;v!=="VISION_ONLY"&&(R=await no({type:"assertion",serializedTree:g,tree:h,description:r.assertion,screenshot:b,options:{aiPageFiltering:a},fixtures:{generator:d,signal:p,logger:s,orgId:t.orgId}}),R!==g&&(m.ragUsed=!0),m.pageState=R);let T={goal:r.assertion,url:E,memory:o?r.cache?.memory:void 0,browserState:R,screenshot:b,contextChoice:v,source:c},M=await(v==="VISION_ONLY"?(z,Y)=>d.getVisualAssertionResult(z,Y):(z,Y)=>d.getAssertionResult(z,Y))(T,{useConsensus:n,attemptNumber:l,useMemory:o,disableCache:!!r.disableCache,abortSignal:p,logger:s,loggerTags:pe(s)});return(M.result||i)&&M.relevantElements&&(m.relevantElementsSerialized=M.relevantElements.map(z=>u.getSerializedFormFromA11yId(z)).filter(z=>!!z),await RU(M.relevantElements,u,s)),{success:M.result,thoughts:M.thoughts,afterScreenshotOverride:f,updatedMemory:o?M.updatedMemory:void 0}}async function RU(r,e,t){let n=Date.now();for(let o of r){if(Date.now()-n>2e3){t.debug("Highlighting relevant elements took over 2s, aborting...");return}try{let i=new AbortController;await B(e.highlightA11yId(o),{milliseconds:1e3,fallback:()=>{throw i.abort(),new Error("Timed out waiting for highlighting to complete")}})}catch(i){t.debug({err:i},"Failed to highlight relevant element after assertion, continuing...");return}}}import{cloneDeep as pw}from"lodash-es";async function mw(r){let{command:e,timeoutMs:t,fixtures:n}=r,{abortSignal:o}=n,i=Vg(e.cache)?e.cache:void 0,a=pw(i),l=()=>{if(i){let m=JT(a,i);i.target=m.target,i.updatedAt=m.updatedAt}},c=Date.now(),s=0,u,d=500,p=!1;for(;s<2||Date.now()-c<t;){s++,s>1&&await X(d,o),o?.throwIfAborted();let{result:m,elementWasFound:g}=await dw({cacheToUse:i,params:r});if(u=m,p=g,m.success)break;l(),d=Math.min(d*2,1e4)}if(!u)throw new w("InternalPlatformError",`Failed to evaluate manual element assertion in ${t}ms.`);if(o?.throwIfAborted(),!u.success&&i?.target&&ns(i.target)){let m=i?.target?.memory?{target:{id:-1,memory:i.target.memory}}:void 0,{result:g}=await dw({cacheToUse:m,params:r});u=g,u.success||l()}return u.success&&i?.target&&!p&&(i.target=Dp(i.target),i.updatedAt=new Date),u}async function dw({cacheToUse:r,params:e}){let{command:t,disableCache:n,fixtures:o,tracer:i,targetingWrapper:a}=e,{logger:l}=o;if(t.target&&!Yr(t.target))throw new Error("Element assertion with x/y is not supported yet");let c=xU(t.assertion),s,u=!1,d=pw(r);try{let{elementInteractedDisplayString:p,result:m,thoughts:g}=await a({ctx:o.ctx,tracer:i,command:t,target:t.target,cache:d?.target,action:async h=>CU(h.locator,e),options:{...t,allowNotActionableNodesOverride:!0,disableCache:n,memory:d?.target?.memory,disableGlobalLocatorRedirect:!0,source:Vi(t),targetName:"target"}});return s={success:m.success,data:m.data,err:m.err,elementInteractedDisplayString:p,thoughts:g},u=!0,m.success||(l.warn({aiThoughts:g,elementString:p,err:m.err},"Element check found an element but failed"),s={...m,thoughts:g}),{result:s,elementWasFound:u}}catch(p){if(c)return s={success:!0,thoughts:`The element described does not exist on the page: ${p.message}`,err:void 0,data:void 0},{result:s,elementWasFound:u};if(!(p instanceof w)||p.reason!="ActionFailureError")throw p;return s={success:!1,err:p,data:void 0,thoughts:void 0},l.warn({err:p},"Element check did not find an element and failed"),{result:s,elementWasFound:u}}}async function CU(r,{command:e,fixtures:t}){let n=e.assertion;await t.browser.highlight(r);let o=!0,i,a;switch(n.type){case"ELEMENT_CONTENT":{let c=await r.textContent()??"";if(a={elementTextContent:_t(c,500,!0)},!Ec(c,n.value,n.operation,!!n.negated)){let s=n.negated?Xn[n.operation]:Jn[n.operation];o=!1,i=new w("AssertionFailureError",`The content ${s} '${n.value}': ${c}`)}break}case"ELEMENT_ATTRIBUTE":{a={elementOuterHtml:_t(await r.evaluate(s=>s.cloneNode(!1).outerHTML),500,!0)};let c;try{c=await r.getAttribute(n.attr,{timeout:3e3})??""}catch(s){i=new w("AssertionFailureError",`The element does not have an attribute named ${n.attr}: ${s}`),o=!1;break}if(!Ec(c,n.value,n.operation,!!n.negated)){let s=n.negated?Xn[n.operation]:Jn[n.operation];o=!1,n.operation==="EXISTS"?i=new w("AssertionFailureError",`The attribute ${n.attr} ${s}`):i=new w("AssertionFailureError",`The attribute ${n.attr} ${s} '${n.value}': ${c}`)}break}case"ELEMENT_EXISTENCE":{switch(n.condition){case"VISIBLE":{o=await r.evaluate(async(s,u)=>{let d=Date.now();for(;Date.now()-d<u;){await new Promise(m=>setTimeout(m,250));let p=s.getBoundingClientRect();if(!(p.width===0||p.height===0)&&window.getComputedStyle(s).visibility!=="hidden"&&window.getComputedStyle(s).display!=="none")return!0}return!1},Xr*1e3);break}case"EDITABLE":{o=await r.isEditable({timeout:Xr*1e3});break}case"EXISTS":{o=!0;break}case"ENABLED":{o=await r.isEnabled({timeout:Xr*1e3});break}case"FOCUSED":{o=await r.evaluate(s=>s===document.activeElement);break}default:return(s=>{throw"If Typescript complains about the line below, you missed a case or break in the switch above"})(n.condition)}if(o=n.negated?!o:o,!o){let c=n.negated?ZT[n.condition]:QT[n.condition];i=new w("AssertionFailureError",`The element ${c}`)}break}case"ELEMENT_NAME":{let c=await r.evaluate(s=>s.tagName);if(!Ec(c,n.value,n.operation,!!n.negated)){let s=n.negated?Xn[n.operation]:Jn[n.operation];o=!1,i=new w("AssertionFailureError",`The element tag name ${s} '${n.value}': ${c}`)}break}case"ELEMENT_STYLE":{let c=await r.evaluate((s,u)=>window.getComputedStyle(s).getPropertyValue(u),n.property);if(!Ec(c,n.value,n.operation,!!n.negated)){let s=n.negated?Xn[n.operation]:Jn[n.operation];o=!1,n.operation==="EXISTS"?i=new w("AssertionFailureError",`The style property ${n.property} ${s}`):i=new w("AssertionFailureError",`The style property ${n.property} ${s} '${n.value}': ${c}`)}break}default:return(c=>{throw"If Typescript complains about the line below, you missed a case or break in the switch above"})(n)}return{success:o,data:a,err:i}}function Ec(r,e,t,n){let o;switch(t){case"CONTAINS":{o=r.includes(e);break}case"EQUALS":{o=r.trim()===e.trim();break}case"STARTS_WITH":{o=r.trim().startsWith(e);break}case"EXISTS":{o=r.trim().length>0;break}default:return(a=>{throw"If Typescript complains about the line below, you missed a case or break in the switch above"})(t)}return n?!o:o}function xU(r){return r.type==="ELEMENT_EXISTENCE"&&r.negated&&(r.condition==="EXISTS"||r.condition==="VISIBLE")}function gw(r){return r.type==="ELEMENT_EXISTENCE"&&r.negated&&r.condition==="EXISTS"}import{Jimp as MU}from"jimp";async function Ba(r,e){let t=await r.screenshot(e),n=await MU.fromBuffer(t);return{buffer:t,width:Math.ceil(n.bitmap.width??0),height:Math.ceil(n.bitmap.height??0)}}import{Jimp as hw}from"jimp";import _m from"jpeg-js";import _U from"pixelmatch";async function fw({ctx:r,tracer:e,command:t,disableCache:n,browser:o,targetingWrapper:i,logger:a,screenshotStorage:l}){if(t.target&&!Yr(t.target))throw new Error("Visual Diff with x/y is not supported yet");await o.waitForDOMStability({logger:a});let c={clearHighlights:!0,hideCaret:!0},s;t.target?.elementDescriptor?s=(await i({ctx:r,tracer:e,command:t,target:t.target,cache:t.cache?.target,action:async oe=>Ba(o,{locator:oe.locator,...c}),options:{...t,disableCache:n,disableGlobalLocatorRedirect:!0,memory:t.cache?.target?.memory,targetName:"target"}})).result:s=await Ba(o,c);let u=await l.prepareGoldenScreenshotForComparison(a,t,s);if((s.height!==u.height||s.width!==u.width)&&a.warn({currHeight:s.height,currWidth:s.width,savedHeight:u.height,savedWidth:u.width},"Mismatched before and after visual diff screenshot sizes"),Math.abs(s.height-u.height)>10||Math.abs(s.width-u.width)>10){let Ee=`${s.width}x${s.height}`,oe=`${u.width}x${u.height}`;return{fail:!0,thoughts:`Current screenshot (${Ee}) does not match saved screenshot dimensions (${oe}) - did you change the size of the target or the viewport?`,beforeScreenshotOverride:u.buffer,afterScreenshotOverride:s.buffer,succeedImmediately:!1,urlAfterCommand:o.url()}}let d=await hw.fromBuffer(s.buffer),p={width:s.width,height:s.height},m=await hw.fromBuffer(u.buffer),g={width:u.width,height:u.height},h,f=p.width*p.height,b=g.width*g.height,E=Math.abs(p.height-g.height),v=Math.abs(p.width-g.width);if(f>b){let Ee=d.cover({w:g.width,h:g.height});s.buffer=await Ee.getBuffer("image/jpeg"),h="current",s.width=g.width,s.height=g.height}else if(b>f){let Ee=m.cover({w:p.width,h:p.height});u.buffer=await Ee.getBuffer("image/jpeg"),h="saved"}let R={data:Buffer.alloc(s.width*s.height*4),width:s.width,height:s.height},T=t.threshold??.1,M=_U(_m.decode(u.buffer).data,_m.decode(s.buffer).data,R.data,s.width,s.height,{threshold:T,diffColorAlt:[0,255,0]})/(s.width*s.height)*100,z=M>T*100,Y=`Visual diff of ${M.toFixed(2)}% detected, which is ${z?"over":"under"} the threshold of ${T*100}%.`;if(h&&(Y+=` The ${h} screenshot was cropped since it was taller by ${E} pixels and wider by ${v} pixels.`),z)throw new w("ActionFailureError",Y);return{fail:z,thoughts:Y,beforeScreenshotOverride:s.buffer,afterScreenshotOverride:_m.encode(R,75).data,succeedImmediately:!1,urlAfterCommand:o.url()}}var IU=3e4;async function Tc({command:r,logger:e,baseUrl:t,fetchImplementation:n=fetch}){let o=r.timeout??IU/1e3,i=Object.fromEntries(Object.entries(r.headers||{}).filter(([m,g])=>m&&g)),a=new URLSearchParams;Object.entries(r.params||{}).filter(([m,g])=>m&&g).forEach(([m,g])=>{a.append(m,g)});let l=a.toString(),c;if(Zo(r.url)&&(c=r.url),t&&Qo(r.url,t)&&(c=new URL(r.url,t).toString()),!c)throw new w("ActionFailureError",`Invalid URL: ${r.url}`);e.info({url:c,searchParams:l,headers:i,body:r.body,method:r.method},"Making HTTP request");let u=await B((async()=>{let m=l?`${c}?${l}`:c;try{return await n(m,{headers:i,method:r.method,body:r.body})}catch(g){throw e.error({err:g},"Failed to make HTTP request"),new Error(`Failed to make HTTP request: ${g}`)}})(),{milliseconds:o*1e3,fallback:()=>{throw new w("ActionFailureError",`Fetch request timed out after ${o} seconds`)}});if(!u.ok){let m;try{m=await u.text()}catch(g){m=`Failed to read response body: ${g}`}throw new w("ActionFailureError",`Fetch request failed with status ${u.status}: ${m}`)}let d={};u.headers.forEach((m,g)=>{d[g]=m});let p={status:u.status,headers:d};if(u.headers.get("content-type")?.includes("json"))try{p.json=await u.json()}catch{}else u.headers.get("content-type")?.includes("text")&&(p.text=await u.text());return p}var PU=5e3;async function bw({timeout:r=Xr,...e}){let t=Date.now(),n=r*1e3,o=n+1e4,i,a=0,l=500;for(;a-t<n;){if(Date.now()-t>o){e.logger.warn("Exceeded max system timeout for page assertion, exiting...");break}e.signal.throwIfAborted();let c=Date.now();i=await Sw(e),a=Date.now();let s=a-c;if(s>1e3&&e.logger.warn({pageAssertDuration:s},"Page assertion took longer than expected"),!i.success)await X(l,e.signal),l=Math.min(Math.floor(l*1.5),PU);else return i}return i=await Sw(e),i}async function Sw({assertion:r,browser:e,autoExpandIframes:t}){switch(r.type){case"CONTENT":{let o,i=!1,a;try{let l;if(t){let c=await e.evaluateFunctionInAllFrames(yw,{value:r.value,negated:!!r.negated,returnHtml:!1});i=r.negated?c.every(s=>s.evaluation):c.some(s=>s.evaluation),l=c.find(s=>s.pageHtml)?.pageHtml}else({evaluation:i,pageHtml:l}=await e.evaluateFunctionInPage(yw,{value:r.value,negated:!!r.negated,returnHtml:!0},"checking page content"));if(!i){let c=r.negated?Xn.CONTAINS:Jn.CONTAINS;a=new w("AssertionFailureError",`The page ${c} '${r.value}'.`),o=l}}catch(l){a=new w("AssertionFailureError",`Failed to evaluate page content assertion: ${l instanceof Error?l.message:`${l}`}`)}return{success:i,err:a,data:i||!o?void 0:{pageContent:o}}}default:return(o=>{throw"If Typescript complains about the line below, you missed a case or break in the switch above"})(r.type)}}function yw({value:r,negated:e,returnHtml:t}){let n=document.documentElement.outerHTML,o=n.includes(r)===!e;return n.length>1e4&&(n=n.slice(0,1e4)+"...TRUNCATED"),{evaluation:o,pageHtml:!o&&t?n:void 0}}var OU=3e4;async function Ew({command:r,logger:e,baseUrl:t,fetchImplementation:n=fetch}){let o=r.timeout??OU/1e3,i=new AbortController,a=Object.fromEntries(Object.entries(r.headers||{}).filter(([d,p])=>d&&p));a["Content-Type"]="application/json";let l;if(Zo(r.url)&&(l=r.url),t&&Qo(r.url,t)&&(l=new URL(r.url,t).toString()),!l)throw new w("ActionFailureError",`Invalid URL: ${r.url}`);let s=await B((async()=>{try{return await n(l,{headers:a,method:"POST",body:JSON.stringify({query:r.query,variables:r.variables?JSON.parse(r.variables):void 0}),signal:i.signal})}catch(d){e.error({err:d},"Failed to make HTTP request")}})(),{milliseconds:o*1e3});if(!s)throw new w("ActionFailureError",`GraphQL request timed out after ${o} seconds`);if(!s.ok){let d,p=await s.text();try{d=JSON.parse(p)}catch{throw new w("ActionFailureError",`GraphQL request failed with status ${s.status}: ${p}`)}throw d?.errors?.length&&d?.errors[0]?.message?new w("ActionFailureError",`GraphQL request failed with status ${s.status}: ${d.errors[0].message}`):new w("ActionFailureError",`GraphQL request failed with status ${s.status}: ${p}`)}let u={};return s.headers.forEach((d,p)=>{u[p]=d}),{status:s.status,headers:u,json:await s.json()}}var vc=class{orgId;options;storage;localCodeEvalTools;uploadedFileStorage;visualDiffScreenshotStorage;browser;generator;executeAbortController=new AbortController;logger;recordAbortController=null;registeredListeners={};recordedRequests={};constructor({browser:e,generator:t,logger:n,storage:o,orgId:i,localCodeEvalTools:a,uploadedFileStorage:l,visualDiffScreenshotStorage:c,options:s}){this.orgId=i,this.options=s,this.browser=e,this.browser.registerAbortSignal(this.executeAbortController.signal),this.storage=o,this.uploadedFileStorage=l,this.visualDiffScreenshotStorage=c,this.localCodeEvalTools=a,this.generator=t,this.logger=n}setOpen(){this.executeAbortController=new AbortController,this.browser.registerAbortSignal(this.executeAbortController.signal)}setClosed(){this.executeAbortController.abort()}throwIfClosed(){this.executeAbortController.signal.throwIfAborted()}get closed(){return this.executeAbortController.signal.aborted}async evaluateAiAction({goal:e,startingScreenshot:t,history:n,disableCache:o,langfuseSessionId:i,lastError:a,logger:l=this.logger}){let[c,s]=await Promise.all([vn(this.browser,{abortSignal:this.executeAbortController.signal,skipWait:!0,skipWaitForPageLoad:!0,logger:l}),this.browser.screenshot({retries:1,clearHighlights:!0})]),u=`data:image/jpeg;base64,${s.toString("base64")}`,d=await no({type:"ai-action",description:e,screenshot:u,serializedTree:c.serializedTree,tree:c.tree,options:{aiPageFiltering:!!this.options?.aiPageFiltering},fixtures:{generator:this.generator,signal:this.executeAbortController.signal,logger:l,orgId:this.orgId}}),p={url:this.browser.url(),browserState:d,startingScreenshot:t,history:n,goal:e,screenshot:u,lastError:a};return await this.generator.getMultiturnAiActionEvaluation(p,{disableCache:o,abortSignal:this.executeAbortController.signal,loggerTags:{...pe(l)},langfuseSessionId:i})}async promptToCommand({goal:e,startingScreenshot:t,history:n,actionHint:o,disableCache:i,logger:a=this.logger,langfuseSessionId:l}){let c=this.browser.url(),[s,u]=await Promise.all([vn(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 no({type:"ai-action",description:e,screenshot:d,serializedTree:s.serializedTree,tree:s.tree,options:{aiPageFiltering:!!this.options?.aiPageFiltering},fixtures:{generator:this.generator,signal:this.executeAbortController.signal,logger:a,orgId:this.orgId}}),m={url:c,browserState:p,startingScreenshot:t,history:n,goal:e,actionHint:o,screenshot:d};try{return await this.generator.getMultiturnAiActionCommand(m,{disableCache:i,abortSignal:this.executeAbortController.signal,loggerTags:{...pe(a)},langfuseSessionId:l})}catch(g){throw new w("InternalWebAgentError",`Error generating command: ${g instanceof Error?g.message:g}`,{errOptions:{cause:g}})}}async getBrowserState(e){return vn(this.browser,e)}async locateElement(e){return await Mm({...e,aiPageFiltering:!!this.options?.aiPageFiltering},this.getControllerFixtures())}async locateElementWithSelector(e,t){return Dr({action:async()=>{let n=await this.browser.resolveHardcodedCssSelector({ctx:null,selector:e,timeoutMs:2e3,logger:this.logger});return{thoughts:"Located element with selector",target:{id:-1,selector:e,targetSource:"USER_CSS_SELECTOR",targetUpdateTime:new Date().toUTCString()},resolution:n}},frameConfig:t?{type:"url",url:t}:void 0,browser:this.browser,logger:this.logger})}getControllerFixtures(e){return{ctx:e??null,browser:this.browser,generator:this.generator,logger:this.logger,orgId:this.orgId,storage:this.storage,localCodeEvalTools:this.localCodeEvalTools,abortSignal:this.executeAbortController.signal}}shouldUseMemory(){return this.options?.useMemory??(this.orgId==="org_01HMSCJQBCCG51M2ZF65YC5B8W"||this.orgId==="org_01HMJTX4GT1KG94KZRCT8MZ6YB")}async wrapMultiElementTargetingCommand({ctx:e,tracer:t,command:n,targetNames:o,descriptions:i,caches:a,action:l,options:c,retriesWithAI:s=1}){let u=[];for(let d=0;d<i.length;d++){let p=i[d],m=await this.wrapElementTargetingCommand({ctx:e,tracer:t,command:n,target:p,cache:a[d],action:async g=>g,options:{...c,targetName:o[d]}});u.push(m)}try{let d=await l(...u.map(g=>g.result)),p=g=>g==="fromTarget"?"From Target":g==="toTarget"?"To Target":"Target",m=u.map((g,h)=>g.thoughts?`${p(o[h])}: ${g.thoughts}`:void 0).filter(g=>!!g).join(" -------------- ")||void 0;return{result:d,elementInteractedDisplayStrings:u.map(g=>g.elementInteractedDisplayString),thoughts:m}}catch(d){if(this.throwIfClosed(),s>0)return this.logger.warn({err:d},"Failed to execute action with multiple cached targets, retrying with AI"),this.wrapMultiElementTargetingCommand({ctx:e,tracer:t,command:n,targetNames:o,descriptions:i,caches:i.map(()=>{}),action:l,options:c,retriesWithAI:s-1});throw new w("ActionFailureError",d.message,{errOptions:{cause:d}})}}async wrapElementTargetingCommand(e){let t=this.logger.child({commandId:e.command.id}),n;for(let o=0;o<2;o++)try{return await Dr({action:()=>this.wrapElementTargetingCommandHelper({...e,originalCache:e.originalCache??e.cache}),frameConfig:e.options.iframeUrl?{type:"url",url:e.options.iframeUrl}:void 0,browser:this.browser,logger:t})}catch(i){if(n=i,this.browser.userBrowserSettings.visualActions&&Au(i)){t.warn({err:i},"Invalid mpath error, retrying element targeting command");continue}if(!this.browser.userBrowserSettings.visualActions&&(Ru(i)||wu(i))){t.warn({err:i},"Invalid momentic id error, retrying element targeting command");continue}if(Cu(i)){t.warn({err:i},"Invalid backend node id error, retrying element targeting command");continue}if(i instanceof Tr&&i.retryableWithAI){t.warn({err:i},"Element cache disqualification error, retrying element targeting command");continue}throw i}throw n instanceof w?n:new w("ActionFailureError",n?.message??"An unknown error occurred during element targeting")}async wrapHardcodedCssTargetingCommandHelper({ctx:e,target:t,action:n,options:o,command:i}){let a=this.logger.child({commandId:i.id}),{targetName:l}=o;if(t.type!=="description")throw new w("ActionFailureError","Cannot use selector with non-description target");let c,s=Date.now(),u=Date.now();for(;Date.now()-u<this.browser.smartWaitingTimeout;){s=Date.now();try{let d=await this.browser.resolveHardcodedCssSelector({ctx:e,selector:t.elementDescriptor,targetName:l,logger:a});return{result:await n({locator:d.locator}),elementInteractedDisplayString:d.displayString}}catch(d){if(d.name==="AbortError")throw d;c=d,a.warn({err:d},"Failed to action on hardcoded css selector"),Date.now()-s<500&&await X(500)}}throw c}async wrapElementTargetingCommandHelper(e){let{ctx:t,tracer:n,target:o,originalCache:i,action:a,options:l,command:c}=e,{disableCache:s,useSelector:u,targetName:d,targetHealingInProgress:p,source:m}=l,g=this.logger.child({commandId:c.id}),h=this.shouldUseMemory(),f=l.retriesWithAI??1,b=!1,E=Tw(e.cache);if((!E||s)&&!au(o))throw new w("ActionFailureError","Cannot target element with no cached data or element descriptor");if(u)return this.wrapHardcodedCssTargetingCommandHelper(e);s&&(g.info("Cache explicitly disabled for this step"),b=!0,E=void 0),E&&this.browser.userBrowserSettings.disableSecondaryCacheResolution&&E.targetSource==="HEURISTIC_HEALED"&&(b=!0,E=void 0),E?.inputDescription&&!lw(o.elementDescriptor,E.inputDescription)&&(g.warn({old:E.inputDescription,new:o.elementDescriptor},"Target cache was generated with a different description, clearing it automatically"),b=!0,E=void 0);let v=T=>!!T&&ns(T),R=!0;if(!v(E)){R=!1,g.info({description:o.elementDescriptor,targetHealingInProgress:p,cacheBustedBeforeAction:b,memory:l.memory,useMemory:h},"Prompting AI for an updated element location"),b&&await X(this.browser.smartWaitingTimeout,this.executeAbortController.signal),f--;let T;try{T=await Mm({description:o.elementDescriptor,disableCache:!!l.disableCache,iframeUrl:l.iframeUrl,source:m,useMemory:h,memory:h?l.memory:void 0,aiPageFiltering:!!this.options?.aiPageFiltering,allowNotActionableNodesOverride:l.allowNotActionableNodesOverride,logger:g},this.getControllerFixtures(t))}catch(z){if(z instanceof vo&&z.updatedLocatorMemory){let Y={id:-1,...i,memory:z.updatedLocatorMemory};Xl({cmd:c,key:d,newTarget:Y,logger:g,updatedWithAI:!0})}throw new w("ActionFailureError",z.message)}T.frameConfig&&this.browser.setActiveFrameConfig(T.frameConfig);let _=l.disableGlobalLocatorRedirect?{locator:T.resolution.locator}:await this.attemptLocatorRedirect(T.resolution.locator,g),M=await a(_);return Xl({cmd:c,key:d,newTarget:T.target,logger:g,updatedWithAI:!0}),p&&(n.recordTargetAutoHeal({healType:"AI"}),T.target.targetSource="AI_HEALED",T.target.targetUpdateTime=new Date().toUTCString(),T.target.targetUpdateLoggerTags=pe(g)),{result:M,elementInteractedDisplayString:T.resolution.displayString,thoughts:T.thoughts}}try{let T=await this.browser.resolveTarget(t,E,{allowNotActionableNodesOverride:l.allowNotActionableNodesOverride,targetName:d,logger:g,signal:this.executeAbortController.signal});(this.browser.userBrowserSettings.visualActions||this.browser.userBrowserSettings.globalLocatorRedirect!==!1)&&await this.browser.scrollIntoViewIfNeeded(T.locator);let _=l.disableGlobalLocatorRedirect?{locator:T.locator}:await this.attemptLocatorRedirect(T.locator,g),M=await a(_);if(vt.increment("cache_target_resolution_v2",1,["outcome:hit","platform:web",`hasRequirements:${!!E.requirements}`,`hasAdditionalElements:${!!E.additionalElements}`,`orgId:${this.orgId}`]),Xl({cmd:c,key:d,newTarget:E,logger:g,updatedWithAI:!1}),R){let z=T.decisions.filter(Y=>Y.matched);if(z.length!==1)g.warn({decisions:T.decisions},"Expected exactly 1 matching method for element location, got more or less");else{let Y=z[0].type;n.recordTargetAutoHeal({healType:Y})}}return{result:M,elementInteractedDisplayString:T.displayString}}catch(T){this.throwIfClosed(),vt.increment("cache_target_resolution_v2",1,["outcome:miss","platform:web",`hasRequirements:${!!E.requirements}`,`hasAdditionalElements:${!!E.additionalElements}`,`orgId:${this.orgId}`]);let _=!1;if((T instanceof Tr||Au(T)||Ru(T)||Cu(T)||Dh(T)||wu(T))&&(_=!0),T instanceof w&&!_)throw g.error({err:T},"Failed to execute action with cached target (fatal)"),T;if(f>0&&o){g.info({err:T},"Failed to execute action with cached target, retrying with AI");let M;return E.memory&&Ug(E.memory)&&(M=E.memory),this.wrapElementTargetingCommand({ctx:t,tracer:n,command:c,target:o,cache:void 0,originalCache:i,action:a,options:{...l,memory:M,retriesWithAI:f,targetHealingInProgress:!0}})}throw new w("ActionFailureError",T.message,{errOptions:{cause:T}})}}async attemptLocatorRedirect(e,t){return this.browser.userBrowserSettings.globalLocatorRedirect!==!1?this.browser.performTargetRedirection(e,t):{locator:e}}async screenshotWithDimensions(e){return Ba(this.browser,e)}async executePresetCommand(e,t,n,o,i){this.options?.slowMoMs&&await X(this.options.slowMoMs);let a=await this.browser.getOpenPages(),l=this.browser.url(),c;try{c=await this.resolveCommandTemplateStrings(n,o)}catch(s){throw this.throwIfClosed(),new w("ActionFailureError",`Failed to substitute template strings in command: ${s.message}`,{errOptions:{cause:s}})}try{let s=await this.executePresetCommandHelper(e,t,n,o,i);return this.browser.userBrowserSettings.visualActions&&Qg(n)?await this.browser.waitForDOMStability({timeout:me}):!this.browser.userBrowserSettings.visualActions&&["PRESS","TYPE"].includes(n.type)&&await this.browser.waitForDOMStability({timeout:Z}),this.options?.autoFollowNewTabs&&await QA({beforeUrl:l,command:n,beforePages:a.map(u=>u.url),browser:this.browser,logger:this.logger}),s}catch(s){throw s.name!=="AbortError"&&this.logger.error({err:s},"Error thrown in action controller"),s}finally{Yl(n,c)}}createCallbacksForBrowser(e){return{createIsolatedFolder:()=>Zp(e)}}async resolveCommandTemplateStrings(e,t){return Kl({obj:e,context:t,bannedKeys:["type","a11yData","thoughts","cache","code"],orgId:this.orgId,logger:this.logger,signal:this.executeAbortController.signal,localTools:this.localCodeEvalTools})}async executePresetCommandHelper(e,t,n,o,i){i=i||"disableCache"in n&&!!n.disableCache;let a=this.logger.child({commandId:n.id});switch(n.type){case"SUCCESS":let l=n.condition;return l?.assertion.trim()?bc({command:l,fixtures:this.getControllerFixtures(e),useMemory:this.shouldUseMemory(),aiPageFiltering:!!this.options?.aiPageFiltering,logger:a}):{succeedImmediately:!1,urlAfterCommand:this.browser.url()};case"AI_ASSERTION":{if(!n.assertion.trim())throw new w("ActionFailureError","Missing assertion");if(n.timeout&&n.timeout>1800)throw new w("AssertionFailureError",`AI check timeout of ${n.timeout} exceeds the maximum allowed value of 30 minutes.`);return bc({command:n,fixtures:this.getControllerFixtures(e),useMemory:this.shouldUseMemory(),aiPageFiltering:!!this.options?.aiPageFiltering,logger:a})}case"AI_EXTRACT":{if(!n.goal.trim())throw new w("ActionFailureError","Cannot perform AI extraction without goal");if(n.schema){let f=yy(n.schema);if(f)throw new w("UserConfigurationError",f)}let g=await this.browser.getCondensedHtml(),h=await this.browser.screenshot({retries:2});try{let f=await this.generator.getTextExtraction({goal:n.goal,browserState:g,returnSchema:n.schema,screenshot:`data:image/jpeg;base64,${h.toString("base64")}`},{disableCache:i,abortSignal:this.executeAbortController.signal,loggerTags:pe(a)});if(f.result==="NOT_FOUND")throw new w("ActionFailureError","No relevant data found for extraction goal on this page");if(f.thoughts?.includes("MaxGenerationLengthExceededError"))throw new w("UserConfigurationError",f.thoughts);return{thoughts:f.thoughts||void 0,data:f.result,succeedImmediately:!1,urlAfterCommand:this.browser.url()}}catch(f){let b=f.message;throw b.includes("MaxGenerationLengthExceededError")?new w("UserConfigurationError","You tried to extract too much data. Please rephrase your query to limit the results returned or use a JavaScript step in the browser instead."):b.includes("AIProviderError")&&b.includes("time")?new w("AIProviderError","The AI provider responded with an error. This may be because you tried to extract too much data. Please limit extraction results to 2000 characters.",{errOptions:{cause:f}}):f}}case"NAVIGATE":if(!Zo(n.url)&&!Qo(n.url,this.browser.baseUrl))throw new w("ActionFailureError",`Invalid URL provided to navigate command: ${n.url}`);await this.browser.navigate({url:n.url,loadTimeoutMs:n.loadTimeout?n.loadTimeout*1e3:void 0});break;case"DIALOG":this.browser.registerDialogHandler(n.action);break;case"CAPTCHA":if(!this.browser.canSolveCaptchas())break;let c=await this.browser.solveCaptcha();c&&(await this.wrapElementTargetingCommand({ctx:e,tracer:t,command:n,target:{type:"description",elementDescriptor:"the captcha image solution input"},cache:void 0,action:g=>this.browser.click(g,this.createCallbacksForBrowser(this.orgId),{}),options:{...n,targetName:"target",disableCache:i}}),await this.browser.type(c,{clearContent:!0,pressEnter:!0},!0));break;case"GO_BACK":await this.browser.goBack();break;case"GO_FORWARD":await this.browser.goForward();break;case"SCROLL_LEFT":case"SCROLL_RIGHT":case"SCROLL_DOWN":case"SCROLL_UP":{let g,h;if(n.target&&br(n.target))await this.browser.hoverUsingVisualCoordinates(n.target.pixels);else if(n.target&&n.target.elementDescriptor.trim()){let{elementInteractedDisplayString:E,thoughts:v}=await this.wrapElementTargetingCommand({ctx:e,tracer:t,command:n,target:n.target,cache:n.cache?.target,action:R=>this.browser.hover(R),options:{...n,targetName:"target",disableGlobalLocatorRedirect:!0,disableCache:i}});g=E,h=v}let f=this.browser.getViewport()?.height??tn.height,b=this.browser.getViewport()?.width??tn.width;switch(n.type){case"SCROLL_UP":await this.browser.scrollVertical(-(n.deltaY??f));break;case"SCROLL_DOWN":await this.browser.scrollVertical(n.deltaY??f);break;case"SCROLL_LEFT":await this.browser.scrollHorizontal(-(n.deltaX??b));break;case"SCROLL_RIGHT":await this.browser.scrollHorizontal(n.deltaX??b);break}return{succeedImmediately:!1,urlAfterCommand:this.browser.url(),elementInteracted:g,thoughts:h}}case"WAIT_FOR_URL":{if(n.timeout&&n.timeout>1800)throw new w("UserConfigurationError",`Wait for URL timeout of ${n.timeout} exceeds the maximum allowed value of 30 minutes.`);let g=n.matcher;await this.browser.waitForUrl({beforeUrl:this.browser.url(),matcher:g},{timeout:n.timeout?n.timeout*1e3:void 0,negated:n.negated,caseInsensitive:n.caseInsensitive});break}case"WAIT":if(n.delay>1800)throw new w("UserConfigurationError",`Wait timeout of ${n.delay} seconds exceeds the maximum allowed value of 30 minutes`);let s=n.delay*1e3;await X(s,this.executeAbortController.signal);break;case"REFRESH":await this.browser.refresh({loadTimeoutMs:n.loadTimeout?n.loadTimeout*1e3:void 0});break;case"CLICK":{if(br(n.target)){await this.browser.clickUsingVisualCoordinates(n.target.pixels,n);break}let g=this.browser.url(),{elementInteractedDisplayString:h,result:f,thoughts:b}=await this.wrapElementTargetingCommand({ctx:e,tracer:t,target:n.target,command:n,cache:n.cache?.target,action:v=>this.browser.click(v,this.createCallbacksForBrowser(this.orgId),n),options:{disableCache:i,targetName:"target",...n}}),E={urlAfterCommand:this.browser.url(),succeedImmediately:!1,elementInteracted:h,thoughts:b,data:f.downloadedFile?{downloadedFile:f.downloadedFile}:void 0};return nc(g,E.urlAfterCommand)&&(E.succeedImmediately=!0,E.succeedImmediatelyReason="URL changed"),E}case"COPY":return await this.browser.copy(n.value),{succeedImmediately:!1,data:n.value,urlAfterCommand:this.browser.url()};case"PASTE":{await this.browser.paste();break}case"DRAG":{if(br(n.fromTarget)&&br(n.toTarget)){await this.browser.dragAndDropUsingVisualCoordinates(n.fromTarget.pixels,n.toTarget.pixels,{hoverSeconds:n.hoverSeconds});break}if(br(n.fromTarget)||br(n.toTarget))throw new Error("Drag and drop targets must be both coordinates or both descriptions");let{elementInteractedDisplayStrings:g,thoughts:h}=await this.wrapMultiElementTargetingCommand({ctx:e,tracer:t,command:n,targetNames:["fromTarget","toTarget"],descriptions:[n.fromTarget,n.toTarget],caches:[n.cache?.fromTarget,n.cache?.toTarget],action:(f,b)=>this.browser.dragAndDrop(f.locator,b.locator,{hoverSeconds:n.hoverSeconds,steps:n.steps}),options:{useSelector:!!n.useSelector,disableCache:i}});return{succeedImmediately:!1,urlAfterCommand:this.browser.url(),elementInteracted:g[0],thoughts:h}}case"MOUSE_DRAG":{let g=parseInt(n.deltaX),h=parseInt(n.deltaY),f=n.steps??5;if(isNaN(g)||isNaN(h))throw new w("ActionFailureError",`Invalid pixel values passed to mouse drag command: (${n.deltaX}, ${n.deltaY})`);if(n.target&&br(n.target)){await this.browser.mouseDragUsingVisualCoordinates(g,h,f,n.target.pixels,{force:n.force});break}let b,E,v;if(n.target?.elementDescriptor){let{elementInteractedDisplayString:R,result:T,thoughts:_}=await this.wrapElementTargetingCommand({ctx:e,tracer:t,command:n,target:n.target,cache:n.cache?.target,action:async M=>M.locator,options:{disableCache:i,targetName:"target",...n}});b=T,E=R,v=_}return await this.browser.mouseDrag(g,h,f,b,{force:n.force}),{succeedImmediately:!1,urlAfterCommand:this.browser.url(),elementInteracted:E,thoughts:v}}case"SELECT_OPTION":{if(!Yr(n.target))throw new Error("Select with x/y is not supported yet");let g=n.target.elementDescriptor,h=n.choice,{elementInteractedDisplayString:f,thoughts:b}=await this.wrapElementTargetingCommand({ctx:e,tracer:t,command:n,target:{type:"description",elementDescriptor:g},cache:n.cache?.target,action:E=>this.browser.selectOption(E,h,n.force),options:{...n,targetName:"target",disableCache:i,source:Vi(n)}});return{succeedImmediately:!1,urlAfterCommand:this.browser.url(),elementInteracted:f,thoughts:b}}case"TAB":{let g={loadTimeoutMs:n.loadTimeout?n.loadTimeout*1e3:void 0,retry:!0};await this.browser.switchToPage(n.action,g);break}case"NEW_TAB":await this.browser.createNewTab(n.url,{loadTimeoutMs:n.loadTimeout?n.loadTimeout*1e3:void 0});break;case"COOKIE":if(!n.value)break;let u=await this.browser.setCookie(n.value);a.debug({results:u},"Set cookies");break;case"LOCAL_STORAGE":if(!n.value||!n.key)break;await this.browser.setLocalStorage(n.key,n.value);break;case"JAVASCRIPT":{let g;try{n.environment==="BROWSER"?(g=await this.browser.evaluateCodeInPage({code:n.code,fragment:n.fragment??!1,context:o.toObjectCopy(),timeoutMs:n.timeout?n.timeout*1e3:void 0}),a.info({result:g},"Executed JavaScript in browser")):g=await Ir({orgId:this.orgId,code:n.code,fragment:!!n.fragment,context:o,timeoutMs:n.timeout?n.timeout*1e3:void 0,logger:a,localTools:this.localCodeEvalTools,signal:this.executeAbortController.signal,callbacks:{onPersistentVariableUpdates:async h=>{if(!this.options?.scratchPadId){a.warn({updates:h},"Got persistent variable updates but scratch pad is not available");return}await this.storage.savePersistentVariables?.({scratchPadId:this.options?.scratchPadId,orgId:this.orgId,updates:h,logger:a})}}})}catch(h){throw this.throwIfClosed(),new w("ActionFailureError",h instanceof Error?h.message:`${h}`,{errOptions:{cause:h}})}try{JSON.stringify(g)}catch(h){throw new w("ActionFailureError",`Return value is not serializable: ${h instanceof Error?h.message:`${h}`}`,{errOptions:{cause:h}})}return{urlAfterCommand:this.browser.url(),succeedImmediately:!1,data:g}}case"TYPE":{if(n.target&&br(n.target)){await this.browser.clickUsingVisualCoordinates(n.target.pixels,n),await this.browser.type(n.value,{force:n.force,clearContent:n.clearContent,forceClearContent:n.forceClearContent,delay:n.delay,pressEnter:n.pressEnter},!0);break}let g=this.browser.url(),h,f,b=Tw(n.target),E=this.browser.userBrowserSettings.globalLocatorRedirect===void 0||this.browser.userBrowserSettings.globalLocatorRedirect==="always";if(b){let{elementInteractedDisplayString:R,thoughts:T}=await this.wrapElementTargetingCommand({ctx:e,tracer:t,command:n,target:b,cache:n.cache?.target,action:_=>this.browser.typeIntoTarget(n.value,_,{force:n.force,clearContent:n.clearContent,forceClearContent:n.forceClearContent,delay:n.delay,pressEnter:n.pressEnter,relativePosition:n.relativePosition}),options:{...n,targetName:"target",disableCache:i,disableGlobalLocatorRedirect:!E,source:Vi(n)}});h=R,f=T}else await this.browser.type(n.value,{force:n.force,clearContent:n.clearContent,forceClearContent:n.forceClearContent,delay:n.delay,pressEnter:n.pressEnter},!0);let v={urlAfterCommand:this.browser.url(),succeedImmediately:!1,elementInteracted:h,thoughts:f};return nc(g,v.urlAfterCommand)&&(v.succeedImmediately=!0,v.succeedImmediatelyReason="URL changed"),v}case"HOVER":{if(br(n.target)){await this.browser.hoverUsingVisualCoordinates(n.target.pixels);break}let{elementInteractedDisplayString:g,thoughts:h}=await this.wrapElementTargetingCommand({ctx:e,tracer:t,command:n,target:n.target,cache:n.cache?.target,action:f=>this.browser.hover(f),options:{...n,targetName:"target",disableCache:i}});return{succeedImmediately:!1,urlAfterCommand:this.browser.url(),elementInteracted:g,thoughts:h}}case"FOCUS":{if(!Yr(n.target))throw new Error("Focus with x/y is not supported yet");let{elementInteractedDisplayString:g,thoughts:h}=await this.wrapElementTargetingCommand({ctx:e,tracer:t,command:n,target:n.target,cache:n.cache?.target,action:f=>this.browser.focus(f),options:{...n,targetName:"target",disableCache:i}});return{succeedImmediately:!1,urlAfterCommand:this.browser.url(),elementInteracted:g,thoughts:h}}case"BLUR":{if(n.target&&!Yr(n.target))throw new Error("Blur with x/y is not supported yet");if(!n.target||!n.target.elementDescriptor)return await this.browser.blur(null),{succeedImmediately:!1,urlAfterCommand:this.browser.url()};let{elementInteractedDisplayString:g,thoughts:h}=await this.wrapElementTargetingCommand({ctx:e,tracer:t,target:n.target,command:n,cache:n.cache?.target,action:f=>this.browser.blur(f),options:{...n,targetName:"target",disableCache:i}});return{succeedImmediately:!1,urlAfterCommand:this.browser.url(),elementInteracted:g,thoughts:h}}case"PRESS":let d=this.browser.url();await this.browser.press(n.value,{repeat:n.repeat,convertMeta:n.convertMeta??!0,delayMs:n.delayMs});let p={urlAfterCommand:this.browser.url(),succeedImmediately:!1};return nc(d,p.urlAfterCommand)&&(p.succeedImmediately=!0,p.succeedImmediatelyReason="URL changed"),p;case"KEY_DOWN":return await this.browser.keyDown(n.value,{convertMeta:n.convertMeta??!0}),{urlAfterCommand:this.browser.url(),succeedImmediately:!1};case"KEY_UP":return await this.browser.keyUp(n.value,{convertMeta:n.convertMeta??!0}),{urlAfterCommand:this.browser.url(),succeedImmediately:!1};case"REQUEST":{let g=new NU,h=LU(fetch,g),f;try{f=new URL(n.url).hostname}catch{}return{data:{...await Tc({command:n,baseUrl:this.browser.baseUrl,logger:a,fetchImplementation:h}),cookies:Is(g,f)},succeedImmediately:!1,urlAfterCommand:this.browser.url()}}case"GRAPHQL_REQUEST":return{data:await Ew({command:n,baseUrl:this.browser.baseUrl,logger:a}),succeedImmediately:!1,urlAfterCommand:this.browser.url()};case"VISUAL_DIFF":return fw({ctx:e,tracer:t,command:n,disableCache:i,browser:this.browser,logger:a,storage:this.storage,screenshotStorage:this.visualDiffScreenshotStorage,targetingWrapper:g=>this.wrapElementTargetingCommand(g)});case"FILE_UPLOAD":{let g,h;if(n.fileSource.type==="URL"?(h=n.fileSource.url,g=await Kv({uri:n.fileSource.url,logger:a,orgId:this.orgId})):n.fileSource.type==="USER_FILE"&&(h=n.fileSource.name,g=await this.uploadedFileStorage?.getFileForUpload(n.fileSource.name,this.orgId)),!g)throw new w("UserConfigurationError",`Attempted to use non-existent file for upload step: ${h}`);await this.browser.setFileChooserHandler({...g,filename:n.filename});break}case"AUTH_SAVE":return{data:await this.browser.saveAuthState(),succeedImmediately:!1,urlAfterCommand:this.browser.url()};case"AUTH_LOAD":{let g;if(!n.storageState.trim())g=void 0;else if(g=await Ir({orgId:this.orgId,code:n.storageState,fragment:!1,context:o,logger:a,localTools:this.localCodeEvalTools,signal:this.executeAbortController.signal}),typeof g!="object")throw new w("ActionFailureError",`Credentials must evaluate to an object (received ${typeof g} instead)`);let h;try{h=Gf.optional().parse(g)}catch(f){throw new w("ActionFailureError",`Credentials provided do not follow the required format: ${f}`)}await this.browser.loadAuthState(h);break}case"ELEMENT_CHECK":{let g=(n.timeout??Xr)*1e3,h=this.generator.getAgentConfig()?.assertion;if(gw(n.assertion)&&!n.useSelector&&n.target.type==="description"&&h&&h!=="v1"){let b={id:n.id,type:"AI_ASSERTION",assertion:`There is no element on the page closely matches the following description. If the description has single quotes, remember that requires an exact text substring match. Description: ${n.target.elementDescriptor}`,iframeUrl:n.iframeUrl,timeout:n.timeout,cache:n.cache&&"memory"in n.cache?{memory:n.cache?.memory}:void 0};try{let E=await bc({command:b,logger:a,aiPageFiltering:!!this.options?.aiPageFiltering,fixtures:this.getControllerFixtures(e),useMemory:this.shouldUseMemory(),source:"NEGATED_CHECK"});return{succeedImmediately:!1,thoughts:`The element described does not exist on the page: ${E.thoughts}`,urlAfterCommand:this.browser.url(),afterScreenshotOverride:E.afterScreenshotOverride}}finally{b.cache?.memory&&Jl(n,b.cache?.memory.traces,a)}}let f=await mw({command:n,tracer:t,timeoutMs:g,targetingWrapper:b=>this.wrapElementTargetingCommand(b),fixtures:this.getControllerFixtures(e),disableCache:i});return{fail:!f.success,data:f.data,elementInteracted:f.elementInteractedDisplayString,thoughts:f.err?.message??f.thoughts??`Element assertion ${f.success?"succeeded":"failed"}.`,succeedImmediately:!1,urlAfterCommand:this.browser.url()}}case"PAGE_CHECK":{let g=await Dr({action:async()=>bw({assertion:n.assertion,browser:this.browser,logger:a,timeout:n.timeout,signal:this.executeAbortController.signal,autoExpandIframes:!!this.browser.userBrowserSettings.autoExpandIframes}),frameConfig:n.iframeUrl?{type:"url",url:n.iframeUrl}:void 0,browser:this.browser,logger:a});return{fail:!g.success,data:g.data,thoughts:g.success?"Page assertion passed.":g.err?.message??`Page assertion still failing after ${n.timeout} seconds.`,urlAfterCommand:this.browser.url(),succeedImmediately:!1}}case"REGISTER_REQUEST_LISTENER":{let g=new En(n.requestMatcher),h=this.browser.registerRequestListener(g);return this.registeredListeners[n.key]=h.then(async f=>await im(f)).catch(f=>{a.error({err:f},"Failed to get request listener response")}),{succeedImmediately:!1,urlAfterCommand:this.browser.url()}}case"AWAIT_LISTENER":{let g=this.registeredListeners[n.key];if(!g)throw new w("ActionFailureError",`No listener registered with key: ${n.key}`);let h=n.timeout??10;return{data:await B(g,{milliseconds:h*1e3,message:`Request listener timed out after ${h} seconds`}),succeedImmediately:!1,urlAfterCommand:this.browser.url()}}case"RECORD_REQUESTS":{let g=new En(n.requestMatcher);return this.recordedRequests[n.key]={},this.browser.registerRequestRecorder(n.key,g,{onRequestStart:(h,f)=>{this.recordedRequests[n.key][h]=lc(f)},onRequestComplete:(h,f)=>{this.recordedRequests[n.key][h]=lc(f)}}),{succeedImmediately:!1,urlAfterCommand:this.browser.url()}}case"GET_RECORDED_REQUESTS":{let g=this.recordedRequests[n.key];if(!g)throw new w("ActionFailureError",`No recorder registered with key: ${n.key}`);return delete this.recordedRequests[n.key],{data:Object.values(g),succeedImmediately:!1,urlAfterCommand:this.browser.url()}}case"SET_HEADER":{let g;return n.requestMatcher&&(g=new En(n.requestMatcher)),this.browser.setHeader(n.name,n.value,g),{succeedImmediately:!1,urlAfterCommand:this.browser.url()}}case"MOCK_ROUTE":return{data:{key:this.browser.registerMock(n.key,new En(n.requestMatcher),async(h,f)=>{let b=await Ir({orgId:this.orgId,code:n.responseGenerator,fragment:!1,context:o,timeoutMs:void 0,logger:a,localTools:this.localCodeEvalTools,mock:{request:h,response:f},disallowVariableUpdates:!0,responseSerialization:"RESPONSE"}),E=rS.parse(b);return new Response(E.body,{status:E.status,headers:E.headers})},n.fetchOriginalResponse??!1)},succeedImmediately:!1,urlAfterCommand:this.browser.url()};case"REMOVE_ROUTE_MOCK":return this.browser.removeMock(n.key),{succeedImmediately:!1,urlAfterCommand:this.browser.url()};case"OFFLINE_MODE":return await this.browser.setOfflineMode(n.enable),{succeedImmediately:!1,urlAfterCommand:this.browser.url()};default:return(g=>{throw"If Typescript complains about the line below, you missed a case or break in the switch above"})(n)}return{succeedImmediately:!1,urlAfterCommand:this.browser.url()}}async getReverseMappedDescription({browserState:e,targetId:t,disableCache:n,screenshot:o}){return(await this.generator.getReverseMappedDescription({browserState:e,target:t,screenshot:o},{disableCache:n,abortSignal:this.executeAbortController.signal,loggerTags:pe(this.logger)})).phrase}async stopRecordMode(){this.recordAbortController?.abort(),await this.browser.clearAllCdpHighlights()}async startRecordMode({params:e,abortController:t,isClickToRecord:n}){this.recordAbortController=t;let o=new gc({signal:t.signal,...e});return await this.browser.startRecording(this.recordAbortController.signal,o,n),o}async runSectionAutohealing(e){return this.generator.getAutohealingProposal(e,{disableCache:!0,abortSignal:this.executeAbortController.signal,loggerTags:pe(this.logger)})}async getFailureRecoveryPlan(e){return this.generator.getFailureRecoveryPlan(e,{disableCache:!0,abortSignal:this.executeAbortController.signal,loggerTags:pe(this.logger)})}};import{cloneDeep as DU}from"lodash-es";import Cw from"truncate-json";var vw=1e3,Aw=5e6,kU=5*1024*1024;function xw(r,e){for(let t=0;t<r.length;t++){let n=r[t];try{if(n.data){let{jsonString:o}=Cw(JSON.stringify(n.data),1e3);n.data=JSON.parse(o)}}catch(o){e.error({err:o},"Failed to serialize individual result output data"),n.data=`Result output data could not be serialized: ${o}`}switch(n.type){case"MOBILE_PRESET_STEP":ww(n);break;case"MOBILE_MODULE_STEP":ww(n),xw(n.steps,e);break;default:return(()=>{throw new Error("If Typescript complains about the line below, you missed a case or break in the switch above")})()}}}function ww(r){if(r.type==="MOBILE_PRESET_STEP"){let e=r.command;"cache"in e&&e.cache&&(e.cache=void 0)}}function Rw(r,e){let t=JSON.stringify(r),n=t.replaceAll("\\u0000","");if(t.length!==n.length){let o=t.indexOf("\\u0000");e.warn({input:t.slice(Math.max(0,o-500),Math.min(t.length,o+500))},"Database content violation: stripped unicode character from input")}return n}function Ac(r,e){let t=DU(r);if(xw(t,e),t.length>vw)return e.error("Database content violation: results too long, truncating before insertion"),t.slice(0,vw);let n=Rw(t,e);if(n.length>Aw)for(e.error({serializedLength:n.length,resultsArrayLength:t.length},"Database content violation: results too large, truncating before insertion");n.length>Aw;)t.pop(),n=Rw(t,e);let{jsonString:o}=Cw(n,kU);try{return tr.array().parse(JSON.parse(o))}catch(i){throw e.error({serialized:n,err:i},"Could not parse serialized results into JSON structure after processing"),i}}import{AsyncLocalStorage as UU}from"async_hooks";var za=new UU;function FU(r){za.enterWith({activeTracers:[r]})}function BU(r,e){let t=za.getStore()?.activeTracers;if(!t)return e();t.push(r);try{return e()}finally{t.pop()}}async function zU(r,e){let t=za.getStore()?.activeTracers;if(!t)return e();let n=[...t,r];return za.run({activeTracers:n},e)}var $r={globalAls:za,initializeRootTracerContext:FU,withChildTracer:BU,withChildTracerAsync:zU};var oo=class r{spans;parentSection;finished=!1;startTime;endTime;constructor(e){this.startTime=e?.startTime??Date.now(),this.spans=e?.subSpans??[],this.parentSection=e}startSection(e,t){let n={type:"SECTION",name:e,startTime:Date.now(),endTime:void 0,subSpans:[],attributes:{}},o=new r(n);try{return $r.withChildTracer(o,()=>t(o,n))}catch(i){throw n.error=i instanceof Error?i.message:String(i),i}finally{o.finish(),this.addSpan(n)}}async startAsyncSection(e,t,n){let o={type:"SECTION",name:e,startTime:Date.now(),endTime:void 0,subSpans:[],attributes:{}},i=new r(o);this.addSpan(o);try{let a;return n?.signal||n?.timeoutMs?a=await $r.withChildTracerAsync(i,()=>B(t(i,o),{milliseconds:n?.timeoutMs??1/0,signal:n?.signal})):a=await $r.withChildTracerAsync(i,()=>t(i,o)),a}catch(a){throw o.error=a instanceof Error?a.message:String(a),a}finally{i.finish()}}finish(){if(!this.finished){this.endTime=Date.now();for(let e of this.spans)e.endTime||(e.endTime=this.endTime,e.durationMs=e.endTime-e.startTime);this.parentSection&&(this.parentSection.endTime=this.endTime,this.parentSection.durationMs=this.parentSection.endTime-this.parentSection.startTime),this.finished=!0}}addSpan(e){this.spans.push(e)}startSpan(e,t,...n){let o={type:e,startTime:Date.now(),endTime:void 0,attributes:{}},i=n[0]??void 0;Object.assign(o,i??{}),this.addSpan(o);let a;try{a=t(o),o.endTime=Date.now(),o.durationMs=o.endTime-o.startTime}catch(l){throw o.error=l instanceof Error?l.message:String(l),o.endTime=Date.now(),o.durationMs=o.endTime-o.startTime,l}return a}async startAsyncSpan(e,t,...n){let o={type:e,startTime:Date.now(),endTime:void 0,attributes:{}},i=n[0]??void 0;Object.assign(o,i??{}),this.addSpan(o);let a;try{i?.signal||i?.timeoutMs?a=await B(t(o),{milliseconds:i?.timeoutMs??1/0,signal:i?.signal}):a=await t(o),o.endTime=Date.now(),o.durationMs=o.endTime-o.startTime}catch(l){throw o.error=l instanceof Error?l.message:String(l),o.endTime=Date.now(),o.durationMs=o.endTime-o.startTime,l}return a}getRootSpan(){return this.finished||this.finish(),{type:"SECTION",name:"root step span",startTime:this.startTime,endTime:this.endTime,subSpans:this.spans,attributes:{},durationMs:this.endTime?this.endTime-this.startTime:void 0}}};function Re(){let r=$r.globalAls.getStore()?.activeTracers,e;return!r||r.length===0?e=void 0:e=r[r.length-1],e||new oo}import{mkdirSync as nF}from"fs";import{tmpdir as oF}from"os";import Dw from"path";import{diff as tF}from"deep-object-diff";import{cloneDeep as rF}from"lodash-es";import Iw from"fontoxpath";import HU from"@prettier/plugin-xml";import GU from"prettier";import{DOMParser as VU,XMLSerializer as jU}from"slimdom";function Im(r){return r.toLowerCase().endsWith("webview")}function WU(r){let e=["android.widget.","android.view.","android.webkit.","android.app.","android.support.","androidx.","com.android.inputmethod."];for(let t of e)if(r.startsWith(t))return r.substring(t.length);return r}var $U=new Set(["index","package","a11y-important","screen-reader-focusabl"]),qU=new Set(["selected","checked","checkable","clickable","enabled","focusable","focused","long-clickable","password","scrollable","selected","showing-hint","context-clickable","multiline","text-entry-key","heading","dismissable","screen-reader-focusable","content-invalid","a11y-focused"]),KU=new Set(["text","hint"]),YU=new Set(["live-region","drawing-order"]),XU=new Set(["displayed","enabled"]);function JU(r,e){let t={};for(let[n,o]of Object.entries(e))$U.has(n)||n==="class"&&r===o||n==="focusable"&&o==="true"&&e.clickable==="true"||qU.has(n)&&o==="false"||KU.has(n)&&o===""||XU.has(n)&&o==="true"||YU.has(n)&&o==="0"||n!=="id"&&(t[n]=o);return t}function Mw(r,e,t){let{prunedDocument:n,idToElement:o,prunedIdToElement:i,idCounter:a,opts:l}=r,c=a.value++;t.setAttribute("id",String(c));let s={};for(let p of e.attributes){let m=p.name,g=p.value;g!=null&&(s[m]=String(g))}let u=JU(e.tagName,s);for(let[p,m]of Object.entries(u))t.setAttribute(p,m);if(o.set(c,e),i.set(c,t),Im(e.tagName)){let p=l?.injectedWebviewContent??"";if(!l?.disableMomenticAccessibilityTree&&p.trim().length>0){for(;t.firstChild;)t.removeChild(t.firstChild);p.trim().length>0&&t.appendChild(n.createCDATASection(`
|
|
4024
4036
|
${p}
|
|
4025
|
-
`));return}}let d=Array.from(e.childNodes??[]);for(let p of d){let g=p.nodeType;if(g===3){let m=p.nodeValue;m&&m.trim().length>0&&t.appendChild(n.createTextNode(m));continue}if(g===1){let m=p,h=n.createElement(OF(m.tagName));$w(r,m,h),t.appendChild(h)}}}function BF(r,e,t,n){let o=r.parseFromString("<hierarchy/>","text/xml"),i=new Map,a={prunedDocument:o,idToElement:t,prunedIdToElement:i,idCounter:{value:0},opts:n},s=o.documentElement;$w(a,e,s);let c=new PF().serializeToString(o);return{prunedDocument:o,prunedIdToElement:i,xml:c}}async function qw(r,e){let t=new IF,n=t.parseFromString(r,"text/xml"),o=new Map,i=n.documentElement;if(!i)throw new Error("No root element found in XML");if(i.tagName!=="hierarchy")throw new Error("No hierarchy element found in XML");let{prunedDocument:a,prunedIdToElement:s,xml:c}=BF(t,i,o,e);return{xml:await MF.format(c,{parser:"xml",plugins:[_F],printWidth:120,tabWidth:1,singleAttributePerLine:!1}),originalXml:r,document:n,idToElement:o,prunedDocument:a,prunedIdToElement:s}}function zF(r){let e=[],t=r;for(;t;){let n=t.tagName,o=t.parentElement,i=1;if(o){let a=Array.from(o.children).filter(s=>s.tagName===n);for(let s=0;s<a.length;s++)if(a[s]===t){i=s+1;break}}e.unshift(`${n}[${i}]`),t=o}return`/${e.join("/")}`}function Dc(r,e){let t=r.idToElement.get(e);if(t)return zF(t)}function Wm(r,e){let t=r.idToElement.get(e);if(!t)return;let n=t.cloneNode(!0);for(let o of Array.from(n.children)){let i=o;for(let a of Array.from(i.children))i.removeChild(a)}return n.outerHTML}function Uc(r){if(!r.hasAttribute("bounds"))return;let e=r.getAttribute("bounds");if(!e)return;let t=e.match(/\[(\d+),(\d+)\]\[(\d+),(\d+)\]/);if(t){let n=parseInt(t[1],10),o=parseInt(t[2],10),i=parseInt(t[3],10),a=parseInt(t[4],10);if(Number.isFinite(n)&&Number.isFinite(o)&&Number.isFinite(i)&&Number.isFinite(a))return[n,o,i,a]}}function $m(r,e){if(r&&!(!e||e.length===0))return Object.fromEntries(e.map(t=>[t,r.getAttribute(t)]).filter(([,t])=>t!==null))}function Xw({aiResponse:r,description:e,emulatorState:t}){let n=t.graph.idToElement.get(r.id);if(!n)throw new Error(`Could not find node with id: ${r.id}`);let o=Uc(n);if(!o)throw new Error(`Node ${r.id} has no bounding box: ${n.outerHTML}`);let i=Dc(t.graph,r.id)??"",a=Wm(t.graph,r.id)??"",s=t.graph.idToElement.get(r.id),c=$m(s,r.requirements?.attributesRequired),u={requiredText:r.requirements?.textRequired?s?.getAttribute("text")??void 0:void 0,requiredAttributes:c,requiredBounds:r.requirements?.boundsRequired},d=[];r.additionalElements&&(d=r.additionalElements.map(({id:g,requirements:m})=>{let h=t.graph.idToElement.get(g);if(!h)return;let f=Dc(t.graph,g);return f?{xPath:f,requirements:{requiredText:m.textRequired?h.getAttribute("text")??void 0:void 0,requiredAttributes:$m(h,m.attributesRequired),requiredBounds:m.boundsRequired}}:void 0}).filter(g=>!!g));let p;return Vm(n.tagName)&&r.inWebview!==!1?p={type:"WEBVIEW",resolvedDescription:e,xPath:i}:p={type:"NATIVE",bounds:o,resolvedDescription:e,xPath:i,elementOnlySerializedXml:a,requirements:u,requiredRelatedElements:d},p}var Yw=(r,e,t)=>{if(!e)return;let{requiredAttributes:n,requiredText:o,requiredBounds:i}=e;if(o!==void 0){let a=r.getAttribute("text")??void 0;if(a!==o)throw new Error(`ActionFailureError: Resolved element text mismatch: expected ${o}, got ${a}`)}if(n)for(let[a,s]of Object.entries(n)){let c=r.getAttribute(a)??void 0;if(c!==s)throw new Error(`ActionFailureError: Attribute ${a} mismatch: expected ${s}, got ${c}`)}if(i&&t){let a=Uc(r);if(!a||a.length!==t.length)throw new Error("ActionFailureError: Resolved element has no bounds or unexpected bounds format");if(!a.every((c,l)=>c===t[l]))throw new Error(`ActionFailureError: Bounds changed from [${t.join(",")} ] to [${a.join(",")} ]`)}};async function Jw(r){let{target:e,domState:t}=r,{graph:n}=t,{document:o}=n,i=ze();if(e.type==="WEBVIEW")return HF(e,r);let a=Kw.evaluateXPathToFirstNode(e.xPath,o,null,null);if(!a)throw new Error(`ActionFailureError: Could not resolve cached target via XPath: ${e.xPath}`);if(e.requiredRelatedElements){let p=e.requiredRelatedElements;i.startSection("Validate related elements are similar enough to past runs",()=>{for(let g of p){let m=Kw.evaluateXPathToFirstNode(g.xPath,o);if(!m)throw new Error(`ActionFailureError: Required related element not found for XPath: ${g.xPath}`);Yw(m,g.requirements)}})}let s=Uc(a);if(!s)throw new Error("ActionFailureError: Resolved native element has no bounding box");Yw(a,e.requirements,e.bounds);let c;for(let[p,g]of n.idToElement.entries())if(g===a){c=p;break}let l=e.elementOnlySerializedXml,u=e.xPath;return c!==void 0&&(l=Wm(n,c)??l,u=Dc(n,c)??u),{resolvedTarget:{...e,bounds:s,elementOnlySerializedXml:l,xPath:u}}}async function HF(r,e){let{stateManager:t,logger:n,signal:o}=e,i=ze(),a=await t.getActiveWebview();if(!a||!a.browserController)throw new Error("No browser controller is attached to the requested webview");let s=a.browserController.browser;if(!r.browserCache)throw new Error("No browser target available on cache");let c=r.browserCache,l=await i.startAsyncSection("Resolve target in webview",()=>s.resolveTarget(null,c,{logger:n,signal:o}));return{resolvedTarget:{...r,controller:a.browserController,resolution:l}}}function qm(r){let{command:e,cacheKey:t="cache",targetName:n="target",updatedCache:o}=r;zl(e)&&(e[t]={...e[t],[n]:Bl.parse(o)},r.updatedWithAI&&(e[t].updatedAt=new Date))}function Zw(r){return r.type==="WEBVIEW"?{type:"WEBVIEW",resolvedDescription:r.resolvedDescription,xPath:r.xPath,browserCache:r.browserCache}:r}var cr=class{driver;stateManager;generator;logger;fixtures;aborter;orgId;constructor(e){this.stateManager=e.stateManager,this.generator=e.generator,this.driver=e.driver,this.logger=e.logger,this.fixtures=e.fixtures,this.aborter=e.aborter,this.orgId=e.orgId}async findElement({description:e,tracer:t}){await this.stateManager.waitForScreenshotStability({timeoutMs:5e3,signal:this.aborter.controller?.signal,reason:"Waiting for stability before locating an element with AI"});let n=await t.startAsyncSection("Get emulator state",async()=>{let c=await this.stateManager.getDomState(),l=await this.stateManager.getCurrentScreenshotPngString();return{emulatorState:c,screenshot:l}}),o;try{o=await t.startAsyncSpan("AI_LOCATOR_CALL",async c=>{let l=await this.generator.getElementLocation({description:e,screenXml:n.emulatorState.graph.xml,screenshot:n.screenshot},{logger:this.logger,loggerTags:ve(this.logger),abortSignal:this.aborter.controller?.signal});return c.result=l,l})}catch(c){throw this.throwIfAborted(),this.logger.error({err:c},"Failed to locate element"),new Error(`ActionFailureError: Failed to locate element: ${c instanceof Error?c.message:c}`)}if(o.id===-1)throw new Error(`ActionFailureError: No matching element found: ${o.thoughts}`);let i=Xw({aiResponse:o,description:e,emulatorState:n.emulatorState});if(i.type==="NATIVE")return t.addSpan({type:"TARGET_RESOLUTION",startTime:Date.now(),endTime:Date.now(),result:{serializedElement:i.elementOnlySerializedXml},attributes:{}}),{resolvedTarget:i,thoughts:o.thoughts};let{browserLocateResult:a,browserController:s}=await t.startAsyncSpan("TARGET_RESOLUTION",async c=>{let l=await this.stateManager.getActiveWebview();if(!l||!l.browserController)throw new Error("No browser controller is attached to the requested webview");let u=await l.browserController.locateElement({description:e,disableCache:!1,logger:this.logger});return c.result={serializedElement:u.target.nodeOnlySerializedHtml??"Unknown HTML element in webview"},{browserLocateResult:u,browserController:l.browserController}});return{resolvedTarget:{...i,controller:s,resolution:a.resolution,browserCache:a.target},thoughts:a.thoughts}}async wrapTargetingAction(e){let{action:t,description:n,command:o,cacheKey:i="cache",targetName:a="target",cacheIsInvalidAfterResolution:s,tracer:c}=e,l=i in o&&o[i]&&a in o[i]?o[i][a]:void 0,u=e.retriesWithAI??1,d=!1,p=jF(l),g;if(o.disableCache&&(this.logger.debug({command:o},"Cache explicitly disabled for command"),d=!0,p=void 0),s&&(d=!0,p=void 0),p&&p?.resolvedDescription!==n&&(this.logger.info({cache:p,description:n},"Cache description mismatch, clearing it automatically"),d=!0,p=void 0),!p){u--,this.logger.info({description:n,cacheBustedBeforeAction:d},"Prompting AI for a new element location");let h=await this.findElement({description:n,tracer:c});return g=h.thoughts,qm({command:o,cacheKey:i,targetName:a,updatedCache:h.resolvedTarget,updatedWithAI:!0}),{result:await t(h.resolvedTarget),thoughts:g}}let m;try{await this.stateManager.waitForScreenshotStability({timeoutMs:5e3,signal:this.aborter.controller?.signal,reason:"Waiting for stability before cache resolution"}),m=await c.startAsyncSection("Get emulator XML tree",async()=>await this.stateManager.getDomState());let h=await c.startAsyncSection("Resolve target cache",async(E,S)=>{let{resolvedTarget:A}=await Jw({target:p,domState:m,stateManager:this.stateManager,logger:this.logger}),C=Zw(A),T=GF(p,C);return this.logger.info({cacheDiffs:T},"Successfully resolved and updated target"),qm({command:o,cacheKey:i,targetName:a,updatedCache:C,updatedWithAI:!1}),S.attributes.serializedElement=A.type==="WEBVIEW"?A.browserCache?.nodeOnlySerializedHtml??"Unknown HTML element in webview":A.elementOnlySerializedXml,A}),f=await t(h);return p.type!=="WEBVIEW"&&St.increment("cache_target_resolution_v2",1,["outcome:hit","platform:native",`hasRequirements:${!!p.requirements}`,`hasAdditionalElements:${!!p.requiredRelatedElements?.length}`,`orgId:${this.orgId}`]),{result:f,thoughts:"Successfully executed preset action with cache."}}catch(h){if(p.type!=="WEBVIEW"&&St.increment("cache_target_resolution_v2",1,["outcome:miss","platform:native",`hasRequirements:${!!p.requirements}`,`hasAdditionalElements:${!!p.requiredRelatedElements?.length}`,`orgId:${this.orgId}`]),this.throwIfAborted(),u>0)return this.logger.warn({err:h},"Failed to resolve target cache, retrying with AI"),this.logger.debug({domState:m?.graph.originalXml},"Emulator state"),this.wrapTargetingAction({...e,cacheIsInvalidAfterResolution:!0,retriesWithAI:u-1});throw new Error(`ActionFailureError: ${h instanceof Error?h.message:h}`,{cause:h})}}constructPerformerParams(){return{stateManager:this.stateManager,generator:this.generator,driver:this.driver,logger:this.logger,fixtures:this.fixtures,aborter:this.aborter,orgId:this.orgId}}throwIfAborted(){this.aborter.controller?.signal.throwIfAborted()}};function $F(r){let e={relativePosition:r.relativePosition};if(r.doubleTap&&r.longPress)throw new Error("UserConfigurationError: Cannot specify both doubleTap and longPress");return r.doubleTap?{...e,doubleTap:!0,doubleTapDelayMs:r.doubleTapDelayMs}:r.longPress?{...e,longPress:!0,longPressDurationMs:r.longPressDurationMs}:e}var Si=class extends cr{async tapOnAbsoluteCoordinates(e){let t=e.x,n=e.y;if(this.logger.info({x:t,y:n},"Tap at coordinates"),e.longPress)return await this.driver.executeScript("mobile: longClickGesture",[{x:t,y:n,duration:e.longPressDurationMs??2e3}]);if(e.doubleTap){await this.driver.tap({x:t,y:n});let o=e.doubleTapDelayMs??100;await new Promise(i=>setTimeout(i,o))}await this.driver.tap({x:t,y:n})}async tapOnNativeTarget(e,t){let[n,o,i,a]=e.bounds,s=i-n,c=a-o,l=t?.relativePosition?.x??s/2,u=t?.relativePosition?.y??c/2;l=Math.max(0,Math.min(l,s)),u=Math.max(0,Math.min(u,c));let d=n+l,p=o+u;return await this.tapOnAbsoluteCoordinates({x:d,y:p,...t}),{x:d,y:p}}async tapOnWebviewTarget(e,t){let{controller:n}=e;return(await n.browser.click(e.resolution,{createIsolatedFolder:()=>{let i=Math.random().toString(36).substring(4),a=Qw.join(WF(),"momentic","downloads"),s=Qw.join(a,this.orgId,i);return VF(s,{recursive:!0}),s}},{delayMs:t?.longPress?t?.longPressDurationMs??2e3:void 0,relativePosition:t?.relativePosition,doubleClick:t?.doubleTap})).coordinates}async tapOnTarget({target:e,options:t}){return await ze().startAsyncSpan("EMULATOR_INTERACTION",async o=>{o.attributes.options=t,"type"in e&&e.type==="NATIVE"?o.attributes.point=await this.tapOnNativeTarget(e,t):(o.withinWebview=!0,o.attributes.point=await this.tapOnWebviewTarget(e,t))},{name:"Tap on target"})}async executeTap({command:e,tracer:t}){let n=$F(e);if(e.target.type==="coordinates"){let a=await this.driver.getWindowSize(),s=e.target.xPercent*a.width,c=e.target.yPercent*a.height;return await t.startAsyncSpan("EMULATOR_INTERACTION",async()=>{await this.tapOnAbsoluteCoordinates({...n,x:s,y:c})},{name:`Tap at coordinates ${s}, ${c}`}),{success:!0,message:`Tapped at ${s}, ${c}`}}let o=e.target.description,{thoughts:i}=await this.wrapTargetingAction({command:e,tracer:t,action:a=>this.tapOnTarget({target:a,options:n}),description:o});return{success:!0,message:i}}};var On=class extends cr{async doPress({keycode:e,longPress:t}){await ze().startAsyncSpan("EMULATOR_INTERACTION",async()=>this.driver.executeScript("mobile: pressKey",[{keycode:e,isLongPress:t}]),{name:"Send key events to emulator"})}};var Fc=class extends cr{async doType(e){if(!e.target){if(e.clearContent)throw new Error("UserConfigurationError: clearing content is only supported when a target is provided to the Type step");return await this.sendKeys(e),{success:!0,message:void 0}}if(e.target.type!=="description")throw new Error("UserConfigurationError: x/y targets are not supported for the Type step");let t=ze(),{thoughts:n}=await this.wrapTargetingAction({command:e,tracer:t,action:async o=>{"type"in o&&o.type==="NATIVE"?await this.doNativeType(e,o):await this.doWebviewType(e,o)},description:e.target.description});return{success:!0,message:n}}async doWebviewType(e,t){await ze().startAsyncSpan("EMULATOR_INTERACTION",async o=>{o.withinWebview=!0,o.attributes.options={clearContent:e.clearContent};let{controller:i}=t;await i.browser.type(e.text,{clearContent:e.clearContent,delay:e.keyPressDelayMs})},{name:"Typing within web view"})}async doNativeType(e,t){let n=new Si(this.constructPerformerParams());e.clearContent?(await n.tapOnNativeTarget(t,{longPress:!0}),await this.clearContent()):await n.tapOnNativeTarget(t),await this.stateManager.waitForScreenshotStability({timeoutMs:2e3,signal:this.aborter.controller?.signal,reason:"Waiting for keyboard to appear before typing"}),await this.sendKeys(e)}async sendKeys(e){let t=ze(),n=e.keyPressDelayMs;n?await t.startAsyncSpan("EMULATOR_INTERACTION",async()=>{await this.driver.updateSettings({keyInjectionDelay:n}),await this.driver.keys(e.text),await this.driver.updateSettings({keyInjectionDelay:0})},{name:"Typing keys with a delay"}):await t.startAsyncSpan("EMULATOR_INTERACTION",async()=>{await this.driver.keys(e.text)},{name:"Typing keys"})}async clearContent(){let e=ze();try{await e.startAsyncSection("Clearing any content from the focused field",()=>this.clearContentHelper())}catch(t){this.logger.warn({err:t},"Failed to clear content because the select all button was not found, continuing...")}}async clearContentHelper(){let e=this.driver.$('//android.widget.LinearLayout[@content-desc="Select all" and @clickable="true"]');await e.waitForExist({timeout:750}),await e.click(),await new On(this.constructPerformerParams()).doPress({keycode:67})}};import Gt from"zod";var eR=.9,qF=Gt.object({navigationBar:Gt.object({visible:Gt.boolean(),x:Gt.number(),y:Gt.number(),width:Gt.number(),height:Gt.number()}),statusBar:Gt.object({visible:Gt.boolean(),x:Gt.number(),y:Gt.number(),width:Gt.number(),height:Gt.number()})}),Bc=class extends cr{async executeSwipe(e){let t=ze();if(e.scrollableElement.type!=="CUSTOM"){await this.stateManager.waitForScreenshotStability({timeoutMs:2e3,signal:this.aborter.controller?.signal,reason:"Waiting for screen to stabilize before swiping"});let n=await this.driver.getWindowRect(),o;if(e.scrollableElement.type==="SCREEN")o={left:n.x+25,top:n.y+50,width:n.width-50,height:n.height-100};else try{let i=qF.parse(await this.driver.executeScript("mobile: getSystemBars",[]));o={left:n.x+25,top:n.y+50,width:n.width-50,height:n.height-100},i.navigationBar.visible&&(o.height-=i.navigationBar.height),i.statusBar.visible&&(o.top+=i.statusBar.height,o.height-=i.statusBar.height)}catch(i){this.logger.warn({err:i},"Failed to get system bars, using hardcoded bounds"),o={left:n.x+50,top:n.y+100,width:n.width-100,height:n.height-200}}return await t.startAsyncSpan("EMULATOR_INTERACTION",async i=>{await this.swipeByAbsoluteCoordinates({span:i,direction:e.direction,percent:e.viewportPercent,durationMs:e.durationMs,containerBounds:o})},{name:`Swipe ${e.direction} in the entire ${e.scrollableElement.type.toLowerCase()}`}),{success:!0}}return await this.wrapTargetingAction({command:e,description:e.scrollableElement.target.description,action:async n=>ze().startAsyncSpan("EMULATOR_INTERACTION",async i=>"type"in n&&n.type==="NATIVE"?this.scrollInNativeContainer({span:i,cmd:e,target:n}):(i.withinWebview=!0,this.scrollInWebview({cmd:e,target:n})),{name:`Swipe ${e.direction} in the specified container`}),tracer:t}),{success:!0}}async scrollInNativeContainer({span:e,cmd:t,target:n}){let o=Math.floor(n.bounds[2]*.05),i=Math.floor(n.bounds[3]*.05);await this.swipeByAbsoluteCoordinates({span:e,direction:t.direction,percent:t.viewportPercent,durationMs:t.durationMs,containerBounds:{left:n.bounds[0]+o,top:n.bounds[1]+i,width:n.bounds[2]-n.bounds[0]-o*2,height:n.bounds[3]-n.bounds[1]-i*2}})}async scrollInWebview({cmd:e,target:t}){let{controller:n}=t,o=n.browser.getViewport();if(!o)throw new Error("Failed to get viewport size from webview");if(e.direction==="down"||e.direction==="up"){let i=o.height*(e.viewportPercent??eR)*(e.direction==="down"?1:-1);await n.browser.scrollVertical(i)}else{let i=o.width*(e.viewportPercent??.9)*(e.direction==="right"?1:-1);await n.browser.scrollHorizontal(i)}}async swipeByAbsoluteCoordinates({span:e,direction:t,percent:n=eR,durationMs:o=500,containerBounds:i}){e.attributes.containerBounds=i;let a,s;t==="up"||t==="down"?(a=i.height*n,s=Math.floor(a/(o/1e3))):(a=i.width*n,s=Math.floor(a/(o/1e3))),e.attributes.pixelDelta=a,e.attributes.pixelsPerSecond=s,await this.driver.executeScript("mobile: swipeGesture",[{...i,direction:t,percent:n,speed:s}])}};import{existsSync as KF,readFileSync as YF}from"fs";import XF from"zod";var JF=XF.string().url();async function tR(r){if(JF.safeParse(r).success){let e=new AbortController,t=setTimeout(()=>e.abort(),1e4),n;try{n=await fetch(r,{signal:e.signal})}catch(i){throw new Error(`Fetch failed or timed out for URL: ${r}`,{cause:i})}finally{clearTimeout(t)}if(!n.ok)throw new Error(`Failed to fetch file from URL: ${r}, status: ${n.status}`);let o=await n.arrayBuffer();return Buffer.from(o).toString("base64")}if(!KF(r))throw new Error(`File does not exist at path: ${r}`);return YF(r).toString("base64")}import{execSync as nR}from"child_process";import QF from"pixelmatch";import{_android as eB,chromium as tB}from"playwright";import{PNG as oR}from"pngjs";import{z as Ve}from"zod";var rR=Ve.array(Ve.object({proc:Ve.string(),webview:Ve.string(),info:Ve.object({"Android-Package":Ve.string(),Browser:Ve.string(),"Protocol-Version":Ve.string(),"User-Agent":Ve.string(),"V8-Version":Ve.string(),"WebKit-Version":Ve.string(),webSocketDebuggerUrl:Ve.string()}),pages:Ve.array(Ve.object({description:Ve.string(),devtoolsFrontendUrl:Ve.string(),id:Ve.string(),title:Ve.string(),type:Ve.string(),url:Ve.string(),webSocketDebuggerUrl:Ve.string()})),webviewName:Ve.string()}));var zc=class r{driver;device;currentContext;logger;webviews=new Map;fixtures;orgId;options;aborter;constructor({driver:e,context:t,logger:n,device:o,fixtures:i,orgId:a,options:s,aborter:c}){this.driver=e,this.device=o,this.currentContext=t,this.logger=n,this.fixtures=i,this.orgId=a,this.options=s,this.aborter=c;for(let l of["SIGINT","SIGTERM"])process.on(l,async()=>{await this.cleanupWebviews(),setImmediate(()=>{setTimeout(()=>{process.exit(1)},2e3).unref()})})}static async init({driver:e,logger:t,fixtures:n,orgId:o,adbPort:i,options:a,aborter:s}){let c=await e.getContext(),l=typeof c=="string"?c:c.id,u=(await eB.devices()).filter(g=>g._initializer?.serial?.endsWith(i.toString()));if(u.length!==1)throw new Error(`Playwright detected ${u.length} Android devices, expected 1. Please stop all other emulators and try again.`);let d=u[0];return new r({driver:e,context:l,logger:t,device:d,fixtures:n,orgId:o,options:a,aborter:s})}async getContexts(){let e=await this.driver.getContexts({}),t=Array.from(this.webviews.values());return{contexts:e,webviews:t.map(n=>({contextId:n.contextId,packageName:n.packageName,active:n.active,hasPlaywright:!!n.browserController,lastSeen:n.lastSeen,socketName:n.socketName}))}}async getRawScreenshotBase64(){return await ze().startAsyncSpan("EMULATOR_READ_STATE",()=>this.driver.takeScreenshot(),{name:"Emulator screenshot",signal:this.aborter.controller?.signal})}async getCurrentScreenshotPngString(){return`data:image/png;base64,${await this.getRawScreenshotBase64()}`}async waitForScreenshotStability({timeoutMs:e,signal:t,reason:n,tolerancePercent:o=1}){await ze().startAsyncSpan("WAIT_FOR_STABILITY",async i=>{let a=Date.now(),s,c=!1,l=(u,d)=>{let p=Buffer.from(u,"base64"),g=Buffer.from(d,"base64"),m=oR.sync.read(p),h=oR.sync.read(g);if(m.width!==h.width||m.height!==h.height)return 100;let f=m.width,E=m.height,S=Buffer.alloc(f*E*4);return QF(m.data,h.data,S,f,E,{threshold:.01})/(f*E)*100};for(;Date.now()-a<e;){if(t?.throwIfAborted(),!s){s=await this.getRawScreenshotBase64();continue}let u=await this.getRawScreenshotBase64();if(l(s,u)<=o){c=!0;break}s=u,await ee(250,t)}c||(i.attributes.timedOut=!0,this.logger.warn({purpose:n},"Timed out waiting for screenshot stability"))},{reason:n})}async getActiveWebviewContent(){let e=await this.getActiveWebview();if(!e||!e.browserController)return;this.throwIfAborted();let t=e.browserController;return(await ze().startAsyncSpan("EMULATOR_READ_STATE",()=>t.getBrowserState({abortSignal:this.aborter.controller?.signal,serializationOpts:{noId:!0}}),{name:"Get webview content",signal:this.aborter.controller?.signal})).serializedTree}async getDomState(e){let t;if(!e?.skipWebviews)try{t=await this.getActiveWebviewContent()}catch(i){this.logger.error({err:i},"Could not get webview info to get the nested DOM state")}this.throwIfAborted();let n=await this.getPageSource();return{graph:await qw(n,{injectedWebviewContent:t,disableMomenticAccessibilityTree:this.options.disableMomenticAccessibilityTree}),context:this.currentContext}}async getPageSource(){return await ze().startAsyncSpan("EMULATOR_READ_STATE",()=>this.driver.getPageSource(),{name:"Get Android page source",signal:this.aborter.controller?.signal})}async refreshWebviews(){await this.getPageSource(),this.throwIfAborted();let e=await this.getDetailedContexts();if(!e){this.logger.warn("No context details, not proceeding with refreshing webviews");return}let t=Date.now(),n=new Set;for(let o of e){if(this.throwIfAborted(),o.webview==="NATIVE_APP")continue;let i=o.info["Android-Package"];if(n.add(o.webview),!this.webviews.has(o.webview)||!this.webviews.get(o.webview)?.active){let a={contextId:o.webview,packageName:i,active:!1,lastSeen:t,socketName:o.proc.startsWith("@")?o.proc.substring(1):o.proc};this.logger.info({contextId:a.contextId,packageName:a.packageName,socketName:a.socketName},"New webview detected"),this.webviews.set(o.webview,a);let s;if(i==="com.android.chrome"?(s=await this.connectPlaywrightToChrome(a),this.logger.info(`Connected Playwright to Android Chrome: ${o.webview}`)):(this.logger.info(`Attempting to connect Playwright to webview: ${o.webview}`),s=await this.connectPlaywrightToWebview(i,a.socketName),this.logger.info(`Connected Playwright to webview ${o.webview}`)),!s)continue;a.browserController=s,a.active=!0}}for(let[o,i]of this.webviews.entries())!n.has(o)&&i.active&&(this.logger.info(`Disconnecting dead webview ${o}`),this.disconnectPlaywrightFromWebview(i),i.active=!1)}async getActiveWebview(){await ze().startAsyncSection("Refresh webviews",async()=>{await this.refreshWebviews()});let e=await this.driver.execute("mobile: getCurrentPackage");e!==void 0&&typeof e!="string"&&this.logger.warn({currentPkg:e},"Unexpected getCurrentPackage result");let t=[];for(let n of this.webviews.values())n.packageName===e&&n.active&&t.push(n);if(t.length!==0){if(t.length>1)throw new Error("Multiple active webviews in a single package is currently not supported");return t[0]}}async executeRawADBCommand(e){let t=this.driver.capabilities,n=t.deviceUDID||t.udid||t["appium:udid"]||t["appium:deviceUDID"],o=process.env.ANDROID_HOME?`${process.env.ANDROID_HOME}/platform-tools/adb`:"adb",i=n?`-s ${n}`:"",a=`${o} ${i} ${e}`;this.logger.info(`Executing ADB command: ${a}`);let s=nR(a,{encoding:"utf8"});return this.logger.info(`ADB command result: ${s}`),s}async cleanupWebviews(){for(let[e,t]of this.webviews.entries())this.logger.info(`Disconnecting webview ${e}`),this.disconnectPlaywrightFromWebview(t),t.active=!1}async getDetailedContexts(){return await ze().startAsyncSpan("EMULATOR_READ_STATE",async()=>{let t=await this.driver.execute("mobile: getContexts");return this.aborter.controller?.signal.throwIfAborted(),rR.parse(t)},{name:"Get available contexts",signal:this.aborter.controller?.signal})}async createBrowserController({context:e}){let t=await qa.fromExistingContext({context:e,logger:this.logger,userBrowserSettings:{visualActions:!0},properties:{isNewHeadless:!0,allowedA11yIgnoreReasonsOverride:[],isAndroid:!0},storage:this.fixtures.storage,enricher:this.fixtures.browserEnricher});return new Nc({browser:t,generator:this.fixtures.browserGenerator,logger:this.logger,orgId:this.orgId,storage:this.fixtures.storage,localCodeEvalTools:this.fixtures.localCodeEvalTools,visualDiffScreenshotStorage:new nc})}async connectPlaywrightToWebview(e,t){return await ze().startAsyncSpan("EMULATOR_READ_STATE",async()=>this.connectPlaywrightToWebviewHelper(e,t),{name:"Connect headless browser client to webview",signal:this.aborter.controller?.signal})}async connectPlaywrightToWebviewHelper(e,t){let o=this.device.webViews().find(a=>!(a.pkg()!==e||"_socketName"in a&&typeof a._socketName=="string"&&a._socketName!==t));if(!o){this.logger.warn(`[WebviewManager] Could not find webview for ${e} with socket name ${t}`);return}return this.logger.info({packageName:e,socketName:t},"Connecting Playwright to app webview"),await this.createBrowserController({context:(await o.page()).context()})}async connectPlaywrightToChrome(e){return await ze().startAsyncSpan("EMULATOR_READ_STATE",async()=>this.connectPlaywrightToChromeHelper(e),{name:"Connect headless browser client to Chrome",signal:this.aborter.controller?.signal})}async connectPlaywrightToChromeHelper(e){let{contextId:t,socketName:n}=e;try{this.logger.info({contextId:t,socketName:n},"Connecting to Chrome webview");let o;e.forwardedPort?(o=`http://127.0.0.1:${e.forwardedPort}`,this.logger.info({contextId:t,endpoint:o,socketName:n},"Using existing forwarded port")):(o=`http://127.0.0.1:${await this.forwardDevToolsSocket(e.socketName)}`,this.logger.info({contextId:t,endpoint:o,socketName:n},`Forwarding DevTools socket for ${e.socketName}`)),this.logger.info({endpoint:o,socketName:n},"Connecting to CDP endpoint");let i=await tB.connectOverCDP({endpointURL:o,timeout:5e3}),a=i.contexts()[0];if(!a){this.logger.warn("No browser context available after CDP connection"),await i.close();return}return this.createBrowserController({context:a})}catch(o){this.logger.error({err:o},`Error connecting Playwright to webview ${e.contextId}`);return}}async disconnectPlaywrightFromWebview(e){try{e.browserController&&(this.logger.info(`Disconnecting Playwright from webview: ${e.contextId}`),await e.browserController.browser.cleanup(),e.browserController=void 0),e.forwardedPort&&await this.removeDevToolsForwarding(e.forwardedPort)}catch(t){this.logger.error({err:t},`Error disconnecting Playwright from webview ${e.contextId}:`)}}async forwardDevToolsSocket(e){this.logger.info("Setting up port forwarding for DevTools");let t=1e4+Math.floor(Math.random()*1e4),n=this.driver.capabilities,o=n.deviceUDID||n.udid||n["appium:udid"]||n["appium:deviceUDID"];this.logger.info({deviceId:o},`Device ID from capabilities: ${o||"not found"}`);let i=process.env.ANDROID_HOME?`${process.env.ANDROID_HOME}/platform-tools/adb`:"adb",a=o?`-s ${o}`:"",s=`${i} ${a} forward tcp:${t} ${`localabstract:${e}`||"localabstract:chrome_devtools_remote"}`;this.logger.info(`Executing command: ${s}`);let c=nR(s,{encoding:"utf8"});return this.logger.info(`ADB command result: ${c}`),this.logger.info(`Successfully forwarded DevTools socket to port ${t}`),t}async removeDevToolsForwarding(e){await this.executeRawADBCommand(`forward --remove tcp:${e}`),this.logger.info("Successfully removed port forwarding")}throwIfAborted(){this.aborter.controller?.signal.throwIfAborted()}};var yi=class r extends cr{options;appsWithGrantedPermissions=new Set;adbPort;constructor(e){super(e),this.options=e.options??{},this.adbPort=e.adbPort}static async init({driver:e,generator:t,logger:n,fixtures:o,orgId:i,options:a,abortController:s,adbPort:c}){let l={controller:s},u=await zc.init({driver:e,logger:n,fixtures:o,orgId:i,options:a?.emulator??{},aborter:l,adbPort:c}),d=new r({driver:e,generator:t,stateManager:u,logger:n,fixtures:o,options:a,aborter:l,orgId:i,adbPort:c});return await d.initializeSettings(),d}async installApp(e){await this.stateManager.executeRawADBCommand(`install ${nB.resolve(e)}`)}async executeCommand(e){let t=["type","a11yData","thoughts","cache","code"],n;try{n=await ac({obj:e.command,context:this.fixtures.testContext,bannedKeys:t,orgId:this.orgId,logger:this.logger,signal:this.aborter.controller?.signal,localTools:this.fixtures.localCodeEvalTools})}catch(o){throw this.throwIfAborted(),new Error(`ActionFailureError: Failed to substitute template strings in command: ${o.message}`,{cause:o})}try{return await this.executeCommandHelper(e)}catch(o){throw o.name!=="AbortError"&&this.logger.error({err:o},"Error thrown in action controller"),o}finally{sc(e.command,n)}}async executeCommandHelper({command:e,tracer:t}){switch(e.type){case"TAP":return new Si(this.constructPerformerParams()).executeTap({command:e,tracer:t});case"TYPE":return await new Fc(this.constructPerformerParams()).doType(e);case"AI_CHECK":{let o=e.timeoutSecs?e.timeoutSecs*1e3:5e3,i=mc(o),a=Date.now(),s=0,c,l=!1,u;for(;s<15&&!l;){this.throwIfAborted(),l||c&&c-a>=o&&(l=!0),s!==0&&await ee(i,this.aborter.controller?.signal),c=Date.now();try{let d="",p="";await t.startAsyncSpan("EMULATOR_READ_STATE",async()=>{d=(await this.stateManager.getDomState({})).graph.xml,p=await this.stateManager.getCurrentScreenshotPngString()},{name:"Get emulator state"});let g=await t.startAsyncSpan("AI_ASSERTION_CALL",async m=>{let h=await this.generator.evaluateAssertion({assertion:e.assertion,screenXml:d,screenshot:p},{logger:this.logger,loggerTags:ve(this.logger)});return m.result={thoughts:h.thoughts,result:h.result},h});if(g.result)return{success:g.result,message:g.thoughts};{let m=`AssertionFailureError: ${g.thoughts}`;u=new Error(m)}}catch(d){this.throwIfAborted(),this.logger.info({err:d},`AI check assert attempt ${s} failed, retrying...`),u=d instanceof Error?d:new Error(`${d}`)}finally{s++}}return{success:!1,message:u?.message}}case"SWIPE":return new Bc(this.constructPerformerParams()).executeSwipe(e);case"JAVASCRIPT":{let n=await kr({orgId:this.orgId,code:e.code,fragment:!1,context:this.fixtures.testContext,timeoutMs:e.timeout?e.timeout*1e3:void 0,logger:this.logger,localTools:this.fixtures.localCodeEvalTools,signal:this.aborter.controller?.signal});try{JSON.stringify(n)}catch(o){throw new Error(`UserConfigurationError: Return value is not serializable: ${o instanceof Error?o.message:`${o}`}`)}return{success:!0,output:n}}case"REQUEST":{let n;try{n=new URL(e.url).hostname}catch(l){throw new Error(`UserConfigurationError: Invalid URL: ${l}`)}let o=new oB,i=rB(fetch,o),a=Date.now(),s=await Lc({command:e,baseUrl:void 0,logger:this.logger,fetchImplementation:i}),c=Fl(o,n);return{output:{...s,cookies:c},success:!0,message:`Successfully executed request in ${Date.now()-a}ms`}}case"OPEN_NOTIFICATION_DRAWER":return await new On(this.constructPerformerParams()).doPress({keycode:83}),{success:!0};case"OPEN_APP":{let n=e.activityName;if(!n){let i=["resolve-activity","--brief","-a","android.intent.action.MAIN","-c","android.intent.category.LAUNCHER",e.packageName],a=await V(this.driver.execute("mobile: shell",{command:"pm",args:i}),{signal:this.aborter.controller?.signal,milliseconds:1e4});if(typeof a!="string")throw new Error(`Could not find main activity name for package ${e.packageName}. Unexpected output: ${a}`);if(a.includes("No activity found"))throw new Error(`No activity found for package ${e.packageName}.`);if(n=a.trim().split(`
|
|
4026
|
-
`).pop()?.replace(/^.*\//,""),!n)throw new Error(`Could not parse main activity name for package ${e.packageName}. Raw output: ${a}`)}if(this.options.emulator?.autoGrantPermissions&&!this.appsWithGrantedPermissions.has(e.packageName)){let i={permissions:"all",appPackage:e.packageName,action:"grant"};await this.driver.executeScript("mobile: changePermissions",[i]),this.appsWithGrantedPermissions.add(e.packageName)}let o=["start"];if(e.intentExtras)try{let i=JSON.parse(e.intentExtras);for(let[a,s]of Object.entries(i))o.push("-e",a,typeof s=="string"?s:JSON.stringify(s))}catch(i){throw new Error(`UserConfigurationError: Invalid intent extras does not parse as valid JSON: ${i instanceof Error?i.message:`${i}`}`)}return o.push("-n",`${e.packageName}/${n}`),await this.driver.execute("mobile: shell",{command:"am",args:o}),await this.stateManager.waitForScreenshotStability({timeoutMs:5e3,signal:this.aborter.controller?.signal,reason:"Waiting for stability after app launch"}),{success:!0}}case"PRESS":{let n=new On(this.constructPerformerParams());switch(e.key){case"HOME":await n.doPress({keycode:3});break;case"BACK":await n.doPress({keycode:4});break;case"APP_SWITCHER":await n.doPress({keycode:187});break;case"POWER":await n.doPress({keycode:26});break;case"SEARCH":await n.doPress({keycode:84});break;case"VOLUME_UP":await n.doPress({keycode:24});break;case"VOLUME_DOWN":await n.doPress({keycode:25});break;case"VOLUME_MUTE":await n.doPress({keycode:164});break}return{success:!0}}case"PRESS_KEYBOARD":{let n=new On(this.constructPerformerParams()),o=i=>n.doPress({keycode:i});switch(e.key){case"CLOSE_KEYBOARD":await this.driver.isKeyboardShown()&&await this.driver.hideKeyboard();break;case"ENTER":await o(66);break;case"BACKSPACE":await o(67);break;default:{let i=e}}return{success:!0}}case"WAIT":return await ee(e.timeoutSecs*1e3,this.aborter.controller?.signal),{success:!0};case"ADD_FILE":{let n=await tR(e.file);return await this.driver.pushFile(e.storageLocation,n),await this.driver.execute("mobile: shell",{command:"am",args:["broadcast","-a","android.intent.action.MEDIA_SCANNER_SCAN_FILE","-d",`file://${e.storageLocation}`]}),{success:!0}}case"ADB":{let n=await this.driver.execute(e.command,JSON.parse(e.jsonArgs??"{}"));return this.logger.info({output:n},"ADB command executed successfully"),{success:!0,output:n,message:"ADB command executed successfully"}}case"STATE":{await this.stateManager.refreshWebviews();let n=await this.stateManager.getDomState(),o=await this.stateManager.getContexts(),i={xml:n.graph.xml,contexts:o};return this.logger.info({result:i},"State debug command output"),{output:i,success:!0}}default:{let n=e;return{success:!0}}}}async initializeSettings(){}async screenshot(){return this.driver.takeScreenshot()}async getA11yTree(){return(await this.stateManager.getDomState({})).graph.xml}resetAbortController(e){this.aborter.controller=e??new AbortController}isAborted(){return this.aborter.controller?.signal.aborted}abort(){this.aborter.controller?.abort()}get context(){return this.fixtures.testContext}get localCodeEvalTools(){return this.fixtures.localCodeEvalTools}};async function iR({socket:r,logger:e,androidDriverFactory:t,getOrgId:n,mobileGeneratorFactory:o,browserGeneratorFactory:i,browserEnricherFactory:a,storageFactory:s,localToolsFactory:c,globalStateManager:l,settingsFactory:u}){let d=r.id,p=r.handshake.query?.testMetadata,g=r.handshake.query?.fileName,m=g?.endsWith("test.yaml")?g.slice(0,-"test.yaml".length):g,h=Or.parse(JSON.parse(p??"")),f=h.id,E=h.settings?.defaultChannel,S=h.settings?.defaultTag,A=await n({testId:f});e=e.child({sessionId:d,testId:f,orgId:A});let T={...(await u(A,e)).emulator,...h.settings?.emulator},I=Date.now(),{driver:R,cleanup:w,limbarToken:B,limbarUrl:D,emulatorName:U,adbTunnelPort:J}=await t({socket:r,logger:e,creationOpts:{region:T.region,apkToInstall:E?{channel:E,tag:S}:void 0}}),Le=await ic({driver:R,onLogs:$t=>{r.emit("logcatLogs",$t)}});e.info({adbTunnelPort:J,apkChannel:E,apkTag:S,duration:Date.now()-I,emulatorName:U},"Android emulator session initiated"),e=e.child({emulator:U});let K=await o(A,e),G=await i(A,e),se=await a(A,e),ce=await s(A),ke=c?await c(A):void 0,fe={};h.settings?.defaultEnv&&(fe=(await ce.fetchEnvironment(h.settings?.defaultEnv,e))?.variables??{});let pt=new ii({variablesFromEnvironment:fe,envName:h.settings?.defaultEnv,testName:m}),Wt=await yi.init({driver:R,generator:K,logger:e,options:{emulator:T},fixtures:{storage:ce,browserEnricher:se,browserGenerator:G,localCodeEvalTools:ke,testContext:pt},orgId:A,adbPort:J,abortController:new AbortController});if(!r.connected)throw await Le(),await w(),new Error("Socket not connected anymore, not proceeding with Android session setup");let we=iB({socket:r,testContext:pt}),tt=async()=>{clearInterval(we);try{await Le(),await w()}catch($t){e.warn({err:$t},"Failed to clean up emulator in socket server")}};return l.registerSession(d,{controller:Wt,cleanup:tt,emulatorName:U}),r.emit("session",{testId:f,sessionId:d,limbarUrl:D,limbarToken:B}),{sessionId:d,testId:f,orgId:A,emulatorName:U,logger:e}}function iB({socket:r,testContext:e}){return setInterval(()=>{let t=e.toEditorDisplayCopy();r.emit("emulatorState",{context:t})},3e3)}async function aR({socket:r,logger:e,globalStateManager:t}){await t.removeSession(r.id,e)}var aB=({socket:r,globalStateManager:e})=>async()=>{let t=e.getSession(r.id);if(!t)throw new Error("No active Android session found");t.controller.abort()},sR={event:"cancel",createHandler:aB};var sB=({logger:r,globalStateManager:e,socket:t})=>async(n,o)=>{let i=e.getSession(t.id);if(!i){o({err:"No active Android session found"});return}try{let s=await i.controller.getA11yTree();o({a11yTree:s})}catch(a){r.error({err:a},"Error fetching a11y tree from the session controller"),o({err:a.message})}},lR={event:"fetchA11yTree",createHandler:sB};import{diff as RB}from"deep-object-diff";import{cloneDeep as CB}from"lodash-es";import ORe,{multistream as NRe}from"pino";import DRe from"pino-pretty";import lB from"fetch-retry";import cB from"os";import cR,{multistream as uB}from"pino";import dB from"pino-pretty";import pB from"pino-std-serializers";var Ei=new Map,mB=!0,uR="Log throttle exceeded",gB=100,hB=5e3,fB=lB(global.fetch,{retries:2,retryOn:function(r,e,t){return!!(e!==null||t&&t.status>=500)},retryDelay:function(r){return Math.pow(2,r)*500}}),Ym=class r{consoleLogger;hostname;bindingAttributes;disableConsoleLogs;minLevelValue=20;logsInCurrentWindow=0;droppedLogsInWindow=!1;lastWindowStart=Date.now();site="https://ingest.us.signoz.cloud:443/logs/json";flushIntervalMs;maxBatchSize;buffer=[];flushTimer;constructor({bindings:e,hostname:t,disableConsoleLogs:n,flushIntervalMs:o,maxBatchSize:i}){this.hostname=t??cB.hostname(),this.disableConsoleLogs=n,this.bindingAttributes={...e,env:"production"},this.flushIntervalMs=o??5e3,this.maxBatchSize=i??10;let a={base:this.bindingAttributes,errorKey:"err",level:"debug"};this.consoleLogger=mB?cR(a):cR(a,uB([{stream:dB({colorize:!0})}]))}getLevel(){return Ql[this.minLevelValue]}child(e){return new r({bindings:{...this.bindingAttributes,...e},hostname:this.hostname,disableConsoleLogs:this.disableConsoleLogs,flushIntervalMs:this.flushIntervalMs,maxBatchSize:this.maxBatchSize})}flush(e){this.flushBuffer(),this.disableConsoleLogs||this.consoleLogger.flush(e)}scheduleFlush(){this.flushTimer||(this.flushTimer=setTimeout(()=>{this.flushTimer=void 0,this.flushBuffer()},this.flushIntervalMs))}async flushBuffer(){if(this.buffer.length===0)return;let e=this.buffer;this.buffer=[];try{let t=await fB(this.site,{method:"POST",headers:{"Content-Type":"application/json","signoz-access-token":"CumAaTMUcwjt05OddAmefKgshbhfRmWxzxih"},body:ci(e),signal:AbortSignal.timeout(5e3)});if(!t.ok)throw new Error(`Got error status (${t.statusText}) from SigNoz`)}catch(t){this.consoleLogger.warn({err:t},"Failed to log to SigNoz")}}shouldAllowLog(e){if(e===uR)return!0;let t=Date.now();return t-this.lastWindowStart>hB&&(this.logsInCurrentWindow=0,this.droppedLogsInWindow&&this.log("error",void 0,uR),this.droppedLogsInWindow=!1,this.lastWindowStart=t),this.logsInCurrentWindow<gB?(this.logsInCurrentWindow++,!0):(this.droppedLogsInWindow=!0,!1)}log(e,t,n,...o){try{this.logHelper(e,t,n,...o)}catch(i){this.consoleLogger.warn(`Failed to log to Signoz: ${i}`)}}logHelper(e,t,n,...o){if(Fa[e]<this.minLevelValue||!this.shouldAllowLog(n))return;typeof t=="string"&&!n&&(t={message:t}),typeof t=="object"&&t&&"err"in t&&t.err instanceof Error&&(t.err=pB.err(t.err));let i={...this.bindingAttributes,...t&&typeof t=="object"?t:{},...o.length>0?{args:o}:{}},a={host:this.hostname,env:this.bindingAttributes.env};this.disableConsoleLogs||this.consoleLogger[e](i,n,...o);let s={timestamp:Math.round(Date.now()*1e6),severity_text:e.toUpperCase(),resources:a,attributes:{},body:XE({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 t=this.bindingAttributes.app;this.bindingAttributes.app=e,Ei.set("app",this),Ei.delete(t)}debug(e,t,...n){this.log("debug",e,t,...n)}info(e,t,...n){this.log("info",e,t,...n)}warn(e,t,...n){this.log("warn",e,t,...n)}error(e,t,...n){this.log("error",e,t,...n)}bindings(){return this.bindingAttributes}addBinding(e,t){this.bindingAttributes[e]=t}setMinLevel(e){typeof e=="number"?(this.minLevelValue=e,this.consoleLogger.level=Ql[e]):(this.minLevelValue=Fa[e],this.consoleLogger.level=e)}enableConsoleLogs(){this.disableConsoleLogs=!1}},Hc=({app:r,hostname:e,disableConsoleLogs:t})=>(Ei.has(r)||Ei.set(r,new Ym({bindings:{app:r},hostname:e,disableConsoleLogs:t})),Ei.get(r));function dR(){for(let r of Ei.values())r.flush()}import{PostHog as ZRe}from"posthog-node";import{PostHog as sCe}from"posthog-node";import Ja from"os";import SB from"v8";var yo=!!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 pR,Hr,yB=Ja.platform(),bB=Ja.cpus().map(r=>({model:r.model,speed:r.speed})).reduce((r,e)=>(r[e.model]={speed:e.speed},r.totalCores=(r.totalCores??0)+1,r),{}),mR=r=>{try{let e=!1,t=EB(),n=TB(),o=`${Math.round(t.freePercentage*100)}%`;t.freePercentage<.05&&(e=!0);let i=`${n?Math.round(n.idle):"unknown"}%`;n&&n?.total>70&&(e=!0);let a=SB.getHeapStatistics(),s=a.used_heap_size,c=a.heap_size_limit;s/c>.9&&(e=!0),e?(r.warn({memory:t,cpu:n,heapStats:a},"Critical resource usage metrics detected"),yo&&x.warn(`Low machine resources detected (memory: ${o} free, cpu: ${i} free)`)):r.debug({memory:t,cpu:n},"Got machine resource usage metrics")}catch{}};function gR(r){if(!wn)return mR(r),{interval:setInterval(()=>mR(r),2e4),cpuMetadata:bB,platform:yB}}function EB(){let r=Ja.totalmem(),e=Ja.freemem(),t=e/r;return{totalMemory:r,freeMemory:e,freePercentage:t}}function TB(){let r=Ja.cpus(),e=Date.now(),t={measurementTime:e,user:0,nice:0,sys:0,idle:0,irq:0,total:0};for(let o of r)t.user+=o.times.user,t.nice+=o.times.nice,t.sys+=o.times.sys,t.idle+=o.times.idle,t.irq+=o.times.irq;if(t.total=t.user+t.nice+t.sys+t.idle+t.irq,!Hr)return Hr=t,null;let n={user:t.user-Hr.user,nice:t.nice-Hr.nice,sys:t.sys-Hr.sys,idle:t.idle-Hr.idle,irq:t.irq-Hr.irq,total:t.total-Hr.total};return pR={measurementTime:e,intervalMs:e-Hr.measurementTime,user:n.user/n.total*100,nice:n.nice/n.total*100,sys:n.sys/n.total*100,idle:n.idle/n.total*100,irq:n.irq/n.total*100,total:100-n.idle/n.total*100},Hr=t,pR}function hR(r,e,t=1e4,n=5e3){let o=0;async function i(){try{let s=await V(r.driver.execute("mobile: shell",{command:"echo",args:["ping"]}).catch(c=>{throw c}),{milliseconds:n});if(typeof s=="string"&&s.trim()==="ping")o>0&&e.info("Driver heartbeat restored"),o=0;else throw new Error(`Unexpected heartbeat output: ${s}`)}catch(s){o++;let c=s instanceof Error?s.message:`${s}`;e.error({attempt:o,error:c},"Driver heartbeat failed"),o>=3&&e.error("Driver appears unresponsive \u2014 possible ADB tunnel/emulator failure")}}let a=setInterval(()=>{i()},t);return i(),a}async function fR(r){let e=Date.now(),t=r.fixtures.controller;try{return await vB(r)}catch(n){let o=t.isAborted()||n instanceof DOMException&&n.name==="AbortError";return{...r.moduleParams.step,steps:[],type:"MOBILE_MODULE_STEP",startTime:e,endTime:Date.now(),status:o?"CANCELLED":"FAILED",message:o?"Step cancelled.":`${n}`}}}async function vB({moduleParams:r,...e}){let t=Date.now(),{step:n,stepTracer:o,executeMobileStepList:i}=r,a=await AB({step:n,params:e}),s={};Object.entries(a).forEach(([p,g])=>{s[p]=JSON.stringify(g)});let c={...n,type:"MOBILE_MODULE_STEP",inputs:s,startTime:t,steps:[],endTime:Date.now(),status:"SUCCESS"},l=await o.startSubSteps(),{status:u,results:d}=await i({...e,listParams:{steps:n.steps,containerName:`module ('${n.name}')`,tracer:l}});return c.steps=d,c.status=u,c.endTime=Date.now(),xv({result:c,...Cv(d)}),c}async function AB({step:r,params:e}){let t={},{logger:n,controller:o}=e.fixtures;for(let i of r.parameters?.parameterNames??[]){let a=r.inputs?.[i]??r.parameters?.defaultParameters?.[i];if(!a){n.warn({k:i},"No value found for parameter in module");continue}t[i]=await kr({orgId:e.inputs.orgId,code:a,fragment:!0,logger:n,context:o.context,localTools:o.localCodeEvalTools})}return t}import{randomUUID as SR}from"crypto";async function yR({fixtures:r,step:e,inputs:t,stepTracer:n}){let o=Date.now(),{logger:i,controller:a}=r,s=n.interactionTracer,c;if(!t.interactive)try{c=await a.screenshot()}catch(u){i.warn({err:u},"Failed to take before screenshot")}let l={...e,status:"SUCCESS",startTime:o,endTime:Date.now()};try{let u=await a.executeCommand({command:e.command,tracer:s});l={...e,status:u.success?"SUCCESS":"FAILED",message:u.message,startTime:o,endTime:Date.now(),data:u.output}}catch(u){u instanceof Error&&u.name==="AbortError"||a.isAborted()?l={...e,status:"CANCELLED",message:"Step cancelled.",startTime:o,endTime:Date.now()}:(i.error({err:u},"Failed to execute preset step"),l={...e,status:"FAILED",message:u instanceof Error?u.message:String(u),startTime:o,endTime:Date.now()})}finally{if(l.trace=s.getRootSpan(),!t.interactive){try{let u=SR(),d=await a.screenshot();l.afterSnapshot=u,n.attachAfterScreenshot({logger:i,snapshotId:u,screenshot:Buffer.from(d,"base64")})}catch(u){i.warn({err:u},"Failed to take after screenshot")}if(c){let u=SR();l.beforeSnapshot=u,n.attachBeforeScreenshot({logger:i,snapshotId:u,screenshot:Buffer.from(c,"base64")})}}}return l}async function Xm(r){let{fixtures:e,inputs:t,listParams:n}=r,{containerName:o,steps:i,tracer:a}=n,{logger:s,controller:c,usageTracker:l}=e,u=a.getParentStepIdChain(),d=[],p,g="SUCCESS",{fromStep:m,toStep:h}=t,f=!!m;for(let E=0;E<i.length;E++){let S=i[E];if(s.info({step:S},`Executing step ${E+1}/${i.length} in ${o}: ${bv(S)}`),S.skipped){s.debug("Step skipped");continue}if(f&&m){let T=JSON.stringify(u);if(S.id===m.fromStepId&&T===JSON.stringify(m.parentStepIdChain))f=!1;else if(!Rv({currentStep:S,currentParentChain:u,desiredStepId:m.fromStepId,desiredStepParentChain:m.parentStepIdChain}))continue}let A=await a.startStep({logger:s,step:S,attempt:1,parentStepIdChain:u});l.trackStepExecution(S);let C=await wB({step:S,stepTracer:A,params:r});if(C.trace&&s.info({step:{id:S.id},trace:C.trace,status:C.status},`Step ${E+1}/${i.length} done (${S.type==="MOBILE_PRESET_STEP"?S.command.type:S.type})`),d.push(C),await A.finish({parentStepIdChain:u,result:C}),C.status!=="SUCCESS"){g=C.status,p=C;break}if(S.envKey&&c.context.setVariable(S.envKey,C.data),h){let T=JSON.stringify([]);if(S.id===h.toStepId&&T===JSON.stringify(h.parentStepIdChain))break}}return{results:d,status:g,terminalResult:p}}async function wB({step:r,stepTracer:e,params:t}){let{fixtures:n,inputs:o}=t,i;switch(r.type){case"MOBILE_PRESET_STEP":{i=await yR({fixtures:n,inputs:o,step:r,stepTracer:e});break}case"RESOLVED_MOBILE_MODULE":{i=await fR({...t,moduleParams:{step:r,stepTracer:e,executeMobileStepList:Xm}});break}}return i}async function Gc(r){let{tracer:e,containerName:t}=r,{steps:n,testMetadata:o}=r.inputs,{cacheStorage:i,logger:a,controller:s}=r.fixtures;await i.resolveEntries({logger:a,testId:o.id,stepLists:{steps:n}});let c=CB(n);a.info({testMetadata:Or.parse(o)},"Starting mobile test");let l=await e.startMainStepList(),u=gR(a),d=hR(s,a);a.info({cpu:u?.cpuMetadata,platform:u?.platform},`Starting execution of ${t}`);let{status:p,results:g}=await Xm({...r,listParams:{containerName:t,tracer:l,steps:c}});if(clearInterval(u?.interval),clearInterval(d),p==="SUCCESS"){let m=RB(c,n);if(m&&Object.keys(m).length>0){a.debug({diffs:m},"Saving mobile step cache entries post-success");let{cachesToSave:h}=await lo({steps:c,cacheCreationParams:{orgId:r.inputs.orgId,testId:o.id}});await i.saveEntries({logger:a,testId:o.id,entries:h})}return{status:"PASSED",results:g}}return p==="CANCELLED"?{status:"CANCELLED",results:g}:{status:"FAILED",results:g}}var Jm=class{parentTracer=null;socket;step;interactionTracer;constructor({step:e,socket:t,parentTracer:n}){this.socket=t,this.parentTracer=n,this.step=e,this.interactionTracer=new fo,Pn.initializeRootTracerContext(this.interactionTracer)}attachBeforeScreenshot(){}attachAfterScreenshot(){}attachBeforeHtmlSnapshot(){}attachAfterHtmlSnapshot(){}async finish(e){this.interactionTracer.finish();let t=this.interactionTracer.getRootSpan(),n={...YT.parse(e),trace:Mp.parse(t)};switch(n.result.status){case"SUCCESS":this.socket.emit("success",n);break;case"FAILED":this.socket.emit("failure",n);break;case"CANCELLED":this.socket.emit("cancelled",n);break}return{trace:t}}getParentStepIdChain(){return this.parentTracer?this.parentTracer?.getParentStepIdChain()??[]:[]}async startSubSteps(){return new Ti({parentStep:this.step,socket:this.socket,parentTracer:this})}},Ti=class{parentTracer;parentStep;socket;constructor({parentStep:e,socket:t,parentTracer:n}){this.parentTracer=n,this.parentStep=e,this.socket=t}getParentStepIdChain(){return this.parentStep?[...this.parentTracer?.getParentStepIdChain()??[],this.parentStep.id]:[]}async startStep(e){return this.socket.emit("started",{stepId:e.step.id,parentStepIdChain:e.parentStepIdChain,attempt:e.attempt}),new Jm({step:e.step,parentTracer:this,socket:this.socket})}},jc=class{constructor(e){this.socket=e}appendLogs(){}async finish(){this.socket.emit("finished")}async startBeforeStepList(){return new Ti({parentStep:null,parentTracer:null,socket:this.socket})}async startMainStepList(){return new Ti({parentStep:null,parentTracer:null,socket:this.socket})}async startAfterStepList(){return new Ti({parentStep:null,parentTracer:null,socket:this.socket})}};var xB=({metadata:r,logger:e,globalStateManager:t,socket:n,cacheStorageFactory:o})=>async(i,a)=>{let s=t.getSession(n.id);if(!s)throw new Error("No active Android session found");let c=e.child({testId:i.testMetadata.id}),l=await o(r.orgId),u=s.controller;u.resetAbortController();let d=new jc(n),p=await Gc({fixtures:{controller:u,logger:c,cacheStorage:l,usageTracker:new Dl},containerName:"entire test",inputs:{steps:i.steps,fromStep:i.fromStep,toStep:i.toStep,orgId:r.orgId,testMetadata:i.testMetadata,interactive:!0},tracer:d});await d.finish();let g={results:Er.array().parse(p.results),status:p.status};a?.(g)},bR={event:"execute",createHandler:xB};import{debounce as _B}from"ts-debounce";var MB=({socket:r,globalStateManager:e,keepSessionAlive:t})=>{let n=_B(t,3e4,{maxWait:6e4});return async()=>{let o=e.getSession(r.id);if(!o)throw new Error("No active Android session found");o.emulatorName&&n(o.emulatorName)}},ER={event:"keepalive",createHandler:MB};var TR=[bR,sR,ER,lR];function vR(r){let{logger:e,baseServer:t,globalStateManager:n}=r,o=new IB(t,{cors:{origin:"*",methods:["GET","POST"]},pingTimeout:15*60*1e3,pingInterval:15*60*1e3,maxHttpBufferSize:1e7,perMessageDeflate:!0}),i=async()=>{await n.removeAllSessions(e)};o.on("connection",async s=>{let c=s.id,l=e.child({sessionId:c});l.info({event:"connection",transport:s.conn.transport.name},"Android websocket connection initiated"),s.on("disconnect",async()=>{await aR({socket:s,globalStateManager:n,logger:l})});let u;try{u=await iR({...r,socket:s,globalStateManager:n,logger:l})}catch(d){l.error({err:d},"Failed to setup Android connection"),s.emit("error",{message:d instanceof Error?d.message:JSON.stringify(d)}),s.disconnect(!0);return}TR.forEach(d=>a(d,{...r,socket:s,metadata:u,logger:l}))});let a=(s,c)=>{let l=s.createHandler(c),u=(...d)=>{s.event!=="keepalive"&&c.logger.debug({event:s.event},`Websocket event (${s.event})`);let p=g=>{c.logger.error({event:s.event,err:g instanceof Error?g:new Error(`${g}`)},"Unhandled exception in socket handler"),c.socket.emit("error",{message:g instanceof Error?g.message:`${g}`})};try{let g=l.apply(this,d);g&&typeof g.catch=="function"&&g.catch(p)}catch(g){p(g)}};c.socket.on(s.event,u)};return{server:o,dispose:i}}import{confirm as LB,input as NB}from"@inquirer/prompts";import{existsSync as k_e,mkdirSync as D_e,statSync as kB}from"fs";import vi,{supportsColor as OB}from"chalk";import{Console as AR}from"console";import{format as Za}from"util";var Zm=class extends Error{constructor(e,t,n){let o=Error.stackTraceLimit;n&&(Error.stackTraceLimit=Math.max(n,o||10)),super(e),Error.captureStackTrace&&Error.captureStackTrace(this,t),Error.stackTraceLimit=o}},Vc=class r extends AR{_buffer=[];_groupDepth=0;Console=AR;constructor(){super({write:e=>(r.write(this._buffer,"log",e),!0)})}static write(e,t,n,o=2){let i=new Zm(void 0,r.write).stack;if(!i)return e;let a=i.split(`
|
|
4037
|
+
`));return}}let d=Array.from(e.childNodes??[]);for(let p of d){let m=p.nodeType;if(m===3){let g=p.nodeValue;g&&g.trim().length>0&&t.appendChild(n.createTextNode(g));continue}if(m===1){let g=p,h=n.createElement(WU(g.tagName));Mw(r,g,h),t.appendChild(h)}}}function ZU(r,e,t,n){let o=r.parseFromString("<hierarchy/>","text/xml"),i=new Map,a={prunedDocument:o,idToElement:t,prunedIdToElement:i,idCounter:{value:0},opts:n},l=o.documentElement;Mw(a,e,l);let c=new jU().serializeToString(o);return{prunedDocument:o,prunedIdToElement:i,xml:c}}async function _w(r,e){let t=new VU,n=t.parseFromString(r,"text/xml"),o=new Map,i=n.documentElement;if(!i)throw new Error("No root element found in XML");if(i.tagName!=="hierarchy")throw new Error("No hierarchy element found in XML");let{prunedDocument:a,prunedIdToElement:l,xml:c}=ZU(t,i,o,e);return{xml:await GU.format(c,{parser:"xml",plugins:[HU],printWidth:120,tabWidth:1,singleAttributePerLine:!1}),originalXml:r,document:n,idToElement:o,prunedDocument:a,prunedIdToElement:l}}function QU(r){let e=[],t=r;for(;t;){let n=t.tagName,o=t.parentElement,i=1;if(o){let a=Array.from(o.children).filter(l=>l.tagName===n);for(let l=0;l<a.length;l++)if(a[l]===t){i=l+1;break}}e.unshift(`${n}[${i}]`),t=o}return`/${e.join("/")}`}function wc(r,e){let t=r.idToElement.get(e);if(t)return QU(t)}function Pm(r,e){let t=r.idToElement.get(e);if(!t)return;let n=t.cloneNode(!0);for(let o of Array.from(n.children)){let i=o;for(let a of Array.from(i.children))i.removeChild(a)}return n.outerHTML}function Rc(r){if(!r.hasAttribute("bounds"))return;let e=r.getAttribute("bounds");if(!e)return;let t=e.match(/\[(\d+),(\d+)\]\[(\d+),(\d+)\]/);if(t){let n=parseInt(t[1],10),o=parseInt(t[2],10),i=parseInt(t[3],10),a=parseInt(t[4],10);if(Number.isFinite(n)&&Number.isFinite(o)&&Number.isFinite(i)&&Number.isFinite(a))return[n,o,i,a]}}function Om(r,e){if(r&&!(!e||e.length===0))return Object.fromEntries(e.map(t=>[t,r.getAttribute(t)]).filter(([,t])=>t!==null))}function Ow({aiResponse:r,description:e,emulatorState:t}){let n=t.graph.idToElement.get(r.id);if(!n)throw new Error(`Could not find node with id: ${r.id}`);let o=Rc(n);if(!o)throw new Error(`Node ${r.id} has no bounding box: ${n.outerHTML}`);let i=wc(t.graph,r.id)??"",a=Pm(t.graph,r.id)??"",l=t.graph.idToElement.get(r.id),c=Om(l,r.requirements?.attributesRequired),u={requiredText:r.requirements?.textRequired?l?.getAttribute("text")??void 0:void 0,requiredAttributes:c,requiredBounds:r.requirements?.boundsRequired},d=[];r.additionalElements&&(d=r.additionalElements.map(({id:m,requirements:g})=>{let h=t.graph.idToElement.get(m);if(!h)return;let f=wc(t.graph,m);return f?{xPath:f,requirements:{requiredText:g.textRequired?h.getAttribute("text")??void 0:void 0,requiredAttributes:Om(h,g.attributesRequired),requiredBounds:g.boundsRequired}}:void 0}).filter(m=>!!m));let p;return Im(n.tagName)&&r.inWebview!==!1?p={type:"WEBVIEW",resolvedDescription:e,xPath:i}:p={type:"NATIVE",bounds:o,resolvedDescription:e,xPath:i,elementOnlySerializedXml:a,requirements:u,requiredRelatedElements:d},p}var Pw=(r,e,t)=>{if(!e)return;let{requiredAttributes:n,requiredText:o,requiredBounds:i}=e;if(o!==void 0){let a=r.getAttribute("text")??void 0;if(a!==o)throw new Error(`ActionFailureError: Resolved element text mismatch: expected ${o}, got ${a}`)}if(n)for(let[a,l]of Object.entries(n)){let c=r.getAttribute(a)??void 0;if(c!==l)throw new Error(`ActionFailureError: Attribute ${a} mismatch: expected ${l}, got ${c}`)}if(i&&t){let a=Rc(r);if(!a||a.length!==t.length)throw new Error("ActionFailureError: Resolved element has no bounds or unexpected bounds format");if(!a.every((c,s)=>c===t[s]))throw new Error(`ActionFailureError: Bounds changed from [${t.join(",")} ] to [${a.join(",")} ]`)}};async function Lw(r){let{target:e,domState:t}=r,{graph:n}=t,{document:o}=n,i=Re();if(e.type==="WEBVIEW")return eF(e,r);let a=Iw.evaluateXPathToFirstNode(e.xPath,o,null,null);if(!a)throw new Error(`ActionFailureError: Could not resolve cached target via XPath: ${e.xPath}`);if(e.requiredRelatedElements){let p=e.requiredRelatedElements;i.startSection("Validate related elements are similar enough to past runs",()=>{for(let m of p){let g=Iw.evaluateXPathToFirstNode(m.xPath,o);if(!g)throw new Error(`ActionFailureError: Required related element not found for XPath: ${m.xPath}`);Pw(g,m.requirements)}})}let l=Rc(a);if(!l)throw new Error("ActionFailureError: Resolved native element has no bounding box");Pw(a,e.requirements,e.bounds);let c;for(let[p,m]of n.idToElement.entries())if(m===a){c=p;break}let s=e.elementOnlySerializedXml,u=e.xPath;return c!==void 0&&(s=Pm(n,c)??s,u=wc(n,c)??u),{resolvedTarget:{...e,bounds:l,elementOnlySerializedXml:s,xPath:u}}}async function eF(r,e){let{stateManager:t,logger:n,signal:o}=e,i=Re(),a=await t.getActiveWebview();if(!a||!a.browserController)throw new Error("No browser controller is attached to the requested webview");let l=a.browserController.browser;if(!r.browserCache)throw new Error("No browser target available on cache");let c=r.browserCache,s=await i.startAsyncSection("Resolve target in webview",()=>l.resolveTarget(null,c,{logger:n,signal:o}));return{resolvedTarget:{...r,controller:a.browserController,resolution:s}}}function Lm(r){let{command:e,cacheKey:t="cache",targetName:n="target",updatedCache:o}=r;Ls(e)&&(e[t]={...e[t],[n]:Ps.parse(o)},r.updatedWithAI&&(e[t].updatedAt=new Date))}function Nw(r){return r.type==="WEBVIEW"?{type:"WEBVIEW",resolvedDescription:r.resolvedDescription,xPath:r.xPath,browserCache:r.browserCache}:r}var lr=class{driver;generator;stateManager;logger;fixtures;aborter;orgId;constructor(e){this.stateManager=e.stateManager,this.generator=e.generator,this.driver=e.driver,this.logger=e.logger,this.fixtures=e.fixtures,this.aborter=e.aborter,this.orgId=e.orgId}async findElement({description:e,tracer:t}){await this.stateManager.waitForScreenshotStability({timeoutMs:5e3,signal:this.aborter.controller?.signal,reason:"Waiting for stability before locating an element with AI"});let n=await t.startAsyncSection("Get emulator state",async()=>{let c=await this.stateManager.getDomState(),s=await this.stateManager.getCurrentScreenshotPngString();return{emulatorState:c,screenshot:s}}),o;try{o=await t.startAsyncSpan("AI_LOCATOR_CALL",async c=>{let s=await this.generator.getElementLocation({description:e,screenXml:n.emulatorState.graph.xml,screenshot:n.screenshot},{logger:this.logger,loggerTags:pe(this.logger),abortSignal:this.aborter.controller?.signal});return c.result=s,s})}catch(c){throw this.throwIfAborted(),this.logger.error({err:c},"Failed to locate element"),new Error(`ActionFailureError: Failed to locate element: ${c instanceof Error?c.message:c}`)}if(o.id===-1)throw new Error(`ActionFailureError: No matching element found: ${o.thoughts}`);let i=Ow({aiResponse:o,description:e,emulatorState:n.emulatorState});if(i.type==="NATIVE")return t.addSpan({type:"TARGET_RESOLUTION",startTime:Date.now(),endTime:Date.now(),result:{serializedElement:i.elementOnlySerializedXml},attributes:{}}),{resolvedTarget:i,thoughts:o.thoughts};let{browserLocateResult:a,browserController:l}=await t.startAsyncSpan("TARGET_RESOLUTION",async c=>{let s=await this.stateManager.getActiveWebview();if(!s||!s.browserController)throw new Error("No browser controller is attached to the requested webview");let u=await s.browserController.locateElement({description:e,disableCache:!1,logger:this.logger});return c.result={serializedElement:u.target.nodeOnlySerializedHtml??"Unknown HTML element in webview"},{browserLocateResult:u,browserController:s.browserController}});return{resolvedTarget:{...i,controller:l,resolution:a.resolution,browserCache:a.target},thoughts:a.thoughts}}async wrapTargetingAction(e){let{action:t,description:n,command:o,cacheKey:i="cache",targetName:a="target",cacheIsInvalidAfterResolution:l,tracer:c}=e,s=i in o&&o[i]&&a in o[i]?o[i][a]:void 0,u=e.retriesWithAI??1,d=!1,p=rF(s),m;if(o.disableCache&&(this.logger.debug({command:o},"Cache explicitly disabled for command"),d=!0,p=void 0),l&&(d=!0,p=void 0),p&&p?.resolvedDescription!==n&&(this.logger.info({cache:p,description:n},"Cache description mismatch, clearing it automatically"),d=!0,p=void 0),!p){u--,this.logger.info({description:n,cacheBustedBeforeAction:d},"Prompting AI for a new element location");let h=await this.findElement({description:n,tracer:c});return m=h.thoughts,Lm({command:o,cacheKey:i,targetName:a,updatedCache:h.resolvedTarget,updatedWithAI:!0}),{result:await t(h.resolvedTarget),thoughts:m}}let g;try{await this.stateManager.waitForScreenshotStability({timeoutMs:5e3,signal:this.aborter.controller?.signal,reason:"Waiting for stability before cache resolution"}),g=await this.stateManager.getDomState();let h=await c.startAsyncSection("Resolve target cache",async(b,E)=>{let{resolvedTarget:v}=await Lw({target:p,domState:g,stateManager:this.stateManager,logger:this.logger}),R=Nw(v),T=tF(p,R);return this.logger.info({cacheDiffs:T},"Successfully resolved and updated target"),Lm({command:o,cacheKey:i,targetName:a,updatedCache:R,updatedWithAI:!1}),E.attributes.serializedElement=v.type==="WEBVIEW"?v.browserCache?.nodeOnlySerializedHtml??"Unknown HTML element in webview":v.elementOnlySerializedXml,v}),f=await t(h);return p.type!=="WEBVIEW"&&vt.increment("cache_target_resolution_v2",1,["outcome:hit","platform:native",`hasRequirements:${!!p.requirements}`,`hasAdditionalElements:${!!p.requiredRelatedElements?.length}`,`orgId:${this.orgId}`]),{result:f,thoughts:"Successfully executed preset action with cache."}}catch(h){if(p.type!=="WEBVIEW"&&vt.increment("cache_target_resolution_v2",1,["outcome:miss","platform:native",`hasRequirements:${!!p.requirements}`,`hasAdditionalElements:${!!p.requiredRelatedElements?.length}`,`orgId:${this.orgId}`]),this.throwIfAborted(),u>0)return this.logger.warn({err:h},"Failed to resolve target cache, retrying with AI"),this.logger.debug({domState:g?.graph.originalXml},"Emulator state"),this.wrapTargetingAction({...e,cacheIsInvalidAfterResolution:!0,retriesWithAI:u-1});throw new Error(`ActionFailureError: ${h instanceof Error?h.message:h}`,{cause:h})}}constructPerformerParams(){return{stateManager:this.stateManager,generator:this.generator,driver:this.driver,logger:this.logger,fixtures:this.fixtures,aborter:this.aborter,orgId:this.orgId}}throwIfAborted(){this.aborter.controller?.signal.throwIfAborted()}get abortSignal(){return this.aborter.controller?.signal}};function iF(r){let e={relativePosition:r.relativePosition};if(r.doubleTap&&r.longPress)throw new Error("UserConfigurationError: Cannot specify both doubleTap and longPress");return r.doubleTap?{...e,doubleTap:!0,doubleTapDelayMs:r.doubleTapDelayMs}:r.longPress?{...e,longPress:!0,longPressDurationMs:r.longPressDurationMs}:e}var ai=class extends lr{async tapOnAbsoluteCoordinates(e){let t=e.x,n=e.y;if(this.logger.info({x:t,y:n},"Tap at coordinates"),e.longPress)return await this.driver.executeScript("mobile: longClickGesture",[{x:t,y:n,duration:e.longPressDurationMs??2e3}]);if(e.doubleTap){await this.driver.tap({x:t,y:n});let o=e.doubleTapDelayMs??100;await new Promise(i=>setTimeout(i,o))}await this.driver.tap({x:t,y:n})}async tapOnNativeTarget(e,t){let[n,o,i,a]=e.bounds,l=i-n,c=a-o,s=t?.relativePosition?.x??l/2,u=t?.relativePosition?.y??c/2;s=Math.max(0,Math.min(s,l)),u=Math.max(0,Math.min(u,c));let d=n+s,p=o+u;return await this.tapOnAbsoluteCoordinates({x:d,y:p,...t}),{x:d,y:p}}async tapOnWebviewTarget(e,t){let{controller:n}=e;return(await n.browser.click(e.resolution,{createIsolatedFolder:()=>{let i=Math.random().toString(36).substring(4),a=Dw.join(oF(),"momentic","downloads"),l=Dw.join(a,this.orgId,i);return nF(l,{recursive:!0}),l}},{delayMs:t?.longPress?t?.longPressDurationMs??2e3:void 0,relativePosition:t?.relativePosition,doubleClick:t?.doubleTap})).coordinates}async tapOnTarget({target:e,options:t}){return await Re().startAsyncSpan("EMULATOR_INTERACTION",async o=>{o.attributes.options=t,"type"in e&&e.type==="NATIVE"?o.attributes.point=await this.tapOnNativeTarget(e,t):(o.withinWebview=!0,o.attributes.point=await this.tapOnWebviewTarget(e,t))},{name:"Tap on target"})}async executeTap({command:e}){let t=Re(),n=iF(e);if(e.target.type==="coordinates"){let a=await this.driver.getWindowSize(),l=e.target.xPercent*a.width,c=e.target.yPercent*a.height;return await t.startAsyncSpan("EMULATOR_INTERACTION",async()=>{await this.tapOnAbsoluteCoordinates({...n,x:l,y:c})},{name:`Tap at coordinates ${l}, ${c}`}),{success:!0,message:`Tapped at ${l}, ${c}`}}let o=e.target.description,{thoughts:i}=await this.wrapTargetingAction({command:e,tracer:t,action:a=>this.tapOnTarget({target:a,options:n}),description:o});return{success:!0,message:i}}};var An=class extends lr{async doPress({keycode:e,longPress:t}){await Re().startAsyncSpan("EMULATOR_INTERACTION",async()=>this.driver.executeScript("mobile: pressKey",[{keycode:e,isLongPress:t}]),{name:"Send key events to emulator"})}};var Cc=class extends lr{async doType(e){if(!e.target){if(e.clearContent)throw new Error("UserConfigurationError: clearing content is only supported when a target is provided to the Type step");return await this.sendKeys(e),{success:!0,message:void 0}}if(e.target.type!=="description")throw new Error("UserConfigurationError: x/y targets are not supported for the Type step");let t=Re(),{thoughts:n}=await this.wrapTargetingAction({command:e,tracer:t,action:async o=>{"type"in o&&o.type==="NATIVE"?await this.doNativeType(e,o):await this.doWebviewType(e,o)},description:e.target.description});return{success:!0,message:n}}async doWebviewType(e,t){await Re().startAsyncSpan("EMULATOR_INTERACTION",async o=>{o.withinWebview=!0,o.attributes.options={clearContent:e.clearContent};let{controller:i}=t;await i.browser.type(e.text,{clearContent:e.clearContent,delay:e.keyPressDelayMs})},{name:"Typing within web view"})}async doNativeType(e,t){let n=new ai(this.constructPerformerParams());e.clearContent?(await n.tapOnNativeTarget(t,{longPress:!0}),await this.clearContent()):await n.tapOnNativeTarget(t),await this.stateManager.waitForScreenshotStability({timeoutMs:2e3,signal:this.aborter.controller?.signal,reason:"Waiting for keyboard to appear before typing"}),await this.sendKeys(e)}async sendKeys(e){let t=Re(),n=e.keyPressDelayMs;n?await t.startAsyncSpan("EMULATOR_INTERACTION",async()=>{await this.driver.updateSettings({keyInjectionDelay:n}),await this.driver.keys(e.text),await this.driver.updateSettings({keyInjectionDelay:0})},{name:"Typing keys with a delay"}):await t.startAsyncSpan("EMULATOR_INTERACTION",async()=>{await this.driver.keys(e.text)},{name:"Typing keys"})}async clearContent(){let e=Re();try{await e.startAsyncSection("Clearing any content from the focused field",()=>this.clearContentHelper())}catch(t){this.logger.warn({err:t},"Failed to clear content because the select all button was not found, continuing...")}}async clearContentHelper(){let e=this.driver.$('//android.widget.LinearLayout[@content-desc="Select all" and @clickable="true"]');await e.waitForExist({timeout:750}),await e.click(),await new An(this.constructPerformerParams()).doPress({keycode:67})}};import zt from"zod";var kw=.9,aF=zt.object({navigationBar:zt.object({visible:zt.boolean(),x:zt.number(),y:zt.number(),width:zt.number(),height:zt.number()}),statusBar:zt.object({visible:zt.boolean(),x:zt.number(),y:zt.number(),width:zt.number(),height:zt.number()})}),xc=class extends lr{async executeSwipe(e){let t=Re();if(e.scrollableElement.type!=="CUSTOM"){await this.stateManager.waitForScreenshotStability({timeoutMs:2e3,signal:this.aborter.controller?.signal,reason:"Waiting for screen to stabilize before swiping"});let n=await this.driver.getWindowRect(),o;if(e.scrollableElement.type==="SCREEN")o={left:n.x+25,top:n.y+50,width:n.width-50,height:n.height-100};else try{let i=aF.parse(await this.driver.executeScript("mobile: getSystemBars",[]));o={left:n.x+25,top:n.y+50,width:n.width-50,height:n.height-100},i.navigationBar.visible&&(o.height-=i.navigationBar.height),i.statusBar.visible&&(o.top+=i.statusBar.height,o.height-=i.statusBar.height)}catch(i){this.logger.warn({err:i},"Failed to get system bars, using hardcoded bounds"),o={left:n.x+50,top:n.y+100,width:n.width-100,height:n.height-200}}return await t.startAsyncSpan("EMULATOR_INTERACTION",async i=>{await this.swipeByAbsoluteCoordinates({span:i,direction:e.direction,percent:e.viewportPercent,durationMs:e.durationMs,containerBounds:o})},{name:`Swipe ${e.direction} in the entire ${e.scrollableElement.type.toLowerCase()}`}),{success:!0}}return await this.wrapTargetingAction({command:e,description:e.scrollableElement.target.description,action:async n=>Re().startAsyncSpan("EMULATOR_INTERACTION",async i=>"type"in n&&n.type==="NATIVE"?this.scrollInNativeContainer({span:i,cmd:e,target:n}):(i.withinWebview=!0,this.scrollInWebview({cmd:e,target:n})),{name:`Swipe ${e.direction} in the specified container`}),tracer:t}),{success:!0}}async scrollInNativeContainer({span:e,cmd:t,target:n}){let o=Math.floor(n.bounds[2]*.05),i=Math.floor(n.bounds[3]*.05);await this.swipeByAbsoluteCoordinates({span:e,direction:t.direction,percent:t.viewportPercent,durationMs:t.durationMs,containerBounds:{left:n.bounds[0]+o,top:n.bounds[1]+i,width:n.bounds[2]-n.bounds[0]-o*2,height:n.bounds[3]-n.bounds[1]-i*2}})}async scrollInWebview({cmd:e,target:t}){let{controller:n}=t,o=n.browser.getViewport();if(!o)throw new Error("Failed to get viewport size from webview");if(e.direction==="down"||e.direction==="up"){let i=o.height*(e.viewportPercent??kw)*(e.direction==="down"?1:-1);await n.browser.scrollVertical(i)}else{let i=o.width*(e.viewportPercent??.9)*(e.direction==="right"?1:-1);await n.browser.scrollHorizontal(i)}}async swipeByAbsoluteCoordinates({span:e,direction:t,percent:n=kw,durationMs:o=500,containerBounds:i}){e.attributes.containerBounds=i;let a,l;t==="up"||t==="down"?(a=i.height*n,l=Math.floor(a/(o/1e3))):(a=i.width*n,l=Math.floor(a/(o/1e3))),e.attributes.pixelDelta=a,e.attributes.pixelsPerSecond=l,await this.driver.executeScript("mobile: swipeGesture",[{...i,direction:t,percent:n,speed:l}])}};import{existsSync as sF,readFileSync as lF}from"fs";import cF from"zod";var uF=cF.string().url();async function Uw(r){if(uF.safeParse(r).success){let e=new AbortController,t=setTimeout(()=>e.abort(),1e4),n;try{n=await fetch(r,{signal:e.signal})}catch(i){throw new Error(`Fetch failed or timed out for URL: ${r}`,{cause:i})}finally{clearTimeout(t)}if(!n.ok)throw new Error(`Failed to fetch file from URL: ${r}, status: ${n.status}`);let o=await n.arrayBuffer();return Buffer.from(o).toString("base64")}if(!sF(r))throw new Error(`File does not exist at path: ${r}`);return lF(r).toString("base64")}import{execSync as zw}from"child_process";import mF from"pixelmatch";import{_android as gF,chromium as hF}from"playwright";import{PNG as Hw}from"pngjs";import{z as je}from"zod";var Fw=je.array(je.object({proc:je.string(),webview:je.string(),info:je.object({"Android-Package":je.string(),Browser:je.string(),"Protocol-Version":je.string(),"User-Agent":je.string(),"V8-Version":je.string(),"WebKit-Version":je.string(),webSocketDebuggerUrl:je.string()}),pages:je.array(je.object({description:je.string(),devtoolsFrontendUrl:je.string(),id:je.string(),title:je.string(),type:je.string(),url:je.string(),webSocketDebuggerUrl:je.string()})),webviewName:je.string()}));var Mc=class r{driver;device;currentContext;logger;webviews=new Map;fixtures;orgId;options;aborter;constructor({driver:e,context:t,logger:n,device:o,fixtures:i,orgId:a,options:l,aborter:c}){this.driver=e,this.device=o,this.currentContext=t,this.logger=n,this.fixtures=i,this.orgId=a,this.options=l,this.aborter=c;for(let s of["SIGINT","SIGTERM"])process.on(s,async()=>{await this.cleanupWebviews(),setImmediate(()=>{setTimeout(()=>{process.exit(1)},2e3).unref()})})}static async init({driver:e,logger:t,fixtures:n,orgId:o,adbPort:i,options:a,aborter:l}){let c=await e.getContext(),s=typeof c=="string"?c:c.id,u=(await gF.devices()).filter(m=>m._initializer?.serial?.endsWith(i.toString()));if(u.length!==1)throw new Error(`Playwright detected ${u.length} Android devices, expected 1. Please stop all other emulators and try again.`);let d=u[0];return new r({driver:e,context:s,logger:t,device:d,fixtures:n,orgId:o,options:a,aborter:l})}async getContexts(){let e=await this.driver.getContexts({}),t=Array.from(this.webviews.values());return{contexts:e,webviews:t.map(n=>({contextId:n.contextId,packageName:n.packageName,active:n.active,hasPlaywright:!!n.browserController,lastSeen:n.lastSeen,socketName:n.socketName}))}}async getRawScreenshotBase64(){return await Re().startAsyncSpan("EMULATOR_READ_STATE",()=>this.driver.takeScreenshot(),{name:"Emulator screenshot",signal:this.aborter.controller?.signal,timeoutMs:2e3})}async getCurrentScreenshotPngString(){return`data:image/png;base64,${await this.getRawScreenshotBase64()}`}async waitForScreenshotStability({timeoutMs:e,signal:t,reason:n,tolerancePercent:o=1}){await Re().startAsyncSpan("WAIT_FOR_STABILITY",async i=>{let a=Date.now(),l,c=!1,s=(u,d)=>{let p=Buffer.from(u,"base64"),m=Buffer.from(d,"base64"),g=Hw.sync.read(p),h=Hw.sync.read(m);if(g.width!==h.width||g.height!==h.height)return 100;let f=g.width,b=g.height,E=Buffer.alloc(f*b*4);return mF(g.data,h.data,E,f,b,{threshold:.01})/(f*b)*100};for(;Date.now()-a<e;){if(t?.throwIfAborted(),!l){l=await this.getRawScreenshotBase64();continue}let u=await this.getRawScreenshotBase64();if(s(l,u)<=o){c=!0;break}l=u,await X(250,t)}c||(i.attributes.timedOut=!0,this.logger.warn({purpose:n},"Timed out waiting for screenshot stability"))},{reason:n})}async getActiveWebviewContent(){let e=await this.getActiveWebview();if(!e||!e.browserController)return;this.throwIfAborted();let t=e.browserController;return(await Re().startAsyncSpan("EMULATOR_READ_STATE",()=>t.getBrowserState({abortSignal:this.aborter.controller?.signal,serializationOpts:{noId:!0}}),{name:"Get webview content",signal:this.aborter.controller?.signal})).serializedTree}async getDomState(e){return await Re().startAsyncSection("Get emulator state XML",async()=>{let n;if(!e?.skipWebviews)try{n=await this.getActiveWebviewContent()}catch(a){this.logger.error({err:a},"Could not get webview info to get the nested DOM state")}this.throwIfAborted();let o=await this.getPageSource();return{graph:await _w(o,{injectedWebviewContent:n,disableMomenticAccessibilityTree:this.options.disableMomenticAccessibilityTree}),context:this.currentContext}},{timeoutMs:15e3})}async getPageSource(){return await Re().startAsyncSpan("EMULATOR_READ_STATE",()=>this.driver.getPageSource(),{name:"Get Android page source",signal:this.aborter.controller?.signal})}async refreshWebviews(){await this.getPageSource(),this.throwIfAborted();let e=await this.getDetailedContexts();if(!e){this.logger.warn("No context details, not proceeding with refreshing webviews");return}let t=Date.now(),n=new Set;for(let o of e){if(this.throwIfAborted(),o.webview==="NATIVE_APP")continue;let i=o.info["Android-Package"];if(n.add(o.webview),!this.webviews.has(o.webview)||!this.webviews.get(o.webview)?.active){let a={contextId:o.webview,packageName:i,active:!1,lastSeen:t,socketName:o.proc.startsWith("@")?o.proc.substring(1):o.proc};this.logger.info({contextId:a.contextId,packageName:a.packageName,socketName:a.socketName},"New webview detected"),this.webviews.set(o.webview,a);let l;if(i==="com.android.chrome"?(l=await this.connectPlaywrightToChrome(a),this.logger.info(`Connected Playwright to Android Chrome: ${o.webview}`)):(this.logger.info(`Connecting Playwright to webview: ${o.webview}`),l=await this.connectPlaywrightToWebview(i,a.socketName),this.logger.info(`Connected Playwright to webview ${o.webview}`)),!l)continue;a.browserController=l,a.active=!0}}for(let[o,i]of this.webviews.entries())!n.has(o)&&i.active&&(this.logger.info(`Disconnecting dead webview ${o}`),this.disconnectPlaywrightFromWebview(i),i.active=!1)}async getActiveWebview(){await Re().startAsyncSection("Refresh webviews",async()=>{await this.refreshWebviews()});let e=await this.driver.execute("mobile: getCurrentPackage");e!==void 0&&typeof e!="string"&&this.logger.warn({currentPkg:e},"Unexpected getCurrentPackage result");let t=[];for(let n of this.webviews.values())n.packageName===e&&n.active&&t.push(n);if(t.length!==0){if(t.length>1)throw new Error("Multiple active webviews in a single package is currently not supported");return t[0]}}async executeRawADBCommand(e){let t=this.driver.capabilities,n=t.deviceUDID||t.udid||t["appium:udid"]||t["appium:deviceUDID"],o=process.env.ANDROID_HOME?`${process.env.ANDROID_HOME}/platform-tools/adb`:"adb",i=n?`-s ${n}`:"",a=`${o} ${i} ${e}`;this.logger.info(`Executing ADB command: ${a}`);let l=zw(a,{encoding:"utf8"});return this.logger.info(`ADB command result: ${l}`),l}async cleanupWebviews(){for(let[e,t]of this.webviews.entries())this.logger.info(`Disconnecting webview ${e}`),this.disconnectPlaywrightFromWebview(t),t.active=!1}async getDetailedContexts(){return await Re().startAsyncSpan("EMULATOR_READ_STATE",async()=>{let t=await this.driver.execute("mobile: getContexts");return this.aborter.controller?.signal.throwIfAborted(),Fw.parse(t)},{name:"Get available contexts",signal:this.aborter.controller?.signal})}async createBrowserController({context:e}){let t=await Fa.fromExistingContext({context:e,logger:this.logger,userBrowserSettings:{visualActions:!0},properties:{isNewHeadless:!0,allowedA11yIgnoreReasonsOverride:[],isAndroid:!0},storage:this.fixtures.storage,enricher:this.fixtures.browserEnricher});return new vc({browser:t,generator:this.fixtures.browserGenerator,logger:this.logger,orgId:this.orgId,storage:this.fixtures.storage,localCodeEvalTools:this.fixtures.localCodeEvalTools,visualDiffScreenshotStorage:new Ys})}async connectPlaywrightToWebview(e,t){return await Re().startAsyncSpan("EMULATOR_READ_STATE",async()=>this.connectPlaywrightToWebviewHelper(e,t),{name:"Connect headless browser client to webview",signal:this.aborter.controller?.signal,timeoutMs:5e3})}async connectPlaywrightToWebviewHelper(e,t){let o=this.device.webViews().find(a=>!(a.pkg()!==e||"_socketName"in a&&typeof a._socketName=="string"&&a._socketName!==t));if(!o){this.logger.warn(`[WebviewManager] Could not find webview for ${e} with socket name ${t}`);return}return this.logger.info({packageName:e,socketName:t},"Connecting Playwright to app webview"),await this.createBrowserController({context:(await o.page()).context()})}async connectPlaywrightToChrome(e){return await Re().startAsyncSpan("EMULATOR_READ_STATE",async()=>this.connectPlaywrightToChromeHelper(e),{name:"Connect headless browser client to Chrome",signal:this.aborter.controller?.signal})}async connectPlaywrightToChromeHelper(e){let{contextId:t,socketName:n}=e;try{this.logger.info({contextId:t,socketName:n},"Connecting to Chrome webview");let o;e.forwardedPort?(o=`http://127.0.0.1:${e.forwardedPort}`,this.logger.info({contextId:t,endpoint:o,socketName:n},"Using existing forwarded port")):(o=`http://127.0.0.1:${await this.forwardDevToolsSocket(e.socketName)}`,this.logger.info({contextId:t,endpoint:o,socketName:n},`Forwarding DevTools socket for ${e.socketName}`)),this.logger.info({endpoint:o,socketName:n},"Connecting to CDP endpoint");let i=await hF.connectOverCDP({endpointURL:o,timeout:5e3}),a=i.contexts()[0];if(!a){this.logger.warn("No browser context available after CDP connection"),await i.close();return}return this.createBrowserController({context:a})}catch(o){this.logger.error({err:o},`Error connecting Playwright to webview ${e.contextId}`);return}}async disconnectPlaywrightFromWebview(e){try{e.browserController&&(this.logger.info(`Disconnecting Playwright from webview: ${e.contextId}`),await e.browserController.browser.cleanup(),e.browserController=void 0),e.forwardedPort&&await this.removeDevToolsForwarding(e.forwardedPort)}catch(t){this.logger.error({err:t},`Error disconnecting Playwright from webview ${e.contextId}:`)}}async forwardDevToolsSocket(e){this.logger.info("Setting up port forwarding for DevTools");let t=1e4+Math.floor(Math.random()*1e4),n=this.driver.capabilities,o=n.deviceUDID||n.udid||n["appium:udid"]||n["appium:deviceUDID"];this.logger.info({deviceId:o},`Device ID from capabilities: ${o||"not found"}`);let i=process.env.ANDROID_HOME?`${process.env.ANDROID_HOME}/platform-tools/adb`:"adb",a=o?`-s ${o}`:"",l=`${i} ${a} forward tcp:${t} ${`localabstract:${e}`||"localabstract:chrome_devtools_remote"}`;this.logger.info(`Executing command: ${l}`);let c=zw(l,{encoding:"utf8"});return this.logger.info(`ADB command result: ${c}`),this.logger.info(`Successfully forwarded DevTools socket to port ${t}`),t}async removeDevToolsForwarding(e){await this.executeRawADBCommand(`forward --remove tcp:${e}`),this.logger.info("Successfully removed port forwarding")}throwIfAborted(){this.aborter.controller?.signal.throwIfAborted()}};var si=class r extends lr{options;appsWithGrantedPermissions=new Set;adbPort;constructor(e){super(e),this.options=e.options??{},this.adbPort=e.adbPort}static async init({driver:e,generator:t,logger:n,fixtures:o,orgId:i,options:a,abortController:l,adbPort:c}){let s={controller:l},u=await Mc.init({driver:e,logger:n,fixtures:o,orgId:i,options:a?.emulator??{},aborter:s,adbPort:c}),d=new r({driver:e,generator:t,stateManager:u,logger:n,fixtures:o,options:a,aborter:s,orgId:i,adbPort:c});return await d.initializeSettings(),d}async installApp(e){await this.stateManager.executeRawADBCommand(`install ${SF.resolve(e)}`)}async executeCommand(e){let t=["type","a11yData","thoughts","cache","code"],n;try{n=await Kl({obj:e.command,context:this.fixtures.testContext,bannedKeys:t,orgId:this.orgId,logger:this.logger,signal:this.abortSignal,localTools:this.fixtures.localCodeEvalTools})}catch(o){throw this.throwIfAborted(),new Error(`ActionFailureError: Failed to substitute template strings in command: ${o.message}`,{cause:o})}try{return await this.executeCommandHelper(e)}catch(o){throw o.name!=="AbortError"&&this.logger.error({err:o},"Error thrown in action controller"),o}finally{Yl(e.command,n)}}async executeCommandHelper({command:e}){let t=Re();switch(e.type){case"TAP":return new ai(this.constructPerformerParams()).executeTap({command:e});case"TYPE":return await new Cc(this.constructPerformerParams()).doType(e);case"AI_CHECK":{let o=e.timeoutSecs?e.timeoutSecs*1e3:5e3,i=tc(o),a=Date.now(),l=0,c,s=!1,u;for(;l<15&&!s;){this.throwIfAborted(),s||c&&c-a>=o&&(s=!0),l!==0&&await X(i,this.abortSignal),c=Date.now();try{let d="",p="";await t.startAsyncSpan("EMULATOR_READ_STATE",async()=>{d=(await this.stateManager.getDomState({})).graph.xml,p=await this.stateManager.getCurrentScreenshotPngString()},{name:"Get emulator state"});let m=await t.startAsyncSpan("AI_ASSERTION_CALL",async g=>{let h=await this.generator.evaluateAssertion({assertion:e.assertion,screenXml:d,screenshot:p},{logger:this.logger,loggerTags:pe(this.logger)});return g.result={thoughts:h.thoughts,result:h.result},h});if(m.result)return{success:m.result,message:m.thoughts};{let g=`AssertionFailureError: ${m.thoughts}`;u=new Error(g)}}catch(d){this.throwIfAborted(),this.logger.info({err:d},`AI check assert attempt ${l} failed, retrying...`),u=d instanceof Error?d:new Error(`${d}`)}finally{l++}}return{success:!1,message:u?.message}}case"SWIPE":return new xc(this.constructPerformerParams()).executeSwipe(e);case"JAVASCRIPT":{let n=await Ir({orgId:this.orgId,code:e.code,fragment:!1,context:this.fixtures.testContext,timeoutMs:e.timeout?e.timeout*1e3:void 0,logger:this.logger,localTools:this.fixtures.localCodeEvalTools,signal:this.abortSignal});try{JSON.stringify(n)}catch(o){throw new Error(`UserConfigurationError: Return value is not serializable: ${o instanceof Error?o.message:`${o}`}`)}return{success:!0,output:n}}case"REQUEST":{let n;try{n=new URL(e.url).hostname}catch(s){throw new Error(`UserConfigurationError: Invalid URL: ${s}`)}let o=new yF,i=fF(fetch,o),a=Date.now(),l=await Tc({command:e,baseUrl:void 0,logger:this.logger,fetchImplementation:i}),c=Is(o,n);return{output:{...l,cookies:c},success:!0,message:`Successfully executed request in ${Date.now()-a}ms`}}case"OPEN_NOTIFICATION_DRAWER":return await new An(this.constructPerformerParams()).doPress({keycode:83}),{success:!0};case"OPEN_APP":{let n=e.activityName;if(!n){let i=["resolve-activity","--brief","-a","android.intent.action.MAIN","-c","android.intent.category.LAUNCHER",e.packageName],a=await B(this.driver.execute("mobile: shell",{command:"pm",args:i}),{signal:this.abortSignal,milliseconds:1e4});if(typeof a!="string")throw new Error(`Could not find main activity name for package ${e.packageName}. Unexpected output: ${a}`);if(a.includes("No activity found"))throw new Error(`No activity found for package ${e.packageName}.`);if(n=a.trim().split(`
|
|
4038
|
+
`).pop()?.replace(/^.*\//,""),!n)throw new Error(`Could not parse main activity name for package ${e.packageName}. Raw output: ${a}`)}if(this.options.emulator?.autoGrantPermissions&&!this.appsWithGrantedPermissions.has(e.packageName)){let i={permissions:"all",appPackage:e.packageName,action:"grant"};await this.driver.executeScript("mobile: changePermissions",[i]),this.appsWithGrantedPermissions.add(e.packageName)}let o=["start"];if(e.intentExtras)try{let i=JSON.parse(e.intentExtras);for(let[a,l]of Object.entries(i))o.push("-e",a,typeof l=="string"?l:JSON.stringify(l))}catch(i){throw new Error(`UserConfigurationError: Invalid intent extras does not parse as valid JSON: ${i instanceof Error?i.message:`${i}`}`)}return o.push("-n",`${e.packageName}/${n}`),await this.driver.execute("mobile: shell",{command:"am",args:o}),await this.stateManager.waitForScreenshotStability({timeoutMs:5e3,signal:this.abortSignal,reason:"Waiting for stability after app launch"}),{success:!0}}case"PRESS":{let n=new An(this.constructPerformerParams());switch(e.key){case"HOME":await n.doPress({keycode:3});break;case"BACK":await n.doPress({keycode:4});break;case"APP_SWITCHER":await n.doPress({keycode:187});break;case"POWER":await n.doPress({keycode:26});break;case"SEARCH":await n.doPress({keycode:84});break;case"VOLUME_UP":await n.doPress({keycode:24});break;case"VOLUME_DOWN":await n.doPress({keycode:25});break;case"VOLUME_MUTE":await n.doPress({keycode:164});break}return{success:!0}}case"PRESS_KEYBOARD":{let n=new An(this.constructPerformerParams()),o=i=>n.doPress({keycode:i});switch(e.key){case"CLOSE_KEYBOARD":await this.driver.isKeyboardShown()&&await this.driver.hideKeyboard();break;case"ENTER":await o(66);break;case"BACKSPACE":await o(67);break;default:{let i=e}}return{success:!0}}case"WAIT":return await X(e.timeoutSecs*1e3,this.aborter.controller?.signal),{success:!0};case"ADD_FILE":{let n=await Uw(e.file);return await this.driver.pushFile(e.storageLocation,n),await this.driver.execute("mobile: shell",{command:"am",args:["broadcast","-a","android.intent.action.MEDIA_SCANNER_SCAN_FILE","-d",`file://${e.storageLocation}`]}),{success:!0}}case"ADB":{let n=await this.driver.execute(e.command,JSON.parse(e.jsonArgs??"{}"));return this.logger.info({output:n},"ADB command executed successfully"),{success:!0,output:n,message:"ADB command executed successfully"}}case"STATE":{await this.stateManager.refreshWebviews();let n=await this.stateManager.getDomState(),o=await this.stateManager.getContexts(),i={xml:n.graph.xml,contexts:o};return this.logger.info({result:i},"State debug command output"),{output:i,success:!0}}default:{let n=e;return{success:!0}}}}async initializeSettings(){}async getScreenshotBase64(){return this.stateManager.getRawScreenshotBase64()}async getScreenshotPngString(){return this.stateManager.getCurrentScreenshotPngString()}async getA11yTree(){return(await this.stateManager.getDomState({})).graph.xml}async waitForScreenshotStability(e){return this.stateManager.waitForScreenshotStability({timeoutMs:e.timeoutMs??5e3,reason:e.reason,signal:this.aborter.controller?.signal})}resetAbortController(e){this.aborter.controller=e??new AbortController}isAborted(){return this.aborter.controller?.signal.aborted}abort(){this.aborter.controller?.abort()}get abortSignal(){return this.aborter.controller?.signal}get context(){return this.fixtures.testContext}get localCodeEvalTools(){return this.fixtures.localCodeEvalTools}};async function Gw({socket:r,logger:e,androidDriverFactory:t,getOrgId:n,mobileGeneratorFactory:o,browserGeneratorFactory:i,browserEnricherFactory:a,storageFactory:l,localToolsFactory:c,globalStateManager:s,settingsFactory:u}){let d=r.id,p=r.handshake.query?.testMetadata,m=r.handshake.query?.fileName,g=m?.endsWith("test.yaml")?m.slice(0,-"test.yaml".length):m,h=vr.parse(JSON.parse(p??"")),f=h.id,b=h.settings?.defaultChannel,E=h.settings?.defaultTag,v=await n({testId:f});e=e.child({sessionId:d,testId:f,orgId:v});let T={...(await u(v,e)).emulator,...h.settings?.emulator},_=Date.now(),{driver:M,cleanup:z,limbarToken:Y,limbarUrl:Ee,emulatorName:oe,adbTunnelPort:ge}=await t({socket:r,logger:e,creationOpts:{region:T.region,apkToInstall:b?{channel:b,tag:E}:void 0}}),et=await ql({driver:M,onLogs:Vt=>{r.emit("logcatLogs",Vt)}});e.info({adbTunnelPort:ge,apkChannel:b,apkTag:E,duration:Date.now()-_,emulatorName:oe},"Android emulator session initiated"),e=e.child({emulator:oe});let j=await o(v,e),U=await i(v,e),ne=await a(v,e),ae=await l(v),Ne=c?await c(v):void 0,he={};h.settings?.defaultEnv&&(he=(await ae.fetchEnvironment(h.settings?.defaultEnv,e))?.variables??{});let dt=new Po({variablesFromEnvironment:he,envName:h.settings?.defaultEnv,testName:g}),Gt=await si.init({driver:M,generator:j,logger:e,options:{emulator:T},fixtures:{storage:ae,browserEnricher:ne,browserGenerator:U,localCodeEvalTools:Ne,testContext:dt},orgId:v,adbPort:ge,abortController:new AbortController});if(!r.connected)throw await et(),await z(),new Error("Socket not connected anymore, not proceeding with Android session setup");let Ae=bF({socket:r,testContext:dt}),tt=async()=>{clearInterval(Ae);try{await et(),await z()}catch(Vt){e.warn({err:Vt},"Failed to clean up emulator in socket server")}};return s.registerSession(d,{controller:Gt,cleanup:tt,emulatorName:oe}),r.emit("session",{testId:f,sessionId:d,limbarUrl:Ee,limbarToken:Y}),{sessionId:d,testId:f,orgId:v,emulatorName:oe,logger:e}}function bF({socket:r,testContext:e}){return setInterval(()=>{let t=e.toEditorDisplayCopy();r.emit("emulatorState",{context:t})},3e3)}async function Vw({socket:r,logger:e,globalStateManager:t}){await t.removeSession(r.id,e)}var EF=({socket:r,globalStateManager:e})=>async()=>{let t=e.getSession(r.id);if(!t)throw new Error("No active Android session found");t.controller.abort()},jw={event:"cancel",createHandler:EF};var TF=({logger:r,globalStateManager:e,socket:t})=>async(n,o)=>{let i=e.getSession(t.id);if(!i){o({err:"No active Android session found"});return}try{let l=await i.controller.getA11yTree();o({a11yTree:l})}catch(a){r.error({err:a},"Error fetching a11y tree from the session controller"),o({err:a.message})}},Ww={event:"fetchA11yTree",createHandler:TF};import{diff as FF}from"deep-object-diff";import{cloneDeep as BF}from"lodash-es";function $w(r,e,t=1e4,n=5e3){let o=0;async function i(){try{let l=await B(r.driver.execute("mobile: shell",{command:"echo",args:["ping"]}).catch(c=>{throw c}),{milliseconds:n});if(typeof l=="string"&&l.trim()==="ping")o>0&&e.info("Driver heartbeat restored"),o=0;else throw new Error(`Unexpected heartbeat output: ${l}`)}catch(l){o++;let c=l instanceof Error?l.message:`${l}`;e.error({attempt:o,error:c},"Driver heartbeat failed"),o>=3&&e.error("Driver appears unresponsive \u2014 possible ADB tunnel/emulator failure")}}let a=setInterval(()=>{i()},t);return i(),a}async function qw(r){let e=Date.now(),t=r.fixtures.controller;try{return await vF(r)}catch(n){let o=t.isAborted()||n instanceof DOMException&&n.name==="AbortError";return{...r.moduleParams.step,steps:[],type:"MOBILE_MODULE_STEP",startTime:e,endTime:Date.now(),status:o?"CANCELLED":"FAILED",message:o?"Step cancelled.":`${n}`}}}async function vF({moduleParams:r,...e}){let t=Date.now(),{step:n,stepTracer:o,executeMobileStepList:i}=r,a=await AF({step:n,params:e}),l={};Object.entries(a).forEach(([p,m])=>{l[p]=JSON.stringify(m)});let c={...n,type:"MOBILE_MODULE_STEP",inputs:l,startTime:t,steps:[],endTime:Date.now(),status:"SUCCESS"},s=await o.startSubSteps(),{status:u,results:d}=await i({...e,listParams:{steps:n.steps,containerName:`module ('${n.name}')`,tracer:s}});return c.steps=d,c.status=u,c.endTime=Date.now(),cv({result:c,...lv(d)}),c}async function AF({step:r,params:e}){let t={},{logger:n,controller:o}=e.fixtures;for(let i of r.parameters?.parameterNames??[]){let a=r.inputs?.[i]??r.parameters?.defaultParameters?.[i];if(!a){n.warn({k:i},"No value found for parameter in module");continue}t[i]=await Ir({orgId:e.inputs.orgId,code:a,fragment:!0,logger:n,context:o.context,localTools:o.localCodeEvalTools})}return t}import{randomUUID as Kw}from"crypto";async function Yw({fixtures:r,step:e,inputs:t,stepTracer:n}){let o=Date.now(),{logger:i,controller:a}=r,l;if(!t.interactive)try{l=await a.getScreenshotBase64()}catch(s){i.warn({err:s},"Failed to take before screenshot")}let c={...e,status:"SUCCESS",startTime:o,endTime:Date.now()};try{let s=await a.executeCommand({command:e.command});c={...e,status:s.success?"SUCCESS":"FAILED",message:s.message,startTime:o,endTime:Date.now(),data:s.output}}catch(s){s instanceof Error&&s.name==="AbortError"||a.isAborted()?c={...e,status:"CANCELLED",message:"Step cancelled.",startTime:o,endTime:Date.now()}:(i.error({err:s},"Failed to execute preset step"),c={...e,status:"FAILED",message:s instanceof Error?s.message:String(s),startTime:o,endTime:Date.now()})}finally{if(!t.interactive){try{let s=Kw(),u=await a.getScreenshotBase64();c.afterSnapshot=s,n.attachAfterScreenshot({logger:i,snapshotId:s,screenshot:Buffer.from(u,"base64")})}catch(s){i.warn({err:s},"Failed to take after screenshot")}if(l){let s=Kw();c.beforeSnapshot=s,n.attachBeforeScreenshot({logger:i,snapshotId:s,screenshot:Buffer.from(l,"base64")})}}}return c}import{streamText as NF}from"ai";import{randomUUID as DF}from"crypto";var _c=class{controller;logger;callbacks;rootStep;subStepIndex=0;finalState=void 0;results=[];constructor(e){let{controller:t,logger:n,callbacks:o,rootStep:i}=e;this.controller=t,this.logger=n,this.callbacks=o,this.rootStep=i}async createAndExecuteStep(e){this.callbacks.onAiActionEvent?.({type:"SUBSTEP_CREATED",rootStep:this.rootStep,step:e});let t=this.subStepIndex++,n=await this.callbacks.executeStep(e,t);return this.results.push(n),n}};import{hasToolCall as OF,stepCountIs as LF}from"ai";var Xw="get_emulator_state",Ic="finish";import Jw from"dedent";var RF=Jw`
|
|
4039
|
+
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.
|
|
4040
|
+
`,Zw=r=>Jw`
|
|
4041
|
+
<background>
|
|
4042
|
+
You are an advanced, AI agent part of an end-to-end testing platform called Momentic.
|
|
4043
|
+
Momentic uses AI agents to translate high-level natural language descriptions of user flows into browser automation for the purpose of validating application correctness.
|
|
4044
|
+
You are an agent specialized in autonomously generating e2e test steps on an Android mobile emulator.
|
|
4045
|
+
|
|
4046
|
+
The steps you generate will be fed to downstream Momentic agents that are responsible for actually converting the steps into Appium code and executing them on a connected emulator. These "executor" agents rely on AI and are not fool proof - you may need to prompt engineer.
|
|
4047
|
+
</background>
|
|
4048
|
+
|
|
4049
|
+
<task>
|
|
4050
|
+
The user will provide you with a high-level goal to achieve. Your task is to use the tools at your disposal to make as much progress as you can towards accomplishing the goal until one of the following is true:
|
|
4051
|
+
- You have successfully accomplished the goal, fulfilling all criteria specified by the user. In this case, end the generation cycle by calling the "finish" tool with success=true.
|
|
4052
|
+
- You have determined that the goal is impossible to accomplish or too vague to interpret confidently. In this case, end the generation cycle by calling the "finish" tool with success=false. Some examples of why a goal could be impossible: a) the goal requires a step type or capability that is not available to you; b) the user's app crashes or displays a 500 internal server error page; c) Momentic's AI agents repeatedly fail to perform the correct interaction, which could indicate an accessibility issue with the app.
|
|
4053
|
+
${r?"":RF}
|
|
4054
|
+
</task>
|
|
4055
|
+
|
|
4056
|
+
<values>
|
|
4057
|
+
Momentic users value the following:
|
|
4058
|
+
- Accuracy: The generated automation should faithfully execute the user's intent. E.g. you should only interact with elements that are reasonably connected to the user's goal. When generating steps, you should make sure to follow all step-specific instructions in the step's schema and populate all options correctly.
|
|
4059
|
+
- Intelligence: You should display thorough and sound reasoning capabilities at all times. E.g. you should analyze the current browser state with high proficiency when determining what step to execute next or whether the user's goal has been accomplished.
|
|
4060
|
+
- Sentience: You should display a reasonable amount of self-sufficiency and assertiveness. Do not blindly follow impossible instructions or retry failed steps endlessly. You should be able to recover from your own mistakes and handle transient errors such as timing related issues or race conditions gracefully.
|
|
4061
|
+
</values>
|
|
4062
|
+
|
|
4063
|
+
<rules>
|
|
4064
|
+
1. Validate after running: After running a step, always analyze the step result and the state of the emulator after the step to determine if the step actually performed the intended task. If Momentic's downstream agents performed the wrong action, determine if the error is recoverable and if so, undo the incorrect action before re-attempting.
|
|
4065
|
+
2. Webviews handling: Webview state is injected into the emulator's XML tree whenever the emulator state is returned to you. The webview state is a processed and slimmed-down version of the webview's accessibility tree. Momentic's AI agents are capable of interacting with elements inside the webview, but the agents that specialize in webview interaction do not see the rest of the native context, and vice-versa.
|
|
4066
|
+
3. Generating assertions: You should generate AI_CHECK steps in two situations only:
|
|
4067
|
+
a) The user's explicitly asks you to validate certain behavior ("e.g. log in and check that the profile is populated"). You have performed all the actions required to set up the correct state for the assertion to be true. Now, the current state should be checked against the expected state. If the user doesn't explicitly state a timeout or number of retries, you can generate and retry an assertion up to 3 times with the default timeout.
|
|
4068
|
+
b) There is a loading state that blocks you from proceeding with generation, and you need to wait until the state changes. In this case, you can generate an AI_CHECK step for the anticipated "done" state (e.g. "There is no loading spinner visible"). Unless explicitly specified by the user, you can generate and retry an assertion up to 3 times with a timeout up to 30 seconds each.
|
|
4069
|
+
If the max. allowed retries is exceeded, fail the generation cycle by calling "finish".
|
|
4070
|
+
</rules>
|
|
4071
|
+
`;import{tool as MF}from"ai";import{randomUUID as _F}from"crypto";import IF from"zod";import{tool as CF}from"ai";import xF from"zod";var Qw=r=>{let e=CF({description:"Get the current state of the emulator (XML + screenshot)",inputSchema:xF.object({}),toModelOutput:t=>t,execute:async()=>{let{controller:t,logger:n}=r;return n.info("AI action tool called (get_emulator_state)"),Nm(t)}});return{name:Xw,tool:e}};async function Nm(r){let e=await r.getA11yTree(),t=await r.getScreenshotBase64();return{type:"content",value:[{type:"text",text:e},{type:"text",text:"</emulatorXml>"},{type:"text",text:"<screenshot>"},{type:"media",data:t,mediaType:"image/png"},{type:"text",text:"</screenshot>"}]}}var eR=r=>({name:"create_execute_step",tool:MF({description:"Create and immediately execute a new Momentic step in the Android emulator, returning the result from the step and the state of the emulator after the step finished executing.",inputSchema:IF.object({step:sd}),toModelOutput:t=>t,execute:async({step:t})=>{let{contextManager:n,logger:o,controller:i}=r;o.info({step:t},"AI action tool called (create_execute_step)");let a=Kf(t),l={id:_F(),type:"MOBILE_PRESET_STEP",command:a},c=await n.createAndExecuteStep(l);c.status==="SUCCESS"&&await i.waitForScreenshotStability({reason:"Waiting for stability after executing AI-generated sub-step"});let s={...c,trace:void 0,beforeSnapshot:void 0,afterSnapshot:void 0},u=await Nm(i);return{type:"content",value:[{type:"text",text:"<result>"},{type:"text",text:JSON.stringify(s,null,2)},{type:"text",text:"</result>"},{type:"text",text:"<stateAfter>"},...u.value,{type:"text",text:"</stateAfter>"}]}}})});import{tool as PF}from"ai";import Dm from"zod";var tR=r=>{let e=PF({description:"Signal that the AI action has reached a terminal state (either success or failure).",inputSchema:Dm.object({message:Dm.string(),success:Dm.boolean()}),toModelOutput:t=>t,execute:async({message:t,success:n})=>{let{contextManager:o,logger:i}=r;return i.info({message:t,success:n},"AI action tool called (finish)"),o.finalState={message:t,status:n?"SUCCESS":"FAILED"},{type:"content",value:[{type:"text",text:"Done"}]}}});return{name:Ic,tool:e}};var rR=[eR,Qw,tR];function nR(r){let{logger:e,controller:t,contextManager:n,aiActionSessionId:o}=r,i={};for(let c of rR){let s=c({contextManager:n,logger:e,controller:t});i[s.name]=s.tool}let a=t.generator.getVercelAnthropicModelFactory({loggerTags:pe(e),sessionId:o}),l=c=>{let{messages:s}=c,u=!1;for(let d=s.length-1;d>=0;d--){let p=s[d];for(let m of p.content)if(!(typeof m!="object"||!("type"in m))&&!(m.type!=="tool-result"||m.output.type!=="content")&&!(m.output.value.length<3))for(let g=0;g<m.output.value.length;g++){let h=m.output.value[g];if(h.type==="text"&&h.text.includes("<emulatorXml>"))if(u){let f=m.output.value[g+1];f.type==="text"?f.text="TRUNCATED DUE TO CONVERSATION LENGTH":e.warn({msg:f},"Got unexpected part when truncating emulator state message")}else{u=!0;continue}}}return c};return{model:a("claude-haiku-4-5-20251001"),tools:i,prepareStep:l,stopWhen:[LF(15),OF(Ic)],system:Zw(!1)}}async function oR(r){let e=Date.now(),{controller:t,logger:n}=r.fixtures;try{return await kF(r)}catch(o){let i=t.isAborted()||o instanceof DOMException&&o.name==="AbortError";return i||n.error({err:o},"Failed to execute mobile AI action"),{...r.aiActionParams.step,steps:[],type:"MOBILE_AI_ACTION_STEP",startTime:e,endTime:Date.now(),status:i?"CANCELLED":"FAILED",message:i?"Step cancelled.":`${o}`}}}async function kF(r){let{step:e,stepTracer:t,executeMobileStepList:n}=r.aiActionParams,{controller:o,logger:i}=r.fixtures,{step:a}=r.callbacks,l=await t.startSubSteps(),c=DF(),s=i.child({stepId:e.id,aiActionSessionId:c}),u=Date.now(),d=async(f,b)=>{let E=await n({...r,listParams:{steps:[f],tracer:l,containerName:`AI action sub-step ${b}`}});if(E.results.length!==1)throw new Error("InternalWebAgentError: Expected exactly one result from executeMobileStepList");return E.results[0]},p={stepId:e.id,parentStepIdChain:t.getParentStepIdChain()},m=new _c({controller:o,callbacks:{onAiActionEvent:a?.onAiActionEvent,executeStep:d},logger:s,rootStep:p}),g=nR({controller:o,logger:s,contextManager:m,aiActionSessionId:c}),h=NF({...g,messages:[{role:"user",content:e.text}]});for await(let f of h.fullStream)switch(f.type){case"text-delta":a?.onAiActionEvent?.({type:"LLM_TEXT_OUTPUT",text:f.text,rootStep:p})}if(await h.response,o.throwIfAborted(),!m.finalState)throw new Error("InternalWebAgentError: The AI agent never reached a final state. This could be because the maximum number of steps was reached.");return{...e,status:m.finalState.status,startTime:u,endTime:Date.now(),message:m.finalState.message,steps:m.results}}async function Pc(r){let{fixtures:e,inputs:t,listParams:n}=r,{containerName:o,steps:i,tracer:a}=n,{logger:l,controller:c,usageTracker:s}=e,u=a.getParentStepIdChain(),d=[],p,m="SUCCESS",{fromStep:g,toStep:h}=t,f=!!g;for(let b=0;b<i.length;b++){let E=i[b];if(l.info({step:E},`Executing step ${b+1}/${i.length} in ${o}: ${tv(E)}`),E.skipped){l.debug("Step skipped");continue}if(f&&g){let _=JSON.stringify(u);if(E.id===g.fromStepId&&_===JSON.stringify(g.parentStepIdChain))f=!1;else if(!sv({currentStep:E,currentParentChain:u,desiredStepId:g.fromStepId,desiredStepParentChain:g.parentStepIdChain}))continue}let v=await a.startStep({logger:l,step:E,attempt:1,parentStepIdChain:u});s.trackStepExecution(E);let R=await UF({step:E,stepTracer:v,params:r}),{trace:T}=await v.finish({parentStepIdChain:u,result:R});if(R.trace=T,l.info({step:{id:E.id},trace:R.trace,status:R.status},`Step ${b+1}/${i.length} done (${E.type==="MOBILE_PRESET_STEP"?E.command.type:E.type})`),d.push(R),R.status!=="SUCCESS"){m=R.status,p=R;break}if(E.envKey&&c.context.setVariable(E.envKey,R.data),h){let _=JSON.stringify([]);if(E.id===h.toStepId&&_===JSON.stringify(h.parentStepIdChain))break}}return{results:d,status:m,terminalResult:p}}async function UF({step:r,stepTracer:e,params:t}){let{fixtures:n,inputs:o,callbacks:i}=t,a;switch(r.type){case"MOBILE_PRESET_STEP":{a=await Yw({fixtures:n,inputs:o,step:r,stepTracer:e,callbacks:i});break}case"RESOLVED_MOBILE_MODULE":{a=await qw({...t,moduleParams:{step:r,stepTracer:e,executeMobileStepList:Pc}});break}case"MOBILE_AI_ACTION_STEP":{a=await oR({...t,aiActionParams:{step:r,stepTracer:e,executeMobileStepList:Pc}});break}}return a}async function Oc(r){let{tracer:e,containerName:t}=r,{steps:n,testMetadata:o}=r.inputs,{cacheStorage:i,logger:a,controller:l}=r.fixtures;await i.resolveEntries({logger:a,testId:o.id,stepLists:{steps:n}});let c=BF(n);a.info({testMetadata:vr.parse(o)},"Starting mobile test");let s=await e.startMainStepList(),u=Py(a),d=$w(l,a);a.info({cpu:u?.cpuMetadata,platform:u?.platform},`Starting execution of ${t}`);let{status:p,results:m}=await Pc({...r,listParams:{containerName:t,tracer:s,steps:c}});if(clearInterval(u?.interval),clearInterval(d),p==="SUCCESS"){let g=FF(c,n);if(g&&Object.keys(g).length>0){a.debug({diffs:g},"Saving mobile step cache entries post-success");let{cachesToSave:h}=await Zn({steps:c,cacheCreationParams:{orgId:r.inputs.orgId,testId:o.id}});await i.saveEntries({logger:a,testId:o.id,entries:h})}return{status:"PASSED",results:m}}return p==="CANCELLED"?{status:"CANCELLED",results:m}:{status:"FAILED",results:m}}var km=class{parentTracer=null;socket;step;interactionTracer;constructor({step:e,socket:t,parentTracer:n}){this.socket=t,this.parentTracer=n,this.step=e,this.interactionTracer=new oo,$r.initializeRootTracerContext(this.interactionTracer)}attachBeforeScreenshot(){}attachAfterScreenshot(){}attachBeforeHtmlSnapshot(){}attachAfterHtmlSnapshot(){}async finish(e){this.interactionTracer.finish();let t=this.interactionTracer.getRootSpan(),n={...Ey.parse(e),trace:ud.parse(t)};switch(n.result.status){case"SUCCESS":this.socket.emit("success",n);break;case"FAILED":this.socket.emit("failure",n);break;case"CANCELLED":this.socket.emit("cancelled",n);break}return{trace:t}}getParentStepIdChain(){return this.parentTracer?this.parentTracer?.getParentStepIdChain()??[]:[]}async startSubSteps(){return new ci({parentStep:this.step,socket:this.socket,parentTracer:this})}},ci=class{parentTracer;parentStep;socket;constructor({parentStep:e,socket:t,parentTracer:n}){this.parentTracer=n,this.parentStep=e,this.socket=t}getParentStepIdChain(){return this.parentStep?[...this.parentTracer?.getParentStepIdChain()??[],this.parentStep.id]:[]}async startStep(e){return this.socket.emit("started",{stepId:e.step.id,parentStepIdChain:e.parentStepIdChain,attempt:e.attempt}),new km({step:e.step,parentTracer:this,socket:this.socket})}},Lc=class{constructor(e){this.socket=e}appendLogs(){}async finish(){this.socket.emit("finished")}async startBeforeStepList(){return new ci({parentStep:null,parentTracer:null,socket:this.socket})}async startMainStepList(){return new ci({parentStep:null,parentTracer:null,socket:this.socket})}async startAfterStepList(){return new ci({parentStep:null,parentTracer:null,socket:this.socket})}};var zF=({metadata:r,logger:e,globalStateManager:t,socket:n,cacheStorageFactory:o})=>async(i,a)=>{let l=t.getSession(n.id);if(!l)throw new Error("No active Android session found");let c=e.child({testId:i.testMetadata.id}),s=await o(r.orgId),u=l.controller;u.resetAbortController();let d=new Lc(n),p=await Oc({fixtures:{controller:u,logger:c,cacheStorage:s,usageTracker:new Ms},containerName:"entire test",inputs:{steps:i.steps,fromStep:i.fromStep,toStep:i.toStep,orgId:r.orgId,testMetadata:i.testMetadata,interactive:!0},tracer:d,callbacks:{step:{onAiActionEvent:g=>{n.emit("aiActionEvent",g)}}}});await d.finish();let m={results:tr.array().parse(p.results),status:p.status};a?.(m)},iR={event:"execute",createHandler:zF};import{debounce as HF}from"ts-debounce";var GF=({socket:r,globalStateManager:e,keepSessionAlive:t})=>{let n=HF(t,3e4,{maxWait:6e4});return async()=>{let o=e.getSession(r.id);if(!o)throw new Error("No active Android session found");o.emulatorName&&n(o.emulatorName)}},aR={event:"keepalive",createHandler:GF};var sR=[iR,jw,aR,Ww];function lR(r){let{logger:e,baseServer:t,globalStateManager:n}=r,o=new VF(t,{cors:{origin:"*",methods:["GET","POST"]},pingTimeout:15*60*1e3,pingInterval:15*60*1e3,maxHttpBufferSize:1e7,perMessageDeflate:!0}),i=async()=>{await n.removeAllSessions(e)};o.on("connection",async l=>{let c=l.id,s=e.child({sessionId:c});s.info({event:"connection",transport:l.conn.transport.name},"Android websocket connection initiated"),l.on("disconnect",async()=>{await Vw({socket:l,globalStateManager:n,logger:s})});let u;try{u=await Gw({...r,socket:l,globalStateManager:n,logger:s})}catch(d){s.error({err:d},"Failed to setup Android connection"),l.emit("error",{message:d instanceof Error?d.message:JSON.stringify(d)}),l.disconnect(!0);return}sR.forEach(d=>a(d,{...r,socket:l,metadata:u,logger:s}))});let a=(l,c)=>{let s=l.createHandler(c),u=(...d)=>{l.event!=="keepalive"&&c.logger.debug({event:l.event},`Websocket event (${l.event})`);let p=m=>{c.logger.error({event:l.event,err:m instanceof Error?m:new Error(`${m}`)},"Unhandled exception in socket handler"),c.socket.emit("error",{message:m instanceof Error?m.message:`${m}`})};try{let m=s.apply(this,d);m&&typeof m.catch=="function"&&m.catch(p)}catch(m){p(m)}};c.socket.on(l.event,u)};return{server:o,dispose:i}}import{confirm as $F,input as qF}from"@inquirer/prompts";import{existsSync as $xe,mkdirSync as qxe,statSync as KF}from"fs";import ui,{supportsColor as WF}from"chalk";import{Console as cR}from"console";import{format as Ga}from"util";var Um=class extends Error{constructor(e,t,n){let o=Error.stackTraceLimit;n&&(Error.stackTraceLimit=Math.max(n,o||10)),super(e),Error.captureStackTrace&&Error.captureStackTrace(this,t),Error.stackTraceLimit=o}},Nc=class r extends cR{_buffer=[];_groupDepth=0;Console=cR;constructor(){super({write:e=>(r.write(this._buffer,"log",e),!0)})}static write(e,t,n,o=2){let i=new Um(void 0,r.write).stack;if(!i)return e;let a=i.split(`
|
|
4027
4072
|
`).slice(o).filter(Boolean).join(`
|
|
4028
|
-
`);return e.push({message:n,origin:a,type:t}),e}_log(e,t){r.write(this._buffer,e," ".repeat(this._groupDepth)+t,3)}debug(e,...t){this._log("debug",
|
|
4073
|
+
`);return e.push({message:n,origin:a,type:t}),e}_log(e,t){r.write(this._buffer,e," ".repeat(this._groupDepth)+t,3)}debug(e,...t){this._log("debug",Ga(e,...t))}error(e,...t){this._log("error",Ga(e,...t))}info(e,...t){this._log("info",Ga(e,...t))}log(e,...t){this._log("log",Ga(e,...t))}warn(e,...t){this._log("warn",Ga(e,...t))}getBuffer(){return this._buffer.length>0?this._buffer:void 0}};function uR(r){let e=globalThis.console,t=new Nc;globalThis.console=t;try{r()}finally{let o=t.getBuffer()?.map(i=>i.message).join(`
|
|
4029
4074
|
`);process.stderr.write(`${o}
|
|
4030
|
-
`),globalThis.console=e}}var Qm=" ".repeat(6);import{hostname as PB}from"os";var Bt=Hc({app:"cli",hostname:PB(),disableConsoleLogs:!0}).child({cliVersion:"0.0.30"});function eg(r){if(!r)return;r=r.toLowerCase();let e=Zl.safeParse(r);if(e.success)return x.setMinLevel(e.data),e.data}function RR({results:r,startTime:e,entity:t,getDisplayLine:n,onFailed:o}){let i=r.filter(u=>u.status==="PASSED"&&u.quarantined),a=r.filter(u=>u.status==="PASSED"&&!u.quarantined),s=r.filter(u=>u.status==="FAILED"&&u.quarantined),c=r.filter(u=>u.status==="FAILED"&&!u.quarantined),l=r.filter(u=>u.status==="CANCELLED");return wR(()=>{if(c.forEach(u=>{x.log(""),o(u)}),c.length){x.log("");let u=c.length===1?"":"s";x.error(`${c.length} ${t}${u} failed:`),c.forEach(d=>{x.dimmed(n(d))})}if(l.length){x.log("");let u=l.length===1?"":"s";x.warn(`${l.length} ${t}${u} cancelled:`),l.forEach(d=>{x.dimmed(n(d))})}if(a.length){x.log("");let u=a.length===1?"":"s";x.success(`${a.length} ${t}${u} passed:`),a.forEach(d=>{x.dimmed(n(d))})}if(s.length){x.log("");let u=s.length===1?"":"s";x.warn(`${s.length} quarantined ${t}${u} failed:`),s.forEach(d=>{x.dimmed(n(d))})}if(i.length){x.log("");let u=i.length===1?"":"s";x.warn(`${i.length} quarantined ${t}${u} passed:`),i.forEach(d=>{x.dimmed(n(d))})}x.log(""),x.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 Qa=({status:r,testLogRef:e,getRunningTestsCount:t,getTotalTestsCount:n,additionalText:o})=>{r=r.toUpperCase();let i=r,a;r.includes("FAIL")?(i=vi.bgRed.white("FAIL"),a=3):r.includes("PASS")?(i=vi.bgGreen.white("PASS"),a=3):r.includes("START")?(i=vi.bgBlue.white("START"),a=2):r.includes("CANCEL")?(i=vi.bgRgb(191,68,11).white("CANCEL"),a=1):r.includes("RETRY")?(i=vi.bgRgb(191,68,11).white("RETRY"),a=2):r.includes("RUN")||r.includes("PROG")?(i=vi.bgMagenta.white("RUNNING"),a=0):(x.warn(`Unknown status tried to be logged in run test locally: ${r}`),a=0),OB||(i=`${i}`),x.log(`${i}${" ".repeat(a)} ${e} ${o?`${o} `:""}(${t()}/${n()})`)};var DB=!1,CR=(()=>{try{return kB("/.dockerenv"),!0}catch{return!1}})();async function Wc(r){return yo||DB||CR?!0:(x.flush(),Bt.flush(),await new Promise(t=>setTimeout(t,500)),await LB({message:r}))}async function xR(r,e){return yo||CR?e:(await NB({message:r,default:e})).trim()||e}import UB from"fs";import{tmpdir as FB}from"os";import BB from"path";import{registry as es}from"playwright-core/lib/server";import _R from"proper-lockfile";var MR=BB.join(FB(),"momenticBrowserInstallation");var tg=["chrome","chromium","chrome-for-testing"],zB={Chromium:"chromium","Google Chrome":"chrome","Chrome for Testing":"chrome-for-testing"},IR={chrome:"chrome",chromium:"chromium","chrome-for-testing":"chromium-headless-shell"};function PR(r){let e=IR[zB[r]??""]??"",t=es.findExecutable(e);return!t||t.installType==="none"?!1:rg(t)}function rg(r){let e=r.executablePath();return UB.existsSync(e)}function HB(r,e){let t=IR[r];if(!t)throw new Error(`Requested install of unknown browser type ${r}`);let n=es.findExecutable(t);if(!n||n.installType==="none")throw new Error(`Requested install of unknown browser type ${r}`);if(!(!e&&rg(n)))return n}async function GB({browser:r,force:e}){let t=HB(r,e);if(!t){x.info(`Browser '${r}' is already installed, skipping...`);return}x.info(`Installing browser '${r}'...`);try{await es.installDeps([t],!1),await es.install([t],!1)}catch(n){if(n.message.includes("Lock file is already being held")){x.warn("Another process is installing Playwright browsers. Waiting for completion before proceeding..");let o=es.findExecutable(r),i=5*60*1e3,a=Date.now();for(;Date.now()-a<i&&!rg(o);)x.info("Waiting for browser to finish installing..."),await new Promise(s=>setTimeout(s,5e3))}else throw n}}async function $c({rawBrowsers:r,force:e=!1,all:t=!1}){let n=t?tg:Array.from(new Set(r));try{await _R.lock(MR,{stale:1e3*60*5,update:1e3*60,realpath:!1,retries:{retries:30,factor:2,maxTimeout:15e3,minTimeout:500}})}catch(i){x.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 GB({browser:i,force:e})}catch(a){o=a,x.error(`Failed to install the ${i} browser: ${a}`)}}finally{await _R.unlock(MR,{realpath:!1})}if(o)throw o}import{createServer as jB}from"http";async function qc(r,e){for(let n=0;n<30;n+=1){let o=r+n;if(await VB(o))return o}x.error(`Could not find an available port for ${e} starting from ${r} after 30 attempts`),process.exit(1)}async function VB(r){return new Promise((e,t)=>{let n=jB();n.once("error",o=>{o.code==="EADDRINUSE"?e(!1):(x.warn({err:o},"Unexpected error checking for open ports, continuing..."),n.close(),e(!0))}),n.once("listening",()=>{n.close(()=>{e(!0)})}),n.listen(r)})}import rMe from"blocked-at";import oMe from"why-is-node-running";import{randomUUID as cG}from"crypto";import{diff as GMe}from"deep-object-diff";import QMe from"yaml";import{z as tIe}from"zod";import{execSync as WB}from"child_process";function bo(r,e){let t=e.hooks?.postSave;if(!t)return;let n;t.includes("$1")?n=t.replaceAll("$1",r):n=`${t} ${r}`,x.debug({postSaveCommand:n},"Executing post-save hook command");try{WB(n,{encoding:"utf-8"})}catch(o){x.warn({err:o,postSaveCommand:n},"Failed to execute post-save hook command, continuing...")}}import{diff as bMe}from"deep-object-diff";import{cloneDeep as TMe}from"lodash-es";import{v4 as LMe}from"uuid";import kMe from"yaml";import $B from"@dotenvx/dotenvx";import qB from"fs";import OR from"path";function KB(r){return r.includes("${")?r.replace(/\$\{([^}]+)\}/g,(e,t)=>{let[n,o]=t.split(/:-|-/,2),i=process.env[n];return t.includes(":-")?i&&i!==""?i:o||"":t.includes("-")?i!==void 0?i:o||"":i||""}):r}function YB(r){let{envVariables:e,project:t}=r;if(!e)return{};let n={};for(let[o,i]of Object.entries(e)){if(typeof i=="string"){let s=KB(i);s&&(n[o]=s);continue}let a;try{a=qB.readFileSync(OR.resolve(t.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&&x.debug(n,"Set environment variables with interpolation from project configuration"),n}function XB(r){let{project:e,envFile:t,logger:n}=r,o={};if(!t)return o;let i=$B.config({path:OR.resolve(e.rootDir,t),processEnv:o,logLevel:"error",quiet:!0});if(i.error)throw new Error(`Failed to load .env file: ${i.error.message}`);return n.debug(o,"Set environment variables from .env file"),o}function Kc(r,e,t){let n=(e.config.environments??[]).find(c=>c.name===r);if(!n)throw new Error(`Environment ${r} not found in local project configuration file`);let o={},i=YB({envVariables:n.envVariables,project:e});Object.assign(o,i);let a=XB({project:e,envFile:n.envFile,logger:t});return Object.assign(o,a),n.inheritFromShell&&(t.debug(process.env,"Inheriting environment variables from shell"),Object.assign(o,process.env)),{name:r,variables:o}}import{existsSync as c1,readFileSync as u1,readdirSync as d1,writeFileSync as p1}from"fs";import{glob as m1}from"glob";import Eo,{dirname as kR}from"path";import{cwd as sg}from"process";import DR from"yaml";import{z as Ie}from"zod";import LR from"fs";import{glob as JB}from"glob";import ts from"path";import ZB from"yaml";import{z as ng}from"zod";var NR=!1,og=["**/*.test.yaml","**/*.module.yaml"],ig=ng.string().refine(r=>/^[a-zA-Z0-9-]+$/.test(r)),ag=15,QB=ng.object({fileType:ng.nativeEnum(_e)});async function vr(r,e=!1){let t={project:r,tests:{},modules:{},mobileTests:{},mobileModules:{},duplicateEntities:{}},n=r.config.include??og,o=Array.from(r.config.exclude??[]).concat(Xl),i=AbortSignal.timeout(5e3),a;try{a=await JB(n,{absolute:!1,cwd:r.rootDir,ignore:o,dotRelative:!1,maxDepth:ag,nodir:!0,signal:i})}catch(s){throw x.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=e1(r.rootDir,s,t,e?Rn:x);c&&(t.duplicateEntities[c.id]=c.paths)}return NR=!0,t}function e1(r,e,t,n){let o=ts.join(r,e),i=t1(o,n);if(!i)return;let a=r1(i,o,n);if(!a)return;let s=QB.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=n1(o,n);if(!l)return;let u=o1(e,o,l);switch(c){case _e.TEST:try{return i1(a,t,u,o,n)}catch(d){n.warn(`Skipping file '${o}' because it is missing Momentic test metadata: ${d}`);return}case _e.MODULE:try{return a1(a,t,u,o,n)}catch(d){n.warn(`Skipping file '${o}' because it is missing Momentic module metadata: ${d}`);return}case _e.MOBILE_TEST:try{return l1(a,t,u,o,n)}catch(d){n.warn(`Skipping file '${o}' because it is missing Momentic mobile test metadata: ${d}`);return}case _e.MOBILE_MODULE:try{return s1(a,t,u,o,n)}catch(d){n.warn(`Skipping file '${o}' because it is missing Momentic mobile module metadata: ${d}`);return}default:{let d=c;return}}}function t1(r,e){try{return LR.readFileSync(r,"utf-8")}catch(t){e.warn(`Could not read possible Momentic file at ${r}, skipping: ${t}`);return}}function r1(r,e,t){try{let n=ZB.parse(r);if(typeof n!="object"||n===null)throw new Error("The YAML document should parse as a map with key-value pairs");return n}catch(n){t.warn(`Could not parse possible Momentic file at ${e}, skipping: ${n}`);return}}function n1(r,e){try{return LR.statSync(r)}catch(t){e.warn(`Skipping path '${r}' because it could not be stat, skipping: ${t}`);return}}function o1(r,e,t){return{relativePath:r,fullFilePath:e,platformSep:ts.sep,fullPathSegments:e.split(ts.sep),relativePathSegments:r.split(ts.sep),fileName:ts.basename(e),lastModified:t.mtime,createdAt:t.birthtime}}function i1(r,e,t,n,o){let i=ai.parse(r),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:_e.TEST,name:i.name,id:i.id,description:i.description??void 0,labels:i.labels,...t},a}function a1(r,e,t,n,o){let i=tr.parse(r),a;if(e.modules[i.moduleId]){let c=e.modules[i.moduleId].fullFilePath;a={id:i.moduleId,paths:[c,n]}}e.modules[i.moduleId]={type:_e.MODULE,name:i.name,id:i.moduleId,description:i.description??void 0,...t};let s=t.fileName.replace(".module.yaml","");return!NR&&fn(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 s1(r,e,t,n,o){let i=La.parse(r),a;if(e.mobileModules[i.moduleId]){let c=e.mobileModules[i.moduleId].fullFilePath;a={id:i.moduleId,paths:[c,n]}}let s=t.fileName.replace(".module.yaml","");return e.mobileModules[i.moduleId]={type:_e.MOBILE_MODULE,name:s,id:i.moduleId,description:i.description??void 0,...t},a}function l1(r,e,t,n,o){let i=Or.parse(r),a;if(e.mobileTests[i.id]){let c=e.mobileTests[i.id].fullFilePath;a={id:i.id,paths:[c,n]}}let s=t.fileName.replace(".test.yaml","");return e.mobileTests[i.id]={type:_e.MOBILE_TEST,name:s,id:i.id,description:i.description??void 0,...t},a}var Ai="momentic.config.yaml",lg="momentic.workspace.yaml",g1=Ie.object({projects:Ie.string().array().describe("list of glob patterns to find project (momentic.config.yaml) files")}),h1=Ie.union([Ie.string(),Ie.object({fromFile:Ie.string(),json:Ie.boolean().optional()})]),f1=Ie.object({name:ig,baseUrl:Ie.string().optional().describe("Optional for mobile tests"),envFile:Ie.string().optional().describe("path to a file on disk to read environment variables from. can be relative to project root or absolute."),envVariables:Ie.record(Ie.string(),h1).optional(),inheritFromShell:Ie.boolean().optional().describe("inherit all environment variables from the shell - might be noisy"),browser:Qn.optional().describe("deprecated: use project-level configuration only")}),S1=Ie.object({postSave:Ie.string().optional()}),y1=Ie.object({name:ig,include:Ie.string().array().optional().describe("list of glob patterns that match momentic files (optional)"),exclude:Ie.string().array().optional().describe("opposite of include, takes precedence over include"),goldenFileDir:Ie.string().optional(),reporterDir:Ie.string().optional(),outputDir:Ie.string().optional(),retries:Ie.number().optional().describe("number of retries per test"),parallel:Ie.number().optional().describe("degree of parallelism"),environments:Ie.array(f1).optional(),gitMainBranch:Ie.string().optional(),gitProtectedBranches:Ie.string().array().optional(),ai:kp.optional(),browser:Qn.optional(),emulator:_p.optional(),advanced:Dp.optional(),hooks:S1.optional()});function UR(r,e){let t;try{t=u1(r,"utf-8")}catch(o){x.warn(`Could not read possible Momentic ${e} file at ${r}: ${o}`);return}let n;try{if(n=DR.parse(t),typeof n!="object"||n===null)throw new Error(`The ${e} file should parse as a map with key-value pairs, but is type ${typeof n} instead`)}catch(o){x.warn(`Possible Momentic ${e} file at ${r} does not parse as valid YAML: ${o}`);return}return n}function cg(r){let e=UR(r,"project configuration");if(e!==void 0)try{return y1.parse(e)}catch(t){x.warn(`Possible Momentic project configuration file at ${r} does not adhere to the required schema: ${t}`);return}}function b1(r){let e=UR(r,"workspace configuration");if(e!==void 0)try{return g1.parse(e)}catch(t){x.warn(`Possible Momentic workspace configuration file at ${r} does not adhere to the required schema: ${t}`);return}}function E1(){let r=[],e=sg(),t=Eo.parse(e).root,n=15,o=0;for(;o<n;){o++;let i=Eo.basename(e);if(Yl.includes(i))return x.warn(`Stopping search for Momentic projects since the current directory name (${i}) is likely a system artifact folder.`),r;for(let a of d1(e))if(a.endsWith(Ai)){let s=Eo.join(e,a),c=cg(s);c&&r.push({configFilePath:s,config:c,rootDir:kR(s)})}if(r.length)return r;if(e=Eo.dirname(e),e===t)break}return r}async function rs(r={}){let{configFilePath:e,nameFilter:t}=r,n=await v1(e);if(t&&(n=n.filter(o=>o.config.name===t)),n.length>1)throw new Error(`Multiple valid projects were found in the same directory. Please use the '-c / --config' flag to disambiguate:
|
|
4031
|
-
${n.map(o=>o.configFilePath)}`);if(n.length===0)throw new Error("No valid Momentic project file available.");return
|
|
4032
|
-
`)){let o=n.indexOf("=");if(o===-1)continue;let i=n.slice(0,o),a=n.slice(o+1).trim();t[i]=a}return t}async function x1(r,e,t){try{let o=t["github.user"]||void 0;if(o)return o}catch{}let n;try{if(e?.startsWith("http://")||e?.startsWith("https://"))n=new URL(e).host;else if(e?.startsWith("git@")){let o=e.indexOf("@"),i=e.indexOf(":",o+1);o!==-1&&i!==-1&&(n=e.slice(o+1,i))}}catch{}if(n=n?.toLowerCase(),!!n){try{if(e?.startsWith("git@")&&n?.includes("github")){let{stdout:o,stderr:i}=await zR("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{}try{let o=n&&n!=="github.com"?["api","--hostname",n,"user","-q",".login"]:["api","user","-q",".login"],{stdout:i}=await zR("gh",o,{timeout:5e3}),a=i?.toString().trim();if(a)return a}catch{}}}async function _1(r,e,t){let n=e?.includes("github.com"),o=e?.includes("gitlab.com");try{if(n)return x1(r,e,t);if(o)return}catch{}}function Yc(r){if(r.startsWith("git@")){let e=r.split(":");if(e.length===2){let t=e[1].replace(".git","").split("/");if(t.length===2){let n=t[0],o=t[1];return`${n}/${o}`}}}else if(r.startsWith("http")||r.startsWith("https")){let t=new URL(r).pathname.split("/").filter(Boolean);if(t.length>=2){let n=t[0],o=t[1].replace(".git","");return`${n}/${o}`}}}async function Oe(r,e){try{return(await e).trim()}catch(t){r.error({err:t},"Failed to run git command");return}}function M1(){if(process.env.GITHUB_ACTION)return"GithubActions";if(process.env.GITLAB_CI)return"GitlabCI";if(process.env.CIRCLECI)return"CircleCI";if(process.env.BUILDKITE)return"Buildkite";if(process.env["System.CollectionUri"]?.includes("azure"))return"AzureDevOps";if(process.env.PROJECT_ID&&process.env.BUILD_ID)return"GCPCloudBuild"}async function I1(r){let[e,t,n]=await Promise.all([Oe(r,Pe.show(["--no-patch","--format=%ci"])),Oe(r,Pe.show(["-s","--pretty=%B"])),Oe(r,Pe.show(["-s","--pretty=%an"]))]),o=process.env.GITHUB_SERVER_URL&&process.env.GITHUB_REPOSITORY?`${process.env.GITHUB_SERVER_URL}/${process.env.GITHUB_REPOSITORY}`:void 0;return{gitCommitSha:process.env.GITHUB_SHA,gitCommitShaShort:process.env.GITHUB_SHA?.slice(0,6),gitCommitTimestamp:e?new Date(e):void 0,gitBranchName:process.env.GITHUB_HEAD_REF||process.env.GITHUB_REF_NAME,gitOriginUrl:o,gitCommitMessage:t,gitCommitAuthorName:n,githubRepository:process.env.GITHUB_REPOSITORY,pipelineId:process.env.GITHUB_RUN_ID}}async function P1(r){let[e,t,n]=await Promise.all([Oe(r,Pe.listRemote(["--get-url","origin"])),Oe(r,Pe.show(["-s","--pretty=%B"])),Oe(r,Pe.show(["-s","--pretty=%an"]))]);return{gitCommitSha:process.env.CI_COMMIT_SHA,gitCommitShaShort:process.env.CI_COMMIT_SHORT_SHA,gitCommitTimestamp:process.env.CI_COMMIT_TIMESTAMP?new Date(process.env.CI_COMMIT_TIMESTAMP):void 0,gitBranchName:process.env.CI_COMMIT_BRANCH||process.env.CI_COMMIT_REF_NAME,gitOriginUrl:e,gitCommitMessage:t,gitCommitAuthorName:n,gitlabProjectPath:process.env.CI_PROJECT_PATH,pipelineId:`${process.env.CI_PIPELINE_ID}:${process.env.CI_JOB_ID}`}}async function O1(r){let[e,t,n,o]=await Promise.all([Oe(r,Pe.show(["--no-patch","--format=%ci"])),Oe(r,Pe.listRemote(["--get-url","origin"])),Oe(r,Pe.show(["-s","--pretty=%B"])),Oe(r,Pe.show(["-s","--pretty=%an"]))]),i=t?.includes("github.com"),a=t?.includes("gitlab.com"),s=t?Yc(t):void 0;return{gitCommitSha:process.env.CIRCLE_SHA1,gitCommitShaShort:process.env.CIRCLE_SHA1?.slice(0,6),gitCommitTimestamp:e?new Date(e):void 0,gitBranchName:process.env.CIRCLE_BRANCH,gitOriginUrl:process.env.CIRCLE_REPOSITORY_URL,gitCommitMessage:n,gitCommitAuthorName:o,githubRepository:i?s:void 0,gitlabProjectPath:a?s:void 0,pipelineId:process.env.CIRCLE_PIPELINE_ID}}async function L1(r){let[e,t,n]=await Promise.all([Oe(r,Pe.show(["--no-patch","--format=%ci"])),Oe(r,Pe.show(["-s","--pretty=%B"])),Oe(r,Pe.show(["-s","--pretty=%an"]))]),o=process.env.BUILDKITE_REPO,i=o?.includes("github.com"),a=o?.includes("gitlab.com"),s=o?Yc(o):void 0;return{gitCommitSha:process.env.BUILDKITE_COMMIT,gitCommitShaShort:process.env.BUILDKITE_COMMIT?.slice(0,6),gitCommitTimestamp:e?new Date(e):void 0,gitBranchName:process.env.BUILDKITE_BRANCH,gitOriginUrl:o,gitCommitMessage:t,gitCommitAuthorName:n,githubRepository:i?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 N1(r){let[e,t,n]=await Promise.all([Oe(r,Pe.show(["--no-patch","--format=%ci"])),Oe(r,Pe.show(["-s","--pretty=%B"])),Oe(r,Pe.show(["-s","--pretty=%an"]))]),o=process.env["Build.Repository.Uri"],i=o?.includes("github.com"),a=o?.includes("gitlab.com"),s=o?Yc(o):void 0;return{gitCommitSha:process.env["Build.SourceVersion"],gitCommitShaShort:process.env["Build.SourceVersion"]?.slice(0,6),gitCommitTimestamp:e?new Date(e):void 0,gitBranchName:process.env["Build.SourceBranchName"],gitOriginUrl:o,gitCommitMessage:t,gitCommitAuthorName:n,githubRepository:i?s:void 0,gitlabProjectPath:a?s:void 0,pipelineId:`${process.env["System.JobId"]}:${process.env["System.JobAttempt"]}`}}async function k1(r,e){let[t,n,o,i,a,s,c,l,u]=await Promise.all([Oe(r,Pe.revparse(["HEAD"])),Oe(r,Pe.revparse(["--short","HEAD"])),Oe(r,Pe.revparse(["--abbrev-ref","HEAD"])),Oe(r,Pe.listRemote(["--get-url","origin"])),Oe(r,Pe.show(["--no-patch","--format=%ci"])),Oe(r,Pe.show(["-s","--pretty=%B"])),Oe(r,Pe.show(["-s","--pretty=%an"])),e?Oe(r,Pe.raw(["merge-base","--fork-point",e])):Promise.resolve(void 0),C1(r)]),d=l?await Oe(r,Pe.show(["--no-patch","--format=%ci",l])):void 0,p=i?.includes("github.com"),g=i?.includes("gitlab.com"),m=i?Yc(i):void 0,h=u["user.email"]||void 0,f=u["user.name"]||void 0,E=u["user.username"]||void 0,S=await _1(r,i,u)??E??void 0;return{gitCommitSha:t,gitCommitShaShort:n,gitBranchName:o,gitOriginUrl:i,gitCommitTimestamp:a?new Date(a):void 0,gitCommitMessage:s,gitCommitAuthorName:c,gitLocalUsername:S,gitLocalEmail:h,gitLocalName:f,lastCommitOnMainSha:l,lastCommitOnMainTimestamp:d?new Date(d):void 0,githubRepository:p?m:void 0,gitlabProjectPath:g?m:void 0,pipelineId:void 0}}async function D1(){let r=process.env._HEAD_REPO_URL;return{gitCommitSha:process.env.COMMIT_SHA,gitCommitShaShort:process.env.COMMIT_SHA?.slice(0,6),gitBranchName:process.env.BRANCH_NAME,gitOriginUrl:r?process.env._HEAD_REPO_URL:void 0,gitCommitTimestamp:void 0,gitCommitMessage:void 0,gitCommitAuthorName:void 0,githubRepository:r?process.env.REPO_FULL_NAME:void 0,pipelineId:`${process.env.PROJECT_ID}:${process.env.BUILD_ID}`}}async function U1(r){let e=r.config.gitProtectedBranches??[];return r.config.gitMainBranch&&e.push(r.config.gitMainBranch),{gitMainBranch:r.config.gitMainBranch,gitProtectedBranches:e}}async function dg(r,e){let t=M1();if(!t)return k1(r,e);switch(t){case"GithubActions":return I1(r);case"GitlabCI":return P1(r);case"CircleCI":return O1(r);case"Buildkite":return L1(r);case"AzureDevOps":return N1(r);case"GCPCloudBuild":return D1()}}async function F1(r,e,t,n){let o=n;if(!n.gitCommitSha)return o;if(n.gitMainBranch&&(!o.lastCommitOnMainSha||!o.lastCommitOnMainTimestamp))try{let i=await e.getMergeBaseCommitFromGitlab(t,n.gitMainBranch,n.gitCommitSha);o={...o,lastCommitOnMainSha:i.sha,lastCommitOnMainTimestamp:i.committer.date}}catch(i){r.warn({err:i},"Failed to get merge base commit from Gitlab")}if(!o.gitCommitTimestamp||!o.gitCommitAuthorName||!o.gitCommitMessage||!o.gitCommitAuthorName)try{let i=await e.getCommitFromGitlab(t,n.gitCommitSha);i&&(o={...o,gitCommitTimestamp:o.gitCommitTimestamp??i.committer.date,gitCommitAuthorName:o.gitCommitAuthorName??i.author.name,gitCommitMessage:o.gitCommitMessage??i.message})}catch(i){r.warn({err:i},"Failed to get commit from Gitlab")}if(n.gitBranchName&&n.gitBranchName===n.gitMainBranch&&!o.mergedGitBranchName)try{let i=await e.getMergedBranchFromGitlab(t,n.gitBranchName??"",n.gitCommitSha);i.mergedBranch&&(o={...o,mergedGitBranchName:i.mergedBranch})}catch(i){r.warn({err:i},"Failed to get merged branch from Gitlab")}return o}async function B1(r,e,t,n,o){let i=o;if(!o.gitCommitSha)return i;if(o.gitMainBranch&&(!i.lastCommitOnMainSha||!i.lastCommitOnMainTimestamp))try{let a=await e.getMergeBaseCommitFromGithub(t,n,o.gitMainBranch,o.gitCommitSha);i={...i,lastCommitOnMainSha:a.sha,lastCommitOnMainTimestamp:a.committer.date}}catch(a){r.warn({err:a},"Failed to get merge base commit from GitHub")}if(!i.gitCommitTimestamp||!i.gitCommitAuthorName||!i.gitCommitMessage||!i.gitCommitAuthorName)try{let a=await e.getCommitFromGithub(t,n,o.gitCommitSha);a&&(i={...i,gitCommitTimestamp:i.gitCommitTimestamp??a.committer.date,gitCommitAuthorName:i.gitCommitAuthorName??a.author.name,gitCommitMessage:i.gitCommitMessage??a.message})}catch(a){r.warn({err:a},"Failed to get commit from GitHub")}if(o.gitBranchName&&o.gitBranchName===o.gitMainBranch&&!i.mergedGitBranchName)try{let a=await e.getMergedBranchFromGithub(t,n,o.gitBranchName??"",o.gitCommitSha);a.mergedBranch&&(i={...i,mergedGitBranchName:a.mergedBranch})}catch(a){r.warn({err:a},"Failed to get merged branch from GitHub")}return i}async function z1(r,e,t){try{if(t.githubRepository){let[n,o]=t.githubRepository.split("/");return await B1(r,e,n,o,t)}else if(t.gitlabProjectPath)return await F1(r,e,t.gitlabProjectPath,t)}catch(n){r.warn({err:n},"Failed to get remote git metadata")}return t}async function Xc(r,e,t){let n=await U1(t),o=await dg(r,n.gitMainBranch),i={...n,...o};(!i.lastCommitOnMainSha||!i.lastCommitOnMainTimestamp)&&i.gitBranchName===n.gitMainBranch&&(i.lastCommitOnMainSha=i.gitCommitSha,i.lastCommitOnMainTimestamp=i.gitCommitTimestamp);let a=await z1(r,e,i);return{...n,...o,...a}}import{diff as HR}from"deep-object-diff";import To from"fs";import{cloneDeep as H1}from"lodash-es";import pg from"path";import{v4 as aPe}from"uuid";import Jc from"yaml";function GR({content:r,schemaVersion:e,momenticFiles:t,project:n,forceSaveOnNoDiffs:o}){let i=t.mobileModules[r.moduleId]?.fullFilePath;if(!i||!To.existsSync(i))throw new Error(`Tried to update mobile module ${r.moduleId} that could not be found on disk`);let a=To.readFileSync(i,"utf-8"),s=Jc.parse(a),c={...s,...r,schemaVersion:e},l=io({fileType:_e.MOBILE_MODULE,...La.parse(c),steps:yr.array().parse(r.steps)}),u=HR(l,s);if(u&&Object.keys(u).length===0&&!o)return;let d=Jc.stringify(l);To.writeFileSync(i,d,"utf-8"),bo(i,n.config)}function jR({moduleId:r,patch:e,momenticFiles:t,project:n,logger:o}){let i=t.mobileModules[r]?.fullFilePath;if(!i)throw new Error(`Tried to update mobile module ${r} that could not be found on disk`);let a=ns(i,o),s={...a,...e},c=io({fileType:_e.MOBILE_MODULE,...Gl.parse(s)}),l=HR(c,a);if(l&&Object.keys(l).length===0)return;let u=Jc.stringify(c);To.writeFileSync(i,u,"utf-8");let d;if(e.name){let p=`${fn(e.name)}.module.yaml`;if(d=pg.join(pg.dirname(i),p),To.existsSync(d))throw new Error(`A conflicting file already exists at the following path: ${d}`);To.renameSync(i,d)}bo(d||i,n.config)}function ns(r,e){let t=To.readFileSync(r,"utf-8"),n=Jc.parse(t);try{return{...Gl.parse(n),name:pg.basename(r,".module.yaml")}}catch(o){throw e.error({err:o,moduleFilePath:r,moduleContents:t},`${r} does not parse as a valid Momentic mobile module`),o}}async function mg(r,e,t,n){let o=ns(r.fullFilePath,t),{resolvedSteps:i}=await uc({rawSteps:o.steps,resolvedModuleCache:n||{},onFetchModule:async s=>{let c=e.mobileModules[s]?.fullFilePath;if(!c)throw new Error(`Could not find mobile module with id ${s}`);return ns(c,t)},logger:t,metadata:{id:o.moduleId,schemaVersion:o.schemaVersion}}),a={...o,name:r.name,steps:i};return n&&(n[r.id]=H1(a)),a}async function VR(r,e){let t={};return await Promise.all(Object.values(r.mobileModules).map(async n=>{await mg(n,r,e,t)})),Array.from(Object.values(t))}import{randomUUID as G1}from"crypto";import vo from"fs";import gg from"path";import Zc from"yaml";function WR({name:r,description:e="",steps:t=[],settings:n={},folder:o}){let a=`${fn(r)}.test.yaml`,s=gg.join(o,a);if(vo.existsSync(s))throw new Error(`A test named '${r}' already exists at path '${s}'. Choose a different name.`);let c={fileType:_e.MOBILE_TEST,id:G1(),description:e,schemaVersion:Zd,settings:n,steps:t},l=Zc.stringify(c);return vo.writeFileSync(s,l,"utf-8"),{fullPath:s,testId:c.id}}function j1(r){if(!vo.existsSync(r))throw new Error(`Test file not found: ${r}`);let e=vo.readFileSync(r,"utf-8").replace(/\r\n|\r/g,`
|
|
4033
|
-
`),t=
|
|
4034
|
-
`),c=Zc.parse(s),l=Wl.parse(c);if(l.fileType!==_e.MOBILE_TEST)throw new Error(`File at '${a}' is not a mobile test (fileType=${l.fileType}).`);let u;e&&(u=await lo({steps:e}));let d={...l,...u?.stepsToSave!==void 0?{steps:u.stepsToSave}:{},...t!==void 0?{settings:t}:{}},p=Zc.stringify(Wl.parse(d));for(let g of u?.moduleUpdates??[])GR({content:g,schemaVersion:Zd,momenticFiles:i,project:o});vo.writeFileSync(a,p,"utf-8"),bo(a,o.config)}import{randomUUID as V1}from"crypto";import Qr from"fs";import Ao from"path";var qR={status:(r,e)=>{if(r.status===e.status)return r.status;if(r.status==="FAILED"||e.status==="FAILED")return"FAILED";if(r.status==="CANCELLED"||e.status==="CANCELLED")return"CANCELLED";if(r.status==="RETRYING"||e.status==="RETRYING")return"RETRYING";if(r.status==="RUNNING"||e.status==="RUNNING")return"RUNNING";if(r.status==="PENDING"||e.status==="PENDING")return"PENDING";throw new Error(`Invalid run status merge: ${r.status} and ${e.status}`)},startedAt:(r,e)=>r.startedAt<e.startedAt?r.startedAt:e.startedAt,updatedAt:(r,e)=>r.updatedAt>e.updatedAt?r.updatedAt:e.updatedAt,finishedAt:(r,e)=>!r.finishedAt||!e.finishedAt?new Date:r.finishedAt>e.finishedAt?r.finishedAt:e.finishedAt,gitCommitTimestamp:(r,e)=>{if(!(!r&&!e)){if(!r.gitCommitTimestamp||!e.gitCommitTimestamp||r.gitCommitTimestamp.getTime()!==e.gitCommitTimestamp.getTime())throw new Error(`Git commit timestamps must match to be merged: ${r.gitCommitTimestamp} and ${e.gitCommitTimestamp}`);return r.gitCommitTimestamp}},pipelineId:(r,e)=>r.pipelineId===e.pipelineId?r.pipelineId:!r.pipelineId&&e.pipelineId?e.pipelineId:!e.pipelineId&&r.pipelineId?r.pipelineId:r.startedAt<e.startedAt?e.pipelineId:r.pipelineId,labels:(r,e)=>{let t=new Set([...r.labels??[],...e.labels??[]]);return Array.from(t)}};function W1(r,e,t){if(qR[t]){let i=qR[t];return i(r,e)}let n=r[t],o=e[t];if(n!==o)throw new Error(`Metadata values for key "${t}" do not match: "${n}" vs "${o}"`);return n}var KR=new Set([".DS_Store","__MACOSX"]);function YR(r,e,t){let n=V1(),o=r.child({runGroupId:n});Qr.rmSync(e,{recursive:!0,force:!0});let i=Qr.readdirSync(t).filter(l=>!KR.has(l)).map(l=>Ao.join(t,l));if(i.length===0)throw new Error(`No run groups found in results path: ${t}`);Qr.mkdirSync(e,{recursive:!0});let a=Ao.join(i[0],"metadata.json"),s={...za.parse(JSON.parse(Qr.readFileSync(a,"utf-8"))),id:n};for(let l of i){let u=Ao.join(l,"runs");if(!Qr.existsSync(u))continue;let d=Qr.readdirSync(u);for(let m of d){if(KR.has(m))continue;let h=Ao.join(u,m),f=Ao.join(e,"runs",m);Qr.cpSync(h,f,{recursive:!0})}let p=Ao.join(l,"metadata.json"),g=za.parse(JSON.parse(Qr.readFileSync(p,"utf-8")));o.info({oldRunGroupId:g.id},"Merging metadata from run groups");for(let m in g){if(m==="id")continue;let h=m;s[h]=W1(s,g,h)}}let c=Ao.join(e,"metadata.json");Qr.writeFileSync(c,JSON.stringify(s,null,2))}import WC from"adm-zip";import Pg from"fs";import{z as bH}from"zod";var z="v1",hg="mobile-cli",wo="0.0.30";var $1=9e4,q1=3,K1=1500,Y1=15e3,Ar=class extends Error{status;rawError;constructor(e,t,n,o={}){super(n,o),this.status=e,this.rawError=t}};async function X1(r){return r.text().then(e=>{try{return JSON.parse(e).error}catch{return e}})}var fg=class{baseUrl;logger;constructor(e){this.baseUrl=e.baseUrl,this.logger=e.logger}getHeaders(){let e={"Content-Type":"application/json"};return wo&&(e[rc]=wo),hg&&(e[nT]=hg),e}async sendRequest(e,t){let{retries:n=q1,requestTimeoutMs:o=$1,initialRetryDelayMs:i=K1,maxRetryDelayMs:a=Y1}=t,s=n,c=n,l,u={path:e,baseUrl:this.baseUrl,method:t.method};for(;s>0;)try{return s--,await this.sendSingleRequestHelper(e,t,o)}catch(d){if(l=d,d instanceof Ar&&d.status>=400&&d.status<500)throw d;if(d instanceof Error&&d.name==="AbortError"&&(l=new Cn),s===0)throw l;let p=c-s,g=Math.min(i*Math.pow(2,p-1),a);await new Promise(m=>setTimeout(m,g))}throw this.logger.warn({...u,err:l},"Got fatal error response from Momentic server"),l}async sendSingleRequestHelper(e,t,n){let o={path:e,baseUrl:this.baseUrl,method:t.method},i=new AbortController,a=setTimeout(()=>i.abort(),n),s=()=>i.abort();t.signal&&t.signal.addEventListener("abort",s,{once:!0});let c={...this.getHeaders(),...t.extraHeaders};try{let l=await fetch(`${this.baseUrl}${e}`,{method:t.method,body:t.body?JSON.stringify(t.body):void 0,headers:c,signal:i.signal});if(!l.ok){let d=await X1(l);throw new Ar(l.status,d,`Request to ${t.method} ${e} failed with status ${l.status}: ${d}`)}let u;if(l.status===204)u={};else{let d=await l.text();try{u=JSON.parse(d)}catch{u=d}}return this.logger&&t.logResponse===!0&&u&&this.logger.debug({result:u,status:l.status,...o},"Got response from Momentic server"),u}finally{clearTimeout(a),t.signal&&t.signal.removeEventListener("abort",s)}}},Gr=class extends fg{apiKey;constructor(e){super(e),this.apiKey=e.apiKey}getHeaders(){return{...super.getHeaders(),Authorization:`Bearer ${this.apiKey}`}}};var XR="vercel.ai.error",J1=Symbol.for(XR),JR,Z1=class ZR extends Error{constructor({name:e,message:t,cause:n}){super(t),this[JR]=!0,this.name=e,this.cause=n}static isInstance(e){return ZR.hasMarker(e,XR)}static hasMarker(e,t){let n=Symbol.for(t);return e!=null&&typeof e=="object"&&n in e&&typeof e[n]=="boolean"&&e[n]===!0}};JR=J1;var At=Z1,QR="AI_APICallError",eC=`vercel.ai.error.${QR}`,Q1=Symbol.for(eC),tC,ur=class extends At{constructor({message:r,url:e,requestBodyValues:t,statusCode:n,responseHeaders:o,responseBody:i,cause:a,isRetryable:s=n!=null&&(n===408||n===409||n===429||n>=500),data:c}){super({name:QR,message:r,cause:a}),this[tC]=!0,this.url=e,this.requestBodyValues=t,this.statusCode=n,this.responseHeaders=o,this.responseBody=i,this.isRetryable=s,this.data=c}static isInstance(r){return At.hasMarker(r,eC)}};tC=Q1;var rC="AI_EmptyResponseBodyError",nC=`vercel.ai.error.${rC}`,ez=Symbol.for(nC),oC,iC=class extends At{constructor({message:r="Empty response body"}={}){super({name:rC,message:r}),this[oC]=!0}static isInstance(r){return At.hasMarker(r,nC)}};oC=ez;function aC(r){return r==null?"unknown error":typeof r=="string"?r:r instanceof Error?r.message:JSON.stringify(r)}var sC="AI_InvalidArgumentError",lC=`vercel.ai.error.${sC}`,tz=Symbol.for(lC),cC,eu=class extends At{constructor({message:r,cause:e,argument:t}){super({name:sC,message:r,cause:e}),this[cC]=!0,this.argument=t}static isInstance(r){return At.hasMarker(r,lC)}};cC=tz;var rz="AI_InvalidPromptError",nz=`vercel.ai.error.${rz}`,oz=Symbol.for(nz),iz;iz=oz;var az="AI_InvalidResponseDataError",sz=`vercel.ai.error.${az}`,lz=Symbol.for(sz),cz;cz=lz;var uC="AI_JSONParseError",dC=`vercel.ai.error.${uC}`,uz=Symbol.for(dC),pC,os=class extends At{constructor({text:r,cause:e}){super({name:uC,message:`JSON parsing failed: Text: ${r}.
|
|
4035
|
-
Error message: ${aC(e)}`,cause:e}),this[pC]=!0,this.text=r}static isInstance(r){return At.hasMarker(r,dC)}};pC=uz;var mC="AI_LoadAPIKeyError",gC=`vercel.ai.error.${mC}`,dz=Symbol.for(gC),hC,is=class extends At{constructor({message:r}){super({name:mC,message:r}),this[hC]=!0}static isInstance(r){return At.hasMarker(r,gC)}};hC=dz;var pz="AI_LoadSettingError",mz=`vercel.ai.error.${pz}`,gz=Symbol.for(mz),hz;hz=gz;var fz="AI_NoContentGeneratedError",Sz=`vercel.ai.error.${fz}`,yz=Symbol.for(Sz),bz;bz=yz;var fC="AI_NoSuchModelError",SC=`vercel.ai.error.${fC}`,Ez=Symbol.for(SC),yC,yg=class extends At{constructor({errorName:r=fC,modelId:e,modelType:t,message:n=`No such ${t}: ${e}`}){super({name:r,message:n}),this[yC]=!0,this.modelId=e,this.modelType=t}static isInstance(r){return At.hasMarker(r,SC)}};yC=Ez;var Tz="AI_TooManyEmbeddingValuesForCallError",vz=`vercel.ai.error.${Tz}`,Az=Symbol.for(vz),wz;wz=Az;var bC="AI_TypeValidationError",EC=`vercel.ai.error.${bC}`,Rz=Symbol.for(EC),TC,Cz=class Sg extends At{constructor({value:e,cause:t}){super({name:bC,message:`Type validation failed: Value: ${JSON.stringify(e)}.
|
|
4036
|
-
Error message: ${aC(t)}`,cause:t}),this[TC]=!0,this.value=e}static isInstance(e){return At.hasMarker(e,EC)}static wrap({value:e,cause:t}){return Sg.isInstance(t)&&t.value===e?t:new Sg({value:e,cause:t})}};TC=Rz;var Ln=Cz,vC="AI_UnsupportedFunctionalityError",AC=`vercel.ai.error.${vC}`,xz=Symbol.for(AC),wC,jr=class extends At{constructor({functionality:r,message:e=`'${r}' functionality not supported.`}){super({name:vC,message:e}),this[wC]=!0,this.functionality=r}static isInstance(r){return At.hasMarker(r,AC)}};wC=xz;var tu=class extends Error{constructor(e,t){super(e),this.name="ParseError",this.type=t.type,this.field=t.field,this.value=t.value,this.line=t.line}};function bg(r){}function RC(r){if(typeof r=="function")throw new TypeError("`callbacks` must be an object, got a function instead. Did you mean `{onEvent: fn}`?");let{onEvent:e=bg,onError:t=bg,onRetry:n=bg,onComment:o}=r,i="",a=!0,s,c="",l="";function u(h){let f=a?h.replace(/^\xEF\xBB\xBF/,""):h,[E,S]=_z(`${i}${f}`);for(let A of E)d(A);i=S,a=!1}function d(h){if(h===""){g();return}if(h.startsWith(":")){o&&o(h.slice(h.startsWith(": ")?2:1));return}let f=h.indexOf(":");if(f!==-1){let E=h.slice(0,f),S=h[f+1]===" "?2:1,A=h.slice(f+S);p(E,A,h);return}p(h,"",h)}function p(h,f,E){switch(h){case"event":l=f;break;case"data":c=`${c}${f}
|
|
4037
|
-
`;break;case"id":s=f.includes("\0")?void 0:f;break;case"retry":/^\d+$/.test(f)?n(parseInt(f,10)):t(new tu(`Invalid \`retry\` value: "${f}"`,{type:"invalid-retry",value:f,line:E}));break;default:t(new tu(`Unknown field "${h.length>20?`${h.slice(0,20)}\u2026`:h}"`,{type:"unknown-field",field:h,value:f,line:E}));break}}function g(){c.length>0&&e({id:s,event:l||void 0,data:c.endsWith(`
|
|
4038
|
-
`)?c.slice(0,-1):c}),s=void 0,c="",l=""}function m(h={}){i&&h.consume&&d(i),a=!0,s=void 0,c="",l="",i=""}return{feed:u,reset:m}}function _z(r){let e=[],t="",n=0;for(;n<r.length;){let o=r.indexOf("\r",n),i=r.indexOf(`
|
|
4039
|
-
`,n),a=-1;if(o!==-1&&i!==-1?a=Math.min(o,i):o!==-1?a=o:i!==-1&&(a=i),a===-1){t=r.slice(n);break}else{let s=r.slice(n,a);e.push(s),n=a+1,r[n-1]==="\r"&&r[n]===`
|
|
4040
|
-
`&&n++}}return[e,t]}var ru=class extends TransformStream{constructor({onError:e,onRetry:t,onComment:n}={}){let o;super({start(i){o=RC({onEvent:a=>{i.enqueue(a)},onError(a){e==="terminate"?i.error(a):typeof e=="function"&&e(a)},onRetry:t,onComment:n})},transform(i){o.feed(i)}})}};import*as NC from"zod/v4";function CC(...r){return r.reduce((e,t)=>({...e,...t??{}}),{})}function nu(r){return Object.fromEntries([...r.headers])}var Mz=({prefix:r,size:e=16,alphabet:t="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",separator:n="-"}={})=>{let o=()=>{let i=t.length,a=new Array(e);for(let s=0;s<e;s++)a[s]=t[Math.random()*i|0];return a.join("")};if(r==null)return o;if(t.includes(n))throw new eu({argument:"separator",message:`The separator "${n}" must not be part of the alphabet "${t}".`});return()=>`${r}${n}${o()}`},ou=Mz();function Eg(r){return(r instanceof Error||r instanceof DOMException)&&(r.name==="AbortError"||r.name==="ResponseAborted"||r.name==="TimeoutError")}var Iz=["fetch failed","failed to fetch"];function Pz({error:r,url:e,requestBodyValues:t}){if(Eg(r))return r;if(r instanceof TypeError&&Iz.includes(r.message.toLowerCase())){let n=r.cause;if(n!=null)return new ur({message:`Cannot connect to API: ${n.message}`,cause:n,url:e,requestBodyValues:t,isRetryable:!0})}return r}function Oz(r){return Object.fromEntries(Object.entries(r).filter(([e,t])=>t!=null))}function xC({apiKey:r,environmentVariableName:e,apiKeyParameterName:t="apiKey",description:n}){if(typeof r=="string")return r;if(r!=null)throw new is({message:`${n} API key must be a string.`});if(typeof process>"u")throw new is({message:`${n} API key is missing. Pass it using the '${t}' parameter. Environment variables is not supported in this environment.`});if(r=process.env[e],r==null)throw new is({message:`${n} API key is missing. Pass it using the '${t}' parameter or the ${e} environment variable.`});if(typeof r!="string")throw new is({message:`${n} API key must be a string. The value of the ${e} environment variable is not a string.`});return r}var Lz=/"__proto__"\s*:/,Nz=/"constructor"\s*:/;function kz(r){let e=JSON.parse(r);return e===null||typeof e!="object"||Lz.test(r)===!1&&Nz.test(r)===!1?e:Dz(e)}function Dz(r){let e=[r];for(;e.length;){let t=e;e=[];for(let n of t){if(Object.prototype.hasOwnProperty.call(n,"__proto__"))throw new SyntaxError("Object contains forbidden prototype property");if(Object.prototype.hasOwnProperty.call(n,"constructor")&&Object.prototype.hasOwnProperty.call(n.constructor,"prototype"))throw new SyntaxError("Object contains forbidden prototype property");for(let o in n){let i=n[o];i&&typeof i=="object"&&e.push(i)}}}return r}function _C(r){let{stackTraceLimit:e}=Error;Error.stackTraceLimit=0;try{return kz(r)}finally{Error.stackTraceLimit=e}}var Tg=Symbol.for("vercel.ai.validator");function Uz(r){return{[Tg]:!0,validate:r}}function Fz(r){return typeof r=="object"&&r!==null&&Tg in r&&r[Tg]===!0&&"validate"in r}function Bz(r){return Fz(r)?r:zz(r)}function zz(r){return Uz(async e=>{let t=await r["~standard"].validate(e);return t.issues==null?{success:!0,value:t.value}:{success:!1,error:new Ln({value:e,cause:t.issues})}})}async function Hz({value:r,schema:e}){let t=await vg({value:r,schema:e});if(!t.success)throw Ln.wrap({value:r,cause:t.error});return t.value}async function vg({value:r,schema:e}){let t=Bz(e);try{if(t.validate==null)return{success:!0,value:r,rawValue:r};let n=await t.validate(r);return n.success?{success:!0,value:n.value,rawValue:r}:{success:!1,error:Ln.wrap({value:r,cause:n.error}),rawValue:r}}catch(n){return{success:!1,error:Ln.wrap({value:r,cause:n}),rawValue:r}}}async function Gz({text:r,schema:e}){try{let t=_C(r);return e==null?t:Hz({value:t,schema:e})}catch(t){throw os.isInstance(t)||Ln.isInstance(t)?t:new os({text:r,cause:t})}}async function MC({text:r,schema:e}){try{let t=_C(r);return e==null?{success:!0,value:t,rawValue:t}:await vg({value:t,schema:e})}catch(t){return{success:!1,error:os.isInstance(t)?t:new os({text:r,cause:t}),rawValue:void 0}}}function jz({stream:r,schema:e}){return r.pipeThrough(new TextDecoderStream).pipeThrough(new ru).pipeThrough(new TransformStream({async transform({data:t},n){t!=="[DONE]"&&n.enqueue(await MC({text:t,schema:e}))}}))}async function wi({provider:r,providerOptions:e,schema:t}){if(e?.[r]==null)return;let n=await vg({value:e[r],schema:t});if(!n.success)throw new eu({argument:"providerOptions",message:`invalid ${r} provider options`,cause:n.error});return n.value}var Vz=()=>globalThis.fetch,Ag=async({url:r,headers:e,body:t,failedResponseHandler:n,successfulResponseHandler:o,abortSignal:i,fetch:a})=>Wz({url:r,headers:{"Content-Type":"application/json",...e},body:{content:JSON.stringify(t),values:t},failedResponseHandler:n,successfulResponseHandler:o,abortSignal:i,fetch:a});var Wz=async({url:r,headers:e={},body:t,successfulResponseHandler:n,failedResponseHandler:o,abortSignal:i,fetch:a=Vz()})=>{try{let s=await a(r,{method:"POST",headers:Oz(e),body:t.content,signal:i}),c=nu(s);if(!s.ok){let l;try{l=await o({response:s,url:r,requestBodyValues:t.values})}catch(u){throw Eg(u)||ur.isInstance(u)?u:new ur({message:"Failed to process error response",cause:u,statusCode:s.status,url:r,responseHeaders:c,requestBodyValues:t.values})}throw l.value}try{return await n({response:s,url:r,requestBodyValues:t.values})}catch(l){throw l instanceof Error&&(Eg(l)||ur.isInstance(l))?l:new ur({message:"Failed to process successful response",cause:l,statusCode:s.status,url:r,responseHeaders:c,requestBodyValues:t.values})}}catch(s){throw Pz({error:s,url:r,requestBodyValues:t.values})}};function zt({id:r,name:e,inputSchema:t}){return({execute:n,outputSchema:o,toModelOutput:i,onInputStart:a,onInputDelta:s,onInputAvailable:c,...l})=>({type:"provider-defined",id:r,name:e,args:l,inputSchema:t,outputSchema:o,execute:n,toModelOutput:i,onInputStart:a,onInputDelta:s,onInputAvailable:c})}function iu({id:r,name:e,inputSchema:t,outputSchema:n}){return({execute:o,toModelOutput:i,onInputStart:a,onInputDelta:s,onInputAvailable:c,...l})=>({type:"provider-defined",id:r,name:e,args:l,inputSchema:t,outputSchema:n,execute:o,toModelOutput:i,onInputStart:a,onInputDelta:s,onInputAvailable:c})}async function IC(r){return typeof r=="function"&&(r=r()),Promise.resolve(r)}var PC=({errorSchema:r,errorToMessage:e,isRetryable:t})=>async({response:n,url:o,requestBodyValues:i})=>{let a=await n.text(),s=nu(n);if(a.trim()==="")return{responseHeaders:s,value:new ur({message:n.statusText,url:o,requestBodyValues:i,statusCode:n.status,responseHeaders:s,responseBody:a,isRetryable:t?.(n)})};try{let c=await Gz({text:a,schema:r});return{responseHeaders:s,value:new ur({message:e(c),url:o,requestBodyValues:i,statusCode:n.status,responseHeaders:s,responseBody:a,data:c,isRetryable:t?.(n,c)})}}catch{return{responseHeaders:s,value:new ur({message:n.statusText,url:o,requestBodyValues:i,statusCode:n.status,responseHeaders:s,responseBody:a,isRetryable:t?.(n)})}}},OC=r=>async({response:e})=>{let t=nu(e);if(e.body==null)throw new iC({});return{responseHeaders:t,value:jz({stream:e.body,schema:r})}};var LC=r=>async({response:e,url:t,requestBodyValues:n})=>{let o=await e.text(),i=await MC({text:o,schema:r}),a=nu(e);if(!i.success)throw new ur({message:"Invalid JSON response",cause:i.error,statusCode:e.status,responseHeaders:a,responseBody:o,url:t,requestBodyValues:n});return{responseHeaders:a,value:i.value,rawValue:i.rawValue}};var uOe=Symbol.for("vercel.ai.schema");var{btoa:$z,atob:dOe}=globalThis;function qz(r){let e="";for(let t=0;t<r.length;t++)e+=String.fromCodePoint(r[t]);return $z(e)}function wg(r){return r instanceof Uint8Array?qz(r):r}function kC(r){return r?.replace(/\/$/,"")}import{z as v}from"zod/v4";import{z as as}from"zod/v4";import{z as jt}from"zod/v4";import{z as Ke}from"zod/v4";import{z as Ro}from"zod/v4";import Rg from"zod/v4";import Cg from"zod/v4";import{z as ss}from"zod/v4";import{z as dr}from"zod/v4";import{z as en}from"zod/v4";import{z as tn}from"zod/v4";import{z as rn}from"zod/v4";var Kz=as.object({type:as.literal("error"),error:as.object({type:as.string(),message:as.string()})}),DC=PC({errorSchema:Kz,errorToMessage:r=>r.error.message}),UC=jt.object({citations:jt.object({enabled:jt.boolean()}).optional(),title:jt.string().optional(),context:jt.string().optional()}),Yz=jt.object({sendReasoning:jt.boolean().optional(),thinking:jt.object({type:jt.union([jt.literal("enabled"),jt.literal("disabled")]),budgetTokens:jt.number().optional()}).optional(),disableParallelToolUse:jt.boolean().optional()});function Nn(r){var e;let t=r?.anthropic;return(e=t?.cacheControl)!=null?e:t?.cache_control}var Xz=Ke.object({maxUses:Ke.number().optional(),allowedDomains:Ke.array(Ke.string()).optional(),blockedDomains:Ke.array(Ke.string()).optional(),userLocation:Ke.object({type:Ke.literal("approximate"),city:Ke.string().optional(),region:Ke.string().optional(),country:Ke.string().optional(),timezone:Ke.string().optional()}).optional()}),zC=Ke.array(Ke.object({url:Ke.string(),title:Ke.string(),pageAge:Ke.string().nullable(),encryptedContent:Ke.string(),type:Ke.string()})),Jz=iu({id:"anthropic.web_search_20250305",name:"web_search",inputSchema:Ke.object({query:Ke.string()}),outputSchema:zC}),Zz=(r={})=>Jz(r);function Qz(r){return typeof r=="object"&&r!==null&&"type"in r&&r.type==="web_search_20250305"}function eH({tools:r,toolChoice:e,disableParallelToolUse:t}){r=r?.length?r:void 0;let n=[],o=new Set;if(r==null)return{tools:void 0,toolChoice:void 0,toolWarnings:n,betas:o};let i=[];for(let s of r){if(Qz(s)){i.push(s);continue}switch(s.type){case"function":let c=Nn(s.providerOptions);i.push({name:s.name,description:s.description,input_schema:s.inputSchema,cache_control:c});break;case"provider-defined":switch(s.id){case"anthropic.computer_20250124":o.add("computer-use-2025-01-24"),i.push({name:"computer",type:"computer_20250124",display_width_px:s.args.displayWidthPx,display_height_px:s.args.displayHeightPx,display_number:s.args.displayNumber});break;case"anthropic.computer_20241022":o.add("computer-use-2024-10-22"),i.push({name:"computer",type:"computer_20241022",display_width_px:s.args.displayWidthPx,display_height_px:s.args.displayHeightPx,display_number:s.args.displayNumber});break;case"anthropic.text_editor_20250124":o.add("computer-use-2025-01-24"),i.push({name:"str_replace_editor",type:"text_editor_20250124"});break;case"anthropic.text_editor_20241022":o.add("computer-use-2024-10-22"),i.push({name:"str_replace_editor",type:"text_editor_20241022"});break;case"anthropic.text_editor_20250429":o.add("computer-use-2025-01-24"),i.push({name:"str_replace_based_edit_tool",type:"text_editor_20250429"});break;case"anthropic.bash_20250124":o.add("computer-use-2025-01-24"),i.push({name:"bash",type:"bash_20250124"});break;case"anthropic.bash_20241022":o.add("computer-use-2024-10-22"),i.push({name:"bash",type:"bash_20241022"});break;case"anthropic.web_search_20250305":{let l=Xz.parse(s.args);i.push({type:"web_search_20250305",name:"web_search",max_uses:l.maxUses,allowed_domains:l.allowedDomains,blocked_domains:l.blockedDomains,user_location:l.userLocation});break}case"anthropic.code_execution_20250522":{o.add("code-execution-2025-05-22"),i.push({type:"code_execution_20250522",name:"code_execution"});break}default:n.push({type:"unsupported-tool",tool:s});break}break;default:n.push({type:"unsupported-tool",tool:s});break}}if(e==null)return{tools:i,toolChoice:t?{type:"auto",disable_parallel_tool_use:t}:void 0,toolWarnings:n,betas:o};let a=e.type;switch(a){case"auto":return{tools:i,toolChoice:{type:"auto",disable_parallel_tool_use:t},toolWarnings:n,betas:o};case"required":return{tools:i,toolChoice:{type:"any",disable_parallel_tool_use:t},toolWarnings:n,betas:o};case"none":return{tools:void 0,toolChoice:void 0,toolWarnings:n,betas:o};case"tool":return{tools:i,toolChoice:{type:"tool",name:e.toolName,disable_parallel_tool_use:t},toolWarnings:n,betas:o};default:{let s=a;throw new jr({functionality:`tool choice type: ${s}`})}}}var HC=Ro.object({type:Ro.literal("code_execution_result"),stdout:Ro.string(),stderr:Ro.string(),return_code:Ro.number()}),tH=iu({id:"anthropic.code_execution_20250522",name:"code_execution",inputSchema:Ro.object({code:Ro.string()}),outputSchema:HC}),rH=(r={})=>tH(r);function nH(r){if(typeof r=="string")return Buffer.from(r,"base64").toString("utf-8");if(r instanceof Uint8Array)return new TextDecoder().decode(r);throw r instanceof URL?new jr({functionality:"URL-based text documents are not supported for citations"}):new jr({functionality:`unsupported data type for text documents: ${typeof r}`})}async function oH({prompt:r,sendReasoning:e,warnings:t}){var n,o,i,a,s;let c=new Set,l=iH(r),u,d=[];async function p(m){var h,f;let E=await wi({provider:"anthropic",providerOptions:m,schema:UC});return(f=(h=E?.citations)==null?void 0:h.enabled)!=null?f:!1}async function g(m){let h=await wi({provider:"anthropic",providerOptions:m,schema:UC});return{title:h?.title,context:h?.context}}for(let m=0;m<l.length;m++){let h=l[m],f=m===l.length-1,E=h.type;switch(E){case"system":{if(u!=null)throw new jr({functionality:"Multiple system messages that are separated by user/assistant messages"});u=h.messages.map(({content:S,providerOptions:A})=>({type:"text",text:S,cache_control:Nn(A)}));break}case"user":{let S=[];for(let A of h.messages){let{role:C,content:T}=A;switch(C){case"user":{for(let I=0;I<T.length;I++){let R=T[I],w=I===T.length-1,B=(n=Nn(R.providerOptions))!=null?n:w?Nn(A.providerOptions):void 0;switch(R.type){case"text":{S.push({type:"text",text:R.text,cache_control:B});break}case"file":{if(R.mediaType.startsWith("image/"))S.push({type:"image",source:R.data instanceof URL?{type:"url",url:R.data.toString()}:{type:"base64",media_type:R.mediaType==="image/*"?"image/jpeg":R.mediaType,data:wg(R.data)},cache_control:B});else if(R.mediaType==="application/pdf"){c.add("pdfs-2024-09-25");let D=await p(R.providerOptions),U=await g(R.providerOptions);S.push({type:"document",source:R.data instanceof URL?{type:"url",url:R.data.toString()}:{type:"base64",media_type:"application/pdf",data:wg(R.data)},title:(o=U.title)!=null?o:R.filename,...U.context&&{context:U.context},...D&&{citations:{enabled:!0}},cache_control:B})}else if(R.mediaType==="text/plain"){let D=await p(R.providerOptions),U=await g(R.providerOptions);S.push({type:"document",source:R.data instanceof URL?{type:"url",url:R.data.toString()}:{type:"text",media_type:"text/plain",data:nH(R.data)},title:(i=U.title)!=null?i:R.filename,...U.context&&{context:U.context},...D&&{citations:{enabled:!0}},cache_control:B})}else throw new jr({functionality:`media type: ${R.mediaType}`});break}}}break}case"tool":{for(let I=0;I<T.length;I++){let R=T[I],w=I===T.length-1,B=(a=Nn(R.providerOptions))!=null?a:w?Nn(A.providerOptions):void 0,D=R.output,U;switch(D.type){case"content":U=D.value.map(J=>{switch(J.type){case"text":return{type:"text",text:J.text,cache_control:void 0};case"media":{if(J.mediaType.startsWith("image/"))return{type:"image",source:{type:"base64",media_type:J.mediaType,data:J.data},cache_control:void 0};throw new jr({functionality:`media type: ${J.mediaType}`})}}});break;case"text":case"error-text":U=D.value;break;case"json":case"error-json":default:U=JSON.stringify(D.value);break}S.push({type:"tool_result",tool_use_id:R.toolCallId,content:U,is_error:D.type==="error-text"||D.type==="error-json"?!0:void 0,cache_control:B})}break}default:{let I=C;throw new Error(`Unsupported role: ${I}`)}}}d.push({role:"user",content:S});break}case"assistant":{let S=[];for(let A=0;A<h.messages.length;A++){let C=h.messages[A],T=A===h.messages.length-1,{content:I}=C;for(let R=0;R<I.length;R++){let w=I[R],B=R===I.length-1,D=(s=Nn(w.providerOptions))!=null?s:B?Nn(C.providerOptions):void 0;switch(w.type){case"text":{S.push({type:"text",text:f&&T&&B?w.text.trim():w.text,cache_control:D});break}case"reasoning":{if(e){let U=await wi({provider:"anthropic",providerOptions:w.providerOptions,schema:uH});U!=null?U.signature!=null?S.push({type:"thinking",thinking:w.text,signature:U.signature,cache_control:D}):U.redactedData!=null?S.push({type:"redacted_thinking",data:U.redactedData,cache_control:D}):t.push({type:"other",message:"unsupported reasoning metadata"}):t.push({type:"other",message:"unsupported reasoning metadata"})}else t.push({type:"other",message:"sending reasoning content is disabled for this model"});break}case"tool-call":{if(w.providerExecuted){if(w.toolName==="web_search"){S.push({type:"server_tool_use",id:w.toolCallId,name:"web_search",input:w.input,cache_control:D});break}if(w.toolName==="code_execution"){S.push({type:"server_tool_use",id:w.toolCallId,name:"code_execution",input:w.input,cache_control:D});break}t.push({type:"other",message:`provider executed tool call for tool ${w.toolName} is not supported`});break}S.push({type:"tool_use",id:w.toolCallId,name:w.toolName,input:w.input,cache_control:D});break}case"tool-result":{if(w.toolName==="web_search"){let U=w.output;if(U.type!=="json"){t.push({type:"other",message:`provider executed tool result output type ${U.type} for tool ${w.toolName} is not supported`});break}let J=zC.parse(U.value);S.push({type:"web_search_tool_result",tool_use_id:w.toolCallId,content:J.map(Le=>({url:Le.url,title:Le.title,page_age:Le.pageAge,encrypted_content:Le.encryptedContent,type:Le.type})),cache_control:D});break}if(w.toolName==="code_execution"){let U=w.output;if(U.type!=="json"){t.push({type:"other",message:`provider executed tool result output type ${U.type} for tool ${w.toolName} is not supported`});break}let J=HC.parse(U.value);S.push({type:"code_execution_tool_result",tool_use_id:w.toolCallId,content:{type:J.type,stdout:J.stdout,stderr:J.stderr,return_code:J.return_code},cache_control:D});break}t.push({type:"other",message:`provider executed tool result for tool ${w.toolName} is not supported`});break}}}}d.push({role:"assistant",content:S});break}default:{let S=E;throw new Error(`content type: ${S}`)}}}return{prompt:{system:u,messages:d},betas:c}}function iH(r){let e=[],t;for(let n of r){let{role:o}=n;switch(o){case"system":{t?.type!=="system"&&(t={type:"system",messages:[]},e.push(t)),t.messages.push(n);break}case"assistant":{t?.type!=="assistant"&&(t={type:"assistant",messages:[]},e.push(t)),t.messages.push(n);break}case"user":{t?.type!=="user"&&(t={type:"user",messages:[]},e.push(t)),t.messages.push(n);break}case"tool":{t?.type!=="user"&&(t={type:"user",messages:[]},e.push(t)),t.messages.push(n);break}default:{let i=o;throw new Error(`Unsupported role: ${i}`)}}}return e}function FC({finishReason:r,isJsonResponseFromTool:e}){switch(r){case"end_turn":case"stop_sequence":return"stop";case"tool_use":return e?"stop":"tool-calls";case"max_tokens":return"length";default:return"unknown"}}var ls={webSearchResult:v.object({type:v.literal("web_search_result_location"),cited_text:v.string(),url:v.string(),title:v.string(),encrypted_index:v.string()}),pageLocation:v.object({type:v.literal("page_location"),cited_text:v.string(),document_index:v.number(),document_title:v.string().nullable(),start_page_number:v.number(),end_page_number:v.number()}),charLocation:v.object({type:v.literal("char_location"),cited_text:v.string(),document_index:v.number(),document_title:v.string().nullable(),start_char_index:v.number(),end_char_index:v.number()})},GC=v.discriminatedUnion("type",[ls.webSearchResult,ls.pageLocation,ls.charLocation]),MOe=v.discriminatedUnion("type",[ls.pageLocation,ls.charLocation]);function BC(r,e,t,n){if(r.type==="page_location"||r.type==="char_location"){let o=aH(r,e,t);o&&n(o)}}function aH(r,e,t){var n;let o=e[r.document_index];if(!o)return null;let i=r.type==="page_location"?{citedText:r.cited_text,startPageNumber:r.start_page_number,endPageNumber:r.end_page_number}:{citedText:r.cited_text,startCharIndex:r.start_char_index,endCharIndex:r.end_char_index};return{type:"source",sourceType:"document",id:t(),mediaType:o.mediaType,title:(n=r.document_title)!=null?n:o.title,filename:o.filename,providerMetadata:{anthropic:i}}}var sH=class{constructor(r,e){this.specificationVersion="v2";var t;this.modelId=r,this.config=e,this.generateId=(t=e.generateId)!=null?t:ou}supportsUrl(r){return r.protocol==="https:"}get provider(){return this.config.provider}get supportedUrls(){var r,e,t;return(t=(e=(r=this.config).supportedUrls)==null?void 0:e.call(r))!=null?t:{}}async getArgs({prompt:r,maxOutputTokens:e=4096,temperature:t,topP:n,topK:o,frequencyPenalty:i,presencePenalty:a,stopSequences:s,responseFormat:c,seed:l,tools:u,toolChoice:d,providerOptions:p}){var g,m,h;let f=[];i!=null&&f.push({type:"unsupported-setting",setting:"frequencyPenalty"}),a!=null&&f.push({type:"unsupported-setting",setting:"presencePenalty"}),l!=null&&f.push({type:"unsupported-setting",setting:"seed"}),c?.type==="json"&&(c.schema==null?f.push({type:"unsupported-setting",setting:"responseFormat",details:"JSON response format requires a schema. The response format is ignored."}):u!=null&&f.push({type:"unsupported-setting",setting:"tools",details:"JSON response format does not support tools. The provided tools are ignored."}));let E=c?.type==="json"&&c.schema!=null?{type:"function",name:"json",description:"Respond with a JSON object.",inputSchema:c.schema}:void 0,S=await wi({provider:"anthropic",providerOptions:p,schema:Yz}),{prompt:A,betas:C}=await oH({prompt:r,sendReasoning:(g=S?.sendReasoning)!=null?g:!0,warnings:f}),T=((m=S?.thinking)==null?void 0:m.type)==="enabled",I=(h=S?.thinking)==null?void 0:h.budgetTokens,R={model:this.modelId,max_tokens:e,temperature:t,top_k:o,top_p:n,stop_sequences:s,...T&&{thinking:{type:"enabled",budget_tokens:I}},system:A.system,messages:A.messages};if(T){if(I==null)throw new jr({functionality:"thinking requires a budget"});R.temperature!=null&&(R.temperature=void 0,f.push({type:"unsupported-setting",setting:"temperature",details:"temperature is not supported when thinking is enabled"})),o!=null&&(R.top_k=void 0,f.push({type:"unsupported-setting",setting:"topK",details:"topK is not supported when thinking is enabled"})),n!=null&&(R.top_p=void 0,f.push({type:"unsupported-setting",setting:"topP",details:"topP is not supported when thinking is enabled"})),R.max_tokens=e+I}let{tools:w,toolChoice:B,toolWarnings:D,betas:U}=eH(E!=null?{tools:[E],toolChoice:{type:"tool",toolName:E.name},disableParallelToolUse:S?.disableParallelToolUse}:{tools:u??[],toolChoice:d,disableParallelToolUse:S?.disableParallelToolUse});return{args:{...R,tools:w,tool_choice:B},warnings:[...f,...D],betas:new Set([...C,...U]),usesJsonResponseTool:E!=null}}async getHeaders({betas:r,headers:e}){return CC(await IC(this.config.headers),r.size>0?{"anthropic-beta":Array.from(r).join(",")}:{},e)}buildRequestUrl(r){var e,t,n;return(n=(t=(e=this.config).buildRequestUrl)==null?void 0:t.call(e,this.config.baseURL,r))!=null?n:`${this.config.baseURL}/messages`}transformRequestBody(r){var e,t,n;return(n=(t=(e=this.config).transformRequestBody)==null?void 0:t.call(e,r))!=null?n:r}extractCitationDocuments(r){let e=t=>{var n,o;if(t.type!=="file"||t.mediaType!=="application/pdf"&&t.mediaType!=="text/plain")return!1;let i=(n=t.providerOptions)==null?void 0:n.anthropic,a=i?.citations;return(o=a?.enabled)!=null?o:!1};return r.filter(t=>t.role==="user").flatMap(t=>t.content).filter(e).map(t=>{var n;let o=t;return{title:(n=o.filename)!=null?n:"Untitled Document",filename:o.filename,mediaType:o.mediaType}})}async doGenerate(r){var e,t,n,o,i;let{args:a,warnings:s,betas:c,usesJsonResponseTool:l}=await this.getArgs(r),u=this.extractCitationDocuments(r.prompt),{responseHeaders:d,value:p,rawValue:g}=await Ag({url:this.buildRequestUrl(!1),headers:await this.getHeaders({betas:c,headers:r.headers}),body:this.transformRequestBody(a),failedResponseHandler:DC,successfulResponseHandler:LC(lH),abortSignal:r.abortSignal,fetch:this.config.fetch}),m=[];for(let h of p.content)switch(h.type){case"text":{if(!l&&(m.push({type:"text",text:h.text}),h.citations))for(let f of h.citations)BC(f,u,this.generateId,E=>m.push(E));break}case"thinking":{m.push({type:"reasoning",text:h.thinking,providerMetadata:{anthropic:{signature:h.signature}}});break}case"redacted_thinking":{m.push({type:"reasoning",text:"",providerMetadata:{anthropic:{redactedData:h.data}}});break}case"tool_use":{m.push(l?{type:"text",text:JSON.stringify(h.input)}:{type:"tool-call",toolCallId:h.id,toolName:h.name,input:JSON.stringify(h.input)});break}case"server_tool_use":{(h.name==="web_search"||h.name==="code_execution")&&m.push({type:"tool-call",toolCallId:h.id,toolName:h.name,input:JSON.stringify(h.input),providerExecuted:!0});break}case"web_search_tool_result":{if(Array.isArray(h.content)){m.push({type:"tool-result",toolCallId:h.tool_use_id,toolName:"web_search",result:h.content.map(f=>{var E;return{url:f.url,title:f.title,pageAge:(E=f.page_age)!=null?E:null,encryptedContent:f.encrypted_content,type:f.type}}),providerExecuted:!0});for(let f of h.content)m.push({type:"source",sourceType:"url",id:this.generateId(),url:f.url,title:f.title,providerMetadata:{anthropic:{pageAge:(e=f.page_age)!=null?e:null}}})}else m.push({type:"tool-result",toolCallId:h.tool_use_id,toolName:"web_search",isError:!0,result:{type:"web_search_tool_result_error",errorCode:h.content.error_code},providerExecuted:!0});break}case"code_execution_tool_result":{h.content.type==="code_execution_result"?m.push({type:"tool-result",toolCallId:h.tool_use_id,toolName:"code_execution",result:{type:h.content.type,stdout:h.content.stdout,stderr:h.content.stderr,return_code:h.content.return_code},providerExecuted:!0}):h.content.type==="code_execution_tool_result_error"&&m.push({type:"tool-result",toolCallId:h.tool_use_id,toolName:"code_execution",isError:!0,result:{type:"code_execution_tool_result_error",errorCode:h.content.error_code},providerExecuted:!0});break}}return{content:m,finishReason:FC({finishReason:p.stop_reason,isJsonResponseFromTool:l}),usage:{inputTokens:p.usage.input_tokens,outputTokens:p.usage.output_tokens,totalTokens:p.usage.input_tokens+p.usage.output_tokens,cachedInputTokens:(t=p.usage.cache_read_input_tokens)!=null?t:void 0},request:{body:a},response:{id:(n=p.id)!=null?n:void 0,modelId:(o=p.model)!=null?o:void 0,headers:d,body:g},warnings:s,providerMetadata:{anthropic:{usage:p.usage,cacheCreationInputTokens:(i=p.usage.cache_creation_input_tokens)!=null?i:null}}}}async doStream(r){let{args:e,warnings:t,betas:n,usesJsonResponseTool:o}=await this.getArgs(r),i=this.extractCitationDocuments(r.prompt),a={...e,stream:!0},{responseHeaders:s,value:c}=await Ag({url:this.buildRequestUrl(!0),headers:await this.getHeaders({betas:n,headers:r.headers}),body:this.transformRequestBody(a),failedResponseHandler:DC,successfulResponseHandler:OC(cH),abortSignal:r.abortSignal,fetch:this.config.fetch}),l="unknown",u={inputTokens:void 0,outputTokens:void 0,totalTokens:void 0},d={},p,g,m=this.generateId;return{stream:c.pipeThrough(new TransformStream({start(h){h.enqueue({type:"stream-start",warnings:t})},transform(h,f){var E,S,A,C,T,I,R;if(r.includeRawChunks&&f.enqueue({type:"raw",rawValue:h.rawValue}),!h.success){f.enqueue({type:"error",error:h.error});return}let w=h.value;switch(w.type){case"ping":return;case"content_block_start":{let B=w.content_block.type;switch(g=B,B){case"text":{d[w.index]={type:"text"},f.enqueue({type:"text-start",id:String(w.index)});return}case"thinking":{d[w.index]={type:"reasoning"},f.enqueue({type:"reasoning-start",id:String(w.index)});return}case"redacted_thinking":{d[w.index]={type:"reasoning"},f.enqueue({type:"reasoning-start",id:String(w.index),providerMetadata:{anthropic:{redactedData:w.content_block.data}}});return}case"tool_use":{d[w.index]=o?{type:"text"}:{type:"tool-call",toolCallId:w.content_block.id,toolName:w.content_block.name,input:""},f.enqueue(o?{type:"text-start",id:String(w.index)}:{type:"tool-input-start",id:w.content_block.id,toolName:w.content_block.name});return}case"server_tool_use":{(w.content_block.name==="web_search"||w.content_block.name==="code_execution")&&(d[w.index]={type:"tool-call",toolCallId:w.content_block.id,toolName:w.content_block.name,input:"",providerExecuted:!0},f.enqueue({type:"tool-input-start",id:w.content_block.id,toolName:w.content_block.name,providerExecuted:!0}));return}case"web_search_tool_result":{let D=w.content_block;if(Array.isArray(D.content)){f.enqueue({type:"tool-result",toolCallId:D.tool_use_id,toolName:"web_search",result:D.content.map(U=>{var J;return{url:U.url,title:U.title,pageAge:(J=U.page_age)!=null?J:null,encryptedContent:U.encrypted_content,type:U.type}}),providerExecuted:!0});for(let U of D.content)f.enqueue({type:"source",sourceType:"url",id:m(),url:U.url,title:U.title,providerMetadata:{anthropic:{pageAge:(E=U.page_age)!=null?E:null}}})}else f.enqueue({type:"tool-result",toolCallId:D.tool_use_id,toolName:"web_search",isError:!0,result:{type:"web_search_tool_result_error",errorCode:D.content.error_code},providerExecuted:!0});return}case"code_execution_tool_result":{let D=w.content_block;D.content.type==="code_execution_result"?f.enqueue({type:"tool-result",toolCallId:D.tool_use_id,toolName:"code_execution",result:{type:D.content.type,stdout:D.content.stdout,stderr:D.content.stderr,return_code:D.content.return_code},providerExecuted:!0}):D.content.type==="code_execution_tool_result_error"&&f.enqueue({type:"tool-result",toolCallId:D.tool_use_id,toolName:"code_execution",isError:!0,result:{type:"code_execution_tool_result_error",errorCode:D.content.error_code},providerExecuted:!0});return}default:{let D=B;throw new Error(`Unsupported content block type: ${D}`)}}}case"content_block_stop":{if(d[w.index]!=null){let B=d[w.index];switch(B.type){case"text":{f.enqueue({type:"text-end",id:String(w.index)});break}case"reasoning":{f.enqueue({type:"reasoning-end",id:String(w.index)});break}case"tool-call":o||(f.enqueue({type:"tool-input-end",id:B.toolCallId}),f.enqueue(B));break}delete d[w.index]}g=void 0;return}case"content_block_delta":{let B=w.delta.type;switch(B){case"text_delta":{if(o)return;f.enqueue({type:"text-delta",id:String(w.index),delta:w.delta.text});return}case"thinking_delta":{f.enqueue({type:"reasoning-delta",id:String(w.index),delta:w.delta.thinking});return}case"signature_delta":{g==="thinking"&&f.enqueue({type:"reasoning-delta",id:String(w.index),delta:"",providerMetadata:{anthropic:{signature:w.delta.signature}}});return}case"input_json_delta":{let D=d[w.index],U=w.delta.partial_json;if(o){if(D?.type!=="text")return;f.enqueue({type:"text-delta",id:String(w.index),delta:U})}else{if(D?.type!=="tool-call")return;f.enqueue({type:"tool-input-delta",id:D.toolCallId,delta:U}),D.input+=U}return}case"citations_delta":{let D=w.delta.citation;BC(D,i,m,U=>f.enqueue(U));return}default:{let D=B;throw new Error(`Unsupported delta type: ${D}`)}}}case"message_start":{u.inputTokens=w.message.usage.input_tokens,u.cachedInputTokens=(S=w.message.usage.cache_read_input_tokens)!=null?S:void 0,p={anthropic:{usage:w.message.usage,cacheCreationInputTokens:(A=w.message.usage.cache_creation_input_tokens)!=null?A:null}},f.enqueue({type:"response-metadata",id:(C=w.message.id)!=null?C:void 0,modelId:(T=w.message.model)!=null?T:void 0});return}case"message_delta":{u.outputTokens=w.usage.output_tokens,u.totalTokens=((I=u.inputTokens)!=null?I:0)+((R=w.usage.output_tokens)!=null?R:0),l=FC({finishReason:w.delta.stop_reason,isJsonResponseFromTool:o});return}case"message_stop":{f.enqueue({type:"finish",finishReason:l,usage:u,providerMetadata:p});return}case"error":{f.enqueue({type:"error",error:w.error});return}default:{let B=w;throw new Error(`Unsupported chunk type: ${B}`)}}}})),request:{body:a},response:{headers:s}}}},lH=v.object({type:v.literal("message"),id:v.string().nullish(),model:v.string().nullish(),content:v.array(v.discriminatedUnion("type",[v.object({type:v.literal("text"),text:v.string(),citations:v.array(GC).optional()}),v.object({type:v.literal("thinking"),thinking:v.string(),signature:v.string()}),v.object({type:v.literal("redacted_thinking"),data:v.string()}),v.object({type:v.literal("tool_use"),id:v.string(),name:v.string(),input:v.unknown()}),v.object({type:v.literal("server_tool_use"),id:v.string(),name:v.string(),input:v.record(v.string(),v.unknown()).nullish()}),v.object({type:v.literal("web_search_tool_result"),tool_use_id:v.string(),content:v.union([v.array(v.object({type:v.literal("web_search_result"),url:v.string(),title:v.string(),encrypted_content:v.string(),page_age:v.string().nullish()})),v.object({type:v.literal("web_search_tool_result_error"),error_code:v.string()})])}),v.object({type:v.literal("code_execution_tool_result"),tool_use_id:v.string(),content:v.union([v.object({type:v.literal("code_execution_result"),stdout:v.string(),stderr:v.string(),return_code:v.number()}),v.object({type:v.literal("code_execution_tool_result_error"),error_code:v.string()})])})])),stop_reason:v.string().nullish(),usage:v.looseObject({input_tokens:v.number(),output_tokens:v.number(),cache_creation_input_tokens:v.number().nullish(),cache_read_input_tokens:v.number().nullish()})}),cH=v.discriminatedUnion("type",[v.object({type:v.literal("message_start"),message:v.object({id:v.string().nullish(),model:v.string().nullish(),usage:v.looseObject({input_tokens:v.number(),output_tokens:v.number(),cache_creation_input_tokens:v.number().nullish(),cache_read_input_tokens:v.number().nullish()})})}),v.object({type:v.literal("content_block_start"),index:v.number(),content_block:v.discriminatedUnion("type",[v.object({type:v.literal("text"),text:v.string()}),v.object({type:v.literal("thinking"),thinking:v.string()}),v.object({type:v.literal("tool_use"),id:v.string(),name:v.string()}),v.object({type:v.literal("redacted_thinking"),data:v.string()}),v.object({type:v.literal("server_tool_use"),id:v.string(),name:v.string(),input:v.record(v.string(),v.unknown()).nullish()}),v.object({type:v.literal("web_search_tool_result"),tool_use_id:v.string(),content:v.union([v.array(v.object({type:v.literal("web_search_result"),url:v.string(),title:v.string(),encrypted_content:v.string(),page_age:v.string().nullish()})),v.object({type:v.literal("web_search_tool_result_error"),error_code:v.string()})])}),v.object({type:v.literal("code_execution_tool_result"),tool_use_id:v.string(),content:v.union([v.object({type:v.literal("code_execution_result"),stdout:v.string(),stderr:v.string(),return_code:v.number()}),v.object({type:v.literal("code_execution_tool_result_error"),error_code:v.string()})])})])}),v.object({type:v.literal("content_block_delta"),index:v.number(),delta:v.discriminatedUnion("type",[v.object({type:v.literal("input_json_delta"),partial_json:v.string()}),v.object({type:v.literal("text_delta"),text:v.string()}),v.object({type:v.literal("thinking_delta"),thinking:v.string()}),v.object({type:v.literal("signature_delta"),signature:v.string()}),v.object({type:v.literal("citations_delta"),citation:GC})])}),v.object({type:v.literal("content_block_stop"),index:v.number()}),v.object({type:v.literal("error"),error:v.object({type:v.string(),message:v.string()})}),v.object({type:v.literal("message_delta"),delta:v.object({stop_reason:v.string().nullish()}),usage:v.object({output_tokens:v.number()})}),v.object({type:v.literal("message_stop")}),v.object({type:v.literal("ping")})]),uH=v.object({signature:v.string().optional(),redactedData:v.string().optional()}),dH=zt({id:"anthropic.bash_20241022",name:"bash",inputSchema:Rg.object({command:Rg.string(),restart:Rg.boolean().optional()})}),pH=zt({id:"anthropic.bash_20250124",name:"bash",inputSchema:Cg.object({command:Cg.string(),restart:Cg.boolean().optional()})}),mH=zt({id:"anthropic.computer_20241022",name:"computer",inputSchema:ss.object({action:ss.enum(["key","type","mouse_move","left_click","left_click_drag","right_click","middle_click","double_click","screenshot","cursor_position"]),coordinate:ss.array(ss.number().int()).optional(),text:ss.string().optional()})}),gH=zt({id:"anthropic.computer_20250124",name:"computer",inputSchema:dr.object({action:dr.enum(["key","hold_key","type","cursor_position","mouse_move","left_mouse_down","left_mouse_up","left_click","left_click_drag","right_click","middle_click","double_click","triple_click","scroll","wait","screenshot"]),coordinate:dr.tuple([dr.number().int(),dr.number().int()]).optional(),duration:dr.number().optional(),scroll_amount:dr.number().optional(),scroll_direction:dr.enum(["up","down","left","right"]).optional(),start_coordinate:dr.tuple([dr.number().int(),dr.number().int()]).optional(),text:dr.string().optional()})}),hH=zt({id:"anthropic.text_editor_20241022",name:"str_replace_editor",inputSchema:en.object({command:en.enum(["view","create","str_replace","insert","undo_edit"]),path:en.string(),file_text:en.string().optional(),insert_line:en.number().int().optional(),new_str:en.string().optional(),old_str:en.string().optional(),view_range:en.array(en.number().int()).optional()})}),fH=zt({id:"anthropic.text_editor_20250124",name:"str_replace_editor",inputSchema:tn.object({command:tn.enum(["view","create","str_replace","insert","undo_edit"]),path:tn.string(),file_text:tn.string().optional(),insert_line:tn.number().int().optional(),new_str:tn.string().optional(),old_str:tn.string().optional(),view_range:tn.array(tn.number().int()).optional()})}),SH=zt({id:"anthropic.text_editor_20250429",name:"str_replace_based_edit_tool",inputSchema:rn.object({command:rn.enum(["view","create","str_replace","insert"]),path:rn.string(),file_text:rn.string().optional(),insert_line:rn.number().int().optional(),new_str:rn.string().optional(),old_str:rn.string().optional(),view_range:rn.array(rn.number().int()).optional()})}),yH={bash_20241022:dH,bash_20250124:pH,textEditor_20241022:hH,textEditor_20250124:fH,textEditor_20250429:SH,computer_20241022:mH,computer_20250124:gH,webSearch_20250305:Zz,codeExecution_20250522:rH};function xg(r={}){var e;let t=(e=kC(r.baseURL))!=null?e:"https://api.anthropic.com/v1",n=()=>({"anthropic-version":"2023-06-01","x-api-key":xC({apiKey:r.apiKey,environmentVariableName:"ANTHROPIC_API_KEY",description:"Anthropic"}),...r.headers}),o=a=>{var s;return new sH(a,{provider:"anthropic.messages",baseURL:t,headers:n,fetch:r.fetch,generateId:(s=r.generateId)!=null?s:ou,supportedUrls:()=>({"image/*":[/^https?:\/\/.*$/]})})},i=function(a){if(new.target)throw new Error("The Anthropic model function cannot be called with the new keyword.");return o(a)};return i.languageModel=o,i.chat=o,i.messages=o,i.textEmbeddingModel=a=>{throw new yg({modelId:a,modelType:"textEmbeddingModel"})},i.imageModel=a=>{throw new yg({modelId:a,modelType:"imageModel"})},i.tools=yH,i}var VOe=xg();var jC=({baseUrl:r,apiKey:e,sessionId:t,extraHeaders:n,loggerTags:o})=>i=>{let a={Authorization:`Bearer ${e}`,[rc]:wo??"",...t&&{[iT]:t},...n||{}};return o&&(a[oT]=JSON.stringify(o)),xg({baseURL:`${r}/v1/llm/anthropic/${i}`,headers:a,apiKey:e})(i)};var Co=class extends Gr{agentConfig;constructor(e,t){super(t),this.agentConfig=e}getAgentConfig(){return this.agentConfig}async rankChunksWithAi(e,t){let n={...e,loggerTags:t.loggerTags},o=await this.sendRequest(`/${z}/web-agent/recommend-chunks-ai`,{method:"POST",body:n,signal:t.abortSignal});return Yb.parse(o)}async rankChunksWithRag(e,t){let n=await this.sendRequest(`/${z}/web-agent/recommend-chunks`,{method:"POST",body:{cliVersion:wo,...e},signal:t.abortSignal});return Kb.parse(n)}async getScreenshotFromS3(e){let t=await this.sendRequest(`/${z}/s3/visual-diff-screenshot`,{method:"POST",body:{url:e}});return bH.string().parse(t)}async getElementLocation(e,t){let n={...e,disableCache:t.disableCache,loggerTags:t.loggerTags,useMemory:t.useMemory,agentConfigVersion:this.agentConfig?.locator},o=await this.sendRequest(`/${z}/web-agent/locate-element`,{method:"POST",body:n,signal:t.abortSignal});return cT.parse(o)}async getAssertionResult(e,t){let n={...e,disableCache:!!t.disableCache,useConsensus:!!t.useConsensus,attemptNumber:t.attemptNumber,loggerTags:t.loggerTags,useMemory:t.useMemory,agentConfigVersion:this.agentConfig?.assertion},o=await this.sendRequest(`/${z}/web-agent/assertion`,{method:"POST",body:n,signal:t.abortSignal});return Fp.parse(o)}async getLintStepResult(e,t){let n={...e,disableCache:!!t.disableCache,loggerTags:t.loggerTags},o=await this.sendRequest(`/${z}/web-agent/lint/step`,{method:"POST",body:n,signal:t.abortSignal});return lT.parse(o)}async getLintMcpCopilotMessageResult(e,t){let n={message:e.message,disableCache:!!t.disableCache,loggerTags:t.loggerTags},o=await this.sendRequest(`/${z}/web-agent/lint/mcp-copilot`,{method:"POST",body:n,signal:t.abortSignal});return sT.parse(o)}async getVisualAssertionResult(e,t){let n={...e,disableCache:!!t.disableCache,useConsensus:!!t.useConsensus,attemptNumber:t.attemptNumber,loggerTags:t.loggerTags,useMemory:t.useMemory,agentConfigVersion:this.agentConfig?.["visual-assertion"]},o=await this.sendRequest(`/${z}/web-agent/visual-assertion`,{method:"POST",body:n,signal:t.abortSignal});return Fp.parse(o)}async getAiActionCommand(e,t){let n=await this.sendRequest(`/${z}/web-agent/next-command-dynamic`,{method:"POST",body:{...e,disableCache:t.disableCache,loggerTags:t.loggerTags},signal:t.abortSignal});return aT.parse(n)}async getMultiturnAiActionCommand(e,t){return await this.sendRequest(`/${z}/web-agent/ai-action/next-command`,{method:"POST",body:{...e,disableCache:t.disableCache,loggerTags:t.loggerTags},signal:t.abortSignal})}async getMultiturnAiActionEvaluation(e,t){let n=await this.sendRequest(`/${z}/web-agent/ai-action/evaluate`,{method:"POST",body:{...e,disableCache:t.disableCache,loggerTags:t.loggerTags},signal:t.abortSignal});return rp.parse(n)}async getReverseMappedDescription(e,t){let n=await this.sendRequest(`/${z}/web-agent/reverse-mapped-description`,{method:"POST",body:{...e,disableCache:t.disableCache,loggerTags:t.loggerTags},signal:t.abortSignal});return uT.parse(n)}async getTextExtraction(e,t){let n={...e,disableCache:t.disableCache,loggerTags:t.loggerTags,agentConfigVersion:this.agentConfig?.["text-extraction"]},o=await this.sendRequest(`/${z}/web-agent/text-extraction`,{method:"POST",body:n,signal:t.abortSignal});return ep.parse(o)}async getPageSummary(e,t){let n={...e,disableCache:t.disableCache,loggerTags:t.loggerTags},o=await this.sendRequest(`/${z}/web-agent/page-summary`,{method:"POST",body:n,signal:t.abortSignal});return xb.parse(o)}async getTestResultClassification(e,t){let n=await this.sendRequest(`/${z}/web-agent/result-classification`,{method:"POST",body:{...e,loggerTags:t.loggerTags},signal:t.abortSignal});return Hd.parse(n)}async getExtractedKeywords(e,t){let n=await this.sendRequest(`/${z}/web-agent/extract-keywords`,{method:"POST",body:e,signal:t.abortSignal});return aE.parse(n)}async getAutohealingProposal(e,t){let n=await this.sendRequest(`/${z}/web-agent/autoheal-section`,{method:"POST",body:{...e,loggerTags:t.loggerTags},signal:t.abortSignal});return Ab.parse(n)}async getFailureRecoveryProposal(e,t){let n=await this.sendRequest(`/${z}/web-agent/failure-recovery`,{method:"POST",body:{...e,loggerTags:t.loggerTags},signal:t.abortSignal});return Cb.parse(n)}async getFailureRecoveryPlan(e,t){let n=await this.sendRequest(`/${z}/web-agent/failure-recovery-plan`,{method:"POST",body:{...e,loggerTags:t.loggerTags},signal:t.abortSignal});return Rb.parse(n)}async getIframeRegex(e,t){let n=await this.sendRequest(`/${z}/web-agent/iframe-regex`,{method:"POST",body:e,signal:t.abortSignal});return uy.parse(n)}getVercelAnthropicModelFactory({loggerTags:e}){return jC({baseUrl:this.baseUrl,apiKey:this.apiKey,loggerTags:e})}};import{z as _g}from"zod";var wr=class extends Gr{constructor(e){super(e)}getAppUrl(){return this.baseUrl==="http://localhost:8000"?"http://localhost:3000":this.baseUrl.replace(/\/\/api/,"//app")}async getAuthInfo(){let e=await this.sendRequest(`/${z}/auth/check`,{method:"GET",retries:10,requestTimeoutMs:5e3});return AT.parse(e)}async bulkGetRunStatus(e){let t=await this.sendRequest(`/${z}/runs/status`,{method:"POST",body:e,retries:3,requestTimeoutMs:1e4});return bT.parse(t)}async getTestYAMLExport(e){let t=await this.sendRequest(`/${z}/tests/export`,{method:"POST",body:e,retries:3,requestTimeoutMs:3e4});return pT.parse(t)}async updateStepCaches(e,t){await this.sendRequest(`/${z}/cache`,{method:"PATCH",body:e,extraHeaders:t,retries:3,requestTimeoutMs:1e4,initialRetryDelayMs:3e3})}async getStepCacheForTest(e,t){let n=await this.sendRequest(`/${z}/cache`,{method:"POST",body:e,extraHeaders:t,retries:10,requestTimeoutMs:3e4,initialRetryDelayMs:3e3});return gT.parse(n)}async updateMobileStepCaches(e,t){await this.sendRequest(`/${z}/mobile-cache`,{method:"PATCH",body:e,extraHeaders:t,retries:3,requestTimeoutMs:1e4,initialRetryDelayMs:3e3})}async getMobileStepCacheForTest(e,t){let n=await this.sendRequest(`/${z}/mobile-cache`,{method:"POST",body:e,extraHeaders:t,retries:10,logResponse:!0,requestTimeoutMs:3e4,initialRetryDelayMs:3e3});return hT.parse(n)}async queueTests(e){let t=await this.sendRequest(`/${z}/tests/queue`,{method:"POST",body:e,retries:3,requestTimeoutMs:1e4});return dT.parse(t)}async uploadScreenshot(e){let t=await this.sendRequest(`/${z}/screenshots`,{method:"POST",body:e,retries:3,requestTimeoutMs:5e3});return vT.parse(t)}async getAllEnvironments(){let e=await this.sendRequest(`/${z}/environments`,{method:"GET",retries:3,requestTimeoutMs:5e3});return wT.parse(e)}async acquireCacheLock(e,t){let n=await this.sendRequest(`/${z}/result-cache/lock`,{method:"POST",body:e,signal:t,retries:3,requestTimeoutMs:3e4});return BT.parse(n)}async releaseCacheLock(e){await this.sendRequest(`/${z}/result-cache/lock`,{method:"DELETE",body:{key:e},retries:3,requestTimeoutMs:5e3})}async deleteCacheResult(e){await this.sendRequest(`/${z}/result-cache/entry`,{method:"DELETE",body:e,retries:3,requestTimeoutMs:5e3})}async setCacheResult(e){await this.sendRequest(`/${z}/result-cache/entry`,{method:"PATCH",body:e,retries:3,requestTimeoutMs:5e3})}async getCacheResult(e){try{return await this.sendRequest(`/${z}/result-cache/entry`,{method:"POST",body:e,retries:3,requestTimeoutMs:5e3})}catch(t){if(t instanceof Error&&t.message.includes("404"))return null;throw t}}async queueSuiteRuns(e){let t=await this.sendRequest(`/${z}/suites/queue`,{method:"POST",body:e,retries:3,requestTimeoutMs:5e3});return RT.parse(t)}async bulkGetRunGroupStatus(e){let t={runGroupIds:e},n=await this.sendRequest(`/${z}/run-groups/status`,{method:"POST",body:t,retries:3,requestTimeoutMs:5e3});return Vb.array().parse(n)}async uploadProposedSteps(e,t){try{await this.sendRequest(`/${z}/test-fragments/`,{method:"POST",body:e,retries:3,requestTimeoutMs:1e4})}catch(n){t.error({err:n},"Failed to upload proposed steps")}}async reportBillableEvents(e,t){try{await this.sendRequest(`/${z}/billing/events`,{method:"POST",body:t,retries:10,requestTimeoutMs:1e4})}catch(n){e.error({err:n},"Failed to report billable event")}}async fetchTestFragment(e){let t=await this.sendRequest(`/${z}/test-fragments/${e}`,{method:"GET",retries:3,requestTimeoutMs:1e4});return CT.parse(t)}async patchTestFragment(e,t){await this.sendRequest(`/${z}/test-fragments/${e}`,{method:"PATCH",body:t,retries:3,requestTimeoutMs:1e4})}async getPastTestResults(e,t){let n=await this.sendRequest(`/${z}/results/tests/${e}`,{method:"POST",body:t,retries:3,requestTimeoutMs:1e4});return xT.parse(n)}async generateTestResultsUploadUrl(){let e=await this.sendRequest(`/${z}/results/uploads`,{method:"POST",retries:3,requestTimeoutMs:1e4});return _T.parse(e)}async startProcessingResultsUpload(e,t){let n=await this.sendRequest(`/${z}/results/uploads/${e}/process`,{method:"POST",body:t,retries:3,requestTimeoutMs:1e4});return MT.parse(n)}async fetchIconKnowledgeBase(e){try{let t=await this.sendRequest(`/${z}/knowledge-base/icons`,{method:"GET",retries:3,requestTimeoutMs:5e3});return GT.parse(t)}catch(t){return e.error({err:t},"Failed to fetch icon knowledge base"),null}}async saveNewIcons(e,t){try{await this.sendRequest(`/${z}/knowledge-base/icons`,{method:"POST",body:e,retries:3,requestTimeoutMs:5e3})}catch(n){t.error({err:n},"Failed to save new icons to icon knowledge base")}}async getMergeBaseCommitFromGithub(e,t,n,o){let i=new URLSearchParams;i.set("base",n),i.set("head",o);let a=await this.sendRequest(`/${z}/git/github/${e}/${t}/merge-base-commit?${i.toString()}`,{method:"GET",retries:3,requestTimeoutMs:1e4});return Ba.parse(a)}async getCommitFromGithub(e,t,n){let o=await this.sendRequest(`/${z}/git/github/${e}/${t}/commits/${n}`,{method:"GET",retries:3,requestTimeoutMs:1e4});return Ba.parse(o)}async getMergedBranchFromGithub(e,t,n,o){let i=encodeURIComponent(n),a=await this.sendRequest(`/${z}/git/github/${e}/${t}/${i}/${o}/merged-branch`,{method:"GET",retries:3,requestTimeoutMs:1e4});return Gp.parse(a)}async getMergeBaseCommitFromGitlab(e,t,n){let o=new URLSearchParams;o.set("base",t),o.set("head",n);let i=encodeURIComponent(e),a=await this.sendRequest(`/${z}/git/gitlab/${i}/merge-base-commit?${o.toString()}`,{method:"GET",retries:3,requestTimeoutMs:5e3});return Ba.parse(a)}async getCommitFromGitlab(e,t){let n=encodeURIComponent(e),o=await this.sendRequest(`/${z}/git/gitlab/${n}/commits/${t}`,{method:"GET",retries:3,requestTimeoutMs:1e4});return Ba.parse(o)}async getMergedBranchFromGitlab(e,t,n){let o=encodeURIComponent(t),i=encodeURIComponent(e),a=await this.sendRequest(`/${z}/git/gitlab/${i}/${o}/${n}/merged-branch`,{method:"GET",retries:3,requestTimeoutMs:1e4});return Gp.parse(a)}async getAgentConfig(){let e=await this.sendRequest(`/${z}/web-agent/agent-config`,{method:"GET",retries:3,requestTimeoutMs:5e3});return _g.record(_g.string(),_g.string()).parse(e)}async getQuarantinedTests(){let e=await this.sendRequest(`/${z}/quarantine`,{method:"GET"});return IT.parse(e)}async quarantineTest(e,t,n){await this.sendRequest(`/${z}/quarantine`,{method:"POST",body:{testId:e.id,testName:e.name,reason:t,...n??{}},retries:3,requestTimeoutMs:1e4})}async unquarantineTest(e,t,n){await this.sendRequest(`/${z}/quarantine/${e.id}`,{method:"DELETE",body:{testName:e.name,reason:t,...n??{}},retries:3,requestTimeoutMs:1e4})}async createAndroidEmulator(e){let t=await this.sendRequest(`/${z}/limbar/android`,{method:"POST",retries:3,body:e,requestTimeoutMs:9e4,initialRetryDelayMs:5e3,maxRetryDelayMs:15e3});return PT.parse(t)}async extendAndroidEmulatorTtl(e){try{await this.sendRequest(`/${z}/limbar/android/${e}/keepalive`,{method:"POST",retries:3,requestTimeoutMs:15e3})}catch{}}async generateAndroidAssetUrls({channel:e,tag:t,md5:n}){let o={channel:e,tag:t,md5:n},i=await this.sendRequest(`/${z}/limbar/android/upload-url`,{method:"POST",retries:3,body:o,requestTimeoutMs:15e3,logResponse:!0});return OT.parse(i)}async deleteAndroidEmulator(e){await this.sendRequest(`/${z}/limbar/android/${e}`,{method:"DELETE",retries:3,requestTimeoutMs:3e4})}async getAndroidAssets(){let e=await this.sendRequest(`/${z}/limbar/assets`,{method:"GET",retries:3,requestTimeoutMs:1e4});return LT.parse(e)}async deleteAndroidAsset(e,t){await this.sendRequest(`/${z}/limbar/assets/${e}/${t}`,{method:"DELETE",retries:3,requestTimeoutMs:1e4})}};async function Mg(r){let e=process.versions.node,t=parseInt(e.split(".")[0]);(isNaN(t)||t<18)&&(x.error(`Node.js version 20 or higher is required to run the CLI. Detected: ${process.versions.node}.`),process.exit(1)),x.debug(`Identified node version ${e}`);let n=await r.client.getAuthInfo();return x.debug("Got auth info from API"),n}var au=class{apiClient;constructor(e){this.apiClient=e}async reportBillableEvents(e,t){await this.apiClient.reportBillableEvents(e,t)}};var Ri=class extends Gr{generator;constructor(e,t){super(e),this.generator=t}async runTemplateMatching(e,t={}){let n=await this.sendRequest(`/${z}/web-agent/template-matching`,{method:"POST",body:e,signal:t?.signal});return dy.parse(n)}async constructIframeRegex(e,t={}){return this.generator.getIframeRegex(e,{abortSignal:t.signal})}};var Ci=class{constructor(e,t){this.client=e;this.orgId=t}async acquireCacheLock(e,t){return this.client.acquireCacheLock(e,t)}async uploadScreenshot(e){return(await this.client.uploadScreenshot({screenshot:e.toString("base64")})).key}async releaseCacheLock(e){return this.client.releaseCacheLock(e)}async deleteCacheResult(e){return this.client.deleteCacheResult(e)}async setCacheResult(e){return this.client.setCacheResult(e)}async getCacheResult(e){return this.client.getCacheResult(e)}fetchIconKnowledgeBase(e){return this.client.fetchIconKnowledgeBase(e)}saveNewIcons(e,t){return this.client.saveNewIcons(e,t)}};import{Faker as EH,en as TH}from"@faker-js/faker";var xi="v1",_i=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 EH({locale:TH}),this.fakerInstance.seed(e.fakerSeed))}async sendAiGenerate(e){let t=typeof e=="string"?{input:e}:e;return this.httpClient.sendRequest(`/${xi}/tools/ai/generate`,{method:"POST",body:t}).catch(n=>{throw n instanceof Ar?new Error(n.rawError):new Error(`Failed to send AI generation: ${n.message}`)})}async sendSms(e){return this.httpClient.sendRequest(`/${xi}/tools/sms/send`,{method:"POST",body:e}).then(()=>{}).catch(t=>{throw t instanceof Ar?new Error(t.rawError):new Error(`Failed to send sms: ${t.message}`)})}async fetchLatestSms(e){return this.httpClient.sendRequest(`/${xi}/tools/sms/fetchLatest`,{method:"POST",body:e}).catch(t=>{throw t instanceof Ar?new Error(t.rawError):t})}async sendEmail(e){return this.httpClient.sendRequest(`/${xi}/tools/email/send`,{method:"POST",body:e}).then(()=>{}).catch(t=>{throw t instanceof Ar?new Error(t.rawError):new Error(`Failed to send email: ${t.message}`)})}async fetchAllEmails(e){return this.httpClient.sendRequest(`/${xi}/tools/email/fetchAll`,{method:"POST",body:e}).catch(t=>{throw t instanceof Ar?new Error(t.rawError):new Error(`Failed to fetch all emails: ${t.message}`)})}async fetchLatestEmail(e){return this.httpClient.sendRequest(`/${xi}/tools/email/fetchLatest`,{method:"POST",body:e}).catch(t=>{throw t instanceof Ar?new Error(t.rawError):new Error(`Failed to fetch latest emails: ${t.message}`)})}};function VC(r,e,t){return fetch(r,{method:"PUT",body:t,headers:{"Content-Type":e}})}var su=class{constructor(e){this.client=e}async uploadResultsArchive(e,t){let{uploadUrl:n,id:o}=await this.client.generateTestResultsUploadUrl(),i=await VC(n,"application/zip",t);if(!i.ok)throw new Error(`Failed to upload test results: ${await i.text()}`);let{runGroupId:a}=await this.client.startProcessingResultsUpload(o,{runGroupId:e});return a}};var Mi=class extends Gr{constructor(e){super(e)}async getElementLocation(e,t){let n={...e,loggerTags:t.loggerTags},o=await this.sendRequest(`/${z}/mobile-agent/locate-element`,{method:"POST",body:n,signal:t.abortSignal});return lE.parse(o)}async evaluateAssertion(e,t){let n={...e,loggerTags:t.loggerTags},o=await this.sendRequest(`/${z}/mobile-agent/assertion`,{method:"POST",body:n,signal:t.abortSignal});return dE.parse(o)}};function lu({orgId:r,client:e,gitMetadata:t,alwaysSaveCache:n,noCache:o}){return o?new oc:new Ig(r,e,t,n)}var Ig=class{constructor(e,t,n,o){this.orgId=e;this.client=t;let{gitBranchName:i,gitProtectedBranches:a}=n;this.cacheHeaders=Bp(n),o?this.writeCaches=!0:i?this.writeCaches=!a.includes(i):this.writeCaches=!0}cacheHeaders;writeCaches;async saveEntries({entries:e,testId:t,logger:n}){if(!this.writeCaches){n.debug("Skipping cache storage because branch is protected");return}try{await this.client.updateMobileStepCaches({entries:e,testId:t},this.cacheHeaders)}catch(o){n.error({err:o},"Failed to save mobile step cache entries")}}async resolveEntries(e){let{steps:t}=e.stepLists,n=await this.client.getMobileStepCacheForTest({testId:e.testId},this.cacheHeaders);if(!this.writeCaches){e.logger.debug("Skipping mobile cache last used at update because branch is protected");return}for(let i of[t])i&&qp({steps:i,stepCacheEntries:n,logger:e.logger});let{cachesToSave:o}=await lo({steps:t,cacheCreationParams:{testId:e.testId,orgId:this.orgId}});this.client.updateMobileStepCaches({entries:o,testId:e.testId},this.cacheHeaders)}};import cu from"path";function vH(r){let e=new WC,t=cu.join(r,"metadata.json"),n=za.parse(JSON.parse(Pg.readFileSync(t,"utf-8")));e.addLocalFile(t);for(let o of Pg.readdirSync(cu.join(r,"runs"))){if(!o.endsWith(".zip"))continue;let i=o.replace(/\.zip$/,""),a=new WC(cu.join(r,"runs",o));for(let s of a.getEntries())s.isDirectory||e.addFile(cu.join("runs",i,s.entryName),s.getData())}return{runGroupId:n.id,buffer:e.toBuffer()}}async function uu(r){let{client:e,consoleLogger:t,resultsPath:n}=r;if(!Pg.existsSync(n)){t.warn("Results path does not exist, skipping upload.");return}let o=new su(e);try{let{runGroupId:i,buffer:a}=vH(n),s=await o.uploadResultsArchive(i,a),c=`${e.getAppUrl()}/run-groups/${s}`;t.success(`Successfully uploaded test results. Once processed, your results can be found at ${c}`);return}catch(i){let a;i instanceof Error?a=i.message:typeof i=="string"?a=i:a="Unknown error",t.error(`Failed to upload test results: ${a}.`);return}}import AH from"adm-zip";import ht from"fs";import Vt from"path";var cs=class r{constructor(e){this.filePath=e;ht.rmSync(this.filePath,{recursive:!0,force:!0}),ht.mkdirSync(this.filePath,{recursive:!0})}cd(e){return new r(Vt.join(this.filePath,e))}mkdir(e){ht.mkdirSync(Vt.join(this.filePath,e),{recursive:!0})}readFile(e){let t=Vt.join(this.filePath,e);if(ht.existsSync(t))return ht.readFileSync(t)}storeFile(e){let{name:t,contents:n}=e,o=Vt.join(this.filePath,t);try{ht.writeFileSync(o,n)}catch{}}createFileStream(e){let t=Vt.join(this.filePath,e);return ht.createWriteStream(t)}createRunArchive(e){return new Og(Vt.join(this.filePath,"runs"),e)}},Og=class{constructor(e,t){this.filePath=e;this.tempPath=Vt.join(e,`.${t}`),this.finalPath=Vt.join(e,`${t}.zip`),ht.rmSync(this.tempPath,{recursive:!0,force:!0}),ht.rmSync(this.finalPath,{recursive:!0,force:!0}),ht.mkdirSync(this.tempPath,{recursive:!0})}tempPath;finalPath;readFile(e){let t=Vt.join(this.tempPath,e);if(ht.existsSync(t))return ht.readFileSync(t)}mkdir(e){ht.mkdirSync(Vt.join(this.tempPath,e),{recursive:!0})}cd(e){return new cs(Vt.join(this.tempPath,e))}storeFile(e){let{name:t,contents:n}=e,o=Vt.join(this.tempPath,t);ht.writeFileSync(o,n)}createFileStream(e){let t=Vt.join(this.tempPath,e);return ht.createWriteStream(t)}close(){let e=new AH;e.addLocalFolder(this.tempPath,void 0,n=>n!==".DS_Store");let t=e.toBuffer();ht.writeFileSync(this.finalPath,t),ht.rmSync(this.tempPath,{recursive:!0,force:!0})}};import yu from"fs";import ox from"body-parser";import HH from"cors";import GH from"dedent";import{Router as xH}from"express";import Pt from"fs";import{globSync as _H}from"glob";import dt from"path";import Ng from"fs";import wH from"path";var RH=new bc(30,60*1e3),Ug="https://api.momentic.ai",kg,qC=r=>{Ug=r},Fg=()=>Ug,Bg=()=>kg;var Ii,Dg,$C,KC=async r=>{if(kg&&Ii&&$C)return Ii;let e=new wr({baseUrl:Ug,apiKey:r,logger:x});kg=e;try{let t=await e.getAuthInfo();return Ii=t.orgId,Dg=t.userId,$C=r,Ii}catch(t){throw new Error(`Error checking API key against server: ${t}`)}},Pi=()=>{if(!Ii)throw new Error("Your organization ID is invalid.");return Ii},du=()=>{if(!Dg)throw new Error("Your user ID is invalid.");return Dg};var zg,Lg,YC=(r,e)=>{zg=r,Lg?.abort(),Lg=new AbortController;let t=Lg.signal,n=[r.configFilePath];r.config.environments?.forEach(o=>{if(!o.envFile)return;let i=wH.resolve(r.rootDir,o.envFile);try{if(Ng.lstatSync(i).isSymbolicLink())return;Ng.existsSync(i)&&n.push(i)}catch(a){x.warn({err:a},`Failed to check if env file ${i} exists`)}});try{CH({filesToWatch:n,revalidator:e,signal:t,project:r})}catch(o){x.error({err:o},"Failed to start config file watchers")}},ut=()=>zg;function CH({filesToWatch:r,revalidator:e,signal:t,project:n}){r.forEach(o=>{Ng.watch(o,{signal:t,persistent:!1,recursive:!1},async(i,a)=>{a&&(RH.increment("setLocalProject")&&x.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.`),zg=await Promise.resolve(e(n.configFilePath)))})})}function st(r){return function(...e){let t=e[e.length-1],n=r(...e);Promise.resolve(n).catch(t)}}var ds=xH();function us(r){let e=ut(),t=dt.dirname(e.configFilePath);return dt.join(t,...r)}function MH(r){let e=ut(),t=dt.dirname(e.configFilePath),n=dt.relative(t,r);return n?n.split(dt.sep):[]}function IH(r,e){let t=Pt.statSync(r),n=MH(r);return Op.parse({name:e,absolutePath:r,relativePath:n.join(dt.sep),pathSegments:n,isDirectory:t.isDirectory(),size:t.size,createdAt:t.birthtime,modifiedAt:t.mtime,accessedAt:t.atime})}ds.post("/",st(async(r,e,t)=>{let n;try{n=WE.parse(r.body).pathSegments}catch(d){e.status(400).json({error:`Failed to parse folder read body: ${d}`});return}let o=us(n);if(!Pt.existsSync(o)){e.status(404).json({error:`Path not found: ${n.join(dt.sep)}`});return}if(!Pt.statSync(o).isDirectory()){e.status(400).json({error:`Path is not a directory: ${n.join(dt.sep)}`});return}let a=ut(),s=Array.from(a.config.exclude??[]).concat(Xl),l=_H("*",{absolute:!1,cwd:o,ignore:s,dotRelative:!1,maxDepth:1,nodir:!1}).map(d=>{let p=dt.join(o,d);return IH(p,d)}),u={absolutePath:o,pathSegments:n,contents:l};e.status(200).json(u)}));ds.put("/",st(async(r,e,t)=>{let n;try{n=$E.parse(r.body).pathSegments}catch(a){e.status(400).json({error:`Failed to parse folder create body: ${a}`});return}let o=us(n);if(Pt.existsSync(o)){e.status(200).json({success:!0,message:`Folder already exists: ${n.join(dt.sep)}`,pathSegments:n});return}Pt.mkdirSync(o,{recursive:!0});let i={success:!0,message:`Folder created: ${n.join(dt.sep)}`,pathSegments:n};e.status(201).json(i)}));ds.patch("/",st(async(r,e,t)=>{let n,o;try{let l=qE.parse(r.body);n=l.pathSegments,o=l.newPathSegments}catch(l){e.status(400).json({error:`Failed to parse folder update body: ${l}`});return}let i=us(n),a=us(o);if(!Pt.existsSync(i)){e.status(400).json({error:`Folder not found: ${n.join(dt.sep)}`});return}if(Pt.existsSync(a)){e.status(400).json({error:`Destination already exists: ${o.join(dt.sep)}`});return}let s=dt.dirname(a);Pt.existsSync(s)||Pt.mkdirSync(s,{recursive:!0}),Pt.renameSync(i,a);let c={success:!0,message:`Folder moved from ${n.join(dt.sep)} to ${o.join(dt.sep)}`,pathSegments:o};e.status(200).json(c)}));ds.delete("/",st(async(r,e,t)=>{let n,o=!0;try{let c=KE.parse(r.body);n=c.pathSegments,o=c.recursive??!0}catch(c){e.status(400).json({error:`Failed to parse folder delete body: ${c}`});return}let i=us(n);if(!Pt.existsSync(i)){e.status(200).json({success:!0,message:`Folder not found: ${n.join(dt.sep)}`,pathSegments:n});return}if(!Pt.statSync(i).isDirectory()){e.status(400).json({error:`Path is not a directory: ${n.join(dt.sep)}`});return}if(o)Pt.rmSync(i,{recursive:!0,force:!0});else{if(Pt.readdirSync(i).length>0){e.status(409).json({error:`Cannot delete non-empty directory without recursive flag: ${n.join("/")}`});return}Pt.rmdirSync(i)}let s={success:!0,message:`Folder deleted: ${n.join("/")}`,pathSegments:n};e.status(200).json(s)}));var Hg=ds;import jH from"events";import ix,{Router as VH}from"express";import WH from"http";import $H from"path";var pu=class{sessions=new Map;registerSession(e,t){this.sessions.set(e,t)}getSession(e){return this.sessions.get(e)}async removeSession(e,t){let n=this.sessions.get(e);if(n)try{await n.cleanup?.(),t.info({sessionId:e,emulatorName:n.emulatorName},"Android emulator cleaned up")}catch(o){t.error({err:o},"Error during Android session cleanup")}finally{this.sessions.delete(e)}}async removeAllSessions(e){let t=Array.from(this.sessions.keys());await Promise.all(t.map(n=>this.removeSession(n,e)))}};var XC=new pu;import{Router as LH}from"express";import{existsSync as NH}from"fs";import kH from"path";import{hostname as PH}from"os";var OH="0.0.30",Ot=Hc({app:"mobile-desktop-server",hostname:PH(),disableConsoleLogs:!0}).child({cliVersion:OH});(async()=>{try{let r=await dg(Ot);r.gitBranchName&&Ot.addBinding("branch",r.gitBranchName)}catch{}})();var Gg=LH();Gg.get("/",st(async(r,e)=>{let t=Bg();if(!t){e.status(500).json({message:"API client not initialized"});return}let n=await t.getAndroidAssets();e.status(200).json(n)}));Gg.post("/upload-url",st(async(r,e)=>{let t;try{t=QE.parse(r.body)}catch(i){e.status(400).json({error:`Invalid request body: ${i}`});return}let n=Bg();if(!n){e.status(500).json({error:"API client not initialized"});return}let o=kH.resolve(t.filePath);if(!NH(o)){e.status(400).json({error:`File not found: ${o}`});return}await cl({tag:t.tag,channel:t.channel,filePath:o,apiClient:n,logger:Ot}),e.sendStatus(204)}));var JC=Gg;import{Router as DH}from"express";var ZC=DH();ZC.get("/",st(async(r,e)=>{let t=ut(),n=await vr(t),o=new Set;n?.tests&&Object.values(n.tests).forEach(c=>{c.labels?.forEach(l=>o.add(l))});let i=Array.from(o).sort(),a=Object.values(n.mobileTests),s={labels:i,modules:[],tests:a};e.status(200).json(s)}));var QC=ZC;import{Router as UH}from"express";var ex=UH();ex.get("/",(r,e)=>{e.status(200).json({userId:du(),orgId:Pi()})});var tx=ex;import{Router as FH}from"express";var mu=FH();async function BH(r){return(await VR(r,Ot)).map(n=>{let o=r.mobileModules[n.moduleId];if(!o){x.warn(`Found a dangling mobile module with ID ${n.moduleId} that could not be found on disk.`);return}return{...o,content:n}}).filter(n=>n!==void 0)}mu.get("/",st(async(r,e)=>{let t=ut(),n=await vr(t),o=await BH(n);e.status(200).json(o)}));mu.get("/:moduleId",st(async(r,e)=>{if(!r.params.moduleId){e.status(400).json({error:"Missing moduleId in url path."});return}let t=await vr(ut()),n=t.mobileModules[r.params.moduleId];if(!n){e.status(404).json({error:"Mobile module not found."});return}try{let o=await mg(n,t,x);e.json(o)}catch(o){e.status(400).json({err:o})}}));mu.patch("/:moduleId/metadata",st(async(r,e)=>{if(!r.params.moduleId){e.status(400).json({error:"Missing moduleId in url path."});return}let t;try{t=eT.parse(r.body)}catch(i){e.status(400).json({error:`Invalid request body: ${i}`});return}let n=ut(),o=await vr(n);jR({moduleId:r.params.moduleId,patch:t,momenticFiles:o,logger:x,project:n}),e.status(201).json({message:"ok"})}));var rx=mu;import{Router as zH}from"express";import jg from"path";var gu=zH();gu.patch("/:testPath",st(async(r,e)=>{let t=r.params.testPath;if(!t){e.status(400).json({error:"Missing testPath in path"});return}let n;try{n=ZE.parse(r.body)}catch(c){e.status(400).json({error:`Invalid request body: ${c}`});return}if(n.steps===void 0&&n.settings===void 0){e.status(400).json({error:"At least one of steps or settings is required"});return}let o=ut(),i=t.endsWith(".test.yaml")?t:`${t}.test.yaml`,a=await vr(o);await $R({filePath:i,steps:n.steps,settings:n.settings,folder:o.rootDir,project:o,momenticFiles:a});let s={message:"ok"};e.status(200).json(s)}));gu.post("/",st((r,e)=>{let t;try{t=JE.parse(r.body)}catch(m){e.status(400).json({error:`Invalid request body: ${m}`});return}let{name:n,description:o,settings:i,pathSegments:a}=t;if(!n||typeof n!="string"){e.status(400).json({error:"Missing or invalid 'name' in body"});return}try{Qd(n)}catch(m){e.status(400).json({error:m.message});return}let s=ut(),c=jg.join(s.rootDir,...a),{fullPath:l,testId:u}=WR({name:n,description:o,steps:[],settings:i,folder:c}),d=jg.basename(l),p=jg.relative(s.rootDir,l),g={id:u,fileName:d,fullPath:l,relativeFilePath:p};e.status(201).json(g)}));gu.get("/:fileName",st(async(r,e)=>{let t=r.params.fileName;if(!t){e.status(400).json({error:"Missing fileName in path"});return}let n=t.endsWith(".test.yaml")?t:`${t}.test.yaml`,o=ut(),i=await vr(o),s=await Qc(n,Ot,i);e.status(200).json(s)}));var nx=gu;var hu=class extends Ci{constructor(t,n){super(t,n);this.client=t;this.orgId=n}async fetchEnvironment(t,n){let o=ut();return Kc(t,o,x)}};var ax="10mb";async function sx(r){let{serverPort:e,apiKey:t,momenticServerUrl:n,staticDir:o,initialProject:i,driverLogLevel:a,alwaysSaveCache:s,noCache:c}=r;n&&qC(n),await KC(t);let l=Pi(),u=du(),d=r.logger.child({orgId:l,userId:u});YC(i,T=>rs({configFilePath:T}));let p=ix();p.use(HH()),p.use(ox.json({limit:ax})),p.use(ox.urlencoded({extended:!1,limit:ax}));let g=VH();if(g.use("/folders",Hg),g.use("/entities",QC),g.use("/identify",tx),g.use("/mobile-tests",nx),g.use("/mobile-modules",rx),g.use("/assets",JC),p.use("/api",g),p.use((T,I,R)=>{x.debug({url:T.url,path:T.path,query:T.query,method:T.method,body:T.body,headers:T.rawHeaders,client:T.ip},"Incoming request on mobile-desktop-server"),I.on("close",()=>{I.statusCode>=400&&(x.error({url:T.url,method:T.method,statusCode:I.statusCode},"Request completed in error on mobile-desktop-server"),Ot.error({url:T.url,method:T.method,statusCode:I.statusCode},"Request completed in error on mobile-desktop-server"))}),R()}),p.use((T,I,R,w)=>{if(T instanceof Error&&T.message.includes("BadRequestError: request aborted")){R.status(400).send("Client disconnected");return}x.error({stack:T.stack,msg:T.message,err:T,url:I.url,method:I.method},"Unhandled exception leading to 500 on mobile-desktop-server"),Ot.error({stack:T.stack,msg:T.message,err:T,url:I.url,method:I.method},"Unhandled exception leading to 500 on mobile-desktop-server"),R.status(500).send(`Internal Server Error: ${T.message}`)}),o){let T=ix.static(o,{setHeaders:I=>{I.setHeader("Cache-Control","no-cache")},redirect:!1});p.use(T),p.use("*",(I,R)=>{R.sendFile($H.join(o,"index.html"))})}let m=WH.createServer(p),h=`http://localhost:${e}`;await new Promise(T=>{try{m.listen(e,()=>{d.info(`Mobile desktop server is running at ${h}`),T()})}catch(I){I.message.includes("EADDRINUSE")?qH(e):x.error(`An unexpected error occurred while starting the server: ${I.message}`),process.exit(1)}});let E={type:"API_KEY",baseUrl:Fg(),apiKey:t,logger:d},S=new wr(E),A=ut(),{dispose:C}=vR({baseServer:m,logger:d,authorization:E,globalStateManager:XC,getOrgId:()=>Pi(),androidDriverFactory:async({socket:T,logger:I,creationOpts:R})=>{let w=Math.floor(Math.random()*1e4)+4e4,B=await qc(w,"appium");return ll({logger:I,driverLogLevel:a,apiClient:S,creationOpts:R,socket:T,appiumPort:B,orgId:Pi(),onStatusUpdate:D=>{T.emit("connectionStatusUpdate",{message:D})}})},mobileGeneratorFactory:async T=>new Mi({baseUrl:Fg(),apiKey:t,logger:d}),browserGeneratorFactory:async T=>new Co(A.config.ai?.agentConfig,E),browserEnricherFactory:async T=>new Ri(E,new Co(A.config.ai?.agentConfig,E)),storageFactory:async T=>new hu(S,T),cacheStorageFactory:async T=>{let I=await Xc(d,S,A);return lu({orgId:T,client:S,gitMetadata:I,noCache:c,alwaysSaveCache:s})},localToolsFactory:async()=>new _i({httpClient:S,fakerSeed:void 0}),keepSessionAlive:T=>S.extendAndroidEmulatorTtl(T),settingsFactory:async()=>({emulator:A.config.emulator})});process.once("SIGUSR2",async()=>{return;try{await C(),await St.flush()}catch(T){x.error({err:T},"Error during session dispose on SIGUSR2")}try{m.close(()=>{process.kill(process.pid,"SIGUSR2")})}catch{process.kill(process.pid,"SIGUSR2")}}),process.once("SIGTERM",async()=>{x.info("SIGTERM in Momentic mobile app received");try{await C(),await St.flush()}finally{m.close(()=>process.exit(0))}}),process.once("SIGINT",async()=>{x.info("SIGINT in Momentic mobile app received");try{await C(),await St.flush()}finally{m.close(()=>process.exit(0))}})}jH.setMaxListeners(25);process.on("warning",r=>{Ot.warn({err:r},`Node warning received on mobile-desktop-server: ${r.message}`)});process.on("uncaughtException",r=>{Ot.error({err:r},"Uncaught exception on mobile-desktop-server"),x.error(`Oh no! The Momentic mobile desktop app encountered a fatal error \u{1F61E}. Error logs: ${r.message}`)});process.on("unhandledRejection",r=>{Ot.error({reason:`${r}`,stack:r?.stack},"Uncaught exception on mobile-desktop-server (promise rejection)"),x.error(`Oh no! The Momentic mobile desktop app encountered an asynchronous error \u{1F61E}. Error logs: ${r}`)});function qH(r){x.error(GH`Port ${r} is already in use by another process. Please close the other process and try again.
|
|
4075
|
+
`),globalThis.console=e}}var Fm=" ".repeat(6);import{hostname as jF}from"os";var Ft=Zs({app:"cli",hostname:jF(),disableConsoleLogs:!0}).child({cliVersion:"0.1.0"});function Bm(r){if(!r)return;r=r.toLowerCase();let e=js.safeParse(r);if(e.success)return A.setMinLevel(e.data),e.data}function dR({results:r,startTime:e,entity:t,getDisplayLine:n,onFailed:o}){let i=r.filter(u=>u.status==="PASSED"&&u.quarantined),a=r.filter(u=>u.status==="PASSED"&&!u.quarantined),l=r.filter(u=>u.status==="FAILED"&&u.quarantined),c=r.filter(u=>u.status==="FAILED"&&!u.quarantined),s=r.filter(u=>u.status==="CANCELLED");return uR(()=>{if(c.forEach(u=>{A.log(""),o(u)}),c.length){A.log("");let u=c.length===1?"":"s";A.error(`${c.length} ${t}${u} failed:`),c.forEach(d=>{A.dimmed(n(d))})}if(s.length){A.log("");let u=s.length===1?"":"s";A.warn(`${s.length} ${t}${u} cancelled:`),s.forEach(d=>{A.dimmed(n(d))})}if(a.length){A.log("");let u=a.length===1?"":"s";A.success(`${a.length} ${t}${u} passed:`),a.forEach(d=>{A.dimmed(n(d))})}if(l.length){A.log("");let u=l.length===1?"":"s";A.warn(`${l.length} quarantined ${t}${u} failed:`),l.forEach(d=>{A.dimmed(n(d))})}if(i.length){A.log("");let u=i.length===1?"":"s";A.warn(`${i.length} quarantined ${t}${u} passed:`),i.forEach(d=>{A.dimmed(n(d))})}A.log(""),A.dimmed(`Total time: ${Math.round((Date.now()-e)/1e3)}s`)}),{quarantinedPassed:i.length,passed:a.length,quarantinedFailed:l.length,failed:c.length,cancelled:s.length}}var Va=({status:r,testLogRef:e,getRunningTestsCount:t,getTotalTestsCount:n,additionalText:o})=>{r=r.toUpperCase();let i=r,a;r.includes("FAIL")?(i=ui.bgRed.white("FAIL"),a=3):r.includes("PASS")?(i=ui.bgGreen.white("PASS"),a=3):r.includes("START")?(i=ui.bgBlue.white("START"),a=2):r.includes("CANCEL")?(i=ui.bgRgb(191,68,11).white("CANCEL"),a=1):r.includes("RETRY")?(i=ui.bgRgb(191,68,11).white("RETRY"),a=2):r.includes("RUN")||r.includes("PROG")?(i=ui.bgMagenta.white("RUNNING"),a=0):(A.warn(`Unknown status tried to be logged in run test locally: ${r}`),a=0),WF||(i=`${i}`),A.log(`${i}${" ".repeat(a)} ${e} ${o?`${o} `:""}(${t()}/${n()})`)};var YF=!1,pR=(()=>{try{return KF("/.dockerenv"),!0}catch{return!1}})();async function Dc(r){return zn||YF||pR?!0:(A.flush(),Ft.flush(),await new Promise(t=>setTimeout(t,500)),await $F({message:r}))}async function mR(r,e){return zn||pR?e:(await qF({message:r,default:e})).trim()||e}import XF from"fs";import{tmpdir as JF}from"os";import ZF from"path";import{registry as ja}from"playwright-core/lib/server";import gR from"proper-lockfile";var hR=ZF.join(JF(),"momenticBrowserInstallation");var zm=["chrome","chromium","chrome-for-testing"],QF={Chromium:"chromium","Google Chrome":"chrome","Chrome for Testing":"chrome-for-testing"},fR={chrome:"chrome",chromium:"chromium","chrome-for-testing":"chromium-headless-shell"};function SR(r){let e=fR[QF[r]??""]??"",t=ja.findExecutable(e);return!t||t.installType==="none"?!1:Hm(t)}function Hm(r){let e=r.executablePath();return XF.existsSync(e)}function eB(r,e){let t=fR[r];if(!t)throw new Error(`Requested install of unknown browser type ${r}`);let n=ja.findExecutable(t);if(!n||n.installType==="none")throw new Error(`Requested install of unknown browser type ${r}`);if(!(!e&&Hm(n)))return n}async function tB({browser:r,force:e}){let t=eB(r,e);if(!t){A.info(`Browser '${r}' is already installed, skipping...`);return}A.info(`Installing browser '${r}'...`);try{await ja.installDeps([t],!1),await ja.install([t],!1)}catch(n){if(n.message.includes("Lock file is already being held")){A.warn("Another process is installing Playwright browsers. Waiting for completion before proceeding..");let o=ja.findExecutable(r),i=5*60*1e3,a=Date.now();for(;Date.now()-a<i&&!Hm(o);)A.info("Waiting for browser to finish installing..."),await new Promise(l=>setTimeout(l,5e3))}else throw n}}async function kc({rawBrowsers:r,force:e=!1,all:t=!1}){let n=t?zm:Array.from(new Set(r));try{await gR.lock(hR,{stale:1e3*60*5,update:1e3*60,realpath:!1,retries:{retries:30,factor:2,maxTimeout:15e3,minTimeout:500}})}catch(i){A.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 tB({browser:i,force:e})}catch(a){o=a,A.error(`Failed to install the ${i} browser: ${a}`)}}finally{await gR.unlock(hR,{realpath:!1})}if(o)throw o}import{createServer as rB}from"http";async function Uc(r,e){for(let n=0;n<30;n+=1){let o=r+n;if(await nB(o))return o}A.error(`Could not find an available port for ${e} starting from ${r} after 30 attempts`),process.exit(1)}async function nB(r){return new Promise((e,t)=>{let n=rB();n.once("error",o=>{o.code==="EADDRINUSE"?e(!1):(A.warn({err:o},"Unexpected error checking for open ports, continuing..."),n.close(),e(!0))}),n.once("listening",()=>{n.close(()=>{e(!0)})}),n.listen(r)})}import mMe from"blocked-at";import hMe from"why-is-node-running";import{randomUUID as t1}from"crypto";import{diff as QMe}from"deep-object-diff";import u_e from"yaml";import{z as p_e}from"zod";import{execSync as oB}from"child_process";function ao(r,e){let t=e.hooks?.postSave;if(!t)return;let n;t.includes("$1")?n=t.replaceAll("$1",r):n=`${t} ${r}`,A.debug({postSaveCommand:n},"Executing post-save hook command");try{oB(n,{encoding:"utf-8"})}catch(o){A.warn({err:o,postSaveCommand:n},"Failed to execute post-save hook command, continuing...")}}import{diff as IMe}from"deep-object-diff";import{cloneDeep as OMe}from"lodash-es";import{v4 as jMe}from"uuid";import $Me from"yaml";import iB from"@dotenvx/dotenvx";import aB from"fs";import yR from"path";function sB(r){return r.includes("${")?r.replace(/\$\{([^}]+)\}/g,(e,t)=>{let[n,o]=t.split(/:-|-/,2),i=process.env[n];return t.includes(":-")?i&&i!==""?i:o||"":t.includes("-")?i!==void 0?i:o||"":i||""}):r}function lB(r){let{envVariables:e,project:t}=r;if(!e)return{};let n={};for(let[o,i]of Object.entries(e)){if(typeof i=="string"){let l=sB(i);l&&(n[o]=l);continue}let a;try{a=aB.readFileSync(yR.resolve(t.rootDir,i.fromFile),"utf-8")}catch(l){throw new Error(`Failed to read environment variable '${o}' from file '${i.fromFile}': ${l}`)}if(i.json)try{n[o]=JSON.parse(a)}catch(l){throw new Error(`Failed to parse environment variable '${o}' from file '${i.fromFile}' as JSON: ${l}`)}else n[o]=a}return Object.keys(n).length>0&&A.debug(n,"Set environment variables with interpolation from project configuration"),n}function cB(r){let{project:e,envFile:t,logger:n}=r,o={};if(!t)return o;let i=iB.config({path:yR.resolve(e.rootDir,t),processEnv:o,logLevel:"error",quiet:!0});if(i.error)throw new Error(`Failed to load .env file: ${i.error.message}`);return n.debug(o,"Set environment variables from .env file"),o}function Fc(r,e,t){let n=(e.config.environments??[]).find(c=>c.name===r);if(!n)throw new Error(`Environment ${r} not found in local project configuration file`);let o={},i=lB({envVariables:n.envVariables,project:e});Object.assign(o,i);let a=cB({project:e,envFile:n.envFile,logger:t});return Object.assign(o,a),n.inheritFromShell&&(t.debug(process.env,"Inheriting environment variables from shell"),Object.assign(o,process.env)),{name:r,variables:o}}import{existsSync as vB,readFileSync as AB,readdirSync as wB,writeFileSync as RB}from"fs";import{glob as CB}from"glob";import so,{dirname as TR}from"path";import{cwd as $m}from"process";import vR from"yaml";import{z as Ie}from"zod";import bR from"fs";import{glob as uB}from"glob";import Wa from"path";import dB from"yaml";import{z as Gm}from"zod";var ER=!1,Vm=["**/*.test.yaml","**/*.module.yaml"],jm=Gm.string().refine(r=>/^[a-zA-Z0-9-]+$/.test(r)),Wm=15,pB=Gm.object({fileType:Gm.nativeEnum(Me)});async function fr(r,e=!1){let t={project:r,tests:{},modules:{},mobileTests:{},mobileModules:{},duplicateEntities:{}},n=r.config.include??Vm,o=Array.from(r.config.exclude??[]).concat(Gs),i=AbortSignal.timeout(5e3),a;try{a=await uB(n,{absolute:!1,cwd:r.rootDir,ignore:o,dotRelative:!1,maxDepth:Wm,nodir:!0,signal:i})}catch(l){throw A.error({err:l},"Failed to list all Momentic files in the current directory. This usually indicates the 'include' and 'exclude' globs are misconfigured in your momentic.config.yaml, or that your machine is severely resource constrained."),new Error("Listing Momentic files timed out after 5 seconds.",{cause:l})}for(let l of a){let c=mB(r.rootDir,l,t,e?un:A);c&&(t.duplicateEntities[c.id]=c.paths)}return ER=!0,t}function mB(r,e,t,n){let o=Wa.join(r,e),i=gB(o,n);if(!i)return;let a=hB(i,o,n);if(!a)return;let l=pB.safeParse(a);if(l.success===!1){n.warn(`Possible Momentic file at ${o} does not have a 'fileType', skipping: ${l.error}`);return}let c=l.data.fileType,s=fB(o,n);if(!s)return;let u=SB(e,o,s);switch(c){case Me.TEST:try{return yB(a,t,u,o,n)}catch(d){n.warn(`Skipping file '${o}' because it is missing Momentic test metadata: ${d}`);return}case Me.MODULE:try{return bB(a,t,u,o,n)}catch(d){n.warn(`Skipping file '${o}' because it is missing Momentic module metadata: ${d}`);return}case Me.MOBILE_TEST:try{return TB(a,t,u,o,n)}catch(d){n.warn(`Skipping file '${o}' because it is missing Momentic mobile test metadata: ${d}`);return}case Me.MOBILE_MODULE:try{return EB(a,t,u,o,n)}catch(d){n.warn(`Skipping file '${o}' because it is missing Momentic mobile module metadata: ${d}`);return}default:{let d=c;return}}}function gB(r,e){try{return bR.readFileSync(r,"utf-8")}catch(t){e.warn(`Could not read possible Momentic file at ${r}, skipping: ${t}`);return}}function hB(r,e,t){try{let n=dB.parse(r);if(typeof n!="object"||n===null)throw new Error("The YAML document should parse as a map with key-value pairs");return n}catch(n){t.warn(`Could not parse possible Momentic file at ${e}, skipping: ${n}`);return}}function fB(r,e){try{return bR.statSync(r)}catch(t){e.warn(`Skipping path '${r}' because it could not be stat, skipping: ${t}`);return}}function SB(r,e,t){return{relativePath:r,fullFilePath:e,platformSep:Wa.sep,fullPathSegments:e.split(Wa.sep),relativePathSegments:r.split(Wa.sep),fileName:Wa.basename(e),lastModified:t.mtime,createdAt:t.birthtime}}function yB(r,e,t,n,o){let i=Oo.parse(r),a;if(e.tests[i.id]){let l=e.tests[i.id].fullFilePath;a={id:i.id,paths:[l,n]}}return e.tests[i.id]={type:Me.TEST,name:i.name,id:i.id,description:i.description??void 0,labels:i.labels,...t},a}function bB(r,e,t,n,o){let i=Kt.parse(r),a;if(e.modules[i.moduleId]){let c=e.modules[i.moduleId].fullFilePath;a={id:i.moduleId,paths:[c,n]}}e.modules[i.moduleId]={type:Me.MODULE,name:i.name,id:i.moduleId,description:i.description??void 0,...t};let l=t.fileName.replace(".module.yaml","");return!ER&&Qr(i.name)!==l&&o.warn(`The module with ID ${i.moduleId} has a name (${i.name}) that does not match its file name (${l}). We recommend renaming the module or the file to be consistent to avoid confusion and issues with module resolution.`),a}function EB(r,e,t,n,o){let i=ea.parse(r),a;if(e.mobileModules[i.moduleId]){let c=e.mobileModules[i.moduleId].fullFilePath;a={id:i.moduleId,paths:[c,n]}}let l=t.fileName.replace(".module.yaml","");return e.mobileModules[i.moduleId]={type:Me.MOBILE_MODULE,name:l,id:i.moduleId,description:i.description??void 0,...t},a}function TB(r,e,t,n,o){let i=vr.parse(r),a;if(e.mobileTests[i.id]){let c=e.mobileTests[i.id].fullFilePath;a={id:i.id,paths:[c,n]}}let l=t.fileName.replace(".test.yaml","");return e.mobileTests[i.id]={type:Me.MOBILE_TEST,name:l,id:i.id,description:i.description??void 0,...t},a}var di="momentic.config.yaml",qm="momentic.workspace.yaml",xB=Ie.object({projects:Ie.string().array().describe("list of glob patterns to find project (momentic.config.yaml) files")}),MB=Ie.union([Ie.string(),Ie.object({fromFile:Ie.string(),json:Ie.boolean().optional()})]),_B=Ie.object({name:jm,baseUrl:Ie.string().optional().describe("Optional for mobile tests"),envFile:Ie.string().optional().describe("path to a file on disk to read environment variables from. can be relative to project root or absolute."),envVariables:Ie.record(Ie.string(),MB).optional(),inheritFromShell:Ie.boolean().optional().describe("inherit all environment variables from the shell - might be noisy"),browser:Dn.optional().describe("deprecated: use project-level configuration only")}),IB=Ie.object({postSave:Ie.string().optional()}),PB=Ie.object({name:jm,include:Ie.string().array().optional().describe("list of glob patterns that match momentic files (optional)"),exclude:Ie.string().array().optional().describe("opposite of include, takes precedence over include"),goldenFileDir:Ie.string().optional(),reporterDir:Ie.string().optional(),outputDir:Ie.string().optional(),retries:Ie.number().optional().describe("number of retries per test"),parallel:Ie.number().optional().describe("degree of parallelism"),environments:Ie.array(_B).optional(),gitMainBranch:Ie.string().optional(),gitProtectedBranches:Ie.string().array().optional(),ai:Sd.optional(),browser:Dn.optional(),emulator:cd.optional(),advanced:yd.optional(),hooks:IB.optional()});function AR(r,e){let t;try{t=AB(r,"utf-8")}catch(o){A.warn(`Could not read possible Momentic ${e} file at ${r}: ${o}`);return}let n;try{if(n=vR.parse(t),typeof n!="object"||n===null)throw new Error(`The ${e} file should parse as a map with key-value pairs, but is type ${typeof n} instead`)}catch(o){A.warn(`Possible Momentic ${e} file at ${r} does not parse as valid YAML: ${o}`);return}return n}function Km(r){let e=AR(r,"project configuration");if(e!==void 0)try{return PB.parse(e)}catch(t){A.warn(`Possible Momentic project configuration file at ${r} does not adhere to the required schema: ${t}`);return}}function OB(r){let e=AR(r,"workspace configuration");if(e!==void 0)try{return xB.parse(e)}catch(t){A.warn(`Possible Momentic workspace configuration file at ${r} does not adhere to the required schema: ${t}`);return}}function LB(){let r=[],e=$m(),t=so.parse(e).root,n=15,o=0;for(;o<n;){o++;let i=so.basename(e);if(Hs.includes(i))return A.warn(`Stopping search for Momentic projects since the current directory name (${i}) is likely a system artifact folder.`),r;for(let a of wB(e))if(a.endsWith(di)){let l=so.join(e,a),c=Km(l);c&&r.push({configFilePath:l,config:c,rootDir:TR(l)})}if(r.length)return r;if(e=so.dirname(e),e===t)break}return r}async function $a(r={}){let{configFilePath:e,nameFilter:t}=r,n=await DB(e);if(t&&(n=n.filter(o=>o.config.name===t)),n.length>1)throw new Error(`Multiple valid projects were found in the same directory. Please use the '-c / --config' flag to disambiguate:
|
|
4076
|
+
${n.map(o=>o.configFilePath)}`);if(n.length===0)throw new Error("No valid Momentic project file available.");return A.debug(`Found valid project configuration at ${n[0].configFilePath}`),n[0]}async function NB(r){let e=OB(r);if(!e||!e.projects||!e.projects.length)return;let t=e.projects.map(a=>(a.endsWith("/")||(a+="/"),`${a}*${di}`)),n=AbortSignal.timeout(2e3),o;try{o=await CB(t,{absolute:!1,cwd:$m(),dotRelative:!1,maxDepth:Wm,nodir:!0,signal:n})}catch(a){throw A.error({err:a},`Failed to list the available Momentic projects in the current directory. This usually indicates the 'include' or 'exclude' option in your ${qm} is misconfigured.`),a}let i=[];for(let a of o){let l=so.join($m(),a),c=Km(l);c&&i.push({configFilePath:l,config:c,rootDir:TR(l)})}return i}async function DB(r){if(r){r=so.resolve(r);let t=Km(r);return t||(console.error(`No valid Momentic project file found at ${r}.`),process.exit(1)),[{config:t,configFilePath:r,rootDir:so.dirname(r)}]}if(vB(qm)){let t=await NB(qm);if(t)return t}return LB()}function wR(r,e){let t=vR.stringify(r);RB(e,t)}import{z as Ym}from"zod";var RR="test-results";var X_e=Ym.object({width:Ym.number(),height:Ym.number()});import{execFile as kB}from"node:child_process";import{promisify as UB}from"node:util";import FB from"simple-git";var Pe=FB(),CR=UB(kB);async function BB(r){let e=await Oe(r,Pe.raw(["config","--list"])),t={};if(!e)return t;for(let n of e.split(`
|
|
4077
|
+
`)){let o=n.indexOf("=");if(o===-1)continue;let i=n.slice(0,o),a=n.slice(o+1).trim();t[i]=a}return t}async function zB(r,e,t){try{let o=t["github.user"]||void 0;if(o)return o}catch{}let n;try{if(e?.startsWith("http://")||e?.startsWith("https://"))n=new URL(e).host;else if(e?.startsWith("git@")){let o=e.indexOf("@"),i=e.indexOf(":",o+1);o!==-1&&i!==-1&&(n=e.slice(o+1,i))}}catch{}if(n=n?.toLowerCase(),!!n){try{if(e?.startsWith("git@")&&n?.includes("github")){let{stdout:o,stderr:i}=await CR("ssh",["-T","-o","BatchMode=yes",`git@${n}`],{timeout:5e3}),l=`${o??""}${i??""}`.trim().match(/Hi\s+([A-Za-z0-9_-]+)!/);if(l?.[1])return l[1]}}catch{}try{let o=n&&n!=="github.com"?["api","--hostname",n,"user","-q",".login"]:["api","user","-q",".login"],{stdout:i}=await CR("gh",o,{timeout:5e3}),a=i?.toString().trim();if(a)return a}catch{}}}async function HB(r,e,t){let n=e?.includes("github.com"),o=e?.includes("gitlab.com");try{if(n)return zB(r,e,t);if(o)return}catch{}}function Bc(r){if(r.startsWith("git@")){let e=r.split(":");if(e.length===2){let t=e[1].replace(".git","").split("/");if(t.length===2){let n=t[0],o=t[1];return`${n}/${o}`}}}else if(r.startsWith("http")||r.startsWith("https")){let t=new URL(r).pathname.split("/").filter(Boolean);if(t.length>=2){let n=t[0],o=t[1].replace(".git","");return`${n}/${o}`}}}async function Oe(r,e){try{return(await e).trim()}catch(t){r.error({err:t},"Failed to run git command");return}}function GB(){if(process.env.GITHUB_ACTION)return"GithubActions";if(process.env.GITLAB_CI)return"GitlabCI";if(process.env.CIRCLECI)return"CircleCI";if(process.env.BUILDKITE)return"Buildkite";if(process.env["System.CollectionUri"]?.includes("azure"))return"AzureDevOps";if(process.env.PROJECT_ID&&process.env.BUILD_ID)return"GCPCloudBuild"}async function VB(r){let[e,t,n]=await Promise.all([Oe(r,Pe.show(["--no-patch","--format=%ci"])),Oe(r,Pe.show(["-s","--pretty=%B"])),Oe(r,Pe.show(["-s","--pretty=%an"]))]),o=process.env.GITHUB_SERVER_URL&&process.env.GITHUB_REPOSITORY?`${process.env.GITHUB_SERVER_URL}/${process.env.GITHUB_REPOSITORY}`:void 0;return{gitCommitSha:process.env.GITHUB_SHA,gitCommitShaShort:process.env.GITHUB_SHA?.slice(0,6),gitCommitTimestamp:e?new Date(e):void 0,gitBranchName:process.env.GITHUB_HEAD_REF||process.env.GITHUB_REF_NAME,gitOriginUrl:o,gitCommitMessage:t,gitCommitAuthorName:n,githubRepository:process.env.GITHUB_REPOSITORY,pipelineId:process.env.GITHUB_RUN_ID}}async function jB(r){let[e,t,n]=await Promise.all([Oe(r,Pe.listRemote(["--get-url","origin"])),Oe(r,Pe.show(["-s","--pretty=%B"])),Oe(r,Pe.show(["-s","--pretty=%an"]))]);return{gitCommitSha:process.env.CI_COMMIT_SHA,gitCommitShaShort:process.env.CI_COMMIT_SHORT_SHA,gitCommitTimestamp:process.env.CI_COMMIT_TIMESTAMP?new Date(process.env.CI_COMMIT_TIMESTAMP):void 0,gitBranchName:process.env.CI_COMMIT_BRANCH||process.env.CI_COMMIT_REF_NAME,gitOriginUrl:e,gitCommitMessage:t,gitCommitAuthorName:n,gitlabProjectPath:process.env.CI_PROJECT_PATH,pipelineId:`${process.env.CI_PIPELINE_ID}:${process.env.CI_JOB_ID}`}}async function WB(r){let[e,t,n,o]=await Promise.all([Oe(r,Pe.show(["--no-patch","--format=%ci"])),Oe(r,Pe.listRemote(["--get-url","origin"])),Oe(r,Pe.show(["-s","--pretty=%B"])),Oe(r,Pe.show(["-s","--pretty=%an"]))]),i=t?.includes("github.com"),a=t?.includes("gitlab.com"),l=t?Bc(t):void 0;return{gitCommitSha:process.env.CIRCLE_SHA1,gitCommitShaShort:process.env.CIRCLE_SHA1?.slice(0,6),gitCommitTimestamp:e?new Date(e):void 0,gitBranchName:process.env.CIRCLE_BRANCH,gitOriginUrl:process.env.CIRCLE_REPOSITORY_URL,gitCommitMessage:n,gitCommitAuthorName:o,githubRepository:i?l:void 0,gitlabProjectPath:a?l:void 0,pipelineId:process.env.CIRCLE_PIPELINE_ID}}async function $B(r){let[e,t,n]=await Promise.all([Oe(r,Pe.show(["--no-patch","--format=%ci"])),Oe(r,Pe.show(["-s","--pretty=%B"])),Oe(r,Pe.show(["-s","--pretty=%an"]))]),o=process.env.BUILDKITE_REPO,i=o?.includes("github.com"),a=o?.includes("gitlab.com"),l=o?Bc(o):void 0;return{gitCommitSha:process.env.BUILDKITE_COMMIT,gitCommitShaShort:process.env.BUILDKITE_COMMIT?.slice(0,6),gitCommitTimestamp:e?new Date(e):void 0,gitBranchName:process.env.BUILDKITE_BRANCH,gitOriginUrl:o,gitCommitMessage:t,gitCommitAuthorName:n,githubRepository:i?l:void 0,gitlabProjectPath:a?l:void 0,pipelineId:`${process.env.BUILDKITE_PIPELINE_ID}:${process.env.BUILDKITE_BUILD_ID}:${process.env.BUILDKITE_JOB_ID}`}}async function qB(r){let[e,t,n]=await Promise.all([Oe(r,Pe.show(["--no-patch","--format=%ci"])),Oe(r,Pe.show(["-s","--pretty=%B"])),Oe(r,Pe.show(["-s","--pretty=%an"]))]),o=process.env["Build.Repository.Uri"],i=o?.includes("github.com"),a=o?.includes("gitlab.com"),l=o?Bc(o):void 0;return{gitCommitSha:process.env["Build.SourceVersion"],gitCommitShaShort:process.env["Build.SourceVersion"]?.slice(0,6),gitCommitTimestamp:e?new Date(e):void 0,gitBranchName:process.env["Build.SourceBranchName"],gitOriginUrl:o,gitCommitMessage:t,gitCommitAuthorName:n,githubRepository:i?l:void 0,gitlabProjectPath:a?l:void 0,pipelineId:`${process.env["System.JobId"]}:${process.env["System.JobAttempt"]}`}}async function KB(r,e){let[t,n,o,i,a,l,c,s,u]=await Promise.all([Oe(r,Pe.revparse(["HEAD"])),Oe(r,Pe.revparse(["--short","HEAD"])),Oe(r,Pe.revparse(["--abbrev-ref","HEAD"])),Oe(r,Pe.listRemote(["--get-url","origin"])),Oe(r,Pe.show(["--no-patch","--format=%ci"])),Oe(r,Pe.show(["-s","--pretty=%B"])),Oe(r,Pe.show(["-s","--pretty=%an"])),e?Oe(r,Pe.raw(["merge-base","--fork-point",e])):Promise.resolve(void 0),BB(r)]),d=s?await Oe(r,Pe.show(["--no-patch","--format=%ci",s])):void 0,p=i?.includes("github.com"),m=i?.includes("gitlab.com"),g=i?Bc(i):void 0,h=u["user.email"]||void 0,f=u["user.name"]||void 0,b=u["user.username"]||void 0,E=await HB(r,i,u)??b??void 0;return{gitCommitSha:t,gitCommitShaShort:n,gitBranchName:o,gitOriginUrl:i,gitCommitTimestamp:a?new Date(a):void 0,gitCommitMessage:l,gitCommitAuthorName:c,gitLocalUsername:E,gitLocalEmail:h,gitLocalName:f,lastCommitOnMainSha:s,lastCommitOnMainTimestamp:d?new Date(d):void 0,githubRepository:p?g:void 0,gitlabProjectPath:m?g:void 0,pipelineId:void 0}}async function YB(){let r=process.env._HEAD_REPO_URL;return{gitCommitSha:process.env.COMMIT_SHA,gitCommitShaShort:process.env.COMMIT_SHA?.slice(0,6),gitBranchName:process.env.BRANCH_NAME,gitOriginUrl:r?process.env._HEAD_REPO_URL:void 0,gitCommitTimestamp:void 0,gitCommitMessage:void 0,gitCommitAuthorName:void 0,githubRepository:r?process.env.REPO_FULL_NAME:void 0,pipelineId:`${process.env.PROJECT_ID}:${process.env.BUILD_ID}`}}async function XB(r){let e=r.config.gitProtectedBranches??[];return r.config.gitMainBranch&&e.push(r.config.gitMainBranch),{gitMainBranch:r.config.gitMainBranch,gitProtectedBranches:e}}async function Xm(r,e){let t=GB();if(!t)return KB(r,e);switch(t){case"GithubActions":return VB(r);case"GitlabCI":return jB(r);case"CircleCI":return WB(r);case"Buildkite":return $B(r);case"AzureDevOps":return qB(r);case"GCPCloudBuild":return YB()}}async function JB(r,e,t,n){let o=n;if(!n.gitCommitSha)return o;if(n.gitMainBranch&&(!o.lastCommitOnMainSha||!o.lastCommitOnMainTimestamp))try{let i=await e.getMergeBaseCommitFromGitlab(t,n.gitMainBranch,n.gitCommitSha);o={...o,lastCommitOnMainSha:i.sha,lastCommitOnMainTimestamp:i.committer.date}}catch(i){r.warn({err:i},"Failed to get merge base commit from Gitlab")}if(!o.gitCommitTimestamp||!o.gitCommitAuthorName||!o.gitCommitMessage||!o.gitCommitAuthorName)try{let i=await e.getCommitFromGitlab(t,n.gitCommitSha);i&&(o={...o,gitCommitTimestamp:o.gitCommitTimestamp??i.committer.date,gitCommitAuthorName:o.gitCommitAuthorName??i.author.name,gitCommitMessage:o.gitCommitMessage??i.message})}catch(i){r.warn({err:i},"Failed to get commit from Gitlab")}if(n.gitBranchName&&n.gitBranchName===n.gitMainBranch&&!o.mergedGitBranchName)try{let i=await e.getMergedBranchFromGitlab(t,n.gitBranchName??"",n.gitCommitSha);i.mergedBranch&&(o={...o,mergedGitBranchName:i.mergedBranch})}catch(i){r.warn({err:i},"Failed to get merged branch from Gitlab")}return o}async function ZB(r,e,t,n,o){let i=o;if(!o.gitCommitSha)return i;if(o.gitMainBranch&&(!i.lastCommitOnMainSha||!i.lastCommitOnMainTimestamp))try{let a=await e.getMergeBaseCommitFromGithub(t,n,o.gitMainBranch,o.gitCommitSha);i={...i,lastCommitOnMainSha:a.sha,lastCommitOnMainTimestamp:a.committer.date}}catch(a){r.warn({err:a},"Failed to get merge base commit from GitHub")}if(!i.gitCommitTimestamp||!i.gitCommitAuthorName||!i.gitCommitMessage||!i.gitCommitAuthorName)try{let a=await e.getCommitFromGithub(t,n,o.gitCommitSha);a&&(i={...i,gitCommitTimestamp:i.gitCommitTimestamp??a.committer.date,gitCommitAuthorName:i.gitCommitAuthorName??a.author.name,gitCommitMessage:i.gitCommitMessage??a.message})}catch(a){r.warn({err:a},"Failed to get commit from GitHub")}if(o.gitBranchName&&o.gitBranchName===o.gitMainBranch&&!i.mergedGitBranchName)try{let a=await e.getMergedBranchFromGithub(t,n,o.gitBranchName??"",o.gitCommitSha);a.mergedBranch&&(i={...i,mergedGitBranchName:a.mergedBranch})}catch(a){r.warn({err:a},"Failed to get merged branch from GitHub")}return i}async function QB(r,e,t){try{if(t.githubRepository){let[n,o]=t.githubRepository.split("/");return await ZB(r,e,n,o,t)}else if(t.gitlabProjectPath)return await JB(r,e,t.gitlabProjectPath,t)}catch(n){r.warn({err:n},"Failed to get remote git metadata")}return t}async function zc(r,e,t){let n=await XB(t),o=await Xm(r,n.gitMainBranch),i={...n,...o};(!i.lastCommitOnMainSha||!i.lastCommitOnMainTimestamp)&&i.gitBranchName===n.gitMainBranch&&(i.lastCommitOnMainSha=i.gitCommitSha,i.lastCommitOnMainTimestamp=i.gitCommitTimestamp);let a=await QB(r,e,i);return{...n,...o,...a}}import{diff as xR}from"deep-object-diff";import lo from"fs";import{cloneDeep as ez}from"lodash-es";import Jm from"path";import{v4 as SIe}from"uuid";import Hc from"yaml";function MR({content:r,schemaVersion:e,momenticFiles:t,project:n,forceSaveOnNoDiffs:o}){let i=t.mobileModules[r.moduleId]?.fullFilePath;if(!i||!lo.existsSync(i))throw new Error(`Tried to update mobile module ${r.moduleId} that could not be found on disk`);let a=lo.readFileSync(i,"utf-8"),l=Hc.parse(a),c={...l,...r,schemaVersion:e},s=Yn({fileType:Me.MOBILE_MODULE,...ea.parse(c),steps:mr.array().parse(r.steps)}),u=xR(s,l);if(u&&Object.keys(u).length===0&&!o)return;let d=Hc.stringify(s);lo.writeFileSync(i,d,"utf-8"),ao(i,n.config)}function _R({moduleId:r,patch:e,momenticFiles:t,project:n,logger:o}){let i=t.mobileModules[r]?.fullFilePath;if(!i)throw new Error(`Tried to update mobile module ${r} that could not be found on disk`);let a=qa(i,o),l={...a,...e},c=Yn({fileType:Me.MOBILE_MODULE,...Ds.parse(l)}),s=xR(c,a);if(s&&Object.keys(s).length===0)return;let u=Hc.stringify(c);lo.writeFileSync(i,u,"utf-8");let d;if(e.name){let p=`${Qr(e.name)}.module.yaml`;if(d=Jm.join(Jm.dirname(i),p),lo.existsSync(d))throw new Error(`A conflicting file already exists at the following path: ${d}`);lo.renameSync(i,d)}ao(d||i,n.config)}function qa(r,e){let t=lo.readFileSync(r,"utf-8"),n=Hc.parse(t);try{return{...Ds.parse(n),name:Jm.basename(r,".module.yaml")}}catch(o){throw e.error({err:o,moduleFilePath:r,moduleContents:t},`${r} does not parse as a valid Momentic mobile module`),o}}async function Zm(r,e,t,n){let o=qa(r.fullFilePath,t),{resolvedSteps:i}=await Zl({rawSteps:o.steps,resolvedModuleCache:n||{},onFetchModule:async l=>{let c=e.mobileModules[l]?.fullFilePath;if(!c)throw new Error(`Could not find mobile module with id ${l}`);return qa(c,t)},logger:t,metadata:{id:o.moduleId,schemaVersion:o.schemaVersion}}),a={...o,name:r.name,steps:i};return n&&(n[r.id]=ez(a)),a}async function IR(r,e){let t={};return await Promise.all(Object.values(r.mobileModules).map(async n=>{await Zm(n,r,e,t)})),Array.from(Object.values(t))}import{randomUUID as tz}from"crypto";import co from"fs";import Qm from"path";import Gc from"yaml";function PR({name:r,description:e="",steps:t=[],settings:n={},folder:o}){let a=`${Qr(r)}.test.yaml`,l=Qm.join(o,a);if(co.existsSync(l))throw new Error(`A test named '${r}' already exists at path '${l}'. Choose a different name.`);let c={fileType:Me.MOBILE_TEST,id:tz(),description:e,schemaVersion:Lu,settings:n,steps:t},s=Gc.stringify(c);return co.writeFileSync(l,s,"utf-8"),{fullPath:l,testId:c.id}}function rz(r){if(!co.existsSync(r))throw new Error(`Test file not found: ${r}`);let e=co.readFileSync(r,"utf-8").replace(/\r\n|\r/g,`
|
|
4078
|
+
`),t=Gc.parse(e),n=Us.parse(t);if(n.fileType!==Me.MOBILE_TEST)throw new Error(`File is not a mobile test (fileType=${n.fileType}): ${r}`);return n}async function Vc(r,e,t){let n=rz(r),o;try{o=vr.parse(n)}catch(l){throw new Error(`Mobile test ${r} is missing metadata or has invalid metadata: ${l}`)}let{resolvedStepLists:i}=await nv({rawStepLists:{steps:n.steps,beforeSteps:void 0,afterSteps:void 0},logger:e,testMetadata:o,onFetchModule:async l=>{let c=t.mobileModules[l]?.fullFilePath;if(!c)throw new Error(`Mobile module ${l} not found`);return qa(c,e)}});return{...o,steps:i.steps}}async function OR({filePath:r,steps:e,settings:t,folder:n,project:o,momenticFiles:i}){let a=Qm.isAbsolute(r)?r:Qm.join(n,r);if(!co.existsSync(a))throw new Error(`Test file not found: ${a}`);let l=co.readFileSync(a,"utf-8").replace(/\r\n|\r/g,`
|
|
4079
|
+
`),c=Gc.parse(l),s=Us.parse(c);if(s.fileType!==Me.MOBILE_TEST)throw new Error(`File at '${a}' is not a mobile test (fileType=${s.fileType}).`);let u;e&&(u=await Zn({steps:e}));let d={...s,...u?.stepsToSave!==void 0?{steps:u.stepsToSave}:{},...t!==void 0?{settings:t}:{}},p=Gc.stringify(Us.parse(d));for(let m of u?.moduleUpdates??[])MR({content:m,schemaVersion:Lu,momenticFiles:i,project:o});co.writeFileSync(a,p,"utf-8"),ao(a,o.config)}import{randomUUID as nz}from"crypto";import wn from"fs";import pi from"path";var LR=new Set([".DS_Store","__MACOSX"]),NR={status:(r,e)=>{if(r.status===e.status)return r.status;if(r.status==="FAILED"||e.status==="FAILED")return"FAILED";if(r.status==="CANCELLED"||e.status==="CANCELLED")return"CANCELLED";if(r.status==="RETRYING"||e.status==="RETRYING")return"RETRYING";if(r.status==="RUNNING"||e.status==="RUNNING")return"RUNNING";if(r.status==="PENDING"||e.status==="PENDING")return"PENDING";throw new Error(`Invalid run status merge: ${r.status} and ${e.status}`)},startedAt:(r,e)=>r.startedAt<e.startedAt?r.startedAt:e.startedAt,updatedAt:(r,e)=>r.updatedAt>e.updatedAt?r.updatedAt:e.updatedAt,finishedAt:(r,e)=>!r.finishedAt||!e.finishedAt?new Date:r.finishedAt>e.finishedAt?r.finishedAt:e.finishedAt,gitCommitTimestamp:(r,e)=>{if(!(!r&&!e)){if(!r.gitCommitTimestamp||!e.gitCommitTimestamp||r.gitCommitTimestamp.getTime()!==e.gitCommitTimestamp.getTime())throw new Error(`Git commit timestamps must match to be merged: ${r.gitCommitTimestamp} and ${e.gitCommitTimestamp}`);return r.gitCommitTimestamp}},pipelineId:(r,e)=>r.pipelineId===e.pipelineId?r.pipelineId:!r.pipelineId&&e.pipelineId?e.pipelineId:!e.pipelineId&&r.pipelineId?r.pipelineId:r.startedAt<e.startedAt?e.pipelineId:r.pipelineId,labels:(r,e)=>{let t=new Set([...r.labels??[],...e.labels??[]]);return Array.from(t)}};function oz(r,e,t){if(NR[t]){let i=NR[t];return i(r,e)}let n=r[t],o=e[t];if(n!==o)throw new Error(`Metadata values for key "${t}" do not match: "${n}" vs "${o}"`);return n}var eg=class extends Error{constructor(e,t){let n=`${e} contains invalid Momentic results: ${t}. Please ensure that the path points to a folder containing only valid results. If you passed \`--output-dir test-results/results-1\` to the \`run\` command, your results path for merging should be \`test-results\`.`;super(n),this.name="InvalidMomenticResultsPathError"}};function DR(r,e){try{let t=pi.join(e,"metadata.json");return Js.parse(JSON.parse(wn.readFileSync(t,"utf-8")))}catch{throw new eg(r,e)}}function kR(r,e,t){let n=nz(),o=r.child({runGroupId:n});wn.rmSync(e,{recursive:!0,force:!0});let i=wn.readdirSync(t).filter(c=>!LR.has(c)).map(c=>pi.join(t,c));if(i.length===0)throw new Error(`No run groups found in results path: ${t}`);wn.mkdirSync(e,{recursive:!0});let a={...DR(t,i[0]),id:n};for(let c of i){let s=pi.join(c,"runs");if(!wn.existsSync(s))continue;let u=DR(t,c);o.info({oldRunGroupId:u.id},"Merging run groups");for(let p in u){if(p==="id")continue;let m=p;a[m]=oz(a,u,m)}let d=wn.readdirSync(s);for(let p of d){if(LR.has(p))continue;let m=pi.join(s,p),g=pi.join(e,"runs",p);wn.cpSync(m,g,{recursive:!0})}}let l=pi.join(e,"metadata.json");wn.writeFileSync(l,JSON.stringify(a,null,2))}import FR from"adm-zip";import ag from"fs";import{z as dz}from"zod";var D="v1",tg="mobile-cli",uo="0.1.0";var iz=9e4,az=3,sz=1500,lz=15e3,Sr=class extends Error{status;rawError;constructor(e,t,n,o={}){super(n,o),this.status=e,this.rawError=t}};async function cz(r){return r.text().then(e=>{try{return JSON.parse(e).error}catch{return e}})}var rg=class{baseUrl;logger;constructor(e){this.baseUrl=e.baseUrl,this.logger=e.logger}getHeaders(){let e={"Content-Type":"application/json"};return uo&&(e[Ks]=uo),tg&&(e[MS]=tg),e}async sendRequest(e,t){let{retries:n=az,requestTimeoutMs:o=iz,initialRetryDelayMs:i=sz,maxRetryDelayMs:a=lz}=t,l=n,c=n,s,u={path:e,baseUrl:this.baseUrl,method:t.method};for(;l>0;)try{return l--,await this.sendSingleRequestHelper(e,t,o)}catch(d){if(s=d,d instanceof Sr&&d.status>=400&&d.status<500)throw d;if(d instanceof Error&&d.name==="AbortError"&&(s=new dn),l===0)throw s;let p=c-l,m=Math.min(i*Math.pow(2,p-1),a);await new Promise(g=>setTimeout(g,m))}throw this.logger.warn({...u,err:s},"Got fatal error response from Momentic server"),s}async sendSingleRequestHelper(e,t,n){let o={path:e,baseUrl:this.baseUrl,method:t.method},i=new AbortController,a=setTimeout(()=>i.abort(),n),l=()=>i.abort();t.signal&&t.signal.addEventListener("abort",l,{once:!0});let c={...this.getHeaders(),...t.extraHeaders};try{let s=await fetch(`${this.baseUrl}${e}`,{method:t.method,body:t.body?JSON.stringify(t.body):void 0,headers:c,signal:i.signal});if(!s.ok){let d=await cz(s);throw new Sr(s.status,d,`Request to ${t.method} ${e} failed with status ${s.status}: ${d}`)}let u;if(s.status===204)u={};else{let d=await s.text();try{u=JSON.parse(d)}catch{u=d}}return this.logger&&t.logResponse===!0&&u&&this.logger.debug({result:u,status:s.status,...o},"Got response from Momentic server"),u}finally{clearTimeout(a),t.signal&&t.signal.removeEventListener("abort",l)}}},kr=class extends rg{apiKey;constructor(e){super(e),this.apiKey=e.apiKey}getHeaders(){return{...super.getHeaders(),Authorization:`Bearer ${this.apiKey}`}}};import{createAnthropic as uz}from"@ai-sdk/anthropic";var jc=({baseUrl:r,apiKey:e,sessionId:t,extraHeaders:n,loggerTags:o})=>i=>{let a={Authorization:`Bearer ${e}`,[Ks]:uo??"",...t&&{[IS]:t},...n||{}};return o&&(a[_S]=JSON.stringify(o)),uz({baseURL:`${r}/v1/llm/anthropic/${i}`,headers:a,apiKey:e})(i)};var po=class extends kr{agentConfig;constructor(e,t){super(t),this.agentConfig=e}getAgentConfig(){return this.agentConfig}async rankChunksWithAi(e,t){let n={...e,loggerTags:t.loggerTags},o=await this.sendRequest(`/${D}/web-agent/recommend-chunks-ai`,{method:"POST",body:n,signal:t.abortSignal});return Ef.parse(o)}async rankChunksWithRag(e,t){let n=await this.sendRequest(`/${D}/web-agent/recommend-chunks`,{method:"POST",body:{cliVersion:uo,...e},signal:t.abortSignal});return bf.parse(n)}async getScreenshotFromS3(e){let t=await this.sendRequest(`/${D}/s3/visual-diff-screenshot`,{method:"POST",body:{url:e}});return dz.string().parse(t)}async getElementLocation(e,t){let n={...e,disableCache:t.disableCache,loggerTags:t.loggerTags,useMemory:t.useMemory,agentConfigVersion:this.agentConfig?.locator},o=await this.sendRequest(`/${D}/web-agent/locate-element`,{method:"POST",body:n,signal:t.abortSignal});return NS.parse(o)}async getAssertionResult(e,t){let n={...e,disableCache:!!t.disableCache,useConsensus:!!t.useConsensus,attemptNumber:t.attemptNumber,loggerTags:t.loggerTags,useMemory:t.useMemory,agentConfigVersion:this.agentConfig?.assertion},o=await this.sendRequest(`/${D}/web-agent/assertion`,{method:"POST",body:n,signal:t.abortSignal});return Ed.parse(o)}async getLintStepResult(e,t){let n={...e,disableCache:!!t.disableCache,loggerTags:t.loggerTags},o=await this.sendRequest(`/${D}/web-agent/lint/step`,{method:"POST",body:n,signal:t.abortSignal});return LS.parse(o)}async getLintMcpCopilotMessageResult(e,t){let n={message:e.message,disableCache:!!t.disableCache,loggerTags:t.loggerTags},o=await this.sendRequest(`/${D}/web-agent/lint/mcp-copilot`,{method:"POST",body:n,signal:t.abortSignal});return OS.parse(o)}async getVisualAssertionResult(e,t){let n={...e,disableCache:!!t.disableCache,useConsensus:!!t.useConsensus,attemptNumber:t.attemptNumber,loggerTags:t.loggerTags,useMemory:t.useMemory,agentConfigVersion:this.agentConfig?.["visual-assertion"]},o=await this.sendRequest(`/${D}/web-agent/visual-assertion`,{method:"POST",body:n,signal:t.abortSignal});return Ed.parse(o)}async getAiActionCommand(e,t){let n=await this.sendRequest(`/${D}/web-agent/next-command-dynamic`,{method:"POST",body:{...e,disableCache:t.disableCache,loggerTags:t.loggerTags},signal:t.abortSignal});return PS.parse(n)}async getMultiturnAiActionCommand(e,t){return await this.sendRequest(`/${D}/web-agent/ai-action/next-command`,{method:"POST",body:{...e,disableCache:t.disableCache,loggerTags:t.loggerTags},signal:t.abortSignal})}async getMultiturnAiActionEvaluation(e,t){let n=await this.sendRequest(`/${D}/web-agent/ai-action/evaluate`,{method:"POST",body:{...e,disableCache:t.disableCache,loggerTags:t.loggerTags},signal:t.abortSignal});return Uu.parse(n)}async getReverseMappedDescription(e,t){let n=await this.sendRequest(`/${D}/web-agent/reverse-mapped-description`,{method:"POST",body:{...e,disableCache:t.disableCache,loggerTags:t.loggerTags},signal:t.abortSignal});return DS.parse(n)}async getTextExtraction(e,t){let n={...e,disableCache:t.disableCache,loggerTags:t.loggerTags,agentConfigVersion:this.agentConfig?.["text-extraction"]},o=await this.sendRequest(`/${D}/web-agent/text-extraction`,{method:"POST",body:n,signal:t.abortSignal});return Du.parse(o)}async getPageSummary(e,t){let n={...e,disableCache:t.disableCache,loggerTags:t.loggerTags},o=await this.sendRequest(`/${D}/web-agent/page-summary`,{method:"POST",body:n,signal:t.abortSignal});return Jh.parse(o)}async getTestResultClassification(e,t){let n=await this.sendRequest(`/${D}/web-agent/result-classification`,{method:"POST",body:{...e,loggerTags:t.loggerTags},signal:t.abortSignal});return vu.parse(n)}async getExtractedKeywords(e,t){let n=await this.sendRequest(`/${D}/web-agent/extract-keywords`,{method:"POST",body:e,signal:t.abortSignal});return Pf.parse(n)}async getAutohealingProposal(e,t){let n=await this.sendRequest(`/${D}/web-agent/autoheal-section`,{method:"POST",body:{...e,loggerTags:t.loggerTags},signal:t.abortSignal});return qh.parse(n)}async getFailureRecoveryProposal(e,t){let n=await this.sendRequest(`/${D}/web-agent/failure-recovery`,{method:"POST",body:{...e,loggerTags:t.loggerTags},signal:t.abortSignal});return Xh.parse(n)}async getFailureRecoveryPlan(e,t){let n=await this.sendRequest(`/${D}/web-agent/failure-recovery-plan`,{method:"POST",body:{...e,loggerTags:t.loggerTags},signal:t.abortSignal});return Yh.parse(n)}async getIframeRegex(e,t){let n=await this.sendRequest(`/${D}/web-agent/iframe-regex`,{method:"POST",body:e,signal:t.abortSignal});return Ng.parse(n)}getVercelAnthropicModelFactory({loggerTags:e}){return jc({baseUrl:this.baseUrl,apiKey:this.apiKey,loggerTags:e})}};import{z as ng}from"zod";var yr=class extends kr{constructor(e){super(e)}getAppUrl(){return this.baseUrl==="http://localhost:8000"?"http://localhost:3000":this.baseUrl.replace(/\/\/api/,"//app")}async getAuthInfo(){let e=await this.sendRequest(`/${D}/auth/check`,{method:"GET",retries:10,requestTimeoutMs:5e3});return KS.parse(e)}async bulkGetRunStatus(e){let t=await this.sendRequest(`/${D}/runs/status`,{method:"POST",body:e,retries:3,requestTimeoutMs:1e4});return jS.parse(t)}async getTestYAMLExport(e){let t=await this.sendRequest(`/${D}/tests/export`,{method:"POST",body:e,retries:3,requestTimeoutMs:3e4});return US.parse(t)}async updateStepCaches(e,t){await this.sendRequest(`/${D}/cache`,{method:"PATCH",body:e,extraHeaders:t,retries:3,requestTimeoutMs:1e4,initialRetryDelayMs:3e3})}async getStepCacheForTest(e,t){let n=await this.sendRequest(`/${D}/cache`,{method:"POST",body:e,extraHeaders:t,retries:10,requestTimeoutMs:3e4,initialRetryDelayMs:3e3});return BS.parse(n)}async updateMobileStepCaches(e,t){await this.sendRequest(`/${D}/mobile-cache`,{method:"PATCH",body:e,extraHeaders:t,retries:3,requestTimeoutMs:1e4,initialRetryDelayMs:3e3})}async getMobileStepCacheForTest(e,t){let n=await this.sendRequest(`/${D}/mobile-cache`,{method:"POST",body:e,extraHeaders:t,retries:10,logResponse:!0,requestTimeoutMs:3e4,initialRetryDelayMs:3e3});return zS.parse(n)}async queueTests(e){let t=await this.sendRequest(`/${D}/tests/queue`,{method:"POST",body:e,retries:3,requestTimeoutMs:1e4});return kS.parse(t)}async uploadScreenshot(e){let t=await this.sendRequest(`/${D}/screenshots`,{method:"POST",body:e,retries:3,requestTimeoutMs:5e3});return qS.parse(t)}async getAllEnvironments(){let e=await this.sendRequest(`/${D}/environments`,{method:"GET",retries:3,requestTimeoutMs:5e3});return YS.parse(e)}async acquireCacheLock(e,t){let n=await this.sendRequest(`/${D}/result-cache/lock`,{method:"POST",body:e,signal:t,retries:3,requestTimeoutMs:3e4});return uy.parse(n)}async releaseCacheLock(e){await this.sendRequest(`/${D}/result-cache/lock`,{method:"DELETE",body:{key:e},retries:3,requestTimeoutMs:5e3})}async deleteCacheResult(e){await this.sendRequest(`/${D}/result-cache/entry`,{method:"DELETE",body:e,retries:3,requestTimeoutMs:5e3})}async setCacheResult(e){await this.sendRequest(`/${D}/result-cache/entry`,{method:"PATCH",body:e,retries:3,requestTimeoutMs:5e3})}async getCacheResult(e){try{return await this.sendRequest(`/${D}/result-cache/entry`,{method:"POST",body:e,retries:3,requestTimeoutMs:5e3})}catch(t){if(t instanceof Error&&t.message.includes("404"))return null;throw t}}async queueSuiteRuns(e){let t=await this.sendRequest(`/${D}/suites/queue`,{method:"POST",body:e,retries:3,requestTimeoutMs:5e3});return XS.parse(t)}async bulkGetRunGroupStatus(e){let t={runGroupIds:e},n=await this.sendRequest(`/${D}/run-groups/status`,{method:"POST",body:t,retries:3,requestTimeoutMs:5e3});return hf.array().parse(n)}async uploadProposedSteps(e,t){try{await this.sendRequest(`/${D}/test-fragments/`,{method:"POST",body:e,retries:3,requestTimeoutMs:1e4})}catch(n){t.error({err:n},"Failed to upload proposed steps")}}async reportBillableEvents(e,t){try{await this.sendRequest(`/${D}/billing/events`,{method:"POST",body:t,retries:10,requestTimeoutMs:1e4})}catch(n){e.error({err:n},"Failed to report billable event")}}async fetchTestFragment(e){let t=await this.sendRequest(`/${D}/test-fragments/${e}`,{method:"GET",retries:3,requestTimeoutMs:1e4});return JS.parse(t)}async patchTestFragment(e,t){await this.sendRequest(`/${D}/test-fragments/${e}`,{method:"PATCH",body:t,retries:3,requestTimeoutMs:1e4})}async getPastTestResults(e,t){let n=await this.sendRequest(`/${D}/results/tests/${e}`,{method:"POST",body:t,retries:3,requestTimeoutMs:1e4});return ZS.parse(n)}async generateTestResultsUploadUrl(){let e=await this.sendRequest(`/${D}/results/uploads`,{method:"POST",retries:3,requestTimeoutMs:1e4});return QS.parse(e)}async startProcessingResultsUpload(e,t){let n=await this.sendRequest(`/${D}/results/uploads/${e}/process`,{method:"POST",body:t,retries:3,requestTimeoutMs:1e4});return ey.parse(n)}async fetchIconKnowledgeBase(e){try{let t=await this.sendRequest(`/${D}/knowledge-base/icons`,{method:"GET",retries:3,requestTimeoutMs:5e3});return my.parse(t)}catch(t){return e.error({err:t},"Failed to fetch icon knowledge base"),null}}async saveNewIcons(e,t){try{await this.sendRequest(`/${D}/knowledge-base/icons`,{method:"POST",body:e,retries:3,requestTimeoutMs:5e3})}catch(n){t.error({err:n},"Failed to save new icons to icon knowledge base")}}async getMergeBaseCommitFromGithub(e,t,n,o){let i=new URLSearchParams;i.set("base",n),i.set("head",o);let a=await this.sendRequest(`/${D}/git/github/${e}/${t}/merge-base-commit?${i.toString()}`,{method:"GET",retries:3,requestTimeoutMs:1e4});return la.parse(a)}async getCommitFromGithub(e,t,n){let o=await this.sendRequest(`/${D}/git/github/${e}/${t}/commits/${n}`,{method:"GET",retries:3,requestTimeoutMs:1e4});return la.parse(o)}async getMergedBranchFromGithub(e,t,n,o){let i=encodeURIComponent(n),a=await this.sendRequest(`/${D}/git/github/${e}/${t}/${i}/${o}/merged-branch`,{method:"GET",retries:3,requestTimeoutMs:1e4});return wd.parse(a)}async getMergeBaseCommitFromGitlab(e,t,n){let o=new URLSearchParams;o.set("base",t),o.set("head",n);let i=encodeURIComponent(e),a=await this.sendRequest(`/${D}/git/gitlab/${i}/merge-base-commit?${o.toString()}`,{method:"GET",retries:3,requestTimeoutMs:5e3});return la.parse(a)}async getCommitFromGitlab(e,t){let n=encodeURIComponent(e),o=await this.sendRequest(`/${D}/git/gitlab/${n}/commits/${t}`,{method:"GET",retries:3,requestTimeoutMs:1e4});return la.parse(o)}async getMergedBranchFromGitlab(e,t,n){let o=encodeURIComponent(t),i=encodeURIComponent(e),a=await this.sendRequest(`/${D}/git/gitlab/${i}/${o}/${n}/merged-branch`,{method:"GET",retries:3,requestTimeoutMs:1e4});return wd.parse(a)}async getAgentConfig(){let e=await this.sendRequest(`/${D}/web-agent/agent-config`,{method:"GET",retries:3,requestTimeoutMs:5e3});return ng.record(ng.string(),ng.string()).parse(e)}async getQuarantinedTests(){let e=await this.sendRequest(`/${D}/quarantine`,{method:"GET"});return ty.parse(e)}async quarantineTest(e,t,n){await this.sendRequest(`/${D}/quarantine`,{method:"POST",body:{testId:e.id,testName:e.name,reason:t,...n??{}},retries:3,requestTimeoutMs:1e4})}async unquarantineTest(e,t,n){await this.sendRequest(`/${D}/quarantine/${e.id}`,{method:"DELETE",body:{testName:e.name,reason:t,...n??{}},retries:3,requestTimeoutMs:1e4})}async createAndroidEmulator(e){let t=await this.sendRequest(`/${D}/limbar/android`,{method:"POST",retries:3,body:e,requestTimeoutMs:9e4,initialRetryDelayMs:5e3,maxRetryDelayMs:15e3});return ry.parse(t)}async extendAndroidEmulatorTtl(e){try{await this.sendRequest(`/${D}/limbar/android/${e}/keepalive`,{method:"POST",retries:3,requestTimeoutMs:15e3})}catch{}}async generateAndroidAssetUrls({channel:e,tag:t,md5:n}){let o={channel:e,tag:t,md5:n},i=await this.sendRequest(`/${D}/limbar/android/upload-url`,{method:"POST",retries:3,body:o,requestTimeoutMs:15e3,logResponse:!0});return ny.parse(i)}async deleteAndroidEmulator(e){await this.sendRequest(`/${D}/limbar/android/${e}`,{method:"DELETE",retries:3,requestTimeoutMs:3e4})}async getAndroidAssets(){let e=await this.sendRequest(`/${D}/limbar/assets`,{method:"GET",retries:3,requestTimeoutMs:1e4});return oy.parse(e)}async deleteAndroidAsset(e,t){await this.sendRequest(`/${D}/limbar/assets/${e}/${t}`,{method:"DELETE",retries:3,requestTimeoutMs:1e4})}};async function og(r){let e=process.versions.node,t=parseInt(e.split(".")[0]);(isNaN(t)||t<18)&&(A.error(`Node.js version 20 or higher is required to run the CLI. Detected: ${process.versions.node}.`),process.exit(1)),A.debug(`Identified node version ${e}`);let n=await r.client.getAuthInfo();return A.debug("Got auth info from API"),n}var Wc=class{apiClient;constructor(e){this.apiClient=e}async reportBillableEvents(e,t){await this.apiClient.reportBillableEvents(e,t)}};var mi=class extends kr{generator;constructor(e,t){super(e),this.generator=t}async runTemplateMatching(e,t={}){let n=await this.sendRequest(`/${D}/web-agent/template-matching`,{method:"POST",body:e,signal:t?.signal});return Dg.parse(n)}async constructIframeRegex(e,t={}){return this.generator.getIframeRegex(e,{abortSignal:t.signal})}};var gi=class{constructor(e,t){this.client=e;this.orgId=t}async acquireCacheLock(e,t){return this.client.acquireCacheLock(e,t)}async uploadScreenshot(e){return(await this.client.uploadScreenshot({screenshot:e.toString("base64")})).key}async releaseCacheLock(e){return this.client.releaseCacheLock(e)}async deleteCacheResult(e){return this.client.deleteCacheResult(e)}async setCacheResult(e){return this.client.setCacheResult(e)}async getCacheResult(e){return this.client.getCacheResult(e)}fetchIconKnowledgeBase(e){return this.client.fetchIconKnowledgeBase(e)}saveNewIcons(e,t){return this.client.saveNewIcons(e,t)}};import{Faker as pz,en as mz}from"@faker-js/faker";var hi="v1",fi=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 pz({locale:mz}),this.fakerInstance.seed(e.fakerSeed))}async sendAiGenerate(e){let t=typeof e=="string"?{input:e}:e;return this.httpClient.sendRequest(`/${hi}/tools/ai/generate`,{method:"POST",body:t}).catch(n=>{throw n instanceof Sr?new Error(n.rawError):new Error(`Failed to send AI generation: ${n.message}`)})}async sendSms(e){return this.httpClient.sendRequest(`/${hi}/tools/sms/send`,{method:"POST",body:e}).then(()=>{}).catch(t=>{throw t instanceof Sr?new Error(t.rawError):new Error(`Failed to send sms: ${t.message}`)})}async fetchLatestSms(e){return this.httpClient.sendRequest(`/${hi}/tools/sms/fetchLatest`,{method:"POST",body:e}).catch(t=>{throw t instanceof Sr?new Error(t.rawError):t})}async sendEmail(e){return this.httpClient.sendRequest(`/${hi}/tools/email/send`,{method:"POST",body:e}).then(()=>{}).catch(t=>{throw t instanceof Sr?new Error(t.rawError):new Error(`Failed to send email: ${t.message}`)})}async fetchAllEmails(e){return this.httpClient.sendRequest(`/${hi}/tools/email/fetchAll`,{method:"POST",body:e}).catch(t=>{throw t instanceof Sr?new Error(t.rawError):new Error(`Failed to fetch all emails: ${t.message}`)})}async fetchLatestEmail(e){return this.httpClient.sendRequest(`/${hi}/tools/email/fetchLatest`,{method:"POST",body:e}).catch(t=>{throw t instanceof Sr?new Error(t.rawError):new Error(`Failed to fetch latest emails: ${t.message}`)})}};function UR(r,e,t){return fetch(r,{method:"PUT",body:t,headers:{"Content-Type":e}})}var $c=class{constructor(e){this.client=e}async uploadResultsArchive(e,t){let{uploadUrl:n,id:o}=await this.client.generateTestResultsUploadUrl(),i=await UR(n,"application/zip",t);if(!i.ok)throw new Error(`Failed to upload test results: ${await i.text()}`);let{runGroupId:a}=await this.client.startProcessingResultsUpload(o,{runGroupId:e});return a}};var Si=class extends kr{constructor(e){super(e)}async getElementLocation(e,t){let n={...e,loggerTags:t.loggerTags},o=await this.sendRequest(`/${D}/mobile-agent/locate-element`,{method:"POST",body:n,signal:t.abortSignal});return Lf.parse(o)}async evaluateAssertion(e,t){let n={...e,loggerTags:t.loggerTags},o=await this.sendRequest(`/${D}/mobile-agent/assertion`,{method:"POST",body:n,signal:t.abortSignal});return kf.parse(o)}getVercelAnthropicModelFactory({loggerTags:e,sessionId:t}){return jc({baseUrl:this.baseUrl,apiKey:this.apiKey,sessionId:t,loggerTags:e})}};function qc({orgId:r,client:e,gitMetadata:t,alwaysSaveCache:n,noCache:o}){return o?new Xs:new ig(r,e,t,n)}var ig=class{constructor(e,t,n,o){this.orgId=e;this.client=t;let{gitBranchName:i,gitProtectedBranches:a}=n;this.cacheHeaders=Td(n),o?this.writeCaches=!0:i?this.writeCaches=!a.includes(i):this.writeCaches=!0}cacheHeaders;writeCaches;async saveEntries({entries:e,testId:t,logger:n}){if(!this.writeCaches){n.debug("Skipping cache storage because branch is protected");return}try{await this.client.updateMobileStepCaches({entries:e,testId:t},this.cacheHeaders)}catch(o){n.error({err:o},"Failed to save mobile step cache entries")}}async resolveEntries(e){let{steps:t}=e.stepLists,n=await this.client.getMobileStepCacheForTest({testId:e.testId},this.cacheHeaders);if(!this.writeCaches){e.logger.debug("Skipping mobile cache last used at update because branch is protected");return}for(let i of[t])i&&Lp({steps:i,stepCacheEntries:n,logger:e.logger});let{cachesToSave:o}=await Zn({steps:t,cacheCreationParams:{testId:e.testId,orgId:this.orgId}});this.client.updateMobileStepCaches({entries:o,testId:e.testId},this.cacheHeaders)}};import Kc from"path";function gz(r){let e=new FR,t=Kc.join(r,"metadata.json"),n=Js.parse(JSON.parse(ag.readFileSync(t,"utf-8")));e.addLocalFile(t);for(let o of ag.readdirSync(Kc.join(r,"runs"))){if(!o.endsWith(".zip"))continue;let i=o.replace(/\.zip$/,""),a=new FR(Kc.join(r,"runs",o));for(let l of a.getEntries())l.isDirectory||e.addFile(Kc.join("runs",i,l.entryName),l.getData())}return{runGroupId:n.id,buffer:e.toBuffer()}}async function Yc(r){let{client:e,consoleLogger:t,resultsPath:n}=r;if(!ag.existsSync(n)){t.warn("Results path does not exist, skipping upload.");return}let o=new $c(e);try{let{runGroupId:i,buffer:a}=gz(n),l=await o.uploadResultsArchive(i,a),c=`${e.getAppUrl()}/run-groups/${l}`;t.success(`Successfully uploaded test results. Once processed, your results can be found at ${c}`);return}catch(i){let a;i instanceof Error?a=i.message:typeof i=="string"?a=i:a="Unknown error",t.error(`Failed to upload test results: ${a}.`);return}}import hz from"adm-zip";import gt from"fs";import Ht from"path";var Ka=class r{constructor(e){this.filePath=e;gt.rmSync(this.filePath,{recursive:!0,force:!0}),gt.mkdirSync(this.filePath,{recursive:!0})}cd(e){return new r(Ht.join(this.filePath,e))}mkdir(e){gt.mkdirSync(Ht.join(this.filePath,e),{recursive:!0})}readFile(e){let t=Ht.join(this.filePath,e);if(gt.existsSync(t))return gt.readFileSync(t)}storeFile(e){let{name:t,contents:n}=e,o=Ht.join(this.filePath,t);try{gt.writeFileSync(o,n)}catch{}}createFileStream(e){let t=Ht.join(this.filePath,e);return gt.createWriteStream(t)}createRunArchive(e){return new sg(Ht.join(this.filePath,"runs"),e)}},sg=class{constructor(e,t){this.filePath=e;this.tempPath=Ht.join(e,`.${t}`),this.finalPath=Ht.join(e,`${t}.zip`),gt.rmSync(this.tempPath,{recursive:!0,force:!0}),gt.rmSync(this.finalPath,{recursive:!0,force:!0}),gt.mkdirSync(this.tempPath,{recursive:!0})}tempPath;finalPath;readFile(e){let t=Ht.join(this.tempPath,e);if(gt.existsSync(t))return gt.readFileSync(t)}mkdir(e){gt.mkdirSync(Ht.join(this.tempPath,e),{recursive:!0})}cd(e){return new Ka(Ht.join(this.tempPath,e))}storeFile(e){let{name:t,contents:n}=e,o=Ht.join(this.tempPath,t);gt.writeFileSync(o,n)}createFileStream(e){let t=Ht.join(this.tempPath,e);return gt.createWriteStream(t)}close(){let e=new hz;e.addLocalFolder(this.tempPath,void 0,n=>n!==".DS_Store");let t=e.toBuffer();gt.writeFileSync(this.finalPath,t),gt.rmSync(this.tempPath,{recursive:!0,force:!0})}};import nu from"fs";import JR from"body-parser";import Lz from"cors";import Nz from"dedent";import{Router as bz}from"express";import It from"fs";import{globSync as Ez}from"glob";import ut from"path";import cg from"fs";import fz from"path";var Sz=new sc(30,60*1e3),pg="https://api.momentic.ai",ug,zR=r=>{pg=r},mg=()=>pg,gg=()=>ug;var yi,dg,BR,HR=async r=>{if(ug&&yi&&BR)return yi;let e=new yr({baseUrl:pg,apiKey:r,logger:A});ug=e;try{let t=await e.getAuthInfo();return yi=t.orgId,dg=t.userId,BR=r,yi}catch(t){throw new Error(`Error checking API key against server: ${t}`)}},bi=()=>{if(!yi)throw new Error("Your organization ID is invalid.");return yi},Xc=()=>{if(!dg)throw new Error("Your user ID is invalid.");return dg};var hg,lg,GR=(r,e)=>{hg=r,lg?.abort(),lg=new AbortController;let t=lg.signal,n=[r.configFilePath];r.config.environments?.forEach(o=>{if(!o.envFile)return;let i=fz.resolve(r.rootDir,o.envFile);try{if(cg.lstatSync(i).isSymbolicLink())return;cg.existsSync(i)&&n.push(i)}catch(a){A.warn({err:a},`Failed to check if env file ${i} exists`)}});try{yz({filesToWatch:n,revalidator:e,signal:t,project:r})}catch(o){A.error({err:o},"Failed to start config file watchers")}},ct=()=>hg;function yz({filesToWatch:r,revalidator:e,signal:t,project:n}){r.forEach(o=>{cg.watch(o,{signal:t,persistent:!1,recursive:!1},async(i,a)=>{a&&(Sz.increment("setLocalProject")&&A.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.`),hg=await Promise.resolve(e(n.configFilePath)))})})}function at(r){return function(...e){let t=e[e.length-1],n=r(...e);Promise.resolve(n).catch(t)}}var Xa=bz();function Ya(r){let e=ct(),t=ut.dirname(e.configFilePath);return ut.join(t,...r)}function Tz(r){let e=ct(),t=ut.dirname(e.configFilePath),n=ut.relative(t,r);return n?n.split(ut.sep):[]}function vz(r,e){let t=It.statSync(r),n=Tz(r);return gd.parse({name:e,absolutePath:r,relativePath:n.join(ut.sep),pathSegments:n,isDirectory:t.isDirectory(),size:t.size,createdAt:t.birthtime,modifiedAt:t.mtime,accessedAt:t.atime})}Xa.post("/",at(async(r,e,t)=>{let n;try{n=fS.parse(r.body).pathSegments}catch(d){e.status(400).json({error:`Failed to parse folder read body: ${d}`});return}let o=Ya(n);if(!It.existsSync(o)){e.status(404).json({error:`Path not found: ${n.join(ut.sep)}`});return}if(!It.statSync(o).isDirectory()){e.status(400).json({error:`Path is not a directory: ${n.join(ut.sep)}`});return}let a=ct(),l=Array.from(a.config.exclude??[]).concat(Gs),s=Ez("*",{absolute:!1,cwd:o,ignore:l,dotRelative:!1,maxDepth:1,nodir:!1}).map(d=>{let p=ut.join(o,d);return vz(p,d)}),u={absolutePath:o,pathSegments:n,contents:s};e.status(200).json(u)}));Xa.put("/",at(async(r,e,t)=>{let n;try{n=SS.parse(r.body).pathSegments}catch(a){e.status(400).json({error:`Failed to parse folder create body: ${a}`});return}let o=Ya(n);if(It.existsSync(o)){e.status(200).json({success:!0,message:`Folder already exists: ${n.join(ut.sep)}`,pathSegments:n});return}It.mkdirSync(o,{recursive:!0});let i={success:!0,message:`Folder created: ${n.join(ut.sep)}`,pathSegments:n};e.status(201).json(i)}));Xa.patch("/",at(async(r,e,t)=>{let n,o;try{let s=yS.parse(r.body);n=s.pathSegments,o=s.newPathSegments}catch(s){e.status(400).json({error:`Failed to parse folder update body: ${s}`});return}let i=Ya(n),a=Ya(o);if(!It.existsSync(i)){e.status(400).json({error:`Folder not found: ${n.join(ut.sep)}`});return}if(It.existsSync(a)){e.status(400).json({error:`Destination already exists: ${o.join(ut.sep)}`});return}let l=ut.dirname(a);It.existsSync(l)||It.mkdirSync(l,{recursive:!0}),It.renameSync(i,a);let c={success:!0,message:`Folder moved from ${n.join(ut.sep)} to ${o.join(ut.sep)}`,pathSegments:o};e.status(200).json(c)}));Xa.delete("/",at(async(r,e,t)=>{let n,o=!0;try{let c=bS.parse(r.body);n=c.pathSegments,o=c.recursive??!0}catch(c){e.status(400).json({error:`Failed to parse folder delete body: ${c}`});return}let i=Ya(n);if(!It.existsSync(i)){e.status(200).json({success:!0,message:`Folder not found: ${n.join(ut.sep)}`,pathSegments:n});return}if(!It.statSync(i).isDirectory()){e.status(400).json({error:`Path is not a directory: ${n.join(ut.sep)}`});return}if(o)It.rmSync(i,{recursive:!0,force:!0});else{if(It.readdirSync(i).length>0){e.status(409).json({error:`Cannot delete non-empty directory without recursive flag: ${n.join("/")}`});return}It.rmdirSync(i)}let l={success:!0,message:`Folder deleted: ${n.join("/")}`,pathSegments:n};e.status(200).json(l)}));var fg=Xa;import Dz from"events";import ZR,{Router as kz}from"express";import Uz from"http";import Fz from"path";var Jc=class{sessions=new Map;registerSession(e,t){this.sessions.set(e,t)}getSession(e){return this.sessions.get(e)}async removeSession(e,t){let n=this.sessions.get(e);if(n)try{await n.cleanup?.(),t.info({sessionId:e,emulatorName:n.emulatorName},"Android emulator cleaned up")}catch(o){t.error({err:o},"Error during Android session cleanup")}finally{this.sessions.delete(e)}}async removeAllSessions(e){let t=Array.from(this.sessions.keys());await Promise.all(t.map(n=>this.removeSession(n,e)))}};var VR=new Jc;import{Router as Rz}from"express";import{existsSync as Cz}from"fs";import xz from"path";import{hostname as Az}from"os";var wz="0.1.0",Pt=Zs({app:"mobile-desktop-server",hostname:Az(),disableConsoleLogs:!0}).child({cliVersion:wz});(async()=>{try{let r=await Xm(Pt);r.gitBranchName&&Pt.addBinding("branch",r.gitBranchName)}catch{}})();var Sg=Rz();Sg.get("/",at(async(r,e)=>{let t=gg();if(!t){e.status(500).json({message:"API client not initialized"});return}let n=await t.getAndroidAssets();e.status(200).json(n)}));Sg.post("/upload-url",at(async(r,e)=>{let t;try{t=wS.parse(r.body)}catch(i){e.status(400).json({error:`Invalid request body: ${i}`});return}let n=gg();if(!n){e.status(500).json({error:"API client not initialized"});return}let o=xz.resolve(t.filePath);if(!Cz(o)){e.status(400).json({error:`File not found: ${o}`});return}await $l({tag:t.tag,channel:t.channel,filePath:o,apiClient:n,logger:Pt}),e.sendStatus(204)}));var jR=Sg;import{Router as Mz}from"express";var WR=Mz();WR.get("/",at(async(r,e)=>{let t=ct(),n=await fr(t),o=new Set;n?.tests&&Object.values(n.tests).forEach(c=>{c.labels?.forEach(s=>o.add(s))});let i=Array.from(o).sort(),a=Object.values(n.mobileTests),l={labels:i,modules:[],tests:a};e.status(200).json(l)}));var $R=WR;import{Router as _z}from"express";var qR=_z();qR.get("/",(r,e)=>{e.status(200).json({userId:Xc(),orgId:bi()})});var KR=qR;import{Router as Iz}from"express";var Zc=Iz();async function Pz(r){return(await IR(r,Pt)).map(n=>{let o=r.mobileModules[n.moduleId];if(!o){A.warn(`Found a dangling mobile module with ID ${n.moduleId} that could not be found on disk.`);return}return{...o,content:n}}).filter(n=>n!==void 0)}Zc.get("/",at(async(r,e)=>{let t=ct(),n=await fr(t),o=await Pz(n);e.status(200).json(o)}));Zc.get("/:moduleId",at(async(r,e)=>{if(!r.params.moduleId){e.status(400).json({error:"Missing moduleId in url path."});return}let t=await fr(ct()),n=t.mobileModules[r.params.moduleId];if(!n){e.status(404).json({error:"Mobile module not found."});return}try{let o=await Zm(n,t,A);e.json(o)}catch(o){e.status(400).json({err:o})}}));Zc.patch("/:moduleId/metadata",at(async(r,e)=>{if(!r.params.moduleId){e.status(400).json({error:"Missing moduleId in url path."});return}let t;try{t=RS.parse(r.body)}catch(i){e.status(400).json({error:`Invalid request body: ${i}`});return}let n=ct(),o=await fr(n);_R({moduleId:r.params.moduleId,patch:t,momenticFiles:o,logger:A,project:n}),e.status(201).json({message:"ok"})}));var YR=Zc;import{Router as Oz}from"express";import yg from"path";var Qc=Oz();Qc.patch("/:testPath",at(async(r,e)=>{let t=r.params.testPath;if(!t){e.status(400).json({error:"Missing testPath in path"});return}let n;try{n=AS.parse(r.body)}catch(c){e.status(400).json({error:`Invalid request body: ${c}`});return}if(n.steps===void 0&&n.settings===void 0){e.status(400).json({error:"At least one of steps or settings is required"});return}let o=ct(),i=t.endsWith(".test.yaml")?t:`${t}.test.yaml`,a=await fr(o);await OR({filePath:i,steps:n.steps,settings:n.settings,folder:o.rootDir,project:o,momenticFiles:a});let l={message:"ok"};e.status(200).json(l)}));Qc.post("/",at((r,e)=>{let t;try{t=vS.parse(r.body)}catch(g){e.status(400).json({error:`Invalid request body: ${g}`});return}let{name:n,description:o,settings:i,pathSegments:a}=t;if(!n||typeof n!="string"){e.status(400).json({error:"Missing or invalid 'name' in body"});return}try{Nu(n)}catch(g){e.status(400).json({error:g.message});return}let l=ct(),c=yg.join(l.rootDir,...a),{fullPath:s,testId:u}=PR({name:n,description:o,steps:[],settings:i,folder:c}),d=yg.basename(s),p=yg.relative(l.rootDir,s),m={id:u,fileName:d,fullPath:s,relativeFilePath:p};e.status(201).json(m)}));Qc.get("/:fileName",at(async(r,e)=>{let t=r.params.fileName;if(!t){e.status(400).json({error:"Missing fileName in path"});return}let n=t.endsWith(".test.yaml")?t:`${t}.test.yaml`,o=ct(),i=await fr(o),l=await Vc(n,Pt,i);e.status(200).json(l)}));var XR=Qc;var eu=class extends gi{constructor(t,n){super(t,n);this.client=t;this.orgId=n}async fetchEnvironment(t,n){let o=ct();return Fc(t,o,A)}};var QR="10mb";async function eC(r){let{serverPort:e,apiKey:t,momenticServerUrl:n,staticDir:o,initialProject:i,driverLogLevel:a,alwaysSaveCache:l,noCache:c}=r;n&&zR(n),await HR(t);let s=bi(),u=Xc(),d=r.logger.child({orgId:s,userId:u});GR(i,T=>$a({configFilePath:T}));let p=ZR();p.use(Lz()),p.use(JR.json({limit:QR})),p.use(JR.urlencoded({extended:!1,limit:QR}));let m=kz();if(m.use("/folders",fg),m.use("/entities",$R),m.use("/identify",KR),m.use("/mobile-tests",XR),m.use("/mobile-modules",YR),m.use("/assets",jR),p.use("/api",m),p.use((T,_,M)=>{A.debug({url:T.url,path:T.path,query:T.query,method:T.method,body:T.body,headers:T.rawHeaders,client:T.ip},"Incoming request on mobile-desktop-server"),_.on("close",()=>{_.statusCode>=400&&(A.error({url:T.url,method:T.method,statusCode:_.statusCode},"Request completed in error on mobile-desktop-server"),Pt.error({url:T.url,method:T.method,statusCode:_.statusCode},"Request completed in error on mobile-desktop-server"))}),M()}),p.use((T,_,M,z)=>{if(T instanceof Error&&T.message.includes("BadRequestError: request aborted")){M.status(400).send("Client disconnected");return}A.error({stack:T.stack,msg:T.message,err:T,url:_.url,method:_.method},"Unhandled exception leading to 500 on mobile-desktop-server"),Pt.error({stack:T.stack,msg:T.message,err:T,url:_.url,method:_.method},"Unhandled exception leading to 500 on mobile-desktop-server"),M.status(500).send(`Internal Server Error: ${T.message}`)}),o){let T=ZR.static(o,{setHeaders:_=>{_.setHeader("Cache-Control","no-cache")},redirect:!1});p.use(T),p.use("*",(_,M)=>{M.sendFile(Fz.join(o,"index.html"))})}let g=Uz.createServer(p),h=`http://localhost:${e}`;await new Promise(T=>{try{g.listen(e,()=>{d.info(`Mobile desktop server is running at ${h}`),T()})}catch(_){_.message.includes("EADDRINUSE")?Bz(e):A.error(`An unexpected error occurred while starting the server: ${_.message}`),process.exit(1)}});let b={type:"API_KEY",baseUrl:mg(),apiKey:t,logger:d},E=new yr(b),v=ct(),{dispose:R}=lR({baseServer:g,logger:d,authorization:b,globalStateManager:VR,getOrgId:()=>bi(),androidDriverFactory:async({socket:T,logger:_,creationOpts:M})=>{let z=Math.floor(Math.random()*1e4)+4e4,Y=await Uc(z,"appium");return Wl({logger:_,driverLogLevel:a,apiClient:E,creationOpts:M,socket:T,appiumPort:Y,orgId:bi(),onStatusUpdate:Ee=>{T.emit("connectionStatusUpdate",{message:Ee})}})},mobileGeneratorFactory:async T=>new Si({baseUrl:mg(),apiKey:t,logger:d}),browserGeneratorFactory:async T=>new po(v.config.ai?.agentConfig,b),browserEnricherFactory:async T=>new mi(b,new po(v.config.ai?.agentConfig,b)),storageFactory:async T=>new eu(E,T),cacheStorageFactory:async T=>{let _=await zc(d,E,v);return qc({orgId:T,client:E,gitMetadata:_,noCache:c,alwaysSaveCache:l})},localToolsFactory:async()=>new fi({httpClient:E,fakerSeed:void 0}),keepSessionAlive:T=>E.extendAndroidEmulatorTtl(T),settingsFactory:async()=>({emulator:v.config.emulator})});process.once("SIGUSR2",async()=>{return;try{await R(),await vt.flush()}catch(T){A.error({err:T},"Error during session dispose on SIGUSR2")}try{g.close(()=>{process.kill(process.pid,"SIGUSR2")})}catch{process.kill(process.pid,"SIGUSR2")}}),process.once("SIGTERM",async()=>{A.info("SIGTERM in Momentic mobile app received");try{await R(),await vt.flush()}finally{g.close(()=>process.exit(0))}}),process.once("SIGINT",async()=>{A.info("SIGINT in Momentic mobile app received");try{await R(),await vt.flush()}finally{g.close(()=>process.exit(0))}})}Dz.setMaxListeners(25);process.on("warning",r=>{Pt.warn({err:r},`Node warning received on mobile-desktop-server: ${r.message}`)});process.on("uncaughtException",r=>{Pt.error({err:r},"Uncaught exception on mobile-desktop-server"),A.error(`Oh no! The Momentic mobile desktop app encountered a fatal error \u{1F61E}. Error logs: ${r.message}`)});process.on("unhandledRejection",r=>{Pt.error({reason:`${r}`,stack:r?.stack},"Uncaught exception on mobile-desktop-server (promise rejection)"),A.error(`Oh no! The Momentic mobile desktop app encountered an asynchronous error \u{1F61E}. Error logs: ${r}`)});function Bz(r){A.error(Nz`Port ${r} is already in use by another process. Please close the other process and try again.
|
|
4041
4080
|
Using Bash on MacOS or Linux:
|
|
4042
4081
|
lsof -t -i :58888 | xargs kill -9
|
|
4043
4082
|
|
|
4044
4083
|
Using Command Prompt on Windows:
|
|
4045
4084
|
for /f "tokens=5" %a in ('netstat -ano ^| findstr :58888') do taskkill /PID %a /F
|
|
4046
|
-
`)}import
|
|
4085
|
+
`)}import r1 from"open";import ou from"path";import{fileURLToPath as n1}from"url";import{InvalidArgumentError as bg,Option as Ot}from"@commander-js/extra-typings";import{z as zz}from"zod";var tC=58890;function Hz(r){let e=parseInt(r,10);if(isNaN(e))throw new bg("Not a number.");return e}var Ja=new Ot("--api-key <key>","Momentic API key").env("MOMENTIC_API_KEY").argParser(r=>{if(!r)throw new bg("API key is required.");return r}).makeOptionMandatory(),Eg=new Ot("-c, --config <configPath>","Absolute or relative path to a Momentic configuration file."),Za=new Ot("--server <server>","Momentic server to use.").env("MOMENTIC_SERVER").default("https://api.momentic.ai").argParser(r=>{try{return zz.string().url().parse(r),r}catch{throw new bg("Not a valid URL.")}}),Tg=new Ot("-y, --yes","Skip all confirmation prompts.").env("CI"),vg=new Ot("--save-cache","Always save updated step caches after successful test runs. By default, caches are not saved when running on protected branches, which are specified in your momentic.config.yaml.").env("CI"),Ag=new Ot("--disable-cache","Disable using step caches completely. Using this option may lead to non-deterministic behavior and significantly longer runtimes."),wg=new Ot("--tag <tag>","Tag identifier for the asset."),rC=new Ot("--channel <channel>","Channel name for the asset."),nC=new Ot("--channel <channel>","Channel name for the asset.").makeOptionMandatory(),oC=new Ot("--env <env>","Environment to run all tests in (overrides test-level configuration)."),iC=new Ot("-p, --parallel <parallel>","The number of tests to run in parallel. Defaults to 1.").argParser(Hz),Rg=new Ot("--output-dir <outputDir>","Output directory to store run artifacts such as screenshots, results, and logs."),aC=new Ot("--upload-results","Upload test results to Momentic Cloud.").default(!1),Cg=new Ot("--log-level <logLevel>","Log level for Momentic and dependent services.").choices(["error","warn","info","debug"]),sC=new Ot("--ignore-quarantine","Run all tests even if they are quarantined. This is useful for validating that quarantined tests are fixed before moving them out of quarantine.").implies({skipQuarantined:!1,onlyQuarantined:!1});import{randomUUID as Xz}from"crypto";import{existsSync as Jz}from"fs";import xg from"fs";import Qa from"path";import{cwd as Vz}from"process";async function lC({tests:r,momenticFiles:e,project:t,yes:n,include:o,exclude:i,logger:a,quarantinedTestReasons:l}){let c=new Set;if(r&&r.length>0){let u=r.some(p=>xg.existsSync(p)),d=Vz();u?(d!==t.rootDir&&a.warn(`The current working directory ('${d}') is different from the project root directory ('${t.rootDir}'). All test path arguments will be resolved relative to the current working directory and only those tests matched by the project inclusion configuration will be ran. To avoid confusion, Momentic strongly recommends running the CLI from the project root directory or using substring filters rather than file paths.`),a.info(`Reading tests from the following local file paths:
|
|
4047
4086
|
- ${r.join(`
|
|
4048
4087
|
- `)}
|
|
4049
|
-
`),r.forEach(p=>{if(!
|
|
4088
|
+
`),r.forEach(p=>{if(!xg.existsSync(p))throw new Error(`Path '${p}' does not exist.`);let m,g;try{m=xg.statSync(p),g=m.isDirectory()}catch(f){a.warn({err:f},`Skipping path ${p} because it cannot be read`);return}let h=Qa.resolve(p);Object.values(e.mobileTests).filter(f=>g?f.fullFilePath.startsWith(h):f.fullFilePath===h).forEach(f=>{c.add(f.fullFilePath)})})):(a.info("The arguments provided don't appear to be valid paths. Treating them as substrings instead... "),Object.values(e.mobileTests).forEach(p=>{r.some(m=>p.relativePath.includes(m))&&c.add(p.fullFilePath)}))}else{!n&&!await Dc("No test paths or substrings were provided. Do you want to run all tests?")&&(a.error("Cancelled by user."),process.exit(1));let u=Object.values(e.mobileTests);a.info(`Reading all ${u.length} mobile tests in the project from local disk.`),u.forEach(d=>{c.add(d.fullFilePath)})}for(let u of Array.from(c)){let d=Qa.relative(t.rootDir,u);o&&!o.some(p=>new RegExp(p).test(d))&&c.delete(u),i&&i.some(p=>new RegExp(p).test(d))&&c.delete(u)}return(await Promise.all(Array.from(c).map(async u=>{try{let d=Qa.relative(t.rootDir,u),p=await Vc(u,a,e),m=Qa.basename(u,Qa.extname(u));return{id:p.id,name:m,description:p.description,schemaVersion:p.schemaVersion,settings:p.settings,steps:p.steps,fullFilePath:u,relativeFilePath:d,quarantined:!!l[p.id],quarantinedReason:l[p.id]}}catch(d){a.error(`Failed to read and resolve mobile test at '${u}': ${d}`),process.exit(1)}}))).filter(u=>!!u)}import{cloneDeep as jz}from"lodash-es";async function cC(r){let{inputs:e,fixtures:t,metadata:n,options:o}=r,{tracer:i,logger:a}=t,{runId:l}=n,{testDefinition:c,runSigIntHandlers:s}=e,u=new Date,d=await i.startRun({logger:a,testId:c.id,testName:c.name,runId:l,testDescription:c.description,schemaVersion:c.schemaVersion,originalSteps:{steps:jz(c.steps),beforeSteps:void 0,afterSteps:void 0},quarantined:c.quarantined,quarantinedReason:c.quarantinedReason}),p=a.child(d.loggerBindings||{}),m=1+(c.settings?.retries??1);try{for(let g=0;g<m;g++){let h=new Date,f=await Wz({runTracer:d,testDefinition:c,metadata:n,constants:{attemptNumber:g,totalAttempts:m},fixtures:{...t,logger:p},inputs:e,options:o}),b=new Date;if(f.status!=="FAILED")return await d.finish({logger:a,...f,finishedAt:b}),{...f,startedAt:u,lastAttemptStartedAt:h,finishedAt:b,attempts:g+1,testMetadata:c,steps:c.steps,filePath:c.relativeFilePath,quarantined:c.quarantined,quarantinedReason:c.quarantinedReason};if(g!==m-1){a.warn("Retrying failed mobile run");continue}return a.error("Mobile test failed after all exhausting attempts"),await d.finish({logger:a,...f,finishedAt:b}),{...f,startedAt:u,lastAttemptStartedAt:h,finishedAt:b,attempts:g+1,testMetadata:c,steps:c.steps,filePath:c.relativeFilePath,quarantined:c.quarantined,quarantinedReason:c.quarantinedReason}}throw new Error("This code should not be reachable")}finally{s?.pop()}}async function Wz(r){let{runTracer:e,testDefinition:t,metadata:n,constants:o,fixtures:i,inputs:a,options:l}=r,{attemptNumber:c,totalAttempts:s}=o,{orgId:u,gitMetadata:d}=n,{apiClient:p,logger:m,usageTracker:g}=i,{logUpdate:h,channel:f,tag:b,project:E,envOverride:v}=a,{alwaysSaveCache:R,noCache:T,logLevel:_}=l;c!==0&&h("RETRY",`attempt ${c}/${s}`);let M={...a.project.config.emulator,...t.settings?.emulator},z=qc({orgId:u,client:p,gitMetadata:d,alwaysSaveCache:R,noCache:T}),Y=new gi(p,u),Ee=new Si(p),oe={type:"API_KEY",baseUrl:p.baseUrl,apiKey:p.apiKey,logger:m},ge=new po(E.config.ai?.agentConfig,oe),et=new mi(oe,ge),j=new fi({httpClient:p,fakerSeed:void 0}),U=Math.floor(Math.random()*1e4)+4e4,ne=await Uc(U,"appium"),Ne=await Wl({apiClient:p,logger:m,driverLogLevel:_,creationOpts:{apkToInstall:f?{channel:f,tag:b}:void 0,region:M.region},onStatusUpdate:ts=>{m.debug({status:ts},"Limbar emulator status update")},appiumPort:ne,orgId:u}),he=await e.startAttempt({emulatorName:Ne.emulatorName}),dt=m.child(he.loggerBindings||{}),Gt=await ql({driver:Ne.driver,onLogs:ts=>{he.appendLogs(ts)}}),Ae=v||t.settings?.defaultEnv,tt;Ae&&(tt=Fc(Ae,E,dt).variables);let Vt=new Po({variablesFromEnvironment:tt??{},envName:Ae,testName:t.name}),mo=await si.init({driver:Ne.driver,generator:Ee,logger:dt,orgId:u,adbPort:Ne.adbTunnelPort,options:{emulator:M},fixtures:{storage:Y,browserEnricher:et,browserGenerator:ge,localCodeEvalTools:j,testContext:Vt}}),Cn;try{Cn=await Oc({containerName:"mobile-test",fixtures:{controller:mo,logger:dt,cacheStorage:z,usageTracker:g},inputs:{steps:t.steps,orgId:u,testMetadata:t},tracer:he,callbacks:{}})}finally{await Gt(),await Ne.cleanup()}return await he.finish({logger:dt,results:Cn.results,status:Cn.status}),Cn}import{randomUUID as $z}from"crypto";import{debounce as qz}from"ts-debounce";var es="0.1.0";var tu="assets";function Kz(r){switch(r){case"PASSED":return"SUCCESS";case"FAILED":return"FAILED";case"CANCELLED":return"CANCELLED";case"RUNNING":case"PENDING":case"RETRYING":case"WAITING_FOR_USER":return"RUNNING"}}function Yz(r){switch(r){case"SUCCESS":return"PASSED";case"FAILED":return"FAILED";case"CANCELLED":return"CANCELLED";case"RUNNING":return"RUNNING";case"IDLE":return"PENDING"}}var Mg=class{constructor(e,t,n,o){this.keepalive=e;this.testId=t;this.testName=n;this.diskStorage=o;this.interactionTracer=new oo,$r.initializeRootTracerContext(this.interactionTracer)}children=[];finished=!1;interactionTracer;getParentStepIdChain(){return[]}attachBeforeScreenshot(e){let{snapshotId:t,screenshot:n}=e;this.diskStorage.storeFile({name:`${tu}/${t}.jpeg`,contents:n})}attachAfterScreenshot(e){let{snapshotId:t,screenshot:n}=e;this.diskStorage.storeFile({name:`${tu}/${t}.jpeg`,contents:n})}async finishInternal(e){this.finished||(this.finished=!0,this.interactionTracer.finish(),await Promise.all(this.children.map(t=>t.finish({status:Yz(e.status),finishedAt:e.finishedAt}))))}async finish(e){return await this.finishInternal({status:e.result.status,finishedAt:new Date(e.result.endTime)}),{trace:this.interactionTracer.getRootSpan()}}async startSubSteps(){let e=new Ei(this.keepalive,this.testId,this.testName,this.diskStorage);return this.children.push(e),e}},Ei=class{constructor(e,t,n,o){this.keepalive=e;this.testId=t;this.testName=n;this.diskStorage=o}children=[];finished=!1;async getScreenshot(e,t){return this.diskStorage.readFile(`${tu}/${t}.jpeg`)}getParentStepIdChain(){return[]}async startStep(e){this.keepalive();let t=new Mg(this.keepalive,this.testId,this.testName,this.diskStorage);return this.children.push(t),t}async finish(e){this.finished||(this.finished=!0,await Promise.all(this.children.map(t=>t.finishInternal({status:Kz(e.status),finishedAt:e.finishedAt}))))}},_g=class{constructor(e,t,n,o,i,a){this.keepalive=e;this.testId=t;this.testName=n;this.runAttemptId=o;this.metadata=i;this.diskStorage=a;this.diskStorage.mkdir("assets"),this.logStream=this.diskStorage.createFileStream("assets/logs.logcat")}finished=!1;children=[];logStream;get loggerBindings(){return{runAttemptId:this.runAttemptId}}appendLogs(e){let t=e.join(`
|
|
4050
4089
|
`);this.logStream.write(t+`
|
|
4051
|
-
`)}async finish(e){if(this.finished)return;this.finished=!0;let{logger:t,status:n,results:o,beforeResults:i,afterResults:a}=e,s={...this.metadata,status:n,finishedAt:new Date,results:kc(o,t),beforeResults:i?kc(i,t):void 0,afterResults:a?kc(a,t):void 0};await Promise.all(this.children.map(c=>c.finish({status:s.status,finishedAt:s.finishedAt})));try{this.logStream.end()}catch{}this.diskStorage.storeFile({name:"metadata.json",contents:JSON.stringify(s,null,2)})}async startBeforeStepList(){let e=new Oi(this.keepalive,this.testId,this.testName,this.diskStorage);return this.children.push(e),e}async startMainStepList(){let e=new Oi(this.keepalive,this.testId,this.testName,this.diskStorage);return this.children.push(e),e}async startAfterStepList(){let e=new Oi(this.keepalive,this.testId,this.testName,this.diskStorage);return this.children.push(e),e}async getScreenshot(e,t){return this.diskStorage.readFile(`${fu}/${t}.jpeg`)}},th=class{constructor(e,t,n,o,i,a){this.client=e;this.testId=t;this.testName=n;this.runId=o;this.metadata=i;this.diskStorage=a}children=[];finished=!1;get loggerBindings(){return{runId:this.runId}}async finish(e){if(this.finished)return;this.finished=!0;let t={...this.metadata,finishedAt:e.finishedAt||new Date,status:e.status,failureDetails:e.failureDetails,failureReason:e.failureReason,flake:e.isFlake||!1,failureRecoveryDetails:e.failureRecoveryDetails};await Promise.all(this.children.map(n=>n.finish({logger:e.logger,status:t.status,results:[],beforeResults:[],afterResults:[]}))),this.diskStorage.storeFile({name:"metadata.json",contents:JSON.stringify(t,null,2)}),this.diskStorage.close()}async startAttempt(e){this.metadata.attempts=this.metadata.attempts+1,this.metadata.status="RUNNING",this.diskStorage.storeFile({name:"metadata.json",contents:JSON.stringify(this.metadata,null,2)});let t=this.diskStorage.cd(`attempts/${this.metadata.attempts}`),n=eG(),o={id:n,schemaVersion:Jn,runAttemptSchemaVersion:XT,startedAt:new Date,status:"RUNNING"};t.storeFile({name:"metadata.json",contents:JSON.stringify(o,null,2)});let i=tG(async()=>{await this.client.extendAndroidEmulatorTtl(e.emulatorName)},3e4,{maxWait:6e4}),a=new eh(()=>void i(),this.testId,this.testName,n,o,t);return this.children.push(a),a}},Su=class r{constructor(e,t,n,o,i){this.orgId=e;this.runGroupId=t;this.metadata=n;this.client=o;this.diskStorage=i}children=[];finished=!1;get loggerBindings(){return{orgId:this.orgId,runGroupId:this.runGroupId,branch:this.metadata.gitBranchName}}static async start({orgId:e,runGroupId:t,outputDir:n,client:o,gitMetadata:i,labels:a}){let s={...i,id:t,trigger:or.CLI,startedAt:new Date,status:"RUNNING",cliVersion:hs,labels:a??[]},c=new cs(n);return c.storeFile({name:"metadata.json",contents:JSON.stringify(s,null,2)}),new r(e,t,s,o,c)}async finish(e){if(this.finished)return;this.finished=!0;let{status:t}=e,n={...this.metadata,status:t,updatedAt:new Date,finishedAt:new Date};await Promise.all(this.children.map(o=>o.finish({logger:e.logger,status:n.status,finishedAt:n.finishedAt}))),this.diskStorage.storeFile({name:"metadata.json",contents:JSON.stringify(n,null,2)})}async startRun(e){let t=this.diskStorage.createRunArchive(e.runId),n={stepsSnapshot:e.originalSteps.steps,runGroupId:this.runGroupId,testId:e.testId,testName:e.testName,testDescription:e.testDescription,labels:e.testLabels,trigger:"CLI",status:"RUNNING",environmentName:e.environmentName,cliVersion:hs,schemaVersion:e.schemaVersion,startedAt:new Date,attempts:0,quarantined:e.quarantined,quarantinedReason:e.quarantinedReason,executionType:"ANDROID"};t.storeFile({name:"metadata.json",contents:JSON.stringify(n,null,2)});let o=new th(this.client,e.testId,e.testName,e.runId,n,t);return this.children.push(o),o}};async function Sx(r,e,t){if(t)return{};try{return(await e.getQuarantinedTests()).quarantined.reduce((o,i)=>(o[i.testId]=i.quarantinedReason,o),{})}catch(n){return r.warn({err:n},"Failed to fetch quarantined tests, proceeding without them."),{}}}async function yx(r){let{options:e,fixtures:t,inputs:n,metadata:o}=r,{project:i,apiClient:a,logger:s}=t,{orgId:c,runGroupId:l,gitMetadata:u}=o,{outputDir:d,parallel:p}=e;iG(d)&&x.warn(`Output directory ${d} already exists, removing before test execution...`);let g=await Sx(s,a,e.ignoreQuarantine),m=await vr(i),h=await hx({tests:n.tests,yes:e.yes,project:i,momenticFiles:m,logger:x,quarantinedTestReasons:g}),f=s.child({orgId:c,runGroupId:l,branch:u.gitBranchName}),E=await Su.start({logger:f,orgId:c,runGroupId:l,outputDir:d,client:a,gitMetadata:u,labels:[]}),S=[],A=new Date,C=new Set,T=async()=>aG({runResults:S,startTime:A,ranTests:C,apiClient:a,uploadResults:e.uploadResults??!1,outputDir:d}),I=[],R=async()=>{x.warn("SIGINT received. Stopping tests and printing latest results..."),await E.finish({logger:f,status:"CANCELLED"}),await T(),await Promise.allSettled(I.map(U=>U())),setImmediate(()=>{setTimeout(()=>{process.exit(1)},2e3).unref()})};process.once("SIGINT",R);let w={};for(let U=0;U<h.length;U++){let J=Object.values(w);J.length===p&&await Promise.race(J.map(G=>G.promise));let Le=h[U],K=`test-${U}`;w[K]={done:!1,promise:(async({testDefinition:G})=>{C.add(K);let se=G.relativeFilePath.includes("..")?G.fullFilePath:G.relativeFilePath;Qa({status:"START",testLogRef:se,getRunningTestsCount:()=>C.size,getTotalTestsCount:()=>h.length});let ce=setInterval(()=>Qa({status:"RUN",testLogRef:se,getRunningTestsCount:()=>C.size,getTotalTestsCount:()=>h.length}),5*60*1e3),ke=oG(),fe=f.child({testId:G.id,runId:ke}),pt=new fc({logger:fe,reporter:new au(a),runType:"mobile-test-run",runId:ke,testMetadata:G,suiteMetadata:void 0});try{let Wt=await fx({metadata:{...o,runId:ke},fixtures:{...t,tracer:E,logger:fe,usageTracker:pt},inputs:{...n,project:i,testDefinition:G,channel:n.channel??G.settings?.defaultChannel,tag:n.tag??G.settings?.defaultTag,logUpdate:(we,tt)=>Qa({status:we,testLogRef:se,getRunningTestsCount:()=>C.size,getTotalTestsCount:()=>h.length,additionalText:tt}),runSigIntHandlers:I},options:e});Qa({status:Wt.status,testLogRef:se,getRunningTestsCount:()=>C.size,getTotalTestsCount:()=>h.length}),S.push(Wt)}catch(Wt){let we=`Encountered unexpected fatal error when running test '${G.name}': ${Wt.message}`;x.error(we),fe.error(we)}finally{clearInterval(ce),w[K].done=!0,delete w[K]}await pt.flush(s)})({testDefinition:Le})}}await Promise.allSettled(Object.values(w).map(U=>U.promise));let D=S.some(U=>U.status==="FAILED"&&!U.quarantined)?"FAILED":"PASSED";return await E.finish({logger:f,status:D}),process.off("SIGINT",R),T()}async function aG({runResults:r,startTime:e,ranTests:t,apiClient:n,uploadResults:o,outputDir:i}){let a=n.getAppUrl(),s=RR({results:r,startTime:e.getTime(),onFailed:c=>{},getDisplayLine:c=>{let l=`${Qm}- ${c.filePath}`;return c.runId&&(l+=` ( link when uploaded: ${a}/runs/${c.runId} )`),l},entity:"mobile test"});return x.log(""),o?(x.success(`Test results have been saved to the folder ${i}. Uploading to Momentic Cloud...`),await uu({client:n,consoleLogger:x,resultsPath:i})):x.success(`Test results have been saved to the folder ${i}. Upload them to Momentic Cloud by running 'npx momentic-mobile results upload ${i}'.`),s}async function rh(){ov(),PR("Chromium")||(yo?(await Wc("The Chromium browser is not installed but is required for automating webviews. Install it now?")||process.exit(1),await $c({rawBrowsers:["chromium"],force:!1,all:!1})):(x.error("The Chromium browser is not installed but is required for automating webviews. Please install it using 'momentic-mobile install-browsers chromium'"),process.exit(1)))}ay({serviceName:"mobile-cli"});Bt.setApp("mobile-cli");var kn=new sG;kn.name("momentic-mobile").description("Momentic Mobile CLI").version(hs);var pG=kn.command("assets").description("Manage mobile testing assets");pG.command("upload").description("Upload an asset for mobile tests").argument("<file>","Path to the asset file to upload").addOption(ps).addOption(ms).addOption(Yg).addOption(ux).action(async(r,e)=>{let{apiKey:t,server:n,tag:o,channel:i}=e,a=bu.resolve(r);yu.existsSync(a)||(x.error(`File not found: ${a}`),process.exit(1));let s=new wr({baseUrl:n,apiKey:t,logger:x});/\.apk$/i.test(a)||(x.error(`File is not an APK file: ${a}`),process.exit(1)),await cl({tag:o?.toLowerCase(),channel:i.toLowerCase(),filePath:a,apiClient:s,logger:x})});kn.command("app").addOption(ps).addOption(ms).addOption($g).addOption(Wg).addOption(Jg).addOption(qg).addOption(Kg).action(async r=>{let{apiKey:e,server:t,yes:n,disableCache:o,saveCache:i}=r,a=eg(r.logLevel);Bt.setApp("mobile-desktop-server");let s=new wr({baseUrl:t,apiKey:e,logger:Bt});await Mg({client:s,skipPrompts:n}),x.debug("API key check complete");let c=dG(import.meta.url),l=bu.dirname(c),u=bu.resolve(l,"..","static");await rh(),x.debug({appiumHome:Ha},"Resolved resource paths");let d=await rs({configFilePath:r.config}),p=lx;await sx({momenticServerUrl:t,serverPort:p,apiKey:e,staticDir:u,initialProject:d,driverLogLevel:a,logger:Bt,noCache:o,alwaysSaveCache:i});let g=`http://localhost:${p}`;x.info(`Local app started on: ${g}`),await uG(g)});var bx=kn.command("results").description("Merge and upload test results.");bx.command("merge").description("Merge test results files.").addOption(Xg).addArgument(new nh("<resultsPath>","Path to a directory that contains on or more test results archives.").argRequired()).action(async(r,e)=>{let{outputDir:t}=e;t||(x.error("Output directory is required."),process.exit(1)),yu.existsSync(r)||(x.warn("Results path does not exist, skipping merge."),process.exit(0)),yu.existsSync(t)&&x.warn(`Output directory ${t} already exists, removing before merging...`),YR(Bt,t,r),Li(),process.exit(0)});var mG=new nh("<results>","Path to the results archive.").argRequired();bx.command("upload").description("Upload test results to Momentic cloud.").addOption(ps).addOption(ms).addArgument(mG).action(async(r,e)=>{let{apiKey:t,server:n}=e,o=Bt,i=new wr({baseUrl:n,apiKey:t,logger:o});await uu({consoleLogger:x,resultsPath:r,client:i}),Li(),process.exit(0)});var gG=kn.command("run").alias("test").description("Run tests on the local machine");gG.addOption(ps).addOption(ms).addOption(Wg).addOption($g).addOption(px).addOption(Jg).addOption(qg).addOption(Kg).addOption(Xg).addOption(mx).addOption(gx).addOption(Yg).addOption(cx).addOption(dx).addArgument(new nh("<tests...>","One or more test file path or folders that exist on the local machine.").argOptional()).action(async(r,e)=>{let{apiKey:t,server:n,tag:o,channel:i,outputDir:a}=e,s=eg(e.logLevel);await rh(),x.debug({appiumHome:Ha},"Resolved resource paths");let c=await rs({configFilePath:e.config}),l=a??c.config.outputDir??BR,u=e.parallel??c.config.parallel??1;x.debug("Checking API key and dependencies");let d=new wr({baseUrl:n,apiKey:t,logger:x}),{orgId:p,userId:g}=await Mg({client:d,skipPrompts:e.yes});x.debug("API key check and browser installation complete");let m=cG(),h=Bt.child({runGroupId:m,orgId:p,userId:g}),f=await Xc(Bt,d,c);h.debug(f,"Got local git metadata");try{let E=await yx({options:{...e,outputDir:l,parallel:u,logLevel:s,alwaysSaveCache:e.saveCache,noCache:e.disableCache},fixtures:{logger:h,project:c,apiClient:d},inputs:{envOverride:e.env,tag:o,channel:i,tests:r},metadata:{gitMetadata:f,runGroupId:m,orgId:p}});Li(),E.failed>0?process.exit(1):process.exit(0)}catch(E){x.error("Failed to run tests locally. Please check the error message below or run with the --verbose flag."),x.error(E),Bt.error({err:E},"Failed to run tests locally"),Li(),process.exit(1)}});kn.command("init").description("Initialize an empty Momentic project in the current working directory").addOption(new lG("--name <name>","Name of the project")).action(async r=>{x.info(`Welcome to the Momentic Mobile project setup wizard! \u{1F680}
|
|
4052
|
-
`),
|
|
4090
|
+
`)}async finish(e){if(this.finished)return;this.finished=!0;let{logger:t,status:n,results:o,beforeResults:i,afterResults:a}=e,l={...this.metadata,status:n,finishedAt:new Date,results:Ac(o,t),beforeResults:i?Ac(i,t):void 0,afterResults:a?Ac(a,t):void 0};await Promise.all(this.children.map(c=>c.finish({status:l.status,finishedAt:l.finishedAt})));try{this.logStream.end()}catch{}this.diskStorage.storeFile({name:"metadata.json",contents:JSON.stringify(l,null,2)})}async startBeforeStepList(){let e=new Ei(this.keepalive,this.testId,this.testName,this.diskStorage);return this.children.push(e),e}async startMainStepList(){let e=new Ei(this.keepalive,this.testId,this.testName,this.diskStorage);return this.children.push(e),e}async startAfterStepList(){let e=new Ei(this.keepalive,this.testId,this.testName,this.diskStorage);return this.children.push(e),e}async getScreenshot(e,t){return this.diskStorage.readFile(`${tu}/${t}.jpeg`)}},Ig=class{constructor(e,t,n,o,i,a){this.client=e;this.testId=t;this.testName=n;this.runId=o;this.metadata=i;this.diskStorage=a}children=[];finished=!1;get loggerBindings(){return{runId:this.runId}}async finish(e){if(this.finished)return;this.finished=!0;let t={...this.metadata,finishedAt:e.finishedAt||new Date,status:e.status,failureDetails:e.failureDetails,failureReason:e.failureReason,flake:e.isFlake||!1,failureRecoveryDetails:e.failureRecoveryDetails};await Promise.all(this.children.map(n=>n.finish({logger:e.logger,status:t.status,results:[],beforeResults:[],afterResults:[]}))),this.diskStorage.storeFile({name:"metadata.json",contents:JSON.stringify(t,null,2)}),this.diskStorage.close()}async startAttempt(e){this.metadata.attempts=this.metadata.attempts+1,this.metadata.status="RUNNING",this.diskStorage.storeFile({name:"metadata.json",contents:JSON.stringify(this.metadata,null,2)});let t=this.diskStorage.cd(`attempts/${this.metadata.attempts}`),n=$z(),o={id:n,schemaVersion:Ln,runAttemptSchemaVersion:Ty,startedAt:new Date,status:"RUNNING"};t.storeFile({name:"metadata.json",contents:JSON.stringify(o,null,2)});let i=qz(async()=>{await this.client.extendAndroidEmulatorTtl(e.emulatorName)},3e4,{maxWait:6e4}),a=new _g(()=>void i(),this.testId,this.testName,n,o,t);return this.children.push(a),a}},ru=class r{constructor(e,t,n,o,i){this.orgId=e;this.runGroupId=t;this.metadata=n;this.client=o;this.diskStorage=i}children=[];finished=!1;get loggerBindings(){return{orgId:this.orgId,runGroupId:this.runGroupId,branch:this.metadata.gitBranchName}}static async start({orgId:e,runGroupId:t,outputDir:n,client:o,gitMetadata:i,labels:a}){let l={...i,id:t,trigger:Jt.CLI,startedAt:new Date,status:"RUNNING",cliVersion:es,labels:a??[]},c=new Ka(n);return c.storeFile({name:"metadata.json",contents:JSON.stringify(l,null,2)}),new r(e,t,l,o,c)}async finish(e){if(this.finished)return;this.finished=!0;let{status:t}=e,n={...this.metadata,status:t,updatedAt:new Date,finishedAt:new Date};await Promise.all(this.children.map(o=>o.finish({logger:e.logger,status:n.status,finishedAt:n.finishedAt}))),this.diskStorage.storeFile({name:"metadata.json",contents:JSON.stringify(n,null,2)})}async startRun(e){let t=this.diskStorage.createRunArchive(e.runId),n={stepsSnapshot:e.originalSteps.steps,runGroupId:this.runGroupId,testId:e.testId,testName:e.testName,testDescription:e.testDescription,labels:e.testLabels,trigger:"CLI",status:"RUNNING",environmentName:e.environmentName,cliVersion:es,schemaVersion:e.schemaVersion,startedAt:new Date,attempts:0,quarantined:e.quarantined,quarantinedReason:e.quarantinedReason,executionType:"ANDROID"};t.storeFile({name:"metadata.json",contents:JSON.stringify(n,null,2)});let o=new Ig(this.client,e.testId,e.testName,e.runId,n,t);return this.children.push(o),o}};async function uC(r,e,t){if(t)return{};try{return(await e.getQuarantinedTests()).quarantined.reduce((o,i)=>(o[i.testId]=i.quarantinedReason,o),{})}catch(n){return r.warn({err:n},"Failed to fetch quarantined tests, proceeding without them."),{}}}async function dC(r){let{options:e,fixtures:t,inputs:n,metadata:o}=r,{project:i,apiClient:a,logger:l}=t,{orgId:c,runGroupId:s,gitMetadata:u}=o,{outputDir:d,parallel:p}=e;Jz(d)&&A.warn(`Output directory ${d} already exists, removing before test execution...`);let m=await uC(l,a,e.ignoreQuarantine),g=await fr(i),h=await lC({tests:n.tests,yes:e.yes,project:i,momenticFiles:g,logger:A,quarantinedTestReasons:m}),f=l.child({orgId:c,runGroupId:s,branch:u.gitBranchName}),b=await ru.start({logger:f,orgId:c,runGroupId:s,outputDir:d,client:a,gitMetadata:u,labels:[]}),E=[],v=new Date,R=new Set,T=async()=>Zz({runResults:E,startTime:v,ranTests:R,apiClient:a,uploadResults:e.uploadResults??!1,outputDir:d}),_=[],M=async()=>{A.warn("SIGINT received. Stopping tests and printing latest results..."),await b.finish({logger:f,status:"CANCELLED"}),await T(),await Promise.allSettled(_.map(oe=>oe())),setImmediate(()=>{setTimeout(()=>{process.exit(1)},2e3).unref()})};process.once("SIGINT",M);let z={};for(let oe=0;oe<h.length;oe++){let ge=Object.values(z);ge.length===p&&await Promise.race(ge.map(U=>U.promise));let et=h[oe],j=`test-${oe}`;z[j]={done:!1,promise:(async({testDefinition:U})=>{R.add(j);let ne=U.relativeFilePath.includes("..")?U.fullFilePath:U.relativeFilePath;Va({status:"START",testLogRef:ne,getRunningTestsCount:()=>R.size,getTotalTestsCount:()=>h.length});let ae=setInterval(()=>Va({status:"RUN",testLogRef:ne,getRunningTestsCount:()=>R.size,getTotalTestsCount:()=>h.length}),5*60*1e3),Ne=Xz(),he=f.child({testId:U.id,runId:Ne}),dt=new oc({logger:he,reporter:new Wc(a),runType:"mobile-test-run",runId:Ne,testMetadata:U,suiteMetadata:void 0});try{let Gt=await cC({metadata:{...o,runId:Ne},fixtures:{...t,tracer:b,logger:he,usageTracker:dt},inputs:{...n,project:i,testDefinition:U,channel:n.channel??U.settings?.defaultChannel,tag:n.tag??U.settings?.defaultTag,logUpdate:(Ae,tt)=>Va({status:Ae,testLogRef:ne,getRunningTestsCount:()=>R.size,getTotalTestsCount:()=>h.length,additionalText:tt}),runSigIntHandlers:_},options:e});Va({status:Gt.status,testLogRef:ne,getRunningTestsCount:()=>R.size,getTotalTestsCount:()=>h.length}),E.push(Gt)}catch(Gt){let Ae=`Encountered unexpected fatal error when running test '${U.name}': ${Gt.message}`;A.error(Ae),he.error(Ae)}finally{clearInterval(ae),z[j].done=!0,delete z[j]}await dt.flush(l)})({testDefinition:et})}}await Promise.allSettled(Object.values(z).map(oe=>oe.promise));let Ee=E.some(oe=>oe.status==="FAILED"&&!oe.quarantined)?"FAILED":"PASSED";return await b.finish({logger:f,status:Ee}),process.off("SIGINT",M),T()}async function Zz({runResults:r,startTime:e,ranTests:t,apiClient:n,uploadResults:o,outputDir:i}){let a=n.getAppUrl(),l=dR({results:r,startTime:e.getTime(),onFailed:c=>{},getDisplayLine:c=>{let s=`${Fm}- ${c.filePath}`;return c.runId&&(s+=` ( link when uploaded: ${a}/runs/${c.runId} )`),s},entity:"mobile test"});return A.log(""),o?(A.success(`Test results have been saved to the folder ${i}. Uploading to Momentic Cloud...`),await Yc({client:n,consoleLogger:A,resultsPath:i})):A.success(`Test results have been saved to the folder ${i}. Upload them to Momentic Cloud by running 'npx momentic-mobile results upload ${i}'.`),l}async function Pg(){HT(),SR("Chromium")||(zn?(await Dc("The Chromium browser is not installed but is required for automating webviews. Install it now?")||process.exit(1),await kc({rawBrowsers:["chromium"],force:!1,all:!1})):(A.error("The Chromium browser is not installed but is required for automating webviews. Please install it using 'momentic-mobile install-browsers chromium'"),process.exit(1)))}LT({serviceName:"mobile-cli"});Ft.setApp("mobile-cli");var Rn=new Qz;Rn.name("momentic-mobile").description("Momentic Mobile CLI").version(es);var o1=Rn.command("assets").description("Manage mobile testing assets");o1.command("upload").description("Upload an asset for mobile tests").argument("<file>","Path to the asset file to upload").addOption(Ja).addOption(Za).addOption(wg).addOption(nC).action(async(r,e)=>{let{apiKey:t,server:n,tag:o,channel:i}=e,a=ou.resolve(r);nu.existsSync(a)||(A.error(`File not found: ${a}`),process.exit(1));let l=new yr({baseUrl:n,apiKey:t,logger:A});/\.apk$/i.test(a)||(A.error(`File is not an APK file: ${a}`),process.exit(1)),await $l({tag:o?.toLowerCase(),channel:i.toLowerCase(),filePath:a,apiClient:l,logger:A})});Rn.command("app").addOption(Ja).addOption(Za).addOption(Tg).addOption(Eg).addOption(Cg).addOption(vg).addOption(Ag).action(async r=>{let{apiKey:e,server:t,yes:n,disableCache:o,saveCache:i}=r,a=Bm(r.logLevel);Ft.setApp("mobile-desktop-server");let l=new yr({baseUrl:t,apiKey:e,logger:Ft});await og({client:l,skipPrompts:n}),A.debug("API key check complete");let c=n1(import.meta.url),s=ou.dirname(c),u=ou.resolve(s,"..","static");await Pg(),A.debug({appiumHome:Oa},"Resolved resource paths");let d=await $a({configFilePath:r.config}),p=tC;await eC({momenticServerUrl:t,serverPort:p,apiKey:e,staticDir:u,initialProject:d,driverLogLevel:a,logger:Ft,noCache:o,alwaysSaveCache:i});let m=`http://localhost:${p}`;A.info(`Local app started on: ${m}`),await r1(m)});var pC=Rn.command("results").description("Merge and upload test results.");pC.command("merge").description("Merge test results files.").addOption(Rg).addArgument(new Og("<resultsPath>","Path to a directory that contains on or more test results archives.").argRequired()).action(async(r,e)=>{let{outputDir:t}=e;t||(A.error("Output directory is required."),process.exit(1)),nu.existsSync(r)||(A.warn("Results path does not exist, skipping merge."),process.exit(0)),nu.existsSync(t)&&A.warn(`Output directory ${t} already exists, removing before merging...`),kR(Ft,t,r),Ti(),process.exit(0)});var i1=new Og("<results>","Path to the results archive.").argRequired();pC.command("upload").description("Upload test results to Momentic cloud.").addOption(Ja).addOption(Za).addArgument(i1).action(async(r,e)=>{let{apiKey:t,server:n}=e,o=Ft,i=new yr({baseUrl:n,apiKey:t,logger:o});await Yc({consoleLogger:A,resultsPath:r,client:i}),Ti(),process.exit(0)});var a1=Rn.command("run").alias("test").description("Run tests on the local machine");a1.addOption(Ja).addOption(Za).addOption(Eg).addOption(Tg).addOption(iC).addOption(Cg).addOption(vg).addOption(Ag).addOption(Rg).addOption(aC).addOption(sC).addOption(wg).addOption(rC).addOption(oC).addArgument(new Og("<tests...>","One or more test file path or folders that exist on the local machine.").argOptional()).action(async(r,e)=>{let{apiKey:t,server:n,tag:o,channel:i,outputDir:a}=e,l=Bm(e.logLevel);await Pg(),A.debug({appiumHome:Oa},"Resolved resource paths");let c=await $a({configFilePath:e.config}),s=a??c.config.outputDir??RR,u=e.parallel??c.config.parallel??1;A.debug("Checking API key and dependencies");let d=new yr({baseUrl:n,apiKey:t,logger:A}),{orgId:p,userId:m}=await og({client:d,skipPrompts:e.yes});A.debug("API key check and browser installation complete");let g=t1(),h=Ft.child({runGroupId:g,orgId:p,userId:m}),f=await zc(Ft,d,c);h.debug(f,"Got local git metadata");try{let b=await dC({options:{...e,outputDir:s,parallel:u,logLevel:l,alwaysSaveCache:e.saveCache,noCache:e.disableCache},fixtures:{logger:h,project:c,apiClient:d},inputs:{envOverride:e.env,tag:o,channel:i,tests:r},metadata:{gitMetadata:f,runGroupId:g,orgId:p}});Ti(),b.failed>0?process.exit(1):process.exit(0)}catch(b){A.error("Failed to run tests locally. Please check the error message below or run with the --verbose flag."),A.error(b),Ft.error({err:b},"Failed to run tests locally"),Ti(),process.exit(1)}});Rn.command("init").description("Initialize an empty Momentic project in the current working directory").addOption(new e1("--name <name>","Name of the project")).action(async r=>{A.info(`Welcome to the Momentic Mobile project setup wizard! \u{1F680}
|
|
4091
|
+
`),A.info("This wizard will help you bootstrap a new Momentic project."),nu.existsSync(di)&&(A.error("A momentic.config.yaml file already exists in this directory. Please rename or remove it to initialize a new project."),process.exit(1));let t={name:r.name??await mR("Choose an identifier for your project, such as a service, product, or team name (default: 'app'):","app"),include:Vm};wR(t,di),A.success(`Initialized Momentic project file at ${ou.resolve(di)}`)});Rn.command("install-browsers").description("Install browser executables onto the local machine.").option("-f, --force","Force reinstallation even if the browser executables already exist on disk.").option("-a, --all","Install all browsers types.").argument("[browsers...]",`Browsers to install. Available choices: ${zm.join(", ")}.`).action(async(r,e)=>{!e.all&&r.length===0&&(A.error("No browsers specified"),process.exit(1)),await kc({rawBrowsers:r,force:e.force,all:e.all})});async function Ti(){try{await vt.flush(),Cy()}catch{}}async function s1(){try{await Rn.parseAsync(process.argv),Ti()}catch(r){Ft.error({err:r},"Uncaught error in CLI"),A.error(r),Ti(),process.exit(1)}}s1();
|
|
4053
4092
|
//# sourceMappingURL=cli.js.map
|