momentic-mobile 0.16.1 → 0.16.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/bin/cli.js CHANGED
@@ -24,7 +24,7 @@ ${this.decisions.map(e=>e.toString()).join(`
24
24
  `).slice(o).filter(Boolean).join(`
25
25
  `);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",ss(e,...t))}error(e,...t){this._log("error",ss(e,...t))}info(e,...t){this._log("info",ss(e,...t))}log(e,...t){this._log("log",ss(e,...t))}warn(e,...t){this._log("warn",ss(e,...t))}getBuffer(){return this._buffer.length>0?this._buffer:void 0}};function cT(r){let e=globalThis.console,t=new Sc;globalThis.console=t;try{r()}finally{let o=t.getBuffer()?.map(i=>i.message).join(`
26
26
  `);process.stderr.write(`${o}
27
- `),globalThis.console=e}}var gp=" ".repeat(6);import lD from"fetch-retry";import cD from"os";import uT,{multistream as uD}from"pino";import dD from"pino-pretty";import mD from"pino-std-serializers";var Mi=new Map,pD=!0,dT="Log throttle exceeded",gD=100,hD=5e3,fD=lD(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}}),hp=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??cD.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=pD?uT(a):uT(a,uD([{stream:dD({colorize:!0})}]))}child(e){return new r({bindings:{...this.bindingAttributes,...e},hostname:this.hostname,disableConsoleLogs:this.disableConsoleLogs,flushIntervalMs:this.flushIntervalMs,maxBatchSize:this.maxBatchSize})}async flush(){await this.flushBuffer(),this.disableConsoleLogs||this.consoleLogger.flush()}scheduleFlush(){this.flushTimer||(this.flushTimer=setTimeout(()=>{this.flushTimer=void 0,this.flushBuffer()},this.flushIntervalMs))}async flushBuffer(){if(this.buffer.length===0)return;let e=this.buffer;this.buffer=[];try{let t=await fD(this.site,{method:"POST",headers:{"Content-Type":"application/json","signoz-access-token":"CumAaTMUcwjt05OddAmefKgshbhfRmWxzxih"},body:Ro(e),signal:AbortSignal.timeout(5e3)});if(!t.ok)throw new Error(`Got error status (${t.statusText}) from SigNoz`)}catch{}}shouldAllowLog(e){if(e===dT)return!0;let t=Date.now();return t-this.lastWindowStart>hD&&(this.logsInCurrentWindow=0,this.droppedLogsInWindow&&this.log("error",void 0,dT),this.droppedLogsInWindow=!1,this.lastWindowStart=t),this.logsInCurrentWindow<gD?(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(os[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=mD.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:Kb({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,Mi.set("app",this),Mi.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=Yb[e]):(this.minLevelValue=os[e],this.consoleLogger.level=e)}enableConsoleLogs(){this.disableConsoleLogs=!1}},_i=({app:r,hostname:e,disableConsoleLogs:t})=>(Mi.has(r)||Mi.set(r,new hp({bindings:{app:r},hostname:e,disableConsoleLogs:t})),Mi.get(r));async function mT(){await Promise.all([...Mi.values()].map(r=>r.flush()))}import{hostname as SD}from"os";var ur=_i({app:"cli",hostname:SD(),disableConsoleLogs:!0}).child({cliVersion:"0.16.1"});function fp(r){if(!r)return;r=r.toLowerCase();let e=cc.safeParse(r);if(e.success)return C.setMinLevel(e.data),e.data}function pT({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 cT(()=>{if(c.forEach(u=>{C.log(""),o(u)}),c.length){C.log("");let u=c.length===1?"":"s";C.error(`${c.length} ${t}${u} failed:`),c.forEach(d=>{C.dimmed(n(d))})}if(l.length){C.log("");let u=l.length===1?"":"s";C.warn(`${l.length} ${t}${u} cancelled:`),l.forEach(d=>{C.dimmed(n(d))})}if(a.length){C.log("");let u=a.length===1?"":"s";C.success(`${a.length} ${t}${u} passed:`),a.forEach(d=>{C.dimmed(n(d))})}if(s.length){C.log("");let u=s.length===1?"":"s";C.warn(`${s.length} quarantined ${t}${u} failed:`),s.forEach(d=>{C.dimmed(n(d))})}if(i.length){C.log("");let u=i.length===1?"":"s";C.warn(`${i.length} quarantined ${t}${u} passed:`),i.forEach(d=>{C.dimmed(n(d))})}C.log(""),C.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 ls=({status:r,testLogRef:e,getRunningTestsCount:t,getTotalTestsCount:n,additionalText:o})=>{r=r.toUpperCase();let i=r,a;r.includes("FAIL")?(i=Pi.bgRed.white("FAIL"),a=3):r.includes("PASS")?(i=Pi.bgGreen.white("PASS"),a=3):r.includes("START")?(i=Pi.bgBlue.white("START"),a=2):r.includes("CANCEL")?(i=Pi.bgRgb(191,68,11).white("CANCEL"),a=1):r.includes("RETRY")?(i=Pi.bgRgb(191,68,11).white("RETRY"),a=2):r.includes("RUN")||r.includes("PROG")?(i=Pi.bgMagenta.white("RUNNING"),a=0):(C.warn(`Unknown status tried to be logged in run test locally: ${r}`),a=0),yD||(i=`${i}`),C.log(`${i}${" ".repeat(a)} ${e} ${o?`${o} `:""}(${t()}/${n()})`)};import bD from"fs";import{tmpdir as ED}from"os";import TD from"path";import{registry as cs}from"playwright-core/lib/server";import gT from"proper-lockfile";var hT=TD.join(ED(),"momenticBrowserInstallation");var Sp=["chrome","chromium","chrome-for-testing","ffmpeg"],vD={Chromium:"chromium","Google Chrome":"chrome","Chrome for Testing":"chrome-for-testing"},fT={chrome:"chrome",chromium:"chromium","chrome-for-testing":"chromium-headless-shell",ffmpeg:"ffmpeg"};function ST(r){if(r==="Org Default")return!1;let e=fT[vD[r]??""]??"",t=cs.findExecutable(e);return!t||t.installType==="none"?!1:yp(t)}function yp(r){let e=r.executablePath();return bD.existsSync(e)}function AD(r,e){let t=fT[r];if(!t)throw new Error(`Requested install of unknown browser type ${r}`);let n=cs.findExecutable(t);if(!n||n.installType==="none")throw new Error(`Requested install of unknown browser type ${r}`);if(!(!e&&yp(n)))return n}async function wD({browser:r,force:e}){let t=AD(r,e);if(!t){C.info(`Browser '${r}' is already installed, skipping...`);return}C.info(`Installing browser '${r}'...`);try{await cs.installDeps([t],!1),await cs.install([t],!1)}catch(n){if(n.message.includes("Lock file is already being held")){C.warn("Another process is installing Playwright browsers. Waiting for completion before proceeding..");let o=cs.findExecutable(r),i=5*60*1e3,a=Date.now();for(;Date.now()-a<i&&!yp(o);)C.info("Waiting for browser to finish installing..."),await new Promise(s=>setTimeout(s,5e3))}else throw n}}async function yc({rawBrowsers:r,force:e=!1,all:t=!1}){let n=t?Sp:Array.from(new Set(r));try{await gT.lock(hT,{stale:1e3*60*5,update:1e3*60,realpath:!1,retries:{retries:30,factor:2,maxTimeout:15e3,minTimeout:500}})}catch(i){C.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 wD({browser:i,force:e})}catch(a){o=a,C.error(`Failed to install the ${i} browser: ${a}`)}}finally{await gT.unlock(hT,{realpath:!1})}if(o)throw o}import{createServer as CD}from"http";async function bc(r,e,t=30){for(let n=0;n<t;n+=1){let o=r+n;if(await Ec(o))return o}C.error(`Could not find an available port for ${e} starting from ${r} after ${t} attempts`),process.exit(1)}async function Ec(r){return new Promise((e,t)=>{let n=CD();n.once("error",o=>{o.code==="EADDRINUSE"?e(!1):(C.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 Mre from"blocked-at";import Pre from"why-is-node-running";function yT(r){let e=r?.shardIndex??1,t=r?.shardCount??1;if(e<1)throw new Error("Shard index must be greater than 0.");if(t<1)throw new Error("Shard count must be greater than 0.");if(e>t)throw new Error("Shard index cannot be greater than shard count")}function RD(r,e,t,n){if(t>r.length&&(C.warn(`Shard count ${t} is greater than the number of tests ${r.length}! Some workers won't have any tests to run.`),t=Math.max(t,r.length),e>t))return[];let o=Math.floor((e-1)*(r.length/t)),i=Math.floor(e*(r.length/t));return(n?[...r].sort((s,c)=>n(s).localeCompare(n(c))):[...r].sort()).filter((s,c)=>c>=o&&c<i)}function bT(r){let{items:e,shardIndex:t,shardCount:n,sortKey:o}=r;return n>1?RD(e,t,n,o):e}import BF from"fs";import Wre,{multistream as $re}from"pino";import Kre from"pino-pretty";var Jre=5*1024,xD="...[truncated]",Qre=Buffer.byteLength(xD,"utf8");import{PostHog as lne}from"posthog-node";var zn=class extends Error{constructor(e){super(e),this.name="TimeoutError"}};var ET=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((s,c)=>{let l;if(e.signal){let{signal:m}=e;if(m.aborted)return c(ET(m));l=()=>c(ET(m)),m.addEventListener("abort",l,{once:!0})}let u=()=>{if(e.signal&&e.signal.removeEventListener("abort",l),n)try{s(n())}catch(m){c(m)}else{typeof r.cancel=="function"&&Promise.resolve().then(()=>r.cancel()).catch(()=>{});let m=o instanceof Error?o:new zn(o??`Promise timed out after ${t}ms`);c(m)}};t<1/0&&(a=i.setTimeout(u,t));let d=()=>{i.clearTimeout(a),e.signal&&e.signal.removeEventListener("abort",l)};Promise.resolve(r).then(m=>{d(),s(m)}).catch(m=>{d(),c(m)})})}import{PostHog as Sne}from"posthog-node";import{execSync as MD}from"child_process";import Ii from"os";import _D from"v8";var TT,Wr,AT=Ii.platform(),PD=Ii.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),{}),vT=r=>{try{let e={},t=!1,n=ID(),o=OD(),i=`${Math.round(n.freePercentage*100)}%`;n.freePercentage<.05&&(Object.assign(e,process.memoryUsage()),t=!0);let a=`${o?Math.round(o.idle):"unknown"}%`;o&&o?.total>80&&(t=!0);let s=_D.getHeapStatistics(),c=s.used_heap_size,l=s.heap_size_limit;c/l>.9&&(t=!0),t?(r.warn({memory:n,cpu:o,heapStats:s,...e},"Critical resource usage metrics detected"),xo&&C.warn(`Low machine resources detected (memory: ${i} free, cpu: ${a} free)`)):r.debug({memory:n,cpu:o},"Got machine resource usage metrics")}catch{}};function wT(r){if(!Cr)return vT(r),{interval:setInterval(()=>vT(r),2e4),cpuMetadata:PD,platform:AT}}function ID(){let r=Ii.totalmem(),e=AT==="darwin"?LD():(()=>{let n=Ii.freemem();return{availableMemory:n,rawFreeMemory:n,cachedMemory:0}})(),t=e.availableMemory/r;return{totalMemory:r,freeMemory:e.availableMemory,freePercentage:t}}function OD(){let r=Ii.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,!Wr)return Wr=t,null;let n={user:t.user-Wr.user,nice:t.nice-Wr.nice,sys:t.sys-Wr.sys,idle:t.idle-Wr.idle,irq:t.irq-Wr.irq,total:t.total-Wr.total};return TT={measurementTime:e,intervalMs:e-Wr.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},Wr=t,TT}function LD(){try{let r=MD("/usr/bin/vm_stat",{encoding:"utf8",stdio:["pipe","pipe","ignore"]}),t=r.match(/page size of (\d+) bytes/)?.[1],n=t?Number.parseInt(t,10):4096,o=u=>{let m=r.match(new RegExp(`${u}:\\s+(\\d+)\\.`,"i"))?.[1];return m?Number.parseInt(m,10):0},i=o("Pages free"),a=o("Pages inactive"),s=o("Pages speculative"),c=i*n,l=(a+s)*n;return{availableMemory:c+l,rawFreeMemory:c,cachedMemory:l}}catch{let e=Ii.freemem();return{availableMemory:e,rawFreeMemory:e,cachedMemory:0}}}var Tc=class{increment(e,t,n){}gauge(e,t){}distribution(e,t,n){}async flush(){}async recordDuration({fn:e}){return await e()}};function ND(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 vc(r,e){let t=ND(r);return!e||Object.keys(e).length===0?t:{...e,...t}}var JT="=",Rc=";",Pp=",";var QT=8192;var Di={};V_(Di,{getKeyPairs:()=>p0,parseKeyPairsIntoRecord:()=>g0,parsePairKeyValue:()=>ZT,serializeKeyPairs:()=>m0});Le();var d0=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 m0(r){return r.reduce(function(e,t){var n=""+e+(e!==""?Pp:"")+t;return n.length>QT?e:n},"")}function p0(r){return r.getAllEntries().map(function(e){var t=d0(e,2),n=t[0],o=t[1],i=encodeURIComponent(n)+"="+encodeURIComponent(o.value);return o.metadata!==void 0&&(i+=Rc+o.metadata.toString()),i})}function ZT(r){var e=r.split(Rc);if(!(e.length<=0)){var t=e.shift();if(t){var n=t.indexOf(JT);if(!(n<=0)){var o=decodeURIComponent(t.substring(0,n).trim()),i=decodeURIComponent(t.substring(n+1).trim()),a;return e.length>0&&(a=Ep(e.join(Rc))),{key:o,value:i,metadata:a}}}}}function g0(r){return typeof r!="string"||r.length===0?{}:r.split(Pp).map(function(e){return ZT(e)}).filter(function(e){return e!==void 0&&e.value.length>0}).reduce(function(e,t){return e[t.key]=t.value,e},{})}Le();var xc;(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"})(xc||(xc={}));var h0=",",f0=["OTEL_SDK_DISABLED"];function S0(r){return f0.indexOf(r)>-1}var y0=["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 b0(r){return y0.indexOf(r)>-1}var E0=["OTEL_NO_PATCH_MODULES","OTEL_PROPAGATORS"];function T0(r){return E0.indexOf(r)>-1}var Ip=1/0,Op=128,v0=128,A0=128,Lp={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:Fe.INFO,OTEL_NO_PATCH_MODULES:[],OTEL_PROPAGATORS:["tracecontext","baggage"],OTEL_RESOURCE_ATTRIBUTES:"",OTEL_SERVICE_NAME:"",OTEL_ATTRIBUTE_VALUE_LENGTH_LIMIT:Ip,OTEL_ATTRIBUTE_COUNT_LIMIT:Op,OTEL_SPAN_ATTRIBUTE_VALUE_LENGTH_LIMIT:Ip,OTEL_SPAN_ATTRIBUTE_COUNT_LIMIT:Op,OTEL_LOGRECORD_ATTRIBUTE_VALUE_LENGTH_LIMIT:Ip,OTEL_LOGRECORD_ATTRIBUTE_COUNT_LIMIT:Op,OTEL_SPAN_EVENT_COUNT_LIMIT:128,OTEL_SPAN_LINK_COUNT_LIMIT:128,OTEL_SPAN_ATTRIBUTE_PER_EVENT_COUNT_LIMIT:v0,OTEL_SPAN_ATTRIBUTE_PER_LINK_COUNT_LIMIT:A0,OTEL_TRACES_EXPORTER:"",OTEL_TRACES_SAMPLER:xc.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 w0(r,e,t){if(!(typeof t[r]>"u")){var n=String(t[r]);e[r]=n.toLowerCase()==="true"}}function C0(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 R0(r,e,t,n){n===void 0&&(n=h0);var o=t[r];typeof o=="string"&&(e[r]=o.split(n).map(function(i){return i.trim()}))}var x0={ALL:Fe.ALL,VERBOSE:Fe.VERBOSE,DEBUG:Fe.DEBUG,INFO:Fe.INFO,WARN:Fe.WARN,ERROR:Fe.ERROR,NONE:Fe.NONE};function M0(r,e,t){var n=t[r];if(typeof n=="string"){var o=x0[n.toUpperCase()];o!=null&&(e[r]=o)}}function ev(r){var e={};for(var t in Lp){var n=t;switch(n){case"OTEL_LOG_LEVEL":M0(n,e,r);break;default:if(S0(n))w0(n,e,r);else if(b0(n))C0(n,e,r);else if(T0(n))R0(n,e,r);else{var o=r[n];typeof o<"u"&&o!==null&&(e[n]=String(o))}}}return e}function Tt(){var r=ev(process.env);return Object.assign({},Lp,r)}function tv(r){return r>=48&&r<=57?r-48:r>=97&&r<=102?r-87:r-55}function Mc(r){for(var e=new Uint8Array(r.length/2),t=0,n=0;n<r.length;n+=2){var o=tv(r.charCodeAt(n)),i=tv(r.charCodeAt(n+1));e[t++]=o<<4|i}return e}var rv="1.25.1";var _0="deployment.environment";var P0="process.runtime.name";var I0="service.name";var O0="service.instance.id";var L0="telemetry.sdk.name",N0="telemetry.sdk.language",D0="telemetry.sdk.version";var nv=_0;var ov=P0;var _c=I0;var iv=O0;var fs=L0,Ss=N0,ys=D0;var k0="nodejs";var av=k0;var ki,Pc=(ki={},ki[fs]="opentelemetry",ki[ov]="node",ki[Ss]=av,ki[ys]=rv,ki);var U0=9,F0=6,B0=Math.pow(10,F0),z0=Math.pow(10,U0);function sv(r){var e=r/1e3,t=Math.trunc(e),n=Math.round(r%1e3*B0);return[t,n]}function lv(r){return r[0]*z0+r[1]}function bs(r){return r[0]*1e6+r[1]/1e3}var _o;(function(r){r[r.SUCCESS=0]="SUCCESS",r[r.FAILED=1]="FAILED"})(_o||(_o={}));var cv=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 H0=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},G0=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))},uv=function(){function r(e,t){this._callback=e,this._that=t,this._isCalled=!1,this._deferred=new cv}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,G0([this._that],H0(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 dr;(function(r){r[r.DELTA=0]="DELTA",r[r.CUMULATIVE=1]="CUMULATIVE"})(dr||(dr={}));var Mt;(function(r){r[r.HISTOGRAM=0]="HISTOGRAM",r[r.EXPONENTIAL_HISTOGRAM=1]="EXPONENTIAL_HISTOGRAM",r[r.GAUGE=2]="GAUGE",r[r.SUM=3]="SUM"})(Mt||(Mt={}));var V0=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 Hie=function(r){V0(e,r);function e(t){var n=r.call(this,t)||this;return Object.setPrototypeOf(n,e.prototype),n}return e}(Error);function dv(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}Le();var mr;(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"})(mr||(mr={}));var mv=function(){function r(){this.kind=mr.DROP}return r.prototype.createAccumulation=function(){},r.prototype.merge=function(e,t){},r.prototype.diff=function(e,t){},r.prototype.toMetricData=function(e,t,n,o){},r}();var me;(function(r){r.COUNTER="COUNTER",r.GAUGE="GAUGE",r.HISTOGRAM="HISTOGRAM",r.UP_DOWN_COUNTER="UP_DOWN_COUNTER",r.OBSERVABLE_COUNTER="OBSERVABLE_COUNTER",r.OBSERVABLE_GAUGE="OBSERVABLE_GAUGE",r.OBSERVABLE_UP_DOWN_COUNTER="OBSERVABLE_UP_DOWN_COUNTER"})(me||(me={}));var W0=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 j0(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 Np=function(){function r(e,t,n,o){n===void 0&&(n=!0),o===void 0&&(o=j0(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=dv(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 Dp=function(){function r(e,t){this._boundaries=e,this._recordMinMax=t,this.kind=mr.HISTOGRAM}return r.prototype.createAccumulation=function(e){return new Np(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 Np(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 Np(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:Mt.HISTOGRAM,dataPoints:n.map(function(i){var a=W0(i,2),s=a[0],c=a[1],l=c.toPointValue(),u=e.type===me.GAUGE||e.type===me.UP_DOWN_COUNTER||e.type===me.OBSERVABLE_GAUGE||e.type===me.OBSERVABLE_UP_DOWN_COUNTER;return{attributes: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}();Le();var kp=function(r,e){var t=typeof Symbol=="function"&&r[Symbol.iterator];if(!t)return r;var n=t.call(r),o,i=[],a;try{for(;(e===void 0||e-- >0)&&!(o=n.next()).done;)i.push(o.value)}catch(s){a={error:s}}finally{try{o&&!o.done&&(t=n.return)&&t.call(n)}finally{if(a)throw a.error}}return i},Up=function(r,e,t){if(t||arguments.length===2)for(var n=0,o=e.length,i;n<o;n++)(i||!(n in e))&&(i||(i=Array.prototype.slice.call(e,0,n)),i[n]=e[n]);return r.concat(i||Array.prototype.slice.call(e))},Fp=function(){function r(e,t,n,o){e===void 0&&(e=new $0),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 $0=function(){function r(e){e===void 0&&(e=[0]),this._counts=e}return Object.defineProperty(r.prototype,"length",{get:function(){return this._counts.length},enumerable:!1,configurable:!0}),r.prototype.countAt=function(e){return this._counts[e]},r.prototype.growTo=function(e,t,n){var o=new Array(e).fill(0);o.splice.apply(o,Up([n,this._counts.length-t],kp(this._counts.slice(t)),!1)),o.splice.apply(o,Up([0,t],kp(this._counts.slice(0,t)),!1)),this._counts=o},r.prototype.reverse=function(e,t){for(var n=Math.floor((e+t)/2)-e,o=0;o<n;o++){var i=this._counts[e+o];this._counts[e+o]=this._counts[t-o-1],this._counts[t-o-1]=i}},r.prototype.emptyBucket=function(e){var t=this._counts[e];return this._counts[e]=0,t},r.prototype.increment=function(e,t){this._counts[e]+=t},r.prototype.decrement=function(e,t){this._counts[e]>=t?this._counts[e]-=t:this._counts[e]=0},r.prototype.clone=function(){return new r(Up([],kp(this._counts),!1))},r}();var pv=52,q0=2146435072,K0=1048575,Bp=1023,Ic=-Bp+1,Oc=Bp,Es=Math.pow(2,-1022);function Lc(r){var e=new DataView(new ArrayBuffer(8));e.setFloat64(0,r);var t=e.getUint32(0),n=(t&q0)>>20;return n-Bp}function Nc(r){var e=new DataView(new ArrayBuffer(8));e.setFloat64(0,r);var t=e.getUint32(0),n=e.getUint32(4),o=(t&K0)*Math.pow(2,32);return o+n}function Ts(r,e){return r===0||r===Number.POSITIVE_INFINITY||r===Number.NEGATIVE_INFINITY||Number.isNaN(r)?r:r*Math.pow(2,e)}function hv(r){return r--,r|=r>>1,r|=r>>2,r|=r>>4,r|=r>>8,r|=r>>16,r++,r}var Y0=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)}}(),Hn=function(r){Y0(e,r);function e(){return r!==null&&r.apply(this,arguments)||this}return e}(Error);var Sv=function(){function r(e){this._shift=-e}return r.prototype.mapToIndex=function(e){if(e<Es)return this._minNormalLowerBoundaryIndex();var t=Lc(e),n=this._rightShift(Nc(e)-1,pv);return t+n>>this._shift},r.prototype.lowerBoundary=function(e){var t=this._minNormalLowerBoundaryIndex();if(e<t)throw new Hn("underflow: "+e+" is < minimum lower boundary: "+t);var n=this._maxNormalLowerBoundaryIndex();if(e>n)throw new Hn("overflow: "+e+" is > maximum lower boundary: "+n);return Ts(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=Ic>>this._shift;return this._shift<2&&e--,e},r.prototype._maxNormalLowerBoundaryIndex=function(){return Oc>>this._shift},r.prototype._rightShift=function(e,t){return Math.floor(e*Math.pow(2,-t))},r}();var yv=function(){function r(e){this._scale=e,this._scaleFactor=Ts(Math.LOG2E,e),this._inverseFactor=Ts(Math.LN2,-e)}return r.prototype.mapToIndex=function(e){if(e<=Es)return this._minNormalLowerBoundaryIndex()-1;if(Nc(e)===0){var t=Lc(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 Hn("overflow: "+e+" is > maximum lower boundary: "+t)}var n=this._minNormalLowerBoundaryIndex();if(e<=n){if(e===n)return Es;if(e===n-1)return Math.exp((e+(1<<this._scale))/this._scaleFactor)/2;throw new Hn("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 Ic<<this._scale},r.prototype._maxNormalLowerBoundaryIndex=function(){return(Oc+1<<this._scale)-1},r}();var bv=-10,Ev=20,X0=Array.from({length:31},function(r,e){return e>10?new yv(e-10):new Sv(e-10)});function zp(r){if(r>Ev||r<bv)throw new Hn("expected scale >= "+bv+" && <= "+Ev+", got: "+r);return X0[r+10]}var J0=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},Dc=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}(),Q0=20,Z0=160,Hp=2,ek=function(){function r(e,t,n,o,i,a,s,c,l,u,d){e===void 0&&(e=e),t===void 0&&(t=Z0),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 Fp),u===void 0&&(u=new Fp),d===void 0&&(d=zp(Q0)),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<Hp&&(W.warn("Exponential Histogram Max Size set to "+this._maxSize+", changing to the minimum size of: "+Hp),this._maxSize=Hp)}return r.prototype.record=function(e){this.updateByIncrement(e,1)},r.prototype.setStartTime=function(e){this.startTime=e},r.prototype.toPointValue=function(){return{hasMinMax:this._recordMinMax,min:this.min,max:this.max,sum:this.sum,positive:{offset:this.positive.offset,bucketCounts:this.positive.counts()},negative:{offset:this.negative.offset,bucketCounts:this.negative.counts()},count:this.count,scale:this.scale,zeroCount:this.zeroCount}},Object.defineProperty(r.prototype,"sum",{get:function(){return this._sum},enumerable:!1,configurable:!0}),Object.defineProperty(r.prototype,"min",{get:function(){return this._min},enumerable:!1,configurable:!0}),Object.defineProperty(r.prototype,"max",{get:function(){return this._max},enumerable:!1,configurable:!0}),Object.defineProperty(r.prototype,"count",{get:function(){return this._count},enumerable:!1,configurable:!0}),Object.defineProperty(r.prototype,"zeroCount",{get:function(){return this._zeroCount},enumerable:!1,configurable:!0}),Object.defineProperty(r.prototype,"scale",{get:function(){return this._count===this._zeroCount?0:this._mapping.scale},enumerable:!1,configurable:!0}),Object.defineProperty(r.prototype,"positive",{get:function(){return this._positive},enumerable:!1,configurable:!0}),Object.defineProperty(r.prototype,"negative",{get:function(){return this._negative},enumerable:!1,configurable:!0}),r.prototype.updateByIncrement=function(e,t){if(!Number.isNaN(e)){if(e>this._max&&(this._max=e),e<this._min&&(this._min=e),this._count+=t,e===0){this._zeroCount+=t;return}this._sum+=e*t,e>0?this._updateBuckets(this._positive,e,t):this._updateBuckets(this._negative,-e,t)}},r.prototype.merge=function(e){this._count===0?(this._min=e.min,this._max=e.max):e.count!==0&&(e.min<this.min&&(this._min=e.min),e.max>this.max&&(this._max=e.max)),this.startTime=e.startTime,this._sum+=e.sum,this._count+=e.count,this._zeroCount+=e.zeroCount;var t=this._minScale(e);this._downscale(this.scale-t),this._mergeBuckets(this.positive,e,e.positive,t),this._mergeBuckets(this.negative,e,e.negative,t)},r.prototype.diff=function(e){this._min=1/0,this._max=-1/0,this._sum-=e.sum,this._count-=e.count,this._zeroCount-=e.zeroCount;var t=this._minScale(e);this._downscale(this.scale-t),this._diffBuckets(this.positive,e,e.positive,t),this._diffBuckets(this.negative,e,e.negative,t)},r.prototype.clone=function(){return new r(this.startTime,this._maxSize,this._recordMinMax,this._sum,this._count,this._zeroCount,this._min,this._max,this.positive.clone(),this.negative.clone(),this._mapping)},r.prototype._updateBuckets=function(e,t,n){var o=this._mapping.mapToIndex(t),i=!1,a=0,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=hv(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=zp(t)}},r.prototype._minScale=function(e){var t=Math.min(this.scale,e.scale),n=Dc.combine(this._highLowAtScale(this.positive,this.scale,t),this._highLowAtScale(e.positive,e.scale,t)),o=Dc.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 Dc(0,-1);var o=t-n;return new Dc(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 Tv=function(){function r(e,t){this._maxSize=e,this._recordMinMax=t,this.kind=mr.EXPONENTIAL_HISTOGRAM}return r.prototype.createAccumulation=function(e){return new ek(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:Mt.EXPONENTIAL_HISTOGRAM,dataPoints:n.map(function(i){var a=J0(i,2),s=a[0],c=a[1],l=c.toPointValue(),u=e.type===me.GAUGE||e.type===me.UP_DOWN_COUNTER||e.type===me.OBSERVABLE_GAUGE||e.type===me.OBSERVABLE_UP_DOWN_COUNTER;return{attributes: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 tk=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},Gp=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=sv(Date.now())},r.prototype.setStartTime=function(e){this.startTime=e},r.prototype.toPointValue=function(){return this._current},r}();var vv=function(){function r(){this.kind=mr.LAST_VALUE}return r.prototype.createAccumulation=function(e){return new Gp(e)},r.prototype.merge=function(e,t){var n=bs(t.sampleTime)>=bs(e.sampleTime)?t:e;return new Gp(e.startTime,n.toPointValue(),n.sampleTime)},r.prototype.diff=function(e,t){var n=bs(t.sampleTime)>=bs(e.sampleTime)?t:e;return new Gp(t.startTime,n.toPointValue(),n.sampleTime)},r.prototype.toMetricData=function(e,t,n,o){return{descriptor:e,aggregationTemporality:t,dataPointType:Mt.GAUGE,dataPoints:n.map(function(i){var a=tk(i,2),s=a[0],c=a[1];return{attributes:s,startTime:c.startTime,endTime:o,value:c.toPointValue()}})}},r}();var rk=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,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 Vp=function(){function r(e){this.monotonic=e,this.kind=mr.SUM}return r.prototype.createAccumulation=function(e){return new vs(e,this.monotonic)},r.prototype.merge=function(e,t){var n=e.toPointValue(),o=t.toPointValue();return t.reset?new vs(t.startTime,this.monotonic,o,t.reset):new vs(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 vs(t.startTime,this.monotonic,o,!0):new vs(t.startTime,this.monotonic,o-n)},r.prototype.toMetricData=function(e,t,n,o){return{descriptor:e,aggregationTemporality:t,dataPointType:Mt.SUM,dataPoints:n.map(function(i){var a=rk(i,2),s=a[0],c=a[1];return{attributes:s,startTime:c.startTime,endTime:o,value:c.toPointValue()}}),isMonotonic:this.monotonic}},r}();var Po=function(){var r=function(e,t){return r=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(n,o){n.__proto__=o}||function(n,o){for(var i in o)Object.prototype.hasOwnProperty.call(o,i)&&(n[i]=o[i])},r(e,t)};return function(e,t){if(typeof t!="function"&&t!==null)throw new TypeError("Class extends value "+String(t)+" is not a constructor or null");r(e,t);function n(){this.constructor=e}e.prototype=t===null?Object.create(t):(n.prototype=t.prototype,new n)}}(),$r=function(){function r(){}return r.Drop=function(){return Pv},r.Sum=function(){return Iv},r.LastValue=function(){return Ov},r.Histogram=function(){return Lv},r.ExponentialHistogram=function(){return nk},r.Default=function(){return ok},r}();var Av=function(r){Po(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 mv,e}($r);var wv=function(r){Po(e,r);function e(){return r!==null&&r.apply(this,arguments)||this}return e.prototype.createAggregator=function(t){switch(t.type){case me.COUNTER:case me.OBSERVABLE_COUNTER:case me.HISTOGRAM:return e.MONOTONIC_INSTANCE;default:return e.NON_MONOTONIC_INSTANCE}},e.MONOTONIC_INSTANCE=new Vp(!0),e.NON_MONOTONIC_INSTANCE=new Vp(!1),e}($r);var Cv=function(r){Po(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 vv,e}($r);var Rv=function(r){Po(e,r);function e(){return r!==null&&r.apply(this,arguments)||this}return e.prototype.createAggregator=function(t){return e.DEFAULT_INSTANCE},e.DEFAULT_INSTANCE=new Dp([0,5,10,25,50,75,100,250,500,750,1e3,2500,5e3,7500,1e4],!0),e}($r);var xv=function(r){Po(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 Dp(this._boundaries,this._recordMinMax)},e}($r);var Mv=function(r){Po(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 Tv(this._maxSize,this._recordMinMax)},e}($r);var _v=function(r){Po(e,r);function e(){return r!==null&&r.apply(this,arguments)||this}return e.prototype._resolve=function(t){switch(t.type){case me.COUNTER:case me.UP_DOWN_COUNTER:case me.OBSERVABLE_COUNTER:case me.OBSERVABLE_UP_DOWN_COUNTER:return Iv;case me.GAUGE:case me.OBSERVABLE_GAUGE:return Ov;case me.HISTOGRAM:return t.advice.explicitBucketBoundaries?new xv(t.advice.explicitBucketBoundaries):Lv}return W.warn("Unable to recognize instrument type: "+t.type),Pv},e.prototype.createAggregator=function(t){return this._resolve(t).createAggregator(t)},e}($r);var Pv=new Av,Iv=new wv,Ov=new Cv,Lv=new Rv,nk=new Mv,ok=new _v;Le();function kc(){return"unknown_service:"+process.argv0}var Gn=function(){return Gn=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},Gn.apply(this,arguments)},ik=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())})},ak=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}}},sk=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},Wp=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[_c]=kc(),e[Ss]=Pc[Ss],e[fs]=Pc[fs],e[ys]=Pc[ys],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 ik(this,void 0,void 0,function(){return ak(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=Gn(Gn({},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=sk(a,2),l=c[0],u=c[1];return Gn(Gn(Gn(Gn({},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 Io;(function(r){r[r.DELTA=0]="DELTA",r[r.CUMULATIVE=1]="CUMULATIVE",r[r.LOWMEMORY=2]="LOWMEMORY"})(Io||(Io={}));Le();var lk=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())})},ck=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}}},jp=function(){return dr.CUMULATIVE},Nv=function(r){switch(r){case me.COUNTER:case me.OBSERVABLE_COUNTER:case me.GAUGE:case me.HISTOGRAM:case me.OBSERVABLE_GAUGE:return dr.DELTA;case me.UP_DOWN_COUNTER:case me.OBSERVABLE_UP_DOWN_COUNTER:return dr.CUMULATIVE}},Dv=function(r){switch(r){case me.COUNTER:case me.HISTOGRAM:return dr.DELTA;case me.GAUGE:case me.UP_DOWN_COUNTER:case me.OBSERVABLE_UP_DOWN_COUNTER:case me.OBSERVABLE_COUNTER:case me.OBSERVABLE_GAUGE:return dr.CUMULATIVE}};function uk(){var r=Tt(),e=r.OTEL_EXPORTER_OTLP_METRICS_TEMPORALITY_PREFERENCE.trim().toLowerCase();return e==="cumulative"?jp:e==="delta"?Nv:e==="lowmemory"?Dv:(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."),jp)}function dk(r){return r!=null?r===Io.DELTA?Nv:r===Io.LOWMEMORY?Dv:jp:uk()}function mk(r){return r?.aggregationPreference?r.aggregationPreference:function(e){return $r.Default()}}var kv=function(){function r(e,t){this._otlpExporter=e,this._aggregationSelector=mk(t),this._aggregationTemporalitySelector=dk(t?.temporalityPreference)}return r.prototype.export=function(e,t){this._otlpExporter.export([e],t)},r.prototype.shutdown=function(){return lk(this,void 0,void 0,function(){return ck(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}();Le();Le();var pk=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},Uv=1e4,Fv=5,Bv=1e3,zv=5e3,Hv=1.5;function As(r){r===void 0&&(r={});var e={};return Object.entries(r).forEach(function(t){var n=pk(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 $p(r,e){return r.endsWith("/")||(r=r+"/"),r+e}function qp(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 Kp(r){return typeof r=="number"?r<=0?Yp(r,Uv):r:gk()}function gk(){var r,e=Number((r=Tt().OTEL_EXPORTER_OTLP_TRACES_TIMEOUT)!==null&&r!==void 0?r:Tt().OTEL_EXPORTER_OTLP_TIMEOUT);return e<=0?Yp(e,Uv):e}function Yp(r,e){return W.warn("Timeout must be greater than 0",r),e}function Gv(r){var e=[429,502,503,504];return e.includes(r)}function Vv(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 Wv=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 uv(this._shutdown,this),this._concurrencyLimit=typeof e.concurrencyLimit=="number"?e.concurrencyLimit:30,this.timeoutMillis=Kp(e.timeoutMillis),this.onInit(e)}return r.prototype.export=function(e,t){if(this._shutdownOnce.isCalled){t({code:_o.FAILED,error:new Error("Exporter has been shutdown")});return}if(this._sendingPromises.length>=this._concurrencyLimit){t({code:_o.FAILED,error:new Error("Concurrent export limit reached")});return}this._export(e).then(function(){t({code:_o.SUCCESS})}).catch(function(n){t({code:_o.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}();Le();import*as Xp from"url";import*as Fc from"http";import*as Bc from"https";import*as jv from"zlib";import{Readable as fk}from"stream";var Vn;(function(r){r.NONE="none",r.GZIP="gzip"})(Vn||(Vn={}));var hk=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)}}(),Ui=function(r){hk(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 Uc=function(){return Uc=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},Uc.apply(this,arguments)};function Jp(r,e,t,n,o){var i=r.timeoutMillis,a=new Xp.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 Ui("Request Timeout");o(h)}else s>=14?l.destroy():l.abort()},i),m={hostname:a.hostname,port:a.port,path:a.pathname,method:"POST",headers:Uc({"Content-Type":t},r.headers),agent:r.agent},p=a.protocol==="http:"?Fc.request:Bc.request,g=function(h,f){switch(h===void 0&&(h=Fv),f===void 0&&(f=Bv),l=p(m,function(b){var w="";b.on("data",function(x){return w+=x}),b.on("aborted",function(){if(u){var x=new Ui("Request Timeout");o(x)}}),b.on("end",function(){if(u===!1)if(b.statusCode&&b.statusCode<299)W.debug("statusCode: "+b.statusCode,w),n(),clearTimeout(d),clearTimeout(c);else if(b.statusCode&&Gv(b.statusCode)&&h>0){var x=void 0;f=Hv*f,b.headers["retry-after"]?x=Vv(b.headers["retry-after"]):x=Math.round(Math.random()*(zv-f)+f),c=setTimeout(function(){g(h-1,f)},x)}else{var A=new Ui(b.statusMessage,b.statusCode,w);o(A),clearTimeout(d),clearTimeout(c)}})}),l.on("error",function(b){if(u){var w=new Ui("Request Timeout",b.code);o(w)}else o(b);clearTimeout(d),clearTimeout(c)}),l.on("abort",function(){if(u){var b=new Ui("Request Timeout");o(b)}clearTimeout(d),clearTimeout(c)}),r.compression){case Vn.GZIP:{l.setHeader("Content-Encoding","gzip");var E=Sk(e);E.on("error",o).pipe(jv.createGzip()).on("error",o).pipe(l);break}default:l.end(Buffer.from(e));break}};g()}function Sk(r){var e=new fk;return e.push(r),e.push(null),e}function Qp(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 Xp.URL(r.url),t=e.protocol==="http:"?Fc.Agent:Bc.Agent;return new t(Uc({keepAlive:!0},r.httpAgentOptions))}catch(n){W.error("collector exporter failed to create http agent. err: "+n.message);return}}function Zp(r){if(r)return r;var e=Tt().OTEL_EXPORTER_OTLP_TRACES_COMPRESSION||Tt().OTEL_EXPORTER_OTLP_COMPRESSION;return e===Vn.GZIP?Vn.GZIP:Vn.NONE}Le();var yk=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)}}(),zc=function(r){yk(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,As(t.headers),Di.parseKeyPairsIntoRecord(Tt().OTEL_EXPORTER_OTLP_HEADERS)),i.agent=Qp(t),i.compression=Zp(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;Jp(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}(Wv);function qv(r){var e=BigInt(1e9);return BigInt(r[0])*e+BigInt(r[1])}function bk(r){var e=Number(BigInt.asUintN(32,r)),t=Number(BigInt.asUintN(32,r>>BigInt(32)));return{low:e,high:t}}function Kv(r){var e=qv(r);return bk(e)}function Ek(r){var e=qv(r);return e.toString()}var Tk=typeof BigInt<"u"?Ek:lv;function $v(r){return r}function Yv(r){if(r!==void 0)return Mc(r)}var vk={encodeHrTime:Kv,encodeSpanContext:Mc,encodeOptionalSpanContext:Yv};function Xv(r){var e,t;if(r===void 0)return vk;var n=(e=r.useLongBits)!==null&&e!==void 0?e:!0,o=(t=r.useHex)!==null&&t!==void 0?t:!1;return{encodeHrTime:n?Kv:Tk,encodeSpanContext:o?$v:Mc,encodeOptionalSpanContext:o?$v:Yv}}var Ak=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 Jv(r){return{name:r.name,version:r.version}}function Fi(r){return Object.keys(r).map(function(e){return Qv(e,r[e])})}function Qv(r,e){return{key:r,value:Zv(e)}}function Zv(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(Zv)}}:e==="object"&&r!=null?{kvlistValue:{values:Object.entries(r).map(function(t){var n=Ak(t,2),o=n[0],i=n[1];return Qv(o,i)})}}:{}}function eA(r){return{attributes:Fi(r.attributes),droppedAttributesCount:0}}Le();function rA(r,e){var t=Xv(e);return{resource:eA(r.resource),schemaUrl:void 0,scopeMetrics:wk(r.scopeMetrics,t)}}function wk(r,e){return Array.from(r.map(function(t){return{scope:Jv(t.scope),metrics:t.metrics.map(function(n){return Ck(n,e)}),schemaUrl:t.scope.schemaUrl}}))}function Ck(r,e){var t={name:r.descriptor.name,description:r.descriptor.description,unit:r.descriptor.unit},n=_k(r.aggregationTemporality);switch(r.dataPointType){case Mt.SUM:t.sum={aggregationTemporality:n,isMonotonic:r.isMonotonic,dataPoints:tA(r,e)};break;case Mt.GAUGE:t.gauge={dataPoints:tA(r,e)};break;case Mt.HISTOGRAM:t.histogram={aggregationTemporality:n,dataPoints:xk(r,e)};break;case Mt.EXPONENTIAL_HISTOGRAM:t.exponentialHistogram={aggregationTemporality:n,dataPoints:Mk(r,e)};break}return t}function Rk(r,e,t){var n={attributes:Fi(r.attributes),startTimeUnixNano:t.encodeHrTime(r.startTime),timeUnixNano:t.encodeHrTime(r.endTime)};switch(e){case qt.INT:n.asInt=r.value;break;case qt.DOUBLE:n.asDouble=r.value;break}return n}function tA(r,e){return r.dataPoints.map(function(t){return Rk(t,r.descriptor.valueType,e)})}function xk(r,e){return r.dataPoints.map(function(t){var n=t.value;return{attributes:Fi(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 Mk(r,e){return r.dataPoints.map(function(t){var n=t.value;return{attributes:Fi(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 _k(r){switch(r){case dr.DELTA:return 1;case dr.CUMULATIVE:return 2}}function nA(r,e){return{resourceMetrics:r.map(function(t){return rA(t,e)})}}var eg={serializeRequest:function(r){var e=nA(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 oA="0.52.1";var iA=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)}}(),Bi=function(){return Bi=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},Bi.apply(this,arguments)},aA="v1/metrics",Pk="http://localhost:4318/"+aA,Ik={"User-Agent":"OTel-OTLP-Exporter-JavaScript/"+oA},Ok=function(r){iA(e,r);function e(t){var n=r.call(this,t,eg,"application/json")||this;return n.headers=Bi(Bi(Bi(Bi({},n.headers),Ik),Di.parseKeyPairsIntoRecord(Tt().OTEL_EXPORTER_OTLP_METRICS_HEADERS)),As(t?.headers)),n}return e.prototype.getDefaultUrl=function(t){return typeof t.url=="string"?t.url:Tt().OTEL_EXPORTER_OTLP_METRICS_ENDPOINT.length>0?qp(Tt().OTEL_EXPORTER_OTLP_METRICS_ENDPOINT):Tt().OTEL_EXPORTER_OTLP_ENDPOINT.length>0?$p(Tt().OTEL_EXPORTER_OTLP_ENDPOINT,aA):Pk},e}(zc),sA=function(r){iA(e,r);function e(t){return r.call(this,new Ok(t),t)||this}return e}(kv);var zi;(function(r){r[r.DELTA=0]="DELTA",r[r.CUMULATIVE=1]="CUMULATIVE"})(zi||(zi={}));var qr;(function(r){r[r.HISTOGRAM=0]="HISTOGRAM",r[r.EXPONENTIAL_HISTOGRAM=1]="EXPONENTIAL_HISTOGRAM",r[r.GAUGE=2]="GAUGE",r[r.SUM=3]="SUM"})(qr||(qr={}));Le();var Lk=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)}}(),lA=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())})},cA=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}}},Nk=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},Dk=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))},kk=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 uA(r){return r!=null}function Hc(r){var e=Object.keys(r);return e.length===0?"":(e=e.sort(),JSON.stringify(e.map(function(t){return[t,r[t]]})))}function dA(r){var e,t;return r.name+":"+((e=r.version)!==null&&e!==void 0?e:"")+":"+((t=r.schemaUrl)!==null&&t!==void 0?t:"")}var tg=function(r){Lk(e,r);function e(t){var n=r.call(this,t)||this;return Object.setPrototypeOf(n,e.prototype),n}return e}(Error);function Wn(r,e){var t,n=new Promise(function(i,a){t=setTimeout(function(){a(new tg("Operation timed out."))},e)});return Promise.race([r,n]).then(function(o){return clearTimeout(t),o},function(o){throw clearTimeout(t),o})}function mA(r){return lA(this,void 0,void 0,function(){var e=this;return cA(this,function(t){return[2,Promise.all(r.map(function(n){return lA(e,void 0,void 0,function(){var o,i;return cA(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 pA(r){return r.status==="rejected"}function rg(r,e){var t=[];return r.forEach(function(n){t.push.apply(t,Dk([],Nk(e(n)),!1))}),t}function gA(r,e){var t,n;if(r.size!==e.size)return!1;try{for(var o=kk(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 hA(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 fA(r,e){return r.toLowerCase()===e.toLowerCase()}Le();var pr;(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"})(pr||(pr={}));var ng=function(){function r(){this.kind=pr.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}();Le();var be;(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"})(be||(be={}));function Kr(r,e,t){var n,o,i,a;return Fk(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:qt.DOUBLE,advice:(a=t?.advice)!==null&&a!==void 0?a:{}}}function SA(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 yA(r,e){return fA(r.name,e.name)&&r.unit===e.unit&&r.type===e.type&&r.valueType===e.valueType}var Uk=/^[a-z][a-z0-9_.\-/]{0,254}$/i;function Fk(r){return r.match(Uk)!=null}var Bk=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 zk(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 Gc=function(){function r(e,t,n,o){n===void 0&&(n=!0),o===void 0&&(o=zk(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=hA(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 Vc=function(){function r(e,t){this._boundaries=e,this._recordMinMax=t,this.kind=pr.HISTOGRAM}return r.prototype.createAccumulation=function(e){return new Gc(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 Gc(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 Gc(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:qr.HISTOGRAM,dataPoints:n.map(function(i){var a=Bk(i,2),s=a[0],c=a[1],l=c.toPointValue(),u=e.type===be.GAUGE||e.type===be.UP_DOWN_COUNTER||e.type===be.OBSERVABLE_GAUGE||e.type===be.OBSERVABLE_UP_DOWN_COUNTER;return{attributes:s,startTime:c.startTime,endTime:o,value:{min:l.hasMinMax?l.min:void 0,max:l.hasMinMax?l.max:void 0,sum:u?void 0:l.sum,buckets:l.buckets,count:l.count}}})}},r}();Le();var og=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},ig=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))},ag=function(){function r(e,t,n,o){e===void 0&&(e=new Hk),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 Hk=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,ig([n,this._counts.length-t],og(this._counts.slice(t)),!1)),o.splice.apply(o,ig([0,t],og(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(ig([],og(this._counts),!1))},r}();var bA=52,Gk=2146435072,Vk=1048575,sg=1023,Wc=-sg+1,jc=sg,ws=Math.pow(2,-1022);function $c(r){var e=new DataView(new ArrayBuffer(8));e.setFloat64(0,r);var t=e.getUint32(0),n=(t&Gk)>>20;return n-sg}function qc(r){var e=new DataView(new ArrayBuffer(8));e.setFloat64(0,r);var t=e.getUint32(0),n=e.getUint32(4),o=(t&Vk)*Math.pow(2,32);return o+n}function Cs(r,e){return r===0||r===Number.POSITIVE_INFINITY||r===Number.NEGATIVE_INFINITY||Number.isNaN(r)?r:r*Math.pow(2,e)}function TA(r){return r--,r|=r>>1,r|=r>>2,r|=r>>4,r|=r>>8,r|=r>>16,r++,r}var Wk=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)}}(),jn=function(r){Wk(e,r);function e(){return r!==null&&r.apply(this,arguments)||this}return e}(Error);var AA=function(){function r(e){this._shift=-e}return r.prototype.mapToIndex=function(e){if(e<ws)return this._minNormalLowerBoundaryIndex();var t=$c(e),n=this._rightShift(qc(e)-1,bA);return t+n>>this._shift},r.prototype.lowerBoundary=function(e){var t=this._minNormalLowerBoundaryIndex();if(e<t)throw new jn("underflow: "+e+" is < minimum lower boundary: "+t);var n=this._maxNormalLowerBoundaryIndex();if(e>n)throw new jn("overflow: "+e+" is > maximum lower boundary: "+n);return Cs(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=Wc>>this._shift;return this._shift<2&&e--,e},r.prototype._maxNormalLowerBoundaryIndex=function(){return jc>>this._shift},r.prototype._rightShift=function(e,t){return Math.floor(e*Math.pow(2,-t))},r}();var wA=function(){function r(e){this._scale=e,this._scaleFactor=Cs(Math.LOG2E,e),this._inverseFactor=Cs(Math.LN2,-e)}return r.prototype.mapToIndex=function(e){if(e<=ws)return this._minNormalLowerBoundaryIndex()-1;if(qc(e)===0){var t=$c(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 jn("overflow: "+e+" is > maximum lower boundary: "+t)}var n=this._minNormalLowerBoundaryIndex();if(e<=n){if(e===n)return ws;if(e===n-1)return Math.exp((e+(1<<this._scale))/this._scaleFactor)/2;throw new jn("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 Wc<<this._scale},r.prototype._maxNormalLowerBoundaryIndex=function(){return(jc+1<<this._scale)-1},r}();var CA=-10,RA=20,jk=Array.from({length:31},function(r,e){return e>10?new wA(e-10):new AA(e-10)});function lg(r){if(r>RA||r<CA)throw new jn("expected scale >= "+CA+" && <= "+RA+", got: "+r);return jk[r+10]}var $k=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},Kc=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}(),qk=20,Kk=160,cg=2,xA=function(){function r(e,t,n,o,i,a,s,c,l,u,d){e===void 0&&(e=e),t===void 0&&(t=Kk),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 ag),u===void 0&&(u=new ag),d===void 0&&(d=lg(qk)),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<cg&&(W.warn("Exponential Histogram Max Size set to "+this._maxSize+", changing to the minimum size of: "+cg),this._maxSize=cg)}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=TA(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=lg(t)}},r.prototype._minScale=function(e){var t=Math.min(this.scale,e.scale),n=Kc.combine(this._highLowAtScale(this.positive,this.scale,t),this._highLowAtScale(e.positive,e.scale,t)),o=Kc.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 Kc(0,-1);var o=t-n;return new Kc(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 ug=function(){function r(e,t){this._maxSize=e,this._recordMinMax=t,this.kind=pr.EXPONENTIAL_HISTOGRAM}return r.prototype.createAccumulation=function(e){return new xA(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:qr.EXPONENTIAL_HISTOGRAM,dataPoints:n.map(function(i){var a=$k(i,2),s=a[0],c=a[1],l=c.toPointValue(),u=e.type===be.GAUGE||e.type===be.UP_DOWN_COUNTER||e.type===be.OBSERVABLE_GAUGE||e.type===be.OBSERVABLE_UP_DOWN_COUNTER;return{attributes:s,startTime:c.startTime,endTime:o,value:{min:l.hasMinMax?l.min:void 0,max:l.hasMinMax?l.max:void 0,sum:u?void 0:l.sum,positive:{offset:l.positive.offset,bucketCounts:l.positive.bucketCounts},negative:{offset:l.negative.offset,bucketCounts:l.negative.bucketCounts},count:l.count,scale:l.scale,zeroCount:l.zeroCount}}})}},r}();Le();var Yk=Tp("OpenTelemetry SDK Context Key SUPPRESS_TRACING");function MA(r){return r.setValue(Yk,!0)}Le();function _A(){return function(r){W.error(Xk(r))}}function Xk(r){return typeof r=="string"?r:JSON.stringify(Jk(r))}function Jk(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 Qk=_A();function Yc(r){try{Qk(r)}catch{}}var PA="1.30.1";var Zk="process.runtime.name";var eU="service.name";var tU="telemetry.sdk.name",rU="telemetry.sdk.language",nU="telemetry.sdk.version";var IA=Zk;var OA=eU;var Rs=tU,xs=rU,Ms=nU;var oU="nodejs";var LA=oU;var Hi,Oo=(Hi={},Hi[Rs]="opentelemetry",Hi[IA]="node",Hi[xs]=LA,Hi[Ms]=PA,Hi);function _s(r){r.unref()}var dU=9,mU=6,pU=Math.pow(10,mU),jle=Math.pow(10,dU);function Lo(r){var e=r/1e3,t=Math.trunc(e),n=Math.round(r%1e3*pU);return[t,n]}function Gi(r){return r[0]*1e6+r[1]/1e3}var Ps;(function(r){r[r.SUCCESS=0]="SUCCESS",r[r.FAILED=1]="FAILED"})(Ps||(Ps={}));Le();function NA(r,e){return new Promise(function(t){Ni.with(MA(Ni.active()),function(){r.export(e,function(n){t(n)})})})}var DA={_export:NA};var gU=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},Xc=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=Lo(Date.now())},r.prototype.setStartTime=function(e){this.startTime=e},r.prototype.toPointValue=function(){return this._current},r}();var dg=function(){function r(){this.kind=pr.LAST_VALUE}return r.prototype.createAccumulation=function(e){return new Xc(e)},r.prototype.merge=function(e,t){var n=Gi(t.sampleTime)>=Gi(e.sampleTime)?t:e;return new Xc(e.startTime,n.toPointValue(),n.sampleTime)},r.prototype.diff=function(e,t){var n=Gi(t.sampleTime)>=Gi(e.sampleTime)?t:e;return new Xc(t.startTime,n.toPointValue(),n.sampleTime)},r.prototype.toMetricData=function(e,t,n,o){return{descriptor:e,aggregationTemporality:t,dataPointType:qr.GAUGE,dataPoints:n.map(function(i){var a=gU(i,2),s=a[0],c=a[1];return{attributes:s,startTime:c.startTime,endTime:o,value:c.toPointValue()}})}},r}();var hU=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},Vi=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 Jc=function(){function r(e){this.monotonic=e,this.kind=pr.SUM}return r.prototype.createAccumulation=function(e){return new Vi(e,this.monotonic)},r.prototype.merge=function(e,t){var n=e.toPointValue(),o=t.toPointValue();return t.reset?new Vi(t.startTime,this.monotonic,o,t.reset):new Vi(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 Vi(t.startTime,this.monotonic,o,!0):new Vi(t.startTime,this.monotonic,o-n)},r.prototype.toMetricData=function(e,t,n,o){return{descriptor:e,aggregationTemporality:t,dataPointType:qr.SUM,dataPoints:n.map(function(i){var a=hU(i,2),s=a[0],c=a[1];return{attributes:s,startTime:c.startTime,endTime:o,value:c.toPointValue()}}),isMonotonic:this.monotonic}},r}();var No=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)}}(),gr=function(){function r(){}return r.Drop=function(){return GA},r.Sum=function(){return VA},r.LastValue=function(){return WA},r.Histogram=function(){return jA},r.ExponentialHistogram=function(){return fU},r.Default=function(){return SU},r}();var kA=function(r){No(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 ng,e}(gr);var UA=function(r){No(e,r);function e(){return r!==null&&r.apply(this,arguments)||this}return e.prototype.createAggregator=function(t){switch(t.type){case be.COUNTER:case be.OBSERVABLE_COUNTER:case be.HISTOGRAM:return e.MONOTONIC_INSTANCE;default:return e.NON_MONOTONIC_INSTANCE}},e.MONOTONIC_INSTANCE=new Jc(!0),e.NON_MONOTONIC_INSTANCE=new Jc(!1),e}(gr);var FA=function(r){No(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 dg,e}(gr);var BA=function(r){No(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 Vc([0,5,10,25,50,75,100,250,500,750,1e3,2500,5e3,7500,1e4],!0),e}(gr);var Is=function(r){No(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 Vc(this._boundaries,this._recordMinMax)},e}(gr);var zA=function(r){No(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 ug(this._maxSize,this._recordMinMax)},e}(gr);var HA=function(r){No(e,r);function e(){return r!==null&&r.apply(this,arguments)||this}return e.prototype._resolve=function(t){switch(t.type){case be.COUNTER:case be.UP_DOWN_COUNTER:case be.OBSERVABLE_COUNTER:case be.OBSERVABLE_UP_DOWN_COUNTER:return VA;case be.GAUGE:case be.OBSERVABLE_GAUGE:return WA;case be.HISTOGRAM:return t.advice.explicitBucketBoundaries?new Is(t.advice.explicitBucketBoundaries):jA}return W.warn("Unable to recognize instrument type: "+t.type),GA},e.prototype.createAggregator=function(t){return this._resolve(t).createAggregator(t)},e}(gr);var GA=new kA,VA=new UA,WA=new FA,jA=new BA,fU=new zA,SU=new HA;var $A=function(r){return gr.Default()},qA=function(r){return zi.CUMULATIVE};var mg=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())})},pg=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}}},KA=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},yU=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))},YA=function(){function r(e){var t,n,o;this._shutdown=!1,this._aggregationSelector=(t=e?.aggregationSelector)!==null&&t!==void 0?t:$A,this._aggregationTemporalitySelector=(n=e?.aggregationTemporalitySelector)!==null&&n!==void 0?n:qA,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 mg(this,void 0,void 0,function(){var t,n,o,i,a,s;return pg(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(yU([this._sdkMetricProducer.collect({timeoutMillis:e?.timeoutMillis})],KA(this._metricProducers.map(function(l){return l.collect({timeoutMillis:e?.timeoutMillis})})),!1))];case 1:return t=KA.apply(void 0,[c.sent()]),n=t[0],o=t.slice(1),i=n.errors.concat(rg(o,function(l){return l.errors})),a=n.resourceMetrics.resource,s=n.resourceMetrics.scopeMetrics.concat(rg(o,function(l){return l.resourceMetrics.scopeMetrics})),[2,{resourceMetrics:{resource:a,scopeMetrics:s},errors:i}]}})})},r.prototype.shutdown=function(e){return mg(this,void 0,void 0,function(){return pg(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,Wn(this.onShutdown(),e.timeoutMillis)];case 3:t.sent(),t.label=4;case 4:return this._shutdown=!0,[2]}})})},r.prototype.forceFlush=function(e){return mg(this,void 0,void 0,function(){return pg(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,Wn(this.onForceFlush(),e.timeoutMillis)];case 3:return t.sent(),[2]}})})},r}();Le();var bU=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)}}(),Qc=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())})},Zc=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}}},EU=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},TU=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))},gg=function(r){bU(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 Qc(this,void 0,void 0,function(){var t;return Zc(this,function(n){switch(n.label){case 0:return n.trys.push([0,2,,3]),[4,Wn(this._doRun(),this._exportTimeout)];case 1:return n.sent(),[3,3];case 2:return t=n.sent(),t instanceof tg?(W.error("Export took longer than %s milliseconds and timed out.",this._exportTimeout),[2]):(Yc(t),[3,3]);case 3:return[2]}})})},e.prototype._doRun=function(){var t,n;return Qc(this,void 0,void 0,function(){var o,i,a,s,c,l;return Zc(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,TU(["PeriodicExportingMetricReader: metrics collection errors"],EU(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),Yc(s),[3,5];case 5:return i.scopeMetrics.length===0?[2]:[4,DA._export(this._exporter,i)];case 6:if(c=u.sent(),c.code!==Ps.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),_s(this._interval)},e.prototype.onForceFlush=function(){return Qc(this,void 0,void 0,function(){return Zc(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 Qc(this,void 0,void 0,function(){return Zc(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}(YA);Le();Le();function eu(){return"unknown_service:"+process.argv0}var $n=function(){return $n=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},$n.apply(this,arguments)},vU=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())})},AU=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}}},wU=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},tu=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[OA]=eu(),e[xs]=Oo[xs],e[Rs]=Oo[Rs],e[Ms]=Oo[Ms],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 vU(this,void 0,void 0,function(){return AU(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=$n($n({},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=wU(a,2),l=c[0],u=c[1];return $n($n($n($n({},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 XA=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}();Le();var Do=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)}}(),ru=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=Ni.active()),typeof e!="number"){W.warn("non-number value provided to metric "+this._descriptor.name+": "+e);return}this._descriptor.valueType===qt.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,Lo(Date.now()))},r}();var JA=function(r){Do(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}(ru);var QA=function(r){Do(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}(ru);var ZA=function(r){Do(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}(ru);var ew=function(r){Do(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}(ru);var nu=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 tw=function(r){Do(e,r);function e(){return r!==null&&r.apply(this,arguments)||this}return e}(nu);var rw=function(r){Do(e,r);function e(){return r!==null&&r.apply(this,arguments)||this}return e}(nu);var nw=function(r){Do(e,r);function e(){return r!==null&&r.apply(this,arguments)||this}return e}(nu);function Os(r){return r instanceof nu}var ow=function(){function r(e){this._meterSharedState=e}return r.prototype.createGauge=function(e,t){var n=Kr(e,be.GAUGE,t),o=this._meterSharedState.registerMetricStorage(n);return new ZA(o,n)},r.prototype.createHistogram=function(e,t){var n=Kr(e,be.HISTOGRAM,t),o=this._meterSharedState.registerMetricStorage(n);return new ew(o,n)},r.prototype.createCounter=function(e,t){var n=Kr(e,be.COUNTER,t),o=this._meterSharedState.registerMetricStorage(n);return new QA(o,n)},r.prototype.createUpDownCounter=function(e,t){var n=Kr(e,be.UP_DOWN_COUNTER,t),o=this._meterSharedState.registerMetricStorage(n);return new JA(o,n)},r.prototype.createObservableGauge=function(e,t){var n=Kr(e,be.OBSERVABLE_GAUGE,t),o=this._meterSharedState.registerAsyncMetricStorage(n);return new rw(n,o,this._meterSharedState.observableRegistry)},r.prototype.createObservableCounter=function(e,t){var n=Kr(e,be.OBSERVABLE_COUNTER,t),o=this._meterSharedState.registerAsyncMetricStorage(n);return new tw(n,o,this._meterSharedState.observableRegistry)},r.prototype.createObservableUpDownCounter=function(e,t){var n=Kr(e,be.OBSERVABLE_UP_DOWN_COUNTER,t),o=this._meterSharedState.registerAsyncMetricStorage(n);return new nw(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 ou=function(){function r(e){this._instrumentDescriptor=e}return r.prototype.getInstrumentDescriptor=function(){return this._instrumentDescriptor},r.prototype.updateDescription=function(e){this._instrumentDescriptor=Kr(this._instrumentDescriptor.name,this._instrumentDescriptor.type,{description:e,valueType:this._instrumentDescriptor.valueType,unit:this._instrumentDescriptor.unit,advice:this._instrumentDescriptor.advice})},r}();var CU=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)}}(),iw=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}}},RU=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 iw(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 iw(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 Rr=function(r){CU(e,r);function e(){return r.call(this,Hc)||this}return e}(RU);var xU=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},iu=function(){function r(e,t){this._aggregator=e,this._activeCollectionStorage=new Rr,this._cumulativeMemoStorage=new Rr,this._overflowAttributes={"otel.metric.overflow":!0},this._cardinalityLimit=(t??2e3)-1,this._overflowHashCode=Hc(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=xU(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 m=n._activeCollectionStorage.get(a,c);u=n._aggregator.merge(m,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 Rr,e},r}();var hg=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.")},aw=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},au=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===zi.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=MU(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=hg(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 Rr,i=this._unreportedAccumulations.get(e);if(this._unreportedAccumulations.set(e,[]),i===void 0)return o;try{for(var a=hg(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=aw(a.value,3),c=s[0],l=s[1],u=s[2];if(e.has(c,u)){var d=e.get(c,u),m=n.merge(d,l);o.set(c,m,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=hg(e.keys()),s=a.next();!s.done;s=a.next()){var c=aw(s.value,2),l=c[0],u=c[1],d=t.get(l,u);d?.setStartTime(n)}}catch(m){o={error:m}}finally{try{s&&!s.done&&(i=a.return)&&i.call(a)}finally{if(o)throw o.error}}return t},r}();function MU(r){return Array.from(r.entries())}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)}}(),PU=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},sw=function(r){_U(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 iu(n,s._aggregationCardinalityLimit),s._temporalMetricStorage=new au(n,i),s}return e.prototype.record=function(t,n){var o=this,i=new Rr;Array.from(t.entries()).forEach(function(a){var s=PU(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}(ou);Le();function fg(r,e){var t="";return r.unit!==e.unit&&(t+=" - Unit '"+r.unit+"' does not match '"+e.unit+`'
27
+ `),globalThis.console=e}}var gp=" ".repeat(6);import lD from"fetch-retry";import cD from"os";import uT,{multistream as uD}from"pino";import dD from"pino-pretty";import mD from"pino-std-serializers";var Mi=new Map,pD=!0,dT="Log throttle exceeded",gD=100,hD=5e3,fD=lD(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}}),hp=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??cD.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=pD?uT(a):uT(a,uD([{stream:dD({colorize:!0})}]))}child(e){return new r({bindings:{...this.bindingAttributes,...e},hostname:this.hostname,disableConsoleLogs:this.disableConsoleLogs,flushIntervalMs:this.flushIntervalMs,maxBatchSize:this.maxBatchSize})}async flush(){await this.flushBuffer(),this.disableConsoleLogs||this.consoleLogger.flush()}scheduleFlush(){this.flushTimer||(this.flushTimer=setTimeout(()=>{this.flushTimer=void 0,this.flushBuffer()},this.flushIntervalMs))}async flushBuffer(){if(this.buffer.length===0)return;let e=this.buffer;this.buffer=[];try{let t=await fD(this.site,{method:"POST",headers:{"Content-Type":"application/json","signoz-access-token":"CumAaTMUcwjt05OddAmefKgshbhfRmWxzxih"},body:Ro(e),signal:AbortSignal.timeout(5e3)});if(!t.ok)throw new Error(`Got error status (${t.statusText}) from SigNoz`)}catch{}}shouldAllowLog(e){if(e===dT)return!0;let t=Date.now();return t-this.lastWindowStart>hD&&(this.logsInCurrentWindow=0,this.droppedLogsInWindow&&this.log("error",void 0,dT),this.droppedLogsInWindow=!1,this.lastWindowStart=t),this.logsInCurrentWindow<gD?(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(os[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=mD.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:Kb({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,Mi.set("app",this),Mi.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=Yb[e]):(this.minLevelValue=os[e],this.consoleLogger.level=e)}enableConsoleLogs(){this.disableConsoleLogs=!1}},_i=({app:r,hostname:e,disableConsoleLogs:t})=>(Mi.has(r)||Mi.set(r,new hp({bindings:{app:r},hostname:e,disableConsoleLogs:t})),Mi.get(r));async function mT(){await Promise.all([...Mi.values()].map(r=>r.flush()))}import{hostname as SD}from"os";var ur=_i({app:"cli",hostname:SD(),disableConsoleLogs:!0}).child({cliVersion:"0.16.3"});function fp(r){if(!r)return;r=r.toLowerCase();let e=cc.safeParse(r);if(e.success)return C.setMinLevel(e.data),e.data}function pT({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 cT(()=>{if(c.forEach(u=>{C.log(""),o(u)}),c.length){C.log("");let u=c.length===1?"":"s";C.error(`${c.length} ${t}${u} failed:`),c.forEach(d=>{C.dimmed(n(d))})}if(l.length){C.log("");let u=l.length===1?"":"s";C.warn(`${l.length} ${t}${u} cancelled:`),l.forEach(d=>{C.dimmed(n(d))})}if(a.length){C.log("");let u=a.length===1?"":"s";C.success(`${a.length} ${t}${u} passed:`),a.forEach(d=>{C.dimmed(n(d))})}if(s.length){C.log("");let u=s.length===1?"":"s";C.warn(`${s.length} quarantined ${t}${u} failed:`),s.forEach(d=>{C.dimmed(n(d))})}if(i.length){C.log("");let u=i.length===1?"":"s";C.warn(`${i.length} quarantined ${t}${u} passed:`),i.forEach(d=>{C.dimmed(n(d))})}C.log(""),C.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 ls=({status:r,testLogRef:e,getRunningTestsCount:t,getTotalTestsCount:n,additionalText:o})=>{r=r.toUpperCase();let i=r,a;r.includes("FAIL")?(i=Pi.bgRed.white("FAIL"),a=3):r.includes("PASS")?(i=Pi.bgGreen.white("PASS"),a=3):r.includes("START")?(i=Pi.bgBlue.white("START"),a=2):r.includes("CANCEL")?(i=Pi.bgRgb(191,68,11).white("CANCEL"),a=1):r.includes("RETRY")?(i=Pi.bgRgb(191,68,11).white("RETRY"),a=2):r.includes("RUN")||r.includes("PROG")?(i=Pi.bgMagenta.white("RUNNING"),a=0):(C.warn(`Unknown status tried to be logged in run test locally: ${r}`),a=0),yD||(i=`${i}`),C.log(`${i}${" ".repeat(a)} ${e} ${o?`${o} `:""}(${t()}/${n()})`)};import bD from"fs";import{tmpdir as ED}from"os";import TD from"path";import{registry as cs}from"playwright-core/lib/server";import gT from"proper-lockfile";var hT=TD.join(ED(),"momenticBrowserInstallation");var Sp=["chrome","chromium","chrome-for-testing","ffmpeg"],vD={Chromium:"chromium","Google Chrome":"chrome","Chrome for Testing":"chrome-for-testing"},fT={chrome:"chrome",chromium:"chromium","chrome-for-testing":"chromium-headless-shell",ffmpeg:"ffmpeg"};function ST(r){if(r==="Org Default")return!1;let e=fT[vD[r]??""]??"",t=cs.findExecutable(e);return!t||t.installType==="none"?!1:yp(t)}function yp(r){let e=r.executablePath();return bD.existsSync(e)}function AD(r,e){let t=fT[r];if(!t)throw new Error(`Requested install of unknown browser type ${r}`);let n=cs.findExecutable(t);if(!n||n.installType==="none")throw new Error(`Requested install of unknown browser type ${r}`);if(!(!e&&yp(n)))return n}async function wD({browser:r,force:e}){let t=AD(r,e);if(!t){C.info(`Browser '${r}' is already installed, skipping...`);return}C.info(`Installing browser '${r}'...`);try{await cs.installDeps([t],!1),await cs.install([t],!1)}catch(n){if(n.message.includes("Lock file is already being held")){C.warn("Another process is installing Playwright browsers. Waiting for completion before proceeding..");let o=cs.findExecutable(r),i=5*60*1e3,a=Date.now();for(;Date.now()-a<i&&!yp(o);)C.info("Waiting for browser to finish installing..."),await new Promise(s=>setTimeout(s,5e3))}else throw n}}async function yc({rawBrowsers:r,force:e=!1,all:t=!1}){let n=t?Sp:Array.from(new Set(r));try{await gT.lock(hT,{stale:1e3*60*5,update:1e3*60,realpath:!1,retries:{retries:30,factor:2,maxTimeout:15e3,minTimeout:500}})}catch(i){C.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 wD({browser:i,force:e})}catch(a){o=a,C.error(`Failed to install the ${i} browser: ${a}`)}}finally{await gT.unlock(hT,{realpath:!1})}if(o)throw o}import{createServer as CD}from"http";async function bc(r,e,t=30){for(let n=0;n<t;n+=1){let o=r+n;if(await Ec(o))return o}C.error(`Could not find an available port for ${e} starting from ${r} after ${t} attempts`),process.exit(1)}async function Ec(r){return new Promise((e,t)=>{let n=CD();n.once("error",o=>{o.code==="EADDRINUSE"?e(!1):(C.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 Mre from"blocked-at";import Pre from"why-is-node-running";function yT(r){let e=r?.shardIndex??1,t=r?.shardCount??1;if(e<1)throw new Error("Shard index must be greater than 0.");if(t<1)throw new Error("Shard count must be greater than 0.");if(e>t)throw new Error("Shard index cannot be greater than shard count")}function RD(r,e,t,n){if(t>r.length&&(C.warn(`Shard count ${t} is greater than the number of tests ${r.length}! Some workers won't have any tests to run.`),t=Math.max(t,r.length),e>t))return[];let o=Math.floor((e-1)*(r.length/t)),i=Math.floor(e*(r.length/t));return(n?[...r].sort((s,c)=>n(s).localeCompare(n(c))):[...r].sort()).filter((s,c)=>c>=o&&c<i)}function bT(r){let{items:e,shardIndex:t,shardCount:n,sortKey:o}=r;return n>1?RD(e,t,n,o):e}import BF from"fs";import Wre,{multistream as $re}from"pino";import Kre from"pino-pretty";var Jre=5*1024,xD="...[truncated]",Qre=Buffer.byteLength(xD,"utf8");import{PostHog as lne}from"posthog-node";var zn=class extends Error{constructor(e){super(e),this.name="TimeoutError"}};var ET=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((s,c)=>{let l;if(e.signal){let{signal:m}=e;if(m.aborted)return c(ET(m));l=()=>c(ET(m)),m.addEventListener("abort",l,{once:!0})}let u=()=>{if(e.signal&&e.signal.removeEventListener("abort",l),n)try{s(n())}catch(m){c(m)}else{typeof r.cancel=="function"&&Promise.resolve().then(()=>r.cancel()).catch(()=>{});let m=o instanceof Error?o:new zn(o??`Promise timed out after ${t}ms`);c(m)}};t<1/0&&(a=i.setTimeout(u,t));let d=()=>{i.clearTimeout(a),e.signal&&e.signal.removeEventListener("abort",l)};Promise.resolve(r).then(m=>{d(),s(m)}).catch(m=>{d(),c(m)})})}import{PostHog as Sne}from"posthog-node";import{execSync as MD}from"child_process";import Ii from"os";import _D from"v8";var TT,Wr,AT=Ii.platform(),PD=Ii.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),{}),vT=r=>{try{let e={},t=!1,n=ID(),o=OD(),i=`${Math.round(n.freePercentage*100)}%`;n.freePercentage<.05&&(Object.assign(e,process.memoryUsage()),t=!0);let a=`${o?Math.round(o.idle):"unknown"}%`;o&&o?.total>80&&(t=!0);let s=_D.getHeapStatistics(),c=s.used_heap_size,l=s.heap_size_limit;c/l>.9&&(t=!0),t?(r.warn({memory:n,cpu:o,heapStats:s,...e},"Critical resource usage metrics detected"),xo&&C.warn(`Low machine resources detected (memory: ${i} free, cpu: ${a} free)`)):r.debug({memory:n,cpu:o},"Got machine resource usage metrics")}catch{}};function wT(r){if(!Cr)return vT(r),{interval:setInterval(()=>vT(r),2e4),cpuMetadata:PD,platform:AT}}function ID(){let r=Ii.totalmem(),e=AT==="darwin"?LD():(()=>{let n=Ii.freemem();return{availableMemory:n,rawFreeMemory:n,cachedMemory:0}})(),t=e.availableMemory/r;return{totalMemory:r,freeMemory:e.availableMemory,freePercentage:t}}function OD(){let r=Ii.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,!Wr)return Wr=t,null;let n={user:t.user-Wr.user,nice:t.nice-Wr.nice,sys:t.sys-Wr.sys,idle:t.idle-Wr.idle,irq:t.irq-Wr.irq,total:t.total-Wr.total};return TT={measurementTime:e,intervalMs:e-Wr.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},Wr=t,TT}function LD(){try{let r=MD("/usr/bin/vm_stat",{encoding:"utf8",stdio:["pipe","pipe","ignore"]}),t=r.match(/page size of (\d+) bytes/)?.[1],n=t?Number.parseInt(t,10):4096,o=u=>{let m=r.match(new RegExp(`${u}:\\s+(\\d+)\\.`,"i"))?.[1];return m?Number.parseInt(m,10):0},i=o("Pages free"),a=o("Pages inactive"),s=o("Pages speculative"),c=i*n,l=(a+s)*n;return{availableMemory:c+l,rawFreeMemory:c,cachedMemory:l}}catch{let e=Ii.freemem();return{availableMemory:e,rawFreeMemory:e,cachedMemory:0}}}var Tc=class{increment(e,t,n){}gauge(e,t){}distribution(e,t,n){}async flush(){}async recordDuration({fn:e}){return await e()}};function ND(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 vc(r,e){let t=ND(r);return!e||Object.keys(e).length===0?t:{...e,...t}}var JT="=",Rc=";",Pp=",";var QT=8192;var Di={};V_(Di,{getKeyPairs:()=>p0,parseKeyPairsIntoRecord:()=>g0,parsePairKeyValue:()=>ZT,serializeKeyPairs:()=>m0});Le();var d0=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 m0(r){return r.reduce(function(e,t){var n=""+e+(e!==""?Pp:"")+t;return n.length>QT?e:n},"")}function p0(r){return r.getAllEntries().map(function(e){var t=d0(e,2),n=t[0],o=t[1],i=encodeURIComponent(n)+"="+encodeURIComponent(o.value);return o.metadata!==void 0&&(i+=Rc+o.metadata.toString()),i})}function ZT(r){var e=r.split(Rc);if(!(e.length<=0)){var t=e.shift();if(t){var n=t.indexOf(JT);if(!(n<=0)){var o=decodeURIComponent(t.substring(0,n).trim()),i=decodeURIComponent(t.substring(n+1).trim()),a;return e.length>0&&(a=Ep(e.join(Rc))),{key:o,value:i,metadata:a}}}}}function g0(r){return typeof r!="string"||r.length===0?{}:r.split(Pp).map(function(e){return ZT(e)}).filter(function(e){return e!==void 0&&e.value.length>0}).reduce(function(e,t){return e[t.key]=t.value,e},{})}Le();var xc;(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"})(xc||(xc={}));var h0=",",f0=["OTEL_SDK_DISABLED"];function S0(r){return f0.indexOf(r)>-1}var y0=["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 b0(r){return y0.indexOf(r)>-1}var E0=["OTEL_NO_PATCH_MODULES","OTEL_PROPAGATORS"];function T0(r){return E0.indexOf(r)>-1}var Ip=1/0,Op=128,v0=128,A0=128,Lp={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:Fe.INFO,OTEL_NO_PATCH_MODULES:[],OTEL_PROPAGATORS:["tracecontext","baggage"],OTEL_RESOURCE_ATTRIBUTES:"",OTEL_SERVICE_NAME:"",OTEL_ATTRIBUTE_VALUE_LENGTH_LIMIT:Ip,OTEL_ATTRIBUTE_COUNT_LIMIT:Op,OTEL_SPAN_ATTRIBUTE_VALUE_LENGTH_LIMIT:Ip,OTEL_SPAN_ATTRIBUTE_COUNT_LIMIT:Op,OTEL_LOGRECORD_ATTRIBUTE_VALUE_LENGTH_LIMIT:Ip,OTEL_LOGRECORD_ATTRIBUTE_COUNT_LIMIT:Op,OTEL_SPAN_EVENT_COUNT_LIMIT:128,OTEL_SPAN_LINK_COUNT_LIMIT:128,OTEL_SPAN_ATTRIBUTE_PER_EVENT_COUNT_LIMIT:v0,OTEL_SPAN_ATTRIBUTE_PER_LINK_COUNT_LIMIT:A0,OTEL_TRACES_EXPORTER:"",OTEL_TRACES_SAMPLER:xc.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 w0(r,e,t){if(!(typeof t[r]>"u")){var n=String(t[r]);e[r]=n.toLowerCase()==="true"}}function C0(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 R0(r,e,t,n){n===void 0&&(n=h0);var o=t[r];typeof o=="string"&&(e[r]=o.split(n).map(function(i){return i.trim()}))}var x0={ALL:Fe.ALL,VERBOSE:Fe.VERBOSE,DEBUG:Fe.DEBUG,INFO:Fe.INFO,WARN:Fe.WARN,ERROR:Fe.ERROR,NONE:Fe.NONE};function M0(r,e,t){var n=t[r];if(typeof n=="string"){var o=x0[n.toUpperCase()];o!=null&&(e[r]=o)}}function ev(r){var e={};for(var t in Lp){var n=t;switch(n){case"OTEL_LOG_LEVEL":M0(n,e,r);break;default:if(S0(n))w0(n,e,r);else if(b0(n))C0(n,e,r);else if(T0(n))R0(n,e,r);else{var o=r[n];typeof o<"u"&&o!==null&&(e[n]=String(o))}}}return e}function Tt(){var r=ev(process.env);return Object.assign({},Lp,r)}function tv(r){return r>=48&&r<=57?r-48:r>=97&&r<=102?r-87:r-55}function Mc(r){for(var e=new Uint8Array(r.length/2),t=0,n=0;n<r.length;n+=2){var o=tv(r.charCodeAt(n)),i=tv(r.charCodeAt(n+1));e[t++]=o<<4|i}return e}var rv="1.25.1";var _0="deployment.environment";var P0="process.runtime.name";var I0="service.name";var O0="service.instance.id";var L0="telemetry.sdk.name",N0="telemetry.sdk.language",D0="telemetry.sdk.version";var nv=_0;var ov=P0;var _c=I0;var iv=O0;var fs=L0,Ss=N0,ys=D0;var k0="nodejs";var av=k0;var ki,Pc=(ki={},ki[fs]="opentelemetry",ki[ov]="node",ki[Ss]=av,ki[ys]=rv,ki);var U0=9,F0=6,B0=Math.pow(10,F0),z0=Math.pow(10,U0);function sv(r){var e=r/1e3,t=Math.trunc(e),n=Math.round(r%1e3*B0);return[t,n]}function lv(r){return r[0]*z0+r[1]}function bs(r){return r[0]*1e6+r[1]/1e3}var _o;(function(r){r[r.SUCCESS=0]="SUCCESS",r[r.FAILED=1]="FAILED"})(_o||(_o={}));var cv=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 H0=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},G0=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))},uv=function(){function r(e,t){this._callback=e,this._that=t,this._isCalled=!1,this._deferred=new cv}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,G0([this._that],H0(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 dr;(function(r){r[r.DELTA=0]="DELTA",r[r.CUMULATIVE=1]="CUMULATIVE"})(dr||(dr={}));var Mt;(function(r){r[r.HISTOGRAM=0]="HISTOGRAM",r[r.EXPONENTIAL_HISTOGRAM=1]="EXPONENTIAL_HISTOGRAM",r[r.GAUGE=2]="GAUGE",r[r.SUM=3]="SUM"})(Mt||(Mt={}));var V0=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 Hie=function(r){V0(e,r);function e(t){var n=r.call(this,t)||this;return Object.setPrototypeOf(n,e.prototype),n}return e}(Error);function dv(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}Le();var mr;(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"})(mr||(mr={}));var mv=function(){function r(){this.kind=mr.DROP}return r.prototype.createAccumulation=function(){},r.prototype.merge=function(e,t){},r.prototype.diff=function(e,t){},r.prototype.toMetricData=function(e,t,n,o){},r}();var me;(function(r){r.COUNTER="COUNTER",r.GAUGE="GAUGE",r.HISTOGRAM="HISTOGRAM",r.UP_DOWN_COUNTER="UP_DOWN_COUNTER",r.OBSERVABLE_COUNTER="OBSERVABLE_COUNTER",r.OBSERVABLE_GAUGE="OBSERVABLE_GAUGE",r.OBSERVABLE_UP_DOWN_COUNTER="OBSERVABLE_UP_DOWN_COUNTER"})(me||(me={}));var W0=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 j0(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 Np=function(){function r(e,t,n,o){n===void 0&&(n=!0),o===void 0&&(o=j0(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=dv(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 Dp=function(){function r(e,t){this._boundaries=e,this._recordMinMax=t,this.kind=mr.HISTOGRAM}return r.prototype.createAccumulation=function(e){return new Np(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 Np(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 Np(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:Mt.HISTOGRAM,dataPoints:n.map(function(i){var a=W0(i,2),s=a[0],c=a[1],l=c.toPointValue(),u=e.type===me.GAUGE||e.type===me.UP_DOWN_COUNTER||e.type===me.OBSERVABLE_GAUGE||e.type===me.OBSERVABLE_UP_DOWN_COUNTER;return{attributes: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}();Le();var kp=function(r,e){var t=typeof Symbol=="function"&&r[Symbol.iterator];if(!t)return r;var n=t.call(r),o,i=[],a;try{for(;(e===void 0||e-- >0)&&!(o=n.next()).done;)i.push(o.value)}catch(s){a={error:s}}finally{try{o&&!o.done&&(t=n.return)&&t.call(n)}finally{if(a)throw a.error}}return i},Up=function(r,e,t){if(t||arguments.length===2)for(var n=0,o=e.length,i;n<o;n++)(i||!(n in e))&&(i||(i=Array.prototype.slice.call(e,0,n)),i[n]=e[n]);return r.concat(i||Array.prototype.slice.call(e))},Fp=function(){function r(e,t,n,o){e===void 0&&(e=new $0),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 $0=function(){function r(e){e===void 0&&(e=[0]),this._counts=e}return Object.defineProperty(r.prototype,"length",{get:function(){return this._counts.length},enumerable:!1,configurable:!0}),r.prototype.countAt=function(e){return this._counts[e]},r.prototype.growTo=function(e,t,n){var o=new Array(e).fill(0);o.splice.apply(o,Up([n,this._counts.length-t],kp(this._counts.slice(t)),!1)),o.splice.apply(o,Up([0,t],kp(this._counts.slice(0,t)),!1)),this._counts=o},r.prototype.reverse=function(e,t){for(var n=Math.floor((e+t)/2)-e,o=0;o<n;o++){var i=this._counts[e+o];this._counts[e+o]=this._counts[t-o-1],this._counts[t-o-1]=i}},r.prototype.emptyBucket=function(e){var t=this._counts[e];return this._counts[e]=0,t},r.prototype.increment=function(e,t){this._counts[e]+=t},r.prototype.decrement=function(e,t){this._counts[e]>=t?this._counts[e]-=t:this._counts[e]=0},r.prototype.clone=function(){return new r(Up([],kp(this._counts),!1))},r}();var pv=52,q0=2146435072,K0=1048575,Bp=1023,Ic=-Bp+1,Oc=Bp,Es=Math.pow(2,-1022);function Lc(r){var e=new DataView(new ArrayBuffer(8));e.setFloat64(0,r);var t=e.getUint32(0),n=(t&q0)>>20;return n-Bp}function Nc(r){var e=new DataView(new ArrayBuffer(8));e.setFloat64(0,r);var t=e.getUint32(0),n=e.getUint32(4),o=(t&K0)*Math.pow(2,32);return o+n}function Ts(r,e){return r===0||r===Number.POSITIVE_INFINITY||r===Number.NEGATIVE_INFINITY||Number.isNaN(r)?r:r*Math.pow(2,e)}function hv(r){return r--,r|=r>>1,r|=r>>2,r|=r>>4,r|=r>>8,r|=r>>16,r++,r}var Y0=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)}}(),Hn=function(r){Y0(e,r);function e(){return r!==null&&r.apply(this,arguments)||this}return e}(Error);var Sv=function(){function r(e){this._shift=-e}return r.prototype.mapToIndex=function(e){if(e<Es)return this._minNormalLowerBoundaryIndex();var t=Lc(e),n=this._rightShift(Nc(e)-1,pv);return t+n>>this._shift},r.prototype.lowerBoundary=function(e){var t=this._minNormalLowerBoundaryIndex();if(e<t)throw new Hn("underflow: "+e+" is < minimum lower boundary: "+t);var n=this._maxNormalLowerBoundaryIndex();if(e>n)throw new Hn("overflow: "+e+" is > maximum lower boundary: "+n);return Ts(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=Ic>>this._shift;return this._shift<2&&e--,e},r.prototype._maxNormalLowerBoundaryIndex=function(){return Oc>>this._shift},r.prototype._rightShift=function(e,t){return Math.floor(e*Math.pow(2,-t))},r}();var yv=function(){function r(e){this._scale=e,this._scaleFactor=Ts(Math.LOG2E,e),this._inverseFactor=Ts(Math.LN2,-e)}return r.prototype.mapToIndex=function(e){if(e<=Es)return this._minNormalLowerBoundaryIndex()-1;if(Nc(e)===0){var t=Lc(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 Hn("overflow: "+e+" is > maximum lower boundary: "+t)}var n=this._minNormalLowerBoundaryIndex();if(e<=n){if(e===n)return Es;if(e===n-1)return Math.exp((e+(1<<this._scale))/this._scaleFactor)/2;throw new Hn("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 Ic<<this._scale},r.prototype._maxNormalLowerBoundaryIndex=function(){return(Oc+1<<this._scale)-1},r}();var bv=-10,Ev=20,X0=Array.from({length:31},function(r,e){return e>10?new yv(e-10):new Sv(e-10)});function zp(r){if(r>Ev||r<bv)throw new Hn("expected scale >= "+bv+" && <= "+Ev+", got: "+r);return X0[r+10]}var J0=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},Dc=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}(),Q0=20,Z0=160,Hp=2,ek=function(){function r(e,t,n,o,i,a,s,c,l,u,d){e===void 0&&(e=e),t===void 0&&(t=Z0),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 Fp),u===void 0&&(u=new Fp),d===void 0&&(d=zp(Q0)),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<Hp&&(W.warn("Exponential Histogram Max Size set to "+this._maxSize+", changing to the minimum size of: "+Hp),this._maxSize=Hp)}return r.prototype.record=function(e){this.updateByIncrement(e,1)},r.prototype.setStartTime=function(e){this.startTime=e},r.prototype.toPointValue=function(){return{hasMinMax:this._recordMinMax,min:this.min,max:this.max,sum:this.sum,positive:{offset:this.positive.offset,bucketCounts:this.positive.counts()},negative:{offset:this.negative.offset,bucketCounts:this.negative.counts()},count:this.count,scale:this.scale,zeroCount:this.zeroCount}},Object.defineProperty(r.prototype,"sum",{get:function(){return this._sum},enumerable:!1,configurable:!0}),Object.defineProperty(r.prototype,"min",{get:function(){return this._min},enumerable:!1,configurable:!0}),Object.defineProperty(r.prototype,"max",{get:function(){return this._max},enumerable:!1,configurable:!0}),Object.defineProperty(r.prototype,"count",{get:function(){return this._count},enumerable:!1,configurable:!0}),Object.defineProperty(r.prototype,"zeroCount",{get:function(){return this._zeroCount},enumerable:!1,configurable:!0}),Object.defineProperty(r.prototype,"scale",{get:function(){return this._count===this._zeroCount?0:this._mapping.scale},enumerable:!1,configurable:!0}),Object.defineProperty(r.prototype,"positive",{get:function(){return this._positive},enumerable:!1,configurable:!0}),Object.defineProperty(r.prototype,"negative",{get:function(){return this._negative},enumerable:!1,configurable:!0}),r.prototype.updateByIncrement=function(e,t){if(!Number.isNaN(e)){if(e>this._max&&(this._max=e),e<this._min&&(this._min=e),this._count+=t,e===0){this._zeroCount+=t;return}this._sum+=e*t,e>0?this._updateBuckets(this._positive,e,t):this._updateBuckets(this._negative,-e,t)}},r.prototype.merge=function(e){this._count===0?(this._min=e.min,this._max=e.max):e.count!==0&&(e.min<this.min&&(this._min=e.min),e.max>this.max&&(this._max=e.max)),this.startTime=e.startTime,this._sum+=e.sum,this._count+=e.count,this._zeroCount+=e.zeroCount;var t=this._minScale(e);this._downscale(this.scale-t),this._mergeBuckets(this.positive,e,e.positive,t),this._mergeBuckets(this.negative,e,e.negative,t)},r.prototype.diff=function(e){this._min=1/0,this._max=-1/0,this._sum-=e.sum,this._count-=e.count,this._zeroCount-=e.zeroCount;var t=this._minScale(e);this._downscale(this.scale-t),this._diffBuckets(this.positive,e,e.positive,t),this._diffBuckets(this.negative,e,e.negative,t)},r.prototype.clone=function(){return new r(this.startTime,this._maxSize,this._recordMinMax,this._sum,this._count,this._zeroCount,this._min,this._max,this.positive.clone(),this.negative.clone(),this._mapping)},r.prototype._updateBuckets=function(e,t,n){var o=this._mapping.mapToIndex(t),i=!1,a=0,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=hv(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=zp(t)}},r.prototype._minScale=function(e){var t=Math.min(this.scale,e.scale),n=Dc.combine(this._highLowAtScale(this.positive,this.scale,t),this._highLowAtScale(e.positive,e.scale,t)),o=Dc.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 Dc(0,-1);var o=t-n;return new Dc(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 Tv=function(){function r(e,t){this._maxSize=e,this._recordMinMax=t,this.kind=mr.EXPONENTIAL_HISTOGRAM}return r.prototype.createAccumulation=function(e){return new ek(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:Mt.EXPONENTIAL_HISTOGRAM,dataPoints:n.map(function(i){var a=J0(i,2),s=a[0],c=a[1],l=c.toPointValue(),u=e.type===me.GAUGE||e.type===me.UP_DOWN_COUNTER||e.type===me.OBSERVABLE_GAUGE||e.type===me.OBSERVABLE_UP_DOWN_COUNTER;return{attributes: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 tk=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},Gp=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=sv(Date.now())},r.prototype.setStartTime=function(e){this.startTime=e},r.prototype.toPointValue=function(){return this._current},r}();var vv=function(){function r(){this.kind=mr.LAST_VALUE}return r.prototype.createAccumulation=function(e){return new Gp(e)},r.prototype.merge=function(e,t){var n=bs(t.sampleTime)>=bs(e.sampleTime)?t:e;return new Gp(e.startTime,n.toPointValue(),n.sampleTime)},r.prototype.diff=function(e,t){var n=bs(t.sampleTime)>=bs(e.sampleTime)?t:e;return new Gp(t.startTime,n.toPointValue(),n.sampleTime)},r.prototype.toMetricData=function(e,t,n,o){return{descriptor:e,aggregationTemporality:t,dataPointType:Mt.GAUGE,dataPoints:n.map(function(i){var a=tk(i,2),s=a[0],c=a[1];return{attributes:s,startTime:c.startTime,endTime:o,value:c.toPointValue()}})}},r}();var rk=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,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 Vp=function(){function r(e){this.monotonic=e,this.kind=mr.SUM}return r.prototype.createAccumulation=function(e){return new vs(e,this.monotonic)},r.prototype.merge=function(e,t){var n=e.toPointValue(),o=t.toPointValue();return t.reset?new vs(t.startTime,this.monotonic,o,t.reset):new vs(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 vs(t.startTime,this.monotonic,o,!0):new vs(t.startTime,this.monotonic,o-n)},r.prototype.toMetricData=function(e,t,n,o){return{descriptor:e,aggregationTemporality:t,dataPointType:Mt.SUM,dataPoints:n.map(function(i){var a=rk(i,2),s=a[0],c=a[1];return{attributes:s,startTime:c.startTime,endTime:o,value:c.toPointValue()}}),isMonotonic:this.monotonic}},r}();var Po=function(){var r=function(e,t){return r=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(n,o){n.__proto__=o}||function(n,o){for(var i in o)Object.prototype.hasOwnProperty.call(o,i)&&(n[i]=o[i])},r(e,t)};return function(e,t){if(typeof t!="function"&&t!==null)throw new TypeError("Class extends value "+String(t)+" is not a constructor or null");r(e,t);function n(){this.constructor=e}e.prototype=t===null?Object.create(t):(n.prototype=t.prototype,new n)}}(),$r=function(){function r(){}return r.Drop=function(){return Pv},r.Sum=function(){return Iv},r.LastValue=function(){return Ov},r.Histogram=function(){return Lv},r.ExponentialHistogram=function(){return nk},r.Default=function(){return ok},r}();var Av=function(r){Po(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 mv,e}($r);var wv=function(r){Po(e,r);function e(){return r!==null&&r.apply(this,arguments)||this}return e.prototype.createAggregator=function(t){switch(t.type){case me.COUNTER:case me.OBSERVABLE_COUNTER:case me.HISTOGRAM:return e.MONOTONIC_INSTANCE;default:return e.NON_MONOTONIC_INSTANCE}},e.MONOTONIC_INSTANCE=new Vp(!0),e.NON_MONOTONIC_INSTANCE=new Vp(!1),e}($r);var Cv=function(r){Po(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 vv,e}($r);var Rv=function(r){Po(e,r);function e(){return r!==null&&r.apply(this,arguments)||this}return e.prototype.createAggregator=function(t){return e.DEFAULT_INSTANCE},e.DEFAULT_INSTANCE=new Dp([0,5,10,25,50,75,100,250,500,750,1e3,2500,5e3,7500,1e4],!0),e}($r);var xv=function(r){Po(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 Dp(this._boundaries,this._recordMinMax)},e}($r);var Mv=function(r){Po(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 Tv(this._maxSize,this._recordMinMax)},e}($r);var _v=function(r){Po(e,r);function e(){return r!==null&&r.apply(this,arguments)||this}return e.prototype._resolve=function(t){switch(t.type){case me.COUNTER:case me.UP_DOWN_COUNTER:case me.OBSERVABLE_COUNTER:case me.OBSERVABLE_UP_DOWN_COUNTER:return Iv;case me.GAUGE:case me.OBSERVABLE_GAUGE:return Ov;case me.HISTOGRAM:return t.advice.explicitBucketBoundaries?new xv(t.advice.explicitBucketBoundaries):Lv}return W.warn("Unable to recognize instrument type: "+t.type),Pv},e.prototype.createAggregator=function(t){return this._resolve(t).createAggregator(t)},e}($r);var Pv=new Av,Iv=new wv,Ov=new Cv,Lv=new Rv,nk=new Mv,ok=new _v;Le();function kc(){return"unknown_service:"+process.argv0}var Gn=function(){return Gn=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},Gn.apply(this,arguments)},ik=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())})},ak=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}}},sk=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},Wp=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[_c]=kc(),e[Ss]=Pc[Ss],e[fs]=Pc[fs],e[ys]=Pc[ys],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 ik(this,void 0,void 0,function(){return ak(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=Gn(Gn({},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=sk(a,2),l=c[0],u=c[1];return Gn(Gn(Gn(Gn({},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 Io;(function(r){r[r.DELTA=0]="DELTA",r[r.CUMULATIVE=1]="CUMULATIVE",r[r.LOWMEMORY=2]="LOWMEMORY"})(Io||(Io={}));Le();var lk=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())})},ck=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}}},jp=function(){return dr.CUMULATIVE},Nv=function(r){switch(r){case me.COUNTER:case me.OBSERVABLE_COUNTER:case me.GAUGE:case me.HISTOGRAM:case me.OBSERVABLE_GAUGE:return dr.DELTA;case me.UP_DOWN_COUNTER:case me.OBSERVABLE_UP_DOWN_COUNTER:return dr.CUMULATIVE}},Dv=function(r){switch(r){case me.COUNTER:case me.HISTOGRAM:return dr.DELTA;case me.GAUGE:case me.UP_DOWN_COUNTER:case me.OBSERVABLE_UP_DOWN_COUNTER:case me.OBSERVABLE_COUNTER:case me.OBSERVABLE_GAUGE:return dr.CUMULATIVE}};function uk(){var r=Tt(),e=r.OTEL_EXPORTER_OTLP_METRICS_TEMPORALITY_PREFERENCE.trim().toLowerCase();return e==="cumulative"?jp:e==="delta"?Nv:e==="lowmemory"?Dv:(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."),jp)}function dk(r){return r!=null?r===Io.DELTA?Nv:r===Io.LOWMEMORY?Dv:jp:uk()}function mk(r){return r?.aggregationPreference?r.aggregationPreference:function(e){return $r.Default()}}var kv=function(){function r(e,t){this._otlpExporter=e,this._aggregationSelector=mk(t),this._aggregationTemporalitySelector=dk(t?.temporalityPreference)}return r.prototype.export=function(e,t){this._otlpExporter.export([e],t)},r.prototype.shutdown=function(){return lk(this,void 0,void 0,function(){return ck(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}();Le();Le();var pk=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},Uv=1e4,Fv=5,Bv=1e3,zv=5e3,Hv=1.5;function As(r){r===void 0&&(r={});var e={};return Object.entries(r).forEach(function(t){var n=pk(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 $p(r,e){return r.endsWith("/")||(r=r+"/"),r+e}function qp(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 Kp(r){return typeof r=="number"?r<=0?Yp(r,Uv):r:gk()}function gk(){var r,e=Number((r=Tt().OTEL_EXPORTER_OTLP_TRACES_TIMEOUT)!==null&&r!==void 0?r:Tt().OTEL_EXPORTER_OTLP_TIMEOUT);return e<=0?Yp(e,Uv):e}function Yp(r,e){return W.warn("Timeout must be greater than 0",r),e}function Gv(r){var e=[429,502,503,504];return e.includes(r)}function Vv(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 Wv=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 uv(this._shutdown,this),this._concurrencyLimit=typeof e.concurrencyLimit=="number"?e.concurrencyLimit:30,this.timeoutMillis=Kp(e.timeoutMillis),this.onInit(e)}return r.prototype.export=function(e,t){if(this._shutdownOnce.isCalled){t({code:_o.FAILED,error:new Error("Exporter has been shutdown")});return}if(this._sendingPromises.length>=this._concurrencyLimit){t({code:_o.FAILED,error:new Error("Concurrent export limit reached")});return}this._export(e).then(function(){t({code:_o.SUCCESS})}).catch(function(n){t({code:_o.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}();Le();import*as Xp from"url";import*as Fc from"http";import*as Bc from"https";import*as jv from"zlib";import{Readable as fk}from"stream";var Vn;(function(r){r.NONE="none",r.GZIP="gzip"})(Vn||(Vn={}));var hk=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)}}(),Ui=function(r){hk(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 Uc=function(){return Uc=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},Uc.apply(this,arguments)};function Jp(r,e,t,n,o){var i=r.timeoutMillis,a=new Xp.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 Ui("Request Timeout");o(h)}else s>=14?l.destroy():l.abort()},i),m={hostname:a.hostname,port:a.port,path:a.pathname,method:"POST",headers:Uc({"Content-Type":t},r.headers),agent:r.agent},p=a.protocol==="http:"?Fc.request:Bc.request,g=function(h,f){switch(h===void 0&&(h=Fv),f===void 0&&(f=Bv),l=p(m,function(b){var w="";b.on("data",function(x){return w+=x}),b.on("aborted",function(){if(u){var x=new Ui("Request Timeout");o(x)}}),b.on("end",function(){if(u===!1)if(b.statusCode&&b.statusCode<299)W.debug("statusCode: "+b.statusCode,w),n(),clearTimeout(d),clearTimeout(c);else if(b.statusCode&&Gv(b.statusCode)&&h>0){var x=void 0;f=Hv*f,b.headers["retry-after"]?x=Vv(b.headers["retry-after"]):x=Math.round(Math.random()*(zv-f)+f),c=setTimeout(function(){g(h-1,f)},x)}else{var A=new Ui(b.statusMessage,b.statusCode,w);o(A),clearTimeout(d),clearTimeout(c)}})}),l.on("error",function(b){if(u){var w=new Ui("Request Timeout",b.code);o(w)}else o(b);clearTimeout(d),clearTimeout(c)}),l.on("abort",function(){if(u){var b=new Ui("Request Timeout");o(b)}clearTimeout(d),clearTimeout(c)}),r.compression){case Vn.GZIP:{l.setHeader("Content-Encoding","gzip");var E=Sk(e);E.on("error",o).pipe(jv.createGzip()).on("error",o).pipe(l);break}default:l.end(Buffer.from(e));break}};g()}function Sk(r){var e=new fk;return e.push(r),e.push(null),e}function Qp(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 Xp.URL(r.url),t=e.protocol==="http:"?Fc.Agent:Bc.Agent;return new t(Uc({keepAlive:!0},r.httpAgentOptions))}catch(n){W.error("collector exporter failed to create http agent. err: "+n.message);return}}function Zp(r){if(r)return r;var e=Tt().OTEL_EXPORTER_OTLP_TRACES_COMPRESSION||Tt().OTEL_EXPORTER_OTLP_COMPRESSION;return e===Vn.GZIP?Vn.GZIP:Vn.NONE}Le();var yk=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)}}(),zc=function(r){yk(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,As(t.headers),Di.parseKeyPairsIntoRecord(Tt().OTEL_EXPORTER_OTLP_HEADERS)),i.agent=Qp(t),i.compression=Zp(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;Jp(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}(Wv);function qv(r){var e=BigInt(1e9);return BigInt(r[0])*e+BigInt(r[1])}function bk(r){var e=Number(BigInt.asUintN(32,r)),t=Number(BigInt.asUintN(32,r>>BigInt(32)));return{low:e,high:t}}function Kv(r){var e=qv(r);return bk(e)}function Ek(r){var e=qv(r);return e.toString()}var Tk=typeof BigInt<"u"?Ek:lv;function $v(r){return r}function Yv(r){if(r!==void 0)return Mc(r)}var vk={encodeHrTime:Kv,encodeSpanContext:Mc,encodeOptionalSpanContext:Yv};function Xv(r){var e,t;if(r===void 0)return vk;var n=(e=r.useLongBits)!==null&&e!==void 0?e:!0,o=(t=r.useHex)!==null&&t!==void 0?t:!1;return{encodeHrTime:n?Kv:Tk,encodeSpanContext:o?$v:Mc,encodeOptionalSpanContext:o?$v:Yv}}var Ak=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 Jv(r){return{name:r.name,version:r.version}}function Fi(r){return Object.keys(r).map(function(e){return Qv(e,r[e])})}function Qv(r,e){return{key:r,value:Zv(e)}}function Zv(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(Zv)}}:e==="object"&&r!=null?{kvlistValue:{values:Object.entries(r).map(function(t){var n=Ak(t,2),o=n[0],i=n[1];return Qv(o,i)})}}:{}}function eA(r){return{attributes:Fi(r.attributes),droppedAttributesCount:0}}Le();function rA(r,e){var t=Xv(e);return{resource:eA(r.resource),schemaUrl:void 0,scopeMetrics:wk(r.scopeMetrics,t)}}function wk(r,e){return Array.from(r.map(function(t){return{scope:Jv(t.scope),metrics:t.metrics.map(function(n){return Ck(n,e)}),schemaUrl:t.scope.schemaUrl}}))}function Ck(r,e){var t={name:r.descriptor.name,description:r.descriptor.description,unit:r.descriptor.unit},n=_k(r.aggregationTemporality);switch(r.dataPointType){case Mt.SUM:t.sum={aggregationTemporality:n,isMonotonic:r.isMonotonic,dataPoints:tA(r,e)};break;case Mt.GAUGE:t.gauge={dataPoints:tA(r,e)};break;case Mt.HISTOGRAM:t.histogram={aggregationTemporality:n,dataPoints:xk(r,e)};break;case Mt.EXPONENTIAL_HISTOGRAM:t.exponentialHistogram={aggregationTemporality:n,dataPoints:Mk(r,e)};break}return t}function Rk(r,e,t){var n={attributes:Fi(r.attributes),startTimeUnixNano:t.encodeHrTime(r.startTime),timeUnixNano:t.encodeHrTime(r.endTime)};switch(e){case qt.INT:n.asInt=r.value;break;case qt.DOUBLE:n.asDouble=r.value;break}return n}function tA(r,e){return r.dataPoints.map(function(t){return Rk(t,r.descriptor.valueType,e)})}function xk(r,e){return r.dataPoints.map(function(t){var n=t.value;return{attributes:Fi(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 Mk(r,e){return r.dataPoints.map(function(t){var n=t.value;return{attributes:Fi(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 _k(r){switch(r){case dr.DELTA:return 1;case dr.CUMULATIVE:return 2}}function nA(r,e){return{resourceMetrics:r.map(function(t){return rA(t,e)})}}var eg={serializeRequest:function(r){var e=nA(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 oA="0.52.1";var iA=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)}}(),Bi=function(){return Bi=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},Bi.apply(this,arguments)},aA="v1/metrics",Pk="http://localhost:4318/"+aA,Ik={"User-Agent":"OTel-OTLP-Exporter-JavaScript/"+oA},Ok=function(r){iA(e,r);function e(t){var n=r.call(this,t,eg,"application/json")||this;return n.headers=Bi(Bi(Bi(Bi({},n.headers),Ik),Di.parseKeyPairsIntoRecord(Tt().OTEL_EXPORTER_OTLP_METRICS_HEADERS)),As(t?.headers)),n}return e.prototype.getDefaultUrl=function(t){return typeof t.url=="string"?t.url:Tt().OTEL_EXPORTER_OTLP_METRICS_ENDPOINT.length>0?qp(Tt().OTEL_EXPORTER_OTLP_METRICS_ENDPOINT):Tt().OTEL_EXPORTER_OTLP_ENDPOINT.length>0?$p(Tt().OTEL_EXPORTER_OTLP_ENDPOINT,aA):Pk},e}(zc),sA=function(r){iA(e,r);function e(t){return r.call(this,new Ok(t),t)||this}return e}(kv);var zi;(function(r){r[r.DELTA=0]="DELTA",r[r.CUMULATIVE=1]="CUMULATIVE"})(zi||(zi={}));var qr;(function(r){r[r.HISTOGRAM=0]="HISTOGRAM",r[r.EXPONENTIAL_HISTOGRAM=1]="EXPONENTIAL_HISTOGRAM",r[r.GAUGE=2]="GAUGE",r[r.SUM=3]="SUM"})(qr||(qr={}));Le();var Lk=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)}}(),lA=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())})},cA=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}}},Nk=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},Dk=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))},kk=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 uA(r){return r!=null}function Hc(r){var e=Object.keys(r);return e.length===0?"":(e=e.sort(),JSON.stringify(e.map(function(t){return[t,r[t]]})))}function dA(r){var e,t;return r.name+":"+((e=r.version)!==null&&e!==void 0?e:"")+":"+((t=r.schemaUrl)!==null&&t!==void 0?t:"")}var tg=function(r){Lk(e,r);function e(t){var n=r.call(this,t)||this;return Object.setPrototypeOf(n,e.prototype),n}return e}(Error);function Wn(r,e){var t,n=new Promise(function(i,a){t=setTimeout(function(){a(new tg("Operation timed out."))},e)});return Promise.race([r,n]).then(function(o){return clearTimeout(t),o},function(o){throw clearTimeout(t),o})}function mA(r){return lA(this,void 0,void 0,function(){var e=this;return cA(this,function(t){return[2,Promise.all(r.map(function(n){return lA(e,void 0,void 0,function(){var o,i;return cA(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 pA(r){return r.status==="rejected"}function rg(r,e){var t=[];return r.forEach(function(n){t.push.apply(t,Dk([],Nk(e(n)),!1))}),t}function gA(r,e){var t,n;if(r.size!==e.size)return!1;try{for(var o=kk(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 hA(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 fA(r,e){return r.toLowerCase()===e.toLowerCase()}Le();var pr;(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"})(pr||(pr={}));var ng=function(){function r(){this.kind=pr.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}();Le();var be;(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"})(be||(be={}));function Kr(r,e,t){var n,o,i,a;return Fk(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:qt.DOUBLE,advice:(a=t?.advice)!==null&&a!==void 0?a:{}}}function SA(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 yA(r,e){return fA(r.name,e.name)&&r.unit===e.unit&&r.type===e.type&&r.valueType===e.valueType}var Uk=/^[a-z][a-z0-9_.\-/]{0,254}$/i;function Fk(r){return r.match(Uk)!=null}var Bk=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 zk(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 Gc=function(){function r(e,t,n,o){n===void 0&&(n=!0),o===void 0&&(o=zk(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=hA(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 Vc=function(){function r(e,t){this._boundaries=e,this._recordMinMax=t,this.kind=pr.HISTOGRAM}return r.prototype.createAccumulation=function(e){return new Gc(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 Gc(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 Gc(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:qr.HISTOGRAM,dataPoints:n.map(function(i){var a=Bk(i,2),s=a[0],c=a[1],l=c.toPointValue(),u=e.type===be.GAUGE||e.type===be.UP_DOWN_COUNTER||e.type===be.OBSERVABLE_GAUGE||e.type===be.OBSERVABLE_UP_DOWN_COUNTER;return{attributes:s,startTime:c.startTime,endTime:o,value:{min:l.hasMinMax?l.min:void 0,max:l.hasMinMax?l.max:void 0,sum:u?void 0:l.sum,buckets:l.buckets,count:l.count}}})}},r}();Le();var og=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},ig=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))},ag=function(){function r(e,t,n,o){e===void 0&&(e=new Hk),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 Hk=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,ig([n,this._counts.length-t],og(this._counts.slice(t)),!1)),o.splice.apply(o,ig([0,t],og(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(ig([],og(this._counts),!1))},r}();var bA=52,Gk=2146435072,Vk=1048575,sg=1023,Wc=-sg+1,jc=sg,ws=Math.pow(2,-1022);function $c(r){var e=new DataView(new ArrayBuffer(8));e.setFloat64(0,r);var t=e.getUint32(0),n=(t&Gk)>>20;return n-sg}function qc(r){var e=new DataView(new ArrayBuffer(8));e.setFloat64(0,r);var t=e.getUint32(0),n=e.getUint32(4),o=(t&Vk)*Math.pow(2,32);return o+n}function Cs(r,e){return r===0||r===Number.POSITIVE_INFINITY||r===Number.NEGATIVE_INFINITY||Number.isNaN(r)?r:r*Math.pow(2,e)}function TA(r){return r--,r|=r>>1,r|=r>>2,r|=r>>4,r|=r>>8,r|=r>>16,r++,r}var Wk=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)}}(),jn=function(r){Wk(e,r);function e(){return r!==null&&r.apply(this,arguments)||this}return e}(Error);var AA=function(){function r(e){this._shift=-e}return r.prototype.mapToIndex=function(e){if(e<ws)return this._minNormalLowerBoundaryIndex();var t=$c(e),n=this._rightShift(qc(e)-1,bA);return t+n>>this._shift},r.prototype.lowerBoundary=function(e){var t=this._minNormalLowerBoundaryIndex();if(e<t)throw new jn("underflow: "+e+" is < minimum lower boundary: "+t);var n=this._maxNormalLowerBoundaryIndex();if(e>n)throw new jn("overflow: "+e+" is > maximum lower boundary: "+n);return Cs(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=Wc>>this._shift;return this._shift<2&&e--,e},r.prototype._maxNormalLowerBoundaryIndex=function(){return jc>>this._shift},r.prototype._rightShift=function(e,t){return Math.floor(e*Math.pow(2,-t))},r}();var wA=function(){function r(e){this._scale=e,this._scaleFactor=Cs(Math.LOG2E,e),this._inverseFactor=Cs(Math.LN2,-e)}return r.prototype.mapToIndex=function(e){if(e<=ws)return this._minNormalLowerBoundaryIndex()-1;if(qc(e)===0){var t=$c(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 jn("overflow: "+e+" is > maximum lower boundary: "+t)}var n=this._minNormalLowerBoundaryIndex();if(e<=n){if(e===n)return ws;if(e===n-1)return Math.exp((e+(1<<this._scale))/this._scaleFactor)/2;throw new jn("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 Wc<<this._scale},r.prototype._maxNormalLowerBoundaryIndex=function(){return(jc+1<<this._scale)-1},r}();var CA=-10,RA=20,jk=Array.from({length:31},function(r,e){return e>10?new wA(e-10):new AA(e-10)});function lg(r){if(r>RA||r<CA)throw new jn("expected scale >= "+CA+" && <= "+RA+", got: "+r);return jk[r+10]}var $k=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},Kc=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}(),qk=20,Kk=160,cg=2,xA=function(){function r(e,t,n,o,i,a,s,c,l,u,d){e===void 0&&(e=e),t===void 0&&(t=Kk),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 ag),u===void 0&&(u=new ag),d===void 0&&(d=lg(qk)),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<cg&&(W.warn("Exponential Histogram Max Size set to "+this._maxSize+", changing to the minimum size of: "+cg),this._maxSize=cg)}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=TA(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=lg(t)}},r.prototype._minScale=function(e){var t=Math.min(this.scale,e.scale),n=Kc.combine(this._highLowAtScale(this.positive,this.scale,t),this._highLowAtScale(e.positive,e.scale,t)),o=Kc.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 Kc(0,-1);var o=t-n;return new Kc(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 ug=function(){function r(e,t){this._maxSize=e,this._recordMinMax=t,this.kind=pr.EXPONENTIAL_HISTOGRAM}return r.prototype.createAccumulation=function(e){return new xA(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:qr.EXPONENTIAL_HISTOGRAM,dataPoints:n.map(function(i){var a=$k(i,2),s=a[0],c=a[1],l=c.toPointValue(),u=e.type===be.GAUGE||e.type===be.UP_DOWN_COUNTER||e.type===be.OBSERVABLE_GAUGE||e.type===be.OBSERVABLE_UP_DOWN_COUNTER;return{attributes:s,startTime:c.startTime,endTime:o,value:{min:l.hasMinMax?l.min:void 0,max:l.hasMinMax?l.max:void 0,sum:u?void 0:l.sum,positive:{offset:l.positive.offset,bucketCounts:l.positive.bucketCounts},negative:{offset:l.negative.offset,bucketCounts:l.negative.bucketCounts},count:l.count,scale:l.scale,zeroCount:l.zeroCount}}})}},r}();Le();var Yk=Tp("OpenTelemetry SDK Context Key SUPPRESS_TRACING");function MA(r){return r.setValue(Yk,!0)}Le();function _A(){return function(r){W.error(Xk(r))}}function Xk(r){return typeof r=="string"?r:JSON.stringify(Jk(r))}function Jk(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 Qk=_A();function Yc(r){try{Qk(r)}catch{}}var PA="1.30.1";var Zk="process.runtime.name";var eU="service.name";var tU="telemetry.sdk.name",rU="telemetry.sdk.language",nU="telemetry.sdk.version";var IA=Zk;var OA=eU;var Rs=tU,xs=rU,Ms=nU;var oU="nodejs";var LA=oU;var Hi,Oo=(Hi={},Hi[Rs]="opentelemetry",Hi[IA]="node",Hi[xs]=LA,Hi[Ms]=PA,Hi);function _s(r){r.unref()}var dU=9,mU=6,pU=Math.pow(10,mU),jle=Math.pow(10,dU);function Lo(r){var e=r/1e3,t=Math.trunc(e),n=Math.round(r%1e3*pU);return[t,n]}function Gi(r){return r[0]*1e6+r[1]/1e3}var Ps;(function(r){r[r.SUCCESS=0]="SUCCESS",r[r.FAILED=1]="FAILED"})(Ps||(Ps={}));Le();function NA(r,e){return new Promise(function(t){Ni.with(MA(Ni.active()),function(){r.export(e,function(n){t(n)})})})}var DA={_export:NA};var gU=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},Xc=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=Lo(Date.now())},r.prototype.setStartTime=function(e){this.startTime=e},r.prototype.toPointValue=function(){return this._current},r}();var dg=function(){function r(){this.kind=pr.LAST_VALUE}return r.prototype.createAccumulation=function(e){return new Xc(e)},r.prototype.merge=function(e,t){var n=Gi(t.sampleTime)>=Gi(e.sampleTime)?t:e;return new Xc(e.startTime,n.toPointValue(),n.sampleTime)},r.prototype.diff=function(e,t){var n=Gi(t.sampleTime)>=Gi(e.sampleTime)?t:e;return new Xc(t.startTime,n.toPointValue(),n.sampleTime)},r.prototype.toMetricData=function(e,t,n,o){return{descriptor:e,aggregationTemporality:t,dataPointType:qr.GAUGE,dataPoints:n.map(function(i){var a=gU(i,2),s=a[0],c=a[1];return{attributes:s,startTime:c.startTime,endTime:o,value:c.toPointValue()}})}},r}();var hU=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},Vi=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 Jc=function(){function r(e){this.monotonic=e,this.kind=pr.SUM}return r.prototype.createAccumulation=function(e){return new Vi(e,this.monotonic)},r.prototype.merge=function(e,t){var n=e.toPointValue(),o=t.toPointValue();return t.reset?new Vi(t.startTime,this.monotonic,o,t.reset):new Vi(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 Vi(t.startTime,this.monotonic,o,!0):new Vi(t.startTime,this.monotonic,o-n)},r.prototype.toMetricData=function(e,t,n,o){return{descriptor:e,aggregationTemporality:t,dataPointType:qr.SUM,dataPoints:n.map(function(i){var a=hU(i,2),s=a[0],c=a[1];return{attributes:s,startTime:c.startTime,endTime:o,value:c.toPointValue()}}),isMonotonic:this.monotonic}},r}();var No=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)}}(),gr=function(){function r(){}return r.Drop=function(){return GA},r.Sum=function(){return VA},r.LastValue=function(){return WA},r.Histogram=function(){return jA},r.ExponentialHistogram=function(){return fU},r.Default=function(){return SU},r}();var kA=function(r){No(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 ng,e}(gr);var UA=function(r){No(e,r);function e(){return r!==null&&r.apply(this,arguments)||this}return e.prototype.createAggregator=function(t){switch(t.type){case be.COUNTER:case be.OBSERVABLE_COUNTER:case be.HISTOGRAM:return e.MONOTONIC_INSTANCE;default:return e.NON_MONOTONIC_INSTANCE}},e.MONOTONIC_INSTANCE=new Jc(!0),e.NON_MONOTONIC_INSTANCE=new Jc(!1),e}(gr);var FA=function(r){No(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 dg,e}(gr);var BA=function(r){No(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 Vc([0,5,10,25,50,75,100,250,500,750,1e3,2500,5e3,7500,1e4],!0),e}(gr);var Is=function(r){No(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 Vc(this._boundaries,this._recordMinMax)},e}(gr);var zA=function(r){No(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 ug(this._maxSize,this._recordMinMax)},e}(gr);var HA=function(r){No(e,r);function e(){return r!==null&&r.apply(this,arguments)||this}return e.prototype._resolve=function(t){switch(t.type){case be.COUNTER:case be.UP_DOWN_COUNTER:case be.OBSERVABLE_COUNTER:case be.OBSERVABLE_UP_DOWN_COUNTER:return VA;case be.GAUGE:case be.OBSERVABLE_GAUGE:return WA;case be.HISTOGRAM:return t.advice.explicitBucketBoundaries?new Is(t.advice.explicitBucketBoundaries):jA}return W.warn("Unable to recognize instrument type: "+t.type),GA},e.prototype.createAggregator=function(t){return this._resolve(t).createAggregator(t)},e}(gr);var GA=new kA,VA=new UA,WA=new FA,jA=new BA,fU=new zA,SU=new HA;var $A=function(r){return gr.Default()},qA=function(r){return zi.CUMULATIVE};var mg=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())})},pg=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}}},KA=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},yU=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))},YA=function(){function r(e){var t,n,o;this._shutdown=!1,this._aggregationSelector=(t=e?.aggregationSelector)!==null&&t!==void 0?t:$A,this._aggregationTemporalitySelector=(n=e?.aggregationTemporalitySelector)!==null&&n!==void 0?n:qA,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 mg(this,void 0,void 0,function(){var t,n,o,i,a,s;return pg(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(yU([this._sdkMetricProducer.collect({timeoutMillis:e?.timeoutMillis})],KA(this._metricProducers.map(function(l){return l.collect({timeoutMillis:e?.timeoutMillis})})),!1))];case 1:return t=KA.apply(void 0,[c.sent()]),n=t[0],o=t.slice(1),i=n.errors.concat(rg(o,function(l){return l.errors})),a=n.resourceMetrics.resource,s=n.resourceMetrics.scopeMetrics.concat(rg(o,function(l){return l.resourceMetrics.scopeMetrics})),[2,{resourceMetrics:{resource:a,scopeMetrics:s},errors:i}]}})})},r.prototype.shutdown=function(e){return mg(this,void 0,void 0,function(){return pg(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,Wn(this.onShutdown(),e.timeoutMillis)];case 3:t.sent(),t.label=4;case 4:return this._shutdown=!0,[2]}})})},r.prototype.forceFlush=function(e){return mg(this,void 0,void 0,function(){return pg(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,Wn(this.onForceFlush(),e.timeoutMillis)];case 3:return t.sent(),[2]}})})},r}();Le();var bU=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)}}(),Qc=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())})},Zc=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}}},EU=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},TU=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))},gg=function(r){bU(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 Qc(this,void 0,void 0,function(){var t;return Zc(this,function(n){switch(n.label){case 0:return n.trys.push([0,2,,3]),[4,Wn(this._doRun(),this._exportTimeout)];case 1:return n.sent(),[3,3];case 2:return t=n.sent(),t instanceof tg?(W.error("Export took longer than %s milliseconds and timed out.",this._exportTimeout),[2]):(Yc(t),[3,3]);case 3:return[2]}})})},e.prototype._doRun=function(){var t,n;return Qc(this,void 0,void 0,function(){var o,i,a,s,c,l;return Zc(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,TU(["PeriodicExportingMetricReader: metrics collection errors"],EU(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),Yc(s),[3,5];case 5:return i.scopeMetrics.length===0?[2]:[4,DA._export(this._exporter,i)];case 6:if(c=u.sent(),c.code!==Ps.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),_s(this._interval)},e.prototype.onForceFlush=function(){return Qc(this,void 0,void 0,function(){return Zc(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 Qc(this,void 0,void 0,function(){return Zc(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}(YA);Le();Le();function eu(){return"unknown_service:"+process.argv0}var $n=function(){return $n=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},$n.apply(this,arguments)},vU=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())})},AU=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}}},wU=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},tu=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[OA]=eu(),e[xs]=Oo[xs],e[Rs]=Oo[Rs],e[Ms]=Oo[Ms],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 vU(this,void 0,void 0,function(){return AU(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=$n($n({},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=wU(a,2),l=c[0],u=c[1];return $n($n($n($n({},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 XA=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}();Le();var Do=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)}}(),ru=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=Ni.active()),typeof e!="number"){W.warn("non-number value provided to metric "+this._descriptor.name+": "+e);return}this._descriptor.valueType===qt.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,Lo(Date.now()))},r}();var JA=function(r){Do(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}(ru);var QA=function(r){Do(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}(ru);var ZA=function(r){Do(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}(ru);var ew=function(r){Do(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}(ru);var nu=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 tw=function(r){Do(e,r);function e(){return r!==null&&r.apply(this,arguments)||this}return e}(nu);var rw=function(r){Do(e,r);function e(){return r!==null&&r.apply(this,arguments)||this}return e}(nu);var nw=function(r){Do(e,r);function e(){return r!==null&&r.apply(this,arguments)||this}return e}(nu);function Os(r){return r instanceof nu}var ow=function(){function r(e){this._meterSharedState=e}return r.prototype.createGauge=function(e,t){var n=Kr(e,be.GAUGE,t),o=this._meterSharedState.registerMetricStorage(n);return new ZA(o,n)},r.prototype.createHistogram=function(e,t){var n=Kr(e,be.HISTOGRAM,t),o=this._meterSharedState.registerMetricStorage(n);return new ew(o,n)},r.prototype.createCounter=function(e,t){var n=Kr(e,be.COUNTER,t),o=this._meterSharedState.registerMetricStorage(n);return new QA(o,n)},r.prototype.createUpDownCounter=function(e,t){var n=Kr(e,be.UP_DOWN_COUNTER,t),o=this._meterSharedState.registerMetricStorage(n);return new JA(o,n)},r.prototype.createObservableGauge=function(e,t){var n=Kr(e,be.OBSERVABLE_GAUGE,t),o=this._meterSharedState.registerAsyncMetricStorage(n);return new rw(n,o,this._meterSharedState.observableRegistry)},r.prototype.createObservableCounter=function(e,t){var n=Kr(e,be.OBSERVABLE_COUNTER,t),o=this._meterSharedState.registerAsyncMetricStorage(n);return new tw(n,o,this._meterSharedState.observableRegistry)},r.prototype.createObservableUpDownCounter=function(e,t){var n=Kr(e,be.OBSERVABLE_UP_DOWN_COUNTER,t),o=this._meterSharedState.registerAsyncMetricStorage(n);return new nw(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 ou=function(){function r(e){this._instrumentDescriptor=e}return r.prototype.getInstrumentDescriptor=function(){return this._instrumentDescriptor},r.prototype.updateDescription=function(e){this._instrumentDescriptor=Kr(this._instrumentDescriptor.name,this._instrumentDescriptor.type,{description:e,valueType:this._instrumentDescriptor.valueType,unit:this._instrumentDescriptor.unit,advice:this._instrumentDescriptor.advice})},r}();var CU=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)}}(),iw=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}}},RU=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 iw(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 iw(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 Rr=function(r){CU(e,r);function e(){return r.call(this,Hc)||this}return e}(RU);var xU=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},iu=function(){function r(e,t){this._aggregator=e,this._activeCollectionStorage=new Rr,this._cumulativeMemoStorage=new Rr,this._overflowAttributes={"otel.metric.overflow":!0},this._cardinalityLimit=(t??2e3)-1,this._overflowHashCode=Hc(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=xU(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 m=n._activeCollectionStorage.get(a,c);u=n._aggregator.merge(m,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 Rr,e},r}();var hg=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.")},aw=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},au=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===zi.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=MU(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=hg(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 Rr,i=this._unreportedAccumulations.get(e);if(this._unreportedAccumulations.set(e,[]),i===void 0)return o;try{for(var a=hg(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=aw(a.value,3),c=s[0],l=s[1],u=s[2];if(e.has(c,u)){var d=e.get(c,u),m=n.merge(d,l);o.set(c,m,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=hg(e.keys()),s=a.next();!s.done;s=a.next()){var c=aw(s.value,2),l=c[0],u=c[1],d=t.get(l,u);d?.setStartTime(n)}}catch(m){o={error:m}}finally{try{s&&!s.done&&(i=a.return)&&i.call(a)}finally{if(o)throw o.error}}return t},r}();function MU(r){return Array.from(r.entries())}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)}}(),PU=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},sw=function(r){_U(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 iu(n,s._aggregationCardinalityLimit),s._temporalMetricStorage=new au(n,i),s}return e.prototype.record=function(t,n){var o=this,i=new Rr;Array.from(t.entries()).forEach(function(a){var s=PU(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}(ou);Le();function fg(r,e){var t="";return r.unit!==e.unit&&(t+=" - Unit '"+r.unit+"' does not match '"+e.unit+`'
28
28
  `),r.type!==e.type&&(t+=" - Type '"+r.type+"' does not match '"+e.type+`'
29
29
  `),r.valueType!==e.valueType&&(t+=" - Value Type '"+r.valueType+"' does not match '"+e.valueType+`'
30
30
  `),r.description!==e.description&&(t+=" - Description '"+r.description+"' does not match '"+e.description+`'
@@ -4357,14 +4357,14 @@ Available pages:${JSON.stringify(n.map(i=>i.url))}`);if(!Uo(o.url,this.logger)){
4357
4357
  `),tokenLength:d}),u=[],d=0,m=p.length?[p[p.length-1].id]:[],g=!1);let h=c[l],f=_r(h);d+=f,h.length>a&&(h=h.slice(0,a));let w=Array.from(h.matchAll(gx)).map(Y=>Y&&Y.length>=3?{tagName:Y[1],id:Y[2]}:void 0).filter(Y=>!!Y),A=Array.from(h.matchAll(D1)).map(Y=>Y&&(Y[2]||Y[4])).filter(Y=>!!Y);A.reverse();let M=h.replace(/ id="[0-9]+"/g,"");u.push(M);for(let Y of w)m.push(Y.id),p.push(Y);for(let Y of A){let H=p[p.length-1];H&&H.tagName===Y&&p.pop()}let v=p.some(Y=>U1.includes(Y.tagName)),_=c[l+1]??"",k=_r(_),Z=Array.from(_.matchAll(gx)).map(Y=>Y&&Y.length>2?Y[1]:void 0).filter(Y=>!!Y),te=Z.some(Y=>Sx.includes(Y)),yt=Z.some(Y=>k1.includes(Y));d+k>=i&&(g=!0),d>=n&&(te&&!v||A.some(Y=>F1.includes(Y)))&&(g=!0),d>=o&&yt&&!v&&(g=!0),l++}return u.length&&s.push({ids:m,content:u.join(`
4358
4358
  `),tokenLength:d}),s.forEach((h,f)=>{let E=h.ids[0],b=h.ids[h.ids.length-1];r.debug({tokenLength:h.tokenLength,minId:E,maxId:b},`Chunk for page filtering (index ${f+1}/${s.length})`)}),{chunks:s}}var H1=75e4,Vu=3e5;async function Go(r){let{options:e,fixtures:t,screenshot:n}=r,{aiPageFiltering:o}=e,{logger:i,generator:a,orgId:s,signal:c}=t,l=r.tree,u=r.serializedTree,d=_r(u);if(d>H1)try{let m=Gu({serializedTree:u,options:{minChunkTokenCount:1e4,maxChunkTokenCount:1e5,acceptableChunkTokenCount:5e4,maxLineLength:4e3},logger:i});l=await V1({...r,tokenLimit:Vu-1e4,chunks:m.chunks}),u=l.serialize();let p=_r(u);i.info({oldTokens:d,newTokens:p},"Filtered page using keywords"),d=p}catch(m){i.warn({err:m},"Error filtering page using keyword matching, using naive truncation"),l=l.pruneToSerializedCharLimit(Vu*Kn),u=l.serialize();let p=_r(u);i.info({oldTokens:d,newTokens:p},"Filtered page using naive truncation"),d=p}if(d>Vu)try{if(o){let m=Gu({serializedTree:u,options:fx,logger:i}),p=z1();l=await B(G1({...r,chunks:m.chunks,callId:p}),{milliseconds:12e3,signal:c}),u=l.serialize();let g=_r(u);i.info({oldTokens:d,newTokens:g,langfuseCallId:p},"Filtered page using AI chunk ranking"),d=g}else{let m=Gu({serializedTree:u,options:hx,logger:i});l=await B(W1({...r,chunkResult:m,tokenLimit:4e4}),{milliseconds:12e3,signal:c}),u=l.serialize();let p=_r(u);i.info({oldTokens:d,newTokens:p},"Filtered page using RAG"),d=p}}catch(m){i.warn({err:m},"Error filtering page using RAG/AI, using naive truncation"),l=l.pruneToSerializedCharLimit(Vu*Kn),u=l.serialize(),i.info("Filtered page using naive truncation")}return u}async function G1({type:r,callId:e,chunks:t,description:n,fixtures:o,tree:i}){let{generator:a,signal:s,logger:c}=o,l=await a.rankChunksWithAi({chunks:t,description:n,type:r,softTokenLimit:4e4,hardTokenLimit:8e4,callId:e},{abortSignal:s,logger:c,loggerTags:Ee(c)}),u=[];return t.forEach((m,p)=>{l.indices.includes(p)&&(u=u.concat(m.ids))}),i.pruneUsingRelevantIds(new Set(u))}async function V1(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 s=await o.getExtractedKeywords({goal:e},{logger:i,loggerTags:Ee(i),abortSignal:a});i.info({keywordsResult:s},"Got keywords for page filtering");for(let c of s.keywords){let l=r.chunks.filter(p=>p.content.toLowerCase().includes(c.toLowerCase()));if(!l.length||l.reduce((p,g)=>p+g.tokenLength,0)>r.tokenLimit&&l.length>1)continue;let d=l.flatMap(p=>p.ids);return n.pruneUsingRelevantIds(new Set(d))}throw new Error("No keywords were unique enough for page filtering")}async function W1(r){let{description:e,fixtures:t,chunkResult:n,tokenLimit:o,tree:i}=r,{generator:a,logger:s,signal:c}=t,l=await a.rankChunksWithRag({description:e,chunks:n.chunks,tokenLimit:o},{abortSignal:c,logger:s,loggerTags:Ee(s)});if(l.ids.length===0)throw new Error("RAG returned no important ids");return i.pruneUsingRelevantIds(new Set(l.ids.map(d=>`${d}`)))}async function vh(r,e){if(!r.description)throw new R("UserConfigurationError","Cannot locate element with empty description");return yr({action:async()=>j1(r,e),frameConfig:r.iframeUrl?{type:"url",url:r.iframeUrl}:void 0,browser:e.browser,logger:r.logger})}async function j1(r,e){let{disableCache:t,testContext:n,filterByViewport:o,skipWait:i,source:a,memory:s,aiPageFiltering:c,logger:l,allowNotActionableNodesOverride:u}=r,{ctx:d,orgId:m,browser:p,localCodeEvalTools:g,generator:h,abortSignal:f}=e,E=r.description,b=r.useMemory&&!t;n&&(E=await Fs({orgId:m,s:E,context:n,localTools:g,signal:f,logger:l})),a&&(E=q1(E,a));let{serializedTree:w,tree:x}=await tn(p,{allowNotActionableNodesOverride:u,filterByViewport:o,abortSignal:f,skipWait:i,logger:l}),A,M=Date.now(),v;for(;!A&&Date.now()-M<3e3;){f.throwIfAborted();try{A=await p.screenshot({clearHighlights:!0,respectActiveFrame:!0,retries:2})}catch(pe){v=pe}}if(!A)throw new R("ActionFailureError",`Failed to take screenshot of page to locate element. The page may be unresponsive, or your machine might be severely resource constrained. Error: ${v?.message}`);let _=w,k=!1,Z=`data:image/jpeg;base64,${A.toString("base64")}`;_=await Go({type:"locator",description:E,screenshot:Z,serializedTree:w,options:{aiPageFiltering:c},tree:x,fixtures:{generator:h,signal:f,logger:l,orgId:m}}),_!==w&&(k=!0);let te=await h.getElementLocation({browserState:_,goal:E,screenshot:Z,source:a,memory:b?s:void 0},{disableCache:t,abortSignal:f,loggerTags:Ee(l),useMemory:b});if(l.debug({usedRag:k,result:te},"Got locator result"),!(te.id>0))throw new _n(`Could not find any relevant element: ${te.thoughts}`,te.updatedMemory?{type:"GCS_TRACES",traces:te.updatedMemory}:void 0);let{resolution:Y,target:H,frameConfig:ce}=await p.createTargetFromA11yId({id:te.id,requirements:te.requirements,additionalElements:te.additionalElements,description:E,targetSource:"AI",logger:l});if(Y.a11yNode?.properties?.hidden&&Y.a11yNode?.properties?.hidden!=="false")throw new R("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: ${Y.displayString}`);return b&&(te.updatedMemory?H.memory={type:"GCS_TRACES",traces:te.updatedMemory}:s&&(H.memory=s)),{thoughts:te.thoughts,target:H,resolution:Y,frameConfig:ce,screenshot:Z}}var $1=["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:"],yx="<select> element:",bx="text input or contenteditable element:",Ex="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:",Tx="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:",Th=[yx,bx,Ex,Tx,...$1];function vx(r,e){if(r===e)return!0;for(let t of Th){if(!r.startsWith(t))continue;let n=r.slice(t.length).trim();if(Th.some(o=>e.startsWith(o)&&e.slice(o.length).trim()===n)||n===e.trim())return!0}return!!Th.some(t=>e.startsWith(t)&&e.slice(t.length).trim()===r.trim())}function q1(r,e){if(!r||!e)return r;switch(e){case"SELECT_OPTION":return`${yx} ${r}`;case"TYPE":return`${bx} ${r}`;case"NEGATED_ELEMENT_VISIBLE_CHECK":return`${Ex}
4359
4359
  ${r}`;case"ELEMENT_CHECK":return`${Tx}
4360
- ${r}`;default:return r}}var K1=15;async function Wu({command:r,aiPageFiltering:e,logger:t,fixtures:n,source:o,useMemory:i,maxRetries:a=K1}){if(!r.assertion.trim())throw new R("ActionFailureError","Assertion command is missing the assertion content");let{browser:s}=n,c=r.timeout?r.timeout*1e3:s.smartWaitingTimeout,l=bu(c),u=0,d=Date.now(),m,p,g;try{await yr({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 j(l,n.abortSignal),h=Date.now();let f=!1;try{if(m=await yr({action:async()=>{let b=await Ax(s,t,n.abortSignal);return p&&p.serializedTree===b.serializedTree&&p.screenshotBuff.equals(b.screenshotBuff)?(f=!0,m):(p=b,wx({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:s}),m?.success){m?.updatedMemory&&Ns(r,m.updatedMemory,t);break}else throw m?.thoughts?new R("AssertionFailureError",m.thoughts):new R("InternalPlatformError","No thoughts were provided for AI assertion failure")}catch(E){n.abortSignal.throwIfAborted(),g=E instanceof Error?E:new Error(`${E}`),f?t.info(`AI check attempt ${u} failed (re-used previous result)`):t.info({err:E},`AI check assert attempt ${u} failed, retrying...`)}finally{u++}}if(!m?.success)try{m=await yr({action:async()=>wx({command:r,state:await Ax(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(),g=f instanceof Error?f:new Error(`${f}`)}finally{u++}if(m?.updatedMemory&&Ns(r,m.updatedMemory,t),!m?.success){let f=`AI check still failing after ${u} attempts.`;throw g&&(f+=` Latest result: ${g.message}`),new R("AssertionFailureError",f)}return{...m,succeedImmediately:!1,urlAfterCommand:s.url()}}async function Ax(r,e,t){let[n,o]=await Promise.all([tn(r,{abortSignal:t,skipWait:!0,skipWaitForPageLoad:!0,logger:e}),r.screenshot({retries:1,respectActiveFrame:!0})]);return{...n,screenshotBuff:o}}async function wx({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:m}=t,p={type:"ASSERTION"},{serializedTree:g,tree:h}=e,f=e.screenshotBuff,E=f.toString("base64"),b=u.url(),w=r.contextChoice??"MULTIMODAL",x=g;w!=="VISION_ONLY"&&(x=await Go({type:"assertion",serializedTree:g,tree:h,description:r.assertion,screenshot:E,options:{aiPageFiltering:a},fixtures:{generator:d,signal:m,logger:l,orgId:t.orgId}}),x!==g&&(p.ragUsed=!0),p.pageState=x);let A={goal:r.assertion,url:b,memory:o?r.cache?.memory:void 0,browserState:x,screenshot:E,contextChoice:w,source:c},v=await(w==="VISION_ONLY"?(_,k)=>d.getVisualAssertionResult(_,k):(_,k)=>d.getAssertionResult(_,k))(A,{useConsensus:n,attemptNumber:s,useMemory:o,disableCache:!!r.disableCache,abortSignal:m,logger:l,loggerTags:Ee(l)});return(v.result||i)&&v.relevantElements&&(p.relevantElementsSerialized=v.relevantElements.map(_=>u.getSerializedFormFromA11yId(_)).filter(_=>!!_),await Y1(v.relevantElements,u,l)),{success:v.result,thoughts:v.thoughts,afterScreenshotOverride:f,updatedMemory:o?v.updatedMemory:void 0}}async function Y1(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}}}var X1=75e4,ju=class extends Error{constructor(){super("The page content exceeds the maximum token limit for AI smart waiting."),this.name="ExceededMaxAISmartWaitingTokensError"}};async function Cx(r,e){let{logger:t}=r,{abortSignal:n,browser:o}=e,i=Date.now();try{await J1(i,r,e)}catch(a){if(a instanceof Error&&(a.name==="AbortError"||a.name==="TimeoutError")||n.aborted)return;a instanceof ju?t.warn("Skipping AI smart waiting due to excessive page size - falling back to naive waiting"):t.warn({err:a},"Unexpected error occurred during AI smart waiting");let s=o.smartWaitingTimeout-(Date.now()-i);s>0&&await j(s,n)}finally{t.debug({durationMs:Date.now()-i},"AI smart waiting complete")}}async function J1(r,e,t){let{abortSignal:n,browser:o}=t;if(o.smartWaitingTimeout<3e3){await j(o.smartWaitingTimeout,n);return}if(!e.description)throw new R("UserConfigurationError","Cannot locate element with empty description");await B(Q1(r,e,t),{milliseconds:o.smartWaitingTimeout})}async function Q1(r,e,t){let{logger:n,iframeUrl:o}=e,{browser:i}=t;for(;Date.now()-r<i.smartWaitingTimeout;)if(await yr({action:async()=>Z1(e,t),frameConfig:o?{type:"url",url:o}:void 0,browser:i,logger:n}))return}async function Z1(r,e){let{testContext:t,logger:n,filterByViewport:o,allowNotActionableNodesOverride:i}=r,{browser:a,abortSignal:s,localCodeEvalTools:c,orgId:l,generator:u}=e,d=r.description;t&&(d=await Fs({orgId:l,s:d,context:t,localTools:c,signal:s,logger:n}));let{serializedTree:m}=await tn(a,{allowNotActionableNodesOverride:i,filterByViewport:o,abortSignal:s,logger:n});if(_r(m)>X1)throw new ju;s.throwIfAborted();let g;try{g=await a.screenshot({clearHighlights:!0,respectActiveFrame:!0,retries:2})}catch(b){throw new R("ActionFailureError",`Failed to take screenshot of page to perform smart waiting. The page may be unresponsive, or your machine might be severely resource constrained. Error: ${b instanceof Error?b.message:b}`)}let f=`data:image/jpeg;base64,${g.toString("base64")}`;s.throwIfAborted();let E=await u.getSmartWaitingDecision({browserState:m,description:d,screenshot:f},{abortSignal:s,loggerTags:Ee(n)});return n.debug({result:E},"Got smart waiting result"),E.isPageReady}import{cloneDeep as xx}from"lodash-es";async function Mx(r){let{command:e,timeoutMs:t,fixtures:n}=r,{abortSignal:o}=n,i=()=>Mf(e.cache)?e.cache:void 0,a=i(),s=xx(a),c=(h=!1)=>{if(a=i(),!!a)if(h){let f=kw(s,a);a.target=f.target,a.updatedAt=f.updatedAt}else{if(!s){a=void 0;return}a.target=s.target,a.updatedAt=s.updatedAt}},l=Date.now(),u=0,d,m=500,p=!1;for(;u<2||Date.now()-l<t;){u++,u>1&&await j(m,o),o?.throwIfAborted(),a=i();let{result:h,elementWasFound:f}=await Rx({cacheToUse:a,params:r});if(d=h,p=f,h.success)break;c(),m=Math.min(m*2,1e4)}if(!d)throw new R("InternalPlatformError",`Failed to evaluate manual element assertion in ${t}ms.`);if(o?.throwIfAborted(),!d.success&&a?.target&&dl(a.target)){let h=a?.target?.memory?{target:{id:-1,memory:a.target.memory}}:void 0,{result:f}=await Rx({cacheToUse:h,params:r});d=f,d.success||c(!0)}let g=i();return d.success&&g?.target&&!p&&(g.target=xg(g.target),g.updatedAt=new Date),d}async function Rx({cacheToUse:r,params:e}){let{command:t,disableCache:n,fixtures:o,tracer:i,targetingWrapper:a}=e,{logger:s}=o;if(t.target&&!Cn(t.target))throw new Error("Element assertion with x/y is not supported yet");let c=pu(t.assertion),l,u=!1,d=xx(r);try{let{elementInteractedDisplayString:m,result:p,thoughts:g}=await a({ctx:o.ctx,tracer:i,command:t,target:t.target,cache:d?.target,action:async h=>eH(h.locator,e),options:{...t,allowNotActionableNodesOverride:!0,disableCache:n,memory:d?.target?.memory,disableGlobalLocatorRedirect:!0,source:ka(t),targetName:"target"}});return l={success:p.success,data:p.data,err:p.err,elementInteractedDisplayString:m,thoughts:g},u=!0,p.success||(s.warn({aiThoughts:g,elementString:m,err:p.err},"Element check found an element but failed"),l={...p,thoughts:g}),{result:l,elementWasFound:u}}catch(m){if(c)return l={success:!0,thoughts:`The element described does not exist on the page: ${m.message}`,err:void 0,data:void 0},{result:l,elementWasFound:u};if(!(m instanceof R)||m.reason!="ActionFailureError")throw m;return l={success:!1,err:m,data:void 0,thoughts:void 0},s.warn({err:m},"Element check did not find an element and failed"),{result:l,elementWasFound:u}}}async function eH(r,{command:e,fixtures:t}){return await t.browser.highlight(r),await tH(r,e.assertion)}async function tH(r,e){let t=!0,n,o;switch(e.type){case"ELEMENT_CONTENT":{let a=await r.textContent()??"";if(o={elementTextContent:ft(a,500,!0)},!Yr(a,e.value,e.operation,{negated:!!e.negated,ignoreCase:!1})){let s=hr(e);t=!1,n=new R("AssertionFailureError",`The content ${s} '${e.value}': ${a}`)}break}case"ELEMENT_ATTRIBUTE":{o={elementOuterHtml:ft(await r.evaluate(s=>s.cloneNode(!1).outerHTML),500,!0)};let a;try{a=await r.getAttribute(e.attr,{timeout:3e3})??""}catch(s){n=new R("AssertionFailureError",`The element does not have an attribute named ${e.attr}: ${s}`),t=!1;break}if(!Yr(a,e.value,e.operation,{negated:!!e.negated,ignoreCase:!1})){let s=hr(e);t=!1,e.operation==="EXISTS"?n=new R("AssertionFailureError",`The attribute ${e.attr} ${s}`):n=new R("AssertionFailureError",`The attribute ${e.attr} ${s} '${e.value}': ${a}`)}break}case"ELEMENT_EXISTENCE":{switch(e.condition){case"VISIBLE":{t=await r.evaluate(async(s,c)=>{let l=Date.now();for(;Date.now()-l<c;){await new Promise(d=>setTimeout(d,250));let u=s.getBoundingClientRect();if(!(u.width===0||u.height===0)&&window.getComputedStyle(s).visibility!=="hidden"&&window.getComputedStyle(s).display!=="none")return!0}return!1},Ot*1e3);break}case"EDITABLE":{t=await r.isEditable({timeout:Ot*1e3});break}case"EXISTS":{t=!0;break}case"ENABLED":{t=await r.isEnabled({timeout:Ot*1e3});break}case"FOCUSED":{t=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"})(e.condition)}if(t=e.negated?!t:t,!t){let a=hr(e);n=new R("AssertionFailureError",`The element ${a}`)}break}case"ELEMENT_NAME":{let a=await r.evaluate(s=>s.tagName);if(!Yr(a,e.value,e.operation,{negated:!!e.negated,ignoreCase:!0})){let s=hr(e);t=!1,n=new R("AssertionFailureError",`The element tag name ${s} '${e.value}': ${a}`)}break}case"ELEMENT_STYLE":{let a=await r.evaluate((s,c)=>window.getComputedStyle(s).getPropertyValue(c),e.property);if(!Yr(a,e.value,e.operation,{negated:!!e.negated,ignoreCase:!1})){let s=hr(e);t=!1,e.operation==="EXISTS"?n=new R("AssertionFailureError",`The style property ${e.property} ${s}`):n=new R("AssertionFailureError",`The style property ${e.property} ${s} '${e.value}': ${a}`)}break}default:return(a=>{throw"If Typescript complains about the line below, you missed a case or break in the switch above"})(e)}return{thoughts:void 0,success:t,data:o,err:n}}function _x(r){return r.type==="ELEMENT_EXISTENCE"&&r.negated&&r.condition==="EXISTS"}import{Jimp as rH}from"jimp";async function Ws(r,e){let t=await r.screenshot(e),n=await rH.fromBuffer(t);return{buffer:t,width:Math.ceil(n.bitmap.width??0),height:Math.ceil(n.bitmap.height??0)}}import{Jimp as Px}from"jimp";import Ah from"jpeg-js";import nH from"pixelmatch";async function Ix({ctx:r,tracer:e,command:t,disableCache:n,browser:o,targetingWrapper:i,logger:a,screenshotStorage:s}){if(t.target&&!Cn(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 Z=>Ws(o,{locator:Z.locator,...c}),options:{...t,disableCache:n,disableGlobalLocatorRedirect:!0,memory:t.cache?.target?.memory,targetName:"target"}})).result:l=await Ws(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 V=`${l.width}x${l.height}`,Z=`${u.width}x${u.height}`;return{fail:!0,thoughts:`Current screenshot (${V}) does not match saved screenshot dimensions (${Z}) - 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 Px.fromBuffer(l.buffer),m={width:l.width,height:l.height},p=await Px.fromBuffer(u.buffer),g={width:u.width,height:u.height},h,f=m.width*m.height,E=g.width*g.height,b=Math.abs(m.height-g.height),w=Math.abs(m.width-g.width);if(f>E){let V=d.cover({w:g.width,h:g.height});l.buffer=await V.getBuffer("image/jpeg"),h="current",l.width=g.width,l.height=g.height}else if(E>f){let V=p.cover({w:m.width,h:m.height});u.buffer=await V.getBuffer("image/jpeg"),h="saved"}let x={data:Buffer.alloc(l.width*l.height*4),width:l.width,height:l.height},A=t.threshold??.1,v=nH(Ah.decode(u.buffer).data,Ah.decode(l.buffer).data,x.data,l.width,l.height,{threshold:A,diffColorAlt:[0,255,0]})/(l.width*l.height)*100,_=v>A*100,k=`Visual diff of ${v.toFixed(2)}% detected, which is ${_?"over":"under"} the threshold of ${A*100}%.`;if(h&&(k+=` The ${h} screenshot was cropped since it was taller by ${b} pixels and wider by ${w} pixels.`),_)throw new R("ActionFailureError",k);return{fail:_,thoughts:k,beforeScreenshotOverride:l.buffer,afterScreenshotOverride:Ah.encode(x,75).data,succeedImmediately:!1,urlAfterCommand:o.url()}}var oH=3e4;function iH(r){if(!r.body)return{};switch(r.body.type){case"json":return{content:r.body.content,contentType:"application/json"};case"form-urlencoded":{let e=new URLSearchParams;return Object.entries(r.body.content).forEach(([t,n])=>{e.append(t,n)}),{content:e.toString(),contentType:"application/x-www-form-urlencoded;charset=UTF-8"}}}}async function $u({command:r,logger:e,baseUrl:t,fetchImplementation:n=fetch}){let o=r.timeout??oH/1e3,i=Object.fromEntries(Object.entries(r.headers||{}).filter(([g,h])=>g&&h)),a=new URLSearchParams;Object.entries(r.params||{}).filter(([g,h])=>g&&h).forEach(([g,h])=>{a.append(g,h)});let s=a.toString(),c;if($i(r.url)&&(c=r.url),t&&qi(r.url,t)&&(c=new URL(r.url,t).toString()),!c)throw new R("ActionFailureError",`Invalid URL: ${r.url}`);let l=c;e.info({url:l,searchParams:s,headers:i,body:r.body,method:r.method},"Making HTTP request");let d=await B((async()=>{let g=s?`${l}?${s}`:l;try{let h=iH(r),f=new Headers(i);return h.contentType&&!f.has("Content-Type")&&f.set("Content-Type",h.contentType),await n(g,{headers:f,method:r.method,body:h.content})}catch(h){throw e.error({err:h},"Failed to make HTTP request"),new Error(`Failed to make HTTP request: ${h}`)}})(),{milliseconds:o*1e3,fallback:()=>{throw new R("ActionFailureError",`Fetch request timed out after ${o} seconds`)}});if(!d.ok){let g;try{g=await d.text()}catch(h){g=`Failed to read response body: ${h}`}throw new R("ActionFailureError",`Fetch request failed with status ${d.status}: ${g}`)}let m={};d.headers.forEach((g,h)=>{m[h]=g});let p={status:d.status,headers:m,request:{url:d.url,method:r.method,headers:i}};if(r.body?.type==="json"&&r.body.content)try{p.request.json=JSON.parse(r.body.content)}catch{}if(d.headers.get("content-type")?.includes("json"))try{p.json=await d.json()}catch{}else d.headers.get("content-type")?.includes("text")&&(p.text=await d.text());return p}var aH=5e3;async function Lx({timeout:r=Ot,...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 qu(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 j(s,e.signal),s=Math.min(Math.floor(s*1.5),aH);else return i}return i=await qu(e),i}async function qu({assertion:r,browser:e,autoExpandIframes:t}){switch(r.type){case"CONTENT":case"CONTENT":{let o,i=!1,a;try{let s;if(t){let c=await e.evaluateFunctionInAllFrames(Ox,{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(Ox,{value:r.value,negated:!!r.negated,returnHtml:!0},"checking page content"));if(!i){let c=r.negated?fn.CONTAINS:Sn.CONTAINS;a=new R("AssertionFailureError",`The page ${c} '${r.value}'.`),o=s}}catch(s){a=new R("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)}}function Ox({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 sH=3e4;async function Nx({command:r,logger:e,baseUrl:t,fetchImplementation:n=fetch}){let o=r.timeout??sH/1e3,i=new AbortController,a=Object.fromEntries(Object.entries(r.headers||{}).filter(([d,m])=>d&&m));a["Content-Type"]="application/json";let s;if($i(r.url)&&(s=r.url),t&&qi(r.url,t)&&(s=new URL(r.url,t).toString()),!s)throw new R("ActionFailureError",`Invalid URL: ${r.url}`);let l=await B((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 R("ActionFailureError",`GraphQL request timed out after ${o} seconds`);if(!l.ok){let d,m=await l.text();try{d=JSON.parse(m)}catch{throw new R("ActionFailureError",`GraphQL request failed with status ${l.status}: ${m}`)}throw d?.errors?.length&&d?.errors[0]?.message?new R("ActionFailureError",`GraphQL request failed with status ${l.status}: ${d.errors[0].message}`):new R("ActionFailureError",`GraphQL request failed with status ${l.status}: ${m}`)}let u={};return l.headers.forEach((d,m)=>{u[m]=d}),{status:l.status,headers:u,json:await l.json()}}var Ku=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([tn(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 Go({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}}),m={url:this.browser.url(),browserState:d,startingScreenshot:t,history:n,goal:e,screenshot:u,lastError:a};return await this.generator.getMultiturnAiActionEvaluation(m,{disableCache:o,abortSignal:this.executeAbortController.signal,loggerTags:{...Ee(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([tn(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")}`,m=await Go({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}}),p={url:c,browserState:m,startingScreenshot:t,history:n,goal:e,actionHint:o,screenshot:d};try{return await this.generator.getMultiturnAiActionCommand(p,{disableCache:i,abortSignal:this.executeAbortController.signal,loggerTags:{...Ee(a)},langfuseSessionId:s})}catch(g){throw new R("InternalWebAgentError",`Error generating command: ${g instanceof Error?g.message:g}`,{errOptions:{cause:g}})}}async getBrowserState(e){return tn(this.browser,e)}async locateElement(e){return await vh({...e,aiPageFiltering:!!this.options?.aiPageFiltering},this.getControllerFixtures())}async locateElementWithSelector(e,t){return yr({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 m=i[d],p=await this.wrapElementTargetingCommand({ctx:e,tracer:t,command:n,target:m,cache:a[d],action:async g=>g,options:{...c,targetName:o[d]}});u.push(p)}try{let d=await s(...u.map(g=>g.result)),m=g=>g==="fromTarget"?"From Target":g==="toTarget"?"To Target":"Target",p=u.map((g,h)=>g.thoughts?`${m(o[h])}: ${g.thoughts}`:void 0).filter(g=>!!g).join(" -------------- ")||void 0;return{result:d,elementInteractedDisplayStrings:u.map(g=>g.elementInteractedDisplayString),thoughts:p}}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 R("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 yr({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&&nm(i)){t.warn({err:i},"Invalid mpath error, retrying element targeting command");continue}if(!this.browser.userBrowserSettings.visualActions&&(am(i)||om(i))){t.warn({err:i},"Invalid momentic id error, retrying element targeting command");continue}if(sm(i)){t.warn({err:i},"Invalid backend node id error, retrying element targeting command");continue}if(i instanceof Fr&&i.retryableWithAI){t.warn({err:i},"Element cache disqualification error, retrying element targeting command");continue}throw i}throw n instanceof R?n:new R("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 R("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 j(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:m,source:p}=s,g=this.logger.child({commandId:c.id}),h=this.shouldUseMemory(),f=s.retriesWithAI??1,E=!1,b=Dx(e.cache);if((!b||l)&&!Wd(o))throw new R("ActionFailureError","Cannot target element with no cached data or element descriptor");if(u)return this.wrapHardcodedCssTargetingCommandHelper(e);l&&(g.info("Cache explicitly disabled for this step"),E=!0,b=void 0),b&&this.browser.userBrowserSettings.disableSecondaryCacheResolution&&b.targetSource==="HEURISTIC_HEALED"&&(E=!0,b=void 0),b?.inputDescription&&!vx(o.elementDescriptor,b.inputDescription)&&(g.warn({old:b.inputDescription,new:o.elementDescriptor},"Target cache was generated with a different description, clearing it automatically"),E=!0,b=void 0);let w=A=>!!A&&dl(A),x=!0;if(!w(b)){x=!1,g.info({description:o.elementDescriptor,targetHealingInProgress:m,cacheBustedBeforeAction:E,memory:s.memory,useMemory:h},"Prompting AI for an updated element location"),(E||!i)&&await Cx({description:o.elementDescriptor,iframeUrl:s.iframeUrl,source:p,logger:g,allowNotActionableNodesOverride:s.allowNotActionableNodesOverride},this.getControllerFixtures(t)),f--;let A;try{A=await vh({description:o.elementDescriptor,disableCache:!!s.disableCache,iframeUrl:s.iframeUrl,source:p,useMemory:h,memory:h?s.memory:void 0,aiPageFiltering:!!this.options?.aiPageFiltering,allowNotActionableNodesOverride:s.allowNotActionableNodesOverride,logger:g},this.getControllerFixtures(t))}catch(_){if(_ instanceof _n&&_.updatedLocatorMemory){let k={id:-1,...i,memory:_.updatedLocatorMemory};hu({cmd:c,key:d,newTarget:k,logger:g,updatedWithAI:!0})}throw new R("ActionFailureError",_.message)}A.frameConfig&&this.browser.setActiveFrameConfig(A.frameConfig);let M=s.disableGlobalLocatorRedirect?{locator:A.resolution.locator}:await this.attemptLocatorRedirect(A.resolution.locator,g),v=await a(M);return hu({cmd:c,key:d,newTarget:A.target,logger:g,updatedWithAI:!0}),m&&(n.recordTargetAutoHeal({healType:"AI"}),A.target.targetSource="AI_HEALED",A.target.targetUpdateTime=new Date().toUTCString(),A.target.targetUpdateLoggerTags=Ee(g)),{result:v,elementInteractedDisplayString:A.resolution.displayString,thoughts:A.thoughts}}try{let A=await this.browser.resolveTarget(t,b,{allowNotActionableNodesOverride:s.allowNotActionableNodesOverride,targetName:d,logger:g,signal:this.executeAbortController.signal});(this.browser.userBrowserSettings.visualActions||this.browser.userBrowserSettings.globalLocatorRedirect!==!1)&&await this.browser.scrollIntoViewIfNeeded(A.locator);let M=s.disableGlobalLocatorRedirect?{locator:A.locator}:await this.attemptLocatorRedirect(A.locator,g),v=await a(M);if(gt.increment("cache_target_resolution_v2",1,["outcome:hit","platform:web",`hasRequirements:${!!b.requirements}`,`hasAdditionalElements:${!!b.additionalElements}`,`orgId:${this.orgId}`,"cliVersion:0.16.1"]),hu({cmd:c,key:d,newTarget:b,logger:g,updatedWithAI:!1}),x){let _=A.decisions.filter(k=>k.matched);if(_.length!==1)g.warn({decisions:A.decisions},"Expected exactly 1 matching method for element location, got more or less");else{let k=_[0].type;n.recordTargetAutoHeal({healType:k})}}return{result:v,elementInteractedDisplayString:A.displayString}}catch(A){this.throwIfClosed();let M="unknown";A instanceof Ur&&A.cacheMissReason&&(M=A.cacheMissReason),gt.increment("cache_target_resolution_v2",1,["outcome:miss","platform:web",`hasRequirements:${!!b.requirements}`,`hasAdditionalElements:${!!b.additionalElements}`,`orgId:${this.orgId}`,"cliVersion:0.16.1",`missReason:${M}`]);let v=!1;if((A instanceof Fr||nm(A)||am(A)||sm(A)||NS(A)||om(A)||DS(A))&&(v=!0),A instanceof R&&!v)throw g.error({err:A},"Failed to execute action with cached target (fatal)"),A;if(f>0&&o){g.info({err:A},"Failed to execute action with cached target, retrying with AI");let _;return b.memory&&Af(b.memory)&&(_=b.memory),this.wrapElementTargetingCommand({ctx:t,tracer:n,command:c,target:o,cache:void 0,originalCache:i,action:a,options:{...s,memory:_,retriesWithAI:f,targetHealingInProgress:!0}})}throw new R("ActionFailureError",A.message,{errOptions:{cause:A}})}}async attemptLocatorRedirect(e,t){return this.browser.userBrowserSettings.globalLocatorRedirect!==!1?this.browser.performTargetRedirection(e,t):{locator:e}}async screenshotWithDimensions(e){return Ws(this.browser,e)}async executePresetCommand(e,t,n,o,i){this.options?.slowMoMs&&await j(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 R("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&&Zf(n)?await this.browser.waitForDOMStability({timeout:Te}):!this.browser.userBrowserSettings.visualActions&&["PRESS","TYPE"].includes(n.type)&&await this.browser.waitForDOMStability({timeout:ie}),this.options?.autoFollowNewTabs&&await px({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{xu(n,c)}}createCallbacksForBrowser(e){return{createIsolatedFolder:()=>$g(e)}}async resolveCommandTemplateStrings(e,t){return Ru({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()?Wu({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 R("ActionFailureError","Missing assertion");if(n.timeout&&n.timeout>1800)throw new R("AssertionFailureError",`AI check timeout of ${n.timeout} exceeds the maximum allowed value of 30 minutes.`);return Wu({command:n,fixtures:this.getControllerFixtures(e),useMemory:this.shouldUseMemory(),aiPageFiltering:!!this.options?.aiPageFiltering,logger:a})}case"AI_EXTRACT":{if(!n.goal.trim())throw new R("ActionFailureError","Cannot perform AI extraction without goal");if(n.schema){let h=ZE(n.schema);if(h)throw new R("UserConfigurationError",h)}let p=await this.browser.getCondensedHtml(),g=await this.browser.screenshot({retries:2});try{let h=await this.generator.getTextExtraction({goal:n.goal,browserState:p,returnSchema:n.schema,screenshot:`data:image/jpeg;base64,${g.toString("base64")}`},{disableCache:i,abortSignal:this.executeAbortController.signal,loggerTags:Ee(a)});if(h.result==="NOT_FOUND")throw new R("ActionFailureError","No relevant data found for extraction goal on this page");if(h.thoughts?.includes("MaxGenerationLengthExceededError"))throw new R("UserConfigurationError",h.thoughts);return{thoughts:h.thoughts||void 0,data:h.result,succeedImmediately:!1,urlAfterCommand:this.browser.url()}}catch(h){let f=h.message;throw f.includes("MaxGenerationLengthExceededError")?new R("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."):f.includes("AIProviderError")&&f.includes("time")?new R("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:h}}):h}}case"NAVIGATE":if(!$i(n.url)&&!qi(n.url,this.browser.baseUrl))throw new R("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":throw new R("UserConfigurationError","Captcha solving is no longer available on Momentic");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 p,g;if(n.target&&Nr(n.target))await this.browser.hoverUsingVisualCoordinates(n.target.pixels);else if(n.target&&n.target.elementDescriptor.trim()){let{elementInteractedDisplayString:E,thoughts:b}=await this.wrapElementTargetingCommand({ctx:e,tracer:t,command:n,target:n.target,cache:n.cache?.target,action:w=>this.browser.hover(w),options:{...n,targetName:"target",disableGlobalLocatorRedirect:!0,disableCache:i}});p=E,g=b}let h=this.browser.getViewport()?.height??Ln.height,f=this.browser.getViewport()?.width??Ln.width;switch(n.type){case"SCROLL_UP":await this.browser.scrollVertical(-(n.deltaY??h));break;case"SCROLL_DOWN":await this.browser.scrollVertical(n.deltaY??h);break;case"SCROLL_LEFT":await this.browser.scrollHorizontal(-(n.deltaX??f));break;case"SCROLL_RIGHT":await this.browser.scrollHorizontal(n.deltaX??f);break}return{succeedImmediately:!1,urlAfterCommand:this.browser.url(),elementInteracted:p,thoughts:g}}case"WAIT_FOR_URL":{if(n.timeout&&n.timeout>1800)throw new R("UserConfigurationError",`Wait for URL timeout of ${n.timeout} exceeds the maximum allowed value of 30 minutes.`);let p=n.matcher;await this.browser.waitForUrl({beforeUrl:this.browser.url(),matcher:p},{timeout:n.timeout?n.timeout*1e3:void 0,negated:n.negated,caseInsensitive:n.caseInsensitive});break}case"WAIT":if(n.delay>1800)throw new R("UserConfigurationError",`Wait timeout of ${n.delay} seconds exceeds the maximum allowed value of 30 minutes`);let c=n.delay*1e3;await j(c,this.executeAbortController.signal);break;case"REFRESH":await this.browser.refresh({loadTimeoutMs:n.loadTimeout?n.loadTimeout*1e3:void 0});break;case"CLICK":{if(Nr(n.target)){await this.browser.clickUsingVisualCoordinates(n.target.pixels,n);break}let p=this.browser.url(),{elementInteractedDisplayString:g,result:h,thoughts:f}=await this.wrapElementTargetingCommand({ctx:e,tracer:t,target:n.target,command:n,cache:n.cache?.target,action:b=>this.browser.click(b,this.createCallbacksForBrowser(this.orgId),n),options:{disableCache:i,targetName:"target",...n}}),E={urlAfterCommand:this.browser.url(),succeedImmediately:!1,elementInteracted:g,thoughts:f,data:h.downloadedFile?{downloadedFile:h.downloadedFile}:void 0};return Tu(p,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(Nr(n.fromTarget)&&Nr(n.toTarget)){await this.browser.dragAndDropUsingVisualCoordinates(n.fromTarget.pixels,n.toTarget.pixels,{hoverDurationMs:n.hoverSeconds?n.hoverSeconds*1e3:void 0});break}if(Nr(n.fromTarget)||Nr(n.toTarget))throw new Error("Drag and drop targets must be both coordinates or both descriptions");let{elementInteractedDisplayStrings:p,thoughts:g}=await this.wrapMultiElementTargetingCommand({ctx:e,tracer:t,command:n,targetNames:["fromTarget","toTarget"],descriptions:[n.fromTarget,n.toTarget],caches:[n.cache?.fromTarget,n.cache?.toTarget],action:(h,f)=>this.browser.dragAndDrop(h.locator,f.locator,{hoverDurationMs:n.hoverSeconds?n.hoverSeconds*1e3:void 0,steps:n.steps}),options:{useSelector:!!n.useSelector,disableCache:i}});return{succeedImmediately:!1,urlAfterCommand:this.browser.url(),elementInteracted:p[0],thoughts:g}}case"MOUSE_DRAG":{let p=parseInt(n.deltaX),g=parseInt(n.deltaY),h=n.steps??5;if(isNaN(p)||isNaN(g))throw new R("ActionFailureError",`Invalid pixel values passed to mouse drag command: (${n.deltaX}, ${n.deltaY})`);if(n.target&&Nr(n.target)){await this.browser.mouseDragUsingVisualCoordinates({deltaX:p,deltaY:g,steps:h,fromTarget:n.target.pixels});break}let f,E;if(n.target?.elementDescriptor){let{elementInteractedDisplayString:b,thoughts:w}=await this.wrapElementTargetingCommand({ctx:e,tracer:t,command:n,target:n.target,cache:n.cache?.target,action:async x=>this.browser.mouseDrag(p,g,h,x.locator,{force:n.force}),options:{disableCache:i,targetName:"target",...n}});f=b,E=w}else await this.browser.mouseDrag(p,g,h,void 0,{force:n.force});return{succeedImmediately:!1,urlAfterCommand:this.browser.url(),elementInteracted:f,thoughts:E}}case"SELECT_OPTION":{if(!Cn(n.target))throw new Error("Select with x/y is not supported yet");let p=n.target.elementDescriptor,g=n.choice,{elementInteractedDisplayString:h,thoughts:f}=await this.wrapElementTargetingCommand({ctx:e,tracer:t,command:n,target:{type:"description",elementDescriptor:p},cache:n.cache?.target,action:E=>this.browser.selectOption(E,g,n.force),options:{...n,targetName:"target",disableCache:i,source:ka(n)}});return{succeedImmediately:!1,urlAfterCommand:this.browser.url(),elementInteracted:h,thoughts:f}}case"TAB":{let p={loadTimeoutMs:n.loadTimeout?n.loadTimeout*1e3:void 0,retry:!0};await this.browser.switchToPage(n.action,p);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 l=await this.browser.setCookie(n.value);a.debug({results:l},"Set cookies");break;case"LOCAL_STORAGE":if(!n.value||!n.key)break;await this.browser.setLocalStorage(n.key,n.value);break;case"JAVASCRIPT":{let p;try{n.environment==="BROWSER"?(p=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:p},"Executed JavaScript in browser")):p=await Jr({orgId:this.orgId,code:n.code,fragment:!!n.fragment,context:o,timeoutMs:n.timeout?n.timeout*1e3:void 0,logger:a,localTools:this.localCodeEvalTools,signal:this.executeAbortController.signal,callbacks:{onPersistentVariableUpdates:async g=>{if(!this.options?.scratchPadId){a.warn({updates:g},"Got persistent variable updates but scratch pad is not available");return}await this.storage.savePersistentVariables?.({scratchPadId:this.options?.scratchPadId,orgId:this.orgId,updates:g,logger:a})}}})}catch(g){throw this.throwIfClosed(),new R("ActionFailureError",g instanceof Error?g.message:`${g}`,{errOptions:{cause:g}})}try{JSON.stringify(p)}catch(g){throw new R("ActionFailureError",`Return value is not serializable: ${g instanceof Error?g.message:`${g}`}`,{errOptions:{cause:g}})}return{urlAfterCommand:this.browser.url(),succeedImmediately:!1,data:p}}case"TYPE":{if(n.target&&Nr(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 p=this.browser.url(),g,h,f=Dx(n.target),E=this.browser.userBrowserSettings.globalLocatorRedirect===void 0||this.browser.userBrowserSettings.globalLocatorRedirect==="always";if(f){let{elementInteractedDisplayString:w,thoughts:x}=await this.wrapElementTargetingCommand({ctx:e,tracer:t,command:n,target:f,cache:n.cache?.target,action:A=>this.browser.typeIntoTarget(n.value,A,{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:ka(n)}});g=w,h=x}else await this.browser.type(n.value,{force:n.force,clearContent:n.clearContent,forceClearContent:n.forceClearContent,delay:n.delay,pressEnter:n.pressEnter},!0);let b={urlAfterCommand:this.browser.url(),succeedImmediately:!1,elementInteracted:g,thoughts:h};return Tu(p,b.urlAfterCommand)&&(b.succeedImmediately=!0,b.succeedImmediatelyReason="URL changed"),b}case"HOVER":{if(Nr(n.target)){await this.browser.hoverUsingVisualCoordinates(n.target.pixels);break}let{elementInteractedDisplayString:p,thoughts:g}=await this.wrapElementTargetingCommand({ctx:e,tracer:t,command:n,target:n.target,cache:n.cache?.target,action:h=>this.browser.hover(h),options:{...n,targetName:"target",disableCache:i}});return{succeedImmediately:!1,urlAfterCommand:this.browser.url(),elementInteracted:p,thoughts:g}}case"FOCUS":{if(!Cn(n.target))throw new Error("Focus with x/y is not supported yet");let{elementInteractedDisplayString:p,thoughts:g}=await this.wrapElementTargetingCommand({ctx:e,tracer:t,command:n,target:n.target,cache:n.cache?.target,action:h=>this.browser.focus(h),options:{...n,targetName:"target",disableCache:i}});return{succeedImmediately:!1,urlAfterCommand:this.browser.url(),elementInteracted:p,thoughts:g}}case"BLUR":{if(n.target&&!Cn(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:p,thoughts:g}=await this.wrapElementTargetingCommand({ctx:e,tracer:t,target:n.target,command:n,cache:n.cache?.target,action:h=>this.browser.blur(h),options:{...n,targetName:"target",disableCache:i}});return{succeedImmediately:!1,urlAfterCommand:this.browser.url(),elementInteracted:p,thoughts:g}}case"PRESS":let u=this.browser.url();await this.browser.press(n.value,{repeat:n.repeat,convertMeta:n.convertMeta??!0,delayMs:n.delayMs});let d={urlAfterCommand:this.browser.url(),succeedImmediately:!1};return Tu(u,d.urlAfterCommand)&&(d.succeedImmediately=!0,d.succeedImmediatelyReason="URL changed"),d;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 p=new cH,g=lH(fetch,p),h;try{h=new URL(n.url).hostname}catch{}let f=await $u({command:n,baseUrl:this.browser.baseUrl,logger:a,fetchImplementation:g});return{data:fl.parse({...f,cookies:ec(p,h)}),succeedImmediately:!1,urlAfterCommand:this.browser.url()}}case"GRAPHQL_REQUEST":return{data:await Nx({command:n,baseUrl:this.browser.baseUrl,logger:a}),succeedImmediately:!1,urlAfterCommand:this.browser.url()};case"VISUAL_DIFF":return Ix({ctx:e,tracer:t,command:n,disableCache:i,browser:this.browser,logger:a,storage:this.storage,screenshotStorage:this.visualDiffScreenshotStorage,targetingWrapper:p=>this.wrapElementTargetingCommand(p)});case"FILE_UPLOAD":{let p,g;if(n.fileSource.type==="URL"?(g=n.fileSource.url,p=await eR({uri:n.fileSource.url,logger:a,orgId:this.orgId})):n.fileSource.type==="USER_FILE"&&(g=n.fileSource.name,p=await this.uploadedFileStorage?.getFileForUpload(n.fileSource.name,this.orgId)),!p)throw new R("UserConfigurationError",`Attempted to use non-existent file for upload step: ${g}`);await this.browser.setFileChooserHandler({...p,filename:n.filename});break}case"AUTH_SAVE":return{data:await this.browser.saveAuthState(),succeedImmediately:!1,urlAfterCommand:this.browser.url()};case"AUTH_LOAD":{let p;if(!n.storageState.trim())p=void 0;else if(p=await Jr({orgId:this.orgId,code:n.storageState,fragment:!1,context:o,logger:a,localTools:this.localCodeEvalTools,signal:this.executeAbortController.signal}),typeof p!="object")throw new R("ActionFailureError",`Credentials must evaluate to an object (received ${typeof p} instead)`);let g;try{g=Ob.optional().parse(p)}catch(h){throw new R("ActionFailureError",`Credentials provided do not follow the required format: ${h}`)}await this.browser.loadAuthState(g);break}case"ELEMENT_CHECK":{let p=(n.timeout??Ot)*1e3,g=this.generator.getAgentConfig()?.assertion;if(_x(n.assertion)&&!n.useSelector&&n.target.type==="description"&&g&&g!=="v1"){let f={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 Wu({command:f,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{f.cache?.memory&&Ns(n,f.cache?.memory.traces,a)}}let h=await Mx({command:n,tracer:t,timeoutMs:p,targetingWrapper:f=>this.wrapElementTargetingCommand(f),fixtures:this.getControllerFixtures(e),disableCache:i});return{fail:!h.success,data:h.data,elementInteracted:h.elementInteractedDisplayString,thoughts:h.err?.message??h.thoughts??`Element assertion ${h.success?"succeeded":"failed"}.`,succeedImmediately:!1,urlAfterCommand:this.browser.url()}}case"PAGE_CHECK":{let p=await yr({action:async()=>Lx({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:!p.success,data:p.data,thoughts:p.success?"Page assertion passed.":p.err?.message??`Page assertion still failing after ${n.timeout} seconds.`,urlAfterCommand:this.browser.url(),succeedImmediately:!1}}case"REGISTER_REQUEST_LISTENER":{let p=new Yn(n.requestMatcher),g=this.browser.registerRequestListener(p);return this.registeredListeners[n.key]=g.then(async h=>await Qg(h)).catch(h=>{a.error({err:h},"Failed to get request listener response")}),{succeedImmediately:!1,urlAfterCommand:this.browser.url()}}case"AWAIT_LISTENER":{let p=this.registeredListeners[n.key];if(!p)throw new R("ActionFailureError",`No listener registered with key: ${n.key}`);let g=n.timeout??10;return{data:await B(p,{milliseconds:g*1e3,message:`Request listener timed out after ${g} seconds`}),succeedImmediately:!1,urlAfterCommand:this.browser.url()}}case"RECORD_REQUESTS":{let p=new Yn(n.requestMatcher);return this.recordedRequests[n.key]={},this.browser.registerRequestRecorder(n.key,{matches:g=>p.matches({url:g.request.url,method:g.request.method}),onRequestStart:(g,h)=>{this.recordedRequests[n.key][g]=Lu(h)},onRequestComplete:(g,h)=>{this.recordedRequests[n.key]?.[g]&&(this.recordedRequests[n.key][g]=Lu(h))}}),{succeedImmediately:!1,urlAfterCommand:this.browser.url()}}case"GET_RECORDED_REQUESTS":{let p=this.recordedRequests[n.key];if(!p)throw new R("ActionFailureError",`No recorder registered with key: ${n.key}`);return delete this.recordedRequests[n.key],{data:Object.values(p),succeedImmediately:!1,urlAfterCommand:this.browser.url()}}case"SET_HEADER":{let p;return n.requestMatcher&&(p=new Yn(n.requestMatcher)),this.browser.setHeader(n.name,n.value,p),{succeedImmediately:!1,urlAfterCommand:this.browser.url()}}case"MOCK_ROUTE":return{data:{key:this.browser.registerMock(n.key,new Yn(n.requestMatcher),async(g,h)=>{let f=await Jr({orgId:this.orgId,code:n.responseGenerator,fragment:!1,context:o,timeoutMs:void 0,logger:a,localTools:this.localCodeEvalTools,mock:{request:g,response:h},disallowVariableUpdates:!0,responseSerialization:"RESPONSE"}),E=Lb.parse(f);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(p=>{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:Ee(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 Bu({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:Ee(this.logger)})}async getFailureRecoveryPlan(e){return this.generator.getFailureRecoveryPlan(e,{disableCache:!0,abortSignal:this.executeAbortController.signal,loggerTags:Ee(this.logger)})}};import{cloneDeep as uH}from"lodash-es";import zx from"truncate-json";var kx=1e3,Ux=5e6,dH=5*1024*1024;function Hx(r,e){for(let t=0;t<r.length;t++){let n=r[t];try{if(n.data){let{jsonString:o}=zx(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":Fx(n);break;case"MOBILE_AI_ACTION_STEP":case"MOBILE_MODULE_STEP":Fx(n),Hx(n.steps,e);break;default:{let o=n;throw new Error("If Typescript complains about the line below, you missed a case or break in the switch above")}}}}function Fx(r){if(r.type==="MOBILE_PRESET_STEP"){let e=r.command;"cache"in e&&e.cache&&(e.cache=void 0)}}function Bx(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 Yu(r,e){let t=uH(r);if(Hx(t,e),t.length>kx)return e.error("Database content violation: results too long, truncating before insertion"),t.slice(0,kx);let n=Bx(t,e);if(n.length>Ux)for(e.error({serializedLength:n.length,resultsArrayLength:t.length},"Database content violation: results too large, truncating before insertion");n.length>Ux;)t.pop(),n=Bx(t,e);let{jsonString:o}=zx(n,dH);try{return Bt.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 mH}from"async_hooks";var js=new mH;function pH(r){js.enterWith({activeTracers:[r]})}function gH(r,e){let t=js.getStore()?.activeTracers;if(!t)return e();t.push(r);try{return e()}finally{t.pop()}}async function hH(r,e){let t=js.getStore()?.activeTracers;if(!t)return e();let n=[...t,r];return js.run({activeTracers:n},e)}var Pr={globalAls:js,initializeRootTracerContext:pH,withChildTracer:gH,withChildTracerAsync:hH};var Vo=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 Pr.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 Pr.withChildTracerAsync(i,()=>B(t(i,o),{milliseconds:n?.timeoutMs??1/0,signal:n?.signal,message:n?.timeoutMsg??`Operation timed out after ${n?.timeoutMs??1/0}ms (${e})`})):a=await Pr.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(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:{},subSpans:[]},i=n[0]??void 0;Object.assign(o,i??{}),this.addSpan(o);let a=new r(o),s;try{i?.signal||i?.timeoutMs?s=await Pr.withChildTracerAsync(a,()=>B(t(o),{milliseconds:i?.timeoutMs??1/0,signal:i?.signal,message:i?.timeoutMsg??`Operation timed out after ${i?.timeoutMs??1/0}ms${"name"in i?` (${i.name})`:""}`})):s=await Pr.withChildTracerAsync(a,()=>t(o)),o.endTime=Date.now(),o.durationMs=o.endTime-o.startTime}catch(c){throw o.error=c instanceof Error?c.message:String(c),o.endTime=Date.now(),o.durationMs=o.endTime-o.startTime,c}return s}getRootSpan(){return this.finished||this.finish(),{type:"SECTION",name:"root step span",startTime:this.startTime,endTime:this.endTime,subSpans:this.spans,attributes:{},durationMs:this.endTime?this.endTime-this.startTime:void 0}}};function ae(){let r=Pr.globalAls.getStore()?.activeTracers,e;return!r||r.length===0?e=void 0:e=r[r.length-1],e||new Vo}async function Gx(r){let{driver:e,abortSignal:t,logger:n,packageName:o}=r,i;try{i=await B(e.execute("mobile: shell",{command:"dumpsys",args:["activity","recents"]}),{signal:t,milliseconds:1e4})}catch(s){t?.throwIfAborted(),n.warn({err:s,packageName:o},"Failed to read recents output while removing package");return}if(typeof i!="string"){n.warn({packageName:o,outputType:typeof i},"Unexpected dumpsys output when removing package from recents");return}let a=fH(i,o);if(a.length!==0)for(let s of a){t?.throwIfAborted();try{await e.execute("mobile: shell",{command:"am",args:["stack","remove",s.toString()]}),n.info({packageName:o,taskId:s},"Removed task from recents")}catch(c){t?.throwIfAborted(),n.warn({err:c,packageName:o,taskId:s},"Failed to remove task from recents")}}}function fH(r,e){let t=r.split("Task{");if(t.length<=1)return[];let n=new Set;for(let o of t.slice(1)){let i=`Task{${o}`;if(!i.includes(e)||i.includes("app.lawnchair/.LawnchairLauncher"))continue;let a=i.match(/taskId=(\d+)/);if(!a)continue;let[,s]=a;if(!s)continue;let c=Number.parseInt(s,10);Number.isNaN(c)||n.add(c)}return Array.from(n)}function $s(r){let e=[],t=r.getAttribute("text")??"",n=r.getAttribute("hint")??"",o=r.getAttribute("showing-hint")==="true";t.trim()&&!o&&t.trim()!==n.trim()&&e.push(t.trim());for(let i of Array.from(r.childNodes??[]))if(i.nodeType===3){let a=i.nodeValue??"";a.trim()&&e.push(a.trim())}else if(i.nodeType===1){let a=$s(i);a.trim()&&e.push(a.trim())}return e.join(" ").trim()}import{mkdirSync as BH}from"fs";import{tmpdir as zH}from"os";import Jx from"path";import{diff as FH}from"deep-object-diff";import{cloneDeep as Xx}from"lodash-es";import $x from"fontoxpath";import SH from"@prettier/plugin-xml";import yH from"prettier";import{DOMParser as bH,XMLSerializer as EH}from"slimdom";var TH=new Set(["android.webkit.webview","com.facebook.react.views.webview.reactwebview","com.tencent.smtt.sdk.webview","com.tencent.smtt.sdk.x5webview","org.xwalk.core.xwalkview","com.uc.webview.export.webview"]);function qs(r){let e=r.toLowerCase();return e.endsWith("webview")||TH.has(e)}function vH(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 AH=new Set(["index","package","a11y-important","screen-reader-focusabl"]),wH=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"]),CH=new Set(["text","hint"]),RH=new Set(["live-region","drawing-order"]),xH=new Set(["displayed","enabled"]);function MH(r,e){let t={};for(let[n,o]of Object.entries(e))AH.has(n)||n==="class"&&r===o||n==="focusable"&&o==="true"&&e.clickable==="true"||wH.has(n)&&o==="false"||CH.has(n)&&o===""||xH.has(n)&&o==="true"||RH.has(n)&&o==="0"||n!=="id"&&(t[n]=o);return t}function Vx(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 m of e.attributes){let p=m.name,g=m.value;g!=null&&(l[p]=String(g))}let u=MH(e.tagName,l);for(let[m,p]of Object.entries(u))t.setAttribute(m,p);if(o.set(c,e),i.set(c,t),qs(e.tagName)){let m=s?.injectedWebviewContent??"";if(s?.removeWebviewContent){for(;t.firstChild;)t.removeChild(t.firstChild);return}else if(!s?.disableMomenticAccessibilityTree&&m.trim().length>0){for(;t.firstChild;)t.removeChild(t.firstChild);m.trim().length>0&&t.appendChild(n.createCDATASection(`
4360
+ ${r}`;default:return r}}var K1=15;async function Wu({command:r,aiPageFiltering:e,logger:t,fixtures:n,source:o,useMemory:i,maxRetries:a=K1}){if(!r.assertion.trim())throw new R("ActionFailureError","Assertion command is missing the assertion content");let{browser:s}=n,c=r.timeout?r.timeout*1e3:s.smartWaitingTimeout,l=bu(c),u=0,d=Date.now(),m,p,g;try{await yr({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 j(l,n.abortSignal),h=Date.now();let f=!1;try{if(m=await yr({action:async()=>{let b=await Ax(s,t,n.abortSignal);return p&&p.serializedTree===b.serializedTree&&p.screenshotBuff.equals(b.screenshotBuff)?(f=!0,m):(p=b,wx({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:s}),m?.success){m?.updatedMemory&&Ns(r,m.updatedMemory,t);break}else throw m?.thoughts?new R("AssertionFailureError",m.thoughts):new R("InternalPlatformError","No thoughts were provided for AI assertion failure")}catch(E){n.abortSignal.throwIfAborted(),g=E instanceof Error?E:new Error(`${E}`),f?t.info(`AI check attempt ${u} failed (re-used previous result)`):t.info({err:E},`AI check assert attempt ${u} failed, retrying...`)}finally{u++}}if(!m?.success)try{m=await yr({action:async()=>wx({command:r,state:await Ax(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(),g=f instanceof Error?f:new Error(`${f}`)}finally{u++}if(m?.updatedMemory&&Ns(r,m.updatedMemory,t),!m?.success){let f=`AI check still failing after ${u} attempts.`;throw g&&(f+=` Latest result: ${g.message}`),new R("AssertionFailureError",f)}return{...m,succeedImmediately:!1,urlAfterCommand:s.url()}}async function Ax(r,e,t){let[n,o]=await Promise.all([tn(r,{abortSignal:t,skipWait:!0,skipWaitForPageLoad:!0,logger:e}),r.screenshot({retries:1,respectActiveFrame:!0})]);return{...n,screenshotBuff:o}}async function wx({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:m}=t,p={type:"ASSERTION"},{serializedTree:g,tree:h}=e,f=e.screenshotBuff,E=f.toString("base64"),b=u.url(),w=r.contextChoice??"MULTIMODAL",x=g;w!=="VISION_ONLY"&&(x=await Go({type:"assertion",serializedTree:g,tree:h,description:r.assertion,screenshot:E,options:{aiPageFiltering:a},fixtures:{generator:d,signal:m,logger:l,orgId:t.orgId}}),x!==g&&(p.ragUsed=!0),p.pageState=x);let A={goal:r.assertion,url:b,memory:o?r.cache?.memory:void 0,browserState:x,screenshot:E,contextChoice:w,source:c},v=await(w==="VISION_ONLY"?(_,k)=>d.getVisualAssertionResult(_,k):(_,k)=>d.getAssertionResult(_,k))(A,{useConsensus:n,attemptNumber:s,useMemory:o,disableCache:!!r.disableCache,abortSignal:m,logger:l,loggerTags:Ee(l)});return(v.result||i)&&v.relevantElements&&(p.relevantElementsSerialized=v.relevantElements.map(_=>u.getSerializedFormFromA11yId(_)).filter(_=>!!_),await Y1(v.relevantElements,u,l)),{success:v.result,thoughts:v.thoughts,afterScreenshotOverride:f,updatedMemory:o?v.updatedMemory:void 0}}async function Y1(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}}}var X1=75e4,ju=class extends Error{constructor(){super("The page content exceeds the maximum token limit for AI smart waiting."),this.name="ExceededMaxAISmartWaitingTokensError"}};async function Cx(r,e){let{logger:t}=r,{abortSignal:n,browser:o}=e,i=Date.now();try{await J1(i,r,e)}catch(a){if(a instanceof Error&&(a.name==="AbortError"||a.name==="TimeoutError")||n.aborted)return;a instanceof ju?t.warn("Skipping AI smart waiting due to excessive page size - falling back to naive waiting"):t.warn({err:a},"Unexpected error occurred during AI smart waiting");let s=o.smartWaitingTimeout-(Date.now()-i);s>0&&await j(s,n)}finally{t.debug({durationMs:Date.now()-i},"AI smart waiting complete")}}async function J1(r,e,t){let{abortSignal:n,browser:o}=t;if(o.smartWaitingTimeout<3e3){await j(o.smartWaitingTimeout,n);return}if(!e.description)throw new R("UserConfigurationError","Cannot locate element with empty description");await B(Q1(r,e,t),{milliseconds:o.smartWaitingTimeout})}async function Q1(r,e,t){let{logger:n,iframeUrl:o}=e,{browser:i}=t;for(;Date.now()-r<i.smartWaitingTimeout;)if(await yr({action:async()=>Z1(e,t),frameConfig:o?{type:"url",url:o}:void 0,browser:i,logger:n}))return}async function Z1(r,e){let{testContext:t,logger:n,filterByViewport:o,allowNotActionableNodesOverride:i}=r,{browser:a,abortSignal:s,localCodeEvalTools:c,orgId:l,generator:u}=e,d=r.description;t&&(d=await Fs({orgId:l,s:d,context:t,localTools:c,signal:s,logger:n}));let{serializedTree:m}=await tn(a,{allowNotActionableNodesOverride:i,filterByViewport:o,abortSignal:s,logger:n});if(_r(m)>X1)throw new ju;s.throwIfAborted();let g;try{g=await a.screenshot({clearHighlights:!0,respectActiveFrame:!0,retries:2})}catch(b){throw new R("ActionFailureError",`Failed to take screenshot of page to perform smart waiting. The page may be unresponsive, or your machine might be severely resource constrained. Error: ${b instanceof Error?b.message:b}`)}let f=`data:image/jpeg;base64,${g.toString("base64")}`;s.throwIfAborted();let E=await u.getSmartWaitingDecision({browserState:m,description:d,screenshot:f},{abortSignal:s,loggerTags:Ee(n)});return n.debug({result:E},"Got smart waiting result"),E.isPageReady}import{cloneDeep as xx}from"lodash-es";async function Mx(r){let{command:e,timeoutMs:t,fixtures:n}=r,{abortSignal:o}=n,i=()=>Mf(e.cache)?e.cache:void 0,a=i(),s=xx(a),c=(h=!1)=>{if(a=i(),!!a)if(h){let f=kw(s,a);a.target=f.target,a.updatedAt=f.updatedAt}else{if(!s){a=void 0;return}a.target=s.target,a.updatedAt=s.updatedAt}},l=Date.now(),u=0,d,m=500,p=!1;for(;u<2||Date.now()-l<t;){u++,u>1&&await j(m,o),o?.throwIfAborted(),a=i();let{result:h,elementWasFound:f}=await Rx({cacheToUse:a,params:r});if(d=h,p=f,h.success)break;c(),m=Math.min(m*2,1e4)}if(!d)throw new R("InternalPlatformError",`Failed to evaluate manual element assertion in ${t}ms.`);if(o?.throwIfAborted(),!d.success&&a?.target&&dl(a.target)){let h=a?.target?.memory?{target:{id:-1,memory:a.target.memory}}:void 0,{result:f}=await Rx({cacheToUse:h,params:r});d=f,d.success||c(!0)}let g=i();return d.success&&g?.target&&!p&&(g.target=xg(g.target),g.updatedAt=new Date),d}async function Rx({cacheToUse:r,params:e}){let{command:t,disableCache:n,fixtures:o,tracer:i,targetingWrapper:a}=e,{logger:s}=o;if(t.target&&!Cn(t.target))throw new Error("Element assertion with x/y is not supported yet");let c=pu(t.assertion),l,u=!1,d=xx(r);try{let{elementInteractedDisplayString:m,result:p,thoughts:g}=await a({ctx:o.ctx,tracer:i,command:t,target:t.target,cache:d?.target,action:async h=>eH(h.locator,e),options:{...t,allowNotActionableNodesOverride:!0,disableCache:n,memory:d?.target?.memory,disableGlobalLocatorRedirect:!0,source:ka(t),targetName:"target"}});return l={success:p.success,data:p.data,err:p.err,elementInteractedDisplayString:m,thoughts:g},u=!0,p.success||(s.warn({aiThoughts:g,elementString:m,err:p.err},"Element check found an element but failed"),l={...p,thoughts:g}),{result:l,elementWasFound:u}}catch(m){if(c)return l={success:!0,thoughts:`The element described does not exist on the page: ${m.message}`,err:void 0,data:void 0},{result:l,elementWasFound:u};if(!(m instanceof R)||m.reason!="ActionFailureError")throw m;return l={success:!1,err:m,data:void 0,thoughts:void 0},s.warn({err:m},"Element check did not find an element and failed"),{result:l,elementWasFound:u}}}async function eH(r,{command:e,fixtures:t}){return await t.browser.highlight(r),await tH(r,e.assertion)}async function tH(r,e){let t=!0,n,o;switch(e.type){case"ELEMENT_CONTENT":{let a=await r.textContent()??"";if(o={elementTextContent:ft(a,500,!0)},!Yr(a,e.value,e.operation,{negated:!!e.negated,ignoreCase:!1})){let s=hr(e);t=!1,n=new R("AssertionFailureError",`The content ${s} '${e.value}': ${a}`)}break}case"ELEMENT_ATTRIBUTE":{o={elementOuterHtml:ft(await r.evaluate(s=>s.cloneNode(!1).outerHTML),500,!0)};let a;try{a=await r.getAttribute(e.attr,{timeout:3e3})??""}catch(s){n=new R("AssertionFailureError",`The element does not have an attribute named ${e.attr}: ${s}`),t=!1;break}if(!Yr(a,e.value,e.operation,{negated:!!e.negated,ignoreCase:!1})){let s=hr(e);t=!1,e.operation==="EXISTS"?n=new R("AssertionFailureError",`The attribute ${e.attr} ${s}`):n=new R("AssertionFailureError",`The attribute ${e.attr} ${s} '${e.value}': ${a}`)}break}case"ELEMENT_EXISTENCE":{switch(e.condition){case"VISIBLE":{t=await r.evaluate(async(s,c)=>{let l=Date.now();for(;Date.now()-l<c;){await new Promise(d=>setTimeout(d,250));let u=s.getBoundingClientRect();if(!(u.width===0||u.height===0)&&window.getComputedStyle(s).visibility!=="hidden"&&window.getComputedStyle(s).display!=="none")return!0}return!1},Ot*1e3);break}case"EDITABLE":{t=await r.isEditable({timeout:Ot*1e3});break}case"EXISTS":{t=!0;break}case"ENABLED":{t=await r.isEnabled({timeout:Ot*1e3});break}case"FOCUSED":{t=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"})(e.condition)}if(t=e.negated?!t:t,!t){let a=hr(e);n=new R("AssertionFailureError",`The element ${a}`)}break}case"ELEMENT_NAME":{let a=await r.evaluate(s=>s.tagName);if(!Yr(a,e.value,e.operation,{negated:!!e.negated,ignoreCase:!0})){let s=hr(e);t=!1,n=new R("AssertionFailureError",`The element tag name ${s} '${e.value}': ${a}`)}break}case"ELEMENT_STYLE":{let a=await r.evaluate((s,c)=>window.getComputedStyle(s).getPropertyValue(c),e.property);if(!Yr(a,e.value,e.operation,{negated:!!e.negated,ignoreCase:!1})){let s=hr(e);t=!1,e.operation==="EXISTS"?n=new R("AssertionFailureError",`The style property ${e.property} ${s}`):n=new R("AssertionFailureError",`The style property ${e.property} ${s} '${e.value}': ${a}`)}break}default:return(a=>{throw"If Typescript complains about the line below, you missed a case or break in the switch above"})(e)}return{thoughts:void 0,success:t,data:o,err:n}}function _x(r){return r.type==="ELEMENT_EXISTENCE"&&r.negated&&r.condition==="EXISTS"}import{Jimp as rH}from"jimp";async function Ws(r,e){let t=await r.screenshot(e),n=await rH.fromBuffer(t);return{buffer:t,width:Math.ceil(n.bitmap.width??0),height:Math.ceil(n.bitmap.height??0)}}import{Jimp as Px}from"jimp";import Ah from"jpeg-js";import nH from"pixelmatch";async function Ix({ctx:r,tracer:e,command:t,disableCache:n,browser:o,targetingWrapper:i,logger:a,screenshotStorage:s}){if(t.target&&!Cn(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 Z=>Ws(o,{locator:Z.locator,...c}),options:{...t,disableCache:n,disableGlobalLocatorRedirect:!0,memory:t.cache?.target?.memory,targetName:"target"}})).result:l=await Ws(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 V=`${l.width}x${l.height}`,Z=`${u.width}x${u.height}`;return{fail:!0,thoughts:`Current screenshot (${V}) does not match saved screenshot dimensions (${Z}) - 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 Px.fromBuffer(l.buffer),m={width:l.width,height:l.height},p=await Px.fromBuffer(u.buffer),g={width:u.width,height:u.height},h,f=m.width*m.height,E=g.width*g.height,b=Math.abs(m.height-g.height),w=Math.abs(m.width-g.width);if(f>E){let V=d.cover({w:g.width,h:g.height});l.buffer=await V.getBuffer("image/jpeg"),h="current",l.width=g.width,l.height=g.height}else if(E>f){let V=p.cover({w:m.width,h:m.height});u.buffer=await V.getBuffer("image/jpeg"),h="saved"}let x={data:Buffer.alloc(l.width*l.height*4),width:l.width,height:l.height},A=t.threshold??.1,v=nH(Ah.decode(u.buffer).data,Ah.decode(l.buffer).data,x.data,l.width,l.height,{threshold:A,diffColorAlt:[0,255,0]})/(l.width*l.height)*100,_=v>A*100,k=`Visual diff of ${v.toFixed(2)}% detected, which is ${_?"over":"under"} the threshold of ${A*100}%.`;if(h&&(k+=` The ${h} screenshot was cropped since it was taller by ${b} pixels and wider by ${w} pixels.`),_)throw new R("ActionFailureError",k);return{fail:_,thoughts:k,beforeScreenshotOverride:l.buffer,afterScreenshotOverride:Ah.encode(x,75).data,succeedImmediately:!1,urlAfterCommand:o.url()}}var oH=3e4;function iH(r){if(!r.body)return{};switch(r.body.type){case"json":return{content:r.body.content,contentType:"application/json"};case"form-urlencoded":{let e=new URLSearchParams;return Object.entries(r.body.content).forEach(([t,n])=>{e.append(t,n)}),{content:e.toString(),contentType:"application/x-www-form-urlencoded;charset=UTF-8"}}}}async function $u({command:r,logger:e,baseUrl:t,fetchImplementation:n=fetch}){let o=r.timeout??oH/1e3,i=Object.fromEntries(Object.entries(r.headers||{}).filter(([g,h])=>g&&h)),a=new URLSearchParams;Object.entries(r.params||{}).filter(([g,h])=>g&&h).forEach(([g,h])=>{a.append(g,h)});let s=a.toString(),c;if($i(r.url)&&(c=r.url),t&&qi(r.url,t)&&(c=new URL(r.url,t).toString()),!c)throw new R("ActionFailureError",`Invalid URL: ${r.url}`);let l=c;e.info({url:l,searchParams:s,headers:i,body:r.body,method:r.method},"Making HTTP request");let d=await B((async()=>{let g=s?`${l}?${s}`:l;try{let h=iH(r),f=new Headers(i);return h.contentType&&!f.has("Content-Type")&&f.set("Content-Type",h.contentType),await n(g,{headers:f,method:r.method,body:h.content})}catch(h){throw e.error({err:h},"Failed to make HTTP request"),new Error(`Failed to make HTTP request: ${h}`)}})(),{milliseconds:o*1e3,fallback:()=>{throw new R("ActionFailureError",`Fetch request timed out after ${o} seconds`)}});if(!d.ok){let g;try{g=await d.text()}catch(h){g=`Failed to read response body: ${h}`}throw new R("ActionFailureError",`Fetch request failed with status ${d.status}: ${g}`)}let m={};d.headers.forEach((g,h)=>{m[h]=g});let p={status:d.status,headers:m,request:{url:d.url,method:r.method,headers:i}};if(r.body?.type==="json"&&r.body.content)try{p.request.json=JSON.parse(r.body.content)}catch{}if(d.headers.get("content-type")?.includes("json"))try{p.json=await d.json()}catch{}else d.headers.get("content-type")?.includes("text")&&(p.text=await d.text());return p}var aH=5e3;async function Lx({timeout:r=Ot,...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 qu(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 j(s,e.signal),s=Math.min(Math.floor(s*1.5),aH);else return i}return i=await qu(e),i}async function qu({assertion:r,browser:e,autoExpandIframes:t}){switch(r.type){case"CONTENT":case"CONTENT":{let o,i=!1,a;try{let s;if(t){let c=await e.evaluateFunctionInAllFrames(Ox,{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(Ox,{value:r.value,negated:!!r.negated,returnHtml:!0},"checking page content"));if(!i){let c=r.negated?fn.CONTAINS:Sn.CONTAINS;a=new R("AssertionFailureError",`The page ${c} '${r.value}'.`),o=s}}catch(s){a=new R("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)}}function Ox({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 sH=3e4;async function Nx({command:r,logger:e,baseUrl:t,fetchImplementation:n=fetch}){let o=r.timeout??sH/1e3,i=new AbortController,a=Object.fromEntries(Object.entries(r.headers||{}).filter(([d,m])=>d&&m));a["Content-Type"]="application/json";let s;if($i(r.url)&&(s=r.url),t&&qi(r.url,t)&&(s=new URL(r.url,t).toString()),!s)throw new R("ActionFailureError",`Invalid URL: ${r.url}`);let l=await B((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 R("ActionFailureError",`GraphQL request timed out after ${o} seconds`);if(!l.ok){let d,m=await l.text();try{d=JSON.parse(m)}catch{throw new R("ActionFailureError",`GraphQL request failed with status ${l.status}: ${m}`)}throw d?.errors?.length&&d?.errors[0]?.message?new R("ActionFailureError",`GraphQL request failed with status ${l.status}: ${d.errors[0].message}`):new R("ActionFailureError",`GraphQL request failed with status ${l.status}: ${m}`)}let u={};return l.headers.forEach((d,m)=>{u[m]=d}),{status:l.status,headers:u,json:await l.json()}}var Ku=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([tn(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 Go({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}}),m={url:this.browser.url(),browserState:d,startingScreenshot:t,history:n,goal:e,screenshot:u,lastError:a};return await this.generator.getMultiturnAiActionEvaluation(m,{disableCache:o,abortSignal:this.executeAbortController.signal,loggerTags:{...Ee(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([tn(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")}`,m=await Go({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}}),p={url:c,browserState:m,startingScreenshot:t,history:n,goal:e,actionHint:o,screenshot:d};try{return await this.generator.getMultiturnAiActionCommand(p,{disableCache:i,abortSignal:this.executeAbortController.signal,loggerTags:{...Ee(a)},langfuseSessionId:s})}catch(g){throw new R("InternalWebAgentError",`Error generating command: ${g instanceof Error?g.message:g}`,{errOptions:{cause:g}})}}async getBrowserState(e){return tn(this.browser,e)}async locateElement(e){return await vh({...e,aiPageFiltering:!!this.options?.aiPageFiltering},this.getControllerFixtures())}async locateElementWithSelector(e,t){return yr({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 m=i[d],p=await this.wrapElementTargetingCommand({ctx:e,tracer:t,command:n,target:m,cache:a[d],action:async g=>g,options:{...c,targetName:o[d]}});u.push(p)}try{let d=await s(...u.map(g=>g.result)),m=g=>g==="fromTarget"?"From Target":g==="toTarget"?"To Target":"Target",p=u.map((g,h)=>g.thoughts?`${m(o[h])}: ${g.thoughts}`:void 0).filter(g=>!!g).join(" -------------- ")||void 0;return{result:d,elementInteractedDisplayStrings:u.map(g=>g.elementInteractedDisplayString),thoughts:p}}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 R("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 yr({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&&nm(i)){t.warn({err:i},"Invalid mpath error, retrying element targeting command");continue}if(!this.browser.userBrowserSettings.visualActions&&(am(i)||om(i))){t.warn({err:i},"Invalid momentic id error, retrying element targeting command");continue}if(sm(i)){t.warn({err:i},"Invalid backend node id error, retrying element targeting command");continue}if(i instanceof Fr&&i.retryableWithAI){t.warn({err:i},"Element cache disqualification error, retrying element targeting command");continue}throw i}throw n instanceof R?n:new R("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 R("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 j(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:m,source:p}=s,g=this.logger.child({commandId:c.id}),h=this.shouldUseMemory(),f=s.retriesWithAI??1,E=!1,b=Dx(e.cache);if((!b||l)&&!Wd(o))throw new R("ActionFailureError","Cannot target element with no cached data or element descriptor");if(u)return this.wrapHardcodedCssTargetingCommandHelper(e);l&&(g.info("Cache explicitly disabled for this step"),E=!0,b=void 0),b&&this.browser.userBrowserSettings.disableSecondaryCacheResolution&&b.targetSource==="HEURISTIC_HEALED"&&(E=!0,b=void 0),b?.inputDescription&&!vx(o.elementDescriptor,b.inputDescription)&&(g.warn({old:b.inputDescription,new:o.elementDescriptor},"Target cache was generated with a different description, clearing it automatically"),E=!0,b=void 0);let w=A=>!!A&&dl(A),x=!0;if(!w(b)){x=!1,g.info({description:o.elementDescriptor,targetHealingInProgress:m,cacheBustedBeforeAction:E,memory:s.memory,useMemory:h},"Prompting AI for an updated element location"),(E||!i)&&await Cx({description:o.elementDescriptor,iframeUrl:s.iframeUrl,source:p,logger:g,allowNotActionableNodesOverride:s.allowNotActionableNodesOverride},this.getControllerFixtures(t)),f--;let A;try{A=await vh({description:o.elementDescriptor,disableCache:!!s.disableCache,iframeUrl:s.iframeUrl,source:p,useMemory:h,memory:h?s.memory:void 0,aiPageFiltering:!!this.options?.aiPageFiltering,allowNotActionableNodesOverride:s.allowNotActionableNodesOverride,logger:g},this.getControllerFixtures(t))}catch(_){if(_ instanceof _n&&_.updatedLocatorMemory){let k={id:-1,...i,memory:_.updatedLocatorMemory};hu({cmd:c,key:d,newTarget:k,logger:g,updatedWithAI:!0})}throw new R("ActionFailureError",_.message)}A.frameConfig&&this.browser.setActiveFrameConfig(A.frameConfig);let M=s.disableGlobalLocatorRedirect?{locator:A.resolution.locator}:await this.attemptLocatorRedirect(A.resolution.locator,g),v=await a(M);return hu({cmd:c,key:d,newTarget:A.target,logger:g,updatedWithAI:!0}),m&&(n.recordTargetAutoHeal({healType:"AI"}),A.target.targetSource="AI_HEALED",A.target.targetUpdateTime=new Date().toUTCString(),A.target.targetUpdateLoggerTags=Ee(g)),{result:v,elementInteractedDisplayString:A.resolution.displayString,thoughts:A.thoughts}}try{let A=await this.browser.resolveTarget(t,b,{allowNotActionableNodesOverride:s.allowNotActionableNodesOverride,targetName:d,logger:g,signal:this.executeAbortController.signal});(this.browser.userBrowserSettings.visualActions||this.browser.userBrowserSettings.globalLocatorRedirect!==!1)&&await this.browser.scrollIntoViewIfNeeded(A.locator);let M=s.disableGlobalLocatorRedirect?{locator:A.locator}:await this.attemptLocatorRedirect(A.locator,g),v=await a(M);if(gt.increment("cache_target_resolution_v2",1,["outcome:hit","platform:web",`hasRequirements:${!!b.requirements}`,`hasAdditionalElements:${!!b.additionalElements}`,`orgId:${this.orgId}`,"cliVersion:0.16.3"]),hu({cmd:c,key:d,newTarget:b,logger:g,updatedWithAI:!1}),x){let _=A.decisions.filter(k=>k.matched);if(_.length!==1)g.warn({decisions:A.decisions},"Expected exactly 1 matching method for element location, got more or less");else{let k=_[0].type;n.recordTargetAutoHeal({healType:k})}}return{result:v,elementInteractedDisplayString:A.displayString}}catch(A){this.throwIfClosed();let M="unknown";A instanceof Ur&&A.cacheMissReason&&(M=A.cacheMissReason),gt.increment("cache_target_resolution_v2",1,["outcome:miss","platform:web",`hasRequirements:${!!b.requirements}`,`hasAdditionalElements:${!!b.additionalElements}`,`orgId:${this.orgId}`,"cliVersion:0.16.3",`missReason:${M}`]);let v=!1;if((A instanceof Fr||nm(A)||am(A)||sm(A)||NS(A)||om(A)||DS(A))&&(v=!0),A instanceof R&&!v)throw g.error({err:A},"Failed to execute action with cached target (fatal)"),A;if(f>0&&o){g.info({err:A},"Failed to execute action with cached target, retrying with AI");let _;return b.memory&&Af(b.memory)&&(_=b.memory),this.wrapElementTargetingCommand({ctx:t,tracer:n,command:c,target:o,cache:void 0,originalCache:i,action:a,options:{...s,memory:_,retriesWithAI:f,targetHealingInProgress:!0}})}throw new R("ActionFailureError",A.message,{errOptions:{cause:A}})}}async attemptLocatorRedirect(e,t){return this.browser.userBrowserSettings.globalLocatorRedirect!==!1?this.browser.performTargetRedirection(e,t):{locator:e}}async screenshotWithDimensions(e){return Ws(this.browser,e)}async executePresetCommand(e,t,n,o,i){this.options?.slowMoMs&&await j(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 R("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&&Zf(n)?await this.browser.waitForDOMStability({timeout:Te}):!this.browser.userBrowserSettings.visualActions&&["PRESS","TYPE"].includes(n.type)&&await this.browser.waitForDOMStability({timeout:ie}),this.options?.autoFollowNewTabs&&await px({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{xu(n,c)}}createCallbacksForBrowser(e){return{createIsolatedFolder:()=>$g(e)}}async resolveCommandTemplateStrings(e,t){return Ru({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()?Wu({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 R("ActionFailureError","Missing assertion");if(n.timeout&&n.timeout>1800)throw new R("AssertionFailureError",`AI check timeout of ${n.timeout} exceeds the maximum allowed value of 30 minutes.`);return Wu({command:n,fixtures:this.getControllerFixtures(e),useMemory:this.shouldUseMemory(),aiPageFiltering:!!this.options?.aiPageFiltering,logger:a})}case"AI_EXTRACT":{if(!n.goal.trim())throw new R("ActionFailureError","Cannot perform AI extraction without goal");if(n.schema){let h=ZE(n.schema);if(h)throw new R("UserConfigurationError",h)}let p=await this.browser.getCondensedHtml(),g=await this.browser.screenshot({retries:2});try{let h=await this.generator.getTextExtraction({goal:n.goal,browserState:p,returnSchema:n.schema,screenshot:`data:image/jpeg;base64,${g.toString("base64")}`},{disableCache:i,abortSignal:this.executeAbortController.signal,loggerTags:Ee(a)});if(h.result==="NOT_FOUND")throw new R("ActionFailureError","No relevant data found for extraction goal on this page");if(h.thoughts?.includes("MaxGenerationLengthExceededError"))throw new R("UserConfigurationError",h.thoughts);return{thoughts:h.thoughts||void 0,data:h.result,succeedImmediately:!1,urlAfterCommand:this.browser.url()}}catch(h){let f=h.message;throw f.includes("MaxGenerationLengthExceededError")?new R("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."):f.includes("AIProviderError")&&f.includes("time")?new R("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:h}}):h}}case"NAVIGATE":if(!$i(n.url)&&!qi(n.url,this.browser.baseUrl))throw new R("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":throw new R("UserConfigurationError","Captcha solving is no longer available on Momentic");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 p,g;if(n.target&&Nr(n.target))await this.browser.hoverUsingVisualCoordinates(n.target.pixels);else if(n.target&&n.target.elementDescriptor.trim()){let{elementInteractedDisplayString:E,thoughts:b}=await this.wrapElementTargetingCommand({ctx:e,tracer:t,command:n,target:n.target,cache:n.cache?.target,action:w=>this.browser.hover(w),options:{...n,targetName:"target",disableGlobalLocatorRedirect:!0,disableCache:i}});p=E,g=b}let h=this.browser.getViewport()?.height??Ln.height,f=this.browser.getViewport()?.width??Ln.width;switch(n.type){case"SCROLL_UP":await this.browser.scrollVertical(-(n.deltaY??h));break;case"SCROLL_DOWN":await this.browser.scrollVertical(n.deltaY??h);break;case"SCROLL_LEFT":await this.browser.scrollHorizontal(-(n.deltaX??f));break;case"SCROLL_RIGHT":await this.browser.scrollHorizontal(n.deltaX??f);break}return{succeedImmediately:!1,urlAfterCommand:this.browser.url(),elementInteracted:p,thoughts:g}}case"WAIT_FOR_URL":{if(n.timeout&&n.timeout>1800)throw new R("UserConfigurationError",`Wait for URL timeout of ${n.timeout} exceeds the maximum allowed value of 30 minutes.`);let p=n.matcher;await this.browser.waitForUrl({beforeUrl:this.browser.url(),matcher:p},{timeout:n.timeout?n.timeout*1e3:void 0,negated:n.negated,caseInsensitive:n.caseInsensitive});break}case"WAIT":if(n.delay>1800)throw new R("UserConfigurationError",`Wait timeout of ${n.delay} seconds exceeds the maximum allowed value of 30 minutes`);let c=n.delay*1e3;await j(c,this.executeAbortController.signal);break;case"REFRESH":await this.browser.refresh({loadTimeoutMs:n.loadTimeout?n.loadTimeout*1e3:void 0});break;case"CLICK":{if(Nr(n.target)){await this.browser.clickUsingVisualCoordinates(n.target.pixels,n);break}let p=this.browser.url(),{elementInteractedDisplayString:g,result:h,thoughts:f}=await this.wrapElementTargetingCommand({ctx:e,tracer:t,target:n.target,command:n,cache:n.cache?.target,action:b=>this.browser.click(b,this.createCallbacksForBrowser(this.orgId),n),options:{disableCache:i,targetName:"target",...n}}),E={urlAfterCommand:this.browser.url(),succeedImmediately:!1,elementInteracted:g,thoughts:f,data:h.downloadedFile?{downloadedFile:h.downloadedFile}:void 0};return Tu(p,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(Nr(n.fromTarget)&&Nr(n.toTarget)){await this.browser.dragAndDropUsingVisualCoordinates(n.fromTarget.pixels,n.toTarget.pixels,{hoverDurationMs:n.hoverSeconds?n.hoverSeconds*1e3:void 0});break}if(Nr(n.fromTarget)||Nr(n.toTarget))throw new Error("Drag and drop targets must be both coordinates or both descriptions");let{elementInteractedDisplayStrings:p,thoughts:g}=await this.wrapMultiElementTargetingCommand({ctx:e,tracer:t,command:n,targetNames:["fromTarget","toTarget"],descriptions:[n.fromTarget,n.toTarget],caches:[n.cache?.fromTarget,n.cache?.toTarget],action:(h,f)=>this.browser.dragAndDrop(h.locator,f.locator,{hoverDurationMs:n.hoverSeconds?n.hoverSeconds*1e3:void 0,steps:n.steps}),options:{useSelector:!!n.useSelector,disableCache:i}});return{succeedImmediately:!1,urlAfterCommand:this.browser.url(),elementInteracted:p[0],thoughts:g}}case"MOUSE_DRAG":{let p=parseInt(n.deltaX),g=parseInt(n.deltaY),h=n.steps??5;if(isNaN(p)||isNaN(g))throw new R("ActionFailureError",`Invalid pixel values passed to mouse drag command: (${n.deltaX}, ${n.deltaY})`);if(n.target&&Nr(n.target)){await this.browser.mouseDragUsingVisualCoordinates({deltaX:p,deltaY:g,steps:h,fromTarget:n.target.pixels});break}let f,E;if(n.target?.elementDescriptor){let{elementInteractedDisplayString:b,thoughts:w}=await this.wrapElementTargetingCommand({ctx:e,tracer:t,command:n,target:n.target,cache:n.cache?.target,action:async x=>this.browser.mouseDrag(p,g,h,x.locator,{force:n.force}),options:{disableCache:i,targetName:"target",...n}});f=b,E=w}else await this.browser.mouseDrag(p,g,h,void 0,{force:n.force});return{succeedImmediately:!1,urlAfterCommand:this.browser.url(),elementInteracted:f,thoughts:E}}case"SELECT_OPTION":{if(!Cn(n.target))throw new Error("Select with x/y is not supported yet");let p=n.target.elementDescriptor,g=n.choice,{elementInteractedDisplayString:h,thoughts:f}=await this.wrapElementTargetingCommand({ctx:e,tracer:t,command:n,target:{type:"description",elementDescriptor:p},cache:n.cache?.target,action:E=>this.browser.selectOption(E,g,n.force),options:{...n,targetName:"target",disableCache:i,source:ka(n)}});return{succeedImmediately:!1,urlAfterCommand:this.browser.url(),elementInteracted:h,thoughts:f}}case"TAB":{let p={loadTimeoutMs:n.loadTimeout?n.loadTimeout*1e3:void 0,retry:!0};await this.browser.switchToPage(n.action,p);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 l=await this.browser.setCookie(n.value);a.debug({results:l},"Set cookies");break;case"LOCAL_STORAGE":if(!n.value||!n.key)break;await this.browser.setLocalStorage(n.key,n.value);break;case"JAVASCRIPT":{let p;try{n.environment==="BROWSER"?(p=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:p},"Executed JavaScript in browser")):p=await Jr({orgId:this.orgId,code:n.code,fragment:!!n.fragment,context:o,timeoutMs:n.timeout?n.timeout*1e3:void 0,logger:a,localTools:this.localCodeEvalTools,signal:this.executeAbortController.signal,callbacks:{onPersistentVariableUpdates:async g=>{if(!this.options?.scratchPadId){a.warn({updates:g},"Got persistent variable updates but scratch pad is not available");return}await this.storage.savePersistentVariables?.({scratchPadId:this.options?.scratchPadId,orgId:this.orgId,updates:g,logger:a})}}})}catch(g){throw this.throwIfClosed(),new R("ActionFailureError",g instanceof Error?g.message:`${g}`,{errOptions:{cause:g}})}try{JSON.stringify(p)}catch(g){throw new R("ActionFailureError",`Return value is not serializable: ${g instanceof Error?g.message:`${g}`}`,{errOptions:{cause:g}})}return{urlAfterCommand:this.browser.url(),succeedImmediately:!1,data:p}}case"TYPE":{if(n.target&&Nr(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 p=this.browser.url(),g,h,f=Dx(n.target),E=this.browser.userBrowserSettings.globalLocatorRedirect===void 0||this.browser.userBrowserSettings.globalLocatorRedirect==="always";if(f){let{elementInteractedDisplayString:w,thoughts:x}=await this.wrapElementTargetingCommand({ctx:e,tracer:t,command:n,target:f,cache:n.cache?.target,action:A=>this.browser.typeIntoTarget(n.value,A,{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:ka(n)}});g=w,h=x}else await this.browser.type(n.value,{force:n.force,clearContent:n.clearContent,forceClearContent:n.forceClearContent,delay:n.delay,pressEnter:n.pressEnter},!0);let b={urlAfterCommand:this.browser.url(),succeedImmediately:!1,elementInteracted:g,thoughts:h};return Tu(p,b.urlAfterCommand)&&(b.succeedImmediately=!0,b.succeedImmediatelyReason="URL changed"),b}case"HOVER":{if(Nr(n.target)){await this.browser.hoverUsingVisualCoordinates(n.target.pixels);break}let{elementInteractedDisplayString:p,thoughts:g}=await this.wrapElementTargetingCommand({ctx:e,tracer:t,command:n,target:n.target,cache:n.cache?.target,action:h=>this.browser.hover(h),options:{...n,targetName:"target",disableCache:i}});return{succeedImmediately:!1,urlAfterCommand:this.browser.url(),elementInteracted:p,thoughts:g}}case"FOCUS":{if(!Cn(n.target))throw new Error("Focus with x/y is not supported yet");let{elementInteractedDisplayString:p,thoughts:g}=await this.wrapElementTargetingCommand({ctx:e,tracer:t,command:n,target:n.target,cache:n.cache?.target,action:h=>this.browser.focus(h),options:{...n,targetName:"target",disableCache:i}});return{succeedImmediately:!1,urlAfterCommand:this.browser.url(),elementInteracted:p,thoughts:g}}case"BLUR":{if(n.target&&!Cn(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:p,thoughts:g}=await this.wrapElementTargetingCommand({ctx:e,tracer:t,target:n.target,command:n,cache:n.cache?.target,action:h=>this.browser.blur(h),options:{...n,targetName:"target",disableCache:i}});return{succeedImmediately:!1,urlAfterCommand:this.browser.url(),elementInteracted:p,thoughts:g}}case"PRESS":let u=this.browser.url();await this.browser.press(n.value,{repeat:n.repeat,convertMeta:n.convertMeta??!0,delayMs:n.delayMs});let d={urlAfterCommand:this.browser.url(),succeedImmediately:!1};return Tu(u,d.urlAfterCommand)&&(d.succeedImmediately=!0,d.succeedImmediatelyReason="URL changed"),d;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 p=new cH,g=lH(fetch,p),h;try{h=new URL(n.url).hostname}catch{}let f=await $u({command:n,baseUrl:this.browser.baseUrl,logger:a,fetchImplementation:g});return{data:fl.parse({...f,cookies:ec(p,h)}),succeedImmediately:!1,urlAfterCommand:this.browser.url()}}case"GRAPHQL_REQUEST":return{data:await Nx({command:n,baseUrl:this.browser.baseUrl,logger:a}),succeedImmediately:!1,urlAfterCommand:this.browser.url()};case"VISUAL_DIFF":return Ix({ctx:e,tracer:t,command:n,disableCache:i,browser:this.browser,logger:a,storage:this.storage,screenshotStorage:this.visualDiffScreenshotStorage,targetingWrapper:p=>this.wrapElementTargetingCommand(p)});case"FILE_UPLOAD":{let p,g;if(n.fileSource.type==="URL"?(g=n.fileSource.url,p=await eR({uri:n.fileSource.url,logger:a,orgId:this.orgId})):n.fileSource.type==="USER_FILE"&&(g=n.fileSource.name,p=await this.uploadedFileStorage?.getFileForUpload(n.fileSource.name,this.orgId)),!p)throw new R("UserConfigurationError",`Attempted to use non-existent file for upload step: ${g}`);await this.browser.setFileChooserHandler({...p,filename:n.filename});break}case"AUTH_SAVE":return{data:await this.browser.saveAuthState(),succeedImmediately:!1,urlAfterCommand:this.browser.url()};case"AUTH_LOAD":{let p;if(!n.storageState.trim())p=void 0;else if(p=await Jr({orgId:this.orgId,code:n.storageState,fragment:!1,context:o,logger:a,localTools:this.localCodeEvalTools,signal:this.executeAbortController.signal}),typeof p!="object")throw new R("ActionFailureError",`Credentials must evaluate to an object (received ${typeof p} instead)`);let g;try{g=Ob.optional().parse(p)}catch(h){throw new R("ActionFailureError",`Credentials provided do not follow the required format: ${h}`)}await this.browser.loadAuthState(g);break}case"ELEMENT_CHECK":{let p=(n.timeout??Ot)*1e3,g=this.generator.getAgentConfig()?.assertion;if(_x(n.assertion)&&!n.useSelector&&n.target.type==="description"&&g&&g!=="v1"){let f={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 Wu({command:f,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{f.cache?.memory&&Ns(n,f.cache?.memory.traces,a)}}let h=await Mx({command:n,tracer:t,timeoutMs:p,targetingWrapper:f=>this.wrapElementTargetingCommand(f),fixtures:this.getControllerFixtures(e),disableCache:i});return{fail:!h.success,data:h.data,elementInteracted:h.elementInteractedDisplayString,thoughts:h.err?.message??h.thoughts??`Element assertion ${h.success?"succeeded":"failed"}.`,succeedImmediately:!1,urlAfterCommand:this.browser.url()}}case"PAGE_CHECK":{let p=await yr({action:async()=>Lx({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:!p.success,data:p.data,thoughts:p.success?"Page assertion passed.":p.err?.message??`Page assertion still failing after ${n.timeout} seconds.`,urlAfterCommand:this.browser.url(),succeedImmediately:!1}}case"REGISTER_REQUEST_LISTENER":{let p=new Yn(n.requestMatcher),g=this.browser.registerRequestListener(p);return this.registeredListeners[n.key]=g.then(async h=>await Qg(h)).catch(h=>{a.error({err:h},"Failed to get request listener response")}),{succeedImmediately:!1,urlAfterCommand:this.browser.url()}}case"AWAIT_LISTENER":{let p=this.registeredListeners[n.key];if(!p)throw new R("ActionFailureError",`No listener registered with key: ${n.key}`);let g=n.timeout??10;return{data:await B(p,{milliseconds:g*1e3,message:`Request listener timed out after ${g} seconds`}),succeedImmediately:!1,urlAfterCommand:this.browser.url()}}case"RECORD_REQUESTS":{let p=new Yn(n.requestMatcher);return this.recordedRequests[n.key]={},this.browser.registerRequestRecorder(n.key,{matches:g=>p.matches({url:g.request.url,method:g.request.method}),onRequestStart:(g,h)=>{this.recordedRequests[n.key][g]=Lu(h)},onRequestComplete:(g,h)=>{this.recordedRequests[n.key]?.[g]&&(this.recordedRequests[n.key][g]=Lu(h))}}),{succeedImmediately:!1,urlAfterCommand:this.browser.url()}}case"GET_RECORDED_REQUESTS":{let p=this.recordedRequests[n.key];if(!p)throw new R("ActionFailureError",`No recorder registered with key: ${n.key}`);return delete this.recordedRequests[n.key],{data:Object.values(p),succeedImmediately:!1,urlAfterCommand:this.browser.url()}}case"SET_HEADER":{let p;return n.requestMatcher&&(p=new Yn(n.requestMatcher)),this.browser.setHeader(n.name,n.value,p),{succeedImmediately:!1,urlAfterCommand:this.browser.url()}}case"MOCK_ROUTE":return{data:{key:this.browser.registerMock(n.key,new Yn(n.requestMatcher),async(g,h)=>{let f=await Jr({orgId:this.orgId,code:n.responseGenerator,fragment:!1,context:o,timeoutMs:void 0,logger:a,localTools:this.localCodeEvalTools,mock:{request:g,response:h},disallowVariableUpdates:!0,responseSerialization:"RESPONSE"}),E=Lb.parse(f);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(p=>{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:Ee(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 Bu({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:Ee(this.logger)})}async getFailureRecoveryPlan(e){return this.generator.getFailureRecoveryPlan(e,{disableCache:!0,abortSignal:this.executeAbortController.signal,loggerTags:Ee(this.logger)})}};import{cloneDeep as uH}from"lodash-es";import zx from"truncate-json";var kx=1e3,Ux=5e6,dH=5*1024*1024;function Hx(r,e){for(let t=0;t<r.length;t++){let n=r[t];try{if(n.data){let{jsonString:o}=zx(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":Fx(n);break;case"MOBILE_AI_ACTION_STEP":case"MOBILE_MODULE_STEP":Fx(n),Hx(n.steps,e);break;default:{let o=n;throw new Error("If Typescript complains about the line below, you missed a case or break in the switch above")}}}}function Fx(r){if(r.type==="MOBILE_PRESET_STEP"){let e=r.command;"cache"in e&&e.cache&&(e.cache=void 0)}}function Bx(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 Yu(r,e){let t=uH(r);if(Hx(t,e),t.length>kx)return e.error("Database content violation: results too long, truncating before insertion"),t.slice(0,kx);let n=Bx(t,e);if(n.length>Ux)for(e.error({serializedLength:n.length,resultsArrayLength:t.length},"Database content violation: results too large, truncating before insertion");n.length>Ux;)t.pop(),n=Bx(t,e);let{jsonString:o}=zx(n,dH);try{return Bt.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 mH}from"async_hooks";var js=new mH;function pH(r){js.enterWith({activeTracers:[r]})}function gH(r,e){let t=js.getStore()?.activeTracers;if(!t)return e();t.push(r);try{return e()}finally{t.pop()}}async function hH(r,e){let t=js.getStore()?.activeTracers;if(!t)return e();let n=[...t,r];return js.run({activeTracers:n},e)}var Pr={globalAls:js,initializeRootTracerContext:pH,withChildTracer:gH,withChildTracerAsync:hH};var Vo=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 Pr.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 Pr.withChildTracerAsync(i,()=>B(t(i,o),{milliseconds:n?.timeoutMs??1/0,signal:n?.signal,message:n?.timeoutMsg??`Operation timed out after ${n?.timeoutMs??1/0}ms (${e})`})):a=await Pr.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(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:{},subSpans:[]},i=n[0]??void 0;Object.assign(o,i??{}),this.addSpan(o);let a=new r(o),s;try{i?.signal||i?.timeoutMs?s=await Pr.withChildTracerAsync(a,()=>B(t(o),{milliseconds:i?.timeoutMs??1/0,signal:i?.signal,message:i?.timeoutMsg??`Operation timed out after ${i?.timeoutMs??1/0}ms${"name"in i?` (${i.name})`:""}`})):s=await Pr.withChildTracerAsync(a,()=>t(o)),o.endTime=Date.now(),o.durationMs=o.endTime-o.startTime}catch(c){throw o.error=c instanceof Error?c.message:String(c),o.endTime=Date.now(),o.durationMs=o.endTime-o.startTime,c}return s}getRootSpan(){return this.finished||this.finish(),{type:"SECTION",name:"root step span",startTime:this.startTime,endTime:this.endTime,subSpans:this.spans,attributes:{},durationMs:this.endTime?this.endTime-this.startTime:void 0}}};function ae(){let r=Pr.globalAls.getStore()?.activeTracers,e;return!r||r.length===0?e=void 0:e=r[r.length-1],e||new Vo}async function Gx(r){let{driver:e,abortSignal:t,logger:n,packageName:o}=r,i;try{i=await B(e.execute("mobile: shell",{command:"dumpsys",args:["activity","recents"]}),{signal:t,milliseconds:1e4})}catch(s){t?.throwIfAborted(),n.warn({err:s,packageName:o},"Failed to read recents output while removing package");return}if(typeof i!="string"){n.warn({packageName:o,outputType:typeof i},"Unexpected dumpsys output when removing package from recents");return}let a=fH(i,o);if(a.length!==0)for(let s of a){t?.throwIfAborted();try{await e.execute("mobile: shell",{command:"am",args:["stack","remove",s.toString()]}),n.info({packageName:o,taskId:s},"Removed task from recents")}catch(c){t?.throwIfAborted(),n.warn({err:c,packageName:o,taskId:s},"Failed to remove task from recents")}}}function fH(r,e){let t=r.split("Task{");if(t.length<=1)return[];let n=new Set;for(let o of t.slice(1)){let i=`Task{${o}`;if(!i.includes(e)||i.includes("app.lawnchair/.LawnchairLauncher"))continue;let a=i.match(/taskId=(\d+)/);if(!a)continue;let[,s]=a;if(!s)continue;let c=Number.parseInt(s,10);Number.isNaN(c)||n.add(c)}return Array.from(n)}function $s(r){let e=[],t=r.getAttribute("text")??"",n=r.getAttribute("hint")??"",o=r.getAttribute("showing-hint")==="true";t.trim()&&!o&&t.trim()!==n.trim()&&e.push(t.trim());for(let i of Array.from(r.childNodes??[]))if(i.nodeType===3){let a=i.nodeValue??"";a.trim()&&e.push(a.trim())}else if(i.nodeType===1){let a=$s(i);a.trim()&&e.push(a.trim())}return e.join(" ").trim()}import{mkdirSync as BH}from"fs";import{tmpdir as zH}from"os";import Jx from"path";import{diff as FH}from"deep-object-diff";import{cloneDeep as Xx}from"lodash-es";import $x from"fontoxpath";import SH from"@prettier/plugin-xml";import yH from"prettier";import{DOMParser as bH,XMLSerializer as EH}from"slimdom";var TH=new Set(["android.webkit.webview","com.facebook.react.views.webview.reactwebview","com.tencent.smtt.sdk.webview","com.tencent.smtt.sdk.x5webview","org.xwalk.core.xwalkview","com.uc.webview.export.webview"]);function qs(r){let e=r.toLowerCase();return e.endsWith("webview")||TH.has(e)}function vH(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 AH=new Set(["index","package","a11y-important","screen-reader-focusabl"]),wH=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"]),CH=new Set(["text","hint"]),RH=new Set(["live-region","drawing-order"]),xH=new Set(["displayed","enabled"]);function MH(r,e){let t={};for(let[n,o]of Object.entries(e))AH.has(n)||n==="class"&&r===o||n==="focusable"&&o==="true"&&e.clickable==="true"||wH.has(n)&&o==="false"||CH.has(n)&&o===""||xH.has(n)&&o==="true"||RH.has(n)&&o==="0"||n!=="id"&&(t[n]=o);return t}function Vx(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 m of e.attributes){let p=m.name,g=m.value;g!=null&&(l[p]=String(g))}let u=MH(e.tagName,l);for(let[m,p]of Object.entries(u))t.setAttribute(m,p);if(o.set(c,e),i.set(c,t),qs(e.tagName)){let m=s?.injectedWebviewContent??"";if(s?.removeWebviewContent){for(;t.firstChild;)t.removeChild(t.firstChild);return}else if(!s?.disableMomenticAccessibilityTree&&m.trim().length>0){for(;t.firstChild;)t.removeChild(t.firstChild);m.trim().length>0&&t.appendChild(n.createCDATASection(`
4361
4361
  ${m}
4362
- `));return}}let d=Array.from(e.childNodes??[]);for(let m of d){let p=m.nodeType;if(p===3){let g=m.nodeValue;g&&g.trim().length>0&&t.appendChild(n.createTextNode(g));continue}if(p===1){let g=m;if(!IH(g,s?.viewportBounds))continue;let h=n.createElement(vH(g.tagName));Vx(r,g,h),t.appendChild(h)}}}function _H(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;Vx(a,e,s);let c=new EH().serializeToString(o);return{prunedDocument:o,prunedIdToElement:i,xml:c}}async function Wx(r,e){let t=new bH,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}=_H(t,i,o,e);return{xml:await yH.format(c,{parser:"xml",plugins:[SH],printWidth:120,tabWidth:1,singleAttributePerLine:!1}),originalXml:r,document:n,idToElement:o,prunedDocument:a,prunedIdToElement:s}}function PH(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 Xu(r,e){let t=r.idToElement.get(e);if(t)return PH(t)}function wh(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 Wo(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 IH(r,e){if(!e)return!0;let t=Wo(r);if(!t||t.length<4)return!0;let n=t[0],o=t[1],i=t[2],a=t[3];return!(i<=e.left||n>=e.right||a<=e.top||o>=e.bottom)}function jx(r,e){if(r&&!(!e||e.length===0))return Object.fromEntries(e.map(t=>[t,r.getAttribute(t)]).filter(([,t])=>t!==null))}function qx({requirements:r,element:e}){let t;if((r?.positionSpecificity||r?.shapeSpecificity)&&(t=Wo(e),!t))throw new Error("ActionFailureError: Element to cache has no bounds or unexpected bounds format");return{requiredText:r?.textRequired?e.getAttribute("text")??void 0:void 0,requiredAttributes:jx(e,r?.attributesRequired),requiredBounds:r?.boundsRequired,position:r?.positionSpecificity?{x1:t[0],y1:t[1],x2:t[2],y2:t[3],tolerance:r?.positionSpecificity}:void 0,shape:r?.shapeSpecificity?{width:t[2]-t[0],height:t[3]-t[1],tolerance:r?.shapeSpecificity}:void 0}}function Yx({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=Wo(n);if(!o)throw new Error(`Node ${r.id} has no bounding box: ${n.outerHTML}`);let i=Xu(t.graph,r.id)??"",a=wh(t.graph,r.id)??"",s=qx({requirements:r.requirements,element:n}),c=[];r.additionalElements&&(c=r.additionalElements.map(({id:u,requirements:d})=>{let m=t.graph.idToElement.get(u);if(!m)return;let p=Xu(t.graph,u);return p?{xPath:p,requirements:qx({requirements:d,element:m})}:void 0}).filter(u=>!!u));let l;if(qs(n.tagName)&&r.inWebview!==!1?l={type:"WEBVIEW",resolvedDescription:e,xPath:i}:l={type:"NATIVE",bounds:o,resolvedDescription:e,xPath:i,elementOnlySerializedXml:a,requirements:s,requiredRelatedElements:c},r.updatedMemory){let u={type:"GCS_TRACES",traces:r.updatedMemory};l.memory=u}return{target:l,resolvedNode:n}}function Ch(r){return r?.type==="WEBVIEW"?r.browserCache?.memory:void 0}var OH=.1,LH=.25;function Ju(r,e,t,n){let o=Math.abs(e-t);switch(r){case"precise":return o<=n;case"narrow":return o<=Math.abs(e)*OH;case"broad":return o<=Math.abs(e)*LH;case"irrelevant":return!0}}function NH(r,e){let t=e.x2-e.x1,n=(e.x1+e.x2)/2,o=(r[0]+r[2])/2;if(!Ju(e.tolerance,n,o,Math.min(1,t)))return!1;let i=e.y2-e.y1,a=(e.y1+e.y2)/2,s=(r[1]+r[3])/2;return Ju(e.tolerance,a,s,Math.min(1,i))}function DH(r,e){return Ju(e.tolerance,e.width,r[2]-r[0],Math.min(1,e.width))?Ju(e.tolerance,e.height,r[3]-r[1],Math.min(1,e.height)):!1}var Kx=(r,e,t)=>{if(!e)return;let{requiredAttributes:n,requiredText:o,requiredBounds:i,position:a,shape:s}=e;if(o!==void 0){let c=$s(r);if(c!==o)throw new Error(`ActionFailureError: Resolved element text mismatch: expected ${o}, got ${c}`)}if(n)for(let[c,l]of Object.entries(n)){let u=r.getAttribute(c)??void 0;if(u!==l)throw new Error(`ActionFailureError: Attribute ${c} mismatch: expected ${l}, got ${u}`)}if(i&&t&&!t.targetBounds.every((l,u)=>l===t.newElementBounds[u]))throw new Error(`ActionFailureError: Bounds changed from [${t.targetBounds.join(",")} ] to [${t.newElementBounds.join(",")} ]`);if(a&&t&&!NH(t.newElementBounds,a))throw new Error(`ActionFailureError: Position mismatch: expected ${JSON.stringify(a)}, got ${JSON.stringify(t.newElementBounds)}`);if(s&&t&&!DH(t.newElementBounds,s))throw new Error(`ActionFailureError: Shape mismatch: expected ${JSON.stringify(s)}, got ${JSON.stringify(t.newElementBounds)}`)};async function Qu(r){let{target:e,domState:t}=r,{graph:n}=t,{document:o}=n,i=ae();if(e.type==="WEBVIEW")return kH(e,r);let a=$x.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 m=e.requiredRelatedElements;i.startSection("Validate related elements are similar enough to past runs",()=>{for(let p of m){let g=$x.evaluateXPathToFirstNode(p.xPath,o);if(!g)throw new Error(`ActionFailureError: Required related element not found for XPath: ${p.xPath}`);Kx(g,p.requirements)}})}let s=Wo(a);if(!s)throw new Error("ActionFailureError: Resolved native element has no bounding box");Kx(a,e.requirements,{targetBounds:e.bounds,newElementBounds:s});let c;for(let[m,p]of n.idToElement.entries())if(p===a){c=m;break}let l=e.elementOnlySerializedXml,u=e.xPath;return c!==void 0&&(l=wh(n,c)??l,u=Xu(n,c)??u),{resolvedTarget:{...e,resolvedNode:a,bounds:s,elementOnlySerializedXml:l,xPath:u}}}async function kH(r,e){let{stateManager:t,logger:n,signal:o}=e,i=ae(),a=await t.getActiveWebview();if(!a||!a.browserController)throw new Error("No browser controller is attached to the requested webview");let 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 jo(r){let{command:e,cacheKey:t="cache",targetName:n="target",updatedCache:o}=r;$l(e)&&(e[t]={...e[t],[n]:fi.parse(o)},r.updatedWithAI&&(e[t].updatedAt=new Date))}function Zu(r){if(r.type==="WEBVIEW")return{type:"WEBVIEW",resolvedDescription:r.resolvedDescription,xPath:r.xPath,browserCache:r.browserCache,memory:r.memory};let{resolvedNode:e,...t}=r;return{...t}}var Xe=class{driver;generator;stateManager;logger;fixtures;aborter;orgId;aiSettings;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,this.aiSettings=e.aiSettings}shouldUseMemoryForCommand(e){return this.aiSettings?.useMemory&&!e?.disableCache}async findElement({description:e,tracer:t,skipFetchingFullWebviewContent:n=!1,removeWebviewContent:o=!1,useMemory:i=!1,memory:a,webviewMemory:s,metadata:c}){let l=this.logger.child({...c});await this.stateManager.waitForScreenshotStability({timeoutMs:5e3,signal:this.aborter.controller?.signal,reason:"Waiting for stability before locating an element with AI"});let u=await t.startAsyncSection("Get emulator state",async()=>{let f=await this.stateManager.getDomState({skipFetchingFullWebviewContent:n,removeWebviewContent:o}),E=await this.stateManager.getCurrentScreenshotPngString();return{emulatorState:f,screenshot:E}}),d;try{d=await t.startAsyncSpan("AI_LOCATOR_CALL",async f=>{let E=await this.generator.getMobileElementLocation({description:e,screenXml:u.emulatorState.graph.xml,screenshot:u.screenshot,memory:i?a:void 0},{logger:l,loggerTags:Ee(l),abortSignal:this.aborter.controller?.signal,useMemory:i,agentConfigVersion:this.aiSettings.agentConfig?.["mobile-locator"]});return f.result=E,E})}catch(f){throw this.throwIfAborted(),l.error({err:f},"Failed to locate element"),new Error(`ActionFailureError: Failed to locate element: ${f instanceof Error?f.message:f}`)}if(d.id===-1)throw new Pn(d.thoughts??"No matching element found");let{target:m,resolvedNode:p}=Yx({aiResponse:d,description:e,emulatorState:u.emulatorState});if(m.type==="NATIVE")return t.addSpan({type:"TARGET_RESOLUTION",startTime:Date.now(),endTime:Date.now(),result:{serializedElement:m.elementOnlySerializedXml},attributes:{},subSpans:[]}),{resolvedTarget:{...m,resolvedNode:p},thoughts:d.thoughts};let{browserLocateResult:g,browserController:h}=await t.startAsyncSpan("TARGET_RESOLUTION",async f=>{let E=await this.stateManager.getActiveWebview();if(!E||!E.browserController)throw new Error("No browser controller is attached to the requested webview");let b=await E.browserController.locateElement({description:e,disableCache:!1,useMemory:i,memory:i?s:void 0,logger:this.logger});return f.result={serializedElement:b.target.nodeOnlySerializedHtml??"Unknown HTML element in webview"},{browserLocateResult:b,browserController:E.browserController}});return{resolvedTarget:{...m,controller:h,resolution:g.resolution,browserCache:g.target},thoughts:g.thoughts}}async wrapTargetingAction(e){let{action:t,description:n,command:o,cacheKey:i="cache",targetName:a="target",cacheIsInvalidAfterResolution:s,tracer:c,skipFetchingFullWebviewContent:l=!1,removeWebviewContent:u=!1}=e,d,m={commandId:o.id};if(i==="cache"&&"cache"in o&&o.cache){let E=o.cache;a==="target"&&"target"in E?d=E.target:a==="fromTarget"&&"fromTarget"in E?d=E.fromTarget:a==="toTarget"&&"toTarget"in E&&(d=E.toTarget)}let p=!1,g=Xx(d),h;if(o.disableCache&&(this.logger.debug({command:o},"Cache explicitly disabled for command"),p=!0,g=void 0),s&&(p=!0,g=void 0),g&&g?.resolvedDescription!==n&&(this.logger.info({description:n,cacheDescription:g?.resolvedDescription},"Cache description mismatch, clearing it automatically"),p=!0,g=void 0),!g){this.logger.info({description:n,cacheBustedBeforeAction:p},"Prompting AI for a new element location");let E=await this.findElement({description:n,tracer:c,skipFetchingFullWebviewContent:l,removeWebviewContent:u,useMemory:this.shouldUseMemoryForCommand(o),memory:d?.memory,webviewMemory:Ch(d),metadata:m});h=E.thoughts;let b=await t(E.resolvedTarget);return jo({command:o,cacheKey:i,targetName:a,updatedCache:E.resolvedTarget,updatedWithAI:!0}),{result:b,thoughts:h}}let f;try{await this.stateManager.waitForScreenshotStability({timeoutMs:5e3,signal:this.aborter.controller?.signal,reason:"Waiting for stability before cache resolution"}),f=await this.stateManager.getDomState();let{resolvedTarget:E,updatedCache:b}=await c.startAsyncSpan("CACHE_RESOLUTION",async x=>{let{resolvedTarget:A}=await Qu({target:g,domState:f,stateManager:this.stateManager,logger:this.logger}),M=Zu(A),v=FH(g,M);return v&&Object.keys(v).length>0&&this.logger.info({cacheDiffs:v},"Successfully resolved target with cache"),x.attributes.serializedElement=A.type==="WEBVIEW"?A.browserCache?.nodeOnlySerializedHtml??"Unknown HTML element in webview":A.elementOnlySerializedXml,{resolvedTarget:A,updatedCache:M}}),w=await t(E);return jo({command:o,cacheKey:i,targetName:a,updatedCache:b,updatedWithAI:!1}),g.type!=="WEBVIEW"&&gt.increment("cache_target_resolution_v2",1,["outcome:hit","platform:native",`hasRequirements:${!!g.requirements}`,`hasAdditionalElements:${!!g.requiredRelatedElements?.length}`,`orgId:${this.orgId}`,"cliVersion:0.16.1"]),{result:w,thoughts:"Successfully executed preset action with cache"}}catch(E){g.type!=="WEBVIEW"&&gt.increment("cache_target_resolution_v2",1,["outcome:miss","platform:native",`hasRequirements:${!!g.requirements}`,`hasAdditionalElements:${!!g.requiredRelatedElements?.length}`,`orgId:${this.orgId}`,"cliVersion:0.16.1"]),this.throwIfAborted(),this.logger.warn({err:E},"Failed to resolve target cache, retrying with AI");let b=this.shouldUseMemoryForCommand(o),w=await this.findElement({description:n,tracer:c,skipFetchingFullWebviewContent:l,removeWebviewContent:u,useMemory:b,memory:g?.memory,webviewMemory:Ch(g),metadata:m});h=w.thoughts;let x=await t(w.resolvedTarget);return jo({command:o,cacheKey:i,targetName:a,updatedCache:w.resolvedTarget,updatedWithAI:!0}),{result:x,thoughts:h}}}constructPerformerParams(){return{stateManager:this.stateManager,generator:this.generator,driver:this.driver,logger:this.logger,fixtures:this.fixtures,aborter:this.aborter,orgId:this.orgId,aiSettings:this.aiSettings}}getBoundsFromNativeCache(e){let[t,n,o,i]=e.bounds;if(t===void 0||n===void 0||o===void 0||i===void 0)throw new Error(`ActionFailureError: Native element cache has incomplete bounds: [${e.bounds.join(", ")}]`);return{left:t,top:n,width:o-t,height:i-n}}calculateSwipeCoordinates({containerBounds:e,direction:t,desiredDelta:n,edgeMarginPercent:o=.1}){let i=e.left+e.width/2,a=e.top+e.height/2;if(t==="up"||t==="down"){let s=e.height*o,c=e.top+s,l=e.top+e.height-s,u=l-c,d=Math.min(Math.abs(n),u);return{startX:i,startY:t==="down"?l:c,actualDelta:d}}else{let s=e.width*o,c=e.left+s,l=e.left+e.width-s,u=l-c,d=Math.min(Math.abs(n),u);return{startX:t==="right"?l:c,startY:a,actualDelta:d}}}invertDirection(e){if(e==="up")return"down";if(e==="down")return"up";if(e==="left")return"right";if(e==="right")return"left";throw new Error(`Unreachable code: ${e}`)}async performRawSwipe({startX:e,startY:t,deltaPixels:n,direction:o,durationMs:i=300}){let a=Math.abs(n),s=e,c=t;o==="up"||o==="down"?c=o==="up"?t-a:t+a:s=o==="left"?e-a:e+a,await this.driver.performActions([{type:"pointer",id:"finger1",parameters:{pointerType:"touch"},actions:[{type:"pointerMove",duration:0,x:e,y:t},{type:"pointerDown",button:0},{type:"pause",duration:100},{type:"pointerMove",duration:i,x:s,y:c},{type:"pointerUp",button:0}]}]),await this.driver.releaseActions()}throwIfAborted(){this.aborter.controller?.signal.throwIfAborted()}get abortSignal(){return this.aborter.controller?.signal}get aiSettingsCopy(){return Xx(this.aiSettings)}};function HH(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 Ji=class extends Xe{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,m=o+u;return await this.tapOnAbsoluteCoordinates({x:d,y:m,...t}),{x:d,y:m}}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=Jx.join(zH(),"momentic","downloads"),s=Jx.join(a,this.orgId,i);return BH(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 ae().startAsyncSpan("EMULATOR_INTERACTION",async o=>{o.attributes.options=t,"type"in e&&e.type==="NATIVE"?o.attributes.point=await this.tapOnNativeTarget(e,t):(o.withinWebview=!0,o.attributes.point=await this.tapOnWebviewTarget(e,t))},{name:"Tap on target"})}async executeTap({command:e}){let t=ae(),n=HH(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 Qn=class extends Xe{async doPress({keycode:e,longPress:t}){await ae().startAsyncSpan("EMULATOR_INTERACTION",async()=>this.driver.executeScript("mobile: pressKey",[{keycode:e,isLongPress:t}]),{name:"Send key events to emulator"})}};var Qx=25,ed=class extends Xe{async doType(e){let t=ae();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.stateManager.waitForScreenshotStability({timeoutMs:3e3,signal:this.aborter.controller?.signal,reason:"Waiting for page to stabilize before typing"}),await this.sendKeys(e),{success:!0,message:"Successfully executed type action"}}if(e.target.type!=="description")throw new Error("UserConfigurationError: x/y targets are not supported for the Type step");let{thoughts:n}=await this.wrapTargetingAction({command:e,tracer:t,action:async o=>{"type"in o&&o.type==="NATIVE"?await this.doNativeType(e,o):await this.doWebviewType(e,o)},description:e.target.description});return{success:!0,message:n}}async doWebviewType(e,t){await ae().startAsyncSpan("EMULATOR_INTERACTION",async o=>{o.withinWebview=!0;let i={clearContent:e.clearContent,forceClearContent:e.forceClearContent,delay:e.keyPressDelayMs??Qx};o.attributes.options=i;let{controller:a,resolution:s}=t;await a.browser.typeIntoTarget(e.text,s,i)},{name:"Typing within web view"})}async doNativeType(e,t){let n=new Ji(this.constructPerformerParams());e.clearContent?(await n.tapOnNativeTarget(t,{longPress:!0}),await this.clearContent()):await n.tapOnNativeTarget(t),await this.stateManager.waitForScreenshotStability({timeoutMs:3e3,signal:this.aborter.controller?.signal,reason:"Waiting for keyboard to appear before typing"}),await this.sendKeys(e)}async sendKeys(e){let t=ae(),n=e.keyPressDelayMs??Qx;await t.startAsyncSection("Waiting for system keyboard to open",async(o,i)=>{let a=Date.now();for(;Date.now()-a<3e3;){if(this.throwIfAborted(),await this.driver.isKeyboardShown())return;await new Promise(s=>setTimeout(s,500))}i.attributes.timedOut=!0}),n?await t.startAsyncSpan("EMULATOR_INTERACTION",async()=>{await this.driver.updateSettings({keyInjectionDelay:n}),await this.driver.keys(e.text),await this.driver.updateSettings({keyInjectionDelay:0})},{name:"Typing keys with a delay"}):await t.startAsyncSpan("EMULATOR_INTERACTION",async()=>{await this.driver.keys(e.text)},{name:"Typing keys"})}async clearContent(){let e=ae();try{await e.startAsyncSection("Clearing any content from the focused field",()=>this.clearContentHelper())}catch(t){this.logger.warn({err:t},"Failed to find select all button, 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 Qn(this.constructPerformerParams()).doPress({keycode:67})}};import Kt from"zod";var Zx=.8,Zn=.2,GH=Kt.object({navigationBar:Kt.object({visible:Kt.boolean(),x:Kt.number(),y:Kt.number(),width:Kt.number(),height:Kt.number()}),statusBar:Kt.object({visible:Kt.boolean(),x:Kt.number(),y:Kt.number(),width:Kt.number(),height:Kt.number()})}),Qi=class extends Xe{async getHardcodedScrollableElementBounds(e,t){let n;switch(e.type){case"SCREEN":n=this.getInsetBoundsFromViewport(t);break;case"OPEN_APP":try{let o=GH.parse(await this.driver.executeScript("mobile: getSystemBars",[]));n=this.getInsetBoundsFromViewport(t),o.navigationBar.visible&&(n.height=Math.max(1,n.height-o.navigationBar.height)),o.statusBar.visible&&(n.top+=o.statusBar.height,n.height=Math.max(1,n.height-o.statusBar.height))}catch(o){this.logger.warn({err:o},"Failed to get system bars, using hardcoded bounds"),n=this.getInsetBoundsFromViewport(t)}break;case"OPEN_WEBVIEW":{let o=await this.stateManager.getActiveWebviewNodes();if(o.length===0)throw new Error("No active webviews found");if(o.length>1){let a=o.map(s=>({id:s.id,ele:s.originalElement.outerHTML,bounds:s.bounds}));throw new Error(`Multiple active webviews found. Momentic currently only supports a single active webview at a time. Discovered nodes: ${JSON.stringify(a)}`)}let i=o[0]?.bounds;if(!i)throw new Error("No bounds found for active webview");n=this.getInsetBoundsFromBounds(i);break}default:{let o=e;throw new Error("If Typescript complains about the line above, you missed a switch case")}}return n}getInsetBoundsFromViewport(e){let t=Math.floor(e.width*Zn),n=Math.floor(e.height*Zn);return{left:e.x+t,top:e.y+n,width:Math.max(1,e.width-t*2),height:Math.max(1,e.height-n*2)}}getInsetBoundsFromBounds(e){let t=e[0],n=e[1],o=e[2],i=e[3],a=o-t,s=i-n,c=Math.floor(a*Zn),l=Math.floor(s*Zn);return{left:t+c,top:n+l,width:Math.max(1,a-c*2),height:Math.max(1,s-l*2)}}async executeSwipe(e){let t=ae();if(e.scrollableElement.type==="CUSTOM_COORDINATES"){let{startX:o,startY:i,deltaPixels:a}=e.scrollableElement;return await t.startAsyncSpan("EMULATOR_INTERACTION",async s=>{s.attributes.startX=o,s.attributes.startY=i,s.attributes.deltaPixels=a,s.attributes.direction=e.direction,await this.performRawSwipe({startX:o,startY:i,deltaPixels:a,direction:e.direction,durationMs:e.durationMs})},{name:`Swipe ${e.direction} using raw coordinates`}),{success:!0,message:"Successfully executed swipe action"}}if(e.scrollableElement.type!=="CUSTOM"){let o=await this.driver.getWindowRect(),i=await this.getHardcodedScrollableElementBounds(e.scrollableElement,o);return await t.startAsyncSpan("EMULATOR_INTERACTION",async a=>{await this.swipeByAbsoluteCoordinates({span:a,direction:e.direction,percent:e.viewportPercent,durationMs:e.durationMs,containerBounds:i})},{name:`Swipe ${e.direction} in the entire ${e.scrollableElement.type.toLowerCase()}`}),{success:!0,message:"Successfully executed swipe action"}}let{thoughts:n}=await this.wrapTargetingAction({command:e,description:e.scrollableElement.target.description,action:async o=>ae().startAsyncSpan("EMULATOR_INTERACTION",async a=>"type"in o&&o.type==="NATIVE"?this.scrollInNativeContainer({span:a,cmd:e,target:o}):(a.withinWebview=!0,this.swipeInWebview({span:a,cmd:e,target:o})),{name:`Swipe ${e.direction} in the specified container`}),tracer:t});return{success:!0,message:n}}async scrollInNativeContainer({span:e,cmd:t,target:n}){let o=n.bounds[2]-n.bounds[0],i=n.bounds[3]-n.bounds[1],a=Math.floor(o*Zn),s=Math.floor(i*Zn);await this.swipeByAbsoluteCoordinates({span:e,direction:t.direction,percent:t.viewportPercent,durationMs:t.durationMs,containerBounds:{left:n.bounds[0]+a,top:n.bounds[1]+s,width:Math.max(1,o-a*2),height:Math.max(1,i-s*2)}})}async swipeInWebview({span:e,cmd:t,target:n}){let{controller:o,resolution:i}=n;if(!o.browser.getViewport())throw new Error("Failed to get viewport size from webview");let s=t.direction==="down"||t.direction==="up",c=await i.locator.boundingBox();if(!c)throw new Error("Failed to get bounds for webview container");let l=Math.floor(c.width*Zn),u=Math.floor(c.height*Zn),d=Math.max(1,c.width-l*2),m=Math.max(1,c.height-u*2),p={x:c.x+l+d/2,y:c.y+u+m/2},g=(s?m:d)*(t.viewportPercent??Zx)*(s?t.direction==="down"?1:-1:t.direction==="right"?1:-1);e.attributes.startPoint=p,e.attributes.scrollPixelAmount=g,await o.browser.mouseDragUsingVisualCoordinates({deltaX:s?0:g,deltaY:s?g:0,steps:10,dragDurationMs:t.durationMs,fromTarget:p})}async swipeByAbsoluteCoordinates({span:e,direction:t,percent:n=Zx,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 WH from"pixelmatch";import{_android as jH,chromium as $H}from"playwright";import{PNG as aM}from"pngjs";import{z as Ge}from"zod";var eM=Ge.object({"Android-Package":Ge.string(),Browser:Ge.string(),"Protocol-Version":Ge.string(),"User-Agent":Ge.string(),"V8-Version":Ge.string(),"WebKit-Version":Ge.string(),webSocketDebuggerUrl:Ge.string()}),tM=Ge.object({description:Ge.string(),devtoolsFrontendUrl:Ge.string(),id:Ge.string(),title:Ge.string(),type:Ge.string(),url:Ge.string(),webSocketDebuggerUrl:Ge.string()}),rM=Ge.object({proc:Ge.string(),webview:Ge.string(),webviewName:Ge.string()}),nM=Ge.array(rM.extend({info:eM.optional(),pages:Ge.array(tM).optional()})),IOe=Ge.array(rM.extend({info:eM,pages:Ge.array(tM)}));function Rh(r,e,t=.01){let n=Buffer.from(r,"base64"),o=Buffer.from(e,"base64"),i=aM.sync.read(n),a=aM.sync.read(o);if(i.width!==a.width||i.height!==a.height)return 100;let s=i.width,c=i.height,l=Buffer.alloc(s*c*4);return WH(i.data,a.data,l,s,c,{threshold:t})/(s*c)*100}var td=class r{driver;limbarClient;device;currentContext;logger;webviews=new Map;fixtures;orgId;options;aborter;constructor({driver:e,context:t,limbarClient:n,logger:o,device:i,fixtures:a,orgId:s,options:c,aborter:l}){this.driver=e,this.limbarClient=n,this.device=i,this.currentContext=t,this.logger=o,this.fixtures=a,this.orgId=s,this.options=c,this.aborter=l;for(let u of["SIGINT","SIGTERM"])process.on(u,async()=>{await this.cleanupWebviews()})}static async init({driver:e,logger:t,fixtures:n,limbarClient:o,orgId:i,adbPort:a,options:s,aborter:c,playwrightDevice:l}){let u=await e.getContext(),d=typeof u=="string"?u:u.id,m;if(l)m=l;else{let g=(await jH.devices()).filter(h=>h._initializer?.serial?.endsWith(a.toString())||h._initializer?.serial?.endsWith((a-1).toString()));if(t.warn({devices:g.map(h=>({serial:h._initializer?.serial,model:h._initializer?.model}))},"No playwright device provided, using ADB to find device"),g.length===0)throw new Error(`Momentic found no devices listening on port ${a} or ${a-1}. This can occur if Android Studio reuses existing emulators. Please run 'adb emu kill' and 'adb disconnect' and retry.`);if(g.length>1)throw new Error(`Momentic found multiple devices on the ports ${a} or ${a-1}. This can occur if Android Studio reuses existing emulators. Please run 'adb emu kill' and 'adb disconnect' and retry.`);m=g[0]}return new r({driver:e,context:d,logger:t,device:m,fixtures:n,orgId:i,options:s,aborter:c,limbarClient:o})}async getContexts(){let e=await this.driver.getContexts({}),t=Array.from(this.webviews.values());return{contexts:e,webviews:t.map(n=>({contextId:n.contextId,packageName:n.packageName,active:n.active,hasPlaywright:!!n.browserController,lastSeen:n.lastSeen,socketName:n.socketName}))}}async getRawScreenshotBase64(e=2){let t=ae(),n;for(let o=0;o<e;o++)try{return await t.startAsyncSpan("EMULATOR_READ_STATE",async()=>await this.driver.takeScreenshot(),{name:"Take screenshot",signal:this.aborter.controller?.signal,timeoutMs:3e3})}catch(i){if(n=i,o===e-1)throw i}throw new Error(`Failed to take screenshot: ${n}`)}async getCurrentScreenshotPngString(){return`data:image/png;base64,${await this.getRawScreenshotBase64(1)}`}async waitForScreenshotStability({timeoutMs:e,signal:t,reason:n,tolerancePercent:o=1}){await ae().startAsyncSpan("WAIT_FOR_SCREENSHOT_STABILITY",async i=>{i.attributes.reason=n;let a=Date.now(),s,c,l=!1;for(;Date.now()-a<e;){c&&c<250&&await j(250-c,t),t?.throwIfAborted();let u=Date.now();if(!s){s=await this.getRawScreenshotBase64(),c=u-a;continue}let d=await this.getRawScreenshotBase64();if(c=u-a,Rh(s,d)<=o){l=!0;break}s=d}l||(i.attributes.timedOut=!0,this.logger.warn({purpose:n},"Timed out waiting for screenshot stability"))})}async getCurrentPackage(){let e=await this.driver.execute("mobile: getCurrentPackage");return typeof e=="string"?e:void 0}async getActiveWebviewNodes(){await this.refreshWebviews();let t=(await this.getDomState({skipFetchingFullWebviewContent:!0,removeWebviewContent:!0})).graph,n=await this.getCurrentPackage(),o=[];for(let[i,a]of t.idToElement.entries()){if(o.some(l=>l.id===i))continue;let s=a.getAttribute("content-desc");(qs(a.tagName)||n==="com.android.chrome"&&s==="Web View"&&a.tagName.toLowerCase().startsWith("frame"))&&o.push({id:i,originalElement:a,bounds:Wo(a)})}return o}async getActiveWebviewContent(){let e=await this.getActiveWebview();if(!e||!e.browserController)return;this.throwIfAborted();let t=e.browserController;return(await ae().startAsyncSpan("EMULATOR_READ_STATE",()=>t.getBrowserState({abortSignal:this.aborter.controller?.signal,serializationOpts:{noId:!0}}),{name:"Get webview content",signal:this.aborter.controller?.signal})).serializedTree}async getDomState(e){return await ae().startAsyncSection("Get emulator state XML",async()=>{let n;if(!e?.skipFetchingFullWebviewContent)try{n=await this.getActiveWebviewContent()}catch(c){this.logger.error({err:c},"Could not get webview info to get the nested DOM state")}this.throwIfAborted();let i=e?.filterOffscreenElements??!0?await this.getViewportBounds():void 0,a=await this.getPageSource();return{graph:await Wx(a,{injectedWebviewContent:n,disableMomenticAccessibilityTree:this.options.disableMomenticAccessibilityTree,removeWebviewContent:e?.removeWebviewContent,viewportBounds:i}),context:this.currentContext}},{timeoutMs:15e3})}async getPageSource(){return await ae().startAsyncSpan("EMULATOR_READ_STATE",()=>this.driver.getPageSource(),{name:"Get Android page source",signal:this.aborter.controller?.signal})}async getViewportBounds(){let e=await this.driver.getWindowRect();return{left:e.x,top:e.y,right:e.x+e.width,bottom:e.y+e.height}}async refreshWebviews(){try{await this.refreshWebviewsHelper()}catch(e){this.logger.warn({err:e},"Error refreshing webviews, continuing...")}}async refreshWebviewsHelper(){await this.getPageSource(),this.throwIfAborted();let e=await this.getCurrentPackage(),t=await this.getDetailedContexts();if(!t){this.logger.warn("No context details, not proceeding with refreshing webviews");return}let n=Date.now(),o=new Set;for(let i of t){if(this.throwIfAborted(),i.webview==="NATIVE_APP")continue;let a=i.info["Android-Package"];if(e&&a!==e&&this.logger.warn({packageName:a,currentPkgName:e},"Ignoring webview not in the active package"),o.add(i.webview),!this.webviews.has(i.webview)||!this.webviews.get(i.webview)?.active){let s={contextId:i.webview,packageName:a,active:!1,lastSeen:n,socketName:i.proc.startsWith("@")?i.proc.substring(1):i.proc};this.logger.info({contextId:s.contextId,packageName:s.packageName,socketName:s.socketName},"New webview detected"),this.webviews.set(i.webview,s);let c;if(a==="com.android.chrome"?(this.logger.info({webviewInfo:s},`Connecting Playwright to Android Chrome: ${i.webview}`),c=await this.connectPlaywrightToChrome(s),this.logger.info(`Connected Playwright to Android Chrome: ${i.webview}`)):(this.logger.info({webviewInfo:s},`Connecting Playwright to webview: ${i.webview}`),c=await this.connectPlaywrightToWebview(a,s.socketName),c&&this.logger.info(`Connected Playwright to webview ${i.webview}`)),!c)continue;s.browserController=c,s.active=!0}}for(let[i,a]of this.webviews.entries())!o.has(i)&&a.active&&(this.logger.info(`Disconnecting dead webview ${i}`),this.disconnectPlaywrightFromWebview(a),a.active=!1)}async getActiveWebview(){await ae().startAsyncSection("Refresh webviews",async()=>{await this.refreshWebviews()});let e=await this.driver.execute("mobile: getCurrentPackage");e!==void 0&&typeof e!="string"&&this.logger.warn({currentPkg:e},"Unexpected getCurrentPackage result");let t=[];for(let n of this.webviews.values())n.packageName===e&&n.active&&t.push(n);if(t.length!==0){if(t.length>1)throw new Error("Multiple active webviews in a single package is currently not supported");return t[0]}}async executeRawADBCommand(e){let t=this.driver.capabilities,n=s=>{if(!t||typeof t!="object")return;let c=t[s];return typeof c=="string"?c:void 0},o=n("deviceUDID")||n("udid")||n("appium:udid")||n("appium:deviceUDID"),i=e.trim().split(/\s+/).filter(s=>s.length>0);this.logger.info({serial:o,cmdArgs:i},"Executing ADB command");let a=await ht(i,{serial:o,timeoutMs:15e3,throwOnError:!0});return this.logger.info({result:a},"ADB command result"),a}async cleanupWebviews(){for(let[e,t]of this.webviews.entries())this.logger.info(`Disconnecting webview ${e}`),this.disconnectPlaywrightFromWebview(t),t.active=!1}async getDetailedContexts(){return await ae().startAsyncSpan("EMULATOR_READ_STATE",async()=>{let t=await this.driver.execute("mobile: getContexts");this.aborter.controller?.signal.throwIfAborted();let n;try{n=nM.parse(t)}catch(o){throw new Error(`Failed to parse contexts. Original error:
4362
+ `));return}}let d=Array.from(e.childNodes??[]);for(let m of d){let p=m.nodeType;if(p===3){let g=m.nodeValue;g&&g.trim().length>0&&t.appendChild(n.createTextNode(g));continue}if(p===1){let g=m;if(!IH(g,s?.viewportBounds))continue;let h=n.createElement(vH(g.tagName));Vx(r,g,h),t.appendChild(h)}}}function _H(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;Vx(a,e,s);let c=new EH().serializeToString(o);return{prunedDocument:o,prunedIdToElement:i,xml:c}}async function Wx(r,e){let t=new bH,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}=_H(t,i,o,e);return{xml:await yH.format(c,{parser:"xml",plugins:[SH],printWidth:120,tabWidth:1,singleAttributePerLine:!1}),originalXml:r,document:n,idToElement:o,prunedDocument:a,prunedIdToElement:s}}function PH(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 Xu(r,e){let t=r.idToElement.get(e);if(t)return PH(t)}function wh(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 Wo(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 IH(r,e){if(!e)return!0;let t=Wo(r);if(!t||t.length<4)return!0;let n=t[0],o=t[1],i=t[2],a=t[3];return!(i<=e.left||n>=e.right||a<=e.top||o>=e.bottom)}function jx(r,e){if(r&&!(!e||e.length===0))return Object.fromEntries(e.map(t=>[t,r.getAttribute(t)]).filter(([,t])=>t!==null))}function qx({requirements:r,element:e}){let t;if((r?.positionSpecificity||r?.shapeSpecificity)&&(t=Wo(e),!t))throw new Error("ActionFailureError: Element to cache has no bounds or unexpected bounds format");return{requiredText:r?.textRequired?e.getAttribute("text")??void 0:void 0,requiredAttributes:jx(e,r?.attributesRequired),requiredBounds:r?.boundsRequired,position:r?.positionSpecificity?{x1:t[0],y1:t[1],x2:t[2],y2:t[3],tolerance:r?.positionSpecificity}:void 0,shape:r?.shapeSpecificity?{width:t[2]-t[0],height:t[3]-t[1],tolerance:r?.shapeSpecificity}:void 0}}function Yx({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=Wo(n);if(!o)throw new Error(`Node ${r.id} has no bounding box: ${n.outerHTML}`);let i=Xu(t.graph,r.id)??"",a=wh(t.graph,r.id)??"",s=qx({requirements:r.requirements,element:n}),c=[];r.additionalElements&&(c=r.additionalElements.map(({id:u,requirements:d})=>{let m=t.graph.idToElement.get(u);if(!m)return;let p=Xu(t.graph,u);return p?{xPath:p,requirements:qx({requirements:d,element:m})}:void 0}).filter(u=>!!u));let l;if(qs(n.tagName)&&r.inWebview!==!1?l={type:"WEBVIEW",resolvedDescription:e,xPath:i}:l={type:"NATIVE",bounds:o,resolvedDescription:e,xPath:i,elementOnlySerializedXml:a,requirements:s,requiredRelatedElements:c},r.updatedMemory){let u={type:"GCS_TRACES",traces:r.updatedMemory};l.memory=u}return{target:l,resolvedNode:n}}function Ch(r){return r?.type==="WEBVIEW"?r.browserCache?.memory:void 0}var OH=.1,LH=.25;function Ju(r,e,t,n){let o=Math.abs(e-t);switch(r){case"precise":return o<=n;case"narrow":return o<=Math.abs(e)*OH;case"broad":return o<=Math.abs(e)*LH;case"irrelevant":return!0}}function NH(r,e){let t=e.x2-e.x1,n=(e.x1+e.x2)/2,o=(r[0]+r[2])/2;if(!Ju(e.tolerance,n,o,Math.min(1,t)))return!1;let i=e.y2-e.y1,a=(e.y1+e.y2)/2,s=(r[1]+r[3])/2;return Ju(e.tolerance,a,s,Math.min(1,i))}function DH(r,e){return Ju(e.tolerance,e.width,r[2]-r[0],Math.min(1,e.width))?Ju(e.tolerance,e.height,r[3]-r[1],Math.min(1,e.height)):!1}var Kx=(r,e,t)=>{if(!e)return;let{requiredAttributes:n,requiredText:o,requiredBounds:i,position:a,shape:s}=e;if(o!==void 0){let c=$s(r);if(c!==o)throw new Error(`ActionFailureError: Resolved element text mismatch: expected ${o}, got ${c}`)}if(n)for(let[c,l]of Object.entries(n)){let u=r.getAttribute(c)??void 0;if(u!==l)throw new Error(`ActionFailureError: Attribute ${c} mismatch: expected ${l}, got ${u}`)}if(i&&t&&!t.targetBounds.every((l,u)=>l===t.newElementBounds[u]))throw new Error(`ActionFailureError: Bounds changed from [${t.targetBounds.join(",")} ] to [${t.newElementBounds.join(",")} ]`);if(a&&t&&!NH(t.newElementBounds,a))throw new Error(`ActionFailureError: Position mismatch: expected ${JSON.stringify(a)}, got ${JSON.stringify(t.newElementBounds)}`);if(s&&t&&!DH(t.newElementBounds,s))throw new Error(`ActionFailureError: Shape mismatch: expected ${JSON.stringify(s)}, got ${JSON.stringify(t.newElementBounds)}`)};async function Qu(r){let{target:e,domState:t}=r,{graph:n}=t,{document:o}=n,i=ae();if(e.type==="WEBVIEW")return kH(e,r);let a=$x.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 m=e.requiredRelatedElements;i.startSection("Validate related elements are similar enough to past runs",()=>{for(let p of m){let g=$x.evaluateXPathToFirstNode(p.xPath,o);if(!g)throw new Error(`ActionFailureError: Required related element not found for XPath: ${p.xPath}`);Kx(g,p.requirements)}})}let s=Wo(a);if(!s)throw new Error("ActionFailureError: Resolved native element has no bounding box");Kx(a,e.requirements,{targetBounds:e.bounds,newElementBounds:s});let c;for(let[m,p]of n.idToElement.entries())if(p===a){c=m;break}let l=e.elementOnlySerializedXml,u=e.xPath;return c!==void 0&&(l=wh(n,c)??l,u=Xu(n,c)??u),{resolvedTarget:{...e,resolvedNode:a,bounds:s,elementOnlySerializedXml:l,xPath:u}}}async function kH(r,e){let{stateManager:t,logger:n,signal:o}=e,i=ae(),a=await t.getActiveWebview();if(!a||!a.browserController)throw new Error("No browser controller is attached to the requested webview");let 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 jo(r){let{command:e,cacheKey:t="cache",targetName:n="target",updatedCache:o}=r;$l(e)&&(e[t]={...e[t],[n]:fi.parse(o)},r.updatedWithAI&&(e[t].updatedAt=new Date))}function Zu(r){if(r.type==="WEBVIEW")return{type:"WEBVIEW",resolvedDescription:r.resolvedDescription,xPath:r.xPath,browserCache:r.browserCache,memory:r.memory};let{resolvedNode:e,...t}=r;return{...t}}var Xe=class{driver;generator;stateManager;logger;fixtures;aborter;orgId;aiSettings;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,this.aiSettings=e.aiSettings}shouldUseMemoryForCommand(e){return this.aiSettings?.useMemory&&!e?.disableCache}async findElement({description:e,tracer:t,skipFetchingFullWebviewContent:n=!1,removeWebviewContent:o=!1,useMemory:i=!1,memory:a,webviewMemory:s,metadata:c}){let l=this.logger.child({...c});await this.stateManager.waitForScreenshotStability({timeoutMs:5e3,signal:this.aborter.controller?.signal,reason:"Waiting for stability before locating an element with AI"});let u=await t.startAsyncSection("Get emulator state",async()=>{let f=await this.stateManager.getDomState({skipFetchingFullWebviewContent:n,removeWebviewContent:o}),E=await this.stateManager.getCurrentScreenshotPngString();return{emulatorState:f,screenshot:E}}),d;try{d=await t.startAsyncSpan("AI_LOCATOR_CALL",async f=>{let E=await this.generator.getMobileElementLocation({description:e,screenXml:u.emulatorState.graph.xml,screenshot:u.screenshot,memory:i?a:void 0},{logger:l,loggerTags:Ee(l),abortSignal:this.aborter.controller?.signal,useMemory:i,agentConfigVersion:this.aiSettings.agentConfig?.["mobile-locator"]});return f.result=E,E})}catch(f){throw this.throwIfAborted(),l.error({err:f},"Failed to locate element"),new Error(`ActionFailureError: Failed to locate element: ${f instanceof Error?f.message:f}`)}if(d.id===-1)throw new Pn(d.thoughts??"No matching element found");let{target:m,resolvedNode:p}=Yx({aiResponse:d,description:e,emulatorState:u.emulatorState});if(m.type==="NATIVE")return t.addSpan({type:"TARGET_RESOLUTION",startTime:Date.now(),endTime:Date.now(),result:{serializedElement:m.elementOnlySerializedXml},attributes:{},subSpans:[]}),{resolvedTarget:{...m,resolvedNode:p},thoughts:d.thoughts};let{browserLocateResult:g,browserController:h}=await t.startAsyncSpan("TARGET_RESOLUTION",async f=>{let E=await this.stateManager.getActiveWebview();if(!E||!E.browserController)throw new Error("No browser controller is attached to the requested webview");let b=await E.browserController.locateElement({description:e,disableCache:!1,useMemory:i,memory:i?s:void 0,logger:this.logger});return f.result={serializedElement:b.target.nodeOnlySerializedHtml??"Unknown HTML element in webview"},{browserLocateResult:b,browserController:E.browserController}});return{resolvedTarget:{...m,controller:h,resolution:g.resolution,browserCache:g.target},thoughts:g.thoughts}}async wrapTargetingAction(e){let{action:t,description:n,command:o,cacheKey:i="cache",targetName:a="target",cacheIsInvalidAfterResolution:s,tracer:c,skipFetchingFullWebviewContent:l=!1,removeWebviewContent:u=!1}=e,d,m={commandId:o.id};if(i==="cache"&&"cache"in o&&o.cache){let E=o.cache;a==="target"&&"target"in E?d=E.target:a==="fromTarget"&&"fromTarget"in E?d=E.fromTarget:a==="toTarget"&&"toTarget"in E&&(d=E.toTarget)}let p=!1,g=Xx(d),h;if(o.disableCache&&(this.logger.debug({command:o},"Cache explicitly disabled for command"),p=!0,g=void 0),s&&(p=!0,g=void 0),g&&g?.resolvedDescription!==n&&(this.logger.info({description:n,cacheDescription:g?.resolvedDescription},"Cache description mismatch, clearing it automatically"),p=!0,g=void 0),!g){this.logger.info({description:n,cacheBustedBeforeAction:p},"Prompting AI for a new element location");let E=await this.findElement({description:n,tracer:c,skipFetchingFullWebviewContent:l,removeWebviewContent:u,useMemory:this.shouldUseMemoryForCommand(o),memory:d?.memory,webviewMemory:Ch(d),metadata:m});h=E.thoughts;let b=await t(E.resolvedTarget);return jo({command:o,cacheKey:i,targetName:a,updatedCache:E.resolvedTarget,updatedWithAI:!0}),{result:b,thoughts:h}}let f;try{await this.stateManager.waitForScreenshotStability({timeoutMs:5e3,signal:this.aborter.controller?.signal,reason:"Waiting for stability before cache resolution"}),f=await this.stateManager.getDomState();let{resolvedTarget:E,updatedCache:b}=await c.startAsyncSpan("CACHE_RESOLUTION",async x=>{let{resolvedTarget:A}=await Qu({target:g,domState:f,stateManager:this.stateManager,logger:this.logger}),M=Zu(A),v=FH(g,M);return v&&Object.keys(v).length>0&&this.logger.info({cacheDiffs:v},"Successfully resolved target with cache"),x.attributes.serializedElement=A.type==="WEBVIEW"?A.browserCache?.nodeOnlySerializedHtml??"Unknown HTML element in webview":A.elementOnlySerializedXml,{resolvedTarget:A,updatedCache:M}}),w=await t(E);return jo({command:o,cacheKey:i,targetName:a,updatedCache:b,updatedWithAI:!1}),g.type!=="WEBVIEW"&&gt.increment("cache_target_resolution_v2",1,["outcome:hit","platform:native",`hasRequirements:${!!g.requirements}`,`hasAdditionalElements:${!!g.requiredRelatedElements?.length}`,`orgId:${this.orgId}`,"cliVersion:0.16.3"]),{result:w,thoughts:"Successfully executed preset action with cache"}}catch(E){g.type!=="WEBVIEW"&&gt.increment("cache_target_resolution_v2",1,["outcome:miss","platform:native",`hasRequirements:${!!g.requirements}`,`hasAdditionalElements:${!!g.requiredRelatedElements?.length}`,`orgId:${this.orgId}`,"cliVersion:0.16.3"]),this.throwIfAborted(),this.logger.warn({err:E},"Failed to resolve target cache, retrying with AI");let b=this.shouldUseMemoryForCommand(o),w=await this.findElement({description:n,tracer:c,skipFetchingFullWebviewContent:l,removeWebviewContent:u,useMemory:b,memory:g?.memory,webviewMemory:Ch(g),metadata:m});h=w.thoughts;let x=await t(w.resolvedTarget);return jo({command:o,cacheKey:i,targetName:a,updatedCache:w.resolvedTarget,updatedWithAI:!0}),{result:x,thoughts:h}}}constructPerformerParams(){return{stateManager:this.stateManager,generator:this.generator,driver:this.driver,logger:this.logger,fixtures:this.fixtures,aborter:this.aborter,orgId:this.orgId,aiSettings:this.aiSettings}}getBoundsFromNativeCache(e){let[t,n,o,i]=e.bounds;if(t===void 0||n===void 0||o===void 0||i===void 0)throw new Error(`ActionFailureError: Native element cache has incomplete bounds: [${e.bounds.join(", ")}]`);return{left:t,top:n,width:o-t,height:i-n}}calculateSwipeCoordinates({containerBounds:e,direction:t,desiredDelta:n,edgeMarginPercent:o=.1}){let i=e.left+e.width/2,a=e.top+e.height/2;if(t==="up"||t==="down"){let s=e.height*o,c=e.top+s,l=e.top+e.height-s,u=l-c,d=Math.min(Math.abs(n),u);return{startX:i,startY:t==="down"?l:c,actualDelta:d}}else{let s=e.width*o,c=e.left+s,l=e.left+e.width-s,u=l-c,d=Math.min(Math.abs(n),u);return{startX:t==="right"?l:c,startY:a,actualDelta:d}}}invertDirection(e){if(e==="up")return"down";if(e==="down")return"up";if(e==="left")return"right";if(e==="right")return"left";throw new Error(`Unreachable code: ${e}`)}async performRawSwipe({startX:e,startY:t,deltaPixels:n,direction:o,durationMs:i=300}){let a=Math.abs(n),s=e,c=t;o==="up"||o==="down"?c=o==="up"?t-a:t+a:s=o==="left"?e-a:e+a,await this.driver.performActions([{type:"pointer",id:"finger1",parameters:{pointerType:"touch"},actions:[{type:"pointerMove",duration:0,x:e,y:t},{type:"pointerDown",button:0},{type:"pause",duration:100},{type:"pointerMove",duration:i,x:s,y:c},{type:"pointerUp",button:0}]}]),await this.driver.releaseActions()}throwIfAborted(){this.aborter.controller?.signal.throwIfAborted()}get abortSignal(){return this.aborter.controller?.signal}get aiSettingsCopy(){return Xx(this.aiSettings)}};function HH(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 Ji=class extends Xe{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,m=o+u;return await this.tapOnAbsoluteCoordinates({x:d,y:m,...t}),{x:d,y:m}}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=Jx.join(zH(),"momentic","downloads"),s=Jx.join(a,this.orgId,i);return BH(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 ae().startAsyncSpan("EMULATOR_INTERACTION",async o=>{o.attributes.options=t,"type"in e&&e.type==="NATIVE"?o.attributes.point=await this.tapOnNativeTarget(e,t):(o.withinWebview=!0,o.attributes.point=await this.tapOnWebviewTarget(e,t))},{name:"Tap on target"})}async executeTap({command:e}){let t=ae(),n=HH(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 Qn=class extends Xe{async doPress({keycode:e,longPress:t}){await ae().startAsyncSpan("EMULATOR_INTERACTION",async()=>this.driver.executeScript("mobile: pressKey",[{keycode:e,isLongPress:t}]),{name:"Send key events to emulator"})}};var Qx=25,ed=class extends Xe{async doType(e){let t=ae();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.stateManager.waitForScreenshotStability({timeoutMs:3e3,signal:this.aborter.controller?.signal,reason:"Waiting for page to stabilize before typing"}),await this.sendKeys(e),{success:!0,message:"Successfully executed type action"}}if(e.target.type!=="description")throw new Error("UserConfigurationError: x/y targets are not supported for the Type step");let{thoughts:n}=await this.wrapTargetingAction({command:e,tracer:t,action:async o=>{"type"in o&&o.type==="NATIVE"?await this.doNativeType(e,o):await this.doWebviewType(e,o)},description:e.target.description});return{success:!0,message:n}}async doWebviewType(e,t){await ae().startAsyncSpan("EMULATOR_INTERACTION",async o=>{o.withinWebview=!0;let i={clearContent:e.clearContent,forceClearContent:e.forceClearContent,delay:e.keyPressDelayMs??Qx};o.attributes.options=i;let{controller:a,resolution:s}=t;await a.browser.typeIntoTarget(e.text,s,i)},{name:"Typing within web view"})}async doNativeType(e,t){let n=new Ji(this.constructPerformerParams());e.clearContent?(await n.tapOnNativeTarget(t,{longPress:!0}),await this.clearContent()):await n.tapOnNativeTarget(t),await this.stateManager.waitForScreenshotStability({timeoutMs:3e3,signal:this.aborter.controller?.signal,reason:"Waiting for keyboard to appear before typing"}),await this.sendKeys(e)}async sendKeys(e){let t=ae(),n=e.keyPressDelayMs??Qx;await t.startAsyncSection("Waiting for system keyboard to open",async(o,i)=>{let a=Date.now();for(;Date.now()-a<3e3;){if(this.throwIfAborted(),await this.driver.isKeyboardShown())return;await new Promise(s=>setTimeout(s,500))}i.attributes.timedOut=!0}),n?await t.startAsyncSpan("EMULATOR_INTERACTION",async()=>{await this.driver.updateSettings({keyInjectionDelay:n}),await this.driver.keys(e.text),await this.driver.updateSettings({keyInjectionDelay:0})},{name:"Typing keys with a delay"}):await t.startAsyncSpan("EMULATOR_INTERACTION",async()=>{await this.driver.keys(e.text)},{name:"Typing keys"})}async clearContent(){let e=ae();try{await e.startAsyncSection("Clearing any content from the focused field",()=>this.clearContentHelper())}catch(t){this.logger.warn({err:t},"Failed to find select all button, 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 Qn(this.constructPerformerParams()).doPress({keycode:67})}};import Kt from"zod";var Zx=.8,Zn=.2,GH=Kt.object({navigationBar:Kt.object({visible:Kt.boolean(),x:Kt.number(),y:Kt.number(),width:Kt.number(),height:Kt.number()}),statusBar:Kt.object({visible:Kt.boolean(),x:Kt.number(),y:Kt.number(),width:Kt.number(),height:Kt.number()})}),Qi=class extends Xe{async getHardcodedScrollableElementBounds(e,t){let n;switch(e.type){case"SCREEN":n=this.getInsetBoundsFromViewport(t);break;case"OPEN_APP":try{let o=GH.parse(await this.driver.executeScript("mobile: getSystemBars",[]));n=this.getInsetBoundsFromViewport(t),o.navigationBar.visible&&(n.height=Math.max(1,n.height-o.navigationBar.height)),o.statusBar.visible&&(n.top+=o.statusBar.height,n.height=Math.max(1,n.height-o.statusBar.height))}catch(o){this.logger.warn({err:o},"Failed to get system bars, using hardcoded bounds"),n=this.getInsetBoundsFromViewport(t)}break;case"OPEN_WEBVIEW":{let o=await this.stateManager.getActiveWebviewNodes();if(o.length===0)throw new Error("No active webviews found");if(o.length>1){let a=o.map(s=>({id:s.id,ele:s.originalElement.outerHTML,bounds:s.bounds}));throw new Error(`Multiple active webviews found. Momentic currently only supports a single active webview at a time. Discovered nodes: ${JSON.stringify(a)}`)}let i=o[0]?.bounds;if(!i)throw new Error("No bounds found for active webview");n=this.getInsetBoundsFromBounds(i);break}default:{let o=e;throw new Error("If Typescript complains about the line above, you missed a switch case")}}return n}getInsetBoundsFromViewport(e){let t=Math.floor(e.width*Zn),n=Math.floor(e.height*Zn);return{left:e.x+t,top:e.y+n,width:Math.max(1,e.width-t*2),height:Math.max(1,e.height-n*2)}}getInsetBoundsFromBounds(e){let t=e[0],n=e[1],o=e[2],i=e[3],a=o-t,s=i-n,c=Math.floor(a*Zn),l=Math.floor(s*Zn);return{left:t+c,top:n+l,width:Math.max(1,a-c*2),height:Math.max(1,s-l*2)}}async executeSwipe(e){let t=ae();if(e.scrollableElement.type==="CUSTOM_COORDINATES"){let{startX:o,startY:i,deltaPixels:a}=e.scrollableElement;return await t.startAsyncSpan("EMULATOR_INTERACTION",async s=>{s.attributes.startX=o,s.attributes.startY=i,s.attributes.deltaPixels=a,s.attributes.direction=e.direction,await this.performRawSwipe({startX:o,startY:i,deltaPixels:a,direction:e.direction,durationMs:e.durationMs})},{name:`Swipe ${e.direction} using raw coordinates`}),{success:!0,message:"Successfully executed swipe action"}}if(e.scrollableElement.type!=="CUSTOM"){let o=await this.driver.getWindowRect(),i=await this.getHardcodedScrollableElementBounds(e.scrollableElement,o);return await t.startAsyncSpan("EMULATOR_INTERACTION",async a=>{await this.swipeByAbsoluteCoordinates({span:a,direction:e.direction,percent:e.viewportPercent,durationMs:e.durationMs,containerBounds:i})},{name:`Swipe ${e.direction} in the entire ${e.scrollableElement.type.toLowerCase()}`}),{success:!0,message:"Successfully executed swipe action"}}let{thoughts:n}=await this.wrapTargetingAction({command:e,description:e.scrollableElement.target.description,action:async o=>ae().startAsyncSpan("EMULATOR_INTERACTION",async a=>"type"in o&&o.type==="NATIVE"?this.scrollInNativeContainer({span:a,cmd:e,target:o}):(a.withinWebview=!0,this.swipeInWebview({span:a,cmd:e,target:o})),{name:`Swipe ${e.direction} in the specified container`}),tracer:t});return{success:!0,message:n}}async scrollInNativeContainer({span:e,cmd:t,target:n}){let o=n.bounds[2]-n.bounds[0],i=n.bounds[3]-n.bounds[1],a=Math.floor(o*Zn),s=Math.floor(i*Zn);await this.swipeByAbsoluteCoordinates({span:e,direction:t.direction,percent:t.viewportPercent,durationMs:t.durationMs,containerBounds:{left:n.bounds[0]+a,top:n.bounds[1]+s,width:Math.max(1,o-a*2),height:Math.max(1,i-s*2)}})}async swipeInWebview({span:e,cmd:t,target:n}){let{controller:o,resolution:i}=n;if(!o.browser.getViewport())throw new Error("Failed to get viewport size from webview");let s=t.direction==="down"||t.direction==="up",c=await i.locator.boundingBox();if(!c)throw new Error("Failed to get bounds for webview container");let l=Math.floor(c.width*Zn),u=Math.floor(c.height*Zn),d=Math.max(1,c.width-l*2),m=Math.max(1,c.height-u*2),p={x:c.x+l+d/2,y:c.y+u+m/2},g=(s?m:d)*(t.viewportPercent??Zx)*(s?t.direction==="down"?1:-1:t.direction==="right"?1:-1);e.attributes.startPoint=p,e.attributes.scrollPixelAmount=g,await o.browser.mouseDragUsingVisualCoordinates({deltaX:s?0:g,deltaY:s?g:0,steps:10,dragDurationMs:t.durationMs,fromTarget:p})}async swipeByAbsoluteCoordinates({span:e,direction:t,percent:n=Zx,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 WH from"pixelmatch";import{_android as jH,chromium as $H}from"playwright";import{PNG as aM}from"pngjs";import{z as Ge}from"zod";var eM=Ge.object({"Android-Package":Ge.string(),Browser:Ge.string(),"Protocol-Version":Ge.string(),"User-Agent":Ge.string(),"V8-Version":Ge.string(),"WebKit-Version":Ge.string(),webSocketDebuggerUrl:Ge.string()}),tM=Ge.object({description:Ge.string(),devtoolsFrontendUrl:Ge.string(),id:Ge.string(),title:Ge.string(),type:Ge.string(),url:Ge.string(),webSocketDebuggerUrl:Ge.string()}),rM=Ge.object({proc:Ge.string(),webview:Ge.string(),webviewName:Ge.string()}),nM=Ge.array(rM.extend({info:eM.optional(),pages:Ge.array(tM).optional()})),IOe=Ge.array(rM.extend({info:eM,pages:Ge.array(tM)}));function Rh(r,e,t=.01){let n=Buffer.from(r,"base64"),o=Buffer.from(e,"base64"),i=aM.sync.read(n),a=aM.sync.read(o);if(i.width!==a.width||i.height!==a.height)return 100;let s=i.width,c=i.height,l=Buffer.alloc(s*c*4);return WH(i.data,a.data,l,s,c,{threshold:t})/(s*c)*100}var td=class r{driver;limbarClient;device;currentContext;logger;webviews=new Map;fixtures;orgId;options;aborter;constructor({driver:e,context:t,limbarClient:n,logger:o,device:i,fixtures:a,orgId:s,options:c,aborter:l}){this.driver=e,this.limbarClient=n,this.device=i,this.currentContext=t,this.logger=o,this.fixtures=a,this.orgId=s,this.options=c,this.aborter=l;for(let u of["SIGINT","SIGTERM"])process.on(u,async()=>{await this.cleanupWebviews()})}static async init({driver:e,logger:t,fixtures:n,limbarClient:o,orgId:i,adbPort:a,options:s,aborter:c,playwrightDevice:l}){let u=await e.getContext(),d=typeof u=="string"?u:u.id,m;if(l)m=l;else{let g=(await jH.devices()).filter(h=>h._initializer?.serial?.endsWith(a.toString())||h._initializer?.serial?.endsWith((a-1).toString()));if(t.warn({devices:g.map(h=>({serial:h._initializer?.serial,model:h._initializer?.model}))},"No playwright device provided, using ADB to find device"),g.length===0)throw new Error(`Momentic found no devices listening on port ${a} or ${a-1}. This can occur if Android Studio reuses existing emulators. Please run 'adb emu kill' and 'adb disconnect' and retry.`);if(g.length>1)throw new Error(`Momentic found multiple devices on the ports ${a} or ${a-1}. This can occur if Android Studio reuses existing emulators. Please run 'adb emu kill' and 'adb disconnect' and retry.`);m=g[0]}return new r({driver:e,context:d,logger:t,device:m,fixtures:n,orgId:i,options:s,aborter:c,limbarClient:o})}async getContexts(){let e=await this.driver.getContexts({}),t=Array.from(this.webviews.values());return{contexts:e,webviews:t.map(n=>({contextId:n.contextId,packageName:n.packageName,active:n.active,hasPlaywright:!!n.browserController,lastSeen:n.lastSeen,socketName:n.socketName}))}}async getRawScreenshotBase64(e=2){let t=ae(),n;for(let o=0;o<e;o++)try{return await t.startAsyncSpan("EMULATOR_READ_STATE",async()=>await this.driver.takeScreenshot(),{name:"Take screenshot",signal:this.aborter.controller?.signal,timeoutMs:3e3})}catch(i){if(n=i,o===e-1)throw i}throw new Error(`Failed to take screenshot: ${n}`)}async getCurrentScreenshotPngString(){return`data:image/png;base64,${await this.getRawScreenshotBase64(1)}`}async waitForScreenshotStability({timeoutMs:e,signal:t,reason:n,tolerancePercent:o=1}){await ae().startAsyncSpan("WAIT_FOR_SCREENSHOT_STABILITY",async i=>{i.attributes.reason=n;let a=Date.now(),s,c,l=!1;for(;Date.now()-a<e;){c&&c<250&&await j(250-c,t),t?.throwIfAborted();let u=Date.now();if(!s){s=await this.getRawScreenshotBase64(),c=u-a;continue}let d=await this.getRawScreenshotBase64();if(c=u-a,Rh(s,d)<=o){l=!0;break}s=d}l||(i.attributes.timedOut=!0,this.logger.warn({purpose:n},"Timed out waiting for screenshot stability"))})}async getCurrentPackage(){let e=await this.driver.execute("mobile: getCurrentPackage");return typeof e=="string"?e:void 0}async getActiveWebviewNodes(){await this.refreshWebviews();let t=(await this.getDomState({skipFetchingFullWebviewContent:!0,removeWebviewContent:!0})).graph,n=await this.getCurrentPackage(),o=[];for(let[i,a]of t.idToElement.entries()){if(o.some(l=>l.id===i))continue;let s=a.getAttribute("content-desc");(qs(a.tagName)||n==="com.android.chrome"&&s==="Web View"&&a.tagName.toLowerCase().startsWith("frame"))&&o.push({id:i,originalElement:a,bounds:Wo(a)})}return o}async getActiveWebviewContent(){let e=await this.getActiveWebview();if(!e||!e.browserController)return;this.throwIfAborted();let t=e.browserController;return(await ae().startAsyncSpan("EMULATOR_READ_STATE",()=>t.getBrowserState({abortSignal:this.aborter.controller?.signal,serializationOpts:{noId:!0}}),{name:"Get webview content",signal:this.aborter.controller?.signal})).serializedTree}async getDomState(e){return await ae().startAsyncSection("Get emulator state XML",async()=>{let n;if(!e?.skipFetchingFullWebviewContent)try{n=await this.getActiveWebviewContent()}catch(c){this.logger.error({err:c},"Could not get webview info to get the nested DOM state")}this.throwIfAborted();let i=e?.filterOffscreenElements??!0?await this.getViewportBounds():void 0,a=await this.getPageSource();return{graph:await Wx(a,{injectedWebviewContent:n,disableMomenticAccessibilityTree:this.options.disableMomenticAccessibilityTree,removeWebviewContent:e?.removeWebviewContent,viewportBounds:i}),context:this.currentContext}},{timeoutMs:15e3})}async getPageSource(){return await ae().startAsyncSpan("EMULATOR_READ_STATE",()=>this.driver.getPageSource(),{name:"Get Android page source",signal:this.aborter.controller?.signal})}async getViewportBounds(){let e=await this.driver.getWindowRect();return{left:e.x,top:e.y,right:e.x+e.width,bottom:e.y+e.height}}async refreshWebviews(){try{await this.refreshWebviewsHelper()}catch(e){this.logger.warn({err:e},"Error refreshing webviews, continuing...")}}async refreshWebviewsHelper(){await this.getPageSource(),this.throwIfAborted();let e=await this.getCurrentPackage(),t=await this.getDetailedContexts();if(!t){this.logger.warn("No context details, not proceeding with refreshing webviews");return}let n=Date.now(),o=new Set;for(let i of t){if(this.throwIfAborted(),i.webview==="NATIVE_APP")continue;let a=i.info["Android-Package"];if(e&&a!==e&&this.logger.warn({packageName:a,currentPkgName:e},"Ignoring webview not in the active package"),o.add(i.webview),!this.webviews.has(i.webview)||!this.webviews.get(i.webview)?.active){let s={contextId:i.webview,packageName:a,active:!1,lastSeen:n,socketName:i.proc.startsWith("@")?i.proc.substring(1):i.proc};this.logger.info({contextId:s.contextId,packageName:s.packageName,socketName:s.socketName},"New webview detected"),this.webviews.set(i.webview,s);let c;if(a==="com.android.chrome"?(this.logger.info({webviewInfo:s},`Connecting Playwright to Android Chrome: ${i.webview}`),c=await this.connectPlaywrightToChrome(s),this.logger.info(`Connected Playwright to Android Chrome: ${i.webview}`)):(this.logger.info({webviewInfo:s},`Connecting Playwright to webview: ${i.webview}`),c=await this.connectPlaywrightToWebview(a,s.socketName),c&&this.logger.info(`Connected Playwright to webview ${i.webview}`)),!c)continue;s.browserController=c,s.active=!0}}for(let[i,a]of this.webviews.entries())!o.has(i)&&a.active&&(this.logger.info(`Disconnecting dead webview ${i}`),this.disconnectPlaywrightFromWebview(a),a.active=!1)}async getActiveWebview(){await ae().startAsyncSection("Refresh webviews",async()=>{await this.refreshWebviews()});let e=await this.driver.execute("mobile: getCurrentPackage");e!==void 0&&typeof e!="string"&&this.logger.warn({currentPkg:e},"Unexpected getCurrentPackage result");let t=[];for(let n of this.webviews.values())n.packageName===e&&n.active&&t.push(n);if(t.length!==0){if(t.length>1)throw new Error("Multiple active webviews in a single package is currently not supported");return t[0]}}async executeRawADBCommand(e){let t=this.driver.capabilities,n=s=>{if(!t||typeof t!="object")return;let c=t[s];return typeof c=="string"?c:void 0},o=n("deviceUDID")||n("udid")||n("appium:udid")||n("appium:deviceUDID"),i=e.trim().split(/\s+/).filter(s=>s.length>0);this.logger.info({serial:o,cmdArgs:i},"Executing ADB command");let a=await ht(i,{serial:o,timeoutMs:15e3,throwOnError:!0});return this.logger.info({result:a},"ADB command result"),a}async cleanupWebviews(){for(let[e,t]of this.webviews.entries())this.logger.info(`Disconnecting webview ${e}`),this.disconnectPlaywrightFromWebview(t),t.active=!1}async getDetailedContexts(){return await ae().startAsyncSpan("EMULATOR_READ_STATE",async()=>{let t=await this.driver.execute("mobile: getContexts");this.aborter.controller?.signal.throwIfAborted();let n;try{n=nM.parse(t)}catch(o){throw new Error(`Failed to parse contexts. Original error:
4363
4363
  ${o}
4364
4364
  Raw: ${JSON.stringify(t)}`)}return n.filter(o=>{if(!o.webviewName)return!0;if(!o.info||!o.pages)return!1;let i=o.pages.filter(a=>{if(!a.title)return!1;let s=a.url;return!(!s||s===""||s.startsWith("about:blank")||s.startsWith("chrome-error:"))});return i?!!i:(this.logger.debug({context:o},"Webview has no qualified pages, skipping"),!1)})},{name:"Get available contexts",signal:this.aborter.controller?.signal})}async createBrowserController({context:e}){return await ae().startSection("Run remote Chrome initialization",async(n,o)=>{let i={};o.attributes.timings=i;let a=await Vs.fromExistingContext({context:e,logger:this.logger,timingRecorder:i,userBrowserSettings:{visualActions:!0,disableBrowserMonitoring:!0,autoExpandIframes:!0},properties:{isNewHeadless:!0,allowedA11yIgnoreReasonsOverride:[],isAndroid:!0},storage:this.fixtures.storage,enricher:this.fixtures.browserEnricher});return new Ku({browser:a,generator:this.fixtures.browserGenerator,logger:this.logger,orgId:this.orgId,storage:this.fixtures.storage,localCodeEvalTools:this.fixtures.localCodeEvalTools,visualDiffScreenshotStorage:new pc})})}async connectPlaywrightToWebview(e,t){return ae().startAsyncSection("Connect headless browser client to webview",async()=>{for(let o=0;o<2;o++)try{return await this.connectPlaywrightToWebviewHelper(e,t)}catch(i){this.logger.warn({err:i},"Failed to connect Playwright to webview, retrying...")}},{signal:this.aborter.controller?.signal,timeoutMs:8e3,timeoutMsg:"Timed out connecting Playwright to the webview"})}extractSocketNameFromWebview(e,t){if("_socketName"in e&&typeof e._socketName=="string")return e._socketName;if("_data"in e&&e._data?.socketName)return e._data.socketName;t.warn({pkg:e.pkg()},"Could not extract socket name from webview")}async connectPlaywrightToWebviewHelper(e,t){let n=this.device.webViews(),o=n.find(l=>!(l.pkg()!==e||this.extractSocketNameFromWebview(l,this.logger)!==t));if(!o){let l=`Could not find webview for ${e} with socket name ${t}`;throw this.logger.warn({webviews:n.map(u=>({pkg:u.pkg,name:this.extractSocketNameFromWebview(u,this.logger)}))},l),new Error(l)}let i=await o.page(),a=i.url();if(a===""||a.startsWith("about:blank")||a.startsWith("chrome-error:")){let l=`Webview ${e} with socket ${t} is not a valid webview`;this.logger.warn({pageUrl:a},l);return}let s=i.context();return await this.createBrowserController({context:s})}async connectPlaywrightToChrome(e){return await ae().startAsyncSpan("EMULATOR_READ_STATE",async()=>this.connectPlaywrightToChromeHelper(e),{name:"Connect headless browser client to Chrome",signal:this.aborter.controller?.signal})}async connectPlaywrightToChromeHelper(e){let{contextId:t,socketName:n}=e;try{this.logger.info({contextId:t,socketName:n},"Connecting to Chrome webview");let o;e.forwardedPort?(o=`http://127.0.0.1:${e.forwardedPort}`,this.logger.info({contextId:t,endpoint:o,socketName:n},"Using existing forwarded port")):(o=`http://127.0.0.1:${await this.forwardDevToolsSocket(e.socketName)}`,this.logger.info({contextId:t,endpoint:o,socketName:n},`Forwarding DevTools socket for ${e.socketName}`)),this.logger.info({endpoint:o,socketName:n},"Connecting to CDP endpoint");let i=await $H.connectOverCDP({endpointURL:o,timeout:8e3}),a=i.contexts()[0];if(!a){this.logger.warn("No browser context available after CDP connection"),await i.close();return}return this.createBrowserController({context:a})}catch(o){this.logger.warn({err:o},`Error connecting Playwright to webview ${e.contextId}, continuing...`);return}}async disconnectPlaywrightFromWebview(e){try{e.browserController&&(this.logger.info(`Disconnecting Playwright from webview: ${e.contextId}`),await e.browserController.browser.cleanup(),e.browserController=void 0),e.forwardedPort&&await this.removeDevToolsForwarding(e.forwardedPort)}catch(t){this.logger.error({err:t},`Error disconnecting Playwright from webview ${e.contextId}:`)}}async forwardDevToolsSocket(e){this.logger.info("Setting up port forwarding for DevTools");let t=1e4+Math.floor(Math.random()*1e4),n=this.driver.capabilities,o=n.deviceUDID||n.udid||n["appium:udid"]||n["appium:deviceUDID"];this.logger.info({deviceId:o},`Device ID from capabilities: ${o||"not found"}`);let i=e&&e.trim().length>0?`localabstract:${e}`:"localabstract:chrome_devtools_remote";return await this.executeRawADBCommand(`forward tcp:${t} ${i}`),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 sM=5,lM=.8,qH=1,rd=class extends Qi{async executeScrollTo(e){let t=e.target.description,n=e.scrollStepPercent??lM,o=await this.tryUseCachedScrollPosition(e,t);return o||this.searchForElement(e,t,n)}async resolveContainer({scrollableElement:e,containerCache:t,aiMetadata:n}){let o=await this.driver.getWindowRect();if(e.type==="CUSTOM_COORDINATES")return{bounds:{left:0,top:0,width:o.width,height:o.height}};if(e.type!=="CUSTOM")return{bounds:await this.getHardcodedScrollableElementBounds(e,o)};let i=ae(),a=e.target.description;if(t){let l=this.getBoundsFromNativeCache(t);return this.logger.info({bounds:l},"Got container bounds from native cache"),{bounds:l,cache:t}}let{resolvedTarget:s}=await this.findElement({description:a,tracer:i,metadata:n});if(s.type!=="NATIVE")throw new Error(`ActionFailureError: Custom scroll container "${a}" resolved to a webview element. Custom containers must be native elements.`);let c=this.getBoundsFromNativeCache(s);return this.logger.info({bounds:c},"Got container bounds from AI"),{bounds:c,cache:s}}async tryUseCachedScrollPosition(e,t){let n=e.cache?.target;return n?n.type==="WEBVIEW"?this.tryUseWebviewCache(e,t):n.scrollDetails?this.tryUseNativeScrollCache(e,t,n):null:null}async tryUseWebviewCache(e,t){let n=ae();try{let{thoughts:o}=await this.wrapTargetingAction({command:e,tracer:n,description:t,action:async i=>{if(i.type==="NATIVE")throw new Error("Expected WEBVIEW target but got NATIVE");await this.scrollWebviewTargetIntoView(i)}});return{success:!0,message:o}}catch(o){return this.logger.warn({err:o},"Failed to use webview cache, falling back to search"),null}}async tryUseNativeScrollCache(e,t,n){let o=n.scrollDetails,i=ae(),a=e.scrollStepPercent??lM,s=o.scrollableElement.type==="CUSTOM"?o.scrollableElement.cache:void 0;await this.scrollByPixelDelta({pixelDelta:o.pixelDelta,scrollableElement:o.scrollableElement,containerCache:s,direction:o.direction,scrollStepPercent:a,aiMetadata:{commandId:e.id}});try{let l=await this.tryFindElement({cmd:e,description:t,tracer:i,scrollDetails:o,useAIIfCacheFails:!1});if(l)return l;this.logger.info("Element not found at cached position, undoing scroll")}catch(l){this.logger.warn({err:l},"Error finding element at cached position, will undo scroll")}let c=o.direction==="down"?"up":"down";return this.logger.info({pixelDelta:o.pixelDelta,originalDirection:o.direction,undoDirection:c,scrollableElementType:o.scrollableElement.type},"Undoing scroll"),await this.scrollByPixelDelta({pixelDelta:o.pixelDelta,scrollableElement:o.scrollableElement,containerCache:s,direction:c,scrollStepPercent:a,aiMetadata:{commandId:e.id}}),null}async tryFindElement({cmd:e,description:t,tracer:n,scrollDetails:o,useAIIfCacheFails:i=!0}){let a,s,c=e.cache?.target;if(c&&c.resolvedDescription===t&&!e.disableCache){await this.stateManager.waitForScreenshotStability({timeoutMs:5e3,signal:this.aborter.controller?.signal,reason:"Waiting for stability before cache resolution"});let u=await this.stateManager.getDomState({skipFetchingFullWebviewContent:!0,removeWebviewContent:!0});try{let{resolvedTarget:d}=await Qu({target:c,domState:u,stateManager:this.stateManager,logger:this.logger});a=d,s="Successfully resolved scroll to target with cache.",this.logger.info("Successfully resolved scroll to target from cache")}catch(d){this.logger.warn({err:d},"Failed to resolve target from cache")}}if(!a&&!i)return null;if(!a)try{let u=await this.findElement({description:t,tracer:n,metadata:{commandId:e.id}});a=u.resolvedTarget,s=u.thoughts}catch(u){if(this.logger.warn({err:u},"Failed to find scroll-to target with AI"),u instanceof Pn)return null;throw u}return a.type==="WEBVIEW"?(await this.scrollWebviewTargetIntoView(a),jo({command:e,updatedCache:Zu(a),updatedWithAI:!0}),{success:!0,message:s}):(jo({command:e,updatedCache:{...a,scrollDetails:o},updatedWithAI:!0}),{success:!0,message:s})}async searchForElement(e,t,n){let o=ae(),i=await this.resolveContainer({scrollableElement:e.scrollableElement,aiMetadata:{commandId:e.id}});return this.scrollAndSearch(e,t,o,n,i)}async scrollAndSearch(e,t,n,o,i){let a=0,s=i.bounds,c=s.height*o,l=!0;for(let u=0;u<sM;u++){this.throwIfAborted();let d=this.buildScrollDetails(e,a,i.cache),m=await this.tryFindElement({cmd:e,description:t,tracer:n,scrollDetails:d});if(m)return m;if(!l)throw new Error(`ActionFailureError: Could not find element "${t}" after scrolling to the end`);this.logger.debug({attempt:u,cumulativePixelDelta:a},"Element not found, scrolling further");let p=KH(e.scrollableElement);l=await this.scrollByPage({direction:e.direction,containerBounds:s,scrollStepPercent:o,rawCoordinates:p}),a+=e.direction==="down"?c:-c}throw new Error(`ActionFailureError: Could not find element "${t}" after ${sM} scroll attempts`)}buildScrollDetails(e,t,n){return e.scrollableElement.type==="CUSTOM"?{pixelDelta:t,scrollableElement:{type:"CUSTOM",target:e.scrollableElement.target,cache:n},direction:e.direction}:e.scrollableElement.type==="CUSTOM_COORDINATES"?{pixelDelta:t,scrollableElement:e.scrollableElement,direction:e.direction}:{pixelDelta:t,scrollableElement:e.scrollableElement,direction:e.direction}}async scrollWebviewTargetIntoView(e){let{controller:t,resolution:n}=e;await t.browser.hover({locator:n.locator})}async scrollByPage({direction:e,containerBounds:t,scrollStepPercent:n,rawCoordinates:o}){return ae().startAsyncSpan("EMULATOR_INTERACTION",async a=>(a.attributes.containerBounds=t,a.attributes.direction=e,this.executeScrollGesture({direction:e,containerBounds:t,scrollStepPercent:n,rawCoordinates:o})),{name:`Scroll ${e} by one page`})}async scrollByPixelDelta({pixelDelta:e,scrollableElement:t,containerCache:n,direction:o,scrollStepPercent:i,aiMetadata:a}){if(e===0)return;let s=ae(),c,l,u;if(t.type==="CUSTOM_COORDINATES")c=t.startX,l=t.startY,u=t.deltaPixels;else{let p=(await this.resolveContainer({scrollableElement:t,containerCache:n,aiMetadata:a})).bounds,g=p.height*i,h=this.calculateSwipeCoordinates({containerBounds:p,direction:o,desiredDelta:g});c=h.startX,l=h.startY,u=h.actualDelta}let d=Math.ceil(Math.abs(e)/u);this.logger.debug({pixelDelta:e,direction:o,scrollableElementType:t.type,startX:c,startY:l,maxScrollPerStep:u,numScrolls:d},"scrollByPixelDelta calculated parameters"),await s.startAsyncSpan("EMULATOR_INTERACTION",async m=>{m.attributes.pixelDelta=e,m.attributes.numScrolls=d,m.attributes.maxScrollPerStep=u,m.attributes.startX=c,m.attributes.startY=l;let p=0;for(let g=0;g<d;g++){this.throwIfAborted();let h=Math.abs(e)-p,f=Math.min(u,h);await this.performRawSwipe({startX:c,startY:l,deltaPixels:f,direction:this.invertDirection(o)}),p+=f}},{name:`Scroll ${o} by ${e}px`})}async executeScrollGesture({direction:e,containerBounds:t,scrollStepPercent:n,diffThresholdPercent:o=qH,rawCoordinates:i}){let a=await this.stateManager.getRawScreenshotBase64(),s,c,l;if(i)s=i.startX,c=i.startY,l=i.deltaPixels;else{let p=t.height*n,g=this.calculateSwipeCoordinates({containerBounds:t,direction:e,desiredDelta:p});s=g.startX,c=g.startY,l=g.actualDelta}await this.performRawSwipe({startX:s,startY:c,deltaPixels:l,direction:this.invertDirection(e)});let u=await this.stateManager.getRawScreenshotBase64(),d=Rh(a,u),m=d>o;return this.logger.debug({diffPercent:d,diffThresholdPercent:o,canScrollMore:m,direction:e,actualDelta:l,rawCoordinates:i},"Scroll gesture visual diff result"),m}};function KH(r){if(r.type==="CUSTOM_COORDINATES")return r}import{randomUUID as YH}from"crypto";import Ys from"fs";import{tmpdir as XH}from"os";import Zi from"path";var nd=class extends Xe{async doInstallApk(e){return await this.installApkFromUri(e.uri),{success:!0,message:"Installed APK."}}async installApkFromUri(e){let t=await this.resolveUriToLocalApk(e);try{await this.stateManager.executeRawADBCommand(`install ${Zi.resolve(t.localPath)}`),this.logger.info({uri:e,localPath:t.localPath},"Installed APK on device")}finally{t.cleanup()}}async resolveUriToLocalApk(e){try{let t=new URL(e);if(t.protocol==="file:"){let n=t.href.slice(7),o;if(Ys.existsSync(n))o=n;else if(Ys.existsSync(Zi.join("/",n)))o=Zi.join("/",n);else throw new Error(`APK not found at path: ${n}`);return this.assertFileExists(o),{localPath:o,cleanup:()=>{}}}if(t.protocol==="http:"||t.protocol==="https:"){let n=await this.fetchWithTimeout(t);if(!n.ok)throw new Error(`Failed to download APK from ${e} (status ${n.status})`);let o=await n.arrayBuffer(),i=Buffer.from(o),a=await this.writeBufferToTempFile(i,t.pathname);return{localPath:a,cleanup:()=>{try{Ys.unlinkSync(a)}catch(s){this.logger.warn({err:s,path:a},"Failed to remove temporary APK file")}}}}throw new Error(`Unsupported URI scheme for APK installation: ${t.protocol}`)}catch(t){if(t instanceof TypeError){let n=Zi.resolve(e);return this.assertFileExists(n),{localPath:n,cleanup:()=>{}}}throw t}}assertFileExists(e){try{Ys.accessSync(e)}catch{throw new Error(`APK not found at path: ${e}`)}}async fetchWithTimeout(e){let t=AbortSignal.timeout(9e4);return await fetch(e,{signal:t})}async writeBufferToTempFile(e,t){let n=Zi.extname(t)||".apk",o=Zi.join(XH(),`momentic-apk-${YH()}${n}`);return Ys.writeFileSync(o,e),o}};import{existsSync as JH,readFileSync as QH}from"fs";import ZH from"zod";var eG=ZH.string().url();async function cM(r){if(eG.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(!JH(r))throw new Error(`File does not exist at path: ${r}`);return QH(r).toString("base64")}var od=class extends Xe{async dragNative(e,t,n){let{left:o,top:i,width:a,height:s}=this.getBoundsFromNativeCache(e),{left:c,top:l,width:u,height:d}=this.getBoundsFromNativeCache(t),m=o+a/2,p=i+s/2,g=c+u/2,h=l+d/2,f=n?.hoverDuration??500,E=n?.dragDuration??1e3;await this.driver.performActions([{type:"pointer",id:"finger1",parameters:{pointerType:"touch"},actions:[{type:"pointerMove",duration:0,x:m,y:p},{type:"pointerDown",button:0},{type:"pause",duration:f},{type:"pointerMove",duration:E,x:g,y:h},{type:"pointerUp",button:0}]}]),await this.driver.releaseActions()}async dragWebview(e,t,n){let{controller:o}=e;if(e.controller!==t.controller)throw new Error("ActionFailureError: Cannot drag and drop between different webviews");let i=n?.dragDuration??1e3,a=n?.hoverDuration??1e3,s;n?.dragDuration&&(s=Math.max(1,Math.floor(i/200))),await o.browser.dragAndDrop(e.resolution.locator,t.resolution.locator,{hoverDurationMs:a,steps:s,dragDurationMs:i})}async executeDragAndDrop({command:e}){let t=ae();if(e.fromTarget.type!=="description"||e.toTarget.type!=="description")throw new Error("ActionFailureError: Drag and drop only supports description targets for now");let n=e.fromTarget.description,{result:o,thoughts:i}=await this.wrapTargetingAction({command:e,tracer:t,description:n,cacheKey:"cache",targetName:"fromTarget",action:async l=>l}),a=e.toTarget.description,{result:s,thoughts:c}=await this.wrapTargetingAction({command:e,tracer:t,description:a,cacheKey:"cache",targetName:"toTarget",action:async l=>l});if(o.type!==s.type)throw new Error(`ActionFailureError: Drag and drop targets must be in the same context (both native or both webview). Found: From=${o.type}, To=${s.type}`);return await t.startAsyncSpan("EMULATOR_INTERACTION",async l=>{o.type==="NATIVE"&&s.type==="NATIVE"?await this.dragNative(o,s,{hoverDuration:e.hoverDuration,dragDuration:e.dragDuration}):o.type==="WEBVIEW"&&s.type==="WEBVIEW"&&(l.withinWebview=!0,await this.dragWebview(o,s,{hoverDuration:e.hoverDuration,dragDuration:e.dragDuration}))},{name:"Drag and drop"}),{success:!0,message:`${i}
4365
4365
  ${c}`}}};import{cloneDeep as uM}from"lodash-es";var id=class{async getTextContent(e){return await e.textContent()??""}async getAttribute(e,t){return await e.getAttribute(t,{timeout:3e3})??""}async getTagName(e){return await e.evaluate(t=>t.tagName)}async isEditable(e){return await e.isEditable({timeout:Ot*1e3})}async isEnabled(e){return await e.isEnabled({timeout:Ot*1e3})}async isFocused(e){return await e.evaluate(t=>t===document.activeElement)}async getStyleProperty(e,t){return await e.evaluate((n,o)=>window.getComputedStyle(n).getPropertyValue(o),t)}},ad=class{async getTextContent(e){return $s(e)}async getAttribute(e,t){return e.getAttribute(t)??""}async getTagName(e){return e.tagName}async isEditable(e){throw new Error("Cannot perform editable check on native element")}async isEnabled(e){return e.getAttribute("enabled")==="true"}async isFocused(e){return e.getAttribute("focused")==="true"}async getStyleProperty(e,t){throw new Error("Cannot perform computed style checks on native element")}};var tG=5e3,sd=class extends Xe{async executeElementCheck(e){let t=Date.now(),n=(e.timeout??Ot)*1e3,o=n+1e4,i,a=0,s=500,c=uM(e.cache);if(e.target.type!=="description")throw new Error("UserConfigurationError: x/y targets are not supported for the Element Check step");for(;a-t<n;){if(Date.now()-t>o){this.logger.warn("Exceeded max system timeout for element check, exiting...");break}if(this.throwIfAborted(),i=await this.executeElementCheckHelper(e),a=Date.now(),!i.success)e.cache=c,c=uM(c),await j(s,this.abortSignal),s=Math.min(Math.floor(s*1.5),tG);else return i}let l=await this.executeElementCheckHelper(e,{cacheIsInvalidAfterResolution:!0});return l.success||c&&e.cache&&(e.cache=Ds({originalCache:c,newCache:e.cache,targetGetter:u=>u.target}).result),l}async executeElementCheckHelper(e,t){let n=ae();if(e.target.type!=="description")throw new Error("UserConfigurationError: x/y targets are not supported for the Element Check step");let o=pu(e.assertion);try{return(await this.wrapTargetingAction({...t??{},command:e,tracer:n,action:async a=>"type"in a&&a.type==="NATIVE"?await this.executeNativeElementCheck(e,a):await this.executeWebviewElementCheck(e,a),description:e.target.description,skipFetchingFullWebviewContent:!0,removeWebviewContent:!0})).result}catch(i){return o&&(i instanceof Pn||i instanceof _n)?{success:!0}:{success:!1,message:`Failed to evaluate element content assertion: ${i instanceof Error?i.message:`${i}`}`}}}async executeNativeElementCheck(e,t){let n=ae(),{assertion:o}=e,i=t.resolvedNode;return await n.startAsyncSpan("ELEMENT_ASSERTION",async a=>{let s=await this.executeElementAssertion({assertion:o,element:i,elementPropertyAccessors:new ad,span:a});return a.result=s,s},{name:"Native element check"})}async executeWebviewElementCheck(e,t){let n=ae(),o=t.resolution.locator,i=e.assertion;return await n.startAsyncSpan("ELEMENT_ASSERTION",async a=>{await t.controller.browser.highlight(o);let s=await this.executeElementAssertion({assertion:i,element:o,elementPropertyAccessors:new id,span:a});return a.result=s,s},{name:"Webview element check"})}async executeElementAssertion({assertion:e,element:t,elementPropertyAccessors:n,span:o}){switch(e.type){case"ELEMENT_CONTENT":{let i=await n.getTextContent(t)??"";return o.attributes.elementTextContent=ft(i,500,!0),Yr(i,e.value,e.operation,{negated:!!e.negated,ignoreCase:!1})?{success:!0}:{success:!1,message:`The content ${hr(e)} '${e.value}': ${i}`}}case"ELEMENT_ATTRIBUTE":{"evaluate"in t&&(o.attributes.elementOuterHtml=ft(await t.evaluate(a=>a.cloneNode(!1).outerHTML),500,!0));let i;try{i=await n.getAttribute(t,e.attr)}catch(a){return{success:!1,message:`The element does not have an attribute named ${e.attr}: ${a}`}}if(!Yr(i,e.value,e.operation,{negated:!!e.negated,ignoreCase:!1})){let a=hr(e);return{success:!1,message:`The attribute ${e.attr} ${a}${e.operation==="EXISTS"?"":` '${e.value}': ${i}`}`}}return{success:!0}}case"ELEMENT_EXISTENCE":{let i=!1;switch(e.condition){case"EDITABLE":i=await n.isEditable(t);break;case"VISIBLE":case"EXISTS":i=!0;break;case"ENABLED":{i=await n.isEnabled(t);break}case"FOCUSED":i=await n.isFocused(t);break;default:throw e.condition,new Error("Unrecognized element condition type")}return i=e.negated?!i:i,i?{success:!0}:{success:!1,message:`The element ${hr(e)}`}}case"ELEMENT_NAME":{let i=await n.getTagName(t);return Yr(i,e.value,e.operation,{negated:!!e.negated,ignoreCase:!0})?{success:!0}:{success:!1,message:`The element tag name ${hr(e)} '${e.value}': ${i}`}}case"ELEMENT_STYLE":{let i=await n.getStyleProperty(t,e.property);if(!Yr(i,e.value,e.operation,{negated:!!e.negated,ignoreCase:!1})){let a=hr(e);return{success:!1,message:`The style property ${e.property} ${a}${e.operation==="EXISTS"?"":` '${e.value}': ${i}`}`}}return{success:!0}}default:throw new Error("Unrecognized element assertion type")}}};var rG=5e3,ld=class extends Xe{async executeScreenCheck(e){let{timeout:t}=e,n=Date.now(),o=(t??Ot)*1e3,i=o+1e4,a=0,s=500;for(;a-n<o;){if(Date.now()-n>i){this.logger.warn("Exceeded max system timeout for screen check, exiting...");break}this.throwIfAborted();let c=await this.executeScreenCheckHelper(e);if(a=Date.now(),!c.success)await j(s,this.abortSignal),s=Math.min(Math.floor(s*1.5),rG);else return c}return await this.executeScreenCheckHelper(e)}async executeScreenCheckHelper(e){return await ae().startAsyncSection("Execute screen check",async(n,o)=>{let[i,a]=await Promise.all([this.executeNativeScreenCheckHelper({span:o,command:e}),this.executeWebviewScreenCheckHelper(e)]);return a?e.assertion.negated?i.success&&a.success?i:i.success?a:i:i.success?i:a:i})}async executeNativeScreenCheckHelper({span:e,command:t}){let{assertion:n}=t;switch(n.type){case"CONTENT":try{let o=(await this.stateManager.getDomState({skipFetchingFullWebviewContent:!0,removeWebviewContent:!0})).graph.document.documentElement?.outerHTML;if(!o)throw new Error("Failed to get screen HTML");let i=o.includes(n.value)===!n.negated;return o.length>1e4&&(o=o.slice(0,1e4)+"...TRUNCATED"),i?{success:!0}:(e.attributes.screenContent=o,{success:!1,message:`The screen ${wg(n)}.`})}catch(o){return{success:!1,message:`Failed to evaluate screen content assertion: ${o instanceof Error?o.message:`${o}`}`}}default:return n.type,{success:!1,message:`Unsupported screen check assertion type: ${n.type}`}}}async executeWebviewScreenCheckHelper(e){let t=await this.stateManager.getActiveWebview();if(!t||!t.browserController)return;let n=t.browserController.browser;return await qu({assertion:e.assertion,logger:this.logger,browser:n,autoExpandIframes:!!n.userBrowserSettings.autoExpandIframes})}};var cd=class extends Xe{async doUninstallApk(e){return await this.uninstallApkPackage(e.packageName),{success:!0,message:"Uninstalled APK."}}async uninstallApkPackage(e){let t=e.replace(/^package:/,""),n=await this.stateManager.executeRawADBCommand(`shell pm list packages | grep -E "^package:${t}$" || true`);if(!n||n.length===0)throw new Error(`Package ${t} not found`);if(n.split(`
4366
4366
  `).filter(i=>!!i).length>1)throw new Error(`Multiple packages found for ${t}`);try{await this.stateManager.executeRawADBCommand(`uninstall ${t}`)}catch(i){throw new Error(`Failed to uninstall package ${t}: ${i}`)}}};var ea=class r extends Xe{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,limbarClient:l,playwrightDevice:u,aiSettings:d}){let m={controller:s},p=await td.init({driver:e,logger:n,fixtures:o,orgId:i,limbarClient:l,options:a?.emulator??{},aborter:m,adbPort:c,playwrightDevice:u}),g=new r({driver:e,generator:t,stateManager:p,logger:n,fixtures:o,options:a,aborter:m,orgId:i,aiSettings:d,adbPort:c});return await g.initializeSettings(),g}async installApp(e){await this.stateManager.executeRawADBCommand(`install ${oG.resolve(e)}`)}async executeCommand(e){let t=["type","a11yData","thoughts","cache","code"],n;try{n=await Ru({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{xu(e.command,n)}}async executeCommandHelper({command:e}){let t=ae();switch(e.type){case"TAP":return new Ji(this.constructPerformerParams()).executeTap({command:e});case"TYPE":return await new ed(this.constructPerformerParams()).doType(e);case"AI_CHECK":{let n=this.shouldUseMemoryForCommand(e),o=15,i=e.timeoutSecs?e.timeoutSecs*1e3:5e3,a=bu(i),s=Date.now(),c=0,l,u=!1,d;for(;c<o&&!u;){this.throwIfAborted(),u||l&&l-s>=i&&(u=!0),c!==0&&await j(a,this.abortSignal),l=Date.now();try{let m="",p="";await t.startAsyncSpan("EMULATOR_READ_STATE",async()=>{m=(await this.stateManager.getDomState({})).graph.xml,p=await this.stateManager.getCurrentScreenshotPngString()},{name:"Get emulator state"});let g=await t.startAsyncSpan("AI_ASSERTION_CALL",async h=>{let f=await this.generator.evaluateMobileAssertion({assertion:e.assertion,screenXml:m,screenshot:p,memory:n?e.cache?.memory:void 0},{logger:this.logger,loggerTags:Ee(this.logger),agentConfigVersion:this.aiSettings.agentConfig?.["mobile-assertion"],useMemory:n});return h.result={thoughts:f.thoughts,result:f.result},f});if(n&&g.updatedMemory){let h={type:"GCS_TRACES",traces:g.updatedMemory};e.cache={...e.cache??{},memory:h}}if(g.result)return{success:g.result,message:g.thoughts};{let h=`AssertionFailureError: ${g.thoughts}`;d=new Error(h)}}catch(m){this.throwIfAborted(),this.logger.info({err:m},`AI check assert attempt ${c} failed, retrying...`),d=m instanceof Error?m:new Error(`${m}`)}finally{c++}}return{success:!1,message:d?.message}}case"SWIPE":return new Qi(this.constructPerformerParams()).executeSwipe(e);case"SCREEN_CHECK":return new ld(this.constructPerformerParams()).executeScreenCheck(e);case"ELEMENT_CHECK":return await new sd(this.constructPerformerParams()).executeElementCheck(e);case"DRAG_AND_DROP":return await new od(this.constructPerformerParams()).executeDragAndDrop({command:e});case"SCROLL_TO":return new rd(this.constructPerformerParams()).executeScrollTo(e);case"JAVASCRIPT":{let n=await Jr({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(l){throw new Error(`UserConfigurationError: Invalid URL: ${l}`)}let o=new iG,i=nG(fetch,o),a=Date.now(),s=await $u({command:e,baseUrl:void 0,logger:this.logger,fetchImplementation:i}),c=ec(o,n);return{output:fl.parse({...s,cookies:c}),success:!0,message:`Successfully executed request in ${Date.now()-a}ms`}}case"OPEN_NOTIFICATION_DRAWER":return await new Qn(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(`
4367
- `).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.abortSignal,reason:"Waiting for stability after app launch"}),{success:!0}}case"PRESS":{let n=new Qn(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 Qn(this.constructPerformerParams()),o=i=>n.doPress({keycode:i});switch(e.key){case"CLOSE_KEYBOARD":{let i=Date.now();for(;Date.now()-i<5e3&&(await this.driver.hideKeyboard(),!!await this.driver.isKeyboardShown()););break}case"ENTER":await o(66);break;case"BACKSPACE":await o(67);break;default:{let i=e}}return{success:!0}}case"WAIT":return await j(e.timeoutSecs*1e3,this.aborter.controller?.signal),{success:!0};case"INSTALL_APP":return new nd(this.constructPerformerParams()).doInstallApk(e);case"UNINSTALL_APP":return new cd(this.constructPerformerParams()).doUninstallApk(e);case"ADD_FILE":{let n=await cM(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"TOGGLE_SETTINGS":{switch(e.settingsType){case"AIRPLANE_MODE":await this.driver.toggleAirplaneMode();break;case"DATA":await this.driver.toggleData();break;case"WIFI":await this.driver.toggleWiFi();break;case"LOCATION":await this.driver.toggleLocationServices();break;default:throw e.settingsType,new Error(`Unknown settings type: ${e.settingsType}`)}return{success:!0}}case"ADB":{let n=await this.driver.execute(e.command,JSON.parse(e.jsonArgs??"{}"));return this.logger.info({output:n},"ADB command executed successfully"),{success:!0,output:n,message:"ADB command executed successfully"}}case"KILL_APP":{let n=await this.stateManager.getCurrentPackage();if(!n)throw new Error("No package is currently active");await this.driver.execute("mobile: shell",{command:"input",args:["keyevent","KEYCODE_HOME"]}),await this.driver.terminateApp(n);try{await Gx({packageName:n,driver:this.driver,abortSignal:this.abortSignal,logger:this.logger})}catch(o){this.throwIfAborted(),this.logger.warn({err:o,packageName:n},"Failed to remove package from recents, continuing...")}return{success:!0}}case"STATE":{await this.stateManager.refreshWebviews();let n=await this.stateManager.getDomState(),o=await this.stateManager.getContexts(),i={xml:n.graph.xml,contexts:o};return this.logger.info({result:i},"State debug command output"),{output:i,success:!0}}default:{let n=e;return{success:!0}}}}async initializeSettings(){let{latitude:e,longitude:t}=this.options?.emulator?.geolocation??Ll;await this.driver.execute("mobile: shell",{command:"pm",args:["grant","io.appium.settings","android.permission.ACCESS_COARSE_LOCATION"]}),await this.driver.execute("mobile: shell",{command:"pm",args:["grant","io.appium.settings","android.permission.ACCESS_FINE_LOCATION"]}),await this.driver.setGeoLocation({latitude:e,longitude:t})}async getScreenshotBase64(){return this.stateManager.getRawScreenshotBase64()}async getScreenshotPngString(){return this.stateManager.getCurrentScreenshotPngString()}async getA11yTree(){return(await this.stateManager.getDomState({})).graph.xml}async executeRawADBCommand(e){return this.stateManager.executeRawADBCommand(e)}async getViewportBounds(){return this.stateManager.getViewportBounds()}async waitForScreenshotStability(e){return this.stateManager.waitForScreenshotStability({timeoutMs:e.timeoutMs??5e3,reason:e.reason,signal:this.aborter.controller?.signal})}resetAbortController(e){this.aborter.controller=e??new AbortController}isAborted(){return this.aborter.controller?.signal.aborted}abort(){this.aborter.controller?.abort()}async cleanup(){await this.stateManager.cleanupWebviews()}get abortSignal(){return this.aborter.controller?.signal}get context(){return this.fixtures.testContext}get localCodeEvalTools(){return this.fixtures.localCodeEvalTools}};async function mM({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,m=r.handshake.query?.testMetadata,p=r.handshake.query?.fileName,g=p?dM.basename(p,".test.yaml"):"",h=wr.parse(JSON.parse(m??"")),f=h.id,E=h.settings?.defaultChannel,b=h.settings?.defaultTag,w=await n({testId:f});e=e.child({sessionId:d,testId:f,orgId:w});let x=await s(w),A=h.settings?.defaultEnv,M={};A&&(M=(await x.fetchEnvironment(A,e))?.variables??{});let v=Ai.parse(M[Eo]),_=Ai.parse(M[Fa]),k=await u(w,e),V={...k.emulator,...h.settings?.emulator},Z=h.settings?.defaultApkFilePath?.trim()||_,te=l.getSession(d);if(te){if(e.info("Reconnecting to existing Android session"),te.local)return r.emit("session",te.metadata),te.softDeleted=!1,te.metadata;throw new Error("Restoring existing remote emulator sessions is not supported. Please reconnect to a new emulator.")}let yt;if(V.region==="local"){if(await l.clearSoftDeletedLocalSessions(e),l.hasActiveLocalSession())throw new Error("Another local emulator session is already active. Please close the existing session before creating a new one.");let an=h.settings?.emulator?.localEmulatorSettings?.avdId?.trim()||v;if(!an)throw new Error(`AVD ID is required when using a local emulator. Set it on the test (Options \u2192 Emulator \u2192 Local AVD ID) or on the environment via ${Eo}.`);yt={avdId:an,apkToInstall:E?{channel:E,tag:b}:void 0,apkFilePath:Z}}else yt={region:V.region,apkToInstall:E?{channel:E,tag:b}:void 0,osVersion:V.remoteEmulatorSettings?.androidVersion};let Y=Date.now(),{driver:H,cleanup:ce,emulatorName:pe,adbPort:Je,limbarClient:Re,limbarToken:jt,limbarUrl:_t,playwrightDevice:Ue}=await t({socket:r,logger:e,creationOpts:yt}),lt=dM.join(aG(),`logcat-logs-${w}-${f}-${d}.txt`),Or=await Cu({driver:H,onLogs:an=>{r.emit("logcatLogs",an)},logFilePath:lt});e.info({adbPort:Je,apkChannel:E,apkTag:b,duration:Date.now()-Y,emulatorName:pe},"Android emulator session initiated"),e=e.child({emulator:pe});let vn=await o(w,e),oo=await i(w,e),Xo=await a(w,e),fa=c?await c(w):void 0,io=new bi({variablesFromEnvironment:M,envName:A,testName:g}),ao=await ea.init({driver:H,generator:vn,logger:e,limbarClient:Re,playwrightDevice:Ue,aiSettings:{...k.ai,useMemory:k.ai?.useMemory!==!1,...h.settings?.ai},options:{emulator:V},fixtures:{storage:x,browserEnricher:Xo,browserGenerator:oo,localCodeEvalTools:fa,testContext:io},orgId:w,adbPort:Je,abortController:new AbortController}),so=await ao.getViewportBounds();if(!r.connected)throw await Or(),await ce(),new Error("Socket not connected anymore, not proceeding with Android session setup");let Lr=sG({socket:r,testContext:io}),$=async()=>{clearInterval(Lr);try{await Or(),await ce(),await ao.cleanup()}catch(an){e.warn({err:an},"Failed to clean up emulator in socket server")}},Sa={sessionId:d,testId:f,orgId:w,emulatorName:pe,testName:g,limbarUrl:_t,limbarToken:jt,viewportBounds:so};return l.registerSession(d,{controller:ao,cleanup:$,emulatorName:pe,local:V.region==="local",metadata:Sa,logFilePath:lt}),r.emit("session",Sa),Sa}function sG({socket:r,testContext:e}){return setInterval(()=>{let t=e.toEditorDisplayCopy();r.emit("emulatorState",{context:t})},3e3)}import gd from"fs/promises";import{z as hG}from"zod";var U="v1",xh="mobile-cli",$o="0.16.1";var lG=9e4,cG=3,uG=1500,dG=15e3,Ir=class extends Error{status;rawError;constructor(e,t,n,o={}){super(n,o),this.status=e,this.rawError=t}};async function mG(r){return r.text().then(e=>{try{return JSON.parse(e).error}catch{return e}})}var Mh=class{baseUrl;logger;constructor(e){this.baseUrl=e.baseUrl,this.logger=e.logger}getHeaders(){let e={"Content-Type":"application/json"};return $o&&(e[mc]=$o),xh&&(e[aE]=xh),e}async sendRequest(e,t){let{retries:n=cG,requestTimeoutMs:o=lG,initialRetryDelayMs:i=uG,maxRetryDelayMs:a=dG,onFailedRequest:s}=t,c=n,l=n,u,d={path:e,baseUrl:this.baseUrl,method:t.method};for(;c>0;)try{return c--,await this.sendSingleRequestHelper(e,t,o)}catch(m){u=m;try{s?.(u)}catch{}if(m instanceof Ir&&m.status>=400&&m.status<500)throw m;if(m instanceof Error&&m.name==="AbortError"&&(u=new zn),c===0)throw u;let p=l-c,g=Math.min(i*Math.pow(2,p-1),a);await new Promise(h=>setTimeout(h,g))}throw this.logger.warn({...d,err:u},"Got fatal error response from Momentic server"),u}async sendSingleRequestHelper(e,t,n){let o={path:e,baseUrl:this.baseUrl,method:t.method},i=new AbortController,a=setTimeout(()=>i.abort(),n),s=()=>i.abort();t.signal&&t.signal.addEventListener("abort",s,{once:!0});let c=Date.now(),l={...this.getHeaders(),...t.extraHeaders};try{let u=await fetch(`${this.baseUrl}${e}`,{method:t.method,body:t.body?JSON.stringify(t.body):void 0,headers:l,signal:i.signal});if(!u.ok){let m=await mG(u);throw new Ir(u.status,m,`Request to ${t.method} ${e} failed with status ${u.status}: ${m}`)}let d;if(u.status===204)d={};else{let m=await u.text();try{d=JSON.parse(m)}catch{d=m}}return this.logger&&t.logResponse===!0&&d&&this.logger.debug({result:d,status:u.status,durationMs:Date.now()-c,...o},"Got response from Momentic server"),d}finally{clearTimeout(a),t.signal&&t.signal.removeEventListener("abort",s)}}},nn=class extends Mh{apiKey;mode;constructor(e){super(e),this.apiKey=e.apiKey,this.mode=e.mode}getHeaders(){return{...super.getHeaders(),Authorization:`Bearer ${this.apiKey}`,[iE]:this.mode??""}}};import{createAnthropic as pG}from"@ai-sdk/anthropic";function gG(r){let{apiKey:e,sessionId:t,extraHeaders:n,loggerTags:o}=r,i={Authorization:`Bearer ${e}`,[mc]:$o??"",...t&&{[lE]:t},...n||{}};return o&&(i[sE]=JSON.stringify(o)),i}var ud=r=>e=>{let t=gG(r);return pG({baseURL:`${r.baseUrl}/v1/llm/anthropic/${e}`,headers:t,apiKey:r.apiKey})(e)};var qo=class extends nn{agentConfig;constructor(e,t){let n={...Ky,...e};super(t),this.agentConfig=n}getAgentConfig(){return this.agentConfig}async rankChunksWithAi(e,t){let n={...e,loggerTags:t.loggerTags},o=await this.sendRequest(`/${U}/web-agent/recommend-chunks-ai`,{method:"POST",body:n,signal:t.abortSignal});return Ly.parse(o)}async rankChunksWithRag(e,t){let n=await this.sendRequest(`/${U}/web-agent/recommend-chunks`,{method:"POST",body:{cliVersion:$o,...e},signal:t.abortSignal});return Oy.parse(n)}async getScreenshotFromS3(e){let t=await this.sendRequest(`/${U}/s3/visual-diff-screenshot`,{method:"POST",body:{url:e}});return hG.string().parse(t)}async getElementLocation(e,t){let n={...e,disableCache:t.disableCache,loggerTags:t.loggerTags,useMemory:t.useMemory,agentConfigVersion:this.agentConfig?.locator},o=await this.sendRequest(`/${U}/web-agent/locate-element`,{method:"POST",body:n,signal:t.abortSignal});return gE.parse(o)}async getAssertionResult(e,t){let n={...e,disableCache:!!t.disableCache,useConsensus:!!t.useConsensus,attemptNumber:t.attemptNumber,loggerTags:t.loggerTags,useMemory:t.useMemory,agentConfigVersion:this.agentConfig?.assertion},o=await this.sendRequest(`/${U}/web-agent/assertion`,{method:"POST",body:n,signal:t.abortSignal});return op.parse(o)}async getLintStepResult(e,t){let n={...e,disableCache:!!t.disableCache,loggerTags:t.loggerTags},o=await this.sendRequest(`/${U}/web-agent/lint/step`,{method:"POST",body:n,signal:t.abortSignal});return pE.parse(o)}async getLintMcpCopilotMessageResult(e,t){let n={message:e.message,disableCache:!!t.disableCache,loggerTags:t.loggerTags},o=await this.sendRequest(`/${U}/web-agent/lint/mcp-copilot`,{method:"POST",body:n,signal:t.abortSignal});return uE.parse(o)}async getMcpCopilotConversationEvaluation(e,t){let n={messagesAndToolCalls:e.messagesAndToolCalls,disableCache:!!t.disableCache,loggerTags:t.loggerTags},o=await this.sendRequest(`/${U}/web-agent/mcp-copilot-conversation-evaluator`,{method:"POST",body:n,signal:t.abortSignal});return dE.parse(o)}async getMcpCopilotChatSummary(e,t){let n={messagesAndToolCalls:e.messagesAndToolCalls,disableCache:!!t.disableCache,loggerTags:t.loggerTags},o=await this.sendRequest(`/${U}/web-agent/mcp-copilot-chat-summary`,{method:"POST",body:n,signal:t.abortSignal});return mE.parse(o)}async getVisualAssertionResult(e,t){let n={...e,disableCache:!!t.disableCache,useConsensus:!!t.useConsensus,attemptNumber:t.attemptNumber,loggerTags:t.loggerTags,useMemory:t.useMemory,agentConfigVersion:this.agentConfig?.["visual-assertion"]},o=await this.sendRequest(`/${U}/web-agent/visual-assertion`,{method:"POST",body:n,signal:t.abortSignal});return op.parse(o)}async getAiActionCommand(e,t){let n=await this.sendRequest(`/${U}/web-agent/next-command-dynamic`,{method:"POST",body:{...e,disableCache:t.disableCache,loggerTags:t.loggerTags},signal:t.abortSignal});return cE.parse(n)}async getMultiturnAiActionCommand(e,t){return await this.sendRequest(`/${U}/web-agent/ai-action/next-command`,{method:"POST",body:{...e,disableCache:t.disableCache,loggerTags:t.loggerTags},signal:t.abortSignal})}async getMultiturnAiActionEvaluation(e,t){let n=await this.sendRequest(`/${U}/web-agent/ai-action/evaluate`,{method:"POST",body:{...e,disableCache:t.disableCache,loggerTags:t.loggerTags},signal:t.abortSignal});return ym.parse(n)}async getReverseMappedDescription(e,t){let n=await this.sendRequest(`/${U}/web-agent/reverse-mapped-description`,{method:"POST",body:{...e,disableCache:t.disableCache,loggerTags:t.loggerTags},signal:t.abortSignal});return hE.parse(n)}async getTextExtraction(e,t){let n={...e,disableCache:t.disableCache,loggerTags:t.loggerTags,agentConfigVersion:this.agentConfig?.["text-extraction"]},o=await this.sendRequest(`/${U}/web-agent/text-extraction`,{method:"POST",body:n,signal:t.abortSignal});return fm.parse(o)}async getPageSummary(e,t){let n={...e,disableCache:t.disableCache,loggerTags:t.loggerTags},o=await this.sendRequest(`/${U}/web-agent/page-summary`,{method:"POST",body:n,signal:t.abortSignal});return dy.parse(o)}async getSmartWaitingDecision(e,t){let n={...e,disableCache:t.disableCache,loggerTags:t.loggerTags},o=await this.sendRequest(`/${U}/web-agent/smart-waiting`,{method:"POST",body:n,signal:t.abortSignal});return my.parse(o)}async getTestResultClassification(e,t){let n=await this.sendRequest(`/${U}/web-agent/result-classification`,{method:"POST",body:{...e,loggerTags:t.loggerTags},signal:t.abortSignal});return rm.parse(n)}async getExtractedKeywords(e,t){let n=await this.sendRequest(`/${U}/web-agent/extract-keywords`,{method:"POST",body:e,signal:t.abortSignal});return qy.parse(n)}async getAutohealingProposal(e,t){let n=await this.sendRequest(`/${U}/web-agent/autoheal-section`,{method:"POST",body:{...e,loggerTags:t.loggerTags},signal:t.abortSignal});return ay.parse(n)}async getFailureRecoveryProposal(e,t){let n=await this.sendRequest(`/${U}/web-agent/failure-recovery`,{method:"POST",body:{...e,loggerTags:t.loggerTags},signal:t.abortSignal});return cy.parse(n)}async getFailureRecoveryPlan(e,t){let n=await this.sendRequest(`/${U}/web-agent/failure-recovery-plan`,{method:"POST",body:{...e,loggerTags:t.loggerTags},signal:t.abortSignal});return ly.parse(n)}async getIframeRegex(e,t){let n=await this.sendRequest(`/${U}/web-agent/iframe-regex`,{method:"POST",body:e,signal:t.abortSignal});return Ef.parse(n)}getVercelAnthropicModelFactory({loggerTags:e}){return ud({baseUrl:this.baseUrl,apiKey:this.apiKey,loggerTags:e})}};import{z as _h}from"zod";var Yt=class extends nn{constructor(e){super({...e,mode:void 0})}getAppUrl(){return this.baseUrl==="http://localhost:8000"?"http://localhost:3000":this.baseUrl.replace(/\/\/api/,"//app")}async getAuthInfo(){let e=await this.sendRequest(`/${U}/auth/check`,{method:"GET",retries:10,requestTimeoutMs:5e3,onFailedRequest:t=>{C.warn(`API key check failed: ${t.message}`)}});return ME.parse(e)}async bulkGetRunStatus(e){let t=await this.sendRequest(`/${U}/runs/status`,{method:"POST",body:e,retries:3,requestTimeoutMs:1e4});return wE.parse(t)}async getTestYAMLExport(e){let t=await this.sendRequest(`/${U}/tests/export`,{method:"POST",body:e,retries:3,requestTimeoutMs:3e4});return SE.parse(t)}async updateStepCaches(e,t){await this.sendRequest(`/${U}/cache`,{method:"PATCH",body:e,extraHeaders:t,retries:3,requestTimeoutMs:1e4,initialRetryDelayMs:3e3})}async getStepCacheForTest(e,t){let n=await this.sendRequest(`/${U}/cache`,{method:"POST",body:e,extraHeaders:t,retries:10,requestTimeoutMs:3e4,initialRetryDelayMs:3e3});return bE.parse(n)}async updateMobileStepCaches(e,t){await this.sendRequest(`/${U}/mobile-cache`,{method:"PATCH",body:e,extraHeaders:t,retries:3,requestTimeoutMs:1e4,initialRetryDelayMs:3e3})}async getMobileStepCacheForTest(e,t){let n=await this.sendRequest(`/${U}/mobile-cache`,{method:"POST",body:e,extraHeaders:t,retries:10,requestTimeoutMs:3e4,initialRetryDelayMs:3e3});return EE.parse(n)}async queueTests(e){let t=await this.sendRequest(`/${U}/tests/queue`,{method:"POST",body:e,retries:3,requestTimeoutMs:1e4});return fE.parse(t)}async uploadScreenshot(e){let t=await this.sendRequest(`/${U}/screenshots`,{method:"POST",body:e,retries:3,requestTimeoutMs:5e3});return xE.parse(t)}async getAllEnvironments(){let e=await this.sendRequest(`/${U}/environments`,{method:"GET",retries:3,requestTimeoutMs:5e3});return _E.parse(e)}async acquireCacheLock(e,t){let n=await this.sendRequest(`/${U}/result-cache/lock`,{method:"POST",body:e,signal:t,retries:3,requestTimeoutMs:3e4});return jE.parse(n)}async releaseCacheLock(e){await this.sendRequest(`/${U}/result-cache/lock`,{method:"DELETE",body:{key:e},retries:3,requestTimeoutMs:5e3})}async deleteCacheResult(e){await this.sendRequest(`/${U}/result-cache/entry`,{method:"DELETE",body:e,retries:3,requestTimeoutMs:5e3})}async setCacheResult(e){await this.sendRequest(`/${U}/result-cache/entry`,{method:"PATCH",body:e,retries:3,requestTimeoutMs:5e3})}async getCacheResult(e){try{return await this.sendRequest(`/${U}/result-cache/entry`,{method:"POST",body:e,retries:3,requestTimeoutMs:5e3})}catch(t){if(t instanceof Error&&t.message.includes("404"))return null;throw t}}async queueSuiteRuns(e){let t=await this.sendRequest(`/${U}/suites/queue`,{method:"POST",body:e,retries:3,requestTimeoutMs:5e3});return PE.parse(t)}async bulkGetRunGroupStatus(e){let t={runGroupIds:e},n=await this.sendRequest(`/${U}/run-groups/status`,{method:"POST",body:t,retries:3,requestTimeoutMs:5e3});return My.array().parse(n)}async uploadProposedSteps(e,t){try{await this.sendRequest(`/${U}/test-fragments/`,{method:"POST",body:e,retries:3,requestTimeoutMs:1e4})}catch(n){t.error({err:n},"Failed to upload proposed steps")}}async reportBillableEvents(e,t){try{await this.sendRequest(`/${U}/billing/events`,{method:"POST",body:t,retries:10,requestTimeoutMs:1e4})}catch(n){e.error({err:n},"Failed to report billable event")}}async fetchTestFragment(e){let t=await this.sendRequest(`/${U}/test-fragments/${e}`,{method:"GET",retries:3,requestTimeoutMs:1e4});return IE.parse(t)}async patchTestFragment(e,t){await this.sendRequest(`/${U}/test-fragments/${e}`,{method:"PATCH",body:t,retries:3,requestTimeoutMs:1e4})}async getPastTestResults(e,t){let n=await this.sendRequest(`/${U}/results/tests/${e}`,{method:"POST",body:t,retries:3,requestTimeoutMs:1e4});return OE.parse(n)}async generateTestResultsUploadUrl(){let e=await this.sendRequest(`/${U}/results/uploads`,{method:"POST",retries:3,requestTimeoutMs:1e4});return LE.parse(e)}async startProcessingResultsUpload(e,t){let n=await this.sendRequest(`/${U}/results/uploads/${e}/process`,{method:"POST",body:t,retries:3,requestTimeoutMs:1e4});return NE.parse(n)}async fetchIconKnowledgeBase(e){try{let t=await this.sendRequest(`/${U}/knowledge-base/icons`,{method:"GET",retries:3,requestTimeoutMs:5e3});return KE.parse(t)}catch(t){return e.error({err:t},"Failed to fetch icon knowledge base"),null}}async saveNewIcons(e,t){try{await this.sendRequest(`/${U}/knowledge-base/icons`,{method:"POST",body:e,retries:3,requestTimeoutMs:5e3})}catch(n){t.error({err:n},"Failed to save new icons to icon knowledge base")}}async getMergeBaseCommitFromGithub(e,t,n,o){let i=new URLSearchParams;i.set("base",n),i.set("head",o);let a=await this.sendRequest(`/${U}/git/github/${e}/${t}/merge-base-commit?${i.toString()}`,{method:"GET",retries:3,requestTimeoutMs:1e4});return is.parse(a)}async getCommitFromGithub(e,t,n){let o=await this.sendRequest(`/${U}/git/github/${e}/${t}/commits/${n}`,{method:"GET",retries:3,requestTimeoutMs:1e4});return is.parse(o)}async getMergedBranchFromGithub(e,t,n,o){let i=encodeURIComponent(n),a=await this.sendRequest(`/${U}/git/github/${e}/${t}/${i}/${o}/merged-branch`,{method:"GET",retries:3,requestTimeoutMs:1e4});return lp.parse(a)}async getMergeBaseCommitFromGitlab(e,t,n){let o=new URLSearchParams;o.set("base",t),o.set("head",n);let i=encodeURIComponent(e),a=await this.sendRequest(`/${U}/git/gitlab/${i}/merge-base-commit?${o.toString()}`,{method:"GET",retries:3,requestTimeoutMs:5e3});return is.parse(a)}async getCommitFromGitlab(e,t){let n=encodeURIComponent(e),o=await this.sendRequest(`/${U}/git/gitlab/${n}/commits/${t}`,{method:"GET",retries:3,requestTimeoutMs:1e4});return is.parse(o)}async getMergedBranchFromGitlab(e,t,n){let o=encodeURIComponent(t),i=encodeURIComponent(e),a=await this.sendRequest(`/${U}/git/gitlab/${i}/${o}/${n}/merged-branch`,{method:"GET",retries:3,requestTimeoutMs:1e4});return lp.parse(a)}async getAgentConfig(){let e=await this.sendRequest(`/${U}/web-agent/agent-config`,{method:"GET",retries:3,requestTimeoutMs:5e3});return _h.record(_h.string(),_h.string()).parse(e)}async getQuarantinedTests(){let e=await this.sendRequest(`/${U}/quarantine`,{method:"GET"});return DE.parse(e)}async quarantineTest(e,t,n){await this.sendRequest(`/${U}/quarantine`,{method:"POST",body:{testId:e.id,testName:e.name,reason:t,...n??{}},retries:3,requestTimeoutMs:1e4})}async unquarantineTest(e,t,n){await this.sendRequest(`/${U}/quarantine/${e.id}`,{method:"DELETE",body:{testName:e.name,reason:t,...n??{}},retries:3,requestTimeoutMs:1e4})}async createAndroidEmulator(e){let t=await this.sendRequest(`/${U}/limbar/android`,{method:"POST",retries:3,body:e,requestTimeoutMs:9e4,initialRetryDelayMs:5e3,maxRetryDelayMs:15e3});return kE.parse(t)}async extendAndroidEmulatorTtl(e){try{await this.sendRequest(`/${U}/limbar/android/${e}/keepalive`,{method:"POST",retries:3,requestTimeoutMs:15e3})}catch{}}async generateAndroidAssetUrls({channel:e,tag:t,md5:n}){let o={channel:e,tag:t,md5:n},i=await this.sendRequest(`/${U}/limbar/android/upload-url`,{method:"POST",retries:3,body:o,requestTimeoutMs:15e3,logResponse:!0});return FE.parse(i)}async deleteAndroidEmulator(e){await this.sendRequest(`/${U}/limbar/android/${e}`,{method:"DELETE",retries:3,requestTimeoutMs:3e4})}async getAndroidAssets(){let e=await this.sendRequest(`/${U}/limbar/assets`,{method:"GET",retries:3,requestTimeoutMs:1e4});return BE.parse(e)}async deleteAndroidAsset(e,t){await this.sendRequest(`/${U}/limbar/assets/${e}/${t}`,{method:"DELETE",retries:3,requestTimeoutMs:1e4})}async createIosEmulator(e){let t=await this.sendRequest(`/${U}/limbar/ios`,{method:"POST",retries:3,body:e,requestTimeoutMs:9e4,initialRetryDelayMs:5e3,maxRetryDelayMs:15e3});return UE.parse(t)}async extendIosEmulatorTtl(e){try{await this.sendRequest(`/${U}/limbar/ios/${e}/keepalive`,{method:"POST",retries:3,requestTimeoutMs:15e3})}catch{}}async deleteIosEmulator(e){await this.sendRequest(`/${U}/limbar/ios/${e}`,{method:"DELETE",retries:3,requestTimeoutMs:3e4})}async generateMobileLogcatUploadUrl(e){let t=await this.sendRequest(`/${U}/logcat/mobile/upload`,{method:"POST",body:e,retries:3,requestTimeoutMs:1e4});return Sb.parse(t)}};async function Ph(r){let e=process.versions.node,t=parseInt(e.split(".")[0]);(isNaN(t)||t<18)&&(C.error(`Node.js version 20 or higher is required to run the CLI. Detected: ${process.versions.node}.`),process.exit(1)),C.debug(`Identified node version ${e}`);let n=await r.client.getAuthInfo();return C.debug("Got auth info from API"),n}var dd=class{apiClient;constructor(e){this.apiClient=e}async reportBillableEvents(e,t){await this.apiClient.reportBillableEvents(e,t)}};var ta=class extends nn{generator;constructor(e,t){super(e),this.generator=t}async runTemplateMatching(e,t={}){let n=await this.sendRequest(`/${U}/web-agent/template-matching`,{method:"POST",body:e,signal:t?.signal});return Tf.parse(n)}async constructIframeRegex(e,t={}){return this.generator.getIframeRegex(e,{abortSignal:t.signal})}};var ra=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 fG,en as SG}from"@faker-js/faker";var na="v1",oa=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 fG({locale:SG}),this.fakerInstance.seed(e.fakerSeed))}async sendAiGenerate(e){let t=typeof e=="string"?{input:e}:e;return this.httpClient.sendRequest(`/${na}/tools/ai/generate`,{method:"POST",body:t}).catch(n=>{throw n instanceof Ir?new Error(n.rawError):new Error(`Failed to send AI generation: ${n.message}`)})}async sendSms(e){return this.httpClient.sendRequest(`/${na}/tools/sms/send`,{method:"POST",body:e}).then(()=>{}).catch(t=>{throw t instanceof Ir?new Error(t.rawError):new Error(`Failed to send sms: ${t.message}`)})}async fetchLatestSms(e){return this.httpClient.sendRequest(`/${na}/tools/sms/fetchLatest`,{method:"POST",body:e}).catch(t=>{throw t instanceof Ir?new Error(t.rawError):t})}async sendEmail(e){return this.httpClient.sendRequest(`/${na}/tools/email/send`,{method:"POST",body:e}).then(()=>{}).catch(t=>{throw t instanceof Ir?new Error(t.rawError):new Error(`Failed to send email: ${t.message}`)})}async fetchAllEmails(e){return this.httpClient.sendRequest(`/${na}/tools/email/fetchAll`,{method:"POST",body:e}).catch(t=>{throw t instanceof Ir?new Error(t.rawError):new Error(`Failed to fetch all emails: ${t.message}`)})}async fetchLatestEmail(e){return this.httpClient.sendRequest(`/${na}/tools/email/fetchLatest`,{method:"POST",body:e}).catch(t=>{throw t instanceof Ir?new Error(t.rawError):new Error(`Failed to fetch latest emails: ${t.message}`)})}};function pM(r,e,t){return fetch(r,{method:"PUT",body:t,headers:{"Content-Type":e}})}var md=class{constructor(e){this.client=e}async uploadResultsArchive(e,t){let{uploadUrl:n,id:o}=await this.client.generateTestResultsUploadUrl(),i=await pM(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 ia=class extends nn{constructor(e){super(e)}async getMobileElementLocation(e,t){let n={...e,disableCache:t.disableCache,useMemory:t.useMemory,agentConfigVersion:t.agentConfigVersion,loggerTags:t.loggerTags},o=await this.sendRequest(`/${U}/mobile-agent/locate-element`,{method:"POST",body:n,signal:t.abortSignal});return Eb.parse(o)}async evaluateMobileAssertion(e,t){let n={...e,disableCache:t.disableCache,useMemory:t.useMemory,agentConfigVersion:t.agentConfigVersion,loggerTags:t.loggerTags},o=await this.sendRequest(`/${U}/mobile-agent/assertion`,{method:"POST",body:n,signal:t.abortSignal});return Ab.parse(o)}async getMobileFailureRecoveryPlan(e,t){let n=await this.sendRequest(`/${U}/mobile-agent/failure-recovery-plan`,{method:"POST",body:{...e,loggerTags:t.loggerTags},signal:t.abortSignal});return Rb.parse(n)}getVercelAnthropicModelFactory({loggerTags:e,sessionId:t}){return ud({baseUrl:this.baseUrl,apiKey:this.apiKey,sessionId:t,loggerTags:e})}};function pd({orgId:r,client:e,gitMetadata:t,regenerateCache:n,alwaysSaveCache:o,noCache:i}){return i?new gc:new Ih(r,e,t,{alwaysSaveCache:o,regenerateCache:n})}var Ih=class{constructor(e,t,n,o){this.orgId=e;this.client=t;let{regenerateCache:i,alwaysSaveCache:a}=o,{gitBranchName:s,gitProtectedBranches:c}=n;this.cacheHeaders=ip(n),this.readCaches=!i;let l=s&&c.includes(s);a||!l?this.writeCaches=!0:this.writeCaches=!1}cacheHeaders;readCaches;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.warn({err:o},"Failed to save mobile step cache entries, continuing...")}}async resolveEntries(e){if(!this.readCaches){e.logger.debug("Skipping cache resolution because of regenerate flag");return}let{steps:t}=e.stepLists,n=await this.client.getMobileStepCacheForTest({testId:e.testId},this.cacheHeaders);if(!this.writeCaches){e.logger.info("Skipping mobile cache last used at update because branch is protected");return}for(let i of[t])i&&Cg({steps:i,stepCacheEntries:n,logger:e.logger});let{cachesToSave:o}=await Xr({steps:t,cacheCreationParams:{testId:e.testId,orgId:this.orgId}});this.client.updateMobileStepCaches({entries:o,testId:e.testId},this.cacheHeaders)}};async function gM({socket:r,logger:e,globalStateManager:t,authorization:n}){let o=r.id,i=t.getSession(o);i&&n&&i.logFilePath&&yG({testId:i.metadata.testId,sessionId:o,logFilePath:i.logFilePath,authorization:n,logger:e}),await t.removeSession(o,e)}async function yG({testId:r,sessionId:e,logFilePath:t,authorization:n,logger:o}){try{let i;try{i=await gd.stat(t)}catch{o.debug({logFilePath:t},"No logcat file found to upload");return}if(i.size===0){o.debug({logFilePath:t},"Logcat file is empty, skipping upload"),await gd.unlink(t);return}let a=new Yt(n),{uploadUrl:s}=await a.generateMobileLogcatUploadUrl({testId:r,sessionId:e}),c=await gd.readFile(t),l=await fetch(s,{headers:{"Content-Length":c.length.toString(),"Content-Type":"text/plain"},method:"PUT",body:c});if(l.status!==200)throw new Error(`Failed to upload logcat: ${l.status} ${await l.text()}`);o.info({testId:r,sessionId:e},"Logcat file uploaded successfully")}catch(i){o.warn({err:i,testId:r,sessionId:e},"Failed to upload logcat file")}finally{try{await gd.unlink(t)}catch(i){o.warn({err:i,logFilePath:t},"Failed to delete temp logcat file")}}}var bG=({socket:r,globalStateManager:e})=>async()=>{let t=e.getSession(r.id);if(!t)throw new Error("No active Android session found");t.controller.abort()},hM={event:"cancel",createHandler:bG};var EG=({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})}},fM={event:"fetchA11yTree",createHandler:EG};import{diff as GG}from"deep-object-diff";import{cloneDeep as VG}from"lodash-es";var TG=1e4,vG=5e3;function SM(r,e,t,n){let o=0;async function i(){try{let s=await B(r.driver.execute("mobile: shell",{command:"echo",args:["ping"]}).catch(c=>{throw c}),{milliseconds:vG});if(typeof s=="string"&&s.trim()==="ping")o>0&&(e.info("Driver heartbeat restored"),n?.()),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"),t?.())}}let a=setInterval(()=>{i()},TG);return i(),a}async function yM(r){let e=Date.now(),t=r.fixtures.controller;try{return await AG(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 AG({moduleParams:r,...e}){let t=Date.now(),{step:n,stepTracer:o,executeMobileStepList:i}=r,a=await wG({step:n,params:e}),s={};Object.entries(a).forEach(([m,p])=>{s[m]=JSON.stringify(p)});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(),vC({result:c,...TC(d)}),c}async function wG({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 Jr({orgId:e.inputs.orgId,code:a,fragment:!0,logger:n,context:o.context,localTools:o.localCodeEvalTools})}return t}import{randomUUID as bM}from"crypto";import{diff as CG}from"deep-object-diff";import{cloneDeep as RG}from"lodash-es";async function EM({fixtures:r,step:e,inputs:t,stepTracer:n}){let o=Date.now(),{logger:i,controller:a}=r,s;if(!t.interactive)try{s=await a.getScreenshotBase64()}catch(u){i.warn({err:u},"Failed to take before screenshot")}let c="cache"in e.command?RG(e.command.cache??{}):{},l={...e,status:"SUCCESS",startTime:o,endTime:Date.now()};try{let u=await a.executeCommand({command:e.command});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(!t.interactive){try{let m=bM(),p=await a.getScreenshotBase64();l.afterSnapshot=m,n.attachAfterScreenshot({logger:i,snapshotId:m,screenshot:Buffer.from(p,"base64")})}catch(m){i.warn({err:m},"Failed to take after screenshot")}if(s){let m=bM();l.beforeSnapshot=m,n.attachBeforeScreenshot({logger:i,snapshotId:m,screenshot:Buffer.from(s,"base64")})}}let u="cache"in e.command?e.command.cache??{}:{},d=CG(c,u);d&&Object.keys(d).length>0&&i.info({diffs:Ti(d)},"Updated cache")}return l}import{streamText as UG}from"ai";import{randomUUID as FG}from"crypto";var hd=class{controller;logger;rootStep;subStepIndex=0;callbacks;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}recordGenericToolCall(e){this.callbacks.onAiActionEvent?.({type:"GENERIC_TOOL_CALLED",toolName:e,rootStep:this.rootStep})}};import{hasToolCall as DG,stepCountIs as kG}from"ai";var Oh="get_emulator_state",fd="finish";import TM from"dedent";var MG=TM`
4367
+ `).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.abortSignal,reason:"Waiting for stability after app launch"}),{success:!0}}case"PRESS":{let n=new Qn(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 Qn(this.constructPerformerParams()),o=i=>n.doPress({keycode:i});switch(e.key){case"CLOSE_KEYBOARD":{let i=Date.now();for(;Date.now()-i<5e3&&(await this.driver.hideKeyboard(),!!await this.driver.isKeyboardShown()););break}case"ENTER":await o(66);break;case"BACKSPACE":await o(67);break;default:{let i=e}}return{success:!0}}case"WAIT":return await j(e.timeoutSecs*1e3,this.aborter.controller?.signal),{success:!0};case"INSTALL_APP":return new nd(this.constructPerformerParams()).doInstallApk(e);case"UNINSTALL_APP":return new cd(this.constructPerformerParams()).doUninstallApk(e);case"ADD_FILE":{let n=await cM(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"TOGGLE_SETTINGS":{switch(e.settingsType){case"AIRPLANE_MODE":await this.driver.toggleAirplaneMode();break;case"DATA":await this.driver.toggleData();break;case"WIFI":await this.driver.toggleWiFi();break;case"LOCATION":await this.driver.toggleLocationServices();break;default:throw e.settingsType,new Error(`Unknown settings type: ${e.settingsType}`)}return{success:!0}}case"ADB":{let n=await this.driver.execute(e.command,JSON.parse(e.jsonArgs??"{}"));return this.logger.info({output:n},"ADB command executed successfully"),{success:!0,output:n,message:"ADB command executed successfully"}}case"KILL_APP":{let n=await this.stateManager.getCurrentPackage();if(!n)throw new Error("No package is currently active");await this.driver.execute("mobile: shell",{command:"input",args:["keyevent","KEYCODE_HOME"]}),await this.driver.terminateApp(n);try{await Gx({packageName:n,driver:this.driver,abortSignal:this.abortSignal,logger:this.logger})}catch(o){this.throwIfAborted(),this.logger.warn({err:o,packageName:n},"Failed to remove package from recents, continuing...")}return{success:!0}}case"STATE":{await this.stateManager.refreshWebviews();let n=await this.stateManager.getDomState(),o=await this.stateManager.getContexts(),i={xml:n.graph.xml,contexts:o};return this.logger.info({result:i},"State debug command output"),{output:i,success:!0}}default:{let n=e;return{success:!0}}}}async initializeSettings(){let{latitude:e,longitude:t}=this.options?.emulator?.geolocation??Ll;await this.driver.execute("mobile: shell",{command:"pm",args:["grant","io.appium.settings","android.permission.ACCESS_COARSE_LOCATION"]}),await this.driver.execute("mobile: shell",{command:"pm",args:["grant","io.appium.settings","android.permission.ACCESS_FINE_LOCATION"]}),await this.driver.setGeoLocation({latitude:e,longitude:t})}async getScreenshotBase64(){return this.stateManager.getRawScreenshotBase64()}async getScreenshotPngString(){return this.stateManager.getCurrentScreenshotPngString()}async getA11yTree(){return(await this.stateManager.getDomState({})).graph.xml}async executeRawADBCommand(e){return this.stateManager.executeRawADBCommand(e)}async getViewportBounds(){return this.stateManager.getViewportBounds()}async waitForScreenshotStability(e){return this.stateManager.waitForScreenshotStability({timeoutMs:e.timeoutMs??5e3,reason:e.reason,signal:this.aborter.controller?.signal})}resetAbortController(e){this.aborter.controller=e??new AbortController}isAborted(){return this.aborter.controller?.signal.aborted}abort(){this.aborter.controller?.abort()}async cleanup(){await this.stateManager.cleanupWebviews()}get abortSignal(){return this.aborter.controller?.signal}get context(){return this.fixtures.testContext}get localCodeEvalTools(){return this.fixtures.localCodeEvalTools}};async function mM({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,m=r.handshake.query?.testMetadata,p=r.handshake.query?.fileName,g=p?dM.basename(p,".test.yaml"):"",h=wr.parse(JSON.parse(m??"")),f=h.id,E=h.settings?.defaultChannel,b=h.settings?.defaultTag,w=await n({testId:f});e=e.child({sessionId:d,testId:f,orgId:w});let x=await s(w),A=h.settings?.defaultEnv,M={};A&&(M=(await x.fetchEnvironment(A,e))?.variables??{});let v=Ai.parse(M[Eo]),_=Ai.parse(M[Fa]),k=await u(w,e),V={...k.emulator,...h.settings?.emulator},Z=h.settings?.defaultApkFilePath?.trim()||_,te=l.getSession(d);if(te){if(e.info("Reconnecting to existing Android session"),te.local)return r.emit("session",te.metadata),te.softDeleted=!1,te.metadata;throw new Error("Restoring existing remote emulator sessions is not supported. Please reconnect to a new emulator.")}let yt;if(V.region==="local"){if(await l.clearSoftDeletedLocalSessions(e),l.hasActiveLocalSession())throw new Error("Another local emulator session is already active. Please close the existing session before creating a new one.");let an=h.settings?.emulator?.localEmulatorSettings?.avdId?.trim()||v;if(!an)throw new Error(`AVD ID is required when using a local emulator. Set it on the test (Options \u2192 Emulator \u2192 Local AVD ID) or on the environment via ${Eo}.`);yt={avdId:an,apkToInstall:E?{channel:E,tag:b}:void 0,apkFilePath:Z}}else yt={region:V.region,apkToInstall:E?{channel:E,tag:b}:void 0,osVersion:V.remoteEmulatorSettings?.androidVersion};let Y=Date.now(),{driver:H,cleanup:ce,emulatorName:pe,adbPort:Je,limbarClient:Re,limbarToken:jt,limbarUrl:_t,playwrightDevice:Ue}=await t({socket:r,logger:e,creationOpts:yt}),lt=dM.join(aG(),`logcat-logs-${w}-${f}-${d}.txt`),Or=await Cu({driver:H,onLogs:an=>{r.emit("logcatLogs",an)},logFilePath:lt});e.info({adbPort:Je,apkChannel:E,apkTag:b,duration:Date.now()-Y,emulatorName:pe},"Android emulator session initiated"),e=e.child({emulator:pe});let vn=await o(w,e),oo=await i(w,e),Xo=await a(w,e),fa=c?await c(w):void 0,io=new bi({variablesFromEnvironment:M,envName:A,testName:g}),ao=await ea.init({driver:H,generator:vn,logger:e,limbarClient:Re,playwrightDevice:Ue,aiSettings:{...k.ai,useMemory:k.ai?.useMemory!==!1,...h.settings?.ai},options:{emulator:V},fixtures:{storage:x,browserEnricher:Xo,browserGenerator:oo,localCodeEvalTools:fa,testContext:io},orgId:w,adbPort:Je,abortController:new AbortController}),so=await ao.getViewportBounds();if(!r.connected)throw await Or(),await ce(),new Error("Socket not connected anymore, not proceeding with Android session setup");let Lr=sG({socket:r,testContext:io}),$=async()=>{clearInterval(Lr);try{await Or(),await ce(),await ao.cleanup()}catch(an){e.warn({err:an},"Failed to clean up emulator in socket server")}},Sa={sessionId:d,testId:f,orgId:w,emulatorName:pe,testName:g,limbarUrl:_t,limbarToken:jt,viewportBounds:so};return l.registerSession(d,{controller:ao,cleanup:$,emulatorName:pe,local:V.region==="local",metadata:Sa,logFilePath:lt}),r.emit("session",Sa),Sa}function sG({socket:r,testContext:e}){return setInterval(()=>{let t=e.toEditorDisplayCopy();r.emit("emulatorState",{context:t})},3e3)}import gd from"fs/promises";import{z as hG}from"zod";var U="v1",xh="mobile-cli",$o="0.16.3";var lG=9e4,cG=3,uG=1500,dG=15e3,Ir=class extends Error{status;rawError;constructor(e,t,n,o={}){super(n,o),this.status=e,this.rawError=t}};async function mG(r){return r.text().then(e=>{try{return JSON.parse(e).error}catch{return e}})}var Mh=class{baseUrl;logger;constructor(e){this.baseUrl=e.baseUrl,this.logger=e.logger}getHeaders(){let e={"Content-Type":"application/json"};return $o&&(e[mc]=$o),xh&&(e[aE]=xh),e}async sendRequest(e,t){let{retries:n=cG,requestTimeoutMs:o=lG,initialRetryDelayMs:i=uG,maxRetryDelayMs:a=dG,onFailedRequest:s}=t,c=n,l=n,u,d={path:e,baseUrl:this.baseUrl,method:t.method};for(;c>0;)try{return c--,await this.sendSingleRequestHelper(e,t,o)}catch(m){u=m;try{s?.(u)}catch{}if(m instanceof Ir&&m.status>=400&&m.status<500)throw m;if(m instanceof Error&&m.name==="AbortError"&&(u=new zn),c===0)throw u;let p=l-c,g=Math.min(i*Math.pow(2,p-1),a);await new Promise(h=>setTimeout(h,g))}throw this.logger.warn({...d,err:u},"Got fatal error response from Momentic server"),u}async sendSingleRequestHelper(e,t,n){let o={path:e,baseUrl:this.baseUrl,method:t.method},i=new AbortController,a=setTimeout(()=>i.abort(),n),s=()=>i.abort();t.signal&&t.signal.addEventListener("abort",s,{once:!0});let c=Date.now(),l={...this.getHeaders(),...t.extraHeaders};try{let u=await fetch(`${this.baseUrl}${e}`,{method:t.method,body:t.body?JSON.stringify(t.body):void 0,headers:l,signal:i.signal});if(!u.ok){let m=await mG(u);throw new Ir(u.status,m,`Request to ${t.method} ${e} failed with status ${u.status}: ${m}`)}let d;if(u.status===204)d={};else{let m=await u.text();try{d=JSON.parse(m)}catch{d=m}}return this.logger&&t.logResponse===!0&&d&&this.logger.debug({result:d,status:u.status,durationMs:Date.now()-c,...o},"Got response from Momentic server"),d}finally{clearTimeout(a),t.signal&&t.signal.removeEventListener("abort",s)}}},nn=class extends Mh{apiKey;mode;constructor(e){super(e),this.apiKey=e.apiKey,this.mode=e.mode}getHeaders(){return{...super.getHeaders(),Authorization:`Bearer ${this.apiKey}`,[iE]:this.mode??""}}};import{createAnthropic as pG}from"@ai-sdk/anthropic";function gG(r){let{apiKey:e,sessionId:t,extraHeaders:n,loggerTags:o}=r,i={Authorization:`Bearer ${e}`,[mc]:$o??"",...t&&{[lE]:t},...n||{}};return o&&(i[sE]=JSON.stringify(o)),i}var ud=r=>e=>{let t=gG(r);return pG({baseURL:`${r.baseUrl}/v1/llm/anthropic/${e}`,headers:t,apiKey:r.apiKey})(e)};var qo=class extends nn{agentConfig;constructor(e,t){let n={...Ky,...e};super(t),this.agentConfig=n}getAgentConfig(){return this.agentConfig}async rankChunksWithAi(e,t){let n={...e,loggerTags:t.loggerTags},o=await this.sendRequest(`/${U}/web-agent/recommend-chunks-ai`,{method:"POST",body:n,signal:t.abortSignal});return Ly.parse(o)}async rankChunksWithRag(e,t){let n=await this.sendRequest(`/${U}/web-agent/recommend-chunks`,{method:"POST",body:{cliVersion:$o,...e},signal:t.abortSignal});return Oy.parse(n)}async getScreenshotFromS3(e){let t=await this.sendRequest(`/${U}/s3/visual-diff-screenshot`,{method:"POST",body:{url:e}});return hG.string().parse(t)}async getElementLocation(e,t){let n={...e,disableCache:t.disableCache,loggerTags:t.loggerTags,useMemory:t.useMemory,agentConfigVersion:this.agentConfig?.locator},o=await this.sendRequest(`/${U}/web-agent/locate-element`,{method:"POST",body:n,signal:t.abortSignal});return gE.parse(o)}async getAssertionResult(e,t){let n={...e,disableCache:!!t.disableCache,useConsensus:!!t.useConsensus,attemptNumber:t.attemptNumber,loggerTags:t.loggerTags,useMemory:t.useMemory,agentConfigVersion:this.agentConfig?.assertion},o=await this.sendRequest(`/${U}/web-agent/assertion`,{method:"POST",body:n,signal:t.abortSignal});return op.parse(o)}async getLintStepResult(e,t){let n={...e,disableCache:!!t.disableCache,loggerTags:t.loggerTags},o=await this.sendRequest(`/${U}/web-agent/lint/step`,{method:"POST",body:n,signal:t.abortSignal});return pE.parse(o)}async getLintMcpCopilotMessageResult(e,t){let n={message:e.message,disableCache:!!t.disableCache,loggerTags:t.loggerTags},o=await this.sendRequest(`/${U}/web-agent/lint/mcp-copilot`,{method:"POST",body:n,signal:t.abortSignal});return uE.parse(o)}async getMcpCopilotConversationEvaluation(e,t){let n={messagesAndToolCalls:e.messagesAndToolCalls,disableCache:!!t.disableCache,loggerTags:t.loggerTags},o=await this.sendRequest(`/${U}/web-agent/mcp-copilot-conversation-evaluator`,{method:"POST",body:n,signal:t.abortSignal});return dE.parse(o)}async getMcpCopilotChatSummary(e,t){let n={messagesAndToolCalls:e.messagesAndToolCalls,disableCache:!!t.disableCache,loggerTags:t.loggerTags},o=await this.sendRequest(`/${U}/web-agent/mcp-copilot-chat-summary`,{method:"POST",body:n,signal:t.abortSignal});return mE.parse(o)}async getVisualAssertionResult(e,t){let n={...e,disableCache:!!t.disableCache,useConsensus:!!t.useConsensus,attemptNumber:t.attemptNumber,loggerTags:t.loggerTags,useMemory:t.useMemory,agentConfigVersion:this.agentConfig?.["visual-assertion"]},o=await this.sendRequest(`/${U}/web-agent/visual-assertion`,{method:"POST",body:n,signal:t.abortSignal});return op.parse(o)}async getAiActionCommand(e,t){let n=await this.sendRequest(`/${U}/web-agent/next-command-dynamic`,{method:"POST",body:{...e,disableCache:t.disableCache,loggerTags:t.loggerTags},signal:t.abortSignal});return cE.parse(n)}async getMultiturnAiActionCommand(e,t){return await this.sendRequest(`/${U}/web-agent/ai-action/next-command`,{method:"POST",body:{...e,disableCache:t.disableCache,loggerTags:t.loggerTags},signal:t.abortSignal})}async getMultiturnAiActionEvaluation(e,t){let n=await this.sendRequest(`/${U}/web-agent/ai-action/evaluate`,{method:"POST",body:{...e,disableCache:t.disableCache,loggerTags:t.loggerTags},signal:t.abortSignal});return ym.parse(n)}async getReverseMappedDescription(e,t){let n=await this.sendRequest(`/${U}/web-agent/reverse-mapped-description`,{method:"POST",body:{...e,disableCache:t.disableCache,loggerTags:t.loggerTags},signal:t.abortSignal});return hE.parse(n)}async getTextExtraction(e,t){let n={...e,disableCache:t.disableCache,loggerTags:t.loggerTags,agentConfigVersion:this.agentConfig?.["text-extraction"]},o=await this.sendRequest(`/${U}/web-agent/text-extraction`,{method:"POST",body:n,signal:t.abortSignal});return fm.parse(o)}async getPageSummary(e,t){let n={...e,disableCache:t.disableCache,loggerTags:t.loggerTags},o=await this.sendRequest(`/${U}/web-agent/page-summary`,{method:"POST",body:n,signal:t.abortSignal});return dy.parse(o)}async getSmartWaitingDecision(e,t){let n={...e,disableCache:t.disableCache,loggerTags:t.loggerTags},o=await this.sendRequest(`/${U}/web-agent/smart-waiting`,{method:"POST",body:n,signal:t.abortSignal});return my.parse(o)}async getTestResultClassification(e,t){let n=await this.sendRequest(`/${U}/web-agent/result-classification`,{method:"POST",body:{...e,loggerTags:t.loggerTags},signal:t.abortSignal});return rm.parse(n)}async getExtractedKeywords(e,t){let n=await this.sendRequest(`/${U}/web-agent/extract-keywords`,{method:"POST",body:e,signal:t.abortSignal});return qy.parse(n)}async getAutohealingProposal(e,t){let n=await this.sendRequest(`/${U}/web-agent/autoheal-section`,{method:"POST",body:{...e,loggerTags:t.loggerTags},signal:t.abortSignal});return ay.parse(n)}async getFailureRecoveryProposal(e,t){let n=await this.sendRequest(`/${U}/web-agent/failure-recovery`,{method:"POST",body:{...e,loggerTags:t.loggerTags},signal:t.abortSignal});return cy.parse(n)}async getFailureRecoveryPlan(e,t){let n=await this.sendRequest(`/${U}/web-agent/failure-recovery-plan`,{method:"POST",body:{...e,loggerTags:t.loggerTags},signal:t.abortSignal});return ly.parse(n)}async getIframeRegex(e,t){let n=await this.sendRequest(`/${U}/web-agent/iframe-regex`,{method:"POST",body:e,signal:t.abortSignal});return Ef.parse(n)}getVercelAnthropicModelFactory({loggerTags:e}){return ud({baseUrl:this.baseUrl,apiKey:this.apiKey,loggerTags:e})}};import{z as _h}from"zod";var Yt=class extends nn{constructor(e){super({...e,mode:void 0})}getAppUrl(){return this.baseUrl==="http://localhost:8000"?"http://localhost:3000":this.baseUrl.replace(/\/\/api/,"//app")}async getAuthInfo(){let e=await this.sendRequest(`/${U}/auth/check`,{method:"GET",retries:10,requestTimeoutMs:5e3,onFailedRequest:t=>{C.warn(`API key check failed: ${t.message}`)}});return ME.parse(e)}async bulkGetRunStatus(e){let t=await this.sendRequest(`/${U}/runs/status`,{method:"POST",body:e,retries:3,requestTimeoutMs:1e4});return wE.parse(t)}async getTestYAMLExport(e){let t=await this.sendRequest(`/${U}/tests/export`,{method:"POST",body:e,retries:3,requestTimeoutMs:3e4});return SE.parse(t)}async updateStepCaches(e,t){await this.sendRequest(`/${U}/cache`,{method:"PATCH",body:e,extraHeaders:t,retries:3,requestTimeoutMs:1e4,initialRetryDelayMs:3e3})}async getStepCacheForTest(e,t){let n=await this.sendRequest(`/${U}/cache`,{method:"POST",body:e,extraHeaders:t,retries:10,requestTimeoutMs:3e4,initialRetryDelayMs:3e3});return bE.parse(n)}async updateMobileStepCaches(e,t){await this.sendRequest(`/${U}/mobile-cache`,{method:"PATCH",body:e,extraHeaders:t,retries:3,requestTimeoutMs:1e4,initialRetryDelayMs:3e3})}async getMobileStepCacheForTest(e,t){let n=await this.sendRequest(`/${U}/mobile-cache`,{method:"POST",body:e,extraHeaders:t,retries:10,requestTimeoutMs:3e4,initialRetryDelayMs:3e3});return EE.parse(n)}async queueTests(e){let t=await this.sendRequest(`/${U}/tests/queue`,{method:"POST",body:e,retries:3,requestTimeoutMs:1e4});return fE.parse(t)}async uploadScreenshot(e){let t=await this.sendRequest(`/${U}/screenshots`,{method:"POST",body:e,retries:3,requestTimeoutMs:5e3});return xE.parse(t)}async getAllEnvironments(){let e=await this.sendRequest(`/${U}/environments`,{method:"GET",retries:3,requestTimeoutMs:5e3});return _E.parse(e)}async acquireCacheLock(e,t){let n=await this.sendRequest(`/${U}/result-cache/lock`,{method:"POST",body:e,signal:t,retries:3,requestTimeoutMs:3e4});return jE.parse(n)}async releaseCacheLock(e){await this.sendRequest(`/${U}/result-cache/lock`,{method:"DELETE",body:{key:e},retries:3,requestTimeoutMs:5e3})}async deleteCacheResult(e){await this.sendRequest(`/${U}/result-cache/entry`,{method:"DELETE",body:e,retries:3,requestTimeoutMs:5e3})}async setCacheResult(e){await this.sendRequest(`/${U}/result-cache/entry`,{method:"PATCH",body:e,retries:3,requestTimeoutMs:5e3})}async getCacheResult(e){try{return await this.sendRequest(`/${U}/result-cache/entry`,{method:"POST",body:e,retries:3,requestTimeoutMs:5e3})}catch(t){if(t instanceof Error&&t.message.includes("404"))return null;throw t}}async queueSuiteRuns(e){let t=await this.sendRequest(`/${U}/suites/queue`,{method:"POST",body:e,retries:3,requestTimeoutMs:5e3});return PE.parse(t)}async bulkGetRunGroupStatus(e){let t={runGroupIds:e},n=await this.sendRequest(`/${U}/run-groups/status`,{method:"POST",body:t,retries:3,requestTimeoutMs:5e3});return My.array().parse(n)}async uploadProposedSteps(e,t){try{await this.sendRequest(`/${U}/test-fragments/`,{method:"POST",body:e,retries:3,requestTimeoutMs:1e4})}catch(n){t.error({err:n},"Failed to upload proposed steps")}}async reportBillableEvents(e,t){try{await this.sendRequest(`/${U}/billing/events`,{method:"POST",body:t,retries:10,requestTimeoutMs:1e4})}catch(n){e.error({err:n},"Failed to report billable event")}}async fetchTestFragment(e){let t=await this.sendRequest(`/${U}/test-fragments/${e}`,{method:"GET",retries:3,requestTimeoutMs:1e4});return IE.parse(t)}async patchTestFragment(e,t){await this.sendRequest(`/${U}/test-fragments/${e}`,{method:"PATCH",body:t,retries:3,requestTimeoutMs:1e4})}async getPastTestResults(e,t){let n=await this.sendRequest(`/${U}/results/tests/${e}`,{method:"POST",body:t,retries:3,requestTimeoutMs:1e4});return OE.parse(n)}async generateTestResultsUploadUrl(){let e=await this.sendRequest(`/${U}/results/uploads`,{method:"POST",retries:3,requestTimeoutMs:1e4});return LE.parse(e)}async startProcessingResultsUpload(e,t){let n=await this.sendRequest(`/${U}/results/uploads/${e}/process`,{method:"POST",body:t,retries:3,requestTimeoutMs:1e4});return NE.parse(n)}async fetchIconKnowledgeBase(e){try{let t=await this.sendRequest(`/${U}/knowledge-base/icons`,{method:"GET",retries:3,requestTimeoutMs:5e3});return KE.parse(t)}catch(t){return e.error({err:t},"Failed to fetch icon knowledge base"),null}}async saveNewIcons(e,t){try{await this.sendRequest(`/${U}/knowledge-base/icons`,{method:"POST",body:e,retries:3,requestTimeoutMs:5e3})}catch(n){t.error({err:n},"Failed to save new icons to icon knowledge base")}}async getMergeBaseCommitFromGithub(e,t,n,o){let i=new URLSearchParams;i.set("base",n),i.set("head",o);let a=await this.sendRequest(`/${U}/git/github/${e}/${t}/merge-base-commit?${i.toString()}`,{method:"GET",retries:3,requestTimeoutMs:1e4});return is.parse(a)}async getCommitFromGithub(e,t,n){let o=await this.sendRequest(`/${U}/git/github/${e}/${t}/commits/${n}`,{method:"GET",retries:3,requestTimeoutMs:1e4});return is.parse(o)}async getMergedBranchFromGithub(e,t,n,o){let i=encodeURIComponent(n),a=await this.sendRequest(`/${U}/git/github/${e}/${t}/${i}/${o}/merged-branch`,{method:"GET",retries:3,requestTimeoutMs:1e4});return lp.parse(a)}async getMergeBaseCommitFromGitlab(e,t,n){let o=new URLSearchParams;o.set("base",t),o.set("head",n);let i=encodeURIComponent(e),a=await this.sendRequest(`/${U}/git/gitlab/${i}/merge-base-commit?${o.toString()}`,{method:"GET",retries:3,requestTimeoutMs:5e3});return is.parse(a)}async getCommitFromGitlab(e,t){let n=encodeURIComponent(e),o=await this.sendRequest(`/${U}/git/gitlab/${n}/commits/${t}`,{method:"GET",retries:3,requestTimeoutMs:1e4});return is.parse(o)}async getMergedBranchFromGitlab(e,t,n){let o=encodeURIComponent(t),i=encodeURIComponent(e),a=await this.sendRequest(`/${U}/git/gitlab/${i}/${o}/${n}/merged-branch`,{method:"GET",retries:3,requestTimeoutMs:1e4});return lp.parse(a)}async getAgentConfig(){let e=await this.sendRequest(`/${U}/web-agent/agent-config`,{method:"GET",retries:3,requestTimeoutMs:5e3});return _h.record(_h.string(),_h.string()).parse(e)}async getQuarantinedTests(){let e=await this.sendRequest(`/${U}/quarantine`,{method:"GET"});return DE.parse(e)}async quarantineTest(e,t,n){await this.sendRequest(`/${U}/quarantine`,{method:"POST",body:{testId:e.id,testName:e.name,reason:t,...n??{}},retries:3,requestTimeoutMs:1e4})}async unquarantineTest(e,t,n){await this.sendRequest(`/${U}/quarantine/${e.id}`,{method:"DELETE",body:{testName:e.name,reason:t,...n??{}},retries:3,requestTimeoutMs:1e4})}async createAndroidEmulator(e){let t=await this.sendRequest(`/${U}/limbar/android`,{method:"POST",retries:3,body:e,requestTimeoutMs:9e4,initialRetryDelayMs:5e3,maxRetryDelayMs:15e3});return kE.parse(t)}async extendAndroidEmulatorTtl(e){try{await this.sendRequest(`/${U}/limbar/android/${e}/keepalive`,{method:"POST",retries:3,requestTimeoutMs:15e3})}catch{}}async generateAndroidAssetUrls({channel:e,tag:t,md5:n}){let o={channel:e,tag:t,md5:n},i=await this.sendRequest(`/${U}/limbar/android/upload-url`,{method:"POST",retries:3,body:o,requestTimeoutMs:15e3,logResponse:!0});return FE.parse(i)}async deleteAndroidEmulator(e){await this.sendRequest(`/${U}/limbar/android/${e}`,{method:"DELETE",retries:3,requestTimeoutMs:3e4})}async getAndroidAssets(){let e=await this.sendRequest(`/${U}/limbar/assets`,{method:"GET",retries:3,requestTimeoutMs:1e4});return BE.parse(e)}async deleteAndroidAsset(e,t){await this.sendRequest(`/${U}/limbar/assets/${e}/${t}`,{method:"DELETE",retries:3,requestTimeoutMs:1e4})}async createIosEmulator(e){let t=await this.sendRequest(`/${U}/limbar/ios`,{method:"POST",retries:3,body:e,requestTimeoutMs:9e4,initialRetryDelayMs:5e3,maxRetryDelayMs:15e3});return UE.parse(t)}async extendIosEmulatorTtl(e){try{await this.sendRequest(`/${U}/limbar/ios/${e}/keepalive`,{method:"POST",retries:3,requestTimeoutMs:15e3})}catch{}}async deleteIosEmulator(e){await this.sendRequest(`/${U}/limbar/ios/${e}`,{method:"DELETE",retries:3,requestTimeoutMs:3e4})}async generateMobileLogcatUploadUrl(e){let t=await this.sendRequest(`/${U}/logcat/mobile/upload`,{method:"POST",body:e,retries:3,requestTimeoutMs:1e4});return Sb.parse(t)}};async function Ph(r){let e=process.versions.node,t=parseInt(e.split(".")[0]);(isNaN(t)||t<18)&&(C.error(`Node.js version 20 or higher is required to run the CLI. Detected: ${process.versions.node}.`),process.exit(1)),C.debug(`Identified node version ${e}`);let n=await r.client.getAuthInfo();return C.debug("Got auth info from API"),n}var dd=class{apiClient;constructor(e){this.apiClient=e}async reportBillableEvents(e,t){await this.apiClient.reportBillableEvents(e,t)}};var ta=class extends nn{generator;constructor(e,t){super(e),this.generator=t}async runTemplateMatching(e,t={}){let n=await this.sendRequest(`/${U}/web-agent/template-matching`,{method:"POST",body:e,signal:t?.signal});return Tf.parse(n)}async constructIframeRegex(e,t={}){return this.generator.getIframeRegex(e,{abortSignal:t.signal})}};var ra=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 fG,en as SG}from"@faker-js/faker";var na="v1",oa=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 fG({locale:SG}),this.fakerInstance.seed(e.fakerSeed))}async sendAiGenerate(e){let t=typeof e=="string"?{input:e}:e;return this.httpClient.sendRequest(`/${na}/tools/ai/generate`,{method:"POST",body:t}).catch(n=>{throw n instanceof Ir?new Error(n.rawError):new Error(`Failed to send AI generation: ${n.message}`)})}async sendSms(e){return this.httpClient.sendRequest(`/${na}/tools/sms/send`,{method:"POST",body:e}).then(()=>{}).catch(t=>{throw t instanceof Ir?new Error(t.rawError):new Error(`Failed to send sms: ${t.message}`)})}async fetchLatestSms(e){return this.httpClient.sendRequest(`/${na}/tools/sms/fetchLatest`,{method:"POST",body:e}).catch(t=>{throw t instanceof Ir?new Error(t.rawError):t})}async sendEmail(e){return this.httpClient.sendRequest(`/${na}/tools/email/send`,{method:"POST",body:e}).then(()=>{}).catch(t=>{throw t instanceof Ir?new Error(t.rawError):new Error(`Failed to send email: ${t.message}`)})}async fetchAllEmails(e){return this.httpClient.sendRequest(`/${na}/tools/email/fetchAll`,{method:"POST",body:e}).catch(t=>{throw t instanceof Ir?new Error(t.rawError):new Error(`Failed to fetch all emails: ${t.message}`)})}async fetchLatestEmail(e){return this.httpClient.sendRequest(`/${na}/tools/email/fetchLatest`,{method:"POST",body:e}).catch(t=>{throw t instanceof Ir?new Error(t.rawError):new Error(`Failed to fetch latest emails: ${t.message}`)})}};function pM(r,e,t){return fetch(r,{method:"PUT",body:t,headers:{"Content-Type":e}})}var md=class{constructor(e){this.client=e}async uploadResultsArchive(e,t){let{uploadUrl:n,id:o}=await this.client.generateTestResultsUploadUrl(),i=await pM(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 ia=class extends nn{constructor(e){super(e)}async getMobileElementLocation(e,t){let n={...e,disableCache:t.disableCache,useMemory:t.useMemory,agentConfigVersion:t.agentConfigVersion,loggerTags:t.loggerTags},o=await this.sendRequest(`/${U}/mobile-agent/locate-element`,{method:"POST",body:n,signal:t.abortSignal});return Eb.parse(o)}async evaluateMobileAssertion(e,t){let n={...e,disableCache:t.disableCache,useMemory:t.useMemory,agentConfigVersion:t.agentConfigVersion,loggerTags:t.loggerTags},o=await this.sendRequest(`/${U}/mobile-agent/assertion`,{method:"POST",body:n,signal:t.abortSignal});return Ab.parse(o)}async getMobileFailureRecoveryPlan(e,t){let n=await this.sendRequest(`/${U}/mobile-agent/failure-recovery-plan`,{method:"POST",body:{...e,loggerTags:t.loggerTags},signal:t.abortSignal});return Rb.parse(n)}getVercelAnthropicModelFactory({loggerTags:e,sessionId:t}){return ud({baseUrl:this.baseUrl,apiKey:this.apiKey,sessionId:t,loggerTags:e})}};function pd({orgId:r,client:e,gitMetadata:t,regenerateCache:n,alwaysSaveCache:o,noCache:i}){return i?new gc:new Ih(r,e,t,{alwaysSaveCache:o,regenerateCache:n})}var Ih=class{constructor(e,t,n,o){this.orgId=e;this.client=t;let{regenerateCache:i,alwaysSaveCache:a}=o,{gitBranchName:s,gitProtectedBranches:c}=n;this.cacheHeaders=ip(n),this.readCaches=!i;let l=s&&c.includes(s);a||!l?this.writeCaches=!0:this.writeCaches=!1}cacheHeaders;readCaches;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.warn({err:o},"Failed to save mobile step cache entries, continuing...")}}async resolveEntries(e){if(!this.readCaches){e.logger.debug("Skipping cache resolution because of regenerate flag");return}let{steps:t}=e.stepLists,n=await this.client.getMobileStepCacheForTest({testId:e.testId},this.cacheHeaders);if(!this.writeCaches){e.logger.info("Skipping mobile cache last used at update because branch is protected");return}for(let i of[t])i&&Cg({steps:i,stepCacheEntries:n,logger:e.logger});let{cachesToSave:o}=await Xr({steps:t,cacheCreationParams:{testId:e.testId,orgId:this.orgId}});this.client.updateMobileStepCaches({entries:o,testId:e.testId},this.cacheHeaders)}};async function gM({socket:r,logger:e,globalStateManager:t,authorization:n}){let o=r.id,i=t.getSession(o);i&&n&&i.logFilePath&&yG({testId:i.metadata.testId,sessionId:o,logFilePath:i.logFilePath,authorization:n,logger:e}),await t.removeSession(o,e)}async function yG({testId:r,sessionId:e,logFilePath:t,authorization:n,logger:o}){try{let i;try{i=await gd.stat(t)}catch{o.debug({logFilePath:t},"No logcat file found to upload");return}if(i.size===0){o.debug({logFilePath:t},"Logcat file is empty, skipping upload"),await gd.unlink(t);return}let a=new Yt(n),{uploadUrl:s}=await a.generateMobileLogcatUploadUrl({testId:r,sessionId:e}),c=await gd.readFile(t),l=await fetch(s,{headers:{"Content-Length":c.length.toString(),"Content-Type":"text/plain"},method:"PUT",body:c});if(l.status!==200)throw new Error(`Failed to upload logcat: ${l.status} ${await l.text()}`);o.info({testId:r,sessionId:e},"Logcat file uploaded successfully")}catch(i){o.warn({err:i,testId:r,sessionId:e},"Failed to upload logcat file")}finally{try{await gd.unlink(t)}catch(i){o.warn({err:i,logFilePath:t},"Failed to delete temp logcat file")}}}var bG=({socket:r,globalStateManager:e})=>async()=>{let t=e.getSession(r.id);if(!t)throw new Error("No active Android session found");t.controller.abort()},hM={event:"cancel",createHandler:bG};var EG=({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})}},fM={event:"fetchA11yTree",createHandler:EG};import{diff as GG}from"deep-object-diff";import{cloneDeep as VG}from"lodash-es";var TG=1e4,vG=5e3;function SM(r,e,t,n){let o=0;async function i(){try{let s=await B(r.driver.execute("mobile: shell",{command:"echo",args:["ping"]}).catch(c=>{throw c}),{milliseconds:vG});if(typeof s=="string"&&s.trim()==="ping")o>0&&(e.info("Driver heartbeat restored"),n?.()),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"),t?.())}}let a=setInterval(()=>{i()},TG);return i(),a}async function yM(r){let e=Date.now(),t=r.fixtures.controller;try{return await AG(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 AG({moduleParams:r,...e}){let t=Date.now(),{step:n,stepTracer:o,executeMobileStepList:i}=r,a=await wG({step:n,params:e}),s={};Object.entries(a).forEach(([m,p])=>{s[m]=JSON.stringify(p)});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(),vC({result:c,...TC(d)}),c}async function wG({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 Jr({orgId:e.inputs.orgId,code:a,fragment:!0,logger:n,context:o.context,localTools:o.localCodeEvalTools})}return t}import{randomUUID as bM}from"crypto";import{diff as CG}from"deep-object-diff";import{cloneDeep as RG}from"lodash-es";async function EM({fixtures:r,step:e,inputs:t,stepTracer:n}){let o=Date.now(),{logger:i,controller:a}=r,s;if(!t.interactive)try{s=await a.getScreenshotBase64()}catch(u){i.warn({err:u},"Failed to take before screenshot")}let c="cache"in e.command?RG(e.command.cache??{}):{},l={...e,status:"SUCCESS",startTime:o,endTime:Date.now()};try{let u=await a.executeCommand({command:e.command});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(!t.interactive){try{let m=bM(),p=await a.getScreenshotBase64();l.afterSnapshot=m,n.attachAfterScreenshot({logger:i,snapshotId:m,screenshot:Buffer.from(p,"base64")})}catch(m){i.warn({err:m},"Failed to take after screenshot")}if(s){let m=bM();l.beforeSnapshot=m,n.attachBeforeScreenshot({logger:i,snapshotId:m,screenshot:Buffer.from(s,"base64")})}}let u="cache"in e.command?e.command.cache??{}:{},d=CG(c,u);d&&Object.keys(d).length>0&&i.info({diffs:Ti(d)},"Updated cache")}return l}import{streamText as UG}from"ai";import{randomUUID as FG}from"crypto";var hd=class{controller;logger;rootStep;subStepIndex=0;callbacks;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}recordGenericToolCall(e){this.callbacks.onAiActionEvent?.({type:"GENERIC_TOOL_CALLED",toolName:e,rootStep:this.rootStep})}};import{hasToolCall as DG,stepCountIs as kG}from"ai";var Oh="get_emulator_state",fd="finish";import TM from"dedent";var MG=TM`
4368
4368
  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.
4369
4369
  `,vM=r=>TM`
4370
4370
  <background>
@@ -4402,7 +4402,7 @@ ${n.map(o=>o.configFilePath)}`);if(n.length===0)throw new Error("No valid Moment
4402
4402
  `)){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 OV(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 GM("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 GM("gh",o,{timeout:5e3}),a=i?.toString().trim();if(a)return a}catch{}}}async function LV(r,e,t){let n=e?.includes("github.com"),o=e?.includes("gitlab.com");try{if(n)return OV(r,e,t);if(o)return}catch{}}function wd(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 ke(r,e){try{return(await e).trim()}catch(t){if(t instanceof Error&&t.message.includes("not a git repository"))return;r.error({err:t},"Failed to run git command");return}}function NV(){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 DV(r){let[e,t,n]=await Promise.all([ke(r,De.show(["--no-patch","--format=%ci"])),ke(r,De.show(["-s","--pretty=%B"])),ke(r,De.show(["-s","--pretty=%an"]))]),o=process.env.GITHUB_SERVER_URL&&process.env.GITHUB_REPOSITORY?`${process.env.GITHUB_SERVER_URL}/${process.env.GITHUB_REPOSITORY}`:void 0;return{ciProvider:"GithubActions",gitCommitSha:process.env.GITHUB_SHA,gitCommitShaShort:process.env.GITHUB_SHA?.slice(0,6),gitCommitTimestamp:e?new Date(e):void 0,gitBranchName:process.env.GITHUB_HEAD_REF||process.env.GITHUB_REF_NAME,gitOriginUrl:o,gitCommitMessage:t,gitCommitAuthorName:n,githubRepository:process.env.GITHUB_REPOSITORY,pipelineId:process.env.GITHUB_RUN_ID}}async function kV(r){let[e,t,n]=await Promise.all([ke(r,De.listRemote(["--get-url","origin"])),ke(r,De.show(["-s","--pretty=%B"])),ke(r,De.show(["-s","--pretty=%an"]))]);return{ciProvider:"GitlabCI",gitCommitSha:process.env.CI_COMMIT_SHA,gitCommitShaShort:process.env.CI_COMMIT_SHORT_SHA,gitCommitTimestamp:process.env.CI_COMMIT_TIMESTAMP?new Date(process.env.CI_COMMIT_TIMESTAMP):void 0,gitBranchName:process.env.CI_COMMIT_BRANCH||process.env.CI_COMMIT_REF_NAME,gitOriginUrl:e,gitCommitMessage:t,gitCommitAuthorName:n,gitlabProjectPath:process.env.CI_PROJECT_PATH,pipelineId:`${process.env.CI_PIPELINE_ID}:${process.env.CI_JOB_ID}`}}async function UV(r){let[e,t,n,o]=await Promise.all([ke(r,De.show(["--no-patch","--format=%ci"])),ke(r,De.listRemote(["--get-url","origin"])),ke(r,De.show(["-s","--pretty=%B"])),ke(r,De.show(["-s","--pretty=%an"]))]),i=process.env.CIRCLE_REPOSITORY_URL??t,a=i?.includes("github.com"),s=i?.includes("gitlab.com"),c=i?wd(i):void 0;return{ciProvider:"CircleCI",gitCommitSha:process.env.CIRCLE_SHA1,gitCommitShaShort:process.env.CIRCLE_SHA1?.slice(0,6),gitCommitTimestamp:e?new Date(e):void 0,gitBranchName:process.env.CIRCLE_BRANCH,gitOriginUrl:i,gitCommitMessage:n,gitCommitAuthorName:o,githubRepository:a?c:void 0,gitlabProjectPath:s?c:void 0,pipelineId:process.env.CIRCLE_PIPELINE_ID}}async function FV(r){let[e,t,n]=await Promise.all([ke(r,De.show(["--no-patch","--format=%ci"])),ke(r,De.show(["-s","--pretty=%B"])),ke(r,De.show(["-s","--pretty=%an"]))]),o=process.env.BUILDKITE_REPO,i=o?.includes("github.com"),a=o?.includes("gitlab.com"),s=o?wd(o):void 0;return{ciProvider:"Buildkite",gitCommitSha:process.env.BUILDKITE_COMMIT,gitCommitShaShort:process.env.BUILDKITE_COMMIT?.slice(0,6),gitCommitTimestamp:e?new Date(e):void 0,gitBranchName:process.env.BUILDKITE_BRANCH,gitOriginUrl:o,gitCommitMessage:t,gitCommitAuthorName:n,githubRepository:i?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 BV(r){let[e,t,n]=await Promise.all([ke(r,De.show(["--no-patch","--format=%ci"])),ke(r,De.show(["-s","--pretty=%B"])),ke(r,De.show(["-s","--pretty=%an"]))]),o=process.env["Build.Repository.Uri"],i=o?.includes("github.com"),a=o?.includes("gitlab.com"),s=o?wd(o):void 0;return{ciProvider:"AzureDevOps",gitCommitSha:process.env["Build.SourceVersion"],gitCommitShaShort:process.env["Build.SourceVersion"]?.slice(0,6),gitCommitTimestamp:e?new Date(e):void 0,gitBranchName:process.env["System.PullRequest.SourceBranch"]??process.env["Build.SourceBranchName"],gitOriginUrl:o,gitCommitMessage:t,gitCommitAuthorName:n,githubRepository:i?s:void 0,gitlabProjectPath:a?s:void 0,pipelineId:`${process.env["System.JobId"]}:${process.env["System.JobAttempt"]}`}}async function zV(r,e){let[t,n,o,i,a,s,c,l,u]=await Promise.all([ke(r,De.revparse(["HEAD"])),ke(r,De.revparse(["--short","HEAD"])),ke(r,De.revparse(["--abbrev-ref","HEAD"])),ke(r,De.listRemote(["--get-url","origin"])),ke(r,De.show(["--no-patch","--format=%ci"])),ke(r,De.show(["-s","--pretty=%B"])),ke(r,De.show(["-s","--pretty=%an"])),e?ke(r,De.raw(["merge-base","--fork-point",e])):Promise.resolve(void 0),IV(r)]),d=l?await ke(r,De.show(["--no-patch","--format=%ci",l])):void 0,m=i?.includes("github.com"),p=i?.includes("gitlab.com"),g=i?wd(i):void 0,h=u["user.email"]||void 0,f=u["user.name"]||void 0,E=u["user.username"]||void 0,b=await LV(r,i,u)??E??void 0;return{ciProvider:"none",gitCommitSha:t,gitCommitShaShort:n,gitBranchName:o,gitOriginUrl:i,gitCommitTimestamp:a?new Date(a):void 0,gitCommitMessage:s,gitCommitAuthorName:c,gitLocalUsername:b,gitLocalEmail:h,gitLocalName:f,lastCommitOnMainSha:l,lastCommitOnMainTimestamp:d?new Date(d):void 0,githubRepository:m?g:void 0,gitlabProjectPath:p?g:void 0,pipelineId:void 0}}async function HV(){let r=process.env._HEAD_REPO_URL;return{ciProvider:"GCPCloudBuild",gitCommitSha:process.env.COMMIT_SHA,gitCommitShaShort:process.env.COMMIT_SHA?.slice(0,6),gitBranchName:process.env.BRANCH_NAME,gitOriginUrl:r?process.env._HEAD_REPO_URL:void 0,gitCommitTimestamp:void 0,gitCommitMessage:void 0,gitCommitAuthorName:void 0,githubRepository:r?process.env.REPO_FULL_NAME:void 0,pipelineId:`${process.env.PROJECT_ID}:${process.env.BUILD_ID}`}}async function GV(r){let e=r.config.gitProtectedBranches??[];return r.config.gitMainBranch&&e.push(r.config.gitMainBranch),{gitMainBranch:r.config.gitMainBranch,gitProtectedBranches:e}}async function Js(r,e){let t=NV();if(!t)return zV(r,e);switch(t){case"GithubActions":return DV(r);case"GitlabCI":return kV(r);case"CircleCI":return UV(r);case"Buildkite":return FV(r);case"AzureDevOps":return BV(r);case"GCPCloudBuild":return HV()}}async function VV(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 WV(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 jV(r,e,t){try{if(t.githubRepository){let[n,o]=t.githubRepository.split("/");return await WV(r,e,n,o,t)}else if(t.gitlabProjectPath)return await VV(r,e,t.gitlabProjectPath,t)}catch(n){r.warn({err:n},"Failed to get remote git metadata")}return t}async function ca(r,e,t){let n=await GV(t),o=await Js(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 jV(r,e,i);return{...n,...o,...a}}import{diff as VM}from"deep-object-diff";import to from"fs";import{cloneDeep as $V}from"lodash-es";import Cd from"path";import{v4 as qV}from"uuid";import Qs from"yaml";function WM(r,e){let t=`${Br(e)}.module.yaml`,n=Cd.join(Cd.dirname(r),t);if(to.existsSync(n))throw new Error(`A conflicting file already exists at the following path: ${n}`);return to.renameSync(r,n),n}function jM({content:r,schemaVersion:e,momenticFiles:t,project:n,forceSaveOnNoDiffs:o}){let i=t.mobileModules[r.moduleId]?.fullFilePath,a=t.mobileModules[r.moduleId]?.name;if(!i||!to.existsSync(i))throw new Error(`Tried to update mobile module ${r.moduleId} that could not be found on disk`);let s=to.readFileSync(i,"utf-8"),c=Qs.parse(s),l={...c,...r,schemaVersion:e},u=ko({fileType:Oe.MOBILE_MODULE,...Za.parse(l),steps:Ht.array().parse(r.steps)}),d=!!r.name&&r.name!==a,m=VM(u,c);if(m&&Object.keys(m).length===0&&!o&&!d)return;let p=Qs.stringify(u);to.writeFileSync(i,p,"utf-8");let g;d&&(g=WM(i,r.name)),on(g||i,n.config)}function $M({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=Zs(i,o),s={...a,...e},c=ko({fileType:Oe.MOBILE_MODULE,...Xl.parse(s)}),l=VM(c,a);if(l&&Object.keys(l).length===0)return;let u=Qs.stringify(c);to.writeFileSync(i,u,"utf-8");let d;e.name&&(d=WM(i,e.name)),on(d||i,n.config)}async function qM({name:r,description:e,enabled:t,steps:n,folder:o,project:i}){let a=Br(r),s=Cd.join(o,`${a}.module.yaml`),c=qV(),{stepsToSave:l}=await Xr({steps:n}),u={schemaVersion:On,moduleId:c,description:e,enabled:t},d={fileType:Oe.MOBILE_MODULE,...u,steps:l},m=Qs.stringify(pb.parse(d));return to.writeFileSync(s,m,"utf-8"),on(s,i.config),{moduleId:c,name:r,description:e||void 0,steps:n}}function Zs(r,e){let t=to.readFileSync(r,"utf-8"),n=Qs.parse(t);try{return{...Xl.parse(n),name:Cd.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 Hh(r,e,t,n){let o=Zs(r.fullFilePath,t),{resolvedSteps:i}=await yu({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 Zs(c,t)},logger:t,metadata:{id:o.moduleId,schemaVersion:o.schemaVersion}}),a={...o,name:r.name,description:o.description||void 0,steps:i};return n&&(n[r.id]=$V(a)),a}async function KM(r,e){let t={};return await Promise.all(Object.values(r.mobileModules).map(async n=>{await Hh(n,r,e,t)})),Array.from(Object.values(t))}import{randomUUID as KV}from"crypto";import br from"fs";import ro from"path";import da from"yaml";import ua from"zod";function YM({name:r,description:e="",steps:t=[],settings:n={},folder:o}){let a=`${Br(r)}.test.yaml`,s=ro.join(o,a);if(br.existsSync(s))throw new Error(`A test named '${r}' already exists at path '${s}'. Choose a different name.`);let c={fileType:Oe.MOBILE_TEST,id:KV(),description:e,schemaVersion:ho,settings:n,steps:t},l=da.stringify(c);return br.writeFileSync(s,l,"utf-8"),{fullPath:s,testId:c.id}}function YV(r){if(!br.existsSync(r))throw new Error(`Test file not found: ${r}`);let e=br.readFileSync(r,"utf-8").replace(/\r\n|\r/g,`
4403
4403
  `),t=da.parse(e);if(!t.steps||!Array.isArray(t.steps))throw new Error(`Test ${r} is missing steps`);return t}async function Rd(r,e,t){let n=YV(r),o;try{o=wr.parse(n)}catch(s){throw new Error(`Mobile test ${r} is missing metadata or has invalid metadata: ${s}`)}let{resolvedStepLists:i}=await pC({rawStepLists:{steps:n.steps,beforeSteps:n.beforeSteps,afterSteps:n.afterSteps},logger:e,testMetadata:o,onFetchModule:async s=>{let c=t.mobileModules[s]?.fullFilePath;if(!c)throw new Error(`Mobile module ${s} not found`);return Zs(c,e)}});return{...o,steps:i.steps}}async function XM({filePath:r,steps:e,settings:t,folder:n,project:o,momenticFiles:i,schemaVersion:a}){let s=ro.isAbsolute(r)?r:ro.join(n,r);if(!br.existsSync(s))throw new Error(`Test file not found: ${s}`);let c=br.readFileSync(s,"utf-8").replace(/\r\n|\r/g,`
4404
4404
  `),l=da.parse(c),u=Jl.extend({steps:ua.record(ua.string(),ua.unknown()).array()}).parse({...l,schemaVersion:a});if(u.fileType!==Oe.MOBILE_TEST)throw new Error(`File at '${s}' is not a mobile test (fileType=${u.fileType}).`);let d;e&&(d=await Xr({steps:e}));let m={...u,...d?.stepsToSave!==void 0?{steps:d.stepsToSave}:{steps:u.steps}};t&&(m.settings=t);let p=da.stringify(m);for(let g of d?.moduleUpdates??[])jM({content:g,schemaVersion:ho,momenticFiles:i,project:o});br.writeFileSync(s,p,"utf-8"),on(s,o.config)}function JM(r,e,t){let n=ro.join(t.rootDir,r);if(!br.existsSync(n))throw new Error(`Test not found at path '${r}' in project '${t.rootDir}'`);let o=br.readFileSync(n,"utf-8").replace(/\r\n|\r/g,`
4405
- `),i=da.parse(o),a=Jl.extend({steps:ua.record(ua.string(),ua.unknown()).array()}).parse(i),s=ro.basename(r,".test.yaml"),c,l;if(e.name&&e.name!==s){let m=`${Br(e.name)}.test.yaml`;if(c=ro.join(ro.dirname(r),m),l=ro.join(t.rootDir,c),br.existsSync(l))throw new Error(`Test with name '${e.name}' already exists at path '${l}'`)}let u={...a,...e};if(delete u.name,u.fileType!==Oe.MOBILE_TEST)throw new Error(`File at '${n}' is not a mobile test (fileType=${u.fileType}).`);let d=da.stringify(u);return br.writeFileSync(n,d,"utf-8"),l&&l!==n?(br.renameSync(n,l),on(l,t.config)):on(n,t.config),{newRelativeTestPath:c}}import{randomUUID as XV}from"crypto";import no from"fs";import ma from"path";var QM=new Set([".DS_Store","__MACOSX"]),ZM={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 JV(r,e,t){if(ZM[t]){let i=ZM[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 Gh=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 e_(r,e){try{let t=ma.join(e,"metadata.json");return hc.parse(JSON.parse(no.readFileSync(t,"utf-8")))}catch{throw new Gh(r,e)}}function t_(r,e,t){let n=XV(),o=r.child({runGroupId:n});no.rmSync(e,{recursive:!0,force:!0});let i=no.readdirSync(t).filter(c=>!QM.has(c)).map(c=>ma.join(t,c));if(i.length===0)throw new Error(`No run groups found in results path: ${t}`);no.mkdirSync(e,{recursive:!0});let a={...e_(t,i[0]),id:n};for(let c of i){let l=ma.join(c,"runs");if(!no.existsSync(l))continue;let u=e_(t,c);o.info({oldRunGroupId:u.id},"Merging run groups");for(let m in u){if(m==="id")continue;let p=m;a[p]=JV(a,u,p)}let d=no.readdirSync(l);for(let m of d){if(QM.has(m))continue;let p=ma.join(l,m),g=ma.join(e,"runs",m);no.cpSync(p,g,{recursive:!0})}}let s=ma.join(e,"metadata.json");no.writeFileSync(s,JSON.stringify(a,null,2))}import r_ from"adm-zip";import Vh from"fs";import xd from"path";function QV(r){let e=new r_,t=xd.join(r,"metadata.json"),n=hc.parse(JSON.parse(Vh.readFileSync(t,"utf-8")));e.addLocalFile(t);for(let o of Vh.readdirSync(xd.join(r,"runs"))){if(!o.endsWith(".zip"))continue;let i=o.replace(/\.zip$/,""),a=new r_(xd.join(r,"runs",o));for(let s of a.getEntries())s.isDirectory||e.addFile(xd.join("runs",i,s.entryName),s.getData())}return{runGroupId:n.id,buffer:e.toBuffer()}}async function Md(r){let{client:e,consoleLogger:t,resultsPath:n}=r;if(!Vh.existsSync(n)){t.warn("Results path does not exist, skipping upload.");return}let o=new md(e);try{let{runGroupId:i,buffer:a}=QV(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 ZV from"adm-zip";import vt from"fs";import Jt from"path";var el=class r{constructor(e){this.filePath=e;vt.rmSync(this.filePath,{recursive:!0,force:!0}),vt.mkdirSync(this.filePath,{recursive:!0})}cd(e){return new r(Jt.join(this.filePath,e))}cwd(){return this.filePath}mkdir(e){vt.mkdirSync(Jt.join(this.filePath,e),{recursive:!0})}readFile(e){let t=Jt.join(this.filePath,e);if(vt.existsSync(t))return vt.readFileSync(t)}storeFile(e){let{name:t,contents:n}=e,o=Jt.join(this.filePath,t);try{vt.writeFileSync(o,n)}catch{}}createFileStream(e){let t=Jt.join(this.filePath,e);return vt.createWriteStream(t)}createRunArchive(e){return new Wh(Jt.join(this.filePath,"runs"),e)}},Wh=class{constructor(e,t){this.filePath=e;this.tempPath=Jt.join(e,`temp-storage-${t}`),this.finalPath=Jt.join(e,`${t}.zip`),vt.rmSync(this.tempPath,{recursive:!0,force:!0}),vt.rmSync(this.finalPath,{recursive:!0,force:!0}),vt.mkdirSync(this.tempPath,{recursive:!0})}tempPath;finalPath;readFile(e){let t=Jt.join(this.tempPath,e);if(vt.existsSync(t))return vt.readFileSync(t)}mkdir(e){vt.mkdirSync(Jt.join(this.tempPath,e),{recursive:!0})}cd(e){return new el(Jt.join(this.tempPath,e))}cwd(){return this.tempPath}storeFile(e){let{name:t,contents:n}=e,o=Jt.join(this.tempPath,t);vt.writeFileSync(o,n)}createFileStream(e){let t=Jt.join(this.tempPath,e);return vt.createWriteStream(t)}close(){let e=new ZV;e.addLocalFolder(this.tempPath,void 0,n=>n!==".DS_Store");let t=e.toBuffer();vt.writeFileSync(this.finalPath,t),vt.rmSync(this.tempPath,{recursive:!0,force:!0})}};import rGe from"adm-zip";import zd from"fs";import T_ from"body-parser";import vW from"cors";import AW from"dedent";import{Router as nW}from"express";import zt from"fs";import{globSync as oW}from"glob";import St from"path";import _d from"fs";import eW from"path";var tW=new Iu(30,60*1e3),Kh="https://api.momentic.ai",$h,o_=r=>{Kh=r},Yh=()=>Kh,tl=()=>$h;var pa,qh,n_,i_=async r=>{if($h&&pa&&n_)return pa;let e=new Yt({baseUrl:Kh,apiKey:r,logger:C});$h=e;try{let t=await e.getAuthInfo();return pa=t.orgId,qh=t.userId,n_=r,pa}catch(t){throw new Error(`Error checking API key against server: ${t}`)}},ga=()=>{if(!pa)throw new Error("Your organization ID is invalid.");return pa},Pd=()=>{if(!qh)throw new Error("Your user ID is invalid.");return qh};var Xh,jh,a_=(r,e)=>{Xh=r,jh?.abort(),jh=new AbortController;let t=jh.signal,n=[r.configFilePath];r.config.environments?.forEach(o=>{if(!o.envFile)return;let i=eW.resolve(r.rootDir,o.envFile);try{if(_d.lstatSync(i).isSymbolicLink())return;_d.existsSync(i)&&n.push(i)}catch(a){C.warn({err:a},`Failed to check if env file ${i} exists`)}});try{rW({filesToWatch:n,revalidator:e,signal:t,project:r})}catch(o){C.error({err:o},"Failed to start config file watchers")}},Ie=()=>Xh;function rW({filesToWatch:r,revalidator:e,signal:t,project:n}){C.debug("Starting watch on the following files:"),r.forEach(o=>{C.debug(`- ${o}`)}),r.forEach(o=>{let i=async(s,c)=>{s.mtime.getTime()!==c.mtime.getTime()&&(tW.increment("setLocalProject")&&C.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.`),Xh=await Promise.resolve(e(n.configFilePath)))};_d.watchFile(o,{persistent:!1},i);let a=()=>{_d.unwatchFile(o,i),t.removeEventListener("abort",a)};t.addEventListener("abort",a),process.once("SIGUSR2",()=>{a(),process.kill(process.pid,"SIGUSR2")})})}function Me(r){return function(...e){let t=e[e.length-1],n=r(...e);Promise.resolve(n).catch(t)}}var nl=nW();function rl(r){let e=Ie(),t=St.dirname(e.configFilePath);return St.join(t,...r)}function iW(r){let e=Ie(),t=St.dirname(e.configFilePath),n=St.relative(t,r);return n?n.split(St.sep):[]}function aW(r,e){let t=zt.statSync(r),n=iW(r);return Qm.parse({name:e,absolutePath:r,relativePath:n.join(St.sep),pathSegments:n,isDirectory:t.isDirectory(),size:t.size,createdAt:t.birthtime,modifiedAt:t.mtime,accessedAt:t.atime})}nl.post("/",Me(async(r,e,t)=>{let n;try{n=Vb.parse(r.body).pathSegments}catch(d){e.status(400).json({error:`Failed to parse folder read body: ${d}`});return}let o=rl(n);if(!zt.existsSync(o)){e.status(404).json({error:`Path not found: ${n.join(St.sep)}`});return}if(!zt.statSync(o).isDirectory()){e.status(400).json({error:`Path is not a directory: ${n.join(St.sep)}`});return}let a=Ie(),s=Array.from(a.config.exclude??[]).concat(sc),l=oW("*",{absolute:!1,cwd:o,ignore:s,dotRelative:!1,maxDepth:1,nodir:!1}).map(d=>{let m=St.join(o,d);return aW(m,d)}),u={absolutePath:o,pathSegments:n,contents:l};e.status(200).json(u)}));nl.put("/",Me(async(r,e,t)=>{let n;try{n=Wb.parse(r.body).pathSegments}catch(a){e.status(400).json({error:`Failed to parse folder create body: ${a}`});return}let o=rl(n);if(zt.existsSync(o)){e.status(200).json({success:!0,message:`Folder already exists: ${n.join(St.sep)}`,pathSegments:n});return}zt.mkdirSync(o,{recursive:!0});let i={success:!0,message:`Folder created: ${n.join(St.sep)}`,pathSegments:n};e.status(201).json(i)}));nl.patch("/",Me(async(r,e,t)=>{let n,o;try{let l=jb.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=rl(n),a=rl(o);if(!zt.existsSync(i)){e.status(400).json({error:`Folder not found: ${n.join(St.sep)}`});return}if(zt.existsSync(a)){e.status(400).json({error:`Destination already exists: ${o.join(St.sep)}`});return}let s=St.dirname(a);zt.existsSync(s)||zt.mkdirSync(s,{recursive:!0}),zt.renameSync(i,a);let c={success:!0,message:`Folder moved from ${n.join(St.sep)} to ${o.join(St.sep)}`,pathSegments:o};e.status(200).json(c)}));nl.delete("/",Me(async(r,e,t)=>{let n,o=!0;try{let c=$b.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=rl(n);if(!zt.existsSync(i)){e.status(200).json({success:!0,message:`Folder not found: ${n.join(St.sep)}`,pathSegments:n});return}if(!zt.statSync(i).isDirectory()){e.status(400).json({error:`Path is not a directory: ${n.join(St.sep)}`});return}if(o)zt.rmSync(i,{recursive:!0,force:!0});else{if(zt.readdirSync(i).length>0){e.status(409).json({error:`Cannot delete non-empty directory without recursive flag: ${n.join("/")}`});return}zt.rmdirSync(i)}let s={success:!0,message:`Folder deleted: ${n.join("/")}`,pathSegments:n};e.status(200).json(s)}));var Jh=nl;import{Router as cW}from"express";import{hostname as sW}from"os";var lW="0.16.1",ol=_i({app:"desktop-server",hostname:sW(),disableConsoleLogs:!0}).child({cliVersion:lW});(async()=>{try{let r=await Js(ol);r.gitBranchName&&ol.addBinding("branch",r.gitBranchName)}catch{}})();var s_=cW();s_.get("/",async(r,e)=>{let t=Ie(),n=tl();if(!n){e.status(500).json({message:"API client not initialized"});return}let o=await ca(ol,n,t);e.status(200).json(o)});var Qh=s_;import wW from"events";import v_,{Router as CW}from"express";import RW from"http";import xW from"path";var Id=new Ed;import{Router as dW}from"express";import{existsSync as mW}from"fs";import pW from"path";import{hostname as uW}from"os";var Zh="0.16.1",st=_i({app:"mobile-desktop-server",hostname:uW(),disableConsoleLogs:!0}).child({cliVersion:Zh});(async()=>{try{let r=await Js(st);r.gitBranchName&&st.addBinding("branch",r.gitBranchName)}catch{}})();var ef=dW();ef.get("/",Me(async(r,e)=>{let t=tl();if(!t){e.status(500).json({message:"API client not initialized"});return}let n=await t.getAndroidAssets();e.status(200).json(n)}));ef.post("/upload-url",Me(async(r,e)=>{let t;try{t=Zb.parse(r.body)}catch(i){e.status(400).json({error:`Invalid request body: ${i}`});return}let n=tl();if(!n){e.status(500).json({error:"API client not initialized"});return}let o=pW.resolve(t.filePath);if(!mW(o)){e.status(400).json({error:`File not found: ${o}`});return}await wu({tag:t.tag,channel:t.channel,filePath:o,apiClient:n,logger:st}),e.sendStatus(204)}));var l_=ef;import{Router as fW}from"express";import{Router as gW}from"express";import c_ from"fs";import hW from"path";var il=gW();async function tf(r){return(await KM(r,st)).map(n=>{let o=r.mobileModules[n.moduleId];if(!o){C.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)}il.get("/",Me(async(r,e)=>{let t=Ie(),n=await Xt(t),o=await tf(n);e.status(200).json(o)}));il.get("/:moduleId",Me(async(r,e)=>{if(!r.params.moduleId){e.status(400).json({error:"Missing moduleId in url path."});return}let t=await Xt(Ie()),n=t.mobileModules[r.params.moduleId];if(!n){e.status(404).json({error:"Mobile module not found."});return}try{let o=await Hh(n,t,C);e.json(o)}catch(o){e.status(400).json({err:o})}}));il.patch("/:moduleId/metadata",Me(async(r,e)=>{if(!r.params.moduleId){e.status(400).json({error:"Missing moduleId in url path."});return}let t;try{t=tE.parse(r.body)}catch(i){e.status(400).json({error:`Invalid request body: ${i}`});return}let n=Ie(),o=await Xt(n);$M({moduleId:r.params.moduleId,patch:t,momenticFiles:o,logger:C,project:n}),e.status(201).json({message:"ok"})}));il.post("/",Me(async(r,e)=>{let t;try{t=rE.parse(r.body)}catch(c){e.status(400).json({error:`Invalid request body: ${c}`});return}try{So(t.name)}catch(c){e.status(400).json({error:`Invalid module name: ${c}`});return}let n=Ie(),i=(await Xt(n)).mobileModules;if(Object.values(i).find(c=>c.name===t.name)){e.status(400).json({error:`A mobile module with the name "${t.name}" already exists. Please choose a different name.`});return}let a=hW.join(n.rootDir,t.folderPath??"");if(!c_.existsSync(a)||!c_.statSync(a).isDirectory()){e.status(400).json({error:`The folder configured for mobile module creation does not exist: ${a}`});return}let s=await qM({...t,folder:a,project:n});e.status(201).json(s)}));var u_=il;var d_=fW();d_.get("/",Me(async(r,e)=>{let t=Ie(),n=await Xt(t),o=await tf(n),i=new Set;n?.tests&&Object.values(n.tests).forEach(l=>{l.labels?.forEach(u=>i.add(u))});let a=Array.from(i).sort(),s=Object.values(n.mobileTests),c={labels:a,modules:o,tests:s};e.status(200).json(c)}));var m_=d_;import{Router as SW}from"express";var Od=SW();Od.get("/",Me((r,e)=>{let t=NM(Ie(),st);e.status(200).json(t)}));Od.get("/names",Me((r,e)=>{let n=Ie().config.environments?.map(o=>o.name)??[];e.status(200).json(n)}));Od.post("/",Me((r,e)=>{let t;try{t=eE.parse(r.body)}catch(s){e.status(400).json({error:`Invalid request body: ${s}`});return}try{So(t.name)}catch(s){e.status(400).json({error:`Invalid environment name: ${s}`});return}let n=Ie();if(n.config.environments?.find(s=>s.name===t.name)){e.status(400).json({error:`An environment with the name "${t.name}" already exists. Please choose a different name.`});return}let i={...n.config,environments:[...n.config.environments??[],{name:t.name}]};n.config=i,Ad(i,n.configFilePath);let a=Ko(t.name,n,st);e.status(201).json(a)}));var p_=Od;import{Router as yW}from"express";var g_=yW();g_.get("/",(r,e)=>{e.status(200).json({userId:Pd(),orgId:ga(),cliVersion:Zh??"0.0.0"})});var h_=g_;import{Router as bW}from"express";var f_=bW();f_.get("/",Me(async(r,e)=>{let t=r.query.sessionId;if(!t){e.status(400).json({packages:[]});return}let n=Id.getSession(t);if(!n?.controller){e.status(200).json({packages:[]});return}try{let a=(await n.controller.executeRawADBCommand("shell pm list packages -3"))?.split(`
4405
+ `),i=da.parse(o),a=Jl.extend({steps:ua.record(ua.string(),ua.unknown()).array()}).parse(i),s=ro.basename(r,".test.yaml"),c,l;if(e.name&&e.name!==s){let m=`${Br(e.name)}.test.yaml`;if(c=ro.join(ro.dirname(r),m),l=ro.join(t.rootDir,c),br.existsSync(l))throw new Error(`Test with name '${e.name}' already exists at path '${l}'`)}let u={...a,...e};if(delete u.name,u.fileType!==Oe.MOBILE_TEST)throw new Error(`File at '${n}' is not a mobile test (fileType=${u.fileType}).`);let d=da.stringify(u);return br.writeFileSync(n,d,"utf-8"),l&&l!==n?(br.renameSync(n,l),on(l,t.config)):on(n,t.config),{newRelativeTestPath:c}}import{randomUUID as XV}from"crypto";import no from"fs";import ma from"path";var QM=new Set([".DS_Store","__MACOSX"]),ZM={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 JV(r,e,t){if(ZM[t]){let i=ZM[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 Gh=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 e_(r,e){try{let t=ma.join(e,"metadata.json");return hc.parse(JSON.parse(no.readFileSync(t,"utf-8")))}catch{throw new Gh(r,e)}}function t_(r,e,t){let n=XV(),o=r.child({runGroupId:n});no.rmSync(e,{recursive:!0,force:!0});let i=no.readdirSync(t).filter(c=>!QM.has(c)).map(c=>ma.join(t,c));if(i.length===0)throw new Error(`No run groups found in results path: ${t}`);no.mkdirSync(e,{recursive:!0});let a={...e_(t,i[0]),id:n};for(let c of i){let l=ma.join(c,"runs");if(!no.existsSync(l))continue;let u=e_(t,c);o.info({oldRunGroupId:u.id},"Merging run groups");for(let m in u){if(m==="id")continue;let p=m;a[p]=JV(a,u,p)}let d=no.readdirSync(l);for(let m of d){if(QM.has(m))continue;let p=ma.join(l,m),g=ma.join(e,"runs",m);no.cpSync(p,g,{recursive:!0})}}let s=ma.join(e,"metadata.json");no.writeFileSync(s,JSON.stringify(a,null,2))}import r_ from"adm-zip";import Vh from"fs";import xd from"path";function QV(r){let e=new r_,t=xd.join(r,"metadata.json"),n=hc.parse(JSON.parse(Vh.readFileSync(t,"utf-8")));e.addLocalFile(t);for(let o of Vh.readdirSync(xd.join(r,"runs"))){if(!o.endsWith(".zip"))continue;let i=o.replace(/\.zip$/,""),a=new r_(xd.join(r,"runs",o));for(let s of a.getEntries())s.isDirectory||e.addFile(xd.join("runs",i,s.entryName),s.getData())}return{runGroupId:n.id,buffer:e.toBuffer()}}async function Md(r){let{client:e,consoleLogger:t,resultsPath:n}=r;if(!Vh.existsSync(n)){t.warn("Results path does not exist, skipping upload.");return}let o=new md(e);try{let{runGroupId:i,buffer:a}=QV(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 ZV from"adm-zip";import vt from"fs";import Jt from"path";var el=class r{constructor(e){this.filePath=e;vt.rmSync(this.filePath,{recursive:!0,force:!0}),vt.mkdirSync(this.filePath,{recursive:!0})}cd(e){return new r(Jt.join(this.filePath,e))}cwd(){return this.filePath}mkdir(e){vt.mkdirSync(Jt.join(this.filePath,e),{recursive:!0})}readFile(e){let t=Jt.join(this.filePath,e);if(vt.existsSync(t))return vt.readFileSync(t)}storeFile(e){let{name:t,contents:n}=e,o=Jt.join(this.filePath,t);try{vt.writeFileSync(o,n)}catch{}}createFileStream(e){let t=Jt.join(this.filePath,e);return vt.createWriteStream(t)}createRunArchive(e){return new Wh(Jt.join(this.filePath,"runs"),e)}},Wh=class{constructor(e,t){this.filePath=e;this.tempPath=Jt.join(e,`temp-storage-${t}`),this.finalPath=Jt.join(e,`${t}.zip`),vt.rmSync(this.tempPath,{recursive:!0,force:!0}),vt.rmSync(this.finalPath,{recursive:!0,force:!0}),vt.mkdirSync(this.tempPath,{recursive:!0})}tempPath;finalPath;readFile(e){let t=Jt.join(this.tempPath,e);if(vt.existsSync(t))return vt.readFileSync(t)}mkdir(e){vt.mkdirSync(Jt.join(this.tempPath,e),{recursive:!0})}cd(e){return new el(Jt.join(this.tempPath,e))}cwd(){return this.tempPath}storeFile(e){let{name:t,contents:n}=e,o=Jt.join(this.tempPath,t);vt.writeFileSync(o,n)}createFileStream(e){let t=Jt.join(this.tempPath,e);return vt.createWriteStream(t)}close(){let e=new ZV;e.addLocalFolder(this.tempPath,void 0,n=>n!==".DS_Store");let t=e.toBuffer();vt.writeFileSync(this.finalPath,t),vt.rmSync(this.tempPath,{recursive:!0,force:!0})}};import rGe from"adm-zip";import zd from"fs";import T_ from"body-parser";import vW from"cors";import AW from"dedent";import{Router as nW}from"express";import zt from"fs";import{globSync as oW}from"glob";import St from"path";import _d from"fs";import eW from"path";var tW=new Iu(30,60*1e3),Kh="https://api.momentic.ai",$h,o_=r=>{Kh=r},Yh=()=>Kh,tl=()=>$h;var pa,qh,n_,i_=async r=>{if($h&&pa&&n_)return pa;let e=new Yt({baseUrl:Kh,apiKey:r,logger:C});$h=e;try{let t=await e.getAuthInfo();return pa=t.orgId,qh=t.userId,n_=r,pa}catch(t){throw new Error(`Error checking API key against server: ${t}`)}},ga=()=>{if(!pa)throw new Error("Your organization ID is invalid.");return pa},Pd=()=>{if(!qh)throw new Error("Your user ID is invalid.");return qh};var Xh,jh,a_=(r,e)=>{Xh=r,jh?.abort(),jh=new AbortController;let t=jh.signal,n=[r.configFilePath];r.config.environments?.forEach(o=>{if(!o.envFile)return;let i=eW.resolve(r.rootDir,o.envFile);try{if(_d.lstatSync(i).isSymbolicLink())return;_d.existsSync(i)&&n.push(i)}catch(a){C.warn({err:a},`Failed to check if env file ${i} exists`)}});try{rW({filesToWatch:n,revalidator:e,signal:t,project:r})}catch(o){C.error({err:o},"Failed to start config file watchers")}},Ie=()=>Xh;function rW({filesToWatch:r,revalidator:e,signal:t,project:n}){C.debug("Starting watch on the following files:"),r.forEach(o=>{C.debug(`- ${o}`)}),r.forEach(o=>{let i=async(s,c)=>{s.mtime.getTime()!==c.mtime.getTime()&&(tW.increment("setLocalProject")&&C.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.`),Xh=await Promise.resolve(e(n.configFilePath)))};_d.watchFile(o,{persistent:!1},i);let a=()=>{_d.unwatchFile(o,i),t.removeEventListener("abort",a)};t.addEventListener("abort",a),process.once("SIGUSR2",()=>{a(),process.kill(process.pid,"SIGUSR2")})})}function Me(r){return function(...e){let t=e[e.length-1],n=r(...e);Promise.resolve(n).catch(t)}}var nl=nW();function rl(r){let e=Ie(),t=St.dirname(e.configFilePath);return St.join(t,...r)}function iW(r){let e=Ie(),t=St.dirname(e.configFilePath),n=St.relative(t,r);return n?n.split(St.sep):[]}function aW(r,e){let t=zt.statSync(r),n=iW(r);return Qm.parse({name:e,absolutePath:r,relativePath:n.join(St.sep),pathSegments:n,isDirectory:t.isDirectory(),size:t.size,createdAt:t.birthtime,modifiedAt:t.mtime,accessedAt:t.atime})}nl.post("/",Me(async(r,e,t)=>{let n;try{n=Vb.parse(r.body).pathSegments}catch(d){e.status(400).json({error:`Failed to parse folder read body: ${d}`});return}let o=rl(n);if(!zt.existsSync(o)){e.status(404).json({error:`Path not found: ${n.join(St.sep)}`});return}if(!zt.statSync(o).isDirectory()){e.status(400).json({error:`Path is not a directory: ${n.join(St.sep)}`});return}let a=Ie(),s=Array.from(a.config.exclude??[]).concat(sc),l=oW("*",{absolute:!1,cwd:o,ignore:s,dotRelative:!1,maxDepth:1,nodir:!1}).map(d=>{let m=St.join(o,d);return aW(m,d)}),u={absolutePath:o,pathSegments:n,contents:l};e.status(200).json(u)}));nl.put("/",Me(async(r,e,t)=>{let n;try{n=Wb.parse(r.body).pathSegments}catch(a){e.status(400).json({error:`Failed to parse folder create body: ${a}`});return}let o=rl(n);if(zt.existsSync(o)){e.status(200).json({success:!0,message:`Folder already exists: ${n.join(St.sep)}`,pathSegments:n});return}zt.mkdirSync(o,{recursive:!0});let i={success:!0,message:`Folder created: ${n.join(St.sep)}`,pathSegments:n};e.status(201).json(i)}));nl.patch("/",Me(async(r,e,t)=>{let n,o;try{let l=jb.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=rl(n),a=rl(o);if(!zt.existsSync(i)){e.status(400).json({error:`Folder not found: ${n.join(St.sep)}`});return}if(zt.existsSync(a)){e.status(400).json({error:`Destination already exists: ${o.join(St.sep)}`});return}let s=St.dirname(a);zt.existsSync(s)||zt.mkdirSync(s,{recursive:!0}),zt.renameSync(i,a);let c={success:!0,message:`Folder moved from ${n.join(St.sep)} to ${o.join(St.sep)}`,pathSegments:o};e.status(200).json(c)}));nl.delete("/",Me(async(r,e,t)=>{let n,o=!0;try{let c=$b.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=rl(n);if(!zt.existsSync(i)){e.status(200).json({success:!0,message:`Folder not found: ${n.join(St.sep)}`,pathSegments:n});return}if(!zt.statSync(i).isDirectory()){e.status(400).json({error:`Path is not a directory: ${n.join(St.sep)}`});return}if(o)zt.rmSync(i,{recursive:!0,force:!0});else{if(zt.readdirSync(i).length>0){e.status(409).json({error:`Cannot delete non-empty directory without recursive flag: ${n.join("/")}`});return}zt.rmdirSync(i)}let s={success:!0,message:`Folder deleted: ${n.join("/")}`,pathSegments:n};e.status(200).json(s)}));var Jh=nl;import{Router as cW}from"express";import{hostname as sW}from"os";var lW="0.16.3",ol=_i({app:"desktop-server",hostname:sW(),disableConsoleLogs:!0}).child({cliVersion:lW});(async()=>{try{let r=await Js(ol);r.gitBranchName&&ol.addBinding("branch",r.gitBranchName)}catch{}})();var s_=cW();s_.get("/",async(r,e)=>{let t=Ie(),n=tl();if(!n){e.status(500).json({message:"API client not initialized"});return}let o=await ca(ol,n,t);e.status(200).json(o)});var Qh=s_;import wW from"events";import v_,{Router as CW}from"express";import RW from"http";import xW from"path";var Id=new Ed;import{Router as dW}from"express";import{existsSync as mW}from"fs";import pW from"path";import{hostname as uW}from"os";var Zh="0.16.3",st=_i({app:"mobile-desktop-server",hostname:uW(),disableConsoleLogs:!0}).child({cliVersion:Zh});(async()=>{try{let r=await Js(st);r.gitBranchName&&st.addBinding("branch",r.gitBranchName)}catch{}})();var ef=dW();ef.get("/",Me(async(r,e)=>{let t=tl();if(!t){e.status(500).json({message:"API client not initialized"});return}let n=await t.getAndroidAssets();e.status(200).json(n)}));ef.post("/upload-url",Me(async(r,e)=>{let t;try{t=Zb.parse(r.body)}catch(i){e.status(400).json({error:`Invalid request body: ${i}`});return}let n=tl();if(!n){e.status(500).json({error:"API client not initialized"});return}let o=pW.resolve(t.filePath);if(!mW(o)){e.status(400).json({error:`File not found: ${o}`});return}await wu({tag:t.tag,channel:t.channel,filePath:o,apiClient:n,logger:st}),e.sendStatus(204)}));var l_=ef;import{Router as fW}from"express";import{Router as gW}from"express";import c_ from"fs";import hW from"path";var il=gW();async function tf(r){return(await KM(r,st)).map(n=>{let o=r.mobileModules[n.moduleId];if(!o){C.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)}il.get("/",Me(async(r,e)=>{let t=Ie(),n=await Xt(t),o=await tf(n);e.status(200).json(o)}));il.get("/:moduleId",Me(async(r,e)=>{if(!r.params.moduleId){e.status(400).json({error:"Missing moduleId in url path."});return}let t=await Xt(Ie()),n=t.mobileModules[r.params.moduleId];if(!n){e.status(404).json({error:"Mobile module not found."});return}try{let o=await Hh(n,t,C);e.json(o)}catch(o){e.status(400).json({err:o})}}));il.patch("/:moduleId/metadata",Me(async(r,e)=>{if(!r.params.moduleId){e.status(400).json({error:"Missing moduleId in url path."});return}let t;try{t=tE.parse(r.body)}catch(i){e.status(400).json({error:`Invalid request body: ${i}`});return}let n=Ie(),o=await Xt(n);$M({moduleId:r.params.moduleId,patch:t,momenticFiles:o,logger:C,project:n}),e.status(201).json({message:"ok"})}));il.post("/",Me(async(r,e)=>{let t;try{t=rE.parse(r.body)}catch(c){e.status(400).json({error:`Invalid request body: ${c}`});return}try{So(t.name)}catch(c){e.status(400).json({error:`Invalid module name: ${c}`});return}let n=Ie(),i=(await Xt(n)).mobileModules;if(Object.values(i).find(c=>c.name===t.name)){e.status(400).json({error:`A mobile module with the name "${t.name}" already exists. Please choose a different name.`});return}let a=hW.join(n.rootDir,t.folderPath??"");if(!c_.existsSync(a)||!c_.statSync(a).isDirectory()){e.status(400).json({error:`The folder configured for mobile module creation does not exist: ${a}`});return}let s=await qM({...t,folder:a,project:n});e.status(201).json(s)}));var u_=il;var d_=fW();d_.get("/",Me(async(r,e)=>{let t=Ie(),n=await Xt(t),o=await tf(n),i=new Set;n?.tests&&Object.values(n.tests).forEach(l=>{l.labels?.forEach(u=>i.add(u))});let a=Array.from(i).sort(),s=Object.values(n.mobileTests),c={labels:a,modules:o,tests:s};e.status(200).json(c)}));var m_=d_;import{Router as SW}from"express";var Od=SW();Od.get("/",Me((r,e)=>{let t=NM(Ie(),st);e.status(200).json(t)}));Od.get("/names",Me((r,e)=>{let n=Ie().config.environments?.map(o=>o.name)??[];e.status(200).json(n)}));Od.post("/",Me((r,e)=>{let t;try{t=eE.parse(r.body)}catch(s){e.status(400).json({error:`Invalid request body: ${s}`});return}try{So(t.name)}catch(s){e.status(400).json({error:`Invalid environment name: ${s}`});return}let n=Ie();if(n.config.environments?.find(s=>s.name===t.name)){e.status(400).json({error:`An environment with the name "${t.name}" already exists. Please choose a different name.`});return}let i={...n.config,environments:[...n.config.environments??[],{name:t.name}]};n.config=i,Ad(i,n.configFilePath);let a=Ko(t.name,n,st);e.status(201).json(a)}));var p_=Od;import{Router as yW}from"express";var g_=yW();g_.get("/",(r,e)=>{e.status(200).json({userId:Pd(),orgId:ga(),cliVersion:Zh??"0.0.0"})});var h_=g_;import{Router as bW}from"express";var f_=bW();f_.get("/",Me(async(r,e)=>{let t=r.query.sessionId;if(!t){e.status(400).json({packages:[]});return}let n=Id.getSession(t);if(!n?.controller){e.status(200).json({packages:[]});return}try{let a=(await n.controller.executeRawADBCommand("shell pm list packages -3"))?.split(`
4406
4406
  `).filter(s=>s.trim().startsWith("package:")).map(s=>s.replace("package:","").trim()).filter(s=>s.length>0&&!s.startsWith("io.appium"))||[];e.status(200).json({packages:a})}catch(o){st.error({err:o},"Error fetching installed packages from the session controller"),e.status(200).json({packages:[]})}}));var S_=f_;import{Router as EW}from"express";import Ld from"path";var al=EW();al.patch("/:testPath",Me(async(r,e)=>{let t=r.params.testPath;if(!t){e.status(400).json({error:"Missing testPath in path"});return}let n;try{n=Jb.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=Ie(),i=t.endsWith(".test.yaml")?t:`${t}.test.yaml`,a=await Xt(o);await XM({filePath:i,steps:n.steps,settings:n.settings,folder:o.rootDir,project:o,momenticFiles:a,schemaVersion:ho});let s={message:"ok"};e.status(200).json(s)}));al.post("/",Me((r,e)=>{let t;try{t=Xb.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{So(n)}catch(g){e.status(400).json({error:g.message});return}let s=Ie(),c=Ld.join(s.rootDir,...a),{fullPath:l,testId:u}=YM({name:n,description:o,steps:[],settings:i,folder:c}),d=Ld.basename(l),m=Ld.relative(s.rootDir,l),p={id:u,fileName:d,fullPath:l,relativeFilePath:m};e.status(201).json(p)}));al.get("/:fileName",Me(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=Ld.basename(n).replace(".test.yaml",""),i=Ie(),a=await Xt(i),c={...await Rd(n,st,a),name:o};e.status(200).json(c)}));al.patch("/:testPath/metadata",Me(async(r,e)=>{let t=r.params.testPath;if(!t){e.status(400).json({error:"Missing testPath in path"});return}let n;try{n=Qb.parse(r.body)}catch(c){e.status(400).json({error:`Invalid request body: ${c}`});return}let o=Ie(),i=t.endsWith(".test.yaml")?t:`${t}.test.yaml`,s={message:"ok",newRelativeTestPath:JM(i,n,o).newRelativeTestPath};e.status(200).json(s)}));var y_=al;import{Router as TW}from"express";var b_=TW();b_.get("/",Me((r,e)=>{let t=Ie(),n={ai:t.config.ai,displayRoot:t.config.displayRoot};e.status(200).json(n)}));var E_=b_;var Nd=class extends ra{constructor(t,n){super(t,n);this.client=t;this.orgId=n}async fetchEnvironment(t,n){let o=Ie();return Ko(t,o,C)}};var A_="10mb";async function w_(r){let{serverPort:e,apiKey:t,momenticServerUrl:n,staticDir:o,initialProject:i,driverLogLevel:a,regenerateCache:s,alwaysSaveCache:c,noCache:l}=r;n&&o_(n),await i_(t);let u=ga(),d=Pd(),m=r.logger.child({orgId:u,userId:d});a_(i,v=>la({configFilePath:v}));let p=v_();p.use(vW()),p.use(T_.json({limit:A_})),p.use(T_.urlencoded({extended:!1,limit:A_}));let g=CW();if(g.use("/folders",Jh),g.use("/entities",m_),g.use("/identify",h_),g.use("/mobile-tests",y_),g.use("/mobile-modules",u_),g.use("/assets",l_),g.use("/git",Qh),g.use("/environments",p_),g.use("/installed-packages",S_),g.use("/settings",E_),p.use("/api",g),p.use((v,_,k)=>{C.debug({url:v.url,path:v.path,query:v.query,method:v.method,body:v.body,headers:v.rawHeaders,client:v.ip},"Incoming request on mobile-desktop-server"),_.on("close",()=>{_.statusCode>=400&&(C.error({url:v.url,method:v.method,statusCode:_.statusCode},"Request completed in error on mobile-desktop-server"),st.error({url:v.url,method:v.method,statusCode:_.statusCode},"Request completed in error on mobile-desktop-server"))}),k()}),p.use((v,_,k,V)=>{if(v instanceof Error&&v.message.includes("BadRequestError: request aborted")){k.status(400).send("Client disconnected");return}C.error({stack:v.stack,msg:v.message,err:v,url:_.url,method:_.method},"Unhandled exception leading to 500 on mobile-desktop-server"),st.error({stack:v.stack,msg:v.message,err:v,url:_.url,method:_.method},"Unhandled exception leading to 500 on mobile-desktop-server"),k.status(500).send(`Internal Server Error: ${v.message}`)}),o){let v=v_.static(o,{setHeaders:_=>{_.setHeader("Cache-Control","no-cache")},redirect:!1});p.use(v),p.use("*",(_,k)=>{k.sendFile(xW.join(o,"index.html"))})}let h=RW.createServer(p),f=`http://localhost:${e}`;await new Promise(v=>{try{h.listen(e,()=>{m.info(`Mobile desktop server is running at ${f}`),v()})}catch(_){_.message.includes("EADDRINUSE")?MW(e):C.error(`An unexpected error occurred while starting the server: ${_.message}`),process.exit(1)}});let b={type:"API_KEY",baseUrl:Yh(),apiKey:t,logger:m},w=new Yt(b),x=Ie(),A={...b,mode:"interactive"},{dispose:M}=OM({baseServer:h,logger:m,authorization:b,globalStateManager:Id,getOrgId:()=>ga(),getGitMetadata:async()=>await ca(m,w,x),androidDriverFactory:async({socket:v,logger:_,creationOpts:k})=>{let V=Math.floor(Math.random()*1e4)+4e4,Z=await bc(V,"appium");return Au({logger:_,driverLogLevel:a,apiClient:w,creationOpts:k,socket:v,appiumPort:Z,sessionId:v.id,orgId:ga(),onStatusUpdate:te=>{v.emit("connectionStatusUpdate",{message:te,type:"info"})},onConnectionStateChange:te=>{te==="disconnected"?v.emit("connectionStatusUpdate",{message:"Emulator websocket connection lost.",type:"disconnected"}):te==="reconnecting"||te==="connecting"?v.emit("connectionStatusUpdate",{message:"Emulator websocket is reconnecting...",type:te==="reconnecting"?"reconnecting":"connecting"}):te==="connected"&&v.emit("connectionStatusUpdate",{message:"Emulator websocket connection restored",type:"connected"})}})},mobileGeneratorFactory:async v=>new ia({baseUrl:Yh(),apiKey:t,logger:m,mode:"interactive"}),browserGeneratorFactory:async v=>new qo(x.config.ai?.agentConfig,A),browserEnricherFactory:async v=>new ta(A,new qo(x.config.ai?.agentConfig,A)),storageFactory:async v=>new Nd(w,v),cacheStorageFactory:async(v,_)=>pd({orgId:v,client:w,gitMetadata:_,regenerateCache:s??!1,noCache:l??!1,alwaysSaveCache:c??!1}),localToolsFactory:async()=>new oa({httpClient:w,fakerSeed:void 0}),keepSessionAlive:v=>w.extendAndroidEmulatorTtl(v),settingsFactory:async()=>({emulator:{},ai:{},...x.config})});process.once("SIGUSR2",async()=>{return;try{await M(),await gt.flush()}catch(v){C.error({err:v},"Error during session dispose on SIGUSR2")}try{h.close(()=>{process.kill(process.pid,"SIGUSR2")})}catch{process.kill(process.pid,"SIGUSR2")}}),process.once("SIGTERM",async()=>{let v="SIGTERM in Momentic mobile app received";C.info(v),m.info(v);try{await M(),await gt.flush()}finally{h.close(()=>process.exit(0))}}),process.once("SIGINT",async()=>{C.info("SIGINT in Momentic mobile app received");try{await M(),await gt.flush()}finally{h.close(()=>process.exit(0))}})}wW.setMaxListeners(25);process.on("warning",r=>{st.warn({err:r},`Node warning received on mobile-desktop-server: ${r.message}`)});process.on("uncaughtException",r=>{st.error({err:r},"Uncaught exception on mobile-desktop-server"),C.error(`Oh no! The Momentic mobile desktop app encountered a fatal error \u{1F61E}. Error logs: ${r.message}`)});process.on("unhandledRejection",r=>{st.error({reason:`${r}`,stack:r?.stack},"Uncaught exception on mobile-desktop-server (promise rejection)"),C.error(`Oh no! The Momentic mobile desktop app encountered an asynchronous error \u{1F61E}. Error logs: ${r}`)});function MW(r){C.error(AW`Port ${r} is already in use by another process. Please close the other process and try again.
4407
4407
  Using Bash on MacOS or Linux:
4408
4408
  lsof -t -i :58888 | xargs kill -9
@@ -4412,7 +4412,7 @@ ${n.map(o=>o.configFilePath)}`);if(n.length===0)throw new Error("No valid Moment
4412
4412
  `)}import $W from"open";import Hd from"path";import{fileURLToPath as qW}from"url";import rf from"fs";import Dd from"path";import{cwd as _W}from"process";async function nf({tests:r,momenticFiles:e,project:t,yes:n,include:o,exclude:i,logger:a,quarantinedTestReasons:s}){let c=new Set;if(r&&r.length>0){let u=r.some(m=>rf.existsSync(m)),d=_W();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:
4413
4413
  - ${r.join(`
4414
4414
  - `)}
4415
- `),r.forEach(m=>{if(!rf.existsSync(m))throw new Error(`Path '${m}' does not exist.`);let p,g;try{p=rf.statSync(m),g=p.isDirectory()}catch(f){a.warn({err:f},`Skipping path ${m} because it cannot be read`);return}let h=Dd.resolve(m);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(m=>{r.some(p=>m.relativePath.includes(p))&&c.add(m.fullFilePath)}))}else{!n&&!await fc("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=Dd.relative(t.rootDir,u);o&&!o.some(m=>new RegExp(m).test(d))&&c.delete(u),i&&i.some(m=>new RegExp(m).test(d))&&c.delete(u)}return(await Promise.all(Array.from(c).map(async u=>{try{let d=Dd.relative(t.rootDir,u),m=await Rd(u,a,e),p=Dd.basename(u,".test.yaml");return m.disabled?null:{id:m.id,name:p,description:m.description,schemaVersion:m.schemaVersion,settings:m.settings,steps:m.steps,fullFilePath:u,relativeFilePath:d,quarantined:!!s[m.id],quarantinedReason:s[m.id]}}catch(d){a.error(`Failed to read and resolve mobile test at '${u}': ${d}`),process.exit(1)}}))).filter(u=>!!u)}import{InvalidArgumentError as kd,Option as Ve}from"@commander-js/extra-typings";import{z as PW}from"zod";var C_=58890;function Ud(r){let e=parseInt(r,10);if(isNaN(e))throw new kd("Not a number.");return e}var sl=new Ve("--api-key <key>","Momentic API key").env("MOMENTIC_API_KEY").argParser(r=>{if(!r)throw new kd("API key is required.");return r}).makeOptionMandatory(),Fd=new Ve("-c, --config <configPath>","Absolute or relative path to a Momentic configuration file."),of=new Ve("-f, --filter <filter>","Run tests within the project that has a name equal to the filter provided. This option cannot be used together with file path or directory arguments, but substring matches are allowed."),ll=new Ve("--server <server>","Momentic server to use.").env("MOMENTIC_SERVER").default("https://api.momentic.ai").argParser(r=>{try{return PW.string().url().parse(r),r}catch{throw new kd("Not a valid URL.")}}),af=new Ve("-y, --yes","Skip all confirmation prompts.").env("CI"),sf=new Ve("--regenerate-cache","Regenerate all caches by starting from an empty cache state. This flag is useful for completely regenerating caches after changing configuration options. Warning: using this option will cause all steps to run without any cached data, resulting in significantly longer execution times.").implies({disableCache:!1,saveCache:!0}),lf=new Ve("--save-cache","Always save updated step caches after successful test runs. By default, caches are not saved when running on protected branches.").env("CI").implies({disableCache:!1}),cf=new Ve("--disable-cache","Disable using step caches completely. Using this option may lead to non-deterministic behavior and significantly longer runtimes.").implies({saveCache:!1,regenerateCache:!1}),uf=new Ve("--tag <tag>","Tag identifier for the asset."),R_=new Ve("--channel <channel>","Channel name for the asset."),x_=new Ve("--channel <channel>","Channel name for the asset.").makeOptionMandatory(),M_=new Ve("--env <env>","Environment to run all tests in (overrides test-level configuration)."),__=new Ve("--local-avd-id <localAvdId>","Force tests to use a specific local Android Virtual Device (AVD) instead of remote emulators."),P_=new Ve("--local-apk-path <localApkPath>","Path to a local APK file to install when running tests with a local emulator. Overrides remote asset configuration."),I_=new Ve("-p, --parallel <parallel>","The number of tests to run in parallel. Defaults to 1.").argParser(Ud),O_=new Ve("--shard-index <shardIndex>","The index of the shard to run tests for. Defaults to 1.").default(1).argParser(r=>{let e=Ud(r);if(e<1)throw new kd("Shard index must be greater than 0.");return e}),L_=new Ve("--shard-count <shardCount>","The number of shards that tests are being run on. Defaults to 1.").default(1).argParser(Ud),df=new Ve("--output-dir <outputDir>","Output directory to store run artifacts such as screenshots, results, and logs."),mf=new Ve("--include <includePatterns...>","Only include tests that match the provided regex patterns. Multiple patterns can be provided. The patterns will be matched against the test file paths and the pattern only needs to match a part of the path for the test to be included."),pf=new Ve("--exclude <excludePatterns...>","The inverted version of --include: a test that matches any of the provided exclusion patterns will be excluded from running."),N_=new Ve("--upload-results","Upload test results to Momentic Cloud.").default(!1),gf=new Ve("--log-level <logLevel>","Log level for Momentic and dependent services.").choices(["error","warn","info","debug"]),D_=new Ve("--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}),k_=new Ve("--timeout-minutes <timeoutMinutes>","Maximum number of minutes to run tests before stopping. When the timeout is reached, tests will stop and current results will be printed.").argParser(Ud);import{randomUUID as zW}from"crypto";import{existsSync as HW}from"fs";import{randomUUID as OW}from"crypto";import{existsSync as LW,statSync as NW}from"fs";import{cloneDeep as DW}from"lodash-es";import U_ from"path";async function F_(r){let{inputs:e,fixtures:t,metadata:n,options:o}=r,{tracer:i,logger:a}=t,{runId:s}=n,{testDefinition:c,runSigIntHandlers:l,project:u}=e,d=new Date,m=await i.startRun({logger:a,testId:c.id,testName:c.name,runId:s,testDescription:c.description,schemaVersion:c.schemaVersion,originalSteps:{steps:DW(c.steps),beforeSteps:void 0,afterSteps:void 0},quarantined:c.quarantined,quarantinedReason:c.quarantinedReason}),p=a.child(m.loggerBindings||{}),g=1+(c.settings?.retries??u.config.retries??1);try{for(let h=0;h<g;h++){let f=new Date,E=await kW({runTracer:m,testDefinition:c,metadata:n,constants:{attemptNumber:h,totalAttempts:g},fixtures:{...t,logger:p},inputs:e,options:o}),b=new Date;if(E.status!=="FAILED")return await m.finish({logger:a,...E,finishedAt:b}),{...E,startedAt:d,lastAttemptStartedAt:f,finishedAt:b,runId:s,attempts:h+1,testMetadata:c,steps:c.steps,filePath:c.relativeFilePath,quarantined:c.quarantined,quarantinedReason:c.quarantinedReason};if(h!==g-1){a.warn("Retrying failed mobile run");continue}return a.error("Mobile test failed after all exhausting attempts"),await m.finish({logger:a,...E,finishedAt:b}),{...E,startedAt:d,lastAttemptStartedAt:f,finishedAt:b,runId:s,attempts:h+1,testMetadata:c,steps:c.steps,filePath:c.relativeFilePath,quarantined:c.quarantined,quarantinedReason:c.quarantinedReason}}throw new Error("This code should not be reachable")}finally{l?.pop()}}async function kW(r){let{runTracer:e,testDefinition:t,metadata:n,constants:o,fixtures:i,inputs:a,options:s}=r,{attemptNumber:c,totalAttempts:l}=o,{orgId:u,gitMetadata:d}=n,{apiClient:m,logger:p,usageTracker:g}=i,{logUpdate:h,channel:f,tag:E,project:b,envOverride:w}=a,{regenerateCache:x,alwaysSaveCache:A,noCache:M,logLevel:v,localAvdId:_,localApkPath:k}=s;c!==0&&h("RETRY",`attempt ${c}/${l}`);let V={...a.project.config.emulator,...t.settings?.emulator},Z=k?U_.resolve(k):void 0;if(Z&&(!LW(Z)||!NW(Z).isFile()))throw new Error(`Local APK path "${Z}" does not exist. Provide a valid file path via --local-apk-path.`);let te=w||t.settings?.defaultEnv,Y=(te?Ko(te,b,p):void 0)?.variables??{},H=typeof Y[Eo]=="string"?Y[Eo].trim():void 0,ce=typeof Y[Fa]=="string"?Y[Fa].trim():void 0,pe=pd({orgId:u,client:m,gitMetadata:d,regenerateCache:x??!1,alwaysSaveCache:A??!1,noCache:M??!1}),Je=new ra(m,u),Re={type:"API_KEY",baseUrl:m.baseUrl,apiKey:m.apiKey,logger:p,mode:"runner"},jt=new ia(Re),_t=new qo(b.config.ai?.agentConfig,Re),Ue=new ta(Re,_t),lt=new oa({httpClient:m,fakerSeed:void 0}),Or=Math.floor(Math.random()*1e4)+4e4,vn=await bc(Or,"appium"),oo=V.region==="local"?Z??t.settings?.defaultApkFilePath?.trim()??(ce?U_.resolve(ce):void 0):void 0,Xo=f&&!oo?{channel:f,tag:E}:void 0,fa,io;if(_||V.region==="local"){if(io=_??V.localEmulatorSettings?.avdId??H,!io)throw new Error(`An AVD ID is required when using a local region. Provide --local-avd-id, configure a default local AVD ID on the test's settings, or set the ${Eo} key on the environment.`);fa={avdId:io,apkToInstall:Xo,apkFilePath:oo}}else fa={region:V.region,apkToInstall:Xo,osVersion:V.remoteEmulatorSettings?.androidVersion??lb};let ao=OW(),so=p.child({runAttemptId:ao}),Lr;try{Lr=await Au({apiClient:m,logger:p,driverLogLevel:v,creationOpts:fa,onStatusUpdate:$t=>{p.debug({status:$t},"Emulator status update")},appiumPort:vn,orgId:u,sessionId:ao,onConnectionStateChange:$t=>{$t==="disconnected"?C.warn("Emulator websocket connection lost. Emulator may be unavailable."):($t==="reconnecting"||$t==="connecting")&&C.info("Emulator websocket is reconnecting...")}})}catch($t){return p.error({err:$t},"Failed to create Android driver, failing attempt"),{status:"FAILED",results:[]}}let $=await e.startAttempt({emulatorName:Lr.emulatorName,runAttemptId:ao});so=so.child($.loggerBindings||{});let Sa=await Cu({driver:Lr.driver,onLogs:$t=>{$.appendLogs($t)}}),an=new bi({variablesFromEnvironment:Y,envName:te,testName:t.name}),bf=await ea.init({driver:Lr.driver,generator:jt,logger:so,limbarClient:Lr.limbarClient,playwrightDevice:Lr.playwrightDevice,orgId:u,adbPort:Lr.adbPort,options:{emulator:V},aiSettings:{...b.config.ai,useMemory:b.config.ai?.useMemory!==!1,...t.settings?.ai},fixtures:{storage:Je,browserEnricher:Ue,browserGenerator:_t,localCodeEvalTools:lt,testContext:an}}),ul;try{ul=await yd({containerName:`mobile test ${t.name}`,fixtures:{controller:bf,logger:so,cacheStorage:pe,usageTracker:g},work:{},inputs:{testName:t.name,steps:t.steps,orgId:u,testMetadata:t},tracer:$,callbacks:{driver:{onHeartbeatFailure:()=>{let $t="Appium heartbeat connection lost \u2014 possible ADB tunnel/emulator failure";C.warn($t)},onHeartbeatRestored:()=>{let $t="Appium heartbeat connection restored";C.info($t)}}}})}finally{await Sa(),await Lr.cleanup(),await bf.cleanup()}return await $.finish({logger:so,results:ul.results,status:ul.status,assetDetails:{avdId:io,tag:Xo?.tag,channel:Xo?.channel}}),ul}import{debounce as UW}from"ts-debounce";var cl="0.16.1";function FW(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 BW(r){switch(r){case"SUCCESS":return"PASSED";case"FAILED":return"FAILED";case"CANCELLED":return"CANCELLED";case"RUNNING":return"RUNNING";case"IDLE":return"PENDING"}}var hf=class{constructor(e,t,n,o){this.keepalive=e;this.testId=t;this.testName=n;this.diskStorage=o;this.interactionTracer=new Vo,Pr.initializeRootTracerContext(this.interactionTracer)}children=[];finished=!1;interactionTracer;getParentStepIdChain(){return[]}attachBeforeScreenshot(e){let{snapshotId:t,screenshot:n}=e;this.diskStorage.storeFile({name:`${as}/${t}.jpeg`,contents:n})}attachAfterScreenshot(e){let{snapshotId:t,screenshot:n}=e;this.diskStorage.storeFile({name:`${as}/${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:BW(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 ha(this.keepalive,this.testId,this.testName,this.diskStorage);return this.children.push(e),e}},ha=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(`${as}/${t}.jpeg`)}getParentStepIdChain(){return[]}async startStep(e){this.keepalive();let t=new hf(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:FW(e.status),finishedAt:e.finishedAt}))))}},ff=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(`
4415
+ `),r.forEach(m=>{if(!rf.existsSync(m))throw new Error(`Path '${m}' does not exist.`);let p,g;try{p=rf.statSync(m),g=p.isDirectory()}catch(f){a.warn({err:f},`Skipping path ${m} because it cannot be read`);return}let h=Dd.resolve(m);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(m=>{r.some(p=>m.relativePath.includes(p))&&c.add(m.fullFilePath)}))}else{!n&&!await fc("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=Dd.relative(t.rootDir,u);o&&!o.some(m=>new RegExp(m).test(d))&&c.delete(u),i&&i.some(m=>new RegExp(m).test(d))&&c.delete(u)}return(await Promise.all(Array.from(c).map(async u=>{try{let d=Dd.relative(t.rootDir,u),m=await Rd(u,a,e),p=Dd.basename(u,".test.yaml");return m.disabled?null:{id:m.id,name:p,description:m.description,schemaVersion:m.schemaVersion,settings:m.settings,steps:m.steps,fullFilePath:u,relativeFilePath:d,quarantined:!!s[m.id],quarantinedReason:s[m.id]}}catch(d){a.error(`Failed to read and resolve mobile test at '${u}': ${d}`),process.exit(1)}}))).filter(u=>!!u)}import{InvalidArgumentError as kd,Option as Ve}from"@commander-js/extra-typings";import{z as PW}from"zod";var C_=58890;function Ud(r){let e=parseInt(r,10);if(isNaN(e))throw new kd("Not a number.");return e}var sl=new Ve("--api-key <key>","Momentic API key").env("MOMENTIC_API_KEY").argParser(r=>{if(!r)throw new kd("API key is required.");return r}).makeOptionMandatory(),Fd=new Ve("-c, --config <configPath>","Absolute or relative path to a Momentic configuration file."),of=new Ve("-f, --filter <filter>","Run tests within the project that has a name equal to the filter provided. This option cannot be used together with file path or directory arguments, but substring matches are allowed."),ll=new Ve("--server <server>","Momentic server to use.").env("MOMENTIC_SERVER").default("https://api.momentic.ai").argParser(r=>{try{return PW.string().url().parse(r),r}catch{throw new kd("Not a valid URL.")}}),af=new Ve("-y, --yes","Skip all confirmation prompts.").env("CI"),sf=new Ve("--regenerate-cache","Regenerate all caches by starting from an empty cache state. This flag is useful for completely regenerating caches after changing configuration options. Warning: using this option will cause all steps to run without any cached data, resulting in significantly longer execution times.").implies({disableCache:!1,saveCache:!0}),lf=new Ve("--save-cache","Always save updated step caches after successful test runs. By default, caches are not saved when running on protected branches.").env("CI").implies({disableCache:!1}),cf=new Ve("--disable-cache","Disable using step caches completely. Using this option may lead to non-deterministic behavior and significantly longer runtimes.").implies({saveCache:!1,regenerateCache:!1}),uf=new Ve("--tag <tag>","Tag identifier for the asset."),R_=new Ve("--channel <channel>","Channel name for the asset."),x_=new Ve("--channel <channel>","Channel name for the asset.").makeOptionMandatory(),M_=new Ve("--env <env>","Environment to run all tests in (overrides test-level configuration)."),__=new Ve("--local-avd-id <localAvdId>","Force tests to use a specific local Android Virtual Device (AVD) instead of remote emulators."),P_=new Ve("--local-apk-path <localApkPath>","Path to a local APK file to install when running tests with a local emulator. Overrides remote asset configuration."),I_=new Ve("-p, --parallel <parallel>","The number of tests to run in parallel. Defaults to 1.").argParser(Ud),O_=new Ve("--shard-index <shardIndex>","The index of the shard to run tests for. Defaults to 1.").default(1).argParser(r=>{let e=Ud(r);if(e<1)throw new kd("Shard index must be greater than 0.");return e}),L_=new Ve("--shard-count <shardCount>","The number of shards that tests are being run on. Defaults to 1.").default(1).argParser(Ud),df=new Ve("--output-dir <outputDir>","Output directory to store run artifacts such as screenshots, results, and logs."),mf=new Ve("--include <includePatterns...>","Only include tests that match the provided regex patterns. Multiple patterns can be provided. The patterns will be matched against the test file paths and the pattern only needs to match a part of the path for the test to be included."),pf=new Ve("--exclude <excludePatterns...>","The inverted version of --include: a test that matches any of the provided exclusion patterns will be excluded from running."),N_=new Ve("--upload-results","Upload test results to Momentic Cloud.").default(!1),gf=new Ve("--log-level <logLevel>","Log level for Momentic and dependent services.").choices(["error","warn","info","debug"]),D_=new Ve("--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}),k_=new Ve("--timeout-minutes <timeoutMinutes>","Maximum number of minutes to run tests before stopping. When the timeout is reached, tests will stop and current results will be printed.").argParser(Ud);import{randomUUID as zW}from"crypto";import{existsSync as HW}from"fs";import{randomUUID as OW}from"crypto";import{existsSync as LW,statSync as NW}from"fs";import{cloneDeep as DW}from"lodash-es";import U_ from"path";async function F_(r){let{inputs:e,fixtures:t,metadata:n,options:o}=r,{tracer:i,logger:a}=t,{runId:s}=n,{testDefinition:c,runSigIntHandlers:l,project:u}=e,d=new Date,m=await i.startRun({logger:a,testId:c.id,testName:c.name,runId:s,testDescription:c.description,schemaVersion:c.schemaVersion,originalSteps:{steps:DW(c.steps),beforeSteps:void 0,afterSteps:void 0},quarantined:c.quarantined,quarantinedReason:c.quarantinedReason}),p=a.child(m.loggerBindings||{}),g=1+(c.settings?.retries??u.config.retries??1);try{for(let h=0;h<g;h++){let f=new Date,E=await kW({runTracer:m,testDefinition:c,metadata:n,constants:{attemptNumber:h,totalAttempts:g},fixtures:{...t,logger:p},inputs:e,options:o}),b=new Date;if(E.status!=="FAILED")return await m.finish({logger:a,...E,finishedAt:b}),{...E,startedAt:d,lastAttemptStartedAt:f,finishedAt:b,runId:s,attempts:h+1,testMetadata:c,steps:c.steps,filePath:c.relativeFilePath,quarantined:c.quarantined,quarantinedReason:c.quarantinedReason};if(h!==g-1){a.warn("Retrying failed mobile run");continue}return a.error("Mobile test failed after all exhausting attempts"),await m.finish({logger:a,...E,finishedAt:b}),{...E,startedAt:d,lastAttemptStartedAt:f,finishedAt:b,runId:s,attempts:h+1,testMetadata:c,steps:c.steps,filePath:c.relativeFilePath,quarantined:c.quarantined,quarantinedReason:c.quarantinedReason}}throw new Error("This code should not be reachable")}finally{l?.pop()}}async function kW(r){let{runTracer:e,testDefinition:t,metadata:n,constants:o,fixtures:i,inputs:a,options:s}=r,{attemptNumber:c,totalAttempts:l}=o,{orgId:u,gitMetadata:d}=n,{apiClient:m,logger:p,usageTracker:g}=i,{logUpdate:h,channel:f,tag:E,project:b,envOverride:w}=a,{regenerateCache:x,alwaysSaveCache:A,noCache:M,logLevel:v,localAvdId:_,localApkPath:k}=s;c!==0&&h("RETRY",`attempt ${c}/${l}`);let V={...a.project.config.emulator,...t.settings?.emulator},Z=k?U_.resolve(k):void 0;if(Z&&(!LW(Z)||!NW(Z).isFile()))throw new Error(`Local APK path "${Z}" does not exist. Provide a valid file path via --local-apk-path.`);let te=w||t.settings?.defaultEnv,Y=(te?Ko(te,b,p):void 0)?.variables??{},H=typeof Y[Eo]=="string"?Y[Eo].trim():void 0,ce=typeof Y[Fa]=="string"?Y[Fa].trim():void 0,pe=pd({orgId:u,client:m,gitMetadata:d,regenerateCache:x??!1,alwaysSaveCache:A??!1,noCache:M??!1}),Je=new ra(m,u),Re={type:"API_KEY",baseUrl:m.baseUrl,apiKey:m.apiKey,logger:p,mode:"runner"},jt=new ia(Re),_t=new qo(b.config.ai?.agentConfig,Re),Ue=new ta(Re,_t),lt=new oa({httpClient:m,fakerSeed:void 0}),Or=Math.floor(Math.random()*1e4)+4e4,vn=await bc(Or,"appium"),oo=V.region==="local"?Z??t.settings?.defaultApkFilePath?.trim()??(ce?U_.resolve(ce):void 0):void 0,Xo=f&&!oo?{channel:f,tag:E}:void 0,fa,io;if(_||V.region==="local"){if(io=_??V.localEmulatorSettings?.avdId??H,!io)throw new Error(`An AVD ID is required when using a local region. Provide --local-avd-id, configure a default local AVD ID on the test's settings, or set the ${Eo} key on the environment.`);fa={avdId:io,apkToInstall:Xo,apkFilePath:oo}}else fa={region:V.region,apkToInstall:Xo,osVersion:V.remoteEmulatorSettings?.androidVersion??lb};let ao=OW(),so=p.child({runAttemptId:ao}),Lr;try{Lr=await Au({apiClient:m,logger:p,driverLogLevel:v,creationOpts:fa,onStatusUpdate:$t=>{p.debug({status:$t},"Emulator status update")},appiumPort:vn,orgId:u,sessionId:ao,onConnectionStateChange:$t=>{$t==="disconnected"?C.warn("Emulator websocket connection lost. Emulator may be unavailable."):($t==="reconnecting"||$t==="connecting")&&C.info("Emulator websocket is reconnecting...")}})}catch($t){return p.error({err:$t},"Failed to create Android driver, failing attempt"),{status:"FAILED",results:[]}}let $=await e.startAttempt({emulatorName:Lr.emulatorName,runAttemptId:ao});so=so.child($.loggerBindings||{});let Sa=await Cu({driver:Lr.driver,onLogs:$t=>{$.appendLogs($t)}}),an=new bi({variablesFromEnvironment:Y,envName:te,testName:t.name}),bf=await ea.init({driver:Lr.driver,generator:jt,logger:so,limbarClient:Lr.limbarClient,playwrightDevice:Lr.playwrightDevice,orgId:u,adbPort:Lr.adbPort,options:{emulator:V},aiSettings:{...b.config.ai,useMemory:b.config.ai?.useMemory!==!1,...t.settings?.ai},fixtures:{storage:Je,browserEnricher:Ue,browserGenerator:_t,localCodeEvalTools:lt,testContext:an}}),ul;try{ul=await yd({containerName:`mobile test ${t.name}`,fixtures:{controller:bf,logger:so,cacheStorage:pe,usageTracker:g},work:{},inputs:{testName:t.name,steps:t.steps,orgId:u,testMetadata:t},tracer:$,callbacks:{driver:{onHeartbeatFailure:()=>{let $t="Appium heartbeat connection lost \u2014 possible ADB tunnel/emulator failure";C.warn($t)},onHeartbeatRestored:()=>{let $t="Appium heartbeat connection restored";C.info($t)}}}})}finally{await Sa(),await Lr.cleanup(),await bf.cleanup()}return await $.finish({logger:so,results:ul.results,status:ul.status,assetDetails:{avdId:io,tag:Xo?.tag,channel:Xo?.channel}}),ul}import{debounce as UW}from"ts-debounce";var cl="0.16.3";function FW(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 BW(r){switch(r){case"SUCCESS":return"PASSED";case"FAILED":return"FAILED";case"CANCELLED":return"CANCELLED";case"RUNNING":return"RUNNING";case"IDLE":return"PENDING"}}var hf=class{constructor(e,t,n,o){this.keepalive=e;this.testId=t;this.testName=n;this.diskStorage=o;this.interactionTracer=new Vo,Pr.initializeRootTracerContext(this.interactionTracer)}children=[];finished=!1;interactionTracer;getParentStepIdChain(){return[]}attachBeforeScreenshot(e){let{snapshotId:t,screenshot:n}=e;this.diskStorage.storeFile({name:`${as}/${t}.jpeg`,contents:n})}attachAfterScreenshot(e){let{snapshotId:t,screenshot:n}=e;this.diskStorage.storeFile({name:`${as}/${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:BW(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 ha(this.keepalive,this.testId,this.testName,this.diskStorage);return this.children.push(e),e}},ha=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(`${as}/${t}.jpeg`)}getParentStepIdChain(){return[]}async startStep(e){this.keepalive();let t=new hf(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:FW(e.status),finishedAt:e.finishedAt}))))}},ff=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(`
4416
4416
  `);this.logStream.write(t+`
4417
4417
  `)}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,assetDetails:e.assetDetails,finishedAt:new Date,results:Yu(o,t),beforeResults:i?Yu(i,t):void 0,afterResults:a?Yu(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 ha(this.keepalive,this.testId,this.testName,this.diskStorage);return this.children.push(e),e}async startMainStepList(){let e=new ha(this.keepalive,this.testId,this.testName,this.diskStorage);return this.children.push(e),e}async startAfterStepList(){let e=new ha(this.keepalive,this.testId,this.testName,this.diskStorage);return this.children.push(e),e}async getScreenshot(e,t){return this.diskStorage.readFile(`${as}/${t}.jpeg`)}},Sf=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){let{runAttemptId:t}=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 n=this.diskStorage.cd(`attempts/${this.metadata.attempts}`),o={id:t,schemaVersion:On,runAttemptSchemaVersion:rT,startedAt:new Date,status:"RUNNING"};n.storeFile({name:"metadata.json",contents:JSON.stringify(o,null,2)});let i=UW(async()=>{await this.client.extendAndroidEmulatorTtl(e.emulatorName)},3e4,{maxWait:6e4}),a=new ff(()=>void i(),this.testId,this.testName,t,o,n);return this.children.push(a),a}},Bd=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:ar.CLI,startedAt:new Date,status:"RUNNING",cliVersion:cl,labels:a??[]},c=new el(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:cl,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 Sf(this.client,e.testId,e.testName,e.runId,n,t);return this.children.push(o),o}};async function B_(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 En(){try{await B(Promise.all([mT(),gt.flush()]),{milliseconds:5e3})}catch{}}async function z_(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:m}=e;HW(d)&&C.warn(`Output directory ${d} already exists, removing before test execution...`);let p=bT({items:n.testDefinitions,shardIndex:e.shardIndex??1,shardCount:e.shardCount??1,sortKey:Z=>Z.relativeFilePath}),g=s.child({orgId:c,runGroupId:l,branch:u.gitBranchName}),h=await Bd.start({logger:g,orgId:c,runGroupId:l,outputDir:d,client:a,gitMetadata:u,labels:[]}),f=[],E=new Date,b=new Set,w=async()=>GW({runResults:f,startTime:E,ranTests:b,apiClient:a,uploadResults:e.uploadResults??!1,outputDir:d}),x=[],A=async Z=>{C.warn(`${Z} Stopping tests and printing latest results.`),await h.finish({logger:g,status:"CANCELLED"}),await w(),await Promise.allSettled(x.map(te=>te())),await En(),process.exit(1)},M=async()=>{await A("SIGINT received.")};process.once("SIGINT",M);let v;if(e.timeoutMinutes!==void 0&&e.timeoutMinutes>0){let Z=e.timeoutMinutes*60*1e3;v=setTimeout(()=>{A(`Timeout of ${e.timeoutMinutes} minute(s) reached.`)},Z)}let _={};for(let Z=0;Z<p.length;Z++){let te=Object.values(_);te.length===m&&await Promise.race(te.map(H=>H.promise));let yt=p[Z],Y=`test-${Z}`;_[Y]={done:!1,promise:(async({testDefinition:H})=>{b.add(Y);let ce=H.relativeFilePath.includes("..")?H.fullFilePath:H.relativeFilePath;ls({status:"START",testLogRef:ce,getRunningTestsCount:()=>b.size,getTotalTestsCount:()=>p.length});let pe=setInterval(()=>ls({status:"RUN",testLogRef:ce,getRunningTestsCount:()=>b.size,getTotalTestsCount:()=>p.length}),5*60*1e3),Je=zW(),Re=g.child({testId:H.id,runId:Je}),jt=new vu({logger:Re,reporter:new dd(a),runType:"mobile-test-run",runId:Je,testMetadata:H,suiteMetadata:void 0});try{let _t=await F_({metadata:{...o,runId:Je},fixtures:{...t,tracer:h,logger:Re,usageTracker:jt},inputs:{...n,project:i,testDefinition:H,channel:n.channel??H.settings?.defaultChannel,tag:n.tag??H.settings?.defaultTag,logUpdate:(Ue,lt)=>ls({status:Ue,testLogRef:ce,getRunningTestsCount:()=>b.size,getTotalTestsCount:()=>p.length,additionalText:lt}),runSigIntHandlers:x},options:e});ls({status:_t.status,testLogRef:ce,getRunningTestsCount:()=>b.size,getTotalTestsCount:()=>p.length}),f.push(_t)}catch(_t){let Ue=`Encountered unexpected fatal error when running test '${H.name}': ${_t.message}
4418
4418
  ${_t.stack}`;C.error(Ue),Re.error({err:_t},`Encountered unexpected fatal error when running test ${H.name}`),await A("Fatal error occurred.")}finally{clearInterval(pe),_[Y].done=!0,delete _[Y]}await jt.flush(s)})({testDefinition:yt})}}await Promise.allSettled(Object.values(_).map(Z=>Z.promise)),v&&clearTimeout(v);let V=f.some(Z=>Z.status==="FAILED"&&!Z.quarantined)?"FAILED":"PASSED";return await h.finish({logger:g,status:V}),process.off("SIGINT",M),w()}async function GW({runResults:r,startTime:e,ranTests:t,apiClient:n,uploadResults:o,outputDir:i}){let a=n.getAppUrl(),s=pT({results:r,startTime:e.getTime(),onFailed:c=>{},getDisplayLine:c=>{let l=`${gp}- ${c.filePath}`;return c.runId&&(l+=` ( link when uploaded: ${a}/runs/${c.runId} )`),l},entity:"mobile test"});return C.log(""),o?(C.success(`Test results have been saved to the folder ${i}. Uploading to Momentic Cloud...`),await Md({client:n,consoleLogger:C,resultsPath:i})):C.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 yf(){DC(),ST("Chromium")||(xo?(await fc("The Chromium browser is not installed but is required for automating webviews. Install it now?")||process.exit(1),await yc({rawBrowsers:["chromium"],force:!1,all:!1})):(C.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)))}Rw({serviceName:"mobile-cli"});ur.setApp("mobile-cli");var Tn=new VW;Tn.name("momentic-mobile").description("Momentic Mobile CLI").version(cl);var KW=Tn.command("assets").description("Manage mobile testing assets");KW.command("upload").description("Upload an asset for mobile tests").argument("<file>","Path to the asset file to upload").addOption(sl).addOption(ll).addOption(uf).addOption(x_).action(async(r,e)=>{let{apiKey:t,server:n,tag:o,channel:i}=e,a=Hd.resolve(r);zd.existsSync(a)||(C.error(`File not found: ${a}`),process.exit(1));let s=new Yt({baseUrl:n,apiKey:t,logger:C});/\.apk$/i.test(a)||(C.error(`File is not an APK file: ${a}`),process.exit(1)),await wu({tag:o?.toLowerCase(),channel:i.toLowerCase(),filePath:a,apiClient:s,logger:C})});Tn.command("app").addOption(sl).addOption(ll).addOption(af).addOption(Fd).addOption(gf).addOption(sf).addOption(lf).addOption(cf).action(async r=>{let{apiKey:e,server:t,yes:n,disableCache:o,saveCache:i,regenerateCache:a}=r,s=fp(r.logLevel);ur.setApp("mobile-desktop-server");let c=new Yt({baseUrl:t,apiKey:e,logger:ur});await Ph({client:c,skipPrompts:n}),C.debug("API key check complete");let l=qW(import.meta.url),u=Hd.dirname(l),d=Hd.resolve(u,"..","static");await yf(),C.debug({appiumHome:Us},"Resolved resource paths");let m=await la({configFilePath:r.config}),p=C_;await w_({momenticServerUrl:t,serverPort:p,apiKey:e,staticDir:d,initialProject:m,driverLogLevel:s,logger:ur,regenerateCache:a,noCache:o,alwaysSaveCache:i});let g=`http://localhost:${p}`;C.info(`Local app started on: ${g}`),await $W(g)});var H_=Tn.command("results").description("Merge and upload test results.");H_.command("merge").description("Merge test results files.").addOption(df).addArgument(new Gd("<resultsPath>","Path to a directory that contains on or more test results archives.").argRequired()).action(async(r,e)=>{let{outputDir:t}=e;t||(C.error("Output directory is required."),process.exit(1)),zd.existsSync(r)||(C.warn("Results path does not exist, skipping merge."),process.exit(0)),zd.existsSync(t)&&C.warn(`Output directory ${t} already exists, removing before merging...`),t_(ur,t,r),await En(),process.exit(0)});var YW=new Gd("<results>","Path to the results archive.").argRequired();H_.command("upload").description("Upload test results to Momentic cloud.").addOption(sl).addOption(ll).addArgument(YW).action(async(r,e)=>{let{apiKey:t,server:n}=e,o=ur,i=new Yt({baseUrl:n,apiKey:t,logger:o});await Md({consoleLogger:C,resultsPath:r,client:i}),await En(),process.exit(0)});var XW=Tn.command("list").description("List mobile test paths");XW.addOption(Fd).addOption(of).addOption(mf).addOption(pf).addArgument(new Gd("[tests...]","One or more test file path or folders that exist on the local machine.").argOptional()).action(async(r,e)=>{let t=await la({configFilePath:e.config,nameFilter:e.filter}),n=await Xt(t),o=await nf({tests:r,momenticFiles:n,yes:!0,include:e.include,exclude:e.exclude,project:t,logger:C,quarantinedTestReasons:{}});C.info(o.map(i=>i.relativeFilePath).join(`