momentic-mobile 0.12.0 → 0.12.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/bin/cli.js CHANGED
@@ -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",ka(e,...t))}error(e,...t){this._log("error",ka(e,...t))}info(e,...t){this._log("info",ka(e,...t))}log(e,...t){this._log("log",ka(e,...t))}warn(e,...t){this._log("warn",ka(e,...t))}getBuffer(){return this._buffer.length>0?this._buffer:void 0}};function RE(r){let e=globalThis.console,t=new Gl;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 Fp=" ".repeat(6);import pN from"fetch-retry";import mN from"os";import xE,{multistream as gN}from"pino";import hN from"pino-pretty";import fN from"pino-std-serializers";var ui=new Map,SN=!0,ME="Log throttle exceeded",yN=100,bN=5e3,EN=pN(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}}),Bp=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??mN.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=SN?xE(a):xE(a,gN([{stream:hN({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 EN(this.site,{method:"POST",headers:{"Content-Type":"application/json","signoz-access-token":"CumAaTMUcwjt05OddAmefKgshbhfRmWxzxih"},body:uo(e),signal:AbortSignal.timeout(5e3)});if(!t.ok)throw new Error(`Got error status (${t.statusText}) from SigNoz`)}catch{}}shouldAllowLog(e){if(e===ME)return!0;let t=Date.now();return t-this.lastWindowStart>bN&&(this.logsInCurrentWindow=0,this.droppedLogsInWindow&&this.log("error",void 0,ME),this.droppedLogsInWindow=!1,this.lastWindowStart=t),this.logsInCurrentWindow<yN?(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(La[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=fN.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:hb({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,ui.set("app",this),ui.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=fb[e]):(this.minLevelValue=La[e],this.consoleLogger.level=e)}enableConsoleLogs(){this.disableConsoleLogs=!1}},di=({app:r,hostname:e,disableConsoleLogs:t})=>(ui.has(r)||ui.set(r,new Bp({bindings:{app:r},hostname:e,disableConsoleLogs:t})),ui.get(r));async function _E(){await Promise.all([...ui.values()].map(r=>r.flush()))}import{hostname as TN}from"os";var lr=di({app:"cli",hostname:TN(),disableConsoleLogs:!0}).child({cliVersion:"0.12.0"});function zp(r){if(!r)return;r=r.toLowerCase();let e=Nl.safeParse(r);if(e.success)return w.setMinLevel(e.data),e.data}function PE({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 RE(()=>{if(c.forEach(u=>{w.log(""),o(u)}),c.length){w.log("");let u=c.length===1?"":"s";w.error(`${c.length} ${t}${u} failed:`),c.forEach(d=>{w.dimmed(n(d))})}if(l.length){w.log("");let u=l.length===1?"":"s";w.warn(`${l.length} ${t}${u} cancelled:`),l.forEach(d=>{w.dimmed(n(d))})}if(a.length){w.log("");let u=a.length===1?"":"s";w.success(`${a.length} ${t}${u} passed:`),a.forEach(d=>{w.dimmed(n(d))})}if(s.length){w.log("");let u=s.length===1?"":"s";w.warn(`${s.length} quarantined ${t}${u} failed:`),s.forEach(d=>{w.dimmed(n(d))})}if(i.length){w.log("");let u=i.length===1?"":"s";w.warn(`${i.length} quarantined ${t}${u} passed:`),i.forEach(d=>{w.dimmed(n(d))})}w.log(""),w.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 Ua=({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):(w.warn(`Unknown status tried to be logged in run test locally: ${r}`),a=0),vN||(i=`${i}`),w.log(`${i}${" ".repeat(a)} ${e} ${o?`${o} `:""}(${t()}/${n()})`)};import AN from"fs";import{tmpdir as wN}from"os";import CN from"path";import{registry as Fa}from"playwright-core/lib/server";import IE from"proper-lockfile";var OE=CN.join(wN(),"momenticBrowserInstallation");var Hp=["chrome","chromium","chrome-for-testing","ffmpeg"],RN={Chromium:"chromium","Google Chrome":"chrome","Chrome for Testing":"chrome-for-testing"},LE={chrome:"chrome",chromium:"chromium","chrome-for-testing":"chromium-headless-shell",ffmpeg:"ffmpeg"};function NE(r){let e=LE[RN[r]??""]??"",t=Fa.findExecutable(e);return!t||t.installType==="none"?!1:Gp(t)}function Gp(r){let e=r.executablePath();return AN.existsSync(e)}function xN(r,e){let t=LE[r];if(!t)throw new Error(`Requested install of unknown browser type ${r}`);let n=Fa.findExecutable(t);if(!n||n.installType==="none")throw new Error(`Requested install of unknown browser type ${r}`);if(!(!e&&Gp(n)))return n}async function MN({browser:r,force:e}){let t=xN(r,e);if(!t){w.info(`Browser '${r}' is already installed, skipping...`);return}w.info(`Installing browser '${r}'...`);try{await Fa.installDeps([t],!1),await Fa.install([t],!1)}catch(n){if(n.message.includes("Lock file is already being held")){w.warn("Another process is installing Playwright browsers. Waiting for completion before proceeding..");let o=Fa.findExecutable(r),i=5*60*1e3,a=Date.now();for(;Date.now()-a<i&&!Gp(o);)w.info("Waiting for browser to finish installing..."),await new Promise(s=>setTimeout(s,5e3))}else throw n}}async function Vl({rawBrowsers:r,force:e=!1,all:t=!1}){let n=t?Hp:Array.from(new Set(r));try{await IE.lock(OE,{stale:1e3*60*5,update:1e3*60,realpath:!1,retries:{retries:30,factor:2,maxTimeout:15e3,minTimeout:500}})}catch(i){w.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 MN({browser:i,force:e})}catch(a){o=a,w.error(`Failed to install the ${i} browser: ${a}`)}}finally{await IE.unlock(OE,{realpath:!1})}if(o)throw o}import{createServer as _N}from"http";async function Wl(r,e,t=30){for(let n=0;n<t;n+=1){let o=r+n;if(await jl(o))return o}w.error(`Could not find an available port for ${e} starting from ${r} after ${t} attempts`),process.exit(1)}async function jl(r){return new Promise((e,t)=>{let n=_N();n.once("error",o=>{o.code==="EADDRINUSE"?e(!1):(w.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 Jee from"blocked-at";import Zee from"why-is-node-running";import FU from"fs";import{tmpdir as BU,totalmem as zU}from"os";import HU from"path";import{execFile as PN}from"child_process";import IN from"path";function ON(){let r=process.env.ANDROID_HOME;if(!r)return"adb";let e=process.platform==="win32"?"adb.exe":"adb";return IN.join(r,"platform-tools",e)}async function ht(r,{timeoutMs:e=5e3,serial:t,throwOnError:n=!1}){let o=ON(),i=t?["-s",t,...r]:r;return await new Promise((a,s)=>{PN(o,i,{encoding:"utf8",timeout:e},(c,l)=>{if(c){if(n){s(c);return}a(void 0);return}a(l)})})}import{createInstanceClient as rU}from"@limrun/api";import{execSync as nU}from"child_process";import mte,{multistream as hte}from"pino";import Ste from"pino-pretty";var Ete=5*1024,LN="...[truncated]",Tte=Buffer.byteLength(LN,"utf8");import{PostHog as Ite}from"posthog-node";var Pn=class extends Error{constructor(e){super(e),this.name="TimeoutError"}};var DE=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 z(r,e){let{milliseconds:t,fallback:n,message:o,customTimers:i={setTimeout,clearTimeout}}=e,a;if(typeof t!="number"||Math.sign(t)!==1)throw new TypeError(`Expected \`milliseconds\` to be a positive number, got \`${t}\``);return new Promise((s,c)=>{let l;if(e.signal){let{signal:p}=e;if(p.aborted)return c(DE(p));l=()=>c(DE(p)),p.addEventListener("abort",l,{once:!0})}let u=()=>{if(e.signal&&e.signal.removeEventListener("abort",l),n)try{s(n())}catch(p){c(p)}else{typeof r.cancel=="function"&&Promise.resolve().then(()=>r.cancel()).catch(()=>{});let p=o instanceof Error?o:new Pn(o??`Promise timed out after ${t}ms`);c(p)}};t<1/0&&(a=i.setTimeout(u,t));let d=()=>{i.clearTimeout(a),e.signal&&e.signal.removeEventListener("abort",l)};Promise.resolve(r).then(p=>{d(),s(p)}).catch(p=>{d(),c(p)})})}import{PostHog as zte}from"posthog-node";import{execSync as NN}from"child_process";import mi from"os";import DN from"v8";var kE,Fr,FE=mi.platform(),kN=mi.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),{}),UE=r=>{try{let e={},t=!1,n=UN(),o=FN(),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=DN.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"),po&&w.warn(`Low machine resources detected (memory: ${i} free, cpu: ${a} free)`)):r.debug({memory:n,cpu:o},"Got machine resource usage metrics")}catch{}};function BE(r){if(!kr)return UE(r),{interval:setInterval(()=>UE(r),2e4),cpuMetadata:kN,platform:FE}}function UN(){let r=mi.totalmem(),e=FE==="darwin"?BN():(()=>{let n=mi.freemem();return{availableMemory:n,rawFreeMemory:n,cachedMemory:0}})(),t=e.availableMemory/r;return{totalMemory:r,freeMemory:e.availableMemory,freePercentage:t}}function FN(){let r=mi.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,!Fr)return Fr=t,null;let n={user:t.user-Fr.user,nice:t.nice-Fr.nice,sys:t.sys-Fr.sys,idle:t.idle-Fr.idle,irq:t.irq-Fr.irq,total:t.total-Fr.total};return kE={measurementTime:e,intervalMs:e-Fr.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},Fr=t,kE}function BN(){try{let r=NN("/usr/bin/vm_stat",{encoding:"utf8",stdio:["pipe","pipe","ignore"]}),t=r.match(/page size of (\d+) bytes/)?.[1],n=t?Number.parseInt(t,10):4096,o=u=>{let p=r.match(new RegExp(`${u}:\\s+(\\d+)\\.`,"i"))?.[1];return p?Number.parseInt(p,10):0},i=o("Pages free"),a=o("Pages inactive"),s=o("Pages speculative"),c=i*n,l=(a+s)*n;return{availableMemory:c+l,rawFreeMemory:c,cachedMemory:l}}catch{let e=mi.freemem();return{availableMemory:e,rawFreeMemory:e,cachedMemory:0}}}var $l=class{increment(e,t,n){}gauge(e,t){}distribution(e,t,n){}async flush(){}async recordDuration({fn:e}){return await e()}};function zN(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 ql(r,e){let t=zN(r);return!e||Object.keys(e).length===0?t:{...e,...t}}var pT="=",Jl=";",em=",";var mT=8192;var Si={};jM(Si,{getKeyPairs:()=>bD,parseKeyPairsIntoRecord:()=>ED,parsePairKeyValue:()=>gT,serializeKeyPairs:()=>yD});_e();var SD=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 yD(r){return r.reduce(function(e,t){var n=""+e+(e!==""?em:"")+t;return n.length>mT?e:n},"")}function bD(r){return r.getAllEntries().map(function(e){var t=SD(e,2),n=t[0],o=t[1],i=encodeURIComponent(n)+"="+encodeURIComponent(o.value);return o.metadata!==void 0&&(i+=Jl+o.metadata.toString()),i})}function gT(r){var e=r.split(Jl);if(!(e.length<=0)){var t=e.shift();if(t){var n=t.indexOf(pT);if(!(n<=0)){var o=decodeURIComponent(t.substring(0,n).trim()),i=decodeURIComponent(t.substring(n+1).trim()),a;return e.length>0&&(a=Wp(e.join(Jl))),{key:o,value:i,metadata:a}}}}}function ED(r){return typeof r!="string"||r.length===0?{}:r.split(em).map(function(e){return gT(e)}).filter(function(e){return e!==void 0&&e.value.length>0}).reduce(function(e,t){return e[t.key]=t.value,e},{})}_e();var Ql;(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"})(Ql||(Ql={}));var TD=",",vD=["OTEL_SDK_DISABLED"];function AD(r){return vD.indexOf(r)>-1}var wD=["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 CD(r){return wD.indexOf(r)>-1}var RD=["OTEL_NO_PATCH_MODULES","OTEL_PROPAGATORS"];function xD(r){return RD.indexOf(r)>-1}var tm=1/0,rm=128,MD=128,_D=128,nm={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:tm,OTEL_ATTRIBUTE_COUNT_LIMIT:rm,OTEL_SPAN_ATTRIBUTE_VALUE_LENGTH_LIMIT:tm,OTEL_SPAN_ATTRIBUTE_COUNT_LIMIT:rm,OTEL_LOGRECORD_ATTRIBUTE_VALUE_LENGTH_LIMIT:tm,OTEL_LOGRECORD_ATTRIBUTE_COUNT_LIMIT:rm,OTEL_SPAN_EVENT_COUNT_LIMIT:128,OTEL_SPAN_LINK_COUNT_LIMIT:128,OTEL_SPAN_ATTRIBUTE_PER_EVENT_COUNT_LIMIT:MD,OTEL_SPAN_ATTRIBUTE_PER_LINK_COUNT_LIMIT:_D,OTEL_TRACES_EXPORTER:"",OTEL_TRACES_SAMPLER:Ql.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 PD(r,e,t){if(!(typeof t[r]>"u")){var n=String(t[r]);e[r]=n.toLowerCase()==="true"}}function ID(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 OD(r,e,t,n){n===void 0&&(n=TD);var o=t[r];typeof o=="string"&&(e[r]=o.split(n).map(function(i){return i.trim()}))}var LD={ALL:Fe.ALL,VERBOSE:Fe.VERBOSE,DEBUG:Fe.DEBUG,INFO:Fe.INFO,WARN:Fe.WARN,ERROR:Fe.ERROR,NONE:Fe.NONE};function ND(r,e,t){var n=t[r];if(typeof n=="string"){var o=LD[n.toUpperCase()];o!=null&&(e[r]=o)}}function hT(r){var e={};for(var t in nm){var n=t;switch(n){case"OTEL_LOG_LEVEL":ND(n,e,r);break;default:if(AD(n))PD(n,e,r);else if(CD(n))ID(n,e,r);else if(xD(n))OD(n,e,r);else{var o=r[n];typeof o<"u"&&o!==null&&(e[n]=String(o))}}}return e}function Et(){var r=hT(process.env);return Object.assign({},nm,r)}function fT(r){return r>=48&&r<=57?r-48:r>=97&&r<=102?r-87:r-55}function Zl(r){for(var e=new Uint8Array(r.length/2),t=0,n=0;n<r.length;n+=2){var o=fT(r.charCodeAt(n)),i=fT(r.charCodeAt(n+1));e[t++]=o<<4|i}return e}var ST="1.25.1";var DD="deployment.environment";var kD="process.runtime.name";var UD="service.name";var FD="service.instance.id";var BD="telemetry.sdk.name",zD="telemetry.sdk.language",HD="telemetry.sdk.version";var yT=DD;var bT=kD;var ec=UD;var ET=FD;var ja=BD,$a=zD,qa=HD;var GD="nodejs";var TT=GD;var yi,tc=(yi={},yi[ja]="opentelemetry",yi[bT]="node",yi[$a]=TT,yi[qa]=ST,yi);var VD=9,WD=6,jD=Math.pow(10,WD),$D=Math.pow(10,VD);function vT(r){var e=r/1e3,t=Math.trunc(e),n=Math.round(r%1e3*jD);return[t,n]}function AT(r){return r[0]*$D+r[1]}function Ka(r){return r[0]*1e6+r[1]/1e3}var go;(function(r){r[r.SUCCESS=0]="SUCCESS",r[r.FAILED=1]="FAILED"})(go||(go={}));var wT=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 qD=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},KD=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))},CT=function(){function r(e,t){this._callback=e,this._that=t,this._isCalled=!1,this._deferred=new wT}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,KD([this._that],qD(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 cr;(function(r){r[r.DELTA=0]="DELTA",r[r.CUMULATIVE=1]="CUMULATIVE"})(cr||(cr={}));var _t;(function(r){r[r.HISTOGRAM=0]="HISTOGRAM",r[r.EXPONENTIAL_HISTOGRAM=1]="EXPONENTIAL_HISTOGRAM",r[r.GAUGE=2]="GAUGE",r[r.SUM=3]="SUM"})(_t||(_t={}));var YD=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 uoe=function(r){YD(e,r);function e(t){var n=r.call(this,t)||this;return Object.setPrototypeOf(n,e.prototype),n}return e}(Error);function RT(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}_e();var ur;(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"})(ur||(ur={}));var xT=function(){function r(){this.kind=ur.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 se;(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"})(se||(se={}));var XD=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 JD(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 om=function(){function r(e,t,n,o){n===void 0&&(n=!0),o===void 0&&(o=JD(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=RT(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 im=function(){function r(e,t){this._boundaries=e,this._recordMinMax=t,this.kind=ur.HISTOGRAM}return r.prototype.createAccumulation=function(e){return new om(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 om(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 om(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:_t.HISTOGRAM,dataPoints:n.map(function(i){var a=XD(i,2),s=a[0],c=a[1],l=c.toPointValue(),u=e.type===se.GAUGE||e.type===se.UP_DOWN_COUNTER||e.type===se.OBSERVABLE_GAUGE||e.type===se.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}();_e();var am=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},sm=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))},lm=function(){function r(e,t,n,o){e===void 0&&(e=new QD),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 QD=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,sm([n,this._counts.length-t],am(this._counts.slice(t)),!1)),o.splice.apply(o,sm([0,t],am(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(sm([],am(this._counts),!1))},r}();var MT=52,ZD=2146435072,e0=1048575,cm=1023,rc=-cm+1,nc=cm,Ya=Math.pow(2,-1022);function oc(r){var e=new DataView(new ArrayBuffer(8));e.setFloat64(0,r);var t=e.getUint32(0),n=(t&ZD)>>20;return n-cm}function ic(r){var e=new DataView(new ArrayBuffer(8));e.setFloat64(0,r);var t=e.getUint32(0),n=e.getUint32(4),o=(t&e0)*Math.pow(2,32);return o+n}function Xa(r,e){return r===0||r===Number.POSITIVE_INFINITY||r===Number.NEGATIVE_INFINITY||Number.isNaN(r)?r:r*Math.pow(2,e)}function PT(r){return r--,r|=r>>1,r|=r>>2,r|=r>>4,r|=r>>8,r|=r>>16,r++,r}var t0=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)}}(),In=function(r){t0(e,r);function e(){return r!==null&&r.apply(this,arguments)||this}return e}(Error);var OT=function(){function r(e){this._shift=-e}return r.prototype.mapToIndex=function(e){if(e<Ya)return this._minNormalLowerBoundaryIndex();var t=oc(e),n=this._rightShift(ic(e)-1,MT);return t+n>>this._shift},r.prototype.lowerBoundary=function(e){var t=this._minNormalLowerBoundaryIndex();if(e<t)throw new In("underflow: "+e+" is < minimum lower boundary: "+t);var n=this._maxNormalLowerBoundaryIndex();if(e>n)throw new In("overflow: "+e+" is > maximum lower boundary: "+n);return Xa(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=rc>>this._shift;return this._shift<2&&e--,e},r.prototype._maxNormalLowerBoundaryIndex=function(){return nc>>this._shift},r.prototype._rightShift=function(e,t){return Math.floor(e*Math.pow(2,-t))},r}();var LT=function(){function r(e){this._scale=e,this._scaleFactor=Xa(Math.LOG2E,e),this._inverseFactor=Xa(Math.LN2,-e)}return r.prototype.mapToIndex=function(e){if(e<=Ya)return this._minNormalLowerBoundaryIndex()-1;if(ic(e)===0){var t=oc(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 In("overflow: "+e+" is > maximum lower boundary: "+t)}var n=this._minNormalLowerBoundaryIndex();if(e<=n){if(e===n)return Ya;if(e===n-1)return Math.exp((e+(1<<this._scale))/this._scaleFactor)/2;throw new In("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 rc<<this._scale},r.prototype._maxNormalLowerBoundaryIndex=function(){return(nc+1<<this._scale)-1},r}();var NT=-10,DT=20,r0=Array.from({length:31},function(r,e){return e>10?new LT(e-10):new OT(e-10)});function um(r){if(r>DT||r<NT)throw new In("expected scale >= "+NT+" && <= "+DT+", got: "+r);return r0[r+10]}var n0=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},ac=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}(),o0=20,i0=160,dm=2,a0=function(){function r(e,t,n,o,i,a,s,c,l,u,d){e===void 0&&(e=e),t===void 0&&(t=i0),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 lm),u===void 0&&(u=new lm),d===void 0&&(d=um(o0)),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<dm&&(V.warn("Exponential Histogram Max Size set to "+this._maxSize+", changing to the minimum size of: "+dm),this._maxSize=dm)}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=PT(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=um(t)}},r.prototype._minScale=function(e){var t=Math.min(this.scale,e.scale),n=ac.combine(this._highLowAtScale(this.positive,this.scale,t),this._highLowAtScale(e.positive,e.scale,t)),o=ac.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 ac(0,-1);var o=t-n;return new ac(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 kT=function(){function r(e,t){this._maxSize=e,this._recordMinMax=t,this.kind=ur.EXPONENTIAL_HISTOGRAM}return r.prototype.createAccumulation=function(e){return new a0(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:_t.EXPONENTIAL_HISTOGRAM,dataPoints:n.map(function(i){var a=n0(i,2),s=a[0],c=a[1],l=c.toPointValue(),u=e.type===se.GAUGE||e.type===se.UP_DOWN_COUNTER||e.type===se.OBSERVABLE_GAUGE||e.type===se.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 s0=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},pm=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=vT(Date.now())},r.prototype.setStartTime=function(e){this.startTime=e},r.prototype.toPointValue=function(){return this._current},r}();var UT=function(){function r(){this.kind=ur.LAST_VALUE}return r.prototype.createAccumulation=function(e){return new pm(e)},r.prototype.merge=function(e,t){var n=Ka(t.sampleTime)>=Ka(e.sampleTime)?t:e;return new pm(e.startTime,n.toPointValue(),n.sampleTime)},r.prototype.diff=function(e,t){var n=Ka(t.sampleTime)>=Ka(e.sampleTime)?t:e;return new pm(t.startTime,n.toPointValue(),n.sampleTime)},r.prototype.toMetricData=function(e,t,n,o){return{descriptor:e,aggregationTemporality:t,dataPointType:_t.GAUGE,dataPoints:n.map(function(i){var a=s0(i,2),s=a[0],c=a[1];return{attributes:s,startTime:c.startTime,endTime:o,value:c.toPointValue()}})}},r}();var l0=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},Ja=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 mm=function(){function r(e){this.monotonic=e,this.kind=ur.SUM}return r.prototype.createAccumulation=function(e){return new Ja(e,this.monotonic)},r.prototype.merge=function(e,t){var n=e.toPointValue(),o=t.toPointValue();return t.reset?new Ja(t.startTime,this.monotonic,o,t.reset):new Ja(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 Ja(t.startTime,this.monotonic,o,!0):new Ja(t.startTime,this.monotonic,o-n)},r.prototype.toMetricData=function(e,t,n,o){return{descriptor:e,aggregationTemporality:t,dataPointType:_t.SUM,dataPoints:n.map(function(i){var a=l0(i,2),s=a[0],c=a[1];return{attributes:s,startTime:c.startTime,endTime:o,value:c.toPointValue()}}),isMonotonic:this.monotonic}},r}();var ho=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)}}(),zr=function(){function r(){}return r.Drop=function(){return jT},r.Sum=function(){return $T},r.LastValue=function(){return qT},r.Histogram=function(){return KT},r.ExponentialHistogram=function(){return c0},r.Default=function(){return u0},r}();var FT=function(r){ho(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 xT,e}(zr);var BT=function(r){ho(e,r);function e(){return r!==null&&r.apply(this,arguments)||this}return e.prototype.createAggregator=function(t){switch(t.type){case se.COUNTER:case se.OBSERVABLE_COUNTER:case se.HISTOGRAM:return e.MONOTONIC_INSTANCE;default:return e.NON_MONOTONIC_INSTANCE}},e.MONOTONIC_INSTANCE=new mm(!0),e.NON_MONOTONIC_INSTANCE=new mm(!1),e}(zr);var zT=function(r){ho(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 UT,e}(zr);var HT=function(r){ho(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 im([0,5,10,25,50,75,100,250,500,750,1e3,2500,5e3,7500,1e4],!0),e}(zr);var GT=function(r){ho(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 im(this._boundaries,this._recordMinMax)},e}(zr);var VT=function(r){ho(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 kT(this._maxSize,this._recordMinMax)},e}(zr);var WT=function(r){ho(e,r);function e(){return r!==null&&r.apply(this,arguments)||this}return e.prototype._resolve=function(t){switch(t.type){case se.COUNTER:case se.UP_DOWN_COUNTER:case se.OBSERVABLE_COUNTER:case se.OBSERVABLE_UP_DOWN_COUNTER:return $T;case se.GAUGE:case se.OBSERVABLE_GAUGE:return qT;case se.HISTOGRAM:return t.advice.explicitBucketBoundaries?new GT(t.advice.explicitBucketBoundaries):KT}return V.warn("Unable to recognize instrument type: "+t.type),jT},e.prototype.createAggregator=function(t){return this._resolve(t).createAggregator(t)},e}(zr);var jT=new FT,$T=new BT,qT=new zT,KT=new HT,c0=new VT,u0=new WT;_e();function sc(){return"unknown_service:"+process.argv0}var On=function(){return On=Object.assign||function(r){for(var e,t=1,n=arguments.length;t<n;t++){e=arguments[t];for(var o in e)Object.prototype.hasOwnProperty.call(e,o)&&(r[o]=e[o])}return r},On.apply(this,arguments)},d0=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())})},p0=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}}},m0=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},gm=function(){function r(e,t){var n=this,o;this._attributes=e,this.asyncAttributesPending=t!=null,this._syncAttributes=(o=this._attributes)!==null&&o!==void 0?o:{},this._asyncAttributesPromise=t?.then(function(i){return n._attributes=Object.assign({},n._attributes,i),n.asyncAttributesPending=!1,i},function(i){return V.debug("a resource's async attributes promise rejected: %s",i),n.asyncAttributesPending=!1,{}})}return r.empty=function(){return r.EMPTY},r.default=function(){var e;return new r((e={},e[ec]=sc(),e[$a]=tc[$a],e[ja]=tc[ja],e[qa]=tc[qa],e))},Object.defineProperty(r.prototype,"attributes",{get:function(){var e;return this.asyncAttributesPending&&V.error("Accessing resource attributes before async attributes settled"),(e=this._attributes)!==null&&e!==void 0?e:{}},enumerable:!1,configurable:!0}),r.prototype.waitForAsyncAttributes=function(){return d0(this,void 0,void 0,function(){return p0(this,function(e){switch(e.label){case 0:return this.asyncAttributesPending?[4,this._asyncAttributesPromise]:[3,2];case 1:e.sent(),e.label=2;case 2:return[2]}})})},r.prototype.merge=function(e){var t=this,n;if(!e)return this;var o=On(On({},this._syncAttributes),(n=e._syncAttributes)!==null&&n!==void 0?n:e.attributes);if(!this._asyncAttributesPromise&&!e._asyncAttributesPromise)return new r(o);var i=Promise.all([this._asyncAttributesPromise,e._asyncAttributesPromise]).then(function(a){var s,c=m0(a,2),l=c[0],u=c[1];return On(On(On(On({},t._syncAttributes),l),(s=e._syncAttributes)!==null&&s!==void 0?s:e.attributes),u)});return new r(o,i)},r.EMPTY=new r({}),r}();var fo;(function(r){r[r.DELTA=0]="DELTA",r[r.CUMULATIVE=1]="CUMULATIVE",r[r.LOWMEMORY=2]="LOWMEMORY"})(fo||(fo={}));_e();var g0=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())})},h0=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}}},hm=function(){return cr.CUMULATIVE},YT=function(r){switch(r){case se.COUNTER:case se.OBSERVABLE_COUNTER:case se.GAUGE:case se.HISTOGRAM:case se.OBSERVABLE_GAUGE:return cr.DELTA;case se.UP_DOWN_COUNTER:case se.OBSERVABLE_UP_DOWN_COUNTER:return cr.CUMULATIVE}},XT=function(r){switch(r){case se.COUNTER:case se.HISTOGRAM:return cr.DELTA;case se.GAUGE:case se.UP_DOWN_COUNTER:case se.OBSERVABLE_UP_DOWN_COUNTER:case se.OBSERVABLE_COUNTER:case se.OBSERVABLE_GAUGE:return cr.CUMULATIVE}};function f0(){var r=Et(),e=r.OTEL_EXPORTER_OTLP_METRICS_TEMPORALITY_PREFERENCE.trim().toLowerCase();return e==="cumulative"?hm:e==="delta"?YT:e==="lowmemory"?XT:(V.warn("OTEL_EXPORTER_OTLP_METRICS_TEMPORALITY_PREFERENCE is set to '"+r.OTEL_EXPORTER_OTLP_METRICS_TEMPORALITY_PREFERENCE+"', but only 'cumulative' and 'delta' are allowed. Using default ('cumulative') instead."),hm)}function S0(r){return r!=null?r===fo.DELTA?YT:r===fo.LOWMEMORY?XT:hm:f0()}function y0(r){return r?.aggregationPreference?r.aggregationPreference:function(e){return zr.Default()}}var JT=function(){function r(e,t){this._otlpExporter=e,this._aggregationSelector=y0(t),this._aggregationTemporalitySelector=S0(t?.temporalityPreference)}return r.prototype.export=function(e,t){this._otlpExporter.export([e],t)},r.prototype.shutdown=function(){return g0(this,void 0,void 0,function(){return h0(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}();_e();_e();var b0=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},QT=1e4,ZT=5,ev=1e3,tv=5e3,rv=1.5;function Qa(r){r===void 0&&(r={});var e={};return Object.entries(r).forEach(function(t){var n=b0(t,2),o=n[0],i=n[1];typeof i<"u"?e[o]=String(i):V.warn('Header "'+o+'" has invalid value ('+i+") and will be ignored")}),e}function fm(r,e){return r.endsWith("/")||(r=r+"/"),r+e}function Sm(r){try{var e=new URL(r);return e.pathname===""&&(e.pathname=e.pathname+"/"),e.toString()}catch{return V.warn("Could not parse export URL: '"+r+"'"),r}}function ym(r){return typeof r=="number"?r<=0?bm(r,QT):r:E0()}function E0(){var r,e=Number((r=Et().OTEL_EXPORTER_OTLP_TRACES_TIMEOUT)!==null&&r!==void 0?r:Et().OTEL_EXPORTER_OTLP_TIMEOUT);return e<=0?bm(e,QT):e}function bm(r,e){return V.warn("Timeout must be greater than 0",r),e}function nv(r){var e=[429,502,503,504];return e.includes(r)}function ov(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 iv=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 CT(this._shutdown,this),this._concurrencyLimit=typeof e.concurrencyLimit=="number"?e.concurrencyLimit:30,this.timeoutMillis=ym(e.timeoutMillis),this.onInit(e)}return r.prototype.export=function(e,t){if(this._shutdownOnce.isCalled){t({code:go.FAILED,error:new Error("Exporter has been shutdown")});return}if(this._sendingPromises.length>=this._concurrencyLimit){t({code:go.FAILED,error:new Error("Concurrent export limit reached")});return}this._export(e).then(function(){t({code:go.SUCCESS})}).catch(function(n){t({code:go.FAILED,error:n})})},r.prototype._export=function(e){var t=this;return new Promise(function(n,o){try{V.debug("items to be sent",e),t.send(e,n,o)}catch(i){o(i)}})},r.prototype.shutdown=function(){return this._shutdownOnce.call()},r.prototype.forceFlush=function(){return Promise.all(this._sendingPromises).then(function(){})},r.prototype._shutdown=function(){return V.debug("shutdown started"),this.onShutdown(),this.forceFlush()},r}();_e();import*as Em from"url";import*as cc from"http";import*as uc from"https";import*as av from"zlib";import{Readable as v0}from"stream";var Ln;(function(r){r.NONE="none",r.GZIP="gzip"})(Ln||(Ln={}));var T0=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(r){T0(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 lc=function(){return lc=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},lc.apply(this,arguments)};function Tm(r,e,t,n,o){var i=r.timeoutMillis,a=new Em.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 bi("Request Timeout");o(h)}else s>=14?l.destroy():l.abort()},i),p={hostname:a.hostname,port:a.port,path:a.pathname,method:"POST",headers:lc({"Content-Type":t},r.headers),agent:r.agent},g=a.protocol==="http:"?cc.request:uc.request,m=function(h,f){switch(h===void 0&&(h=ZT),f===void 0&&(f=ev),l=g(p,function(b){var C="";b.on("data",function(R){return C+=R}),b.on("aborted",function(){if(u){var R=new bi("Request Timeout");o(R)}}),b.on("end",function(){if(u===!1)if(b.statusCode&&b.statusCode<299)V.debug("statusCode: "+b.statusCode,C),n(),clearTimeout(d),clearTimeout(c);else if(b.statusCode&&nv(b.statusCode)&&h>0){var R=void 0;f=rv*f,b.headers["retry-after"]?R=ov(b.headers["retry-after"]):R=Math.round(Math.random()*(tv-f)+f),c=setTimeout(function(){m(h-1,f)},R)}else{var v=new bi(b.statusMessage,b.statusCode,C);o(v),clearTimeout(d),clearTimeout(c)}})}),l.on("error",function(b){if(u){var C=new bi("Request Timeout",b.code);o(C)}else o(b);clearTimeout(d),clearTimeout(c)}),l.on("abort",function(){if(u){var b=new bi("Request Timeout");o(b)}clearTimeout(d),clearTimeout(c)}),r.compression){case Ln.GZIP:{l.setHeader("Content-Encoding","gzip");var E=A0(e);E.on("error",o).pipe(av.createGzip()).on("error",o).pipe(l);break}default:l.end(Buffer.from(e));break}};m()}function A0(r){var e=new v0;return e.push(r),e.push(null),e}function vm(r){if(r.httpAgentOptions&&r.keepAlive===!1){V.warn("httpAgentOptions is used only when keepAlive is true");return}if(!(r.keepAlive===!1||!r.url))try{var e=new Em.URL(r.url),t=e.protocol==="http:"?cc.Agent:uc.Agent;return new t(lc({keepAlive:!0},r.httpAgentOptions))}catch(n){V.error("collector exporter failed to create http agent. err: "+n.message);return}}function Am(r){if(r)return r;var e=Et().OTEL_EXPORTER_OTLP_TRACES_COMPRESSION||Et().OTEL_EXPORTER_OTLP_COMPRESSION;return e===Ln.GZIP?Ln.GZIP:Ln.NONE}_e();var w0=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)}}(),dc=function(r){w0(e,r);function e(t,n,o){t===void 0&&(t={});var i=r.call(this,t)||this;return i.DEFAULT_HEADERS={},i._contentType=o,t.metadata&&V.warn("Metadata cannot be set when using http"),i.headers=Object.assign(i.DEFAULT_HEADERS,Qa(t.headers),Si.parseKeyPairsIntoRecord(Et().OTEL_EXPORTER_OTLP_HEADERS)),i.agent=vm(t),i.compression=Am(t.compression),i._serializer=n,i}return e.prototype.onInit=function(t){},e.prototype.send=function(t,n,o){var i=this;if(this._shutdownOnce.isCalled){V.debug("Shutdown already started. Cannot send objects");return}var a=new Promise(function(c,l){var u;Tm(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}(iv);function lv(r){var e=BigInt(1e9);return BigInt(r[0])*e+BigInt(r[1])}function C0(r){var e=Number(BigInt.asUintN(32,r)),t=Number(BigInt.asUintN(32,r>>BigInt(32)));return{low:e,high:t}}function cv(r){var e=lv(r);return C0(e)}function R0(r){var e=lv(r);return e.toString()}var x0=typeof BigInt<"u"?R0:AT;function sv(r){return r}function uv(r){if(r!==void 0)return Zl(r)}var M0={encodeHrTime:cv,encodeSpanContext:Zl,encodeOptionalSpanContext:uv};function dv(r){var e,t;if(r===void 0)return M0;var n=(e=r.useLongBits)!==null&&e!==void 0?e:!0,o=(t=r.useHex)!==null&&t!==void 0?t:!1;return{encodeHrTime:n?cv:x0,encodeSpanContext:o?sv:Zl,encodeOptionalSpanContext:o?sv:uv}}var _0=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 pv(r){return{name:r.name,version:r.version}}function Ei(r){return Object.keys(r).map(function(e){return mv(e,r[e])})}function mv(r,e){return{key:r,value:gv(e)}}function gv(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(gv)}}:e==="object"&&r!=null?{kvlistValue:{values:Object.entries(r).map(function(t){var n=_0(t,2),o=n[0],i=n[1];return mv(o,i)})}}:{}}function hv(r){return{attributes:Ei(r.attributes),droppedAttributesCount:0}}_e();function Sv(r,e){var t=dv(e);return{resource:hv(r.resource),schemaUrl:void 0,scopeMetrics:P0(r.scopeMetrics,t)}}function P0(r,e){return Array.from(r.map(function(t){return{scope:pv(t.scope),metrics:t.metrics.map(function(n){return I0(n,e)}),schemaUrl:t.scope.schemaUrl}}))}function I0(r,e){var t={name:r.descriptor.name,description:r.descriptor.description,unit:r.descriptor.unit},n=D0(r.aggregationTemporality);switch(r.dataPointType){case _t.SUM:t.sum={aggregationTemporality:n,isMonotonic:r.isMonotonic,dataPoints:fv(r,e)};break;case _t.GAUGE:t.gauge={dataPoints:fv(r,e)};break;case _t.HISTOGRAM:t.histogram={aggregationTemporality:n,dataPoints:L0(r,e)};break;case _t.EXPONENTIAL_HISTOGRAM:t.exponentialHistogram={aggregationTemporality:n,dataPoints:N0(r,e)};break}return t}function O0(r,e,t){var n={attributes:Ei(r.attributes),startTimeUnixNano:t.encodeHrTime(r.startTime),timeUnixNano:t.encodeHrTime(r.endTime)};switch(e){case Kt.INT:n.asInt=r.value;break;case Kt.DOUBLE:n.asDouble=r.value;break}return n}function fv(r,e){return r.dataPoints.map(function(t){return O0(t,r.descriptor.valueType,e)})}function L0(r,e){return r.dataPoints.map(function(t){var n=t.value;return{attributes:Ei(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 N0(r,e){return r.dataPoints.map(function(t){var n=t.value;return{attributes:Ei(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 D0(r){switch(r){case cr.DELTA:return 1;case cr.CUMULATIVE:return 2}}function yv(r,e){return{resourceMetrics:r.map(function(t){return Sv(t,e)})}}var wm={serializeRequest:function(r){var e=yv(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 bv="0.52.1";var Ev=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)}}(),Ti=function(){return Ti=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},Ti.apply(this,arguments)},Tv="v1/metrics",k0="http://localhost:4318/"+Tv,U0={"User-Agent":"OTel-OTLP-Exporter-JavaScript/"+bv},F0=function(r){Ev(e,r);function e(t){var n=r.call(this,t,wm,"application/json")||this;return n.headers=Ti(Ti(Ti(Ti({},n.headers),U0),Si.parseKeyPairsIntoRecord(Et().OTEL_EXPORTER_OTLP_METRICS_HEADERS)),Qa(t?.headers)),n}return e.prototype.getDefaultUrl=function(t){return typeof t.url=="string"?t.url:Et().OTEL_EXPORTER_OTLP_METRICS_ENDPOINT.length>0?Sm(Et().OTEL_EXPORTER_OTLP_METRICS_ENDPOINT):Et().OTEL_EXPORTER_OTLP_ENDPOINT.length>0?fm(Et().OTEL_EXPORTER_OTLP_ENDPOINT,Tv):k0},e}(dc),vv=function(r){Ev(e,r);function e(t){return r.call(this,new F0(t),t)||this}return e}(JT);var vi;(function(r){r[r.DELTA=0]="DELTA",r[r.CUMULATIVE=1]="CUMULATIVE"})(vi||(vi={}));var Hr;(function(r){r[r.HISTOGRAM=0]="HISTOGRAM",r[r.EXPONENTIAL_HISTOGRAM=1]="EXPONENTIAL_HISTOGRAM",r[r.GAUGE=2]="GAUGE",r[r.SUM=3]="SUM"})(Hr||(Hr={}));_e();var B0=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)}}(),Av=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())})},wv=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}}},z0=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},H0=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))},G0=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 Cv(r){return r!=null}function pc(r){var e=Object.keys(r);return e.length===0?"":(e=e.sort(),JSON.stringify(e.map(function(t){return[t,r[t]]})))}function Rv(r){var e,t;return r.name+":"+((e=r.version)!==null&&e!==void 0?e:"")+":"+((t=r.schemaUrl)!==null&&t!==void 0?t:"")}var Cm=function(r){B0(e,r);function e(t){var n=r.call(this,t)||this;return Object.setPrototypeOf(n,e.prototype),n}return e}(Error);function Nn(r,e){var t,n=new Promise(function(i,a){t=setTimeout(function(){a(new Cm("Operation timed out."))},e)});return Promise.race([r,n]).then(function(o){return clearTimeout(t),o},function(o){throw clearTimeout(t),o})}function xv(r){return Av(this,void 0,void 0,function(){var e=this;return wv(this,function(t){return[2,Promise.all(r.map(function(n){return Av(e,void 0,void 0,function(){var o,i;return wv(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 Mv(r){return r.status==="rejected"}function Rm(r,e){var t=[];return r.forEach(function(n){t.push.apply(t,H0([],z0(e(n)),!1))}),t}function _v(r,e){var t,n;if(r.size!==e.size)return!1;try{for(var o=G0(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 Pv(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 Iv(r,e){return r.toLowerCase()===e.toLowerCase()}_e();var dr;(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"})(dr||(dr={}));var xm=function(){function r(){this.kind=dr.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}();_e();var Se;(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"})(Se||(Se={}));function Gr(r,e,t){var n,o,i,a;return W0(r)||V.warn('Invalid metric name: "'+r+'". The metric name should be a ASCII string with a length no greater than 255 characters.'),{name:r,type:e,description:(n=t?.description)!==null&&n!==void 0?n:"",unit:(o=t?.unit)!==null&&o!==void 0?o:"",valueType:(i=t?.valueType)!==null&&i!==void 0?i:Kt.DOUBLE,advice:(a=t?.advice)!==null&&a!==void 0?a:{}}}function Ov(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 Lv(r,e){return Iv(r.name,e.name)&&r.unit===e.unit&&r.type===e.type&&r.valueType===e.valueType}var V0=/^[a-z][a-z0-9_.\-/]{0,254}$/i;function W0(r){return r.match(V0)!=null}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};function $0(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 mc=function(){function r(e,t,n,o){n===void 0&&(n=!0),o===void 0&&(o=$0(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=Pv(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 gc=function(){function r(e,t){this._boundaries=e,this._recordMinMax=t,this.kind=dr.HISTOGRAM}return r.prototype.createAccumulation=function(e){return new mc(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 mc(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 mc(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:Hr.HISTOGRAM,dataPoints:n.map(function(i){var a=j0(i,2),s=a[0],c=a[1],l=c.toPointValue(),u=e.type===Se.GAUGE||e.type===Se.UP_DOWN_COUNTER||e.type===Se.OBSERVABLE_GAUGE||e.type===Se.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}();_e();var Mm=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},_m=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))},Pm=function(){function r(e,t,n,o){e===void 0&&(e=new q0),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 q0=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,_m([n,this._counts.length-t],Mm(this._counts.slice(t)),!1)),o.splice.apply(o,_m([0,t],Mm(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(_m([],Mm(this._counts),!1))},r}();var Nv=52,K0=2146435072,Y0=1048575,Im=1023,hc=-Im+1,fc=Im,Za=Math.pow(2,-1022);function Sc(r){var e=new DataView(new ArrayBuffer(8));e.setFloat64(0,r);var t=e.getUint32(0),n=(t&K0)>>20;return n-Im}function yc(r){var e=new DataView(new ArrayBuffer(8));e.setFloat64(0,r);var t=e.getUint32(0),n=e.getUint32(4),o=(t&Y0)*Math.pow(2,32);return o+n}function es(r,e){return r===0||r===Number.POSITIVE_INFINITY||r===Number.NEGATIVE_INFINITY||Number.isNaN(r)?r:r*Math.pow(2,e)}function kv(r){return r--,r|=r>>1,r|=r>>2,r|=r>>4,r|=r>>8,r|=r>>16,r++,r}var X0=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)}}(),Dn=function(r){X0(e,r);function e(){return r!==null&&r.apply(this,arguments)||this}return e}(Error);var Fv=function(){function r(e){this._shift=-e}return r.prototype.mapToIndex=function(e){if(e<Za)return this._minNormalLowerBoundaryIndex();var t=Sc(e),n=this._rightShift(yc(e)-1,Nv);return t+n>>this._shift},r.prototype.lowerBoundary=function(e){var t=this._minNormalLowerBoundaryIndex();if(e<t)throw new Dn("underflow: "+e+" is < minimum lower boundary: "+t);var n=this._maxNormalLowerBoundaryIndex();if(e>n)throw new Dn("overflow: "+e+" is > maximum lower boundary: "+n);return es(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=hc>>this._shift;return this._shift<2&&e--,e},r.prototype._maxNormalLowerBoundaryIndex=function(){return fc>>this._shift},r.prototype._rightShift=function(e,t){return Math.floor(e*Math.pow(2,-t))},r}();var Bv=function(){function r(e){this._scale=e,this._scaleFactor=es(Math.LOG2E,e),this._inverseFactor=es(Math.LN2,-e)}return r.prototype.mapToIndex=function(e){if(e<=Za)return this._minNormalLowerBoundaryIndex()-1;if(yc(e)===0){var t=Sc(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 Dn("overflow: "+e+" is > maximum lower boundary: "+t)}var n=this._minNormalLowerBoundaryIndex();if(e<=n){if(e===n)return Za;if(e===n-1)return Math.exp((e+(1<<this._scale))/this._scaleFactor)/2;throw new Dn("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 hc<<this._scale},r.prototype._maxNormalLowerBoundaryIndex=function(){return(fc+1<<this._scale)-1},r}();var zv=-10,Hv=20,J0=Array.from({length:31},function(r,e){return e>10?new Bv(e-10):new Fv(e-10)});function Om(r){if(r>Hv||r<zv)throw new Dn("expected scale >= "+zv+" && <= "+Hv+", got: "+r);return J0[r+10]}var Q0=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},bc=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}(),Z0=20,ek=160,Lm=2,Gv=function(){function r(e,t,n,o,i,a,s,c,l,u,d){e===void 0&&(e=e),t===void 0&&(t=ek),n===void 0&&(n=!0),o===void 0&&(o=0),i===void 0&&(i=0),a===void 0&&(a=0),s===void 0&&(s=Number.POSITIVE_INFINITY),c===void 0&&(c=Number.NEGATIVE_INFINITY),l===void 0&&(l=new Pm),u===void 0&&(u=new Pm),d===void 0&&(d=Om(Z0)),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<Lm&&(V.warn("Exponential Histogram Max Size set to "+this._maxSize+", changing to the minimum size of: "+Lm),this._maxSize=Lm)}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=kv(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=Om(t)}},r.prototype._minScale=function(e){var t=Math.min(this.scale,e.scale),n=bc.combine(this._highLowAtScale(this.positive,this.scale,t),this._highLowAtScale(e.positive,e.scale,t)),o=bc.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 bc(0,-1);var o=t-n;return new bc(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 Nm=function(){function r(e,t){this._maxSize=e,this._recordMinMax=t,this.kind=dr.EXPONENTIAL_HISTOGRAM}return r.prototype.createAccumulation=function(e){return new Gv(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:Hr.EXPONENTIAL_HISTOGRAM,dataPoints:n.map(function(i){var a=Q0(i,2),s=a[0],c=a[1],l=c.toPointValue(),u=e.type===Se.GAUGE||e.type===Se.UP_DOWN_COUNTER||e.type===Se.OBSERVABLE_GAUGE||e.type===Se.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}();_e();var tk=jp("OpenTelemetry SDK Context Key SUPPRESS_TRACING");function Vv(r){return r.setValue(tk,!0)}_e();function Wv(){return function(r){V.error(rk(r))}}function rk(r){return typeof r=="string"?r:JSON.stringify(nk(r))}function nk(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 ok=Wv();function Ec(r){try{ok(r)}catch{}}var jv="1.30.1";var ik="process.runtime.name";var ak="service.name";var sk="telemetry.sdk.name",lk="telemetry.sdk.language",ck="telemetry.sdk.version";var $v=ik;var qv=ak;var ts=sk,rs=lk,ns=ck;var uk="nodejs";var Kv=uk;var Ai,So=(Ai={},Ai[ts]="opentelemetry",Ai[$v]="node",Ai[rs]=Kv,Ai[ns]=jv,Ai);function os(r){r.unref()}var Sk=9,yk=6,bk=Math.pow(10,yk),gse=Math.pow(10,Sk);function yo(r){var e=r/1e3,t=Math.trunc(e),n=Math.round(r%1e3*bk);return[t,n]}function wi(r){return r[0]*1e6+r[1]/1e3}var is;(function(r){r[r.SUCCESS=0]="SUCCESS",r[r.FAILED=1]="FAILED"})(is||(is={}));_e();function Yv(r,e){return new Promise(function(t){fi.with(Vv(fi.active()),function(){r.export(e,function(n){t(n)})})})}var Xv={_export:Yv};var Ek=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},Tc=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=yo(Date.now())},r.prototype.setStartTime=function(e){this.startTime=e},r.prototype.toPointValue=function(){return this._current},r}();var Dm=function(){function r(){this.kind=dr.LAST_VALUE}return r.prototype.createAccumulation=function(e){return new Tc(e)},r.prototype.merge=function(e,t){var n=wi(t.sampleTime)>=wi(e.sampleTime)?t:e;return new Tc(e.startTime,n.toPointValue(),n.sampleTime)},r.prototype.diff=function(e,t){var n=wi(t.sampleTime)>=wi(e.sampleTime)?t:e;return new Tc(t.startTime,n.toPointValue(),n.sampleTime)},r.prototype.toMetricData=function(e,t,n,o){return{descriptor:e,aggregationTemporality:t,dataPointType:Hr.GAUGE,dataPoints:n.map(function(i){var a=Ek(i,2),s=a[0],c=a[1];return{attributes:s,startTime:c.startTime,endTime:o,value:c.toPointValue()}})}},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},Ci=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 vc=function(){function r(e){this.monotonic=e,this.kind=dr.SUM}return r.prototype.createAccumulation=function(e){return new Ci(e,this.monotonic)},r.prototype.merge=function(e,t){var n=e.toPointValue(),o=t.toPointValue();return t.reset?new Ci(t.startTime,this.monotonic,o,t.reset):new Ci(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 Ci(t.startTime,this.monotonic,o,!0):new Ci(t.startTime,this.monotonic,o-n)},r.prototype.toMetricData=function(e,t,n,o){return{descriptor:e,aggregationTemporality:t,dataPointType:Hr.SUM,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()}}),isMonotonic:this.monotonic}},r}();var bo=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)}}(),pr=function(){function r(){}return r.Drop=function(){return nA},r.Sum=function(){return oA},r.LastValue=function(){return iA},r.Histogram=function(){return aA},r.ExponentialHistogram=function(){return vk},r.Default=function(){return Ak},r}();var Jv=function(r){bo(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 xm,e}(pr);var Qv=function(r){bo(e,r);function e(){return r!==null&&r.apply(this,arguments)||this}return e.prototype.createAggregator=function(t){switch(t.type){case Se.COUNTER:case Se.OBSERVABLE_COUNTER:case Se.HISTOGRAM:return e.MONOTONIC_INSTANCE;default:return e.NON_MONOTONIC_INSTANCE}},e.MONOTONIC_INSTANCE=new vc(!0),e.NON_MONOTONIC_INSTANCE=new vc(!1),e}(pr);var Zv=function(r){bo(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 Dm,e}(pr);var eA=function(r){bo(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 gc([0,5,10,25,50,75,100,250,500,750,1e3,2500,5e3,7500,1e4],!0),e}(pr);var as=function(r){bo(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 gc(this._boundaries,this._recordMinMax)},e}(pr);var tA=function(r){bo(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 Nm(this._maxSize,this._recordMinMax)},e}(pr);var rA=function(r){bo(e,r);function e(){return r!==null&&r.apply(this,arguments)||this}return e.prototype._resolve=function(t){switch(t.type){case Se.COUNTER:case Se.UP_DOWN_COUNTER:case Se.OBSERVABLE_COUNTER:case Se.OBSERVABLE_UP_DOWN_COUNTER:return oA;case Se.GAUGE:case Se.OBSERVABLE_GAUGE:return iA;case Se.HISTOGRAM:return t.advice.explicitBucketBoundaries?new as(t.advice.explicitBucketBoundaries):aA}return V.warn("Unable to recognize instrument type: "+t.type),nA},e.prototype.createAggregator=function(t){return this._resolve(t).createAggregator(t)},e}(pr);var nA=new Jv,oA=new Qv,iA=new Zv,aA=new eA,vk=new tA,Ak=new rA;var sA=function(r){return pr.Default()},lA=function(r){return vi.CUMULATIVE};var km=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())})},Um=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}}},cA=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},wk=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))},uA=function(){function r(e){var t,n,o;this._shutdown=!1,this._aggregationSelector=(t=e?.aggregationSelector)!==null&&t!==void 0?t:sA,this._aggregationTemporalitySelector=(n=e?.aggregationTemporalitySelector)!==null&&n!==void 0?n:lA,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 km(this,void 0,void 0,function(){var t,n,o,i,a,s;return Um(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(wk([this._sdkMetricProducer.collect({timeoutMillis:e?.timeoutMillis})],cA(this._metricProducers.map(function(l){return l.collect({timeoutMillis:e?.timeoutMillis})})),!1))];case 1:return t=cA.apply(void 0,[c.sent()]),n=t[0],o=t.slice(1),i=n.errors.concat(Rm(o,function(l){return l.errors})),a=n.resourceMetrics.resource,s=n.resourceMetrics.scopeMetrics.concat(Rm(o,function(l){return l.resourceMetrics.scopeMetrics})),[2,{resourceMetrics:{resource:a,scopeMetrics:s},errors:i}]}})})},r.prototype.shutdown=function(e){return km(this,void 0,void 0,function(){return Um(this,function(t){switch(t.label){case 0:return this._shutdown?(V.error("Cannot call shutdown twice."),[2]):e?.timeoutMillis!=null?[3,2]:[4,this.onShutdown()];case 1:return t.sent(),[3,4];case 2:return[4,Nn(this.onShutdown(),e.timeoutMillis)];case 3:t.sent(),t.label=4;case 4:return this._shutdown=!0,[2]}})})},r.prototype.forceFlush=function(e){return km(this,void 0,void 0,function(){return Um(this,function(t){switch(t.label){case 0:return this._shutdown?(V.warn("Cannot forceFlush on already shutdown MetricReader."),[2]):e?.timeoutMillis!=null?[3,2]:[4,this.onForceFlush()];case 1:return t.sent(),[2];case 2:return[4,Nn(this.onForceFlush(),e.timeoutMillis)];case 3:return t.sent(),[2]}})})},r}();_e();var Ck=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)}}(),Ac=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())})},wc=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}}},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},xk=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))},Fm=function(r){Ck(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 Ac(this,void 0,void 0,function(){var t;return wc(this,function(n){switch(n.label){case 0:return n.trys.push([0,2,,3]),[4,Nn(this._doRun(),this._exportTimeout)];case 1:return n.sent(),[3,3];case 2:return t=n.sent(),t instanceof Cm?(V.error("Export took longer than %s milliseconds and timed out.",this._exportTimeout),[2]):(Ec(t),[3,3]);case 3:return[2]}})})},e.prototype._doRun=function(){var t,n;return Ac(this,void 0,void 0,function(){var o,i,a,s,c,l;return wc(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=V).error.apply(l,xk(["PeriodicExportingMetricReader: metrics collection errors"],Rk(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(),V.debug("Error while resolving async portion of resource: ",s),Ec(s),[3,5];case 5:return i.scopeMetrics.length===0?[2]:[4,Xv._export(this._exporter,i)];case 6:if(c=u.sent(),c.code!==is.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),os(this._interval)},e.prototype.onForceFlush=function(){return Ac(this,void 0,void 0,function(){return wc(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 Ac(this,void 0,void 0,function(){return wc(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}(uA);_e();_e();function Cc(){return"unknown_service:"+process.argv0}var kn=function(){return kn=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},kn.apply(this,arguments)},Mk=function(r,e,t,n){function o(i){return i instanceof t?i:new t(function(a){a(i)})}return new(t||(t=Promise))(function(i,a){function s(u){try{l(n.next(u))}catch(d){a(d)}}function c(u){try{l(n.throw(u))}catch(d){a(d)}}function l(u){u.done?i(u.value):o(u.value).then(s,c)}l((n=n.apply(r,e||[])).next())})},_k=function(r,e){var t={label:0,sent:function(){if(i[0]&1)throw i[1];return i[1]},trys:[],ops:[]},n,o,i,a;return a={next:s(0),throw:s(1),return:s(2)},typeof Symbol=="function"&&(a[Symbol.iterator]=function(){return this}),a;function s(l){return function(u){return c([l,u])}}function c(l){if(n)throw new TypeError("Generator is already executing.");for(;t;)try{if(n=1,o&&(i=l[0]&2?o.return:l[0]?o.throw||((i=o.return)&&i.call(o),0):o.next)&&!(i=i.call(o,l[1])).done)return i;switch(o=0,i&&(l=[l[0]&2,i.value]),l[0]){case 0:case 1:i=l;break;case 4:return t.label++,{value:l[1],done:!1};case 5:t.label++,o=l[1],l=[0];continue;case 7:l=t.ops.pop(),t.trys.pop();continue;default:if(i=t.trys,!(i=i.length>0&&i[i.length-1])&&(l[0]===6||l[0]===2)){t=0;continue}if(l[0]===3&&(!i||l[1]>i[0]&&l[1]<i[3])){t.label=l[1];break}if(l[0]===6&&t.label<i[1]){t.label=i[1],i=l;break}if(i&&t.label<i[2]){t.label=i[2],t.ops.push(l);break}i[2]&&t.ops.pop(),t.trys.pop();continue}l=e.call(r,t)}catch(u){l=[6,u],o=0}finally{n=i=0}if(l[0]&5)throw l[1];return{value:l[0]?l[1]:void 0,done:!0}}},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},Rc=function(){function r(e,t){var n=this,o;this._attributes=e,this.asyncAttributesPending=t!=null,this._syncAttributes=(o=this._attributes)!==null&&o!==void 0?o:{},this._asyncAttributesPromise=t?.then(function(i){return n._attributes=Object.assign({},n._attributes,i),n.asyncAttributesPending=!1,i},function(i){return V.debug("a resource's async attributes promise rejected: %s",i),n.asyncAttributesPending=!1,{}})}return r.empty=function(){return r.EMPTY},r.default=function(){var e;return new r((e={},e[qv]=Cc(),e[rs]=So[rs],e[ts]=So[ts],e[ns]=So[ns],e))},Object.defineProperty(r.prototype,"attributes",{get:function(){var e;return this.asyncAttributesPending&&V.error("Accessing resource attributes before async attributes settled"),(e=this._attributes)!==null&&e!==void 0?e:{}},enumerable:!1,configurable:!0}),r.prototype.waitForAsyncAttributes=function(){return Mk(this,void 0,void 0,function(){return _k(this,function(e){switch(e.label){case 0:return this.asyncAttributesPending?[4,this._asyncAttributesPromise]:[3,2];case 1:e.sent(),e.label=2;case 2:return[2]}})})},r.prototype.merge=function(e){var t=this,n;if(!e)return this;var o=kn(kn({},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=Pk(a,2),l=c[0],u=c[1];return kn(kn(kn(kn({},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 dA=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}();_e();var Eo=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)}}(),xc=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=fi.active()),typeof e!="number"){V.warn("non-number value provided to metric "+this._descriptor.name+": "+e);return}this._descriptor.valueType===Kt.INT&&!Number.isInteger(e)&&(V.warn("INT value type cannot accept a floating-point value for "+this._descriptor.name+", ignoring the fractional digits."),e=Math.trunc(e),!Number.isInteger(e))||this._writableMetricStorage.record(e,t,n,yo(Date.now()))},r}();var pA=function(r){Eo(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}(xc);var mA=function(r){Eo(e,r);function e(){return r!==null&&r.apply(this,arguments)||this}return e.prototype.add=function(t,n,o){if(t<0){V.warn("negative value provided to counter "+this._descriptor.name+": "+t);return}this._record(t,n,o)},e}(xc);var gA=function(r){Eo(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}(xc);var hA=function(r){Eo(e,r);function e(){return r!==null&&r.apply(this,arguments)||this}return e.prototype.record=function(t,n,o){if(t<0){V.warn("negative value provided to histogram "+this._descriptor.name+": "+t);return}this._record(t,n,o)},e}(xc);var Mc=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 fA=function(r){Eo(e,r);function e(){return r!==null&&r.apply(this,arguments)||this}return e}(Mc);var SA=function(r){Eo(e,r);function e(){return r!==null&&r.apply(this,arguments)||this}return e}(Mc);var yA=function(r){Eo(e,r);function e(){return r!==null&&r.apply(this,arguments)||this}return e}(Mc);function ss(r){return r instanceof Mc}var bA=function(){function r(e){this._meterSharedState=e}return r.prototype.createGauge=function(e,t){var n=Gr(e,Se.GAUGE,t),o=this._meterSharedState.registerMetricStorage(n);return new gA(o,n)},r.prototype.createHistogram=function(e,t){var n=Gr(e,Se.HISTOGRAM,t),o=this._meterSharedState.registerMetricStorage(n);return new hA(o,n)},r.prototype.createCounter=function(e,t){var n=Gr(e,Se.COUNTER,t),o=this._meterSharedState.registerMetricStorage(n);return new mA(o,n)},r.prototype.createUpDownCounter=function(e,t){var n=Gr(e,Se.UP_DOWN_COUNTER,t),o=this._meterSharedState.registerMetricStorage(n);return new pA(o,n)},r.prototype.createObservableGauge=function(e,t){var n=Gr(e,Se.OBSERVABLE_GAUGE,t),o=this._meterSharedState.registerAsyncMetricStorage(n);return new SA(n,o,this._meterSharedState.observableRegistry)},r.prototype.createObservableCounter=function(e,t){var n=Gr(e,Se.OBSERVABLE_COUNTER,t),o=this._meterSharedState.registerAsyncMetricStorage(n);return new fA(n,o,this._meterSharedState.observableRegistry)},r.prototype.createObservableUpDownCounter=function(e,t){var n=Gr(e,Se.OBSERVABLE_UP_DOWN_COUNTER,t),o=this._meterSharedState.registerAsyncMetricStorage(n);return new yA(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 _c=function(){function r(e){this._instrumentDescriptor=e}return r.prototype.getInstrumentDescriptor=function(){return this._instrumentDescriptor},r.prototype.updateDescription=function(e){this._instrumentDescriptor=Gr(this._instrumentDescriptor.name,this._instrumentDescriptor.type,{description:e,valueType:this._instrumentDescriptor.valueType,unit:this._instrumentDescriptor.unit,advice:this._instrumentDescriptor.advice})},r}();var Ik=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)}}(),EA=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}}},Ok=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 EA(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 EA(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 Ar=function(r){Ik(e,r);function e(){return r.call(this,pc)||this}return e}(Ok);var Lk=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},Pc=function(){function r(e,t){this._aggregator=e,this._activeCollectionStorage=new Ar,this._cumulativeMemoStorage=new Ar,this._overflowAttributes={"otel.metric.overflow":!0},this._cardinalityLimit=(t??2e3)-1,this._overflowHashCode=pc(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=Lk(o,3),a=i[0],s=i[1],c=i[2],l=n._aggregator.createAccumulation(t);l?.record(s);var u=l;if(n._cumulativeMemoStorage.has(a,c)){var d=n._cumulativeMemoStorage.get(a,c);u=n._aggregator.diff(d,l)}else if(n._cumulativeMemoStorage.size>=n._cardinalityLimit&&(a=n._overflowAttributes,c=n._overflowHashCode,n._cumulativeMemoStorage.has(a,c))){var d=n._cumulativeMemoStorage.get(a,c);u=n._aggregator.diff(d,l)}if(n._activeCollectionStorage.has(a,c)){var p=n._activeCollectionStorage.get(a,c);u=n._aggregator.merge(p,u)}n._cumulativeMemoStorage.set(a,l,c),n._activeCollectionStorage.set(a,u,c)})},r.prototype.collect=function(){var e=this._activeCollectionStorage;return this._activeCollectionStorage=new Ar,e},r}();var Bm=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.")},TA=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},Ic=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===vi.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=Nk(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=Bm(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 Ar,i=this._unreportedAccumulations.get(e);if(this._unreportedAccumulations.set(e,[]),i===void 0)return o;try{for(var a=Bm(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=TA(a.value,3),c=s[0],l=s[1],u=s[2];if(e.has(c,u)){var d=e.get(c,u),p=n.merge(d,l);o.set(c,p,u)}else o.set(c,l,u);a=i.next()}return o},r.calibrateStartTime=function(e,t,n){var o,i;try{for(var a=Bm(e.keys()),s=a.next();!s.done;s=a.next()){var c=TA(s.value,2),l=c[0],u=c[1],d=t.get(l,u);d?.setStartTime(n)}}catch(p){o={error:p}}finally{try{s&&!s.done&&(i=a.return)&&i.call(a)}finally{if(o)throw o.error}}return t},r}();function Nk(r){return Array.from(r.entries())}var Dk=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)}}(),kk=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},vA=function(r){Dk(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 Pc(n,s._aggregationCardinalityLimit),s._temporalMetricStorage=new Ic(n,i),s}return e.prototype.record=function(t,n){var o=this,i=new Ar;Array.from(t.entries()).forEach(function(a){var s=kk(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}(_c);_e();function zm(r,e){var t="";return r.unit!==e.unit&&(t+=" - Unit '"+r.unit+"' does not match '"+e.unit+`'
27
+ `),globalThis.console=e}}var Fp=" ".repeat(6);import pN from"fetch-retry";import mN from"os";import xE,{multistream as gN}from"pino";import hN from"pino-pretty";import fN from"pino-std-serializers";var ui=new Map,SN=!0,ME="Log throttle exceeded",yN=100,bN=5e3,EN=pN(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}}),Bp=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??mN.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=SN?xE(a):xE(a,gN([{stream:hN({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 EN(this.site,{method:"POST",headers:{"Content-Type":"application/json","signoz-access-token":"CumAaTMUcwjt05OddAmefKgshbhfRmWxzxih"},body:uo(e),signal:AbortSignal.timeout(5e3)});if(!t.ok)throw new Error(`Got error status (${t.statusText}) from SigNoz`)}catch{}}shouldAllowLog(e){if(e===ME)return!0;let t=Date.now();return t-this.lastWindowStart>bN&&(this.logsInCurrentWindow=0,this.droppedLogsInWindow&&this.log("error",void 0,ME),this.droppedLogsInWindow=!1,this.lastWindowStart=t),this.logsInCurrentWindow<yN?(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(La[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=fN.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:hb({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,ui.set("app",this),ui.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=fb[e]):(this.minLevelValue=La[e],this.consoleLogger.level=e)}enableConsoleLogs(){this.disableConsoleLogs=!1}},di=({app:r,hostname:e,disableConsoleLogs:t})=>(ui.has(r)||ui.set(r,new Bp({bindings:{app:r},hostname:e,disableConsoleLogs:t})),ui.get(r));async function _E(){await Promise.all([...ui.values()].map(r=>r.flush()))}import{hostname as TN}from"os";var lr=di({app:"cli",hostname:TN(),disableConsoleLogs:!0}).child({cliVersion:"0.12.1"});function zp(r){if(!r)return;r=r.toLowerCase();let e=Nl.safeParse(r);if(e.success)return w.setMinLevel(e.data),e.data}function PE({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 RE(()=>{if(c.forEach(u=>{w.log(""),o(u)}),c.length){w.log("");let u=c.length===1?"":"s";w.error(`${c.length} ${t}${u} failed:`),c.forEach(d=>{w.dimmed(n(d))})}if(l.length){w.log("");let u=l.length===1?"":"s";w.warn(`${l.length} ${t}${u} cancelled:`),l.forEach(d=>{w.dimmed(n(d))})}if(a.length){w.log("");let u=a.length===1?"":"s";w.success(`${a.length} ${t}${u} passed:`),a.forEach(d=>{w.dimmed(n(d))})}if(s.length){w.log("");let u=s.length===1?"":"s";w.warn(`${s.length} quarantined ${t}${u} failed:`),s.forEach(d=>{w.dimmed(n(d))})}if(i.length){w.log("");let u=i.length===1?"":"s";w.warn(`${i.length} quarantined ${t}${u} passed:`),i.forEach(d=>{w.dimmed(n(d))})}w.log(""),w.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 Ua=({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):(w.warn(`Unknown status tried to be logged in run test locally: ${r}`),a=0),vN||(i=`${i}`),w.log(`${i}${" ".repeat(a)} ${e} ${o?`${o} `:""}(${t()}/${n()})`)};import AN from"fs";import{tmpdir as wN}from"os";import CN from"path";import{registry as Fa}from"playwright-core/lib/server";import IE from"proper-lockfile";var OE=CN.join(wN(),"momenticBrowserInstallation");var Hp=["chrome","chromium","chrome-for-testing","ffmpeg"],RN={Chromium:"chromium","Google Chrome":"chrome","Chrome for Testing":"chrome-for-testing"},LE={chrome:"chrome",chromium:"chromium","chrome-for-testing":"chromium-headless-shell",ffmpeg:"ffmpeg"};function NE(r){let e=LE[RN[r]??""]??"",t=Fa.findExecutable(e);return!t||t.installType==="none"?!1:Gp(t)}function Gp(r){let e=r.executablePath();return AN.existsSync(e)}function xN(r,e){let t=LE[r];if(!t)throw new Error(`Requested install of unknown browser type ${r}`);let n=Fa.findExecutable(t);if(!n||n.installType==="none")throw new Error(`Requested install of unknown browser type ${r}`);if(!(!e&&Gp(n)))return n}async function MN({browser:r,force:e}){let t=xN(r,e);if(!t){w.info(`Browser '${r}' is already installed, skipping...`);return}w.info(`Installing browser '${r}'...`);try{await Fa.installDeps([t],!1),await Fa.install([t],!1)}catch(n){if(n.message.includes("Lock file is already being held")){w.warn("Another process is installing Playwright browsers. Waiting for completion before proceeding..");let o=Fa.findExecutable(r),i=5*60*1e3,a=Date.now();for(;Date.now()-a<i&&!Gp(o);)w.info("Waiting for browser to finish installing..."),await new Promise(s=>setTimeout(s,5e3))}else throw n}}async function Vl({rawBrowsers:r,force:e=!1,all:t=!1}){let n=t?Hp:Array.from(new Set(r));try{await IE.lock(OE,{stale:1e3*60*5,update:1e3*60,realpath:!1,retries:{retries:30,factor:2,maxTimeout:15e3,minTimeout:500}})}catch(i){w.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 MN({browser:i,force:e})}catch(a){o=a,w.error(`Failed to install the ${i} browser: ${a}`)}}finally{await IE.unlock(OE,{realpath:!1})}if(o)throw o}import{createServer as _N}from"http";async function Wl(r,e,t=30){for(let n=0;n<t;n+=1){let o=r+n;if(await jl(o))return o}w.error(`Could not find an available port for ${e} starting from ${r} after ${t} attempts`),process.exit(1)}async function jl(r){return new Promise((e,t)=>{let n=_N();n.once("error",o=>{o.code==="EADDRINUSE"?e(!1):(w.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 Jee from"blocked-at";import Zee from"why-is-node-running";import FU from"fs";import{tmpdir as BU,totalmem as zU}from"os";import HU from"path";import{execFile as PN}from"child_process";import IN from"path";function ON(){let r=process.env.ANDROID_HOME;if(!r)return"adb";let e=process.platform==="win32"?"adb.exe":"adb";return IN.join(r,"platform-tools",e)}async function ht(r,{timeoutMs:e=5e3,serial:t,throwOnError:n=!1}){let o=ON(),i=t?["-s",t,...r]:r;return await new Promise((a,s)=>{PN(o,i,{encoding:"utf8",timeout:e},(c,l)=>{if(c){if(n){s(c);return}a(void 0);return}a(l)})})}import{createInstanceClient as rU}from"@limrun/api";import{execSync as nU}from"child_process";import mte,{multistream as hte}from"pino";import Ste from"pino-pretty";var Ete=5*1024,LN="...[truncated]",Tte=Buffer.byteLength(LN,"utf8");import{PostHog as Ite}from"posthog-node";var Pn=class extends Error{constructor(e){super(e),this.name="TimeoutError"}};var DE=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 z(r,e){let{milliseconds:t,fallback:n,message:o,customTimers:i={setTimeout,clearTimeout}}=e,a;if(typeof t!="number"||Math.sign(t)!==1)throw new TypeError(`Expected \`milliseconds\` to be a positive number, got \`${t}\``);return new Promise((s,c)=>{let l;if(e.signal){let{signal:p}=e;if(p.aborted)return c(DE(p));l=()=>c(DE(p)),p.addEventListener("abort",l,{once:!0})}let u=()=>{if(e.signal&&e.signal.removeEventListener("abort",l),n)try{s(n())}catch(p){c(p)}else{typeof r.cancel=="function"&&Promise.resolve().then(()=>r.cancel()).catch(()=>{});let p=o instanceof Error?o:new Pn(o??`Promise timed out after ${t}ms`);c(p)}};t<1/0&&(a=i.setTimeout(u,t));let d=()=>{i.clearTimeout(a),e.signal&&e.signal.removeEventListener("abort",l)};Promise.resolve(r).then(p=>{d(),s(p)}).catch(p=>{d(),c(p)})})}import{PostHog as zte}from"posthog-node";import{execSync as NN}from"child_process";import mi from"os";import DN from"v8";var kE,Fr,FE=mi.platform(),kN=mi.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),{}),UE=r=>{try{let e={},t=!1,n=UN(),o=FN(),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=DN.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"),po&&w.warn(`Low machine resources detected (memory: ${i} free, cpu: ${a} free)`)):r.debug({memory:n,cpu:o},"Got machine resource usage metrics")}catch{}};function BE(r){if(!kr)return UE(r),{interval:setInterval(()=>UE(r),2e4),cpuMetadata:kN,platform:FE}}function UN(){let r=mi.totalmem(),e=FE==="darwin"?BN():(()=>{let n=mi.freemem();return{availableMemory:n,rawFreeMemory:n,cachedMemory:0}})(),t=e.availableMemory/r;return{totalMemory:r,freeMemory:e.availableMemory,freePercentage:t}}function FN(){let r=mi.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,!Fr)return Fr=t,null;let n={user:t.user-Fr.user,nice:t.nice-Fr.nice,sys:t.sys-Fr.sys,idle:t.idle-Fr.idle,irq:t.irq-Fr.irq,total:t.total-Fr.total};return kE={measurementTime:e,intervalMs:e-Fr.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},Fr=t,kE}function BN(){try{let r=NN("/usr/bin/vm_stat",{encoding:"utf8",stdio:["pipe","pipe","ignore"]}),t=r.match(/page size of (\d+) bytes/)?.[1],n=t?Number.parseInt(t,10):4096,o=u=>{let p=r.match(new RegExp(`${u}:\\s+(\\d+)\\.`,"i"))?.[1];return p?Number.parseInt(p,10):0},i=o("Pages free"),a=o("Pages inactive"),s=o("Pages speculative"),c=i*n,l=(a+s)*n;return{availableMemory:c+l,rawFreeMemory:c,cachedMemory:l}}catch{let e=mi.freemem();return{availableMemory:e,rawFreeMemory:e,cachedMemory:0}}}var $l=class{increment(e,t,n){}gauge(e,t){}distribution(e,t,n){}async flush(){}async recordDuration({fn:e}){return await e()}};function zN(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 ql(r,e){let t=zN(r);return!e||Object.keys(e).length===0?t:{...e,...t}}var pT="=",Jl=";",em=",";var mT=8192;var Si={};jM(Si,{getKeyPairs:()=>bD,parseKeyPairsIntoRecord:()=>ED,parsePairKeyValue:()=>gT,serializeKeyPairs:()=>yD});_e();var SD=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 yD(r){return r.reduce(function(e,t){var n=""+e+(e!==""?em:"")+t;return n.length>mT?e:n},"")}function bD(r){return r.getAllEntries().map(function(e){var t=SD(e,2),n=t[0],o=t[1],i=encodeURIComponent(n)+"="+encodeURIComponent(o.value);return o.metadata!==void 0&&(i+=Jl+o.metadata.toString()),i})}function gT(r){var e=r.split(Jl);if(!(e.length<=0)){var t=e.shift();if(t){var n=t.indexOf(pT);if(!(n<=0)){var o=decodeURIComponent(t.substring(0,n).trim()),i=decodeURIComponent(t.substring(n+1).trim()),a;return e.length>0&&(a=Wp(e.join(Jl))),{key:o,value:i,metadata:a}}}}}function ED(r){return typeof r!="string"||r.length===0?{}:r.split(em).map(function(e){return gT(e)}).filter(function(e){return e!==void 0&&e.value.length>0}).reduce(function(e,t){return e[t.key]=t.value,e},{})}_e();var Ql;(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"})(Ql||(Ql={}));var TD=",",vD=["OTEL_SDK_DISABLED"];function AD(r){return vD.indexOf(r)>-1}var wD=["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 CD(r){return wD.indexOf(r)>-1}var RD=["OTEL_NO_PATCH_MODULES","OTEL_PROPAGATORS"];function xD(r){return RD.indexOf(r)>-1}var tm=1/0,rm=128,MD=128,_D=128,nm={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:tm,OTEL_ATTRIBUTE_COUNT_LIMIT:rm,OTEL_SPAN_ATTRIBUTE_VALUE_LENGTH_LIMIT:tm,OTEL_SPAN_ATTRIBUTE_COUNT_LIMIT:rm,OTEL_LOGRECORD_ATTRIBUTE_VALUE_LENGTH_LIMIT:tm,OTEL_LOGRECORD_ATTRIBUTE_COUNT_LIMIT:rm,OTEL_SPAN_EVENT_COUNT_LIMIT:128,OTEL_SPAN_LINK_COUNT_LIMIT:128,OTEL_SPAN_ATTRIBUTE_PER_EVENT_COUNT_LIMIT:MD,OTEL_SPAN_ATTRIBUTE_PER_LINK_COUNT_LIMIT:_D,OTEL_TRACES_EXPORTER:"",OTEL_TRACES_SAMPLER:Ql.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 PD(r,e,t){if(!(typeof t[r]>"u")){var n=String(t[r]);e[r]=n.toLowerCase()==="true"}}function ID(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 OD(r,e,t,n){n===void 0&&(n=TD);var o=t[r];typeof o=="string"&&(e[r]=o.split(n).map(function(i){return i.trim()}))}var LD={ALL:Fe.ALL,VERBOSE:Fe.VERBOSE,DEBUG:Fe.DEBUG,INFO:Fe.INFO,WARN:Fe.WARN,ERROR:Fe.ERROR,NONE:Fe.NONE};function ND(r,e,t){var n=t[r];if(typeof n=="string"){var o=LD[n.toUpperCase()];o!=null&&(e[r]=o)}}function hT(r){var e={};for(var t in nm){var n=t;switch(n){case"OTEL_LOG_LEVEL":ND(n,e,r);break;default:if(AD(n))PD(n,e,r);else if(CD(n))ID(n,e,r);else if(xD(n))OD(n,e,r);else{var o=r[n];typeof o<"u"&&o!==null&&(e[n]=String(o))}}}return e}function Et(){var r=hT(process.env);return Object.assign({},nm,r)}function fT(r){return r>=48&&r<=57?r-48:r>=97&&r<=102?r-87:r-55}function Zl(r){for(var e=new Uint8Array(r.length/2),t=0,n=0;n<r.length;n+=2){var o=fT(r.charCodeAt(n)),i=fT(r.charCodeAt(n+1));e[t++]=o<<4|i}return e}var ST="1.25.1";var DD="deployment.environment";var kD="process.runtime.name";var UD="service.name";var FD="service.instance.id";var BD="telemetry.sdk.name",zD="telemetry.sdk.language",HD="telemetry.sdk.version";var yT=DD;var bT=kD;var ec=UD;var ET=FD;var ja=BD,$a=zD,qa=HD;var GD="nodejs";var TT=GD;var yi,tc=(yi={},yi[ja]="opentelemetry",yi[bT]="node",yi[$a]=TT,yi[qa]=ST,yi);var VD=9,WD=6,jD=Math.pow(10,WD),$D=Math.pow(10,VD);function vT(r){var e=r/1e3,t=Math.trunc(e),n=Math.round(r%1e3*jD);return[t,n]}function AT(r){return r[0]*$D+r[1]}function Ka(r){return r[0]*1e6+r[1]/1e3}var go;(function(r){r[r.SUCCESS=0]="SUCCESS",r[r.FAILED=1]="FAILED"})(go||(go={}));var wT=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 qD=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},KD=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))},CT=function(){function r(e,t){this._callback=e,this._that=t,this._isCalled=!1,this._deferred=new wT}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,KD([this._that],qD(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 cr;(function(r){r[r.DELTA=0]="DELTA",r[r.CUMULATIVE=1]="CUMULATIVE"})(cr||(cr={}));var _t;(function(r){r[r.HISTOGRAM=0]="HISTOGRAM",r[r.EXPONENTIAL_HISTOGRAM=1]="EXPONENTIAL_HISTOGRAM",r[r.GAUGE=2]="GAUGE",r[r.SUM=3]="SUM"})(_t||(_t={}));var YD=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 uoe=function(r){YD(e,r);function e(t){var n=r.call(this,t)||this;return Object.setPrototypeOf(n,e.prototype),n}return e}(Error);function RT(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}_e();var ur;(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"})(ur||(ur={}));var xT=function(){function r(){this.kind=ur.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 se;(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"})(se||(se={}));var XD=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 JD(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 om=function(){function r(e,t,n,o){n===void 0&&(n=!0),o===void 0&&(o=JD(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=RT(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 im=function(){function r(e,t){this._boundaries=e,this._recordMinMax=t,this.kind=ur.HISTOGRAM}return r.prototype.createAccumulation=function(e){return new om(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 om(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 om(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:_t.HISTOGRAM,dataPoints:n.map(function(i){var a=XD(i,2),s=a[0],c=a[1],l=c.toPointValue(),u=e.type===se.GAUGE||e.type===se.UP_DOWN_COUNTER||e.type===se.OBSERVABLE_GAUGE||e.type===se.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}();_e();var am=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},sm=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))},lm=function(){function r(e,t,n,o){e===void 0&&(e=new QD),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 QD=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,sm([n,this._counts.length-t],am(this._counts.slice(t)),!1)),o.splice.apply(o,sm([0,t],am(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(sm([],am(this._counts),!1))},r}();var MT=52,ZD=2146435072,e0=1048575,cm=1023,rc=-cm+1,nc=cm,Ya=Math.pow(2,-1022);function oc(r){var e=new DataView(new ArrayBuffer(8));e.setFloat64(0,r);var t=e.getUint32(0),n=(t&ZD)>>20;return n-cm}function ic(r){var e=new DataView(new ArrayBuffer(8));e.setFloat64(0,r);var t=e.getUint32(0),n=e.getUint32(4),o=(t&e0)*Math.pow(2,32);return o+n}function Xa(r,e){return r===0||r===Number.POSITIVE_INFINITY||r===Number.NEGATIVE_INFINITY||Number.isNaN(r)?r:r*Math.pow(2,e)}function PT(r){return r--,r|=r>>1,r|=r>>2,r|=r>>4,r|=r>>8,r|=r>>16,r++,r}var t0=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)}}(),In=function(r){t0(e,r);function e(){return r!==null&&r.apply(this,arguments)||this}return e}(Error);var OT=function(){function r(e){this._shift=-e}return r.prototype.mapToIndex=function(e){if(e<Ya)return this._minNormalLowerBoundaryIndex();var t=oc(e),n=this._rightShift(ic(e)-1,MT);return t+n>>this._shift},r.prototype.lowerBoundary=function(e){var t=this._minNormalLowerBoundaryIndex();if(e<t)throw new In("underflow: "+e+" is < minimum lower boundary: "+t);var n=this._maxNormalLowerBoundaryIndex();if(e>n)throw new In("overflow: "+e+" is > maximum lower boundary: "+n);return Xa(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=rc>>this._shift;return this._shift<2&&e--,e},r.prototype._maxNormalLowerBoundaryIndex=function(){return nc>>this._shift},r.prototype._rightShift=function(e,t){return Math.floor(e*Math.pow(2,-t))},r}();var LT=function(){function r(e){this._scale=e,this._scaleFactor=Xa(Math.LOG2E,e),this._inverseFactor=Xa(Math.LN2,-e)}return r.prototype.mapToIndex=function(e){if(e<=Ya)return this._minNormalLowerBoundaryIndex()-1;if(ic(e)===0){var t=oc(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 In("overflow: "+e+" is > maximum lower boundary: "+t)}var n=this._minNormalLowerBoundaryIndex();if(e<=n){if(e===n)return Ya;if(e===n-1)return Math.exp((e+(1<<this._scale))/this._scaleFactor)/2;throw new In("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 rc<<this._scale},r.prototype._maxNormalLowerBoundaryIndex=function(){return(nc+1<<this._scale)-1},r}();var NT=-10,DT=20,r0=Array.from({length:31},function(r,e){return e>10?new LT(e-10):new OT(e-10)});function um(r){if(r>DT||r<NT)throw new In("expected scale >= "+NT+" && <= "+DT+", got: "+r);return r0[r+10]}var n0=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},ac=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}(),o0=20,i0=160,dm=2,a0=function(){function r(e,t,n,o,i,a,s,c,l,u,d){e===void 0&&(e=e),t===void 0&&(t=i0),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 lm),u===void 0&&(u=new lm),d===void 0&&(d=um(o0)),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<dm&&(V.warn("Exponential Histogram Max Size set to "+this._maxSize+", changing to the minimum size of: "+dm),this._maxSize=dm)}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=PT(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=um(t)}},r.prototype._minScale=function(e){var t=Math.min(this.scale,e.scale),n=ac.combine(this._highLowAtScale(this.positive,this.scale,t),this._highLowAtScale(e.positive,e.scale,t)),o=ac.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 ac(0,-1);var o=t-n;return new ac(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 kT=function(){function r(e,t){this._maxSize=e,this._recordMinMax=t,this.kind=ur.EXPONENTIAL_HISTOGRAM}return r.prototype.createAccumulation=function(e){return new a0(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:_t.EXPONENTIAL_HISTOGRAM,dataPoints:n.map(function(i){var a=n0(i,2),s=a[0],c=a[1],l=c.toPointValue(),u=e.type===se.GAUGE||e.type===se.UP_DOWN_COUNTER||e.type===se.OBSERVABLE_GAUGE||e.type===se.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 s0=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},pm=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=vT(Date.now())},r.prototype.setStartTime=function(e){this.startTime=e},r.prototype.toPointValue=function(){return this._current},r}();var UT=function(){function r(){this.kind=ur.LAST_VALUE}return r.prototype.createAccumulation=function(e){return new pm(e)},r.prototype.merge=function(e,t){var n=Ka(t.sampleTime)>=Ka(e.sampleTime)?t:e;return new pm(e.startTime,n.toPointValue(),n.sampleTime)},r.prototype.diff=function(e,t){var n=Ka(t.sampleTime)>=Ka(e.sampleTime)?t:e;return new pm(t.startTime,n.toPointValue(),n.sampleTime)},r.prototype.toMetricData=function(e,t,n,o){return{descriptor:e,aggregationTemporality:t,dataPointType:_t.GAUGE,dataPoints:n.map(function(i){var a=s0(i,2),s=a[0],c=a[1];return{attributes:s,startTime:c.startTime,endTime:o,value:c.toPointValue()}})}},r}();var l0=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},Ja=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 mm=function(){function r(e){this.monotonic=e,this.kind=ur.SUM}return r.prototype.createAccumulation=function(e){return new Ja(e,this.monotonic)},r.prototype.merge=function(e,t){var n=e.toPointValue(),o=t.toPointValue();return t.reset?new Ja(t.startTime,this.monotonic,o,t.reset):new Ja(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 Ja(t.startTime,this.monotonic,o,!0):new Ja(t.startTime,this.monotonic,o-n)},r.prototype.toMetricData=function(e,t,n,o){return{descriptor:e,aggregationTemporality:t,dataPointType:_t.SUM,dataPoints:n.map(function(i){var a=l0(i,2),s=a[0],c=a[1];return{attributes:s,startTime:c.startTime,endTime:o,value:c.toPointValue()}}),isMonotonic:this.monotonic}},r}();var ho=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)}}(),zr=function(){function r(){}return r.Drop=function(){return jT},r.Sum=function(){return $T},r.LastValue=function(){return qT},r.Histogram=function(){return KT},r.ExponentialHistogram=function(){return c0},r.Default=function(){return u0},r}();var FT=function(r){ho(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 xT,e}(zr);var BT=function(r){ho(e,r);function e(){return r!==null&&r.apply(this,arguments)||this}return e.prototype.createAggregator=function(t){switch(t.type){case se.COUNTER:case se.OBSERVABLE_COUNTER:case se.HISTOGRAM:return e.MONOTONIC_INSTANCE;default:return e.NON_MONOTONIC_INSTANCE}},e.MONOTONIC_INSTANCE=new mm(!0),e.NON_MONOTONIC_INSTANCE=new mm(!1),e}(zr);var zT=function(r){ho(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 UT,e}(zr);var HT=function(r){ho(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 im([0,5,10,25,50,75,100,250,500,750,1e3,2500,5e3,7500,1e4],!0),e}(zr);var GT=function(r){ho(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 im(this._boundaries,this._recordMinMax)},e}(zr);var VT=function(r){ho(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 kT(this._maxSize,this._recordMinMax)},e}(zr);var WT=function(r){ho(e,r);function e(){return r!==null&&r.apply(this,arguments)||this}return e.prototype._resolve=function(t){switch(t.type){case se.COUNTER:case se.UP_DOWN_COUNTER:case se.OBSERVABLE_COUNTER:case se.OBSERVABLE_UP_DOWN_COUNTER:return $T;case se.GAUGE:case se.OBSERVABLE_GAUGE:return qT;case se.HISTOGRAM:return t.advice.explicitBucketBoundaries?new GT(t.advice.explicitBucketBoundaries):KT}return V.warn("Unable to recognize instrument type: "+t.type),jT},e.prototype.createAggregator=function(t){return this._resolve(t).createAggregator(t)},e}(zr);var jT=new FT,$T=new BT,qT=new zT,KT=new HT,c0=new VT,u0=new WT;_e();function sc(){return"unknown_service:"+process.argv0}var On=function(){return On=Object.assign||function(r){for(var e,t=1,n=arguments.length;t<n;t++){e=arguments[t];for(var o in e)Object.prototype.hasOwnProperty.call(e,o)&&(r[o]=e[o])}return r},On.apply(this,arguments)},d0=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())})},p0=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}}},m0=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},gm=function(){function r(e,t){var n=this,o;this._attributes=e,this.asyncAttributesPending=t!=null,this._syncAttributes=(o=this._attributes)!==null&&o!==void 0?o:{},this._asyncAttributesPromise=t?.then(function(i){return n._attributes=Object.assign({},n._attributes,i),n.asyncAttributesPending=!1,i},function(i){return V.debug("a resource's async attributes promise rejected: %s",i),n.asyncAttributesPending=!1,{}})}return r.empty=function(){return r.EMPTY},r.default=function(){var e;return new r((e={},e[ec]=sc(),e[$a]=tc[$a],e[ja]=tc[ja],e[qa]=tc[qa],e))},Object.defineProperty(r.prototype,"attributes",{get:function(){var e;return this.asyncAttributesPending&&V.error("Accessing resource attributes before async attributes settled"),(e=this._attributes)!==null&&e!==void 0?e:{}},enumerable:!1,configurable:!0}),r.prototype.waitForAsyncAttributes=function(){return d0(this,void 0,void 0,function(){return p0(this,function(e){switch(e.label){case 0:return this.asyncAttributesPending?[4,this._asyncAttributesPromise]:[3,2];case 1:e.sent(),e.label=2;case 2:return[2]}})})},r.prototype.merge=function(e){var t=this,n;if(!e)return this;var o=On(On({},this._syncAttributes),(n=e._syncAttributes)!==null&&n!==void 0?n:e.attributes);if(!this._asyncAttributesPromise&&!e._asyncAttributesPromise)return new r(o);var i=Promise.all([this._asyncAttributesPromise,e._asyncAttributesPromise]).then(function(a){var s,c=m0(a,2),l=c[0],u=c[1];return On(On(On(On({},t._syncAttributes),l),(s=e._syncAttributes)!==null&&s!==void 0?s:e.attributes),u)});return new r(o,i)},r.EMPTY=new r({}),r}();var fo;(function(r){r[r.DELTA=0]="DELTA",r[r.CUMULATIVE=1]="CUMULATIVE",r[r.LOWMEMORY=2]="LOWMEMORY"})(fo||(fo={}));_e();var g0=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())})},h0=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}}},hm=function(){return cr.CUMULATIVE},YT=function(r){switch(r){case se.COUNTER:case se.OBSERVABLE_COUNTER:case se.GAUGE:case se.HISTOGRAM:case se.OBSERVABLE_GAUGE:return cr.DELTA;case se.UP_DOWN_COUNTER:case se.OBSERVABLE_UP_DOWN_COUNTER:return cr.CUMULATIVE}},XT=function(r){switch(r){case se.COUNTER:case se.HISTOGRAM:return cr.DELTA;case se.GAUGE:case se.UP_DOWN_COUNTER:case se.OBSERVABLE_UP_DOWN_COUNTER:case se.OBSERVABLE_COUNTER:case se.OBSERVABLE_GAUGE:return cr.CUMULATIVE}};function f0(){var r=Et(),e=r.OTEL_EXPORTER_OTLP_METRICS_TEMPORALITY_PREFERENCE.trim().toLowerCase();return e==="cumulative"?hm:e==="delta"?YT:e==="lowmemory"?XT:(V.warn("OTEL_EXPORTER_OTLP_METRICS_TEMPORALITY_PREFERENCE is set to '"+r.OTEL_EXPORTER_OTLP_METRICS_TEMPORALITY_PREFERENCE+"', but only 'cumulative' and 'delta' are allowed. Using default ('cumulative') instead."),hm)}function S0(r){return r!=null?r===fo.DELTA?YT:r===fo.LOWMEMORY?XT:hm:f0()}function y0(r){return r?.aggregationPreference?r.aggregationPreference:function(e){return zr.Default()}}var JT=function(){function r(e,t){this._otlpExporter=e,this._aggregationSelector=y0(t),this._aggregationTemporalitySelector=S0(t?.temporalityPreference)}return r.prototype.export=function(e,t){this._otlpExporter.export([e],t)},r.prototype.shutdown=function(){return g0(this,void 0,void 0,function(){return h0(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}();_e();_e();var b0=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},QT=1e4,ZT=5,ev=1e3,tv=5e3,rv=1.5;function Qa(r){r===void 0&&(r={});var e={};return Object.entries(r).forEach(function(t){var n=b0(t,2),o=n[0],i=n[1];typeof i<"u"?e[o]=String(i):V.warn('Header "'+o+'" has invalid value ('+i+") and will be ignored")}),e}function fm(r,e){return r.endsWith("/")||(r=r+"/"),r+e}function Sm(r){try{var e=new URL(r);return e.pathname===""&&(e.pathname=e.pathname+"/"),e.toString()}catch{return V.warn("Could not parse export URL: '"+r+"'"),r}}function ym(r){return typeof r=="number"?r<=0?bm(r,QT):r:E0()}function E0(){var r,e=Number((r=Et().OTEL_EXPORTER_OTLP_TRACES_TIMEOUT)!==null&&r!==void 0?r:Et().OTEL_EXPORTER_OTLP_TIMEOUT);return e<=0?bm(e,QT):e}function bm(r,e){return V.warn("Timeout must be greater than 0",r),e}function nv(r){var e=[429,502,503,504];return e.includes(r)}function ov(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 iv=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 CT(this._shutdown,this),this._concurrencyLimit=typeof e.concurrencyLimit=="number"?e.concurrencyLimit:30,this.timeoutMillis=ym(e.timeoutMillis),this.onInit(e)}return r.prototype.export=function(e,t){if(this._shutdownOnce.isCalled){t({code:go.FAILED,error:new Error("Exporter has been shutdown")});return}if(this._sendingPromises.length>=this._concurrencyLimit){t({code:go.FAILED,error:new Error("Concurrent export limit reached")});return}this._export(e).then(function(){t({code:go.SUCCESS})}).catch(function(n){t({code:go.FAILED,error:n})})},r.prototype._export=function(e){var t=this;return new Promise(function(n,o){try{V.debug("items to be sent",e),t.send(e,n,o)}catch(i){o(i)}})},r.prototype.shutdown=function(){return this._shutdownOnce.call()},r.prototype.forceFlush=function(){return Promise.all(this._sendingPromises).then(function(){})},r.prototype._shutdown=function(){return V.debug("shutdown started"),this.onShutdown(),this.forceFlush()},r}();_e();import*as Em from"url";import*as cc from"http";import*as uc from"https";import*as av from"zlib";import{Readable as v0}from"stream";var Ln;(function(r){r.NONE="none",r.GZIP="gzip"})(Ln||(Ln={}));var T0=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(r){T0(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 lc=function(){return lc=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},lc.apply(this,arguments)};function Tm(r,e,t,n,o){var i=r.timeoutMillis,a=new Em.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 bi("Request Timeout");o(h)}else s>=14?l.destroy():l.abort()},i),p={hostname:a.hostname,port:a.port,path:a.pathname,method:"POST",headers:lc({"Content-Type":t},r.headers),agent:r.agent},g=a.protocol==="http:"?cc.request:uc.request,m=function(h,f){switch(h===void 0&&(h=ZT),f===void 0&&(f=ev),l=g(p,function(b){var C="";b.on("data",function(R){return C+=R}),b.on("aborted",function(){if(u){var R=new bi("Request Timeout");o(R)}}),b.on("end",function(){if(u===!1)if(b.statusCode&&b.statusCode<299)V.debug("statusCode: "+b.statusCode,C),n(),clearTimeout(d),clearTimeout(c);else if(b.statusCode&&nv(b.statusCode)&&h>0){var R=void 0;f=rv*f,b.headers["retry-after"]?R=ov(b.headers["retry-after"]):R=Math.round(Math.random()*(tv-f)+f),c=setTimeout(function(){m(h-1,f)},R)}else{var v=new bi(b.statusMessage,b.statusCode,C);o(v),clearTimeout(d),clearTimeout(c)}})}),l.on("error",function(b){if(u){var C=new bi("Request Timeout",b.code);o(C)}else o(b);clearTimeout(d),clearTimeout(c)}),l.on("abort",function(){if(u){var b=new bi("Request Timeout");o(b)}clearTimeout(d),clearTimeout(c)}),r.compression){case Ln.GZIP:{l.setHeader("Content-Encoding","gzip");var E=A0(e);E.on("error",o).pipe(av.createGzip()).on("error",o).pipe(l);break}default:l.end(Buffer.from(e));break}};m()}function A0(r){var e=new v0;return e.push(r),e.push(null),e}function vm(r){if(r.httpAgentOptions&&r.keepAlive===!1){V.warn("httpAgentOptions is used only when keepAlive is true");return}if(!(r.keepAlive===!1||!r.url))try{var e=new Em.URL(r.url),t=e.protocol==="http:"?cc.Agent:uc.Agent;return new t(lc({keepAlive:!0},r.httpAgentOptions))}catch(n){V.error("collector exporter failed to create http agent. err: "+n.message);return}}function Am(r){if(r)return r;var e=Et().OTEL_EXPORTER_OTLP_TRACES_COMPRESSION||Et().OTEL_EXPORTER_OTLP_COMPRESSION;return e===Ln.GZIP?Ln.GZIP:Ln.NONE}_e();var w0=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)}}(),dc=function(r){w0(e,r);function e(t,n,o){t===void 0&&(t={});var i=r.call(this,t)||this;return i.DEFAULT_HEADERS={},i._contentType=o,t.metadata&&V.warn("Metadata cannot be set when using http"),i.headers=Object.assign(i.DEFAULT_HEADERS,Qa(t.headers),Si.parseKeyPairsIntoRecord(Et().OTEL_EXPORTER_OTLP_HEADERS)),i.agent=vm(t),i.compression=Am(t.compression),i._serializer=n,i}return e.prototype.onInit=function(t){},e.prototype.send=function(t,n,o){var i=this;if(this._shutdownOnce.isCalled){V.debug("Shutdown already started. Cannot send objects");return}var a=new Promise(function(c,l){var u;Tm(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}(iv);function lv(r){var e=BigInt(1e9);return BigInt(r[0])*e+BigInt(r[1])}function C0(r){var e=Number(BigInt.asUintN(32,r)),t=Number(BigInt.asUintN(32,r>>BigInt(32)));return{low:e,high:t}}function cv(r){var e=lv(r);return C0(e)}function R0(r){var e=lv(r);return e.toString()}var x0=typeof BigInt<"u"?R0:AT;function sv(r){return r}function uv(r){if(r!==void 0)return Zl(r)}var M0={encodeHrTime:cv,encodeSpanContext:Zl,encodeOptionalSpanContext:uv};function dv(r){var e,t;if(r===void 0)return M0;var n=(e=r.useLongBits)!==null&&e!==void 0?e:!0,o=(t=r.useHex)!==null&&t!==void 0?t:!1;return{encodeHrTime:n?cv:x0,encodeSpanContext:o?sv:Zl,encodeOptionalSpanContext:o?sv:uv}}var _0=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 pv(r){return{name:r.name,version:r.version}}function Ei(r){return Object.keys(r).map(function(e){return mv(e,r[e])})}function mv(r,e){return{key:r,value:gv(e)}}function gv(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(gv)}}:e==="object"&&r!=null?{kvlistValue:{values:Object.entries(r).map(function(t){var n=_0(t,2),o=n[0],i=n[1];return mv(o,i)})}}:{}}function hv(r){return{attributes:Ei(r.attributes),droppedAttributesCount:0}}_e();function Sv(r,e){var t=dv(e);return{resource:hv(r.resource),schemaUrl:void 0,scopeMetrics:P0(r.scopeMetrics,t)}}function P0(r,e){return Array.from(r.map(function(t){return{scope:pv(t.scope),metrics:t.metrics.map(function(n){return I0(n,e)}),schemaUrl:t.scope.schemaUrl}}))}function I0(r,e){var t={name:r.descriptor.name,description:r.descriptor.description,unit:r.descriptor.unit},n=D0(r.aggregationTemporality);switch(r.dataPointType){case _t.SUM:t.sum={aggregationTemporality:n,isMonotonic:r.isMonotonic,dataPoints:fv(r,e)};break;case _t.GAUGE:t.gauge={dataPoints:fv(r,e)};break;case _t.HISTOGRAM:t.histogram={aggregationTemporality:n,dataPoints:L0(r,e)};break;case _t.EXPONENTIAL_HISTOGRAM:t.exponentialHistogram={aggregationTemporality:n,dataPoints:N0(r,e)};break}return t}function O0(r,e,t){var n={attributes:Ei(r.attributes),startTimeUnixNano:t.encodeHrTime(r.startTime),timeUnixNano:t.encodeHrTime(r.endTime)};switch(e){case Kt.INT:n.asInt=r.value;break;case Kt.DOUBLE:n.asDouble=r.value;break}return n}function fv(r,e){return r.dataPoints.map(function(t){return O0(t,r.descriptor.valueType,e)})}function L0(r,e){return r.dataPoints.map(function(t){var n=t.value;return{attributes:Ei(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 N0(r,e){return r.dataPoints.map(function(t){var n=t.value;return{attributes:Ei(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 D0(r){switch(r){case cr.DELTA:return 1;case cr.CUMULATIVE:return 2}}function yv(r,e){return{resourceMetrics:r.map(function(t){return Sv(t,e)})}}var wm={serializeRequest:function(r){var e=yv(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 bv="0.52.1";var Ev=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)}}(),Ti=function(){return Ti=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},Ti.apply(this,arguments)},Tv="v1/metrics",k0="http://localhost:4318/"+Tv,U0={"User-Agent":"OTel-OTLP-Exporter-JavaScript/"+bv},F0=function(r){Ev(e,r);function e(t){var n=r.call(this,t,wm,"application/json")||this;return n.headers=Ti(Ti(Ti(Ti({},n.headers),U0),Si.parseKeyPairsIntoRecord(Et().OTEL_EXPORTER_OTLP_METRICS_HEADERS)),Qa(t?.headers)),n}return e.prototype.getDefaultUrl=function(t){return typeof t.url=="string"?t.url:Et().OTEL_EXPORTER_OTLP_METRICS_ENDPOINT.length>0?Sm(Et().OTEL_EXPORTER_OTLP_METRICS_ENDPOINT):Et().OTEL_EXPORTER_OTLP_ENDPOINT.length>0?fm(Et().OTEL_EXPORTER_OTLP_ENDPOINT,Tv):k0},e}(dc),vv=function(r){Ev(e,r);function e(t){return r.call(this,new F0(t),t)||this}return e}(JT);var vi;(function(r){r[r.DELTA=0]="DELTA",r[r.CUMULATIVE=1]="CUMULATIVE"})(vi||(vi={}));var Hr;(function(r){r[r.HISTOGRAM=0]="HISTOGRAM",r[r.EXPONENTIAL_HISTOGRAM=1]="EXPONENTIAL_HISTOGRAM",r[r.GAUGE=2]="GAUGE",r[r.SUM=3]="SUM"})(Hr||(Hr={}));_e();var B0=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)}}(),Av=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())})},wv=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}}},z0=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},H0=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))},G0=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 Cv(r){return r!=null}function pc(r){var e=Object.keys(r);return e.length===0?"":(e=e.sort(),JSON.stringify(e.map(function(t){return[t,r[t]]})))}function Rv(r){var e,t;return r.name+":"+((e=r.version)!==null&&e!==void 0?e:"")+":"+((t=r.schemaUrl)!==null&&t!==void 0?t:"")}var Cm=function(r){B0(e,r);function e(t){var n=r.call(this,t)||this;return Object.setPrototypeOf(n,e.prototype),n}return e}(Error);function Nn(r,e){var t,n=new Promise(function(i,a){t=setTimeout(function(){a(new Cm("Operation timed out."))},e)});return Promise.race([r,n]).then(function(o){return clearTimeout(t),o},function(o){throw clearTimeout(t),o})}function xv(r){return Av(this,void 0,void 0,function(){var e=this;return wv(this,function(t){return[2,Promise.all(r.map(function(n){return Av(e,void 0,void 0,function(){var o,i;return wv(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 Mv(r){return r.status==="rejected"}function Rm(r,e){var t=[];return r.forEach(function(n){t.push.apply(t,H0([],z0(e(n)),!1))}),t}function _v(r,e){var t,n;if(r.size!==e.size)return!1;try{for(var o=G0(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 Pv(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 Iv(r,e){return r.toLowerCase()===e.toLowerCase()}_e();var dr;(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"})(dr||(dr={}));var xm=function(){function r(){this.kind=dr.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}();_e();var Se;(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"})(Se||(Se={}));function Gr(r,e,t){var n,o,i,a;return W0(r)||V.warn('Invalid metric name: "'+r+'". The metric name should be a ASCII string with a length no greater than 255 characters.'),{name:r,type:e,description:(n=t?.description)!==null&&n!==void 0?n:"",unit:(o=t?.unit)!==null&&o!==void 0?o:"",valueType:(i=t?.valueType)!==null&&i!==void 0?i:Kt.DOUBLE,advice:(a=t?.advice)!==null&&a!==void 0?a:{}}}function Ov(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 Lv(r,e){return Iv(r.name,e.name)&&r.unit===e.unit&&r.type===e.type&&r.valueType===e.valueType}var V0=/^[a-z][a-z0-9_.\-/]{0,254}$/i;function W0(r){return r.match(V0)!=null}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};function $0(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 mc=function(){function r(e,t,n,o){n===void 0&&(n=!0),o===void 0&&(o=$0(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=Pv(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 gc=function(){function r(e,t){this._boundaries=e,this._recordMinMax=t,this.kind=dr.HISTOGRAM}return r.prototype.createAccumulation=function(e){return new mc(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 mc(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 mc(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:Hr.HISTOGRAM,dataPoints:n.map(function(i){var a=j0(i,2),s=a[0],c=a[1],l=c.toPointValue(),u=e.type===Se.GAUGE||e.type===Se.UP_DOWN_COUNTER||e.type===Se.OBSERVABLE_GAUGE||e.type===Se.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}();_e();var Mm=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},_m=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))},Pm=function(){function r(e,t,n,o){e===void 0&&(e=new q0),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 q0=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,_m([n,this._counts.length-t],Mm(this._counts.slice(t)),!1)),o.splice.apply(o,_m([0,t],Mm(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(_m([],Mm(this._counts),!1))},r}();var Nv=52,K0=2146435072,Y0=1048575,Im=1023,hc=-Im+1,fc=Im,Za=Math.pow(2,-1022);function Sc(r){var e=new DataView(new ArrayBuffer(8));e.setFloat64(0,r);var t=e.getUint32(0),n=(t&K0)>>20;return n-Im}function yc(r){var e=new DataView(new ArrayBuffer(8));e.setFloat64(0,r);var t=e.getUint32(0),n=e.getUint32(4),o=(t&Y0)*Math.pow(2,32);return o+n}function es(r,e){return r===0||r===Number.POSITIVE_INFINITY||r===Number.NEGATIVE_INFINITY||Number.isNaN(r)?r:r*Math.pow(2,e)}function kv(r){return r--,r|=r>>1,r|=r>>2,r|=r>>4,r|=r>>8,r|=r>>16,r++,r}var X0=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)}}(),Dn=function(r){X0(e,r);function e(){return r!==null&&r.apply(this,arguments)||this}return e}(Error);var Fv=function(){function r(e){this._shift=-e}return r.prototype.mapToIndex=function(e){if(e<Za)return this._minNormalLowerBoundaryIndex();var t=Sc(e),n=this._rightShift(yc(e)-1,Nv);return t+n>>this._shift},r.prototype.lowerBoundary=function(e){var t=this._minNormalLowerBoundaryIndex();if(e<t)throw new Dn("underflow: "+e+" is < minimum lower boundary: "+t);var n=this._maxNormalLowerBoundaryIndex();if(e>n)throw new Dn("overflow: "+e+" is > maximum lower boundary: "+n);return es(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=hc>>this._shift;return this._shift<2&&e--,e},r.prototype._maxNormalLowerBoundaryIndex=function(){return fc>>this._shift},r.prototype._rightShift=function(e,t){return Math.floor(e*Math.pow(2,-t))},r}();var Bv=function(){function r(e){this._scale=e,this._scaleFactor=es(Math.LOG2E,e),this._inverseFactor=es(Math.LN2,-e)}return r.prototype.mapToIndex=function(e){if(e<=Za)return this._minNormalLowerBoundaryIndex()-1;if(yc(e)===0){var t=Sc(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 Dn("overflow: "+e+" is > maximum lower boundary: "+t)}var n=this._minNormalLowerBoundaryIndex();if(e<=n){if(e===n)return Za;if(e===n-1)return Math.exp((e+(1<<this._scale))/this._scaleFactor)/2;throw new Dn("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 hc<<this._scale},r.prototype._maxNormalLowerBoundaryIndex=function(){return(fc+1<<this._scale)-1},r}();var zv=-10,Hv=20,J0=Array.from({length:31},function(r,e){return e>10?new Bv(e-10):new Fv(e-10)});function Om(r){if(r>Hv||r<zv)throw new Dn("expected scale >= "+zv+" && <= "+Hv+", got: "+r);return J0[r+10]}var Q0=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},bc=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}(),Z0=20,ek=160,Lm=2,Gv=function(){function r(e,t,n,o,i,a,s,c,l,u,d){e===void 0&&(e=e),t===void 0&&(t=ek),n===void 0&&(n=!0),o===void 0&&(o=0),i===void 0&&(i=0),a===void 0&&(a=0),s===void 0&&(s=Number.POSITIVE_INFINITY),c===void 0&&(c=Number.NEGATIVE_INFINITY),l===void 0&&(l=new Pm),u===void 0&&(u=new Pm),d===void 0&&(d=Om(Z0)),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<Lm&&(V.warn("Exponential Histogram Max Size set to "+this._maxSize+", changing to the minimum size of: "+Lm),this._maxSize=Lm)}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=kv(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=Om(t)}},r.prototype._minScale=function(e){var t=Math.min(this.scale,e.scale),n=bc.combine(this._highLowAtScale(this.positive,this.scale,t),this._highLowAtScale(e.positive,e.scale,t)),o=bc.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 bc(0,-1);var o=t-n;return new bc(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 Nm=function(){function r(e,t){this._maxSize=e,this._recordMinMax=t,this.kind=dr.EXPONENTIAL_HISTOGRAM}return r.prototype.createAccumulation=function(e){return new Gv(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:Hr.EXPONENTIAL_HISTOGRAM,dataPoints:n.map(function(i){var a=Q0(i,2),s=a[0],c=a[1],l=c.toPointValue(),u=e.type===Se.GAUGE||e.type===Se.UP_DOWN_COUNTER||e.type===Se.OBSERVABLE_GAUGE||e.type===Se.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}();_e();var tk=jp("OpenTelemetry SDK Context Key SUPPRESS_TRACING");function Vv(r){return r.setValue(tk,!0)}_e();function Wv(){return function(r){V.error(rk(r))}}function rk(r){return typeof r=="string"?r:JSON.stringify(nk(r))}function nk(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 ok=Wv();function Ec(r){try{ok(r)}catch{}}var jv="1.30.1";var ik="process.runtime.name";var ak="service.name";var sk="telemetry.sdk.name",lk="telemetry.sdk.language",ck="telemetry.sdk.version";var $v=ik;var qv=ak;var ts=sk,rs=lk,ns=ck;var uk="nodejs";var Kv=uk;var Ai,So=(Ai={},Ai[ts]="opentelemetry",Ai[$v]="node",Ai[rs]=Kv,Ai[ns]=jv,Ai);function os(r){r.unref()}var Sk=9,yk=6,bk=Math.pow(10,yk),gse=Math.pow(10,Sk);function yo(r){var e=r/1e3,t=Math.trunc(e),n=Math.round(r%1e3*bk);return[t,n]}function wi(r){return r[0]*1e6+r[1]/1e3}var is;(function(r){r[r.SUCCESS=0]="SUCCESS",r[r.FAILED=1]="FAILED"})(is||(is={}));_e();function Yv(r,e){return new Promise(function(t){fi.with(Vv(fi.active()),function(){r.export(e,function(n){t(n)})})})}var Xv={_export:Yv};var Ek=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},Tc=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=yo(Date.now())},r.prototype.setStartTime=function(e){this.startTime=e},r.prototype.toPointValue=function(){return this._current},r}();var Dm=function(){function r(){this.kind=dr.LAST_VALUE}return r.prototype.createAccumulation=function(e){return new Tc(e)},r.prototype.merge=function(e,t){var n=wi(t.sampleTime)>=wi(e.sampleTime)?t:e;return new Tc(e.startTime,n.toPointValue(),n.sampleTime)},r.prototype.diff=function(e,t){var n=wi(t.sampleTime)>=wi(e.sampleTime)?t:e;return new Tc(t.startTime,n.toPointValue(),n.sampleTime)},r.prototype.toMetricData=function(e,t,n,o){return{descriptor:e,aggregationTemporality:t,dataPointType:Hr.GAUGE,dataPoints:n.map(function(i){var a=Ek(i,2),s=a[0],c=a[1];return{attributes:s,startTime:c.startTime,endTime:o,value:c.toPointValue()}})}},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},Ci=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 vc=function(){function r(e){this.monotonic=e,this.kind=dr.SUM}return r.prototype.createAccumulation=function(e){return new Ci(e,this.monotonic)},r.prototype.merge=function(e,t){var n=e.toPointValue(),o=t.toPointValue();return t.reset?new Ci(t.startTime,this.monotonic,o,t.reset):new Ci(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 Ci(t.startTime,this.monotonic,o,!0):new Ci(t.startTime,this.monotonic,o-n)},r.prototype.toMetricData=function(e,t,n,o){return{descriptor:e,aggregationTemporality:t,dataPointType:Hr.SUM,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()}}),isMonotonic:this.monotonic}},r}();var bo=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)}}(),pr=function(){function r(){}return r.Drop=function(){return nA},r.Sum=function(){return oA},r.LastValue=function(){return iA},r.Histogram=function(){return aA},r.ExponentialHistogram=function(){return vk},r.Default=function(){return Ak},r}();var Jv=function(r){bo(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 xm,e}(pr);var Qv=function(r){bo(e,r);function e(){return r!==null&&r.apply(this,arguments)||this}return e.prototype.createAggregator=function(t){switch(t.type){case Se.COUNTER:case Se.OBSERVABLE_COUNTER:case Se.HISTOGRAM:return e.MONOTONIC_INSTANCE;default:return e.NON_MONOTONIC_INSTANCE}},e.MONOTONIC_INSTANCE=new vc(!0),e.NON_MONOTONIC_INSTANCE=new vc(!1),e}(pr);var Zv=function(r){bo(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 Dm,e}(pr);var eA=function(r){bo(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 gc([0,5,10,25,50,75,100,250,500,750,1e3,2500,5e3,7500,1e4],!0),e}(pr);var as=function(r){bo(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 gc(this._boundaries,this._recordMinMax)},e}(pr);var tA=function(r){bo(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 Nm(this._maxSize,this._recordMinMax)},e}(pr);var rA=function(r){bo(e,r);function e(){return r!==null&&r.apply(this,arguments)||this}return e.prototype._resolve=function(t){switch(t.type){case Se.COUNTER:case Se.UP_DOWN_COUNTER:case Se.OBSERVABLE_COUNTER:case Se.OBSERVABLE_UP_DOWN_COUNTER:return oA;case Se.GAUGE:case Se.OBSERVABLE_GAUGE:return iA;case Se.HISTOGRAM:return t.advice.explicitBucketBoundaries?new as(t.advice.explicitBucketBoundaries):aA}return V.warn("Unable to recognize instrument type: "+t.type),nA},e.prototype.createAggregator=function(t){return this._resolve(t).createAggregator(t)},e}(pr);var nA=new Jv,oA=new Qv,iA=new Zv,aA=new eA,vk=new tA,Ak=new rA;var sA=function(r){return pr.Default()},lA=function(r){return vi.CUMULATIVE};var km=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())})},Um=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}}},cA=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},wk=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))},uA=function(){function r(e){var t,n,o;this._shutdown=!1,this._aggregationSelector=(t=e?.aggregationSelector)!==null&&t!==void 0?t:sA,this._aggregationTemporalitySelector=(n=e?.aggregationTemporalitySelector)!==null&&n!==void 0?n:lA,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 km(this,void 0,void 0,function(){var t,n,o,i,a,s;return Um(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(wk([this._sdkMetricProducer.collect({timeoutMillis:e?.timeoutMillis})],cA(this._metricProducers.map(function(l){return l.collect({timeoutMillis:e?.timeoutMillis})})),!1))];case 1:return t=cA.apply(void 0,[c.sent()]),n=t[0],o=t.slice(1),i=n.errors.concat(Rm(o,function(l){return l.errors})),a=n.resourceMetrics.resource,s=n.resourceMetrics.scopeMetrics.concat(Rm(o,function(l){return l.resourceMetrics.scopeMetrics})),[2,{resourceMetrics:{resource:a,scopeMetrics:s},errors:i}]}})})},r.prototype.shutdown=function(e){return km(this,void 0,void 0,function(){return Um(this,function(t){switch(t.label){case 0:return this._shutdown?(V.error("Cannot call shutdown twice."),[2]):e?.timeoutMillis!=null?[3,2]:[4,this.onShutdown()];case 1:return t.sent(),[3,4];case 2:return[4,Nn(this.onShutdown(),e.timeoutMillis)];case 3:t.sent(),t.label=4;case 4:return this._shutdown=!0,[2]}})})},r.prototype.forceFlush=function(e){return km(this,void 0,void 0,function(){return Um(this,function(t){switch(t.label){case 0:return this._shutdown?(V.warn("Cannot forceFlush on already shutdown MetricReader."),[2]):e?.timeoutMillis!=null?[3,2]:[4,this.onForceFlush()];case 1:return t.sent(),[2];case 2:return[4,Nn(this.onForceFlush(),e.timeoutMillis)];case 3:return t.sent(),[2]}})})},r}();_e();var Ck=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)}}(),Ac=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())})},wc=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}}},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},xk=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))},Fm=function(r){Ck(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 Ac(this,void 0,void 0,function(){var t;return wc(this,function(n){switch(n.label){case 0:return n.trys.push([0,2,,3]),[4,Nn(this._doRun(),this._exportTimeout)];case 1:return n.sent(),[3,3];case 2:return t=n.sent(),t instanceof Cm?(V.error("Export took longer than %s milliseconds and timed out.",this._exportTimeout),[2]):(Ec(t),[3,3]);case 3:return[2]}})})},e.prototype._doRun=function(){var t,n;return Ac(this,void 0,void 0,function(){var o,i,a,s,c,l;return wc(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=V).error.apply(l,xk(["PeriodicExportingMetricReader: metrics collection errors"],Rk(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(),V.debug("Error while resolving async portion of resource: ",s),Ec(s),[3,5];case 5:return i.scopeMetrics.length===0?[2]:[4,Xv._export(this._exporter,i)];case 6:if(c=u.sent(),c.code!==is.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),os(this._interval)},e.prototype.onForceFlush=function(){return Ac(this,void 0,void 0,function(){return wc(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 Ac(this,void 0,void 0,function(){return wc(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}(uA);_e();_e();function Cc(){return"unknown_service:"+process.argv0}var kn=function(){return kn=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},kn.apply(this,arguments)},Mk=function(r,e,t,n){function o(i){return i instanceof t?i:new t(function(a){a(i)})}return new(t||(t=Promise))(function(i,a){function s(u){try{l(n.next(u))}catch(d){a(d)}}function c(u){try{l(n.throw(u))}catch(d){a(d)}}function l(u){u.done?i(u.value):o(u.value).then(s,c)}l((n=n.apply(r,e||[])).next())})},_k=function(r,e){var t={label:0,sent:function(){if(i[0]&1)throw i[1];return i[1]},trys:[],ops:[]},n,o,i,a;return a={next:s(0),throw:s(1),return:s(2)},typeof Symbol=="function"&&(a[Symbol.iterator]=function(){return this}),a;function s(l){return function(u){return c([l,u])}}function c(l){if(n)throw new TypeError("Generator is already executing.");for(;t;)try{if(n=1,o&&(i=l[0]&2?o.return:l[0]?o.throw||((i=o.return)&&i.call(o),0):o.next)&&!(i=i.call(o,l[1])).done)return i;switch(o=0,i&&(l=[l[0]&2,i.value]),l[0]){case 0:case 1:i=l;break;case 4:return t.label++,{value:l[1],done:!1};case 5:t.label++,o=l[1],l=[0];continue;case 7:l=t.ops.pop(),t.trys.pop();continue;default:if(i=t.trys,!(i=i.length>0&&i[i.length-1])&&(l[0]===6||l[0]===2)){t=0;continue}if(l[0]===3&&(!i||l[1]>i[0]&&l[1]<i[3])){t.label=l[1];break}if(l[0]===6&&t.label<i[1]){t.label=i[1],i=l;break}if(i&&t.label<i[2]){t.label=i[2],t.ops.push(l);break}i[2]&&t.ops.pop(),t.trys.pop();continue}l=e.call(r,t)}catch(u){l=[6,u],o=0}finally{n=i=0}if(l[0]&5)throw l[1];return{value:l[0]?l[1]:void 0,done:!0}}},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},Rc=function(){function r(e,t){var n=this,o;this._attributes=e,this.asyncAttributesPending=t!=null,this._syncAttributes=(o=this._attributes)!==null&&o!==void 0?o:{},this._asyncAttributesPromise=t?.then(function(i){return n._attributes=Object.assign({},n._attributes,i),n.asyncAttributesPending=!1,i},function(i){return V.debug("a resource's async attributes promise rejected: %s",i),n.asyncAttributesPending=!1,{}})}return r.empty=function(){return r.EMPTY},r.default=function(){var e;return new r((e={},e[qv]=Cc(),e[rs]=So[rs],e[ts]=So[ts],e[ns]=So[ns],e))},Object.defineProperty(r.prototype,"attributes",{get:function(){var e;return this.asyncAttributesPending&&V.error("Accessing resource attributes before async attributes settled"),(e=this._attributes)!==null&&e!==void 0?e:{}},enumerable:!1,configurable:!0}),r.prototype.waitForAsyncAttributes=function(){return Mk(this,void 0,void 0,function(){return _k(this,function(e){switch(e.label){case 0:return this.asyncAttributesPending?[4,this._asyncAttributesPromise]:[3,2];case 1:e.sent(),e.label=2;case 2:return[2]}})})},r.prototype.merge=function(e){var t=this,n;if(!e)return this;var o=kn(kn({},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=Pk(a,2),l=c[0],u=c[1];return kn(kn(kn(kn({},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 dA=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}();_e();var Eo=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)}}(),xc=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=fi.active()),typeof e!="number"){V.warn("non-number value provided to metric "+this._descriptor.name+": "+e);return}this._descriptor.valueType===Kt.INT&&!Number.isInteger(e)&&(V.warn("INT value type cannot accept a floating-point value for "+this._descriptor.name+", ignoring the fractional digits."),e=Math.trunc(e),!Number.isInteger(e))||this._writableMetricStorage.record(e,t,n,yo(Date.now()))},r}();var pA=function(r){Eo(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}(xc);var mA=function(r){Eo(e,r);function e(){return r!==null&&r.apply(this,arguments)||this}return e.prototype.add=function(t,n,o){if(t<0){V.warn("negative value provided to counter "+this._descriptor.name+": "+t);return}this._record(t,n,o)},e}(xc);var gA=function(r){Eo(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}(xc);var hA=function(r){Eo(e,r);function e(){return r!==null&&r.apply(this,arguments)||this}return e.prototype.record=function(t,n,o){if(t<0){V.warn("negative value provided to histogram "+this._descriptor.name+": "+t);return}this._record(t,n,o)},e}(xc);var Mc=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 fA=function(r){Eo(e,r);function e(){return r!==null&&r.apply(this,arguments)||this}return e}(Mc);var SA=function(r){Eo(e,r);function e(){return r!==null&&r.apply(this,arguments)||this}return e}(Mc);var yA=function(r){Eo(e,r);function e(){return r!==null&&r.apply(this,arguments)||this}return e}(Mc);function ss(r){return r instanceof Mc}var bA=function(){function r(e){this._meterSharedState=e}return r.prototype.createGauge=function(e,t){var n=Gr(e,Se.GAUGE,t),o=this._meterSharedState.registerMetricStorage(n);return new gA(o,n)},r.prototype.createHistogram=function(e,t){var n=Gr(e,Se.HISTOGRAM,t),o=this._meterSharedState.registerMetricStorage(n);return new hA(o,n)},r.prototype.createCounter=function(e,t){var n=Gr(e,Se.COUNTER,t),o=this._meterSharedState.registerMetricStorage(n);return new mA(o,n)},r.prototype.createUpDownCounter=function(e,t){var n=Gr(e,Se.UP_DOWN_COUNTER,t),o=this._meterSharedState.registerMetricStorage(n);return new pA(o,n)},r.prototype.createObservableGauge=function(e,t){var n=Gr(e,Se.OBSERVABLE_GAUGE,t),o=this._meterSharedState.registerAsyncMetricStorage(n);return new SA(n,o,this._meterSharedState.observableRegistry)},r.prototype.createObservableCounter=function(e,t){var n=Gr(e,Se.OBSERVABLE_COUNTER,t),o=this._meterSharedState.registerAsyncMetricStorage(n);return new fA(n,o,this._meterSharedState.observableRegistry)},r.prototype.createObservableUpDownCounter=function(e,t){var n=Gr(e,Se.OBSERVABLE_UP_DOWN_COUNTER,t),o=this._meterSharedState.registerAsyncMetricStorage(n);return new yA(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 _c=function(){function r(e){this._instrumentDescriptor=e}return r.prototype.getInstrumentDescriptor=function(){return this._instrumentDescriptor},r.prototype.updateDescription=function(e){this._instrumentDescriptor=Gr(this._instrumentDescriptor.name,this._instrumentDescriptor.type,{description:e,valueType:this._instrumentDescriptor.valueType,unit:this._instrumentDescriptor.unit,advice:this._instrumentDescriptor.advice})},r}();var Ik=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)}}(),EA=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}}},Ok=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 EA(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 EA(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 Ar=function(r){Ik(e,r);function e(){return r.call(this,pc)||this}return e}(Ok);var Lk=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},Pc=function(){function r(e,t){this._aggregator=e,this._activeCollectionStorage=new Ar,this._cumulativeMemoStorage=new Ar,this._overflowAttributes={"otel.metric.overflow":!0},this._cardinalityLimit=(t??2e3)-1,this._overflowHashCode=pc(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=Lk(o,3),a=i[0],s=i[1],c=i[2],l=n._aggregator.createAccumulation(t);l?.record(s);var u=l;if(n._cumulativeMemoStorage.has(a,c)){var d=n._cumulativeMemoStorage.get(a,c);u=n._aggregator.diff(d,l)}else if(n._cumulativeMemoStorage.size>=n._cardinalityLimit&&(a=n._overflowAttributes,c=n._overflowHashCode,n._cumulativeMemoStorage.has(a,c))){var d=n._cumulativeMemoStorage.get(a,c);u=n._aggregator.diff(d,l)}if(n._activeCollectionStorage.has(a,c)){var p=n._activeCollectionStorage.get(a,c);u=n._aggregator.merge(p,u)}n._cumulativeMemoStorage.set(a,l,c),n._activeCollectionStorage.set(a,u,c)})},r.prototype.collect=function(){var e=this._activeCollectionStorage;return this._activeCollectionStorage=new Ar,e},r}();var Bm=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.")},TA=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},Ic=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===vi.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=Nk(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=Bm(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 Ar,i=this._unreportedAccumulations.get(e);if(this._unreportedAccumulations.set(e,[]),i===void 0)return o;try{for(var a=Bm(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=TA(a.value,3),c=s[0],l=s[1],u=s[2];if(e.has(c,u)){var d=e.get(c,u),p=n.merge(d,l);o.set(c,p,u)}else o.set(c,l,u);a=i.next()}return o},r.calibrateStartTime=function(e,t,n){var o,i;try{for(var a=Bm(e.keys()),s=a.next();!s.done;s=a.next()){var c=TA(s.value,2),l=c[0],u=c[1],d=t.get(l,u);d?.setStartTime(n)}}catch(p){o={error:p}}finally{try{s&&!s.done&&(i=a.return)&&i.call(a)}finally{if(o)throw o.error}}return t},r}();function Nk(r){return Array.from(r.entries())}var Dk=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)}}(),kk=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},vA=function(r){Dk(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 Pc(n,s._aggregationCardinalityLimit),s._temporalMetricStorage=new Ic(n,i),s}return e.prototype.record=function(t,n){var o=this,i=new Ar;Array.from(t.entries()).forEach(function(a){var s=kk(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}(_c);_e();function zm(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+`'
@@ -4333,7 +4333,7 @@ ${c}`,{errOptions:{cause:r}})}if(i.includes("element is not visible")){let c="Th
4333
4333
  ${v}${u}</${p}>
4334
4334
  `}if(e.neighbors!==void 0&&e.neighbors>0&&this.parent){let v=this.parent.children.findIndex(I=>I.id===this.id),M=v>0?this.parent.children[v-1]?.serialize({...e,neighbors:0}):"",A=v<this.parent.children.length-1?this.parent.children[v+1]?.serialize({...e,neighbors:0}):"";return`${M||""}
4335
4335
  ${E}
4336
- ${A||""}`}return E}shallowClone(){let e=new r({id:this.id,role:this.role,name:this.name,nameSources:this.nameSources,content:this.content,properties:[],pathFromRoot:this.pathFromRoot,children:[],ignoredReasons:this.ignoredReasons,backendNodeID:this.backendNodeId,ignoredByCDP:this.ignoredByCDP,internalProperties:Dg(this.internalProperties),importantProperties:this.importantProperties,parentFrame:this.parentFrame,flagNotActionableNodes:this.flagNotActionableNodes});return e.tagName=this.tagName,e.dataMomenticId=this.dataMomenticId,e.properties=Dg(this.properties),e}},Ug=class r{constructor(e,t,n,o){this.root=e;this.a11yIdNodeMap=t;this.dataMomenticIdMap=n;this.selectorToNodeMap=o}serialize(e){return this.root.serialize(e)}pruneUsingSummaries(e){let t=this.root;if(!t)throw new Error("Cannot prune a11y tree with no root");let n={},o={},i={},a=c=>{let l=c.shallowClone();if(e[c.id])return l.properties["data-momentic-summary"]=e[c.id],n[c.id]=l,c.dataMomenticId&&(o[c.dataMomenticId]=l),c.mPathSelector&&(i[c.mPathSelector]=l),l;let u=[];for(let d of c.children){let p=a(d);p&&(u.push(p),p.parent=l)}return l.children=u,n[c.id]=l,c.dataMomenticId&&(o[c.dataMomenticId]=l),c.mPathSelector&&(i[c.mPathSelector]=l),l},s=a(t);return new r(s,n,o,i)}pruneUsingRelevantIds(e){let t=this.root;if(!t)throw new Error("Cannot prune a11y tree with no root");function n(i,a=!1){let s=e.has(`${i.id}`)||i.id===t?.id,c=i.shallowClone(),l=i.children,u=!1,d=[];for(let p of l){let g=n(p,s||u);g&&(d.push(g),g.parent=c,u=!0)}if(c.children=d,s||u)return c;if(Fg.includes(i.role)&&a)return c}let o=n(t);return new r(o,this.a11yIdNodeMap,this.dataMomenticIdMap,this.selectorToNodeMap)}pruneToSerializedCharLimit(e){let t=this.root;if(!t)throw new Error("Cannot prune a11y tree with no root");let n=c=>c.role==="StaticText"||c.role==="ListMarker",o=new WeakMap,i=(c,l)=>{if(o.has(c))return o.get(c);let u=c.serialize({indentLevel:l,noChildren:!0});return o.set(c,u),u},a=(c,l,u)=>{let d=c.shallowClone();d.children=[];let p=i(c,l).length;if(u<=p)return{clone:d,used:p};if(n(c)||c.children.length===0)return{clone:d,used:p};let g=p,m=u-g;for(let h of c.children){let f=l+2,E=i(h,f).length;if(m<E)break;let{clone:b,used:C}=a(h,f,m);if(C>m)break;d.children.push(b),b.parent=d,g+=C,m-=C}return{clone:d,used:g}},{clone:s}=a(t,0,Math.max(1e4,e));return new r(s,this.a11yIdNodeMap,this.dataMomenticIdMap,this.selectorToNodeMap)}};function rz(r){return r.name?.value?`"${r.name.value}"`:r.role?.value&&r.role.value!=="none"&&r.role.value!=="generic"?`"${r.role.value}"`:`"${r.nodeId}"`}function nz(r,e,t,n){return r.bounds.x===null||r.bounds.y===null||r.bounds.height===null||r.bounds.width===null||r.bounds.width===0||r.bounds.height===0?!0:r.bounds.x+r.bounds.width<e.leftBound||r.bounds.x>e.rightBound?(Dl({logger:t,logKey:n,maxCount:5,intervalMs:3e3},{domNode:r,logKey:n},"Filtering out node since it is not in the viewport horizontally"),!1):r.bounds.y+r.bounds.height<e.upperBound||r.bounds.y>e.lowerBound?(Dl({logger:t,logKey:n,maxCount:5,intervalMs:3e3},{domNode:r,logKey:n},"Filtering out node since it is not in the viewport vertically"),!1):r.computedStyles.display==="none"?(t.debug({domNode:r},"Filtering out node since it has display none"),!1):!0}async function rR({node:r,parent:e,frameId:t,frameContext:n,axGraph:o,domGraph:i,inputNodeMap:a,flagNotActionableNodes:s,showZeroOpacityElements:c,filterByViewport:l,viewportDetails:u,useMPaths:d,importantProperties:p,allowedA11yIgnoreReasonsOverride:g,cdpClient:m,logger:h,callId:f}){if(!e&&r.parentId)throw new Error(`Got no parent for accessibility node ${r.nodeId}: ${JSON.stringify(r)}`);let E=($,le={})=>{},b=r.backendDOMNodeId,C=JB.includes(r.role?.value?.toLowerCase()??"");if(!C&&b===void 0)return E("Filtering out node since it doesn't exist in the DOM"),[];let R=b?i.backendIdToNode[b]:void 0;if(!C&&!R)try{let $=await z(m.send({method:"DOM.describeNode",params:{backendNodeId:b}}),{milliseconds:750,fallback:()=>{h.debug("Timeout getting node from CDP while processing a11y tree")}});if($&&$.node.nodeName.toLowerCase()==="slot"&&$.node.distributedNodes?.length)h.debug({redirectedDomNode:R,parentAXNode:e?.getNodeOnlySerializedForm(),originalAXNode:r,cdpResult:$},"Redirecting node to assigned slot");else return E("Filtering out node since it doesn't exist in the DOM",{cdpResult:$}),[]}catch($){return E("Filtering out node since it doesn't exist in the DOM",{err:$}),[]}if(R&&e&&l&&u&&r.backendDOMNodeId&&!nz(R,u,h,f))return R.momenticIgnored=!0,[];if(R&&R.computedStyles.display==="none")return R.momenticIgnored=!0,[];if(R&&R.computedStyles.opacity==="0"&&c!==!0){if(c==="inputs-only"&&R.tagName.toLowerCase()!=="input")return R.momenticIgnored=!0,[];if(c===!1)return R.momenticIgnored=!0,[]}let v=r.name?.value?typeof r.name.value=="string"?r.name.value:`${r.name.value}`:"",M=r.value?.value?typeof r.value.value=="string"?r.value.value:`${r.value.value}`:"",A=new kg({domNode:R,id:parseInt(r.nodeId),role:r.role?.value||"",name:v,nameSources:r.name?.sources,content:M,properties:r.properties,children:[],ignoredReasons:r.ignoredReasons?.filter($=>(g??ZC).includes($.name)||eR.includes($.name))??[],pathFromRoot:(e?`${e.pathFromRoot} `:"")+rz(r),backendNodeID:r.backendDOMNodeId,ignoredByCDP:r.ignored,internalProperties:{inCodeMirrorEditor:e?.internalProperties?.inCodeMirrorEditor},importantProperties:p,parentFrame:n.type==="root"?void 0:n,flagNotActionableNodes:s}),I=n,k=a[t],G=t;if(R?.tagName.toLowerCase()==="iframe"&&R.ownedFrameId){let $=n.childFrames.find(Qe=>Qe.frameId===R.ownedFrameId),le=o[$?.frameId??""]?.root,Q=a[$?.frameId??""];if($&&le&&Q){r.childIds&&r.childIds.length>0&&h.debug("Replacing existing node's children with children from the iframe");let Qe=le;r.childIds=Qe.childIds,I=$,k=Q,G=$.frameId}}let ge=R?.childrenBackendIds?.length??0,be=(r.childIds??[]).filter($=>!!k.get(parseInt($))).length;if(ge>be){let $=r.childIds?.map(Q=>k.get(parseInt(Q))).filter(Boolean).map(Q=>Q?.backendDOMNodeId).filter(Q=>Q!==void 0)??[],le=0;for(let Q of R?.childrenBackendIds??[]){if($.includes(Q)){le=(r.childIds?.findIndex(Ue=>k.get(parseInt(Ue))?.backendDOMNodeId===Q)??0)+1;continue}let Qe=i.backendIdToNode[Q];if(!Qe||Qe?.tagName.toLowerCase()!=="svg")continue;let ke=Math.floor(-1*Math.random()*1e7),Gt={nodeId:ke.toString(),parentId:r.nodeId,ignored:!1,backendDOMNodeId:Q,frameId:G,role:{type:"string",value:"graphics-symbol"}};k.set(ke,Gt),r.childIds||(r.childIds=[]),r.childIds.splice(le,0,ke.toString()),le++}}if(r.childIds?.length===1&&R){let $=k.get(parseInt(r.childIds[0])),le=$?.role?.value,Q=R.childrenBackendIds;if($&&le==="StaticText"&&Q.length===1){let Qe=i.backendIdToNode[Q[0]];if(Qe?.tagName?.toLowerCase()==="span"){let ke=Math.floor(-1*Math.random()*1e7).toString(),Gt={nodeId:ke,parentId:r.nodeId,ignored:!1,backendDOMNodeId:Qe.backendNodeId,frameId:G,childIds:[$.nodeId]};$.parentId=ke,k.set(parseInt(ke),Gt),r.childIds=[ke]}}}for(let $ of r.childIds??[]){if(!$)continue;let le=k.get(parseInt($));if(!le)continue;let Q=await rR({node:le,parent:A,domGraph:i,axGraph:o,frameId:G,frameContext:I,inputNodeMap:a,cdpClient:m,logger:h,callId:f,filterByViewport:l,showZeroOpacityElements:c,importantProperties:p,viewportDetails:u,useMPaths:d,flagNotActionableNodes:s});Q.length&&(A.children=A.children.concat(Q))}if(A.role==="StaticText"&&(A.children=[]),A.children.length===1&&A.children[0].role==="StaticText"){let $=A.name,le=A.children[0]?.name;($===le||!le)&&(A.children=[])}let Re=[];for(let $=A.children.length-1;$>=0;$--){let le=A.children[$];if(le.role!=="StaticText"){Re.push(le);continue}if($===0||A.children[$-1].role!=="StaticText"){Re.push(le);continue}A.children[$-1].name+=le.name}if(A.children=Re.reverse(),!A.isInteresting(p)&&r.parentId)return R&&(R.momenticIgnored=!0),A.children;for(let $ of A.children)$.parent=A;return az(A),R&&d&&Ng(R,i),[A]}function nR({node:r,a11yIdNodeMap:e,dataMomenticIdMap:t,logger:n,callId:o,domGraph:i,useMPaths:a,selectorToNodeMap:s,iconKnowledgeBase:c,startId:l=1}){r.id=l,l+=1,e[r.id]=r,r.dataMomenticId?t[r.dataMomenticId]=r:Fg.includes(r.role);let u=r.backendNodeId,d=u!==void 0?i.backendIdToNode[u]:void 0;if(a&&d&&d.mPathSelector&&(s[d.mPathSelector]=r,r.mPathSelector=d.mPathSelector),c&&d&&d.tagName?.toLowerCase()==="svg"){let p=Lg(d,i),g=p?c[p.hash]:void 0,m=g?g.description:void 0;g&&(r.properties["data-momentic-description"]=m)}for(let p of r.children)l=nR({node:p,a11yIdNodeMap:e,dataMomenticIdMap:t,logger:n,callId:o,startId:l,useMPaths:a,domGraph:i,selectorToNodeMap:s,iconKnowledgeBase:c});return l}async function oR({rawA11yGraph:r,domGraph:e,startingFrameId:t,logger:n,cdpClient:o,filterByViewport:i,showZeroOpacityElements:a,flagNotActionableNodes:s,importantProperties:c,viewportDetails:l,useMPaths:u,frameContext:d,iconKnowledgeBase:p,allowedA11yIgnoreReasonsOverride:g}){let m=t??"root",h=r[m]?.root;if(!h)throw new Error("A11y tree has no root");let f=WB(),E=A=>{let I=A.allNodes.filter(G=>!G.ignoredReasons?.find(be=>(g??ZC).includes(be.name))),k=new Map;return I.forEach(G=>{k.set(parseInt(G.nodeId),G)}),k},b={};Object.entries(r).forEach(([A,I])=>{b[A]=E(I)});let C=await rR({node:h,domGraph:e,parent:null,inputNodeMap:b,axGraph:r,frameId:m,frameContext:d,cdpClient:o,logger:n,callId:f,showZeroOpacityElements:a,importantProperties:c,filterByViewport:i,viewportDetails:l,useMPaths:u,flagNotActionableNodes:s,allowedA11yIgnoreReasonsOverride:g});if(C.length>1)throw new Error(`Something went horribly wrong processing the a11y tree, we got: ${JSON.stringify(C)}`);if(C.length===0)throw new Error("There are no accessible elements on this page or frame. Are you sure this website loads properly?");let R={},v={},M={};return nR({node:C[0],a11yIdNodeMap:R,dataMomenticIdMap:v,selectorToNodeMap:M,domGraph:e,logger:n,callId:f,useMPaths:u,iconKnowledgeBase:p}),new Ug(C[0],R,v,M)}function oz(r,e,t,n){if(r==="class"){if(t.tagName?.toLowerCase()==="svg")return e.split(" ").filter(a=>a.length<tR&&!gr.bannedClassSubstrings.some(s=>a.includes(s))).slice(0,3).join(" ");let o=e.split(" "),i=[];for(let a of o)if(iR(a,n)){i.push(a);continue}return i.length?i.join(" "):null}if(e==="true")return!0;if(e==="false")return!1;try{let o=parseInt(e);if(!isNaN(o))return o}catch{}return r==="src"&&e.includes("base64")?e.slice(0,e.indexOf("base64")+6)+"...":e.length>60?e.slice(0,50)+"...":e}function iz(r,e,t){if(!e)return;Object.entries(e.attributes).forEach(([a,s])=>{let c=r[a]||a.startsWith("aria")||qB.includes(a);if((gr.relevantElementAttributes.includes(a)||aR(a,t))&&!c){let u=oz(a,s,e,t);u!==null&&(r[a]=u)}});let n,o=[];if(e.computedStyles.position&&XC.includes(e.computedStyles.position))n=e.computedStyles.position;else if(e.attributes.style){for(let a of XC)if(e.attributes.style.includes(`position: ${a}`)){n=a;break}}n&&o.push(`position: ${n}`);let i;e.computedStyles.opacity&&e.computedStyles.opacity==="0"&&(i="opacity: 0"),i&&o.push(i);for(let a of t?.styles??[]){let s=a.split(":"),c=s[0]?.trim(),l=s[1]?.trim(),u=e.computedStyles[c??""];if(c!==void 0&&l!==void 0&&u!==void 0&&(l==="*"||u===l)){let d=e.computedStyles[c],p=`${c}: ${d}`;o.includes(p)||o.push(p)}}o.length>0&&(r.style=o.join("; "))}function az(r){let e=r.properties.class;if(typeof e=="string"&&e.includes("cm-content")){r.children.forEach((i,a)=>{i.properties["cm-line-number"]=`${a+1}`});return}if(typeof e=="string"&&e.includes("notion-page-content")){r.children.forEach((i,a)=>{i.properties["block-number"]=`${a+1}`}),r.children.length>0&&(r.children[r.children.length-1].properties.description="This is the last block in the document. Click here to add new text to the end.");return}if(r.tagName==="table"){let i=[],a=r.children.find(c=>c.tagName==="thead");if(a){let c=a.children.find(l=>l.tagName==="tr");if(c){let l=c.children.filter(u=>u.tagName==="th");l.forEach((u,d)=>{u.properties["col-index"]||(u.properties["col-index"]=d+1),i?.push(ft(u.name,100,!1))}),i?.length!==l.length&&(i=void 0)}}let s=0;for(let c of r.children)if(c.tagName==="tbody")for(let l=0;l<c.children.length;l++){let u=c.children[l];if(u.tagName!=="tr")continue;if(l===0&&!i?.length){let g=u.children.filter(m=>m.tagName==="th");if(g.length){if(i=g.map(m=>ft(m.name,100,!1)),i.length===g.length)continue;i=void 0}}s+=1,u.properties["row-index"]||(u.properties["row-index"]=s);let d=u.children.filter(g=>g.tagName==="td"||g.tagName==="th"),p=d.length===i?.length;d.forEach((g,m)=>{g.tagName!=="th"&&(g.properties["col-index"]||(g.properties["col-index"]=m+1),p&&(g.properties.col||(g.properties.col=i[m])))})}}}function sz(r){let e=r.properties.class,t=typeof e=="string"&&e.includes("cm-content");r.internalProperties.inCodeMirrorEditor=r.internalProperties?.inCodeMirrorEditor||t}function iR(r,e){if(e&&sR(r,e))return!0;if(gr.bannedClassSubstrings.some(t=>r.includes(t)))return!1;if(gr.alwaysInterestingClassNames.includes(r))return!0;for(let t of gr.alwaysInterestingClassPrefixes)if(r.startsWith(t))return!0;return!1}function aR(r,e){if(e?.attributes?.includes(r))return!0;for(let t of e?.attributes??[])if(t.endsWith("*")){let n=t.slice(0,-1);if(r.startsWith(n))return!0}return!1}function sR(r,e){if(e?.classes?.includes(r))return!0;for(let t of e?.classes??[])if(t.endsWith("*")){let n=t.slice(0,-1);if(r.startsWith(n))return!0}return!1}var su=class r{constructor(e,t,n,o,i){this.session=e;this.logger=t;this.contextGetter=n;this.pageGetter=o;this.defaultTimeoutMs=i}cdpInitializingPromise=void 0;cdpCrashDetails=void 0;cdpFullyDead=!1;loadEventLogs=[];static async init({logger:e,contextGetter:t,pageGetter:n,defaultTimeoutMs:o}){let i=t(),a=n(),s,c;for(let u=0;u<2;u++)try{s=await z(i.newCDPSession(a),{milliseconds:o*u,fallback:()=>{throw new x("UserInfrastructureError",`Failed to initialize Chrome session within the page load timeout (${a.url()})`)}});break}catch(d){await W(ut),c=d}if(!s)throw c;let l=new r(s,e,t,n,o);try{await z(l.registerHandlers(s),{milliseconds:o,message:`CDP handler registration timed out after ${o}ms`})}catch(u){throw l.cdpFullyDead=!0,new x("UserInfrastructureError",`Failed to initialize CDP client: ${u}`)}return l}async registerHandlers(e){e.on("Target.attachedToTarget",async()=>{try{await e.send("Runtime.runIfWaitingForDebugger")}catch(t){this.logger.warn({err:t},"Failed to run Runtime.runIfWaitingForDebugger")}}),e.on("Target.targetCrashed",t=>{this.cdpCrashDetails={...this.cdpCrashDetails??{},targetCrashDetails:JSON.stringify(t)},this.logger.error({payload:t},"CDP session crashed, Momentic will likely not function correctly")}),e.on("Inspector.targetCrashed",t=>{this.cdpCrashDetails={...this.cdpCrashDetails??{},inspectorCrashDetails:JSON.stringify(t)},this.logger.error({payload:t},"CDP inspector session crashed, Momentic will likely not function correctly")}),e.on("Page.frameRequestedNavigation",t=>{this.loadEventLogs.push(`[${new Date(Date.now()).toLocaleString("en-US",{timeZone:"America/Los_Angeles"})}] Frame requested navigation: ${JSON.stringify(t)}`)}),e.on("Page.navigatedWithinDocument",t=>{this.loadEventLogs.push(`[${new Date(Date.now()).toLocaleString("en-US",{timeZone:"America/Los_Angeles"})}] Navigated within document: ${JSON.stringify(t)}`)}),e.on("Page.lifecycleEvent",t=>{this.loadEventLogs.push(`[${new Date(Date.now()).toLocaleString("en-US",{timeZone:"America/Los_Angeles"})}] Page lifecycle event: ${JSON.stringify(t)}`)}),e.on("Page.loadEventFired",()=>{this.loadEventLogs.push(`[${new Date(Date.now()).toLocaleString("en-US",{timeZone:"America/Los_Angeles"})}] Page load event fired`)}),await Promise.all([e.send("Accessibility.enable"),e.send("Page.enable"),e.send("DOM.enable"),e.send("Overlay.enable"),e.send("DOMSnapshot.enable"),e.send("CSS.enable")])}async send({method:e,params:t,timeout:n=this.defaultTimeoutMs,timeoutMsg:o}){for(;this.cdpInitializingPromise;)await z(this.cdpInitializingPromise,{milliseconds:n});if(this.cdpCrashDetails){if(this.cdpFullyDead)throw new x("UserInfrastructureError",`The browser inspector session encountered a critical crash: ${JSON.stringify(this.cdpCrashDetails)}`);this.logger.warn(`Detected crashed CDP client before method ${e}, reinitializing before proceeding...`),await this.reinitialize()}try{return await z(this.session.send(e,t),{milliseconds:n,message:o??`Chrome command ${e} timed out after ${n}ms. This is likely an infrastructure issue caused by a lack of compute resources or a crash at the browser level.`})}catch(i){throw["Internal error","Target crashed"].some(a=>i.message.includes(a))&&!this.cdpInitializingPromise&&(this.logger.warn({err:i},`CDP crashed during CDP method ${e}, re-initializing client`),await this.reinitialize()),i}}async createRawCDPSession(e=this.defaultTimeoutMs){let t=e,n=this.pageGetter(),o=await z(this.contextGetter().newCDPSession(n),{milliseconds:t,fallback:()=>{throw this.logger.error(`Failed to initialize CDP session within the page load timeout (${n.url()})`),new x("UserInfrastructureError",`Failed to initialize CDP session within the page load timeout (${n.url()})`)}});return this.logger.debug(`Created new CDP session for ${n.url()}`),o}async reinitialize(e=this.defaultTimeoutMs){await this.cdpInitializingPromise,this.cdpInitializingPromise=(async()=>{try{let t=this.session;this.session=await this.createRawCDPSession(e),await z(this.registerHandlers(this.session),{milliseconds:e,message:`Failed to register CDP handlers within ${e}ms`}),this.logger.debug("Successfully reinitialized and attached new handlers to CDP session");try{await z(t.detach(),{milliseconds:1e3})}catch(n){this.logger.warn({err:n},"Failed to detach old CDP session after reinitialization, continuing...")}this.cdpCrashDetails=void 0,this.cdpFullyDead=!1}catch(t){this.cdpCrashDetails={...this.cdpCrashDetails??{},reinitializeError:`${t}`},this.cdpFullyDead=!0}finally{this.cdpInitializingPromise=void 0}})(),await this.cdpInitializingPromise}on(e,t){return this.session.on(e,t),this.session}off(e,t){return this.session.off(e,t),this.session}addListener(e,t){return this.session.addListener(e,t),this.session}removeListener(e,t){return this.session.removeListener(e,t),this.session}};var Oi="<empty>";function lz(r){return r.includes("doubleclick.net")||r.includes("googletagmanager.com")||r.includes("googlesyndication.com")||r.includes("s.amazon-adsystem.com")||r.includes("smartadserver.com")||r.includes("omnitagjs.com")||r.includes("x.adroll.com")}function uR(r){let e=r.adFrameStatus?.adFrameType;return e==="child"||e==="root"||lz(r.url)}async function cz(r,e){let t=await r.send({timeout:te,method:"DOM.getFrameOwner",params:{frameId:e}}),o=(await r.send({timeout:te,method:"DOM.pushNodesByBackendIdsToFrontend",params:{backendNodeIds:[t.backendNodeId]}})).nodeIds[0],a=(await r.send({timeout:te,method:"DOM.describeNode",params:{backendNodeId:t.backendNodeId}})).node;return a.nodeId=o,a}async function Li({cdpClient:r,page:e,logger:t}){let n={type:"root",childFrames:[],page:e},o=[],[i,a]=await Promise.all([r.send({timeout:Pi,method:"Page.getFrameTree",params:{}}),r.send({timeout:Pi,method:"DOM.getDocument",params:{depth:0}})]),l=(i.frameTree.childFrames??[]).map(async(d,p)=>{if(uR(d.frame))return null;try{return await dR({cdpClient:r,rawFrameTree:d,indices:[p],parent:n,warnings:o,logger:t})}catch(g){return o.push(`Failed to get child frame: ${g}`),null}}),u=await Promise.all(l);return n.childFrames=u.filter(d=>d!==null),o.length&&t?.warn({warnings:o},"Got warnings when fetching frame tree"),n}async function dR({cdpClient:r,rawFrameTree:e,indices:t,parent:n,warnings:o,logger:i}){let a=e.frame.id,s=await cz(r,a),c=s.attributes??[],l=null,u=[];for(let m of["src","name","id","title","srcdoc","sandbox"]){let h=Gn(c,m);h&&(u.push(`${m}=${JSON.stringify(h)}`),m==="src"&&(l=h))}let d={type:"frame",cdpFrame:e.frame,url:e.frame.url,frameId:a,locationData:{indices:t,attributeSelectors:u},src:l,childFrames:[],parent:n,domNode:s},g=(e.childFrames??[]).map(async(m,h)=>{if(uR(m.frame))return null;try{return await dR({cdpClient:r,rawFrameTree:m,indices:[...t,h],parent:d,warnings:o,logger:i})}catch(f){return o.push(`Failed to get child frame (child ${h} of frame with url ${e.frame.url}): ${f}`),null}});return d.childFrames=(await Promise.all(g)).filter(m=>m!==null),d}async function uz(r){try{return await r.owner().count()===1}catch{return!1}}async function dz(r){try{return await r.count()===1}catch{return!1}}async function $r(r,e){let t=[],n=r;for(;n.parent.type==="frame";)t.push(n.parent),n=n.parent;t.reverse();let o=e,i=[];for(let l of t){let u=!1;for(let d of[...l.locationData.attributeSelectors,Oi]){let p=o.frameLocator(d===Oi?"iframe":`iframe[${d}]`);if(await uz(p)){u=!0,o=p,i.push(d);break}}if(!u)throw new x("ActionFailureError",`Failed to find a unique attribute to identify intermediate frame with url matching '${l.url}'. Please attach a unique 'id', 'name', 'title', or 'src' attribute to the frame.`)}let a;for(let l of[...r.locationData.attributeSelectors,Oi]){let u=o.locator(l===Oi?"iframe":`iframe[${l}]`);if(await dz(u)){a=u,i.push(l);break}}if(!a)throw new x("ActionFailureError",`Failed to find a unique attribute to identify target frame with url matching '${r.url}'. Please attach a unique 'id', 'name', 'title', or 'src' attribute to the frame.`);let s=await a.evaluateHandle(l=>l,{timeout:re}),c=await s.asElement().contentFrame();if(!c)throw new x("InternalWebAgentError",`Failed to load Playwright Frame for iframe with url '${r.url}'`);return await s.dispose(),{frame:c,mPathSelectorTokens:i}}function lR(r,e){let t=[...r],n=[];for(;t.length;){let o=t.shift();e(o)&&n.push(o),t.push(...o.childFrames)}return n}async function pR({page:r,frameTree:e,cache:t}){let n,o=e.childFrames,i=[];if(t.mPathSelectorTokens.length){let s=o;for(let u=0;u<t.mPathSelectorTokens.length-1;u++){let d=t.mPathSelectorTokens[u];d===Oi?s=s.length===1?s[0].childFrames:[]:s=s.filter(p=>p.locationData.attributeSelectors.includes(d)).map(p=>p.childFrames).flat()}let c=[],l=t.mPathSelectorTokens[t.mPathSelectorTokens.length-1];if(l===Oi?c=s:c=s.filter(u=>u.locationData.attributeSelectors.includes(l)),c.length===1)return n=c[0],i.push(`Found unique frame with mpath ${t.mPathSelectorTokens.join(" > ")}`),{resolution:{type:"auto",frame:(await $r(n,r)).frame,handle:n,mPathSelectorTokens:t.mPathSelectorTokens,frameTree:e},logs:i};i.push(`Found ${c.length} frames with mpath ${t.mPathSelectorTokens.join(" > ")}`)}if(t.frameSrcRegex){let s=new RegExp(t.frameSrcRegex),c=lR(o,l=>!!l.src&&s.test(l.src));if(c.length===1)return n=c[0],i.push(`Found unique frame with src regex ${t.frameSrcRegex}`),{resolution:{type:"auto",frame:(await $r(n,r)).frame,handle:n,mPathSelectorTokens:t.mPathSelectorTokens,frameTree:e},logs:i};i.push(`Found ${c.length} frames with src regex ${t.frameSrcRegex}`),t.frameSrcRegex=void 0}if(t.frameUrlRegex){let s=new RegExp(t.frameUrlRegex),c=lR(o,l=>!!l.url&&s.test(l.url));if(c.length===1)return n=c[0],i.push(`Found unique frame with url regex ${t.frameUrlRegex}`),{resolution:{type:"auto",frame:(await $r(n,r)).frame,handle:n,mPathSelectorTokens:t.mPathSelectorTokens,frameTree:e},logs:i};i.push(`Found ${c.length} frames with url regex ${t.frameUrlRegex}`),t.frameUrlRegex=void 0}let a=o;for(let s=0;s<t.indices.length-1;s++)a=a[t.indices[s]]?.childFrames??[];if(n=a[t.indices[t.indices.length-1]],n)return i.push(`Found unique frame with indices ${t.indices.join(" > ")}`),{resolution:{type:"auto",frame:(await $r(n,r)).frame,handle:n,mPathSelectorTokens:t.mPathSelectorTokens,frameTree:e},logs:i};throw i.push(`Found ${a.length} frames with indices ${t.indices}`),new Or("Failed to find the iframe that previously contained this element",[{type:"AUTO_FRAME",matched:!1,logs:i}],"could-not-find-iframe")}function lu(r){return r.type==="auto"?JSON.stringify({type:"auto",frameId:r.handle.frameId}):JSON.stringify(r)}function Bg(r){for(;r.parent.type==="frame";)r=r.parent;return r.parent}function mR(r){let e=Bg(r),t=r.src??"",n=r.url??"",o=[],i=[],a=[...e.childFrames];for(;a.length;){let s=a.shift();s.src&&o.push(s.src),s.url&&i.push(s.url),a.push(...s.childFrames)}return{srcs:o,urls:i,desiredSrc:t,desiredUrl:n}}function gR(r){return r.type==="auto"?{type:"auto",frameId:r.handle.frameId,url:r.handle.url,src:r.handle.src??"",mPathSelectorTokens:r.mPathSelectorTokens.join(" > ")}:{type:"url",url:r.url}}async function hR({frame:r,logger:e,signal:t}){let n;try{n=await r.frameElement(),await pz({frameElementHandle:n,logger:e,signal:t})}catch(o){n?e.warn({err:o},"Failed to scroll iframe into view, trying with raw JS"):e.warn("Failed to scroll iframe into view - no frame element")}finally{await n?.dispose()}}async function pz({frameElementHandle:r,logger:e,signal:t}){let n=await r.boundingBox();await cs({promiseGenerator:async()=>r.evaluate(async i=>{let a=i.scrollTop;i.scrollIntoView({behavior:"instant",block:"center",inline:"center"}),await new Promise(c=>setTimeout(c,250));let s=Date.now();for(;Date.now()-s<1e3;){let c=i.scrollTop;if(c===a)break;a=c,await new Promise(l=>setTimeout(l,250))}}),timeoutMs:Ee,codePath:"scrollIframeIntoView",signal:t}),e.info({oldBb:n,newBb:await r.boundingBox()},"Successfully scrolled iframe into view")}import{create as mz,windowedFiniteBatchScheduler as gz}from"@yornaath/batshit";import{reduce as hz}from"lodash-es";var fz=100,Sz=2e3;function fR(r){return mz({fetcher:async t=>{r(hz(t,(n,o)=>({...n,...o}),{}))},resolver:()=>{},scheduler:gz({windowMs:Sz,maxBatchSize:fz})})}async function SR({event:r,transformer:e,enricher:t,frame:n,lastScreenshotForRecording:o,logger:i}){let{warnings:a,error:s,properties:c}=r.target;if(s){i.error({error:s,warnings:a},"Error while capturing passive click");return}if(a.length&&i.warn({warnings:a},"Warnings while capturing passive click"),!c)return;let l=n.parentFrame()?n.url():void 0,d=n.page().frames().map(m=>m.url());i.debug({frameUrl:l,...r},"Passive click event captured on element");let p,g;if(l)try{let m=await n.frameElement();p=await z(m?.boundingBox(),{milliseconds:te})??void 0;let h=await t.constructIframeRegex({urls:d,srcs:[],desiredUrl:l});if(h.urlRegex)g={type:"url",url:`/${h.urlRegex}/`};else throw new Error(`Got no url regex options: ${JSON.stringify(h)}`)}catch(m){i.warn({err:m},"Failed to construct iframe details for recorded action, using hardcoded URL only"),g={type:"url",url:l}}(async()=>{try{await e.recordElementAction({...r,screenshotBase64:o,frameConfig:g,frameBoundingBox:p})}catch(m){i.error({err:m},"Failed to transform passive click action")}})()}import{randomUUID as qr}from"crypto";import yz from"js-beautify";var bz=["Dead"],cu=class{recordedSteps=new Map;callbacks;signal;generator;testId;orgId;nextStepOffset=0;logger;constructor({signal:e,callbacks:t,generator:n,testId:o,orgId:i,logger:a}){this.signal=e,this.logger=a,this.testId=o,this.orgId=i,this.callbacks={onStepRecorded:(s,c)=>{this.recordedSteps.set(c,{step:s}),t.onStepRecorded(s,c)},onActionReceived:(s,c)=>{this.recordedSteps.set(c,{step:s}),t.onActionReceived?.(s,c)}},this.generator=n}reserveIndexForCommand(e){let t=this.nextStepOffset;return this.recordedSteps.set(t,{step:{id:qr(),type:"PRESET_ACTION",command:Qr(e)}}),this.nextStepOffset++,t}async recordElementAction(e){let{type:t,target:n,frameConfig:o}=e;if(this.signal.aborted){this.logger.debug("Transformer was already cleaned up, ignoring click...");return}let i,a,s=n.properties.attributes.nodeOnlySerializedHtml.trim(),c=s,l;switch(e.frameConfig?e.frameBoundingBox?l={x:e.frameBoundingBox.x+n.properties.boundingBox.x,y:e.frameBoundingBox.y+n.properties.boundingBox.y,width:n.properties.boundingBox.width,height:n.properties.boundingBox.height}:this.logger.warn(e,"No frame bounding box found, refusing to write bounding box"):l=n.properties.boundingBox,t){case"CLICK":{i="CLICK";let h=Qr(i);a={id:qr(),type:"PRESET_ACTION",command:{...h,target:{type:"description",elementDescriptor:c},iframeUrl:o?.url,cache:{target:{id:-1,...n.properties.attributes,targetSource:"RECORDING",targetUpdateTime:new Date().toUTCString(),boundingBox:l}}}};break}case"SELECT":{i="SELECT_OPTION";let h=Qr(i);a={id:qr(),type:"PRESET_ACTION",command:{...h,type:"SELECT_OPTION",iframeUrl:o?.url,target:{type:"description",elementDescriptor:c},cache:{target:{id:-1,...n.properties.attributes,targetSource:"RECORDING",targetUpdateTime:new Date().toUTCString(),boundingBox:l}},choice:{type:"VALUE",value:e.selectedValue??"Unknown option"}}};break}case"MOUSE_DRAG":{i="MOUSE_DRAG";let h=Qr(i);a={id:qr(),type:"PRESET_ACTION",command:{...h,target:{type:"description",elementDescriptor:c},deltaX:e.deltaX.toString(),deltaY:e.deltaY.toString(),iframeUrl:o?.url,cache:{target:{id:-1,...n.properties.attributes,targetSource:"RECORDING",targetUpdateTime:new Date().toUTCString(),targetUpdateLoggerTags:ye(this.logger),boundingBox:l}}}};break}default:throw new Error(`Unknown action type: ${t}`)}let u;e.offset===void 0?(u=this.nextStepOffset,this.nextStepOffset++):u=e.offset,this.callbacks.onActionReceived?.(a,u);let d=e.target.browserState;try{d=yz.html(d,{indent_size:1,indent_with_tabs:!1,preserve_newlines:!1}),d=rC(d,"data-momentic-interacted",4e4)}catch{}let p;try{p=(await this.generator.getReverseMappedDescription({target:d,screenshot:e.screenshotBase64?`data:image/jpeg;base64,${e.screenshotBase64}`:void 0,boundingBox:n.properties.boundingBox},{disableCache:!1,loggerTags:{testId:this.testId,...ye(this.logger)}})).phrase}catch(h){this.logger.error({err:h},"Error generating reverse mapping description"),p=s}let g=this.recordedSteps.get(u)?.step??a,m=g?.command;m&&"target"in m&&m.target?(m.target={type:"description",elementDescriptor:p},this.callbacks.onStepRecorded({...g,command:m},u)):this.logger.warn("Could not find existing command to update after description mapping")}recordKeystroke(e){let{key:t,combinable:n}=e;if(bz.includes(t)||this.signal.aborted)return;let o="normal";t.length>1&&(o="special");let i;if(o==="normal"){let d=Qr("TYPE");i={id:qr(),type:"PRESET_ACTION",command:{...d,target:void 0,value:t,clearContent:!1}}}else{let d=Qr("PRESS");i={id:qr(),type:"PRESET_ACTION",command:{...d,value:t}}}let a,s=this.nextStepOffset-1,c=this.recordedSteps.get(s),l=c?.step,u=l?.command;if(n){if(u?.type===i.command.type){let d=u.value,p=i.command.value;i={id:qr(),type:"PRESET_ACTION",command:{...u,value:i.command.type==="PRESS"?`${d}+${p}`:`${d}${p}`}},a=s}else if(u?.type==="CLICK"&&i.command.type==="TYPE")l.command={...i.command,target:u.target,cache:u.cache},i=c.step,a=s;else if(u?.type==="TYPE"&&i.command.type==="PRESS"&&i.command.value==="Backspace"){let d=u.value;i={id:qr(),type:"PRESET_ACTION",command:{...u,value:d.slice(0,d.length-1)}},a=s}}a===void 0&&(a=this.nextStepOffset,this.nextStepOffset++),this.callbacks.onStepRecorded(i,a)}recordScroll(e){if(this.signal.aborted)return;let t=()=>{let{deltaY:i}=e;if(!i)return;let a=this.nextStepOffset-1,s=this.recordedSteps.get(a)?.step.command,c;s?.type==="SCROLL_DOWN"&&s.deltaY?(i+=s.deltaY,c=a):s?.type==="SCROLL_UP"&&s.deltaY?(i-=s.deltaY,c=a):(c=this.nextStepOffset,this.nextStepOffset++);let l=i>0?"SCROLL_DOWN":"SCROLL_UP",u=Qr(l);u.deltaY=Math.abs(i);let d={id:qr(),type:"PRESET_ACTION",command:u};this.callbacks.onStepRecorded(d,c)},n=()=>{let{deltaX:i}=e;if(!i)return;let a=this.nextStepOffset-1,s=this.recordedSteps.get(a)?.step.command,c;s?.type==="SCROLL_RIGHT"&&s.deltaX?(i+=s.deltaX,c=a):s?.type==="SCROLL_LEFT"&&s.deltaX?(i-=s.deltaX,c=a):(c=this.nextStepOffset,this.nextStepOffset++);let l=i>0?"SCROLL_RIGHT":"SCROLL_LEFT",u=Qr(l);u.deltaX=Math.abs(i);let d={id:qr(),type:"PRESET_ACTION",command:u};this.callbacks.onStepRecorded(d,c)},o=this.recordedSteps.get(this.nextStepOffset-1);o?.step.command.type==="SCROLL_LEFT"||o?.step.command.type==="SCROLL_RIGHT"?(n(),e.deltaY>=20&&t()):(t(),e.deltaX>=20&&n())}};import{z as zg}from"zod";var EAe=zg.object({type:zg.literal("url"),url:zg.string()});var uu=class{smartWaitingTimeoutMs;pageLoadTimeoutMs;allowPartialAccessibilityTree;logger;cdpClient;pageGetter;abortSignalGetter;userControlledBrowserSettings;enricher;iconKnowledgeBase;computedStylesToFetch=["display","opacity","visibility","height","position","background-image"];activeFrameCache;activeFrameConfig;lastA11yIdToNodeMap={};lastDataMomenticIdToNodeMap={};lastSelectorToNodeMap={};lastA11yTreeRoot;lastDomGraph;allowedA11yIgnoreReasonsOverride;constructor({smartWaitingTimeoutMs:e,pageLoadTimeoutMs:t,allowPartialAccessibilityTree:n,logger:o,cdpClient:i,pageGetter:a,abortSignalGetter:s,enricher:c,iconKnowledgeBase:l,userBrowserSettings:u,allowedA11yIgnoreReasonsOverride:d}){if(this.smartWaitingTimeoutMs=e,this.pageLoadTimeoutMs=t,this.allowPartialAccessibilityTree=n,this.logger=o,this.cdpClient=i,this.pageGetter=a,this.abortSignalGetter=s,this.enricher=c,this.iconKnowledgeBase=l,this.userControlledBrowserSettings=u,this.allowedA11yIgnoreReasonsOverride=d,this.userControlledBrowserSettings.importantStyles)for(let p of this.userControlledBrowserSettings.importantStyles){let g=p.split(":");if(g.length!==2){this.logger.warn({style:p},"Invalid style property passed to importantStyles");continue}let m=g[0]?.trim(),h=g[1]?.trim();if(m===void 0||h===void 0){this.logger.warn({style:p},"Invalid style property passed to importantStyles");continue}this.computedStylesToFetch.includes(m)||this.computedStylesToFetch.push(m)}}get frameConfig(){return this.activeFrameConfig}get domGraph(){return this.lastDomGraph}get selectorToNodeMap(){return this.lastSelectorToNodeMap}get dataMomenticIdToNodeMap(){return this.lastDataMomenticIdToNodeMap}get a11yIdToNodeMap(){return this.lastA11yIdToNodeMap}get a11yTreeRoot(){return this.lastA11yTreeRoot}setActiveFrameConfig(e){e?(this.activeFrameConfig=e,this.activeFrameCache=void 0):(this.activeFrameConfig=void 0,this.activeFrameCache=void 0)}reset(){this.activeFrameCache=void 0,this.activeFrameConfig=void 0,this.lastA11yIdToNodeMap={},this.lastDataMomenticIdToNodeMap={},this.lastSelectorToNodeMap={},this.lastA11yTreeRoot=void 0,this.lastDomGraph=void 0}saveAutoFrameCacheDetails(e){if(!this.activeFrameConfig||this.activeFrameConfig.type!=="auto"||!this.userControlledBrowserSettings.autoExpandIframes)return;let t={...e,indices:this.activeFrameConfig.handle.locationData.indices,mPathSelectorTokens:this.activeFrameConfig.mPathSelectorTokens};return this.constructIframeRegexAsync(this.activeFrameConfig.handle,t),t}async getAutoFrameDetailsFromHandle(e){let t=this.pageGetter(),n=Bg(e),{frame:o,mPathSelectorTokens:i}=await $r(e,t),a={indices:e.locationData.indices,mPathSelectorTokens:i};return this.constructIframeRegexAsync(e,a),{cache:a,config:{type:"auto",frame:o,handle:e,mPathSelectorTokens:i,frameTree:n,cache:a}}}async resolveAutoFrameCache(e){let t=this.pageGetter(),n=await Li({cdpClient:this.cdpClient,page:t,logger:this.logger}),{resolution:o,logs:i}=await pR({page:t,frameTree:n,cache:e});return this.logger.info({logs:i},"Resolved auto frame cache"),{...o,cache:e}}async resolveActiveFrameConfig({logger:e=this.logger,signal:t=this.abortSignalGetter()}){if(!this.frameConfig)return null;if(this.activeFrameCache)if(lu(this.frameConfig)!==this.activeFrameCache.frameIdentifierStringified)this.activeFrameCache=void 0;else if(this.activeFrameCache.frame&&"isDetached"in this.activeFrameCache.frame&&this.activeFrameCache.frame.isDetached())this.activeFrameCache=void 0;else return this.activeFrameCache;let n;return this.frameConfig.type==="url"?n=await this.resolveUrlMatcherFrameConfig({config:this.frameConfig,logger:e,signal:t}):n={source:"auto",frame:this.frameConfig.frame,handle:this.frameConfig.handle,frameIdentifierStringified:lu(this.frameConfig),cacheTime:Date.now(),frameTree:this.frameConfig.frameTree,mPathSelectorTokens:this.frameConfig.mPathSelectorTokens},await hR({frame:n.frame,logger:e,signal:t}),this.activeFrameCache=n,n}async executeFunctionInAllFrames(e,t){let n=this.pageGetter(),o=await Li({cdpClient:this.cdpClient,page:n,logger:this.logger}),i=[z(n.evaluate(e,t),{milliseconds:Ee})],a=Array.from(o.childFrames);for(;a.length>0;){let c=a.shift(),l=c.url;l==="about:blank"||l.startsWith("chrome-error://")||(a.push(...c.childFrames),i.push($r(c,n).then(({frame:u})=>z(u.evaluate(e,t),{milliseconds:Ee})).catch(u=>(this.logger.warn({err:u,frameUrl:c.url},"Failed to evaluate function in frame"),"MOMENTIC_FRAME_EVAL_ERROR"))))}return(await Promise.all(i)).filter(c=>c!=="MOMENTIC_FRAME_EVAL_ERROR")}async getAllChildFrameUrls(){let e=this.pageGetter(),t=await Li({cdpClient:this.cdpClient,page:e,logger:this.logger}),n=Array.from(t.childFrames),o=[];for(;n.length>0;){let i=n.shift();n.push(...i.childFrames),o.push(i.src??i.url)}return o}async getDomGraph({devicePixelRatio:e,signal:t,logger:n}){return this.getDOMTree({devicePixelRatio:e??1,signal:t,logger:n??this.logger})}async getA11yTree(e){let t={},n=e.logger??this.logger,o=e.abortSignal??this.abortSignalGetter(),i=this.pageGetter(),a,s,c=null;if(this.frameConfig?.type==="url"){if(a=await hr({fn:()=>this.resolveActiveFrameConfig({logger:n,signal:o}),codePath:"getActiveFrameDetails",logObject:t,signal:o,logger:n})??void 0,!a)throw new x("ActionFailureError","Got null frame details despite active frame config");s=a.handle,c=s.frameId}else this.userControlledBrowserSettings.autoExpandIframes?(s=await hr({fn:()=>Li({cdpClient:this.cdpClient,page:this.pageGetter(),logger:n}),codePath:"getMomenticFrameTree",logObject:t,signal:o,logger:n}),c=null):(s={type:"root",page:i,childFrames:[]},c=null);await hr({fn:async()=>this.addMomenticIds({rootPage:i,childFrames:s.childFrames,frameFilter:a?.frame,logger:n}),codePath:"addIdsToElement",logObject:t,signal:o,logger:n});let l=await hr({fn:()=>this.getDOMTree({devicePixelRatio:e.devicePixelRatio??1,signal:o,logger:n}),codePath:"domFetch",logObject:t,signal:o,logger:n}),u=await hr({fn:()=>this.getRawA11yGraph({cdpClient:this.cdpClient,frameId:c,childFrames:s.childFrames,logTimings:t,logger:n,signal:o}),codePath:"totalA11yFetch",logObject:t,signal:o,logger:n}),{tree:d}=await hr({fn:()=>this.composeA11yDomGraph({opts:e,a11yGraph:u,domGraph:l,startingFrameId:c,frameContext:s,logger:n,iconKnowledgeBase:this.iconKnowledgeBase,showZeroOpacityElements:e.showZeroOpacityElements,flagNotActionableNodes:e.flagNotActionableNodes}),codePath:"a11yProcess",logObject:t,signal:o,logger:n});return Object.values(t).some(p=>p>750)&&n.warn({logTimings:t},"A11y tree fetch component took a long time"),this.lastA11yIdToNodeMap=d.a11yIdNodeMap,this.lastDataMomenticIdToNodeMap=d.dataMomenticIdMap,this.lastA11yTreeRoot=d.root,this.lastDomGraph=l,this.lastSelectorToNodeMap=d.selectorToNodeMap,d}async fetchA11yTreeForRecording(e,t){if(await this.getA11yTree({devicePixelRatio:e,abortSignal:t,logger:_n,filterByViewport:!1,flagNotActionableNodes:!1}),Math.random()<.1){let n=this.lastA11yTreeRoot?.serialize();this.logger.debug({tree:n&&n.length>4e5?"REDACTED_DUE_TO_SIZE":n},"Refreshed a11y tree during recording")}}async getLocatorFromA11yNode({page:e,root:t,node:n}){if(n.backendNodeId===void 0)throw new Error(`Node with a11y id ${n.id} has no backend node ID: ${n.getNodeOnlySerializedForm()}`);if(this.userControlledBrowserSettings.visualActions){let o=this.domGraph?.backendIdToNode[n.backendNodeId];if(!o)throw new Error(`Could not find DOM node for backend node ID ${n.backendNodeId}`);let i=qC({node:o,domGraph:this.domGraph});return KC(e,i)}else return this.getLocatorFromBackendId(t,n.backendNodeId)}async getLocatorFromBackendId(e,t){let n=await this.cdpClient.send({method:"DOM.resolveNode",params:{backendNodeId:t},timeout:Ee});if(!n||!n.object.objectId)throw new Error(`Could not resolve backend node ${t}`);let o;try{o=await YC(this.cdpClient,n.object.objectId)}catch(i){throw this.logger.debug({err:i,object:JSON.stringify(n.object)},"Failed to get ID attribute"),i}return e.locator(wr(o))}getNodeUsingMPathSelector(e){let t=this.selectorToNodeMap[e];if(t)return t;let n=e.split(" > "),o="";for(let i=n.length-1;i>=0;i--){let a=n.slice(i).join(" > ");if(this.selectorToNodeMap[a]){o=a;break}}this.logger.warn({selectorMapSize:Object.keys(this.selectorToNodeMap).length,selector:e,closestSelector:o},"Could not find a11y node using mpath selector")}async resolveUrlMatcherFrameConfig({config:e,signal:t=this.abortSignalGetter(),logger:n=this.logger}){let o=Date.now(),i,a,s,c=0;for(;Date.now()-o<this.smartWaitingTimeoutMs;)try{i=await Li({cdpClient:this.cdpClient,page:this.pageGetter(),logger:n}),a=await this.getMatchingFrameByUrlWithCdp(i,e),n.info({frameId:a.handle.frameId,url:a.handle.url,src:a.handle.src,locationData:a.handle.locationData},`Found matching frame using ${a.matchType}`);break}catch(l){if(s=l,l instanceof x&&l.reason==="UserInfrastructureError")throw l;c%3===0&&this.logger.warn({attempt:c,err:l},"Failed to resolve active frame, retrying..."),await W(ut,t)}finally{c++}if(a)return{source:"url",frame:a.frame,handle:a.handle,frameIdentifierStringified:lu(e),cacheTime:Date.now(),frameTree:i,mPathSelectorTokens:[]};throw s}async getMatchingFrameByUrlWithCdp(e,t){let n=t.url,o=this.pageGetter(),i=Array.from(e.childFrames),a=[];for(;i.length>0;){let s=i.shift(),c=s.domNode;i.push(...s.childFrames);let l=Gn(c.attributes??[],"src"),u=c.contentDocument?.documentURL;if(!l&&!u){this.logger.debug("Skipping frame with no URL or src");continue}for(let d of[l,u])if(d){if(n.startsWith("/")&&n.endsWith("/")){if(new RegExp(n.slice(1,-1)).test(d)){a.push({handle:s,matchType:"regex",...await $r(s,o)});break}}else if(n.trim()===d.trim()){a.push({handle:s,matchType:"url",...await $r(s,o)});break}}}if(a.length===1){let s=a[0];return this.userControlledBrowserSettings.autoExpandIframes||(s.handle.childFrames=[]),s}else throw a.length>1?new Error(`Found multiple frames with src matching '${n}'. Please use a more specific selector.`):new x("ActionFailureError",`Failed to find frame with src matching: ${n}`)}async composeA11yDomGraph({opts:e,a11yGraph:t,domGraph:n,startingFrameId:o,frameContext:i,logger:a,iconKnowledgeBase:s,showZeroOpacityElements:c,flagNotActionableNodes:l}){let u=await oR({rawA11yGraph:t,startingFrameId:o,frameContext:i,domGraph:n,logger:a,cdpClient:this.cdpClient,showZeroOpacityElements:c,flagNotActionableNodes:l,filterByViewport:e.filterByViewport,importantProperties:{attributes:this.userControlledBrowserSettings.importantAttributes,classes:this.userControlledBrowserSettings.importantClasses,styles:this.userControlledBrowserSettings.importantStyles},viewportDetails:void 0,iconKnowledgeBase:s,useMPaths:this.userControlledBrowserSettings.visualActions,allowedA11yIgnoreReasonsOverride:this.allowedA11yIgnoreReasonsOverride});if(!u||!u.root)throw new Error("Accessibility tree appears empty");return{tree:u}}async addMomenticIds({rootPage:e,childFrames:t,frameFilter:n,logger:o}){if(this.userControlledBrowserSettings.visualActions)return;let i=await this.addMomenticIdsHelper(n??e,1);if(!this.userControlledBrowserSettings.autoExpandIframes||n)return;let a=Array.from(t),s=[];for(;a.length>0;){let c=a.shift();a.push(...c.childFrames);let l=async()=>{try{let{frame:u}=await $r(c,e);i=await this.addMomenticIdsHelper(u,i)}catch(u){c.url!=="about:blank"&&o.warn({err:u},"Error adding momentic IDs to child frame, continuing...")}};s.push(l())}await Promise.all(s)}async addMomenticIdsHelper(e,t){if(this.userControlledBrowserSettings.visualActions)return t;let n=this.logger;return await at({root:e,fn:i=>window.addIdsToElement?.(document.body,i),arg:t,timeout:Ee,waitForPageLoad:async()=>{try{await e.waitForLoadState("domcontentloaded",{timeout:this.smartWaitingTimeoutMs})}catch(i){n.warn({err:i},"Error loading frame root adding momentic ids, continuing...")}},codePath:"adding Momentic element IDs to the page"})??t}getPageDomain(e){try{let t=new URL(e);if(!t.hostname)return null;let n=t.hostname.split("."),o=n.length>2?n.slice(-2).join("."):t.hostname;return`${t.protocol}//${o}`}catch{return null}}async decideChildFrameUnrollEligibility({logger:e,warnings:t,handle:n}){try{let{shouldUnroll:o,reason:i}=await this.decideChildFrameUnrollEligibilityHelper({domNode:n.domNode});return{shouldUnroll:o,reason:i}}catch(o){if(o.message.includes("Could not compute box model"))return{shouldUnroll:!1};let i=`Got error when determining whether to filter frame ${n.frameId} with url ${n.url}, allowing it to be fetched: ${o}`;return t?.push(i),e?.warn({err:o},i),{shouldUnroll:!0}}}async decideChildFrameUnrollEligibilityHelper({domNode:e}){let t=e.attributes??[];if(Gn(t,"aria-hidden")==="true")return{shouldUnroll:!1,reason:"aria-hidden"};let n=Gn(t,"style");if(n?.includes("display: none")||n?.includes("visibility: hidden"))return{shouldUnroll:!1,reason:"hidden CSS style"};await this.cdpClient.send({timeout:te,method:"DOM.pushNodesByBackendIdsToFrontend",params:{backendNodeIds:[e.backendNodeId]}});let[o,i]=await Promise.all([this.cdpClient.send({timeout:te,method:"DOM.getBoxModel",params:{backendNodeId:e.backendNodeId}}),this.cdpClient.send({timeout:te,method:"CSS.getComputedStyleForNode",params:{nodeId:e.nodeId}})]);if(!o.model||!o.model.height||!o.model.width)return{shouldUnroll:!1,reason:"no bounding box"};if(o.model.height<10||o.model.width<10)return{shouldUnroll:!1,reason:"small bounding box"};for(let a of i.computedStyle){if(a.name==="display"&&a.value==="none")return{shouldUnroll:!1,reason:"display: none"};if(a.name==="visibility"&&a.value==="hidden")return{shouldUnroll:!1,reason:"visibility: hidden"};if(a.name==="opacity"&&a.value==="0")return{shouldUnroll:!1,reason:"opacity: 0"}}return{shouldUnroll:!0}}async getRawA11yGraph({cdpClient:e,frameId:t,childFrames:n,logTimings:o,logger:i=this.logger,signal:a=this.abortSignalGetter()}){let s=[];try{await this.pageGetter().waitForLoadState("load",{timeout:this.pageLoadTimeoutMs})}catch(g){i.warn({err:g},"Failed to wait for page load event before a11y tree fetch, attempting to continue without it..."),await this.cdpClient.reinitialize()}let c,l;for(let g=0;g<3;g++)try{l=await hr({fn:()=>this.getRawA11yTreeForFrame({frameId:t,timeoutMs:this.pageLoadTimeoutMs,logTimings:o}),codePath:"a11y-tree-fetch-root",logObject:o,logger:i});break}catch(m){c=m,i.warn({err:m},"Reinitializing CDP client before retrying a11y graph fetch"),await this.cdpClient.reinitialize()}if(!l)throw new Error(`Failed to fetch accessibility tree for root page: ${c}`);let u={};if(u[t??"root"]=l,!this.userControlledBrowserSettings.autoExpandIframes)return u;let d=Array.from(n),p=[];for(;d.length>0;){let g=d.shift();try{let{shouldUnroll:h}=await this.decideChildFrameUnrollEligibility({handle:g,warnings:s});if(!h)continue}catch(h){if(h.message.includes("Could not compute box model"))continue;s.push(`Got error when determining whether to filter frame ${g.frameId} with url ${g.url}, allowing it to be fetched: ${h}`)}d.push(...g.childFrames);let m=async()=>{try{let h=await hr({fn:()=>this.getRawA11yTreeForFrame({frameId:g.frameId,timeoutMs:this.smartWaitingTimeoutMs,logTimings:o}),codePath:`a11y-tree-fetch-child-${g.frameId}`,logObject:o,logger:i});u[g.frameId]=h}catch(h){i.warn({err:h,url:g.url,src:g.src},`Error getting raw a11y tree for child frame ${g.frameId}, continuing...`)}};p.push(m())}return await Promise.all(p),s.length>0&&this.logger.warn({warnings:s},"Got warnings when fetching the raw a11y graph"),u}async getRawA11yTreeForFrame({frameId:e,timeoutMs:t,logTimings:n}){let o;if(this.allowPartialAccessibilityTree)o=(await hr({fn:()=>this.cdpClient.send({method:"Accessibility.getFullAXTree",params:{frameId:e??void 0},timeout:t,timeoutMsg:`Fetching the document tree took over ${t}ms. This usually indicates that the current page is too large to be loaded at once, or your machine is severely resource constrained.`}),codePath:"cdp-query-ax-tree",logObject:n,logger:this.logger})).nodes;else{let a=(await hr({fn:()=>this.cdpClient.send({method:"Accessibility.getRootAXNode",params:{frameId:e??void 0},timeout:Ee}),codePath:"cdp-get-root-ax-node",logObject:n,logger:this.logger})).node.backendDOMNodeId;o=(await hr({fn:()=>this.cdpClient.send({method:"Accessibility.queryAXTree",params:{backendNodeId:a},timeout:t,timeoutMsg:`Fetching the document tree took over ${t}ms. This usually indicates that the current page is too large to be loaded at once, or your machine is severely resource constrained.`}),codePath:"cdp-query-ax-tree",logObject:n,logger:this.logger})).nodes}if(!o||o.length<=1)throw new Error("Document is entirely empty");return{root:o[0],allNodes:o}}async getDOMTree({devicePixelRatio:e,signal:t,logger:n}){let o,i=0,a;for(;!o&&i<3;)try{if(o=await this.cdpClient.send({method:"DOMSnapshot.captureSnapshot",params:{computedStyles:this.computedStylesToFetch},timeout:te}),!o||!o.documents.length)throw new Error("Got empty DOM tree")}catch(s){await W(ut,t),i++,a=s}if(!o||!o.documents.length)throw n.error({err:a},"Fatal error fetching DOM tree"),new x("UserInfrastructureError",`Received an empty HTML snapshot from the browser. This usually indicates the page has crashed due to resource consumption issues or hanging client-side JavaScript code: ${a?.message}`);return $C({snapshot:o,devicePixelRatio:e,computedStylesToFetch:this.computedStylesToFetch,logger:n})}constructIframeRegexAsync(e,t){if(t.frameSrcRegex||t.frameUrlRegex)return;let n=mR(e);(async()=>{try{let o=await this.enricher?.constructIframeRegex(n);o?.srcRegex&&(t.frameSrcRegex=o.srcRegex),o?.urlRegex&&(t.frameUrlRegex=o.urlRegex),this.logger.debug({result:o,params:n},"Constructed iframe regex for cache")}catch(o){this.logger.warn({err:o},"Failed to construct iframe regex, skipping...")}})()}};function Hg(r){let e=[],t="";for(let n of r)n==="+"&&t?(e.push(t),t=""):t+=n;return e.push(t),e}var hs=class r{static USER_AGENT=eu;abortSignal=void 0;contextInitialized=!1;cleanedUp=!1;browser;context;properties;page;userControlledBrowserSettings;pageLoadPromises={};lastTabChangeEventTimeout=void 0;pageLoadAbortControllers=new Set;pageLoadAbortListenerCleanup;clientCallbacks;harBatcher;iconKnowledgeBase;cdpClient;debugData={logsPerPage:[]};recentFrameNavigations={};requestRecorders={};mocks={};customHeaders=[];enricher;storage;logger;stateManager;transformer;lastScreenshotForRecording=void 0;originsVisited=new Set;viewport;onVideoPageChange;baseUrl;constructor({storage:e,enricher:t,browser:n,context:o,page:i,baseUrl:a,logger:s,userBrowserSettings:c,viewport:l,properties:u,clientCallbacks:d,iconKnowledgeBase:p,onVideoPageChange:g}){yE(c),this.storage=e,this.enricher=t,this.browser=n,this.context=o,this.page=i,this.baseUrl=a,this.logger=s,this.userControlledBrowserSettings=c,this.viewport=l,this.properties=u,this.clientCallbacks=d,this.iconKnowledgeBase=p,this.onVideoPageChange=g}registerAbortSignal(e){if(this.pageLoadAbortListenerCleanup&&(this.pageLoadAbortListenerCleanup(),this.pageLoadAbortListenerCleanup=void 0),this.abortSignal=e,!this.abortSignal)return;let t=()=>{for(let n of this.pageLoadAbortControllers)n.abort();this.pageLoadAbortControllers.clear()};if(this.abortSignal.aborted){t();return}this.abortSignal.addEventListener("abort",t),this.pageLoadAbortListenerCleanup=()=>{this.abortSignal?.removeEventListener("abort",t)}}async initialize({grantPermissions:e,runInitScripts:t,timingRecorder:n}){if(this.contextInitialized)return;let o={[Qc]:this.userBrowserSettings.visualActions},i=[];if(this.userControlledBrowserSettings.extraHeaders&&i.push(this.context.setExtraHTTPHeaders(this.userControlledBrowserSettings.extraHeaders)),e){let u=["clipboard-read","clipboard-write","microphone","camera","geolocation"];kr||u.push("local-network-access"),i.push(this.context.grantPermissions(u))}i.push(this.context.addInitScript({content:`${ag.htmlUtilsLibJs}
4336
+ ${A||""}`}return E}shallowClone(){let e=new r({id:this.id,role:this.role,name:this.name,nameSources:this.nameSources,content:this.content,properties:[],pathFromRoot:this.pathFromRoot,children:[],ignoredReasons:this.ignoredReasons,backendNodeID:this.backendNodeId,ignoredByCDP:this.ignoredByCDP,internalProperties:Dg(this.internalProperties),importantProperties:this.importantProperties,parentFrame:this.parentFrame,flagNotActionableNodes:this.flagNotActionableNodes});return e.tagName=this.tagName,e.dataMomenticId=this.dataMomenticId,e.properties=Dg(this.properties),e}},Ug=class r{constructor(e,t,n,o){this.root=e;this.a11yIdNodeMap=t;this.dataMomenticIdMap=n;this.selectorToNodeMap=o}serialize(e){return this.root.serialize(e)}pruneUsingSummaries(e){let t=this.root;if(!t)throw new Error("Cannot prune a11y tree with no root");let n={},o={},i={},a=c=>{let l=c.shallowClone();if(e[c.id])return l.properties["data-momentic-summary"]=e[c.id],n[c.id]=l,c.dataMomenticId&&(o[c.dataMomenticId]=l),c.mPathSelector&&(i[c.mPathSelector]=l),l;let u=[];for(let d of c.children){let p=a(d);p&&(u.push(p),p.parent=l)}return l.children=u,n[c.id]=l,c.dataMomenticId&&(o[c.dataMomenticId]=l),c.mPathSelector&&(i[c.mPathSelector]=l),l},s=a(t);return new r(s,n,o,i)}pruneUsingRelevantIds(e){let t=this.root;if(!t)throw new Error("Cannot prune a11y tree with no root");function n(i,a=!1){let s=e.has(`${i.id}`)||i.id===t?.id,c=i.shallowClone(),l=i.children,u=!1,d=[];for(let p of l){let g=n(p,s||u);g&&(d.push(g),g.parent=c,u=!0)}if(c.children=d,s||u)return c;if(Fg.includes(i.role)&&a)return c}let o=n(t);return new r(o,this.a11yIdNodeMap,this.dataMomenticIdMap,this.selectorToNodeMap)}pruneToSerializedCharLimit(e){let t=this.root;if(!t)throw new Error("Cannot prune a11y tree with no root");let n=c=>c.role==="StaticText"||c.role==="ListMarker",o=new WeakMap,i=(c,l)=>{if(o.has(c))return o.get(c);let u=c.serialize({indentLevel:l,noChildren:!0});return o.set(c,u),u},a=(c,l,u)=>{let d=c.shallowClone();d.children=[];let p=i(c,l).length;if(u<=p)return{clone:d,used:p};if(n(c)||c.children.length===0)return{clone:d,used:p};let g=p,m=u-g;for(let h of c.children){let f=l+2,E=i(h,f).length;if(m<E)break;let{clone:b,used:C}=a(h,f,m);if(C>m)break;d.children.push(b),b.parent=d,g+=C,m-=C}return{clone:d,used:g}},{clone:s}=a(t,0,Math.max(1e4,e));return new r(s,this.a11yIdNodeMap,this.dataMomenticIdMap,this.selectorToNodeMap)}};function rz(r){return r.name?.value?`"${r.name.value}"`:r.role?.value&&r.role.value!=="none"&&r.role.value!=="generic"?`"${r.role.value}"`:`"${r.nodeId}"`}function nz(r,e,t,n){return r.bounds.x===null||r.bounds.y===null||r.bounds.height===null||r.bounds.width===null||r.bounds.width===0||r.bounds.height===0?!0:r.bounds.x+r.bounds.width<e.leftBound||r.bounds.x>e.rightBound?(Dl({logger:t,logKey:n,maxCount:5,intervalMs:3e3},{domNode:r,logKey:n},"Filtering out node since it is not in the viewport horizontally"),!1):r.bounds.y+r.bounds.height<e.upperBound||r.bounds.y>e.lowerBound?(Dl({logger:t,logKey:n,maxCount:5,intervalMs:3e3},{domNode:r,logKey:n},"Filtering out node since it is not in the viewport vertically"),!1):r.computedStyles.display==="none"?(t.debug({domNode:r},"Filtering out node since it has display none"),!1):!0}async function rR({node:r,parent:e,frameId:t,frameContext:n,axGraph:o,domGraph:i,inputNodeMap:a,flagNotActionableNodes:s,showZeroOpacityElements:c,filterByViewport:l,viewportDetails:u,useMPaths:d,importantProperties:p,allowedA11yIgnoreReasonsOverride:g,cdpClient:m,logger:h,callId:f}){if(!e&&r.parentId)throw new Error(`Got no parent for accessibility node ${r.nodeId}: ${JSON.stringify(r)}`);let E=($,le={})=>{},b=r.backendDOMNodeId,C=JB.includes(r.role?.value?.toLowerCase()??"");if(!C&&b===void 0)return E("Filtering out node since it doesn't exist in the DOM"),[];let R=b?i.backendIdToNode[b]:void 0;if(!C&&!R)try{let $=await z(m.send({method:"DOM.describeNode",params:{backendNodeId:b}}),{milliseconds:750,fallback:()=>{h.debug("Timeout getting node from CDP while processing a11y tree")}});if($&&$.node.nodeName.toLowerCase()==="slot"&&$.node.distributedNodes?.length)h.debug({redirectedDomNode:R,parentAXNode:e?.getNodeOnlySerializedForm(),originalAXNode:r,cdpResult:$},"Redirecting node to assigned slot");else return E("Filtering out node since it doesn't exist in the DOM",{cdpResult:$}),[]}catch($){return E("Filtering out node since it doesn't exist in the DOM",{err:$}),[]}if(R&&e&&l&&u&&r.backendDOMNodeId&&!nz(R,u,h,f))return R.momenticIgnored=!0,[];if(R&&R.computedStyles.display==="none")return R.momenticIgnored=!0,[];if(R&&R.computedStyles.opacity==="0"&&c!==!0){if(c==="inputs-only"&&R.tagName.toLowerCase()!=="input")return R.momenticIgnored=!0,[];if(c===!1)return R.momenticIgnored=!0,[]}let v=r.name?.value?typeof r.name.value=="string"?r.name.value:`${r.name.value}`:"",M=r.value?.value?typeof r.value.value=="string"?r.value.value:`${r.value.value}`:"",A=new kg({domNode:R,id:parseInt(r.nodeId),role:r.role?.value||"",name:v,nameSources:r.name?.sources,content:M,properties:r.properties,children:[],ignoredReasons:r.ignoredReasons?.filter($=>(g??ZC).includes($.name)||eR.includes($.name))??[],pathFromRoot:(e?`${e.pathFromRoot} `:"")+rz(r),backendNodeID:r.backendDOMNodeId,ignoredByCDP:r.ignored,internalProperties:{inCodeMirrorEditor:e?.internalProperties?.inCodeMirrorEditor},importantProperties:p,parentFrame:n.type==="root"?void 0:n,flagNotActionableNodes:s}),I=n,k=a[t],G=t;if(R?.tagName.toLowerCase()==="iframe"&&R.ownedFrameId){let $=n.childFrames.find(Qe=>Qe.frameId===R.ownedFrameId),le=o[$?.frameId??""]?.root,Q=a[$?.frameId??""];if($&&le&&Q){r.childIds&&r.childIds.length>0&&h.debug("Replacing existing node's children with children from the iframe");let Qe=le;r.childIds=Qe.childIds,I=$,k=Q,G=$.frameId}}let ge=R?.childrenBackendIds?.length??0,be=(r.childIds??[]).filter($=>!!k.get(parseInt($))).length;if(ge>be){let $=r.childIds?.map(Q=>k.get(parseInt(Q))).filter(Boolean).map(Q=>Q?.backendDOMNodeId).filter(Q=>Q!==void 0)??[],le=0;for(let Q of R?.childrenBackendIds??[]){if($.includes(Q)){le=(r.childIds?.findIndex(Ue=>k.get(parseInt(Ue))?.backendDOMNodeId===Q)??0)+1;continue}let Qe=i.backendIdToNode[Q];if(!Qe||Qe?.tagName.toLowerCase()!=="svg")continue;let ke=Math.floor(-1*Math.random()*1e7),Gt={nodeId:ke.toString(),parentId:r.nodeId,ignored:!1,backendDOMNodeId:Q,frameId:G,role:{type:"string",value:"graphics-symbol"}};k.set(ke,Gt),r.childIds||(r.childIds=[]),r.childIds.splice(le,0,ke.toString()),le++}}if(r.childIds?.length===1&&R){let $=k.get(parseInt(r.childIds[0])),le=$?.role?.value,Q=R.childrenBackendIds;if($&&le==="StaticText"&&Q.length===1){let Qe=i.backendIdToNode[Q[0]];if(Qe?.tagName?.toLowerCase()==="span"){let ke=Math.floor(-1*Math.random()*1e7).toString(),Gt={nodeId:ke,parentId:r.nodeId,ignored:!1,backendDOMNodeId:Qe.backendNodeId,frameId:G,childIds:[$.nodeId]};$.parentId=ke,k.set(parseInt(ke),Gt),r.childIds=[ke]}}}for(let $ of r.childIds??[]){if(!$)continue;let le=k.get(parseInt($));if(!le)continue;let Q=await rR({node:le,parent:A,domGraph:i,axGraph:o,frameId:G,frameContext:I,inputNodeMap:a,cdpClient:m,logger:h,callId:f,filterByViewport:l,showZeroOpacityElements:c,importantProperties:p,viewportDetails:u,useMPaths:d,flagNotActionableNodes:s});Q.length&&(A.children=A.children.concat(Q))}if(A.role==="StaticText"&&(A.children=[]),A.children.length===1&&A.children[0].role==="StaticText"){let $=A.name,le=A.children[0]?.name;($===le||!le)&&(A.children=[])}let Re=[];for(let $=A.children.length-1;$>=0;$--){let le=A.children[$];if(le.role!=="StaticText"){Re.push(le);continue}if($===0||A.children[$-1].role!=="StaticText"){Re.push(le);continue}A.children[$-1].name+=le.name}if(A.children=Re.reverse(),!A.isInteresting(p)&&r.parentId)return R&&(R.momenticIgnored=!0),A.children;for(let $ of A.children)$.parent=A;return az(A),R&&d&&Ng(R,i),[A]}function nR({node:r,a11yIdNodeMap:e,dataMomenticIdMap:t,logger:n,callId:o,domGraph:i,useMPaths:a,selectorToNodeMap:s,iconKnowledgeBase:c,startId:l=1}){r.id=l,l+=1,e[r.id]=r,r.dataMomenticId?t[r.dataMomenticId]=r:Fg.includes(r.role);let u=r.backendNodeId,d=u!==void 0?i.backendIdToNode[u]:void 0;if(a&&d&&d.mPathSelector&&(s[d.mPathSelector]=r,r.mPathSelector=d.mPathSelector),c&&d&&d.tagName?.toLowerCase()==="svg"){let p=Lg(d,i),g=p?c[p.hash]:void 0,m=g?g.description:void 0;g&&(r.properties["data-momentic-description"]=m)}for(let p of r.children)l=nR({node:p,a11yIdNodeMap:e,dataMomenticIdMap:t,logger:n,callId:o,startId:l,useMPaths:a,domGraph:i,selectorToNodeMap:s,iconKnowledgeBase:c});return l}async function oR({rawA11yGraph:r,domGraph:e,startingFrameId:t,logger:n,cdpClient:o,filterByViewport:i,showZeroOpacityElements:a,flagNotActionableNodes:s,importantProperties:c,viewportDetails:l,useMPaths:u,frameContext:d,iconKnowledgeBase:p,allowedA11yIgnoreReasonsOverride:g}){let m=t??"root",h=r[m]?.root;if(!h)throw new Error("A11y tree has no root");let f=WB(),E=A=>{let I=A.allNodes.filter(G=>!G.ignoredReasons?.find(be=>(g??ZC).includes(be.name))),k=new Map;return I.forEach(G=>{k.set(parseInt(G.nodeId),G)}),k},b={};Object.entries(r).forEach(([A,I])=>{b[A]=E(I)});let C=await rR({node:h,domGraph:e,parent:null,inputNodeMap:b,axGraph:r,frameId:m,frameContext:d,cdpClient:o,logger:n,callId:f,showZeroOpacityElements:a,importantProperties:c,filterByViewport:i,viewportDetails:l,useMPaths:u,flagNotActionableNodes:s,allowedA11yIgnoreReasonsOverride:g});if(C.length>1)throw new Error(`Something went horribly wrong processing the a11y tree, we got: ${JSON.stringify(C)}`);if(C.length===0)throw new Error("There are no accessible elements on this page or frame. Are you sure this website loads properly?");let R={},v={},M={};return nR({node:C[0],a11yIdNodeMap:R,dataMomenticIdMap:v,selectorToNodeMap:M,domGraph:e,logger:n,callId:f,useMPaths:u,iconKnowledgeBase:p}),new Ug(C[0],R,v,M)}function oz(r,e,t,n){if(r==="class"){if(t.tagName?.toLowerCase()==="svg")return e.split(" ").filter(a=>a.length<tR&&!gr.bannedClassSubstrings.some(s=>a.includes(s))).slice(0,3).join(" ");let o=e.split(" "),i=[];for(let a of o)if(iR(a,n)){i.push(a);continue}return i.length?i.join(" "):null}if(e==="true")return!0;if(e==="false")return!1;try{let o=Number(e);if(!Number.isNaN(o))return o}catch{}return r==="src"&&e.includes("base64")?e.slice(0,e.indexOf("base64")+6)+"...":e.length>60?e.slice(0,50)+"...":e}function iz(r,e,t){if(!e)return;Object.entries(e.attributes).forEach(([a,s])=>{let c=r[a]||a.startsWith("aria")||qB.includes(a);if((gr.relevantElementAttributes.includes(a)||aR(a,t))&&!c){let u=oz(a,s,e,t);u!==null&&(r[a]=u)}});let n,o=[];if(e.computedStyles.position&&XC.includes(e.computedStyles.position))n=e.computedStyles.position;else if(e.attributes.style){for(let a of XC)if(e.attributes.style.includes(`position: ${a}`)){n=a;break}}n&&o.push(`position: ${n}`);let i;e.computedStyles.opacity&&e.computedStyles.opacity==="0"&&(i="opacity: 0"),i&&o.push(i);for(let a of t?.styles??[]){let s=a.split(":"),c=s[0]?.trim(),l=s[1]?.trim(),u=e.computedStyles[c??""];if(c!==void 0&&l!==void 0&&u!==void 0&&(l==="*"||u===l)){let d=e.computedStyles[c],p=`${c}: ${d}`;o.includes(p)||o.push(p)}}o.length>0&&(r.style=o.join("; "))}function az(r){let e=r.properties.class;if(typeof e=="string"&&e.includes("cm-content")){r.children.forEach((i,a)=>{i.properties["cm-line-number"]=`${a+1}`});return}if(typeof e=="string"&&e.includes("notion-page-content")){r.children.forEach((i,a)=>{i.properties["block-number"]=`${a+1}`}),r.children.length>0&&(r.children[r.children.length-1].properties.description="This is the last block in the document. Click here to add new text to the end.");return}if(r.tagName==="table"){let i=[],a=r.children.find(c=>c.tagName==="thead");if(a){let c=a.children.find(l=>l.tagName==="tr");if(c){let l=c.children.filter(u=>u.tagName==="th");l.forEach((u,d)=>{u.properties["col-index"]||(u.properties["col-index"]=d+1),i?.push(ft(u.name,100,!1))}),i?.length!==l.length&&(i=void 0)}}let s=0;for(let c of r.children)if(c.tagName==="tbody")for(let l=0;l<c.children.length;l++){let u=c.children[l];if(u.tagName!=="tr")continue;if(l===0&&!i?.length){let g=u.children.filter(m=>m.tagName==="th");if(g.length){if(i=g.map(m=>ft(m.name,100,!1)),i.length===g.length)continue;i=void 0}}s+=1,u.properties["row-index"]||(u.properties["row-index"]=s);let d=u.children.filter(g=>g.tagName==="td"||g.tagName==="th"),p=d.length===i?.length;d.forEach((g,m)=>{g.tagName!=="th"&&(g.properties["col-index"]||(g.properties["col-index"]=m+1),p&&(g.properties.col||(g.properties.col=i[m])))})}}}function sz(r){let e=r.properties.class,t=typeof e=="string"&&e.includes("cm-content");r.internalProperties.inCodeMirrorEditor=r.internalProperties?.inCodeMirrorEditor||t}function iR(r,e){if(e&&sR(r,e))return!0;if(gr.bannedClassSubstrings.some(t=>r.includes(t)))return!1;if(gr.alwaysInterestingClassNames.includes(r))return!0;for(let t of gr.alwaysInterestingClassPrefixes)if(r.startsWith(t))return!0;return!1}function aR(r,e){if(e?.attributes?.includes(r))return!0;for(let t of e?.attributes??[])if(t.endsWith("*")){let n=t.slice(0,-1);if(r.startsWith(n))return!0}return!1}function sR(r,e){if(e?.classes?.includes(r))return!0;for(let t of e?.classes??[])if(t.endsWith("*")){let n=t.slice(0,-1);if(r.startsWith(n))return!0}return!1}var su=class r{constructor(e,t,n,o,i){this.session=e;this.logger=t;this.contextGetter=n;this.pageGetter=o;this.defaultTimeoutMs=i}cdpInitializingPromise=void 0;cdpCrashDetails=void 0;cdpFullyDead=!1;loadEventLogs=[];static async init({logger:e,contextGetter:t,pageGetter:n,defaultTimeoutMs:o}){let i=t(),a=n(),s,c;for(let u=0;u<2;u++)try{s=await z(i.newCDPSession(a),{milliseconds:o*u,fallback:()=>{throw new x("UserInfrastructureError",`Failed to initialize Chrome session within the page load timeout (${a.url()})`)}});break}catch(d){await W(ut),c=d}if(!s)throw c;let l=new r(s,e,t,n,o);try{await z(l.registerHandlers(s),{milliseconds:o,message:`CDP handler registration timed out after ${o}ms`})}catch(u){throw l.cdpFullyDead=!0,new x("UserInfrastructureError",`Failed to initialize CDP client: ${u}`)}return l}async registerHandlers(e){e.on("Target.attachedToTarget",async()=>{try{await e.send("Runtime.runIfWaitingForDebugger")}catch(t){this.logger.warn({err:t},"Failed to run Runtime.runIfWaitingForDebugger")}}),e.on("Target.targetCrashed",t=>{this.cdpCrashDetails={...this.cdpCrashDetails??{},targetCrashDetails:JSON.stringify(t)},this.logger.error({payload:t},"CDP session crashed, Momentic will likely not function correctly")}),e.on("Inspector.targetCrashed",t=>{this.cdpCrashDetails={...this.cdpCrashDetails??{},inspectorCrashDetails:JSON.stringify(t)},this.logger.error({payload:t},"CDP inspector session crashed, Momentic will likely not function correctly")}),e.on("Page.frameRequestedNavigation",t=>{this.loadEventLogs.push(`[${new Date(Date.now()).toLocaleString("en-US",{timeZone:"America/Los_Angeles"})}] Frame requested navigation: ${JSON.stringify(t)}`)}),e.on("Page.navigatedWithinDocument",t=>{this.loadEventLogs.push(`[${new Date(Date.now()).toLocaleString("en-US",{timeZone:"America/Los_Angeles"})}] Navigated within document: ${JSON.stringify(t)}`)}),e.on("Page.lifecycleEvent",t=>{this.loadEventLogs.push(`[${new Date(Date.now()).toLocaleString("en-US",{timeZone:"America/Los_Angeles"})}] Page lifecycle event: ${JSON.stringify(t)}`)}),e.on("Page.loadEventFired",()=>{this.loadEventLogs.push(`[${new Date(Date.now()).toLocaleString("en-US",{timeZone:"America/Los_Angeles"})}] Page load event fired`)}),await Promise.all([e.send("Accessibility.enable"),e.send("Page.enable"),e.send("DOM.enable"),e.send("Overlay.enable"),e.send("DOMSnapshot.enable"),e.send("CSS.enable")])}async send({method:e,params:t,timeout:n=this.defaultTimeoutMs,timeoutMsg:o}){for(;this.cdpInitializingPromise;)await z(this.cdpInitializingPromise,{milliseconds:n});if(this.cdpCrashDetails){if(this.cdpFullyDead)throw new x("UserInfrastructureError",`The browser inspector session encountered a critical crash: ${JSON.stringify(this.cdpCrashDetails)}`);this.logger.warn(`Detected crashed CDP client before method ${e}, reinitializing before proceeding...`),await this.reinitialize()}try{return await z(this.session.send(e,t),{milliseconds:n,message:o??`Chrome command ${e} timed out after ${n}ms. This is likely an infrastructure issue caused by a lack of compute resources or a crash at the browser level.`})}catch(i){throw["Internal error","Target crashed"].some(a=>i.message.includes(a))&&!this.cdpInitializingPromise&&(this.logger.warn({err:i},`CDP crashed during CDP method ${e}, re-initializing client`),await this.reinitialize()),i}}async createRawCDPSession(e=this.defaultTimeoutMs){let t=e,n=this.pageGetter(),o=await z(this.contextGetter().newCDPSession(n),{milliseconds:t,fallback:()=>{throw this.logger.error(`Failed to initialize CDP session within the page load timeout (${n.url()})`),new x("UserInfrastructureError",`Failed to initialize CDP session within the page load timeout (${n.url()})`)}});return this.logger.debug(`Created new CDP session for ${n.url()}`),o}async reinitialize(e=this.defaultTimeoutMs){await this.cdpInitializingPromise,this.cdpInitializingPromise=(async()=>{try{let t=this.session;this.session=await this.createRawCDPSession(e),await z(this.registerHandlers(this.session),{milliseconds:e,message:`Failed to register CDP handlers within ${e}ms`}),this.logger.debug("Successfully reinitialized and attached new handlers to CDP session");try{await z(t.detach(),{milliseconds:1e3})}catch(n){this.logger.warn({err:n},"Failed to detach old CDP session after reinitialization, continuing...")}this.cdpCrashDetails=void 0,this.cdpFullyDead=!1}catch(t){this.cdpCrashDetails={...this.cdpCrashDetails??{},reinitializeError:`${t}`},this.cdpFullyDead=!0}finally{this.cdpInitializingPromise=void 0}})(),await this.cdpInitializingPromise}on(e,t){return this.session.on(e,t),this.session}off(e,t){return this.session.off(e,t),this.session}addListener(e,t){return this.session.addListener(e,t),this.session}removeListener(e,t){return this.session.removeListener(e,t),this.session}};var Oi="<empty>";function lz(r){return r.includes("doubleclick.net")||r.includes("googletagmanager.com")||r.includes("googlesyndication.com")||r.includes("s.amazon-adsystem.com")||r.includes("smartadserver.com")||r.includes("omnitagjs.com")||r.includes("x.adroll.com")}function uR(r){let e=r.adFrameStatus?.adFrameType;return e==="child"||e==="root"||lz(r.url)}async function cz(r,e){let t=await r.send({timeout:te,method:"DOM.getFrameOwner",params:{frameId:e}}),o=(await r.send({timeout:te,method:"DOM.pushNodesByBackendIdsToFrontend",params:{backendNodeIds:[t.backendNodeId]}})).nodeIds[0],a=(await r.send({timeout:te,method:"DOM.describeNode",params:{backendNodeId:t.backendNodeId}})).node;return a.nodeId=o,a}async function Li({cdpClient:r,page:e,logger:t}){let n={type:"root",childFrames:[],page:e},o=[],[i,a]=await Promise.all([r.send({timeout:Pi,method:"Page.getFrameTree",params:{}}),r.send({timeout:Pi,method:"DOM.getDocument",params:{depth:0}})]),l=(i.frameTree.childFrames??[]).map(async(d,p)=>{if(uR(d.frame))return null;try{return await dR({cdpClient:r,rawFrameTree:d,indices:[p],parent:n,warnings:o,logger:t})}catch(g){return o.push(`Failed to get child frame: ${g}`),null}}),u=await Promise.all(l);return n.childFrames=u.filter(d=>d!==null),o.length&&t?.warn({warnings:o},"Got warnings when fetching frame tree"),n}async function dR({cdpClient:r,rawFrameTree:e,indices:t,parent:n,warnings:o,logger:i}){let a=e.frame.id,s=await cz(r,a),c=s.attributes??[],l=null,u=[];for(let m of["src","name","id","title","srcdoc","sandbox"]){let h=Gn(c,m);h&&(u.push(`${m}=${JSON.stringify(h)}`),m==="src"&&(l=h))}let d={type:"frame",cdpFrame:e.frame,url:e.frame.url,frameId:a,locationData:{indices:t,attributeSelectors:u},src:l,childFrames:[],parent:n,domNode:s},g=(e.childFrames??[]).map(async(m,h)=>{if(uR(m.frame))return null;try{return await dR({cdpClient:r,rawFrameTree:m,indices:[...t,h],parent:d,warnings:o,logger:i})}catch(f){return o.push(`Failed to get child frame (child ${h} of frame with url ${e.frame.url}): ${f}`),null}});return d.childFrames=(await Promise.all(g)).filter(m=>m!==null),d}async function uz(r){try{return await r.owner().count()===1}catch{return!1}}async function dz(r){try{return await r.count()===1}catch{return!1}}async function $r(r,e){let t=[],n=r;for(;n.parent.type==="frame";)t.push(n.parent),n=n.parent;t.reverse();let o=e,i=[];for(let l of t){let u=!1;for(let d of[...l.locationData.attributeSelectors,Oi]){let p=o.frameLocator(d===Oi?"iframe":`iframe[${d}]`);if(await uz(p)){u=!0,o=p,i.push(d);break}}if(!u)throw new x("ActionFailureError",`Failed to find a unique attribute to identify intermediate frame with url matching '${l.url}'. Please attach a unique 'id', 'name', 'title', or 'src' attribute to the frame.`)}let a;for(let l of[...r.locationData.attributeSelectors,Oi]){let u=o.locator(l===Oi?"iframe":`iframe[${l}]`);if(await dz(u)){a=u,i.push(l);break}}if(!a)throw new x("ActionFailureError",`Failed to find a unique attribute to identify target frame with url matching '${r.url}'. Please attach a unique 'id', 'name', 'title', or 'src' attribute to the frame.`);let s=await a.evaluateHandle(l=>l,{timeout:re}),c=await s.asElement().contentFrame();if(!c)throw new x("InternalWebAgentError",`Failed to load Playwright Frame for iframe with url '${r.url}'`);return await s.dispose(),{frame:c,mPathSelectorTokens:i}}function lR(r,e){let t=[...r],n=[];for(;t.length;){let o=t.shift();e(o)&&n.push(o),t.push(...o.childFrames)}return n}async function pR({page:r,frameTree:e,cache:t}){let n,o=e.childFrames,i=[];if(t.mPathSelectorTokens.length){let s=o;for(let u=0;u<t.mPathSelectorTokens.length-1;u++){let d=t.mPathSelectorTokens[u];d===Oi?s=s.length===1?s[0].childFrames:[]:s=s.filter(p=>p.locationData.attributeSelectors.includes(d)).map(p=>p.childFrames).flat()}let c=[],l=t.mPathSelectorTokens[t.mPathSelectorTokens.length-1];if(l===Oi?c=s:c=s.filter(u=>u.locationData.attributeSelectors.includes(l)),c.length===1)return n=c[0],i.push(`Found unique frame with mpath ${t.mPathSelectorTokens.join(" > ")}`),{resolution:{type:"auto",frame:(await $r(n,r)).frame,handle:n,mPathSelectorTokens:t.mPathSelectorTokens,frameTree:e},logs:i};i.push(`Found ${c.length} frames with mpath ${t.mPathSelectorTokens.join(" > ")}`)}if(t.frameSrcRegex){let s=new RegExp(t.frameSrcRegex),c=lR(o,l=>!!l.src&&s.test(l.src));if(c.length===1)return n=c[0],i.push(`Found unique frame with src regex ${t.frameSrcRegex}`),{resolution:{type:"auto",frame:(await $r(n,r)).frame,handle:n,mPathSelectorTokens:t.mPathSelectorTokens,frameTree:e},logs:i};i.push(`Found ${c.length} frames with src regex ${t.frameSrcRegex}`),t.frameSrcRegex=void 0}if(t.frameUrlRegex){let s=new RegExp(t.frameUrlRegex),c=lR(o,l=>!!l.url&&s.test(l.url));if(c.length===1)return n=c[0],i.push(`Found unique frame with url regex ${t.frameUrlRegex}`),{resolution:{type:"auto",frame:(await $r(n,r)).frame,handle:n,mPathSelectorTokens:t.mPathSelectorTokens,frameTree:e},logs:i};i.push(`Found ${c.length} frames with url regex ${t.frameUrlRegex}`),t.frameUrlRegex=void 0}let a=o;for(let s=0;s<t.indices.length-1;s++)a=a[t.indices[s]]?.childFrames??[];if(n=a[t.indices[t.indices.length-1]],n)return i.push(`Found unique frame with indices ${t.indices.join(" > ")}`),{resolution:{type:"auto",frame:(await $r(n,r)).frame,handle:n,mPathSelectorTokens:t.mPathSelectorTokens,frameTree:e},logs:i};throw i.push(`Found ${a.length} frames with indices ${t.indices}`),new Or("Failed to find the iframe that previously contained this element",[{type:"AUTO_FRAME",matched:!1,logs:i}],"could-not-find-iframe")}function lu(r){return r.type==="auto"?JSON.stringify({type:"auto",frameId:r.handle.frameId}):JSON.stringify(r)}function Bg(r){for(;r.parent.type==="frame";)r=r.parent;return r.parent}function mR(r){let e=Bg(r),t=r.src??"",n=r.url??"",o=[],i=[],a=[...e.childFrames];for(;a.length;){let s=a.shift();s.src&&o.push(s.src),s.url&&i.push(s.url),a.push(...s.childFrames)}return{srcs:o,urls:i,desiredSrc:t,desiredUrl:n}}function gR(r){return r.type==="auto"?{type:"auto",frameId:r.handle.frameId,url:r.handle.url,src:r.handle.src??"",mPathSelectorTokens:r.mPathSelectorTokens.join(" > ")}:{type:"url",url:r.url}}async function hR({frame:r,logger:e,signal:t}){let n;try{n=await r.frameElement(),await pz({frameElementHandle:n,logger:e,signal:t})}catch(o){n?e.warn({err:o},"Failed to scroll iframe into view, trying with raw JS"):e.warn("Failed to scroll iframe into view - no frame element")}finally{await n?.dispose()}}async function pz({frameElementHandle:r,logger:e,signal:t}){let n=await r.boundingBox();await cs({promiseGenerator:async()=>r.evaluate(async i=>{let a=i.scrollTop;i.scrollIntoView({behavior:"instant",block:"center",inline:"center"}),await new Promise(c=>setTimeout(c,250));let s=Date.now();for(;Date.now()-s<1e3;){let c=i.scrollTop;if(c===a)break;a=c,await new Promise(l=>setTimeout(l,250))}}),timeoutMs:Ee,codePath:"scrollIframeIntoView",signal:t}),e.info({oldBb:n,newBb:await r.boundingBox()},"Successfully scrolled iframe into view")}import{create as mz,windowedFiniteBatchScheduler as gz}from"@yornaath/batshit";import{reduce as hz}from"lodash-es";var fz=100,Sz=2e3;function fR(r){return mz({fetcher:async t=>{r(hz(t,(n,o)=>({...n,...o}),{}))},resolver:()=>{},scheduler:gz({windowMs:Sz,maxBatchSize:fz})})}async function SR({event:r,transformer:e,enricher:t,frame:n,lastScreenshotForRecording:o,logger:i}){let{warnings:a,error:s,properties:c}=r.target;if(s){i.error({error:s,warnings:a},"Error while capturing passive click");return}if(a.length&&i.warn({warnings:a},"Warnings while capturing passive click"),!c)return;let l=n.parentFrame()?n.url():void 0,d=n.page().frames().map(m=>m.url());i.debug({frameUrl:l,...r},"Passive click event captured on element");let p,g;if(l)try{let m=await n.frameElement();p=await z(m?.boundingBox(),{milliseconds:te})??void 0;let h=await t.constructIframeRegex({urls:d,srcs:[],desiredUrl:l});if(h.urlRegex)g={type:"url",url:`/${h.urlRegex}/`};else throw new Error(`Got no url regex options: ${JSON.stringify(h)}`)}catch(m){i.warn({err:m},"Failed to construct iframe details for recorded action, using hardcoded URL only"),g={type:"url",url:l}}(async()=>{try{await e.recordElementAction({...r,screenshotBase64:o,frameConfig:g,frameBoundingBox:p})}catch(m){i.error({err:m},"Failed to transform passive click action")}})()}import{randomUUID as qr}from"crypto";import yz from"js-beautify";var bz=["Dead"],cu=class{recordedSteps=new Map;callbacks;signal;generator;testId;orgId;nextStepOffset=0;logger;constructor({signal:e,callbacks:t,generator:n,testId:o,orgId:i,logger:a}){this.signal=e,this.logger=a,this.testId=o,this.orgId=i,this.callbacks={onStepRecorded:(s,c)=>{this.recordedSteps.set(c,{step:s}),t.onStepRecorded(s,c)},onActionReceived:(s,c)=>{this.recordedSteps.set(c,{step:s}),t.onActionReceived?.(s,c)}},this.generator=n}reserveIndexForCommand(e){let t=this.nextStepOffset;return this.recordedSteps.set(t,{step:{id:qr(),type:"PRESET_ACTION",command:Qr(e)}}),this.nextStepOffset++,t}async recordElementAction(e){let{type:t,target:n,frameConfig:o}=e;if(this.signal.aborted){this.logger.debug("Transformer was already cleaned up, ignoring click...");return}let i,a,s=n.properties.attributes.nodeOnlySerializedHtml.trim(),c=s,l;switch(e.frameConfig?e.frameBoundingBox?l={x:e.frameBoundingBox.x+n.properties.boundingBox.x,y:e.frameBoundingBox.y+n.properties.boundingBox.y,width:n.properties.boundingBox.width,height:n.properties.boundingBox.height}:this.logger.warn(e,"No frame bounding box found, refusing to write bounding box"):l=n.properties.boundingBox,t){case"CLICK":{i="CLICK";let h=Qr(i);a={id:qr(),type:"PRESET_ACTION",command:{...h,target:{type:"description",elementDescriptor:c},iframeUrl:o?.url,cache:{target:{id:-1,...n.properties.attributes,targetSource:"RECORDING",targetUpdateTime:new Date().toUTCString(),boundingBox:l}}}};break}case"SELECT":{i="SELECT_OPTION";let h=Qr(i);a={id:qr(),type:"PRESET_ACTION",command:{...h,type:"SELECT_OPTION",iframeUrl:o?.url,target:{type:"description",elementDescriptor:c},cache:{target:{id:-1,...n.properties.attributes,targetSource:"RECORDING",targetUpdateTime:new Date().toUTCString(),boundingBox:l}},choice:{type:"VALUE",value:e.selectedValue??"Unknown option"}}};break}case"MOUSE_DRAG":{i="MOUSE_DRAG";let h=Qr(i);a={id:qr(),type:"PRESET_ACTION",command:{...h,target:{type:"description",elementDescriptor:c},deltaX:e.deltaX.toString(),deltaY:e.deltaY.toString(),iframeUrl:o?.url,cache:{target:{id:-1,...n.properties.attributes,targetSource:"RECORDING",targetUpdateTime:new Date().toUTCString(),targetUpdateLoggerTags:ye(this.logger),boundingBox:l}}}};break}default:throw new Error(`Unknown action type: ${t}`)}let u;e.offset===void 0?(u=this.nextStepOffset,this.nextStepOffset++):u=e.offset,this.callbacks.onActionReceived?.(a,u);let d=e.target.browserState;try{d=yz.html(d,{indent_size:1,indent_with_tabs:!1,preserve_newlines:!1}),d=rC(d,"data-momentic-interacted",4e4)}catch{}let p;try{p=(await this.generator.getReverseMappedDescription({target:d,screenshot:e.screenshotBase64?`data:image/jpeg;base64,${e.screenshotBase64}`:void 0,boundingBox:n.properties.boundingBox},{disableCache:!1,loggerTags:{testId:this.testId,...ye(this.logger)}})).phrase}catch(h){this.logger.error({err:h},"Error generating reverse mapping description"),p=s}let g=this.recordedSteps.get(u)?.step??a,m=g?.command;m&&"target"in m&&m.target?(m.target={type:"description",elementDescriptor:p},this.callbacks.onStepRecorded({...g,command:m},u)):this.logger.warn("Could not find existing command to update after description mapping")}recordKeystroke(e){let{key:t,combinable:n}=e;if(bz.includes(t)||this.signal.aborted)return;let o="normal";t.length>1&&(o="special");let i;if(o==="normal"){let d=Qr("TYPE");i={id:qr(),type:"PRESET_ACTION",command:{...d,target:void 0,value:t,clearContent:!1}}}else{let d=Qr("PRESS");i={id:qr(),type:"PRESET_ACTION",command:{...d,value:t}}}let a,s=this.nextStepOffset-1,c=this.recordedSteps.get(s),l=c?.step,u=l?.command;if(n){if(u?.type===i.command.type){let d=u.value,p=i.command.value;i={id:qr(),type:"PRESET_ACTION",command:{...u,value:i.command.type==="PRESS"?`${d}+${p}`:`${d}${p}`}},a=s}else if(u?.type==="CLICK"&&i.command.type==="TYPE")l.command={...i.command,target:u.target,cache:u.cache},i=c.step,a=s;else if(u?.type==="TYPE"&&i.command.type==="PRESS"&&i.command.value==="Backspace"){let d=u.value;i={id:qr(),type:"PRESET_ACTION",command:{...u,value:d.slice(0,d.length-1)}},a=s}}a===void 0&&(a=this.nextStepOffset,this.nextStepOffset++),this.callbacks.onStepRecorded(i,a)}recordScroll(e){if(this.signal.aborted)return;let t=()=>{let{deltaY:i}=e;if(!i)return;let a=this.nextStepOffset-1,s=this.recordedSteps.get(a)?.step.command,c;s?.type==="SCROLL_DOWN"&&s.deltaY?(i+=s.deltaY,c=a):s?.type==="SCROLL_UP"&&s.deltaY?(i-=s.deltaY,c=a):(c=this.nextStepOffset,this.nextStepOffset++);let l=i>0?"SCROLL_DOWN":"SCROLL_UP",u=Qr(l);u.deltaY=Math.abs(i);let d={id:qr(),type:"PRESET_ACTION",command:u};this.callbacks.onStepRecorded(d,c)},n=()=>{let{deltaX:i}=e;if(!i)return;let a=this.nextStepOffset-1,s=this.recordedSteps.get(a)?.step.command,c;s?.type==="SCROLL_RIGHT"&&s.deltaX?(i+=s.deltaX,c=a):s?.type==="SCROLL_LEFT"&&s.deltaX?(i-=s.deltaX,c=a):(c=this.nextStepOffset,this.nextStepOffset++);let l=i>0?"SCROLL_RIGHT":"SCROLL_LEFT",u=Qr(l);u.deltaX=Math.abs(i);let d={id:qr(),type:"PRESET_ACTION",command:u};this.callbacks.onStepRecorded(d,c)},o=this.recordedSteps.get(this.nextStepOffset-1);o?.step.command.type==="SCROLL_LEFT"||o?.step.command.type==="SCROLL_RIGHT"?(n(),e.deltaY>=20&&t()):(t(),e.deltaX>=20&&n())}};import{z as zg}from"zod";var EAe=zg.object({type:zg.literal("url"),url:zg.string()});var uu=class{smartWaitingTimeoutMs;pageLoadTimeoutMs;allowPartialAccessibilityTree;logger;cdpClient;pageGetter;abortSignalGetter;userControlledBrowserSettings;enricher;iconKnowledgeBase;computedStylesToFetch=["display","opacity","visibility","height","position","background-image"];activeFrameCache;activeFrameConfig;lastA11yIdToNodeMap={};lastDataMomenticIdToNodeMap={};lastSelectorToNodeMap={};lastA11yTreeRoot;lastDomGraph;allowedA11yIgnoreReasonsOverride;constructor({smartWaitingTimeoutMs:e,pageLoadTimeoutMs:t,allowPartialAccessibilityTree:n,logger:o,cdpClient:i,pageGetter:a,abortSignalGetter:s,enricher:c,iconKnowledgeBase:l,userBrowserSettings:u,allowedA11yIgnoreReasonsOverride:d}){if(this.smartWaitingTimeoutMs=e,this.pageLoadTimeoutMs=t,this.allowPartialAccessibilityTree=n,this.logger=o,this.cdpClient=i,this.pageGetter=a,this.abortSignalGetter=s,this.enricher=c,this.iconKnowledgeBase=l,this.userControlledBrowserSettings=u,this.allowedA11yIgnoreReasonsOverride=d,this.userControlledBrowserSettings.importantStyles)for(let p of this.userControlledBrowserSettings.importantStyles){let g=p.split(":");if(g.length!==2){this.logger.warn({style:p},"Invalid style property passed to importantStyles");continue}let m=g[0]?.trim(),h=g[1]?.trim();if(m===void 0||h===void 0){this.logger.warn({style:p},"Invalid style property passed to importantStyles");continue}this.computedStylesToFetch.includes(m)||this.computedStylesToFetch.push(m)}}get frameConfig(){return this.activeFrameConfig}get domGraph(){return this.lastDomGraph}get selectorToNodeMap(){return this.lastSelectorToNodeMap}get dataMomenticIdToNodeMap(){return this.lastDataMomenticIdToNodeMap}get a11yIdToNodeMap(){return this.lastA11yIdToNodeMap}get a11yTreeRoot(){return this.lastA11yTreeRoot}setActiveFrameConfig(e){e?(this.activeFrameConfig=e,this.activeFrameCache=void 0):(this.activeFrameConfig=void 0,this.activeFrameCache=void 0)}reset(){this.activeFrameCache=void 0,this.activeFrameConfig=void 0,this.lastA11yIdToNodeMap={},this.lastDataMomenticIdToNodeMap={},this.lastSelectorToNodeMap={},this.lastA11yTreeRoot=void 0,this.lastDomGraph=void 0}saveAutoFrameCacheDetails(e){if(!this.activeFrameConfig||this.activeFrameConfig.type!=="auto"||!this.userControlledBrowserSettings.autoExpandIframes)return;let t={...e,indices:this.activeFrameConfig.handle.locationData.indices,mPathSelectorTokens:this.activeFrameConfig.mPathSelectorTokens};return this.constructIframeRegexAsync(this.activeFrameConfig.handle,t),t}async getAutoFrameDetailsFromHandle(e){let t=this.pageGetter(),n=Bg(e),{frame:o,mPathSelectorTokens:i}=await $r(e,t),a={indices:e.locationData.indices,mPathSelectorTokens:i};return this.constructIframeRegexAsync(e,a),{cache:a,config:{type:"auto",frame:o,handle:e,mPathSelectorTokens:i,frameTree:n,cache:a}}}async resolveAutoFrameCache(e){let t=this.pageGetter(),n=await Li({cdpClient:this.cdpClient,page:t,logger:this.logger}),{resolution:o,logs:i}=await pR({page:t,frameTree:n,cache:e});return this.logger.info({logs:i},"Resolved auto frame cache"),{...o,cache:e}}async resolveActiveFrameConfig({logger:e=this.logger,signal:t=this.abortSignalGetter()}){if(!this.frameConfig)return null;if(this.activeFrameCache)if(lu(this.frameConfig)!==this.activeFrameCache.frameIdentifierStringified)this.activeFrameCache=void 0;else if(this.activeFrameCache.frame&&"isDetached"in this.activeFrameCache.frame&&this.activeFrameCache.frame.isDetached())this.activeFrameCache=void 0;else return this.activeFrameCache;let n;return this.frameConfig.type==="url"?n=await this.resolveUrlMatcherFrameConfig({config:this.frameConfig,logger:e,signal:t}):n={source:"auto",frame:this.frameConfig.frame,handle:this.frameConfig.handle,frameIdentifierStringified:lu(this.frameConfig),cacheTime:Date.now(),frameTree:this.frameConfig.frameTree,mPathSelectorTokens:this.frameConfig.mPathSelectorTokens},await hR({frame:n.frame,logger:e,signal:t}),this.activeFrameCache=n,n}async executeFunctionInAllFrames(e,t){let n=this.pageGetter(),o=await Li({cdpClient:this.cdpClient,page:n,logger:this.logger}),i=[z(n.evaluate(e,t),{milliseconds:Ee})],a=Array.from(o.childFrames);for(;a.length>0;){let c=a.shift(),l=c.url;l==="about:blank"||l.startsWith("chrome-error://")||(a.push(...c.childFrames),i.push($r(c,n).then(({frame:u})=>z(u.evaluate(e,t),{milliseconds:Ee})).catch(u=>(this.logger.warn({err:u,frameUrl:c.url},"Failed to evaluate function in frame"),"MOMENTIC_FRAME_EVAL_ERROR"))))}return(await Promise.all(i)).filter(c=>c!=="MOMENTIC_FRAME_EVAL_ERROR")}async getAllChildFrameUrls(){let e=this.pageGetter(),t=await Li({cdpClient:this.cdpClient,page:e,logger:this.logger}),n=Array.from(t.childFrames),o=[];for(;n.length>0;){let i=n.shift();n.push(...i.childFrames),o.push(i.src??i.url)}return o}async getDomGraph({devicePixelRatio:e,signal:t,logger:n}){return this.getDOMTree({devicePixelRatio:e??1,signal:t,logger:n??this.logger})}async getA11yTree(e){let t={},n=e.logger??this.logger,o=e.abortSignal??this.abortSignalGetter(),i=this.pageGetter(),a,s,c=null;if(this.frameConfig?.type==="url"){if(a=await hr({fn:()=>this.resolveActiveFrameConfig({logger:n,signal:o}),codePath:"getActiveFrameDetails",logObject:t,signal:o,logger:n})??void 0,!a)throw new x("ActionFailureError","Got null frame details despite active frame config");s=a.handle,c=s.frameId}else this.userControlledBrowserSettings.autoExpandIframes?(s=await hr({fn:()=>Li({cdpClient:this.cdpClient,page:this.pageGetter(),logger:n}),codePath:"getMomenticFrameTree",logObject:t,signal:o,logger:n}),c=null):(s={type:"root",page:i,childFrames:[]},c=null);await hr({fn:async()=>this.addMomenticIds({rootPage:i,childFrames:s.childFrames,frameFilter:a?.frame,logger:n}),codePath:"addIdsToElement",logObject:t,signal:o,logger:n});let l=await hr({fn:()=>this.getDOMTree({devicePixelRatio:e.devicePixelRatio??1,signal:o,logger:n}),codePath:"domFetch",logObject:t,signal:o,logger:n}),u=await hr({fn:()=>this.getRawA11yGraph({cdpClient:this.cdpClient,frameId:c,childFrames:s.childFrames,logTimings:t,logger:n,signal:o}),codePath:"totalA11yFetch",logObject:t,signal:o,logger:n}),{tree:d}=await hr({fn:()=>this.composeA11yDomGraph({opts:e,a11yGraph:u,domGraph:l,startingFrameId:c,frameContext:s,logger:n,iconKnowledgeBase:this.iconKnowledgeBase,showZeroOpacityElements:e.showZeroOpacityElements,flagNotActionableNodes:e.flagNotActionableNodes}),codePath:"a11yProcess",logObject:t,signal:o,logger:n});return Object.values(t).some(p=>p>750)&&n.warn({logTimings:t},"A11y tree fetch component took a long time"),this.lastA11yIdToNodeMap=d.a11yIdNodeMap,this.lastDataMomenticIdToNodeMap=d.dataMomenticIdMap,this.lastA11yTreeRoot=d.root,this.lastDomGraph=l,this.lastSelectorToNodeMap=d.selectorToNodeMap,d}async fetchA11yTreeForRecording(e,t){if(await this.getA11yTree({devicePixelRatio:e,abortSignal:t,logger:_n,filterByViewport:!1,flagNotActionableNodes:!1}),Math.random()<.1){let n=this.lastA11yTreeRoot?.serialize();this.logger.debug({tree:n&&n.length>4e5?"REDACTED_DUE_TO_SIZE":n},"Refreshed a11y tree during recording")}}async getLocatorFromA11yNode({page:e,root:t,node:n}){if(n.backendNodeId===void 0)throw new Error(`Node with a11y id ${n.id} has no backend node ID: ${n.getNodeOnlySerializedForm()}`);if(this.userControlledBrowserSettings.visualActions){let o=this.domGraph?.backendIdToNode[n.backendNodeId];if(!o)throw new Error(`Could not find DOM node for backend node ID ${n.backendNodeId}`);let i=qC({node:o,domGraph:this.domGraph});return KC(e,i)}else return this.getLocatorFromBackendId(t,n.backendNodeId)}async getLocatorFromBackendId(e,t){let n=await this.cdpClient.send({method:"DOM.resolveNode",params:{backendNodeId:t},timeout:Ee});if(!n||!n.object.objectId)throw new Error(`Could not resolve backend node ${t}`);let o;try{o=await YC(this.cdpClient,n.object.objectId)}catch(i){throw this.logger.debug({err:i,object:JSON.stringify(n.object)},"Failed to get ID attribute"),i}return e.locator(wr(o))}getNodeUsingMPathSelector(e){let t=this.selectorToNodeMap[e];if(t)return t;let n=e.split(" > "),o="";for(let i=n.length-1;i>=0;i--){let a=n.slice(i).join(" > ");if(this.selectorToNodeMap[a]){o=a;break}}this.logger.warn({selectorMapSize:Object.keys(this.selectorToNodeMap).length,selector:e,closestSelector:o},"Could not find a11y node using mpath selector")}async resolveUrlMatcherFrameConfig({config:e,signal:t=this.abortSignalGetter(),logger:n=this.logger}){let o=Date.now(),i,a,s,c=0;for(;Date.now()-o<this.smartWaitingTimeoutMs;)try{i=await Li({cdpClient:this.cdpClient,page:this.pageGetter(),logger:n}),a=await this.getMatchingFrameByUrlWithCdp(i,e),n.info({frameId:a.handle.frameId,url:a.handle.url,src:a.handle.src,locationData:a.handle.locationData},`Found matching frame using ${a.matchType}`);break}catch(l){if(s=l,l instanceof x&&l.reason==="UserInfrastructureError")throw l;c%3===0&&this.logger.warn({attempt:c,err:l},"Failed to resolve active frame, retrying..."),await W(ut,t)}finally{c++}if(a)return{source:"url",frame:a.frame,handle:a.handle,frameIdentifierStringified:lu(e),cacheTime:Date.now(),frameTree:i,mPathSelectorTokens:[]};throw s}async getMatchingFrameByUrlWithCdp(e,t){let n=t.url,o=this.pageGetter(),i=Array.from(e.childFrames),a=[];for(;i.length>0;){let s=i.shift(),c=s.domNode;i.push(...s.childFrames);let l=Gn(c.attributes??[],"src"),u=c.contentDocument?.documentURL;if(!l&&!u){this.logger.debug("Skipping frame with no URL or src");continue}for(let d of[l,u])if(d){if(n.startsWith("/")&&n.endsWith("/")){if(new RegExp(n.slice(1,-1)).test(d)){a.push({handle:s,matchType:"regex",...await $r(s,o)});break}}else if(n.trim()===d.trim()){a.push({handle:s,matchType:"url",...await $r(s,o)});break}}}if(a.length===1){let s=a[0];return this.userControlledBrowserSettings.autoExpandIframes||(s.handle.childFrames=[]),s}else throw a.length>1?new Error(`Found multiple frames with src matching '${n}'. Please use a more specific selector.`):new x("ActionFailureError",`Failed to find frame with src matching: ${n}`)}async composeA11yDomGraph({opts:e,a11yGraph:t,domGraph:n,startingFrameId:o,frameContext:i,logger:a,iconKnowledgeBase:s,showZeroOpacityElements:c,flagNotActionableNodes:l}){let u=await oR({rawA11yGraph:t,startingFrameId:o,frameContext:i,domGraph:n,logger:a,cdpClient:this.cdpClient,showZeroOpacityElements:c,flagNotActionableNodes:l,filterByViewport:e.filterByViewport,importantProperties:{attributes:this.userControlledBrowserSettings.importantAttributes,classes:this.userControlledBrowserSettings.importantClasses,styles:this.userControlledBrowserSettings.importantStyles},viewportDetails:void 0,iconKnowledgeBase:s,useMPaths:this.userControlledBrowserSettings.visualActions,allowedA11yIgnoreReasonsOverride:this.allowedA11yIgnoreReasonsOverride});if(!u||!u.root)throw new Error("Accessibility tree appears empty");return{tree:u}}async addMomenticIds({rootPage:e,childFrames:t,frameFilter:n,logger:o}){if(this.userControlledBrowserSettings.visualActions)return;let i=await this.addMomenticIdsHelper(n??e,1);if(!this.userControlledBrowserSettings.autoExpandIframes||n)return;let a=Array.from(t),s=[];for(;a.length>0;){let c=a.shift();a.push(...c.childFrames);let l=async()=>{try{let{frame:u}=await $r(c,e);i=await this.addMomenticIdsHelper(u,i)}catch(u){c.url!=="about:blank"&&o.warn({err:u},"Error adding momentic IDs to child frame, continuing...")}};s.push(l())}await Promise.all(s)}async addMomenticIdsHelper(e,t){if(this.userControlledBrowserSettings.visualActions)return t;let n=this.logger;return await at({root:e,fn:i=>window.addIdsToElement?.(document.body,i),arg:t,timeout:Ee,waitForPageLoad:async()=>{try{await e.waitForLoadState("domcontentloaded",{timeout:this.smartWaitingTimeoutMs})}catch(i){n.warn({err:i},"Error loading frame root adding momentic ids, continuing...")}},codePath:"adding Momentic element IDs to the page"})??t}getPageDomain(e){try{let t=new URL(e);if(!t.hostname)return null;let n=t.hostname.split("."),o=n.length>2?n.slice(-2).join("."):t.hostname;return`${t.protocol}//${o}`}catch{return null}}async decideChildFrameUnrollEligibility({logger:e,warnings:t,handle:n}){try{let{shouldUnroll:o,reason:i}=await this.decideChildFrameUnrollEligibilityHelper({domNode:n.domNode});return{shouldUnroll:o,reason:i}}catch(o){if(o.message.includes("Could not compute box model"))return{shouldUnroll:!1};let i=`Got error when determining whether to filter frame ${n.frameId} with url ${n.url}, allowing it to be fetched: ${o}`;return t?.push(i),e?.warn({err:o},i),{shouldUnroll:!0}}}async decideChildFrameUnrollEligibilityHelper({domNode:e}){let t=e.attributes??[];if(Gn(t,"aria-hidden")==="true")return{shouldUnroll:!1,reason:"aria-hidden"};let n=Gn(t,"style");if(n?.includes("display: none")||n?.includes("visibility: hidden"))return{shouldUnroll:!1,reason:"hidden CSS style"};await this.cdpClient.send({timeout:te,method:"DOM.pushNodesByBackendIdsToFrontend",params:{backendNodeIds:[e.backendNodeId]}});let[o,i]=await Promise.all([this.cdpClient.send({timeout:te,method:"DOM.getBoxModel",params:{backendNodeId:e.backendNodeId}}),this.cdpClient.send({timeout:te,method:"CSS.getComputedStyleForNode",params:{nodeId:e.nodeId}})]);if(!o.model||!o.model.height||!o.model.width)return{shouldUnroll:!1,reason:"no bounding box"};if(o.model.height<10||o.model.width<10)return{shouldUnroll:!1,reason:"small bounding box"};for(let a of i.computedStyle){if(a.name==="display"&&a.value==="none")return{shouldUnroll:!1,reason:"display: none"};if(a.name==="visibility"&&a.value==="hidden")return{shouldUnroll:!1,reason:"visibility: hidden"};if(a.name==="opacity"&&a.value==="0")return{shouldUnroll:!1,reason:"opacity: 0"}}return{shouldUnroll:!0}}async getRawA11yGraph({cdpClient:e,frameId:t,childFrames:n,logTimings:o,logger:i=this.logger,signal:a=this.abortSignalGetter()}){let s=[];try{await this.pageGetter().waitForLoadState("load",{timeout:this.pageLoadTimeoutMs})}catch(g){i.warn({err:g},"Failed to wait for page load event before a11y tree fetch, attempting to continue without it..."),await this.cdpClient.reinitialize()}let c,l;for(let g=0;g<3;g++)try{l=await hr({fn:()=>this.getRawA11yTreeForFrame({frameId:t,timeoutMs:this.pageLoadTimeoutMs,logTimings:o}),codePath:"a11y-tree-fetch-root",logObject:o,logger:i});break}catch(m){c=m,i.warn({err:m},"Reinitializing CDP client before retrying a11y graph fetch"),await this.cdpClient.reinitialize()}if(!l)throw new Error(`Failed to fetch accessibility tree for root page: ${c}`);let u={};if(u[t??"root"]=l,!this.userControlledBrowserSettings.autoExpandIframes)return u;let d=Array.from(n),p=[];for(;d.length>0;){let g=d.shift();try{let{shouldUnroll:h}=await this.decideChildFrameUnrollEligibility({handle:g,warnings:s});if(!h)continue}catch(h){if(h.message.includes("Could not compute box model"))continue;s.push(`Got error when determining whether to filter frame ${g.frameId} with url ${g.url}, allowing it to be fetched: ${h}`)}d.push(...g.childFrames);let m=async()=>{try{let h=await hr({fn:()=>this.getRawA11yTreeForFrame({frameId:g.frameId,timeoutMs:this.smartWaitingTimeoutMs,logTimings:o}),codePath:`a11y-tree-fetch-child-${g.frameId}`,logObject:o,logger:i});u[g.frameId]=h}catch(h){i.warn({err:h,url:g.url,src:g.src},`Error getting raw a11y tree for child frame ${g.frameId}, continuing...`)}};p.push(m())}return await Promise.all(p),s.length>0&&this.logger.warn({warnings:s},"Got warnings when fetching the raw a11y graph"),u}async getRawA11yTreeForFrame({frameId:e,timeoutMs:t,logTimings:n}){let o;if(this.allowPartialAccessibilityTree)o=(await hr({fn:()=>this.cdpClient.send({method:"Accessibility.getFullAXTree",params:{frameId:e??void 0},timeout:t,timeoutMsg:`Fetching the document tree took over ${t}ms. This usually indicates that the current page is too large to be loaded at once, or your machine is severely resource constrained.`}),codePath:"cdp-query-ax-tree",logObject:n,logger:this.logger})).nodes;else{let a=(await hr({fn:()=>this.cdpClient.send({method:"Accessibility.getRootAXNode",params:{frameId:e??void 0},timeout:Ee}),codePath:"cdp-get-root-ax-node",logObject:n,logger:this.logger})).node.backendDOMNodeId;o=(await hr({fn:()=>this.cdpClient.send({method:"Accessibility.queryAXTree",params:{backendNodeId:a},timeout:t,timeoutMsg:`Fetching the document tree took over ${t}ms. This usually indicates that the current page is too large to be loaded at once, or your machine is severely resource constrained.`}),codePath:"cdp-query-ax-tree",logObject:n,logger:this.logger})).nodes}if(!o||o.length<=1)throw new Error("Document is entirely empty");return{root:o[0],allNodes:o}}async getDOMTree({devicePixelRatio:e,signal:t,logger:n}){let o,i=0,a;for(;!o&&i<3;)try{if(o=await this.cdpClient.send({method:"DOMSnapshot.captureSnapshot",params:{computedStyles:this.computedStylesToFetch},timeout:te}),!o||!o.documents.length)throw new Error("Got empty DOM tree")}catch(s){await W(ut,t),i++,a=s}if(!o||!o.documents.length)throw n.error({err:a},"Fatal error fetching DOM tree"),new x("UserInfrastructureError",`Received an empty HTML snapshot from the browser. This usually indicates the page has crashed due to resource consumption issues or hanging client-side JavaScript code: ${a?.message}`);return $C({snapshot:o,devicePixelRatio:e,computedStylesToFetch:this.computedStylesToFetch,logger:n})}constructIframeRegexAsync(e,t){if(t.frameSrcRegex||t.frameUrlRegex)return;let n=mR(e);(async()=>{try{let o=await this.enricher?.constructIframeRegex(n);o?.srcRegex&&(t.frameSrcRegex=o.srcRegex),o?.urlRegex&&(t.frameUrlRegex=o.urlRegex),this.logger.debug({result:o,params:n},"Constructed iframe regex for cache")}catch(o){this.logger.warn({err:o},"Failed to construct iframe regex, skipping...")}})()}};function Hg(r){let e=[],t="";for(let n of r)n==="+"&&t?(e.push(t),t=""):t+=n;return e.push(t),e}var hs=class r{static USER_AGENT=eu;abortSignal=void 0;contextInitialized=!1;cleanedUp=!1;browser;context;properties;page;userControlledBrowserSettings;pageLoadPromises={};lastTabChangeEventTimeout=void 0;pageLoadAbortControllers=new Set;pageLoadAbortListenerCleanup;clientCallbacks;harBatcher;iconKnowledgeBase;cdpClient;debugData={logsPerPage:[]};recentFrameNavigations={};requestRecorders={};mocks={};customHeaders=[];enricher;storage;logger;stateManager;transformer;lastScreenshotForRecording=void 0;originsVisited=new Set;viewport;onVideoPageChange;baseUrl;constructor({storage:e,enricher:t,browser:n,context:o,page:i,baseUrl:a,logger:s,userBrowserSettings:c,viewport:l,properties:u,clientCallbacks:d,iconKnowledgeBase:p,onVideoPageChange:g}){yE(c),this.storage=e,this.enricher=t,this.browser=n,this.context=o,this.page=i,this.baseUrl=a,this.logger=s,this.userControlledBrowserSettings=c,this.viewport=l,this.properties=u,this.clientCallbacks=d,this.iconKnowledgeBase=p,this.onVideoPageChange=g}registerAbortSignal(e){if(this.pageLoadAbortListenerCleanup&&(this.pageLoadAbortListenerCleanup(),this.pageLoadAbortListenerCleanup=void 0),this.abortSignal=e,!this.abortSignal)return;let t=()=>{for(let n of this.pageLoadAbortControllers)n.abort();this.pageLoadAbortControllers.clear()};if(this.abortSignal.aborted){t();return}this.abortSignal.addEventListener("abort",t),this.pageLoadAbortListenerCleanup=()=>{this.abortSignal?.removeEventListener("abort",t)}}async initialize({grantPermissions:e,runInitScripts:t,timingRecorder:n}){if(this.contextInitialized)return;let o={[Qc]:this.userBrowserSettings.visualActions},i=[];if(this.userControlledBrowserSettings.extraHeaders&&i.push(this.context.setExtraHTTPHeaders(this.userControlledBrowserSettings.extraHeaders)),e){let u=["clipboard-read","clipboard-write","microphone","camera","geolocation"];kr||u.push("local-network-access"),i.push(this.context.grantPermissions(u))}i.push(this.context.addInitScript({content:`${ag.htmlUtilsLibJs}
4337
4337
  //# sourceURL=momentic-injected/browser-scripts.js`}),this.context.addInitScript({content:Mg(o,this.userBrowserSettings.disableFullStory)}),this.exposeRecordingBindings());let a=u=>this.handleNewPageEvent(u);this.context.on("page",a),this.handleNewPageEventHelper(this.page),this.context.on("close",()=>{this.context.off("page",a)});let s=!1;if(t){let u=async()=>{let d=Date.now();try{await Promise.all([this.page.addScriptTag({content:`${ag.htmlUtilsLibJs}
4338
4338
  //# sourceURL=momentic-injected/browser-scripts.js`}),this.page.addScriptTag({content:Mg(o,this.userBrowserSettings.disableFullStory)})])}catch(p){if(p instanceof Error&&p.message.includes("Content Security Policy"))this.logger.warn({err:p},"Content Security Policy error from adding Momentic scripts, reloading page instead"),s=!0;else throw p}(n??{})["add-init-scripts"]=Date.now()-d};i.push(u())}if(!this.properties.systemDevicePixelRatio)if(process.env.MOMENTIC_LOCAL_DEV==="1"&&xz()==="darwin"&&Tz("system_profiler SPDisplaysDataType").toString().includes("Retina"))w.warn("[DEV] Setting device pixel ratio to 2 in local dev since a Retina display was detected"),this.properties.systemDevicePixelRatio=2;else{let u=async()=>{let d=Date.now();this.properties.systemDevicePixelRatio=await this.page.evaluate(()=>window.devicePixelRatio),(n??{})["fetch-dpr"]=Date.now()-d};i.push(u())}let c=Date.now();await z(Promise.all(i),{milliseconds:this.pageLoadTimeout,message:"Timed out attaching Chrome permissions and initialization scripts",signal:this.abortSignal});let l=Date.now();(n??{})["ops-attach"]=l-c,s&&await this.page.reload(),this.cdpClient=await su.init({logger:this.logger,contextGetter:()=>this.context,pageGetter:()=>this.page,defaultTimeoutMs:this.pageLoadTimeout}),(n??{})["cdp-init"]=Date.now()-l,await this.initializeScreencast(),this.stateManager=new uu({smartWaitingTimeoutMs:this.smartWaitingTimeout,pageLoadTimeoutMs:this.pageLoadTimeout,allowPartialAccessibilityTree:this.userControlledBrowserSettings.allowPartialAccessibilityTree??!1,logger:this.logger,cdpClient:this.cdpClient,pageGetter:()=>this.page,abortSignalGetter:()=>this.abortSignal,enricher:this.enricher,iconKnowledgeBase:this.iconKnowledgeBase,userBrowserSettings:this.userBrowserSettings,allowedA11yIgnoreReasonsOverride:this.properties.allowedA11yIgnoreReasonsOverride}),this.contextInitialized=!0}async fixViewportForNewHeadless(){this.properties.isNewHeadless&&this.viewport&&await this.cdpClient.send({method:"Emulation.setDeviceMetricsOverride",params:{width:this.viewport.width,height:this.viewport.height,deviceScaleFactor:0,mobile:this.viewport.width<1e3}})}async initializeScreencast(){await this.fixViewportForNewHeadless(),this.clientCallbacks?.onScreencastFrame&&this.viewport&&(await this.cdpClient.send({method:"Page.startScreencast",params:{format:"jpeg",quality:75,maxWidth:this.viewport.width,maxHeight:this.viewport.height}}),this.cdpClient.on("Page.screencastFrame",e=>{let t=e.sessionId,n=Buffer.from(e.data,"base64");this.lastScreenshotForRecording=n,this.clientCallbacks?.onScreencastFrame?.(n,()=>{(async()=>{try{await this.cdpClient.send({method:"Page.screencastFrameAck",params:{sessionId:t}})}catch{}})()})}))}static async init(e){let t=await OC(e),n=new r(t);return await n.initialize({grantPermissions:!0,runInitScripts:!1}),n}static async fromExistingContext({context:e,storage:t,enricher:n,userBrowserSettings:o,properties:i,logger:a,timingRecorder:s}){let c=e.pages()[0];if(!c)throw new Error("No page found in existing context");let l=c.viewportSize();if(!l){let p=Date.now();l=await c.evaluate(()=>({width:window.innerWidth,height:window.innerHeight})),s["eval-viewport"]=Date.now()-p}let u=c?.url(),d=new r({browser:e.browser(),context:e,page:c,baseUrl:u,logger:a,storage:t,enricher:n,userBrowserSettings:o,viewport:l,properties:i,clientCallbacks:void 0,iconKnowledgeBase:null});return await d.initialize({grantPermissions:!1,runInitScripts:!0,timingRecorder:s}),d}async handleAvailableTabsChangeHelper(){try{let e=await Og(this.context,{getTitles:!0}),t=this.page.url();this.clientCallbacks?.onTabsChange?.(e,t)}catch(e){this.logger.error({err:e},"Error sending available tabs to frontend")}}handleAvailableTabsChange(){try{clearTimeout(this.lastTabChangeEventTimeout),this.lastTabChangeEventTimeout=setTimeout(()=>this.handleAvailableTabsChangeHelper(),500)}catch(e){this.logger.warn({err:e},"Error handling available tabs change")}}addToPageLoadPromises(e,t){let n=Gg(),o=`${e}-${n}`,i=Date.now(),a=!1,s=new AbortController;this.pageLoadAbortControllers.add(s);let c=async()=>{try{await z(t(),{signal:s.signal,milliseconds:this.pageLoadTimeout,message:`Page load promise for code path ${e} timed out after ${this.pageLoadTimeout}ms`})}catch(l){l.name!=="AbortError"&&!this.closed&&this.logger.error({err:l,promiseKey:o,codePath:e,duration:Date.now()-i},`Page load promise for code path ${e} encountered error`)}finally{delete this.pageLoadPromises[o],this.pageLoadAbortControllers.delete(s),a=!0}};this.pageLoadPromises[o]=c().catch(()=>{}),a&&delete this.pageLoadPromises[o]}handlePageClosedEvent(e){if(this.page!==e){this.logger.debug({url:e.url()},"Detected background page was closed, just updating available tabs only"),this.handleAvailableTabsChange();return}let t=async()=>{if(this.closed)return;this.logger.info({url:e.url()},"Detected active page was closed, switching to another tab");let n=this.context.pages();for(let o=n.length-1;o>=0;o--){let i=n[o];if(!(!i||i.isClosed()||!vo(i.url()))){this.logger.info(`Automatically switching to tab ${o} after close: ${i.url()}`),await this.switchToPage({type:"INDEX",index:String(o)});break}}};this.addToPageLoadPromises("page closed handler",async()=>t())}handleNewPageEvent(e){let t=e.url();this.logger.info({url:t},"Detected new page event, registering handlers and waiting for load to complete");try{this.handleNewPageEventHelper(e)}catch(n){this.logger.warn({err:n},"Error handling new page open, continuing....")}}handleNewPageEventHelper(e){let t=Gg(),n="new-page-load-handler";e.on("close",a=>this.handlePageClosedEvent(a)),e.on("framenavigated",a=>this.handleFrameNavigationEvent(a)),e.on("crash",()=>{this.logger.error("Page crashed at the Playwright level!")});let o=this.context.pages().indexOf(e);!this.userBrowserSettings.disableBrowserMonitoring&&!this.userControlledBrowserSettings.disableConsoleLogs&&e.on("console",a=>{hC(e,o,this.debugData,a,this.logger)});let i=async()=>{!this.userBrowserSettings.disableBrowserMonitoring&&!this.userControlledBrowserSettings.disableNetworkLogs&&(yC(this.logger,t,this.clientCallbacks?.onNetworkPage,e),!this.harBatcher&&this.clientCallbacks?.onNetworkLogs&&(this.harBatcher=fR(this.clientCallbacks.onNetworkLogs)),await e.route("**/*",async(a,s)=>{await Tg({pageId:t,route:a,request:s,onHarEntry:(c,l)=>{this.harBatcher?.fetch({[c]:l}).catch(()=>{})},logger:this.logger,requestRecorders:this.requestRecorders,mocks:this.mocks,isBrowserClosed:()=>this.closed})}),await e.route("**/*",AC(this.customHeaders,this.logger))),kr&&await e.route("**/*",ms),await this.loadFrameAndRecordUrl({root:e,codePath:n}),this.handleAvailableTabsChange()};this.addToPageLoadPromises(n,async()=>i())}async handleCollectSvgs(e){}handleFrameNavigationEvent(e){let t=e.url(),n=e.parentFrame()?"has-parent":"no-parent",o=`frame-navigation-handler-${t.slice(0,50)} (${n})`;if(!t||t==="about:blank"||!vo(t)||this.recentFrameNavigations[o]&&Date.now()-this.recentFrameNavigations[o]<1e3)return;this.recentFrameNavigations[o]=Date.now();let i=async()=>{try{if(e.isDetached())return;await this.loadFrameAndRecordUrl({root:e,codePath:o}),this.handleAvailableTabsChange(),!e.parentFrame()&&!e.isDetached()&&this.clientCallbacks?.onSvgsCollected&&(setTimeout(()=>{(async()=>{try{await this.handleCollectSvgs(e)}catch(s){this.logger.warn({err:s},"Failed to collect SVGs on page, continuing...")}})()},5e3),this.transformer&&await this.injectKnowledgeBaseIntoBrowser(e))}catch(a){a.name!=="AbortError"&&this.logger.warn({err:a,url:t,codePath:o},"Failed to handle frame navigation event, continuing...")}};this.addToPageLoadPromises(o,async()=>i())}async injectKnowledgeBaseIntoBrowser(e){try{if(!this.iconKnowledgeBase||await e.evaluate(()=>!!window._MOMENTIC_ICON_KNOWLEDGE_BASE))return;let n={};Object.keys(this.iconKnowledgeBase).forEach(o=>{this.iconKnowledgeBase[o]?.description&&(n[o]=this.iconKnowledgeBase[o].description)}),await e.evaluate(o=>{let i=window;i._MOMENTIC_ICON_KNOWLEDGE_BASE=o},n)}catch(t){this.logger.warn({err:t},"Failed to inject icon knowledge base into browser, continuing...")}}getBrowserCallbacks(){return{waitForPageLoad:()=>this.waitForPageLoad(),waitForUrl:e=>this.waitForUrl(e),getBrowserState:e=>this.getBrowserState(e),waitForDomStability:e=>this.waitForDOMStability(e),state:{url:()=>this.url(),getDomGraph:()=>this.stateManager.domGraph,getOpenPages:()=>this.getOpenPages(),getRoot:()=>this.getActivePageOrFrame(),userBrowserSettings:this.userBrowserSettings},pageLoadTimeoutMs:this.pageLoadTimeout,signal:this.abortSignal}}ping(){if(this.closed)throw new Error("Page has been closed")}setActiveFrameConfig(e){this.stateManager.setActiveFrameConfig(e)}async reset(e){this.abortSignal=void 0,this.debugData.logsPerPage=[],this.pageLoadPromises={},await this.clearAuthState({closeNonActiveTabs:!0}),await this.stopScreencast(),await this.reinitializeCDPClient(),await this.navigate({url:e.newUrl??this.baseUrl,initialNavigation:!0,loadTimeoutMs:e.timeout}),this.stateManager.reset()}async clearHighlights(){try{await z(_g(this.getBrowserCallbacks()),{milliseconds:re})}catch(e){this.logger.debug({err:e},"Failed to clear highlights, continuing...")}}async cleanup(){this.abortSignal=void 0,this.cleanedUp=!0;try{this.pageLoadAbortListenerCleanup?.(),this.pageLoadAbortListenerCleanup=void 0,this.pageLoadAbortControllers.forEach(e=>e.abort()),this.pageLoadAbortControllers.clear(),this.originsVisited.clear(),await this.context.close(),await this.browser?.close(),this.browser=null}catch(e){this.logger.warn({err:e},"Error cleaning up browser, continuing...")}finally{this.browser=null}}get closed(){return this.cleanedUp||this.context.pages().every(e=>e.isClosed())||!!this.browser&&!this.browser.isConnected()}async ensureMomenticBrowserScriptsLoaded(e,t,n){let o=Date.now(),i=0,a=0;for(;Date.now()-o<Pi;){a++,n?.throwIfAborted();try{if(await at({fn:()=>{let c=window;return!!(c.generateCssSelectors&&c.evaluateCssSelectors&&c.evaluatePrimaryCaches&&c.generateHtmlCacheAttributes&&c.ldist)},timeout:re,arg:void 0,waitForPageLoad:()=>this.waitForPageLoad(),root:e,codePath:"ensuring Momentic system scripts are loaded"}))return}catch(s){if(i++,i>=3){t.warn({err:s},"Multiple errors checking if Momentic scripts are loaded, aborting...");return}}await W(ut),a%2===0&&t.warn("Still waiting for momentic browser scripts to load...")}throw new Error(`Failed to load momentic browser scripts on page ${e.url()}`)}async html(){let e=await this.getActivePageOrFrame();return await this.ensureMomenticBrowserScriptsLoaded(e,this.logger),at({root:e,fn:()=>{let t=window;if(!t?.getFullHtmlTree)throw new Error("Missing Momentic HTML library when fetching page HTML");return t.getFullHtmlTree()},arg:void 0,timeout:te,waitForPageLoad:()=>this.waitForPageLoad(),codePath:"getting the full HTML tree"})}url(){return this.page.url()}async stabilizePageForScreenshot(){try{await this.evaluateFunctionInPage(()=>{let e=window,t=[],n=new Map;document.querySelectorAll("input,textarea,[contenteditable]").forEach(o=>{n.set(o,{value:o.style.getPropertyValue("caret-color"),priority:o.style.getPropertyPriority("caret-color")}),o.style.setProperty("caret-color","transparent","important")}),t.push(()=>{for(let[o,i]of n)o.style.setProperty("caret-color",i.value,i.priority)}),e._MOMENTIC_SCREENSHOT_CLEANUP=()=>{for(let o of t)o();delete e._MOMENTIC_SCREENSHOT_CLEANUP}},void 0,"stabilizing page for screenshot")}catch(e){(!(e instanceof Error)||!e.message.includes("Execution context was destroyed"))&&this.logger.warn({err:e},"Failed to stabilize page before screenshot, continuing...")}}async removeScreenshotStabilization(){try{await this.evaluateFunctionInPage(()=>{window._MOMENTIC_SCREENSHOT_CLEANUP?.()},void 0,"removing screenshot stabilization")}catch{}}async screenshot(e){let{retries:t=1,stabilizeBeforeScreenshot:n=!1}=e,o=this.page.url();n&&await this.stabilizePageForScreenshot();let i=Date.now();try{await this.fixViewportForNewHeadless();let a=await this.screenshotHelper({...e,retries:t});if(a.byteLength>5e6)this.logger.error("Page screenshot is greater than 5MB, which may cause performance issues with some AI models");else if(a.length===0)throw new Error("Got empty screenshot");return a}catch(a){if(t<=0||a.message.includes("has been closed"))throw a;return this.logger.warn({err:a,pageUrl:o},"Failed taking screenshot, retrying..."),await W(Ao),this.screenshot({...e,retries:t-1})}finally{Date.now()-i>1e3&&this.logger.warn({pageUrl:o,duration:Date.now()-i},"Screenshot took longer than expected"),n&&await this.removeScreenshotStabilization()}}async screenshotHelper({locator:e,quality:t,saveToDiskPath:n,timeout:o,respectActiveFrame:i,clearHighlights:a=!1}){a&&await this.clearHighlights(),i&&this.stateManager.frameConfig&&(e=await(await this.getActivePageOrFrame()).frameElement());let s=await this.cdpClient.send({method:"Page.captureScreenshot",params:{format:"jpeg",quality:t,optimizeForSpeed:!0},timeout:o??Ee}),c=Buffer.from(s.data,"base64"),l=await bR.fromBuffer(c),{width:u,height:d}=this.getViewport()??{};if(u&&d&&(l.bitmap.width!==u||l.bitmap.height!==d)&&(c=await l.resize({w:u,h:d}).getBuffer("image/jpeg")),n&&wz(n,c),this.lastScreenshotForRecording=c,!e)return c;let p=await e.boundingBox({timeout:te});if(!p)throw new Error("Attempted to screenshot an element that is not visible on the page");let{x:g,y:m,width:h,height:f}=p;if(!h||!f)throw new Error("Attempted to screenshot an element with zero width or height");g=Math.floor(g),m=Math.floor(m),h=Math.floor(h),f=Math.floor(f);try{let E=await bR.fromBuffer(c),b=E.bitmap.width,C=E.bitmap.height;g=Math.max(0,Math.min(g,b-1)),m=Math.max(0,Math.min(m,C-1)),h=Math.max(1,Math.min(h,b-g)),f=Math.max(1,Math.min(f,C-m)),c=await E.crop({x:g,y:m,w:h,h:f}).getBuffer("image/jpeg")}catch(E){throw new Error(`Failed taking element screenshot at coordinates (${g}, ${m}) with size (${h}, ${f}): ${E}`)}finally{"dispose"in e&&await e?.dispose()}return c}getViewport(){if(this.viewport)return this.viewport;let e=this.page.viewportSize();return e||null}async navigate({url:e,initialNavigation:t=!1,loadTimeoutMs:n=this.pageLoadTimeout}){Lw(e)&&(e=new URL(e,this.baseUrl).toString());let o=Date.now();t||(await this.waitForPageLoad(),await this.waitForDOMStability());let i=!1,a;for(let c=0;c<3;c++)try{await this.page.goto(e,{timeout:n,waitUntil:"domcontentloaded"}),i=!0;break}catch(l){if(a=l,this.abortSignal?.throwIfAborted(),this.logger.warn({err:l},`Error occurred during navigation${c===0?", retrying...":" (fatal)"}`),await W(ut),a.message.includes("Timeout")&&a.message.includes("exceeded")||a.message.includes("net::ERR_CONNECTION_REFUSED"))break;await this.cdpClient.send({method:"Page.stopLoading",params:{},timeout:re})}if(!i)throw new x("UserInfrastructureError",a?.message??"Failed to load page");await this.loadFrameAndRecordUrl({root:this.page,signal:this.abortSignal,codePath:"navigate-step-wait-for-load"}),this.logger.info({url:e},`Navigation complete in ${Math.floor(Date.now()-o)}ms`);let s=this.url();if(lC.has(s))throw new x("UserInfrastructureError",`${e} took too long to load \u{1F61E}. Please ensure the site is accessible and returns content within the page load timeout.`);await this.fixViewportForNewHeadless()}async type(e,t={},n=!1){await this.directTypeHelper(e,t,n)}async getActiveElementHandle(e){return e.evaluateHandle(()=>document.activeElement)}async getActiveElement(e){try{return await at({root:e,fn:()=>{let n=document.activeElement?.textContent??void 0;n&&n.length>100&&(n=n.slice(0,100)+"...[TRUNCATED]");let o=!1,i=window.getSelection();i&&!i.isCollapsed&&i.toString().trim().length>0&&(o=!0);let a=document.activeElement;return a&&"selectionStart"in a&&typeof a.selectionStart=="number"&&typeof a.selectionEnd=="number"&&a.selectionStart!==a.selectionEnd&&(o=!0),document.activeElement?{tag:document.activeElement.tagName.toLowerCase(),contentEditable:document.activeElement.getAttribute("contenteditable")??void 0,textContent:n,hasTextSelected:o}:{hasTextSelected:o}},arg:void 0,timeout:re,waitForPageLoad:()=>this.waitForPageLoad(),codePath:"getting the active element"})}catch(t){this.logger.warn({err:t},"Failed to get active element");return}}async directTypeHelper(e,t={},n=!1){let o=await this.getActivePageOrFrame();await kC({root:o,text:e,options:t,logger:this.logger,callbacks:this.getBrowserCallbacks()});let i=await this.getActiveElement(o);if(n){let s=Date.now();for(;Date.now()-s<this.smartWaitingTimeout&&(!i||i.tag==="body");)await W(Ao),this.abortSignal?.throwIfAborted(),i=await this.getActiveElement(o);i||this.logger.warn("No active element found to type into, attempting anyways")}let a=i?.tag==="input"||i?.tag==="textarea";if(t.clearContent)if(a||t.forceClearContent)if(this.properties.isAndroid&&!a&&i?.textContent){this.logger.info("Clearing content using backspaces");let s=0,c=i.textContent?.length;for(;c&&s<50;){s++;let l=[...Array(c)].map(()=>"Backspace").join("+");await this.page.keyboard.press(l),i=await this.getActiveElement(o),c=i?.textContent?.length}c&&this.logger.warn("Content still remains after clearing existing")}else this.properties.isAndroid?await this.page.keyboard.press("Control+A"):process.platform==="darwin"?await this.page.keyboard.press("Meta+A"):await this.page.keyboard.press("Control+A"),await this.page.keyboard.press("Backspace"),await this.page.waitForTimeout(25);else this.logger.info({activeElementDetails:i},"Currently active element is not eligible for replace content, skipping...");await this.page.keyboard.type(e,{delay:t.delay??gf}),t.pressEnter&&await this.press("Enter",{})}async scrollIntoViewIfNeeded(e){try{await e.scrollIntoViewIfNeeded({timeout:Ee})}catch(t){this.logger.warn({err:t},"Failed to scroll into view, trying with raw JS");try{await e.evaluate(async n=>{let o=n.scrollTop;n.scrollIntoView(),await new Promise(a=>setTimeout(a,250));let i=Date.now();for(;Date.now()-i<1e3;){let a=n.scrollTop;if(a===o)break;o=a,await new Promise(s=>setTimeout(s,250))}},void 0,{timeout:Ee})}catch(n){this.logger.warn({err:n},"Failed to scroll into view using JS, continuing...")}}}async highlightA11yId(e){try{let{resolution:t}=await this.createTargetFromA11yId({id:e,description:null,targetSource:"AI",skipSaveToCache:!0});return await this.highlight(t.locator),!0}catch(t){return this.logger.debug({err:t,id:e},"Failed to highlight target"),!1}}async highlight(e){return iu({locator:e,callbacks:this.getBrowserCallbacks(),logger:this.logger})}recordUrlVisited(e){try{let t=new URL(e).origin;if(t==="null")return;this.originsVisited.add(t)}catch(t){this.logger.warn({err:t},"Failed to record origin visited")}}async waitForPageLoad(){let e=Date.now(),t=Object.values(this.pageLoadPromises),n=Object.keys(this.pageLoadPromises),o=-1,i=0;for(;t.length!==0;){if(Date.now()-e>this.pageLoadTimeout&&this.logger.error({outstandingPromiseKeys:n,outstandingPromises:t},"Still waiting on page load promises"),Date.now()-o<20&&(i++,i>2)){this.logger.error({outstandingPromiseKeys:n,outstandingPromises:t},"Synchronous waiting loop detected, exiting page load wait");return}o=Date.now(),await Promise.allSettled(t),t=Object.values(this.pageLoadPromises),n=Object.keys(this.pageLoadPromises)}}async clearAuthState(e){await this.context.clearCookies();for(let o of this.originsVisited)this.logger.debug({origin:o},`Clearing data using CDP for origin ${o}`),await this.cdpClient.send({method:"Storage.clearDataForOrigin",params:{origin:o,storageTypes:"all"},timeout:re}),this.originsVisited.delete(o);let t=this.context.pages().indexOf(this.page),n=[...this.context.pages()];for(let o=0;o<n.length;o++){let i=n[o];if(i.isClosed())continue;let a=i.url();try{this.originsVisited.delete(new URL(a).origin)}catch{}await gC(i,this.logger),o!==t&&e.closeNonActiveTabs&&(this.logger.info(`Closing tab ${o} with URL ${a}`),await i.close())}}async loadAuthState(e){await this.waitForPageLoad(),await this.waitForDOMStability(),!e||Object.keys(e).length===0?await this.clearAuthState({closeNonActiveTabs:!1}):await this.loadAuthStateHelper(e),await this.refresh(),await this.waitForDOMStability()}async loadAuthStateHelper(e){let t=[];for(let i of e.cookies??[]){let a=await this.setCookie(i);t=t.concat(a)}this.logger.info(`Loaded ${e.cookies?.length??0} cookies`),await this.cdpClient.send({method:"DOMStorage.enable",params:void 0,timeout:re});let n=0;for(let i of e.origins??[])for(let a of i.localStorage)try{await this.cdpClient.send({timeout:re,method:"DOMStorage.setDOMStorageItem",params:{storageId:{securityOrigin:new URL(i.origin).origin,isLocalStorage:!0},key:a.name,value:a.value}}),n++}catch(s){this.logger.warn({err:s,origin:i},"Failed to set local storage entry, continuing...");break}this.logger.info(`Loaded ${n} local storage entries`);let o=e.idb;o&&Object.keys(o).length>0&&(await mC(this.page,o,this.logger),this.logger.info(`Loaded ${Object.keys(o??{}).length} indexedDB databases`))}async saveAuthState(){let t=0,n=null;for(;t<=2;)try{await this.waitForPageLoad(),await this.waitForDOMStability();let o=await this.context.storageState();return o.idb=await pC(this.page,this.logger),o}catch(o){if(n=o,t++,t<=2){this.logger.warn({err:o,retryCount:t,maxRetries:2},`Error saving auth state, retrying (${t}/2)...`);let i=Math.pow(2,t)*100;await new Promise(a=>setTimeout(a,i))}}throw this.logger.error({err:n},"Failed to save auth state after 2 retries"),new x("ActionFailureError",`Failed to save auth state: ${n?.message}`)}async getOpenPages(e){return Og(this.context,e)}saveA11yDetailsToCache(e,t){t.content=e.content,t.name=e.name,t.role=e.role,t.numChildren=e.children.length,delete t.serializedForm,delete t.nodeOnlySerializedForm}async updateCacheWithNewNodeDetails({node:e,target:t,locator:n,startingBoundingBox:o,allowNotActionableNodesOverride:i,logger:a=this.logger}){if(e&&this.saveA11yDetailsToCache(e,t),t.frameCache=this.stateManager.saveAutoFrameCacheDetails(t.frameCache),n)try{let s=await this.fetchHtmlAttributes({locator:n,logger:a,startingBoundingBox:o,allowNotActionableNodesOverride:i});s?(t.generatedSelectors=s.generatedSelectors,t.serializedHtml=s.serializedHtml,t.nodeOnlySerializedHtml=s.nodeOnlySerializedHtml,t.hybridSelector=s.hybridSelector):a.warn("Got undefined HTML attributes when trying to update cache")}catch(s){if(s instanceof Lr)throw a.warn({err:s},"Cache attributes disqualify found element"),s;a.warn({err:s},"Failed to fetch HTML attributes for target, continuing...")}try{await this.saveElementVisualAttributes({target:t,locator:n,logger:a,boundingBox:o})}catch(s){a.debug({err:s},"Failed to save element visual details, continuing...")}}async saveElementVisualAttributes({target:e,locator:t,logger:n,boundingBox:o}){if(!t)return{scrollPerformed:!1};if(!cg.includes(e?.role??""))return{scrollPerformed:!1};if(await this.scrollIntoViewIfNeeded(t),o||(o=await t.boundingBox({timeout:te})),!o||!o.width||!o.height)return n.debug("Skipping visual attributes saving for element with no bounding box after action"),e.boundingBox=void 0,e.screenshotUrl=void 0,{scrollPerformed:!0};let{x:i=0,y:a=0,width:s=0,height:c=0}=o;if(e.boundingBox&&Math.abs(e.boundingBox.width-s)<1&&Math.abs(e.boundingBox.height-c)<1&&Math.abs((e.boundingBox.x??0)-i)<1&&Math.abs((e.boundingBox.y??0)-a)<1)return{scrollPerformed:!0};e.boundingBox=o;let l=await this.screenshot({locator:t,quality:75,retries:0});return e.screenshotUrl=await this.storage.uploadScreenshot(l),{scrollPerformed:!0}}async resolveAutoFrameCache(e){return this.stateManager.resolveAutoFrameCache(e)}async getElementRequiredValues({logger:e,locator:t,requirements:n}){let o={},i=!!n?.position&&n.position!=="irrelevant",a=!!n?.shape&&n.shape!=="irrelevant";if(i||a){let s=await t.boundingBox({timeout:te});if(!s||!s.width||!s.height)throw new x("ActionFailureError","Element does not have a bounding box as required");a&&(o.shape={width:s.width,height:s.height,tolerance:n.shape}),i&&(o.position={x1:s.x,y1:s.y,x2:s.x+s.width,y2:s.y+s.height,tolerance:n.position})}if(n?.text){let s=await t.textContent({timeout:te});o.text=s?.trim()}if(n?.attributes&&n.attributes.length>0){let s={};for(let c of n.attributes){let l=c.trim().toLowerCase();if(!(!l||gr.bannedAiRequiredCacheAttributes.includes(l)))try{let u=await t.getAttribute(l,{timeout:te});u!==null&&(s[c]=u)}catch(u){e.warn({err:u,attr:c},"Failed to fetch required attribute, continuing...")}}o.attributes=s}return o}async getAdditionalElementDetails({mainLocator:e,additionalElement:t,root:n,logger:o}){let i=this.stateManager.a11yIdToNodeMap[t.id];if(!i)return;let a=await this.stateManager.getLocatorFromA11yNode({page:this.page,root:n,node:i});if(e.contentFrame!==a.contentFrame)return;let s=await this.fetchHtmlAttributes({locator:a,logger:o});if(!s?.generatedSelectors||s.generatedSelectors.length===0)return;let c={selectors:s.generatedSelectors};return t.requirements&&(c.requirements=await this.getElementRequiredValues({logger:o,locator:a,requirements:t.requirements})),c}async getAdditionalElementsDetails({mainElementId:e,mainLocator:t,additionalElements:n,root:o,logger:i}){let a=new Set,s=[];for(let c of n)try{if(c.id===e||a.has(c.id))continue;let l=await this.getAdditionalElementDetails({mainLocator:t,additionalElement:c,root:o,logger:i});if(a.add(c.id),!l)continue;s.push(l)}catch(l){this.logger.warn({err:l,additionalElement:c},"Failed to fetch additional element details, continuing...")}return s}async updateCacheWithAdditionalRequirements({mainElementId:e,requirements:t,additionalElements:n,target:o,locator:i,root:a,logger:s}){if(t)try{o.requirements=await this.getElementRequiredValues({logger:s,locator:i,requirements:t})}catch(c){s.warn({err:c},"Failed to generate required values for target")}n&&(o.additionalElements=await this.getAdditionalElementsDetails({mainElementId:e,mainLocator:i,additionalElements:n,root:a,logger:s}))}async createTargetFromA11yId({id:e,description:t,targetSource:n,skipSaveToCache:o,logger:i=this.logger,requirements:a,additionalElements:s}){if(e<0)throw new x("InternalWebAgentError","Only positive IDs should be passed to resolveAllyIdToTarget");let c=this.stateManager.a11yIdToNodeMap[e];if(!c)throw new x("InternalWebAgentError",`Resolving target failed because id ${e} does not exist on the page. This generally indicates an incorrect element was targeted.`);let l=this.stateManager.frameConfig,u,d,p,g;if(this.userBrowserSettings.autoExpandIframes&&!l&&c.parentFrame){let b=c.parentFrame,{cache:C,config:R}=await this.stateManager.getAutoFrameDetailsFromHandle(b);d=C,p=R,u=R.frame,g="auto iframe"}else c.parentFrame&&l?(p=l,u=await this.getActivePageOrFrame(),g="hardcoded url already on the state manager"):(u=await this.getActivePageOrFrame(),g="should not be possible");let m=await this.stateManager.getLocatorFromA11yNode({page:this.page,root:u,node:c}),h={id:e,inputDescription:t??void 0,targetSource:n,targetUpdateTime:new Date().toISOString(),targetUpdateLoggerTags:ye(i),frameCache:d},f,E=!1;o||(p&&(i.info({frameConfigSource:g,frameConfig:gR(p)},"A11y node was resolved to a target within an iframe"),f=this.stateManager.frameConfig,this.stateManager.setActiveFrameConfig(p),E=!0),await this.updateCacheWithNewNodeDetails({node:c,target:h,locator:m,logger:i,allowNotActionableNodesOverride:!0}),await this.updateCacheWithAdditionalRequirements({mainElementId:e,requirements:a,additionalElements:s,target:h,root:u,locator:m,logger:i}));try{return{resolution:{locator:m,a11yNode:c,displayString:c.getNodeOnlySerializedForm(),decisions:[]},target:h,frameConfig:p,frameConfigSource:g}}finally{E&&this.stateManager.setActiveFrameConfig(f)}}async resolveTarget(e,t,n={}){let{targetName:o,logger:i=this.logger,signal:a=this.abortSignal,allowNotActionableNodesOverride:s}=n;if(t.frameCache&&this.userBrowserSettings.autoExpandIframes){let g,m=!1,h=Date.now();for(;Date.now()-h<this.smartWaitingTimeout;)try{let f=await this.stateManager.resolveAutoFrameCache(t.frameCache);this.setActiveFrameConfig(f),m=!0;break}catch(f){g=f,await W(ut,a)}if(!m)throw g}let c=await this.getActivePageOrFrame();await this.ensureMomenticBrowserScriptsLoaded(c,i,a);let l=Date.now(),u=0,d=0,p;for(;Date.now()-l<this.smartWaitingTimeout;){this.abortSignal?.throwIfAborted(),u++;let g=u===2||Date.now()-l>this.smartWaitingTimeout-2e3&&u%2===0;try{p=await this.resolveTargetHelper({root:c,target:t,primaryOnly:!0,shouldLogOnFailure:g,logger:i,allowNotActionableNodesOverride:s,signal:a});break}catch(m){if(m instanceof da)break;if(m instanceof Lr){if(d++,d>2)throw i.error({err:m},"Got multiple cache disqualification errors, giving up"),m;i.warn({err:m},"Got cache disqualification error, waiting and retrying resolution"),await W(ut,a)}a?.throwIfAborted(),g&&i.warn({err:m},`Could not resolve target using primary cache only (x${u})`),await W(ut,a)}}return p||(p=await this.resolveTargetHelper({root:c,target:t,primaryOnly:!1,logger:i,signal:a,allowNotActionableNodesOverride:s}),i.info({decisions:p.decisions},"Target resolution succeeded after waiting")),e?.details?.push({type:"TARGETING",name:o,elementLocationDecisions:p?.decisions??[],pageState:void 0,targetSource:t.targetSource,targetUpdateTime:t.targetUpdateTime}),p}async resolveTargetHelper({root:e,target:t,primaryOnly:n,logger:o,signal:i,allowNotActionableNodesOverride:a,shouldLogOnFailure:s}){let c=Ni(t),l=[],u,d=(await this.getBrowserState({logger:o,abortSignal:i,skipWait:!0,allowNotActionableNodesOverride:a})).serialize(),p;if(t.generatedSelectors||t.hybridSelector){let g;try{g=await this.resolveTargetWithPrimaryMethods({root:e,target:t,logger:o,allowNotActionableNodesOverride:a,shouldLogOnFailure:s})}catch(m){p=m,m instanceof Or&&(l.push(...m.decisions),u=m.cacheMissReason)}if(g)return{...g,pageState:void 0,decisions:[...l,...g.decisions]};n||(l.push({type:"CSS_SELECTOR",matched:!1,reason:p?.message,selectors:Ni(t.generatedSelectors??[])}),t.generatedSelectors=void 0,t.hybridSelector=void 0)}if(n)throw p;if(!this.userBrowserSettings.disableSecondaryCacheResolution){let g=await this.resolveTargetWithSecondaryMethods({root:e,tree:d,target:t,decisions:l,logger:o,signal:i,allowNotActionableNodesOverride:a});if(g)return t.targetSource="HEURISTIC_HEALED",t.targetUpdateTime=new Date().toISOString(),t.targetUpdateLoggerTags=ye(o),g;u=u??"secondary-resolution-failed"}throw new Or(`Could not find any relevant node given target: ${JSON.stringify(c)}`,l,u)}async resolveTargetWithPrimaryMethods({root:e,target:t,logger:n,allowNotActionableNodesOverride:o,shouldLogOnFailure:i}){if(!t.nodeOnlySerializedHtml)throw new da("Insufficient data to resolve target using primary methods (missing node HTML)");let a=i?n:_n,s=this.userControlledBrowserSettings.hybridSelectorMode,c={ldistThreshold:lg,requireBoundingBox:!o,ignoreHrefForCaching:this.userControlledBrowserSettings.ignoreHrefForCaching,requireMatchingBoundingBox:this.userControlledBrowserSettings.bustCacheOnBoundingBoxChange?t.boundingBox:void 0,requirements:t.requirements,additionalElements:t.additionalElements,importantProperties:{attributes:this.userControlledBrowserSettings.importantAttributes,classes:this.userControlledBrowserSettings.importantClasses,styles:this.userControlledBrowserSettings.importantStyles}},{css:l,hybrid:u}=await at({fn:v=>window.evaluatePrimaryCaches(v),arg:{cssParams:{selectors:t.generatedSelectors??[],cachedElementSerialized:t.nodeOnlySerializedHtml,opts:c},hybridParams:s&&t.hybridSelector?{nodes:t.hybridSelector,cachedElementSerialized:t.nodeOnlySerializedHtml,opts:c}:void 0},root:e,timeout:te,waitForPageLoad:()=>this.waitForPageLoad(),codePath:"evaluating target caches"}),d,p,g=[];if(s==="prefer"&&u?.result){d=u.result;let v={type:"HYBRID_SELECTOR",matched:!0,logs:u.logs,reason:"Discovered a match using Momentic's hybrid text and CSS selector approach"};g.push(v),p="HYBRID_SELECTOR"}else if(l?.result){d=l.result;let v=`${d.workingSelectors.length} CSS selectors matched the following element: ${d.serializedElement}`,M=d.workingSelectors.slice(0,5);g.push({type:"CSS_SELECTOR",matched:!0,logs:l.logs,reason:v,selectors:M}),n.debug({reason:v,workingSelectors:M},"Resolved with CSS selectors"),p="CSS_SELECTOR"}else throw g.push({type:"CSS_SELECTOR",matched:!1,reason:l.logs.length===1?"CSS evaluation failed":"No CSS selectors matched",selectors:[],logs:l.logs}),u&&g.push({type:"HYBRID_SELECTOR",matched:!1,reason:u.logs.length===1?"Hybrid evaluation failed":"No hybrid selectors matched",logs:u.logs}),l?.error&&n.error({err:new Error(l.error)},"Cache evaluation errored unexpectedly (CSS)"),u?.error&&n.error({err:new Error(u.error)},"Cache evaluation errored unexpectedly (Hybrid)"),new Or("Cache evaluation failed",g,l.cacheMissReason);let m,h,f;if(this.userBrowserSettings.visualActions){let v=d.mPath;if(!v)throw new Error("Found element did not have an mPath despite using visual actions");let M=v.join(" > ");m=e.locator(M),h=this.stateManager.getNodeUsingMPathSelector(M)}else if(d.dataMomenticId!==void 0)f=parseInt(d.dataMomenticId),h=this.stateManager.dataMomenticIdToNodeMap[f],"workingSelectors"in d?m=e.locator(d.workingSelectors[0]):m=e.locator(wr(f));else throw new x("InternalWebAgentError","Received an element resolution result with no identifying attributes");s&&t.hybridSelector&&(u?.logs.length===1?a.warn({hybridResult:u,cssResult:l,hybridMode:s},"Hybrid selector resolution rejected, continuing..."):u?.result?l?.result&&u?.result&&u.result.serializedElement!==l.result.serializedElement&&(this.userBrowserSettings.visualActions&&JSON.stringify(l.result.mPath)!==JSON.stringify(u.result.mPath)?n.warn({originalCache:t,hybridResult:u,cssResult:l,hybridMode:s,mode:"visualActions"},"Hybrid selector resolution returned a different element than CSS selector resolution, continuing..."):l.result.dataMomenticId!==u.result.dataMomenticId&&n.warn({originalCache:t,hybridResult:u,cssResult:l,hybridMode:s,mode:"dataMomenticId"},"Hybrid selector resolution returned a different element than CSS selector resolution, continuing...")):a.warn({originalCache:t,hybridResult:u,cssResult:l,hybridMode:s},"Hybrid selector resolution returned no eligible elements while CSS resolution did, continuing..."));let[E,b]=await Promise.all([m.textContent(),m.boundingBox()]);if((E??"")!==(d.textContent??""))throw n.warn({currentTextContent:E,originalTextContent:d.textContent},"Retrying cache resolution because element's text content has changed since resolution"),new Error("Element's text has changed since cache was resolved");if(!b||Math.abs(b.height-d.boundingBox.height)>1||Math.abs(b.width-d.boundingBox.width)>1||Math.abs((b.x??0)-(d.boundingBox.x??0))>1||Math.abs((b.y??0)-(d.boundingBox.y??0))>1)throw n.warn({currentBoundingBox:b,originalBoundingBox:d.boundingBox},"Retrying cache resolution because element's bounding box has changed since resolution"),new Error("Element's bounding box has changed since cache was resolved");let C=Ni(t);await this.updateCacheWithNewNodeDetails({node:h,target:t,locator:m,logger:n,startingBoundingBox:d.boundingBox,allowNotActionableNodesOverride:o});let R=Vg(C,t);return R&&Object.keys(R).length>0&&(t.cacheResolutionUpdateTime=new Date().toISOString(),t.cacheResolutionUpdateLoggerTags=ye(n),t.cacheResolutionUpdateSource=p),{a11yNode:h,displayString:d.serializedElement,locator:m,decisions:g}}async resolveHardcodedCssSelector(e){let{ctx:t,selector:n,logger:o=this.logger,signal:i=this.abortSignal,timeoutMs:a=this.smartWaitingTimeout}=e,s=await this.getActivePageOrFrame(),c=Date.now(),l=0,u,d=[];for(;Date.now()-c<a;){i?.throwIfAborted(),l++;let p=s.locator(n),g;try{return await p.waitFor({state:"attached",timeout:re}),g=await Cr(p,o,500)??"",d.push({type:"USER_SELECTOR",matched:!0,reason:`The user-provided CSS selector ${n} matched an element on the page.`}),t?.details?.push({type:"TARGETING",name:e.targetName,elementLocationDecisions:d,targetSource:"USER_CSS_SELECTOR",targetUpdateTime:new Date().toISOString()}),{locator:p,displayString:g,decisions:d}}catch(m){let h=m.message;u=new x("ActionFailureError",`CSS selector '${n}' failed to resolve after ${l} attempts: ${h.includes("locator.waitFor: Timeout")?"the selector did not match any element on the page":h}`),await W(ut,i)}}throw u}async resolveTargetWithSecondaryMethods(e){if(!e.target.boundingBox)return;let{x:t,y:n,width:o,height:i}=e.target.boundingBox,a=await this.resolveTargetWithSecondaryMethodsHelper(e);if(!a)return;let s=await a.locator.boundingBox({timeout:te});if(!s){this.logger.debug({proposedNode:a.displayString},"Rejecting secondary matching result due to lack of a bounding box");return}let{x:c,y:l,width:u,height:d}=s;if(Math.abs(u-o)>10||Math.abs(d-i)>10){this.logger.debug({newW:u,oldW:o,newH:d,oldH:i,proposedNode:a.displayString},"Rejecting secondary matching result due to difference in dimensions");return}else if(!t||!n||!c||!l){this.logger.debug({oldX:t,oldY:n,newX:c,newY:l,proposedNode:a.displayString},"Rejecting secondary matching result due to missing x/y coords");return}else if(Math.abs(c-t)>100||Math.abs(l-n)>100){this.logger.debug({newX:c,newY:l,oldX:t,oldY:n,proposedNode:a.displayString},"Rejecting secondary matching result due to large difference in x/y coords");return}return a}async resolveTargetWithSecondaryMethodsHelper({root:e,target:t,decisions:n,logger:o,signal:i,allowNotActionableNodesOverride:a}){if(t.nodeOnlySerializedHtml&&t.nodeOnlySerializedHtml.trim().length<aC){let l="Refusing to attempt HTML comparison since the saved element is too short.";n.push({type:"HTML_DISTANCE",matched:!1,reason:l})}else if(t.nodeOnlySerializedHtml&&t.nodeOnlySerializedHtml.length>50)try{let l=await at({fn:d=>window.findClosestElementByLDist?.(d),arg:{nodeOnlySerializedHtml:t.nodeOnlySerializedHtml},timeout:Ee,root:e,waitForPageLoad:()=>this.waitForPageLoad(),codePath:"finding the closest element on the page"}),u=Math.floor(lg*t.nodeOnlySerializedHtml.length);if(l&&l.closestDistance&&l.closestDistance>=u){let d=`Closest HTML candidate still has too far distance (${l.closestDistance}) from threshold (${u})`;n.push({type:"HTML_DISTANCE",matched:!1,reason:d,distance:l.closestDistance,closestElement:l.closestNodeSerialized})}else{if(l?.error)throw new Error(l.error);if(l?.dataMomenticId||l?.mPathSelector){let d=l.dataMomenticId?parseInt(l.dataMomenticId):void 0,p,g;if(d)p=this.stateManager.dataMomenticIdToNodeMap[d],g=e.locator(wr(d));else if(l.mPathSelector)p=this.stateManager.getNodeUsingMPathSelector(l.mPathSelector),g=e.locator(l.mPathSelector);else throw new Error("HTML ldist comparison returned no error, data momentic id, or mPath selector");let m=l.closestNodeSerialized??await Cr(g,o,500)??"unknown element";o.warn({result:l,originalTarget:t,displayString:m},"Resolved cached target to new node with pure html levenshtein distance");let h=Ni(t);await this.updateCacheWithNewNodeDetails({node:p,target:t,locator:g,logger:o,startingBoundingBox:l.boundingBox,allowNotActionableNodesOverride:a});let f=Vg(h,t);return f&&Object.keys(f).length>0&&(t.cacheResolutionUpdateTime=new Date().toISOString(),t.cacheResolutionUpdateLoggerTags=ye(o),t.cacheResolutionUpdateSource="HTML_DISTANCE",o.info({diffs:f,result:l},"Updated cache after l-dist resolution")),n.push({type:"HTML_DISTANCE",matched:!0,reason:`Found an element on the page within ${u} string comparison distance of the saved element.`,logs:l.logs,distance:l.closestDistance,closestElement:m,savedElement:t.nodeOnlySerializedHtml}),{locator:g,a11yNode:p,displayString:m,decisions:n,pageState:void 0}}else throw new Error(`Got invalid HTML evaluation result: ${JSON.stringify(l)}`)}}catch(l){o.info({err:l},"Failed to find closest HTML node using levenshtein distance"),n.push({type:"HTML_DISTANCE",matched:!1,reason:`Error finding closest HTML node by string distance: ${l}`})}let s=t.screenshotUrl,c=t.role??"";if(s&&cg.includes(c))try{let l=await this.resolveTargetWithTemplateMatching({root:e,oldTarget:t,screenshotUrl:s,signal:i,allowNotActionableNodesOverride:a});return{...l,decisions:[...n,...l.decisions],pageState:void 0}}catch(l){i?.throwIfAborted(),n.push({type:"TEMPLATE_MATCHING",matched:!1,reason:`Error finding closest element using saved screenshot: ${l}`,elementImageUrl:s}),o.warn({err:l},"Did not find any close element using saved screenshot")}}async resolveTargetWithTemplateMatching({screenshotUrl:e,oldTarget:t,signal:n,allowNotActionableNodesOverride:o}){let i;if(!this.enricher)throw new Error("Enricher not available for screenshot resolution");let a=await this.screenshot({retries:0}),c=await(await fetch(e)).arrayBuffer(),l=Pz(),u=await this.enricher.runTemplateMatching({id:l,searchImageBase64String:Buffer.from(c).toString("base64"),pageImageBase64String:a.toString("base64")},{signal:n}),{target:d,locator:p}=await this.getTargetFromPositionPercentages({percentX:u.x,percentY:u.y,allowNotActionableNodesOverride:o}),g=d.boundingBox?.width,m=d.boundingBox?.height;if(!g||!m)throw i="Rejecting target from screenshot due to no bounding box",new Error(i);let h=d.id,f=this.stateManager.a11yIdToNodeMap[h],E=Ni(t);await this.updateCacheWithNewNodeDetails({target:t,node:f,locator:p,allowNotActionableNodesOverride:o});let b=Vg(E,t);return b&&Object.keys(b).length>0&&(t.cacheResolutionUpdateTime=new Date().toISOString(),t.cacheResolutionUpdateLoggerTags=ye(this.logger),t.cacheResolutionUpdateSource="TEMPLATE_MATCHING",this.logger.info({id:l,diffs:b,templateMatch:u},"Updated cache after template matching resolution")),{locator:p,a11yNode:f,displayString:d.nodeOnlySerializedHtml??"",decisions:[{type:"TEMPLATE_MATCHING",matched:!0,reason:"Found element using screenshot",elementImageUrl:e}]}}async typeIntoTarget(e,t,n={}){await this.highlight(t.locator);let o=await t.locator.getAttribute("type",{timeout:re})??"",i=DC.some(a=>a===o.toLowerCase());return await Pg({targetingResult:t,options:{force:n.force,relativePosition:n.relativePosition},logger:this.logger,retryTimeoutMs:this.smartWaitingTimeout,position:i?{x:1,y:1}:void 0,actionSource:"type",browserCallbacks:this.getBrowserCallbacks(),isAndroid:this.properties.isAndroid??!1}),await this.page.waitForTimeout(150),this.directTypeHelper(e,n)}async click(e,t,n={}){return Pg({targetingResult:e,options:n,logger:this.logger,actionSource:"click",retryTimeoutMs:this.smartWaitingTimeout,controllerCallbacks:t,browserCallbacks:this.getBrowserCallbacks(),isAndroid:this.properties.isAndroid??!1})}async waitForUrl({beforeUrl:e,matcher:t},n){let o=n?.timeout??this.pageLoadTimeout,i=Date.now(),a=!1,s=e;for(;Date.now()-i<o;){if(this.abortSignal?.throwIfAborted(),s=this.url(),Wc(s,t,n)){a=!0;break}await W(ut,this.abortSignal)}if(!a)throw new x("ActionFailureError",`The active page URL ${n?.negated?"still does":"does not"} ${jA(t)} in ${o}ms.
4339
4339
  Current tab: ${s}`);try{await this.loadFrameAndRecordUrl({root:this.page,signal:this.abortSignal,codePath:"wait-for-url-step"})}catch(c){this.logger.warn({err:c},"Failed waiting for page load after URL change, continuing...")}}async dragAndDrop(e,t,n={}){await this.highlight(e),await this.hover({locator:e}),await this.page.mouse.down();let o=await t.boundingBox({timeout:te});if(!o)throw new x("ActionFailureError","Could not get bounding box of target element");let i=o.x+o.width/2,a=o.y+o.height/2,s=n.steps??5;await this.page.mouse.move(i,a,{steps:s}),await W(n.hoverSeconds?Math.min(n.hoverSeconds*1e3,Ee):500),await this.highlight(t),await this.page.mouse.up()}async mouseDrag(e,t,n,o){o&&await this.hover({locator:o}),await this.page.mouse.down();let i;if(o){let a=await o.boundingBox({timeout:te});a&&(i={x:a.x+a.width/2,y:a.y+a.height/2})}i||(this.logger.warn("Could not get starting position from fromTarget, falling back to (0,0)"),i={x:0,y:0}),await this.page.mouse.move(i.x+e,i.y+t,{steps:n}),await W(Ao),await this.page.mouse.up()}async hover(e){await this.highlight(e.locator),await Co({func:async t=>{await this.scrollIntoViewIfNeeded(t.locator);let n=await t.locator.boundingBox({timeout:te});if(!n)throw new Error("Attempted to hover over element with no bounding box");await this.page.mouse.move(n.x+n.width/2,n.y+n.height/2,{steps:3})},action:"hovering over element",logger:this.logger,retryTimeoutMs:this.smartWaitingTimeout,targetingResult:e,callbacks:this.getBrowserCallbacks()})}async focus(e){await this.highlight(e.locator),await Co({func:t=>t.locator.focus({timeout:Ee}),action:"focusing element",logger:this.logger,retryTimeoutMs:this.smartWaitingTimeout,callbacks:this.getBrowserCallbacks(),targetingResult:e})}async blur(e){if(!e){let t=await this.getActivePageOrFrame();await at({fn:()=>{let n=document.activeElement;n&&n.nodeType===1&&n.blur()},root:t,arg:void 0,waitForPageLoad:()=>this.waitForPageLoad(),timeout:re,codePath:"blurring the active element"});return}await this.highlight(e.locator),await Co({func:t=>t.locator.blur({timeout:Ee}),action:"blurring element",logger:this.logger,retryTimeoutMs:this.smartWaitingTimeout,callbacks:this.getBrowserCallbacks(),targetingResult:e})}async selectOption(e,t,n=!1){await this.highlight(e.locator),await Co({action:"selecting option from dropdown",logger:this.logger,retryTimeoutMs:this.smartWaitingTimeout,callbacks:this.getBrowserCallbacks(),func:async o=>{if(t.type==="INDEX"){let i=Number(t.index);if(isNaN(i))throw new x("UserConfigurationError",`Page index ${t.index} is not a number`)}await o.locator.selectOption({value:t.type==="VALUE"?t.value:void 0,label:t.type==="LABEL"?t.label:void 0,index:t.type==="INDEX"?Number(t.index):void 0},{force:n,timeout:te})},targetingResult:e})}async press(e,t){let n=t.repeat??1;if(t.convertMeta){let o=au(e,this.properties.isAndroid);o!==e&&(this.logger.info({key:e,convertedKey:o},"Converted platform dependent keys"),e=o)}for(let o=0;o<n;o++)await this.page.keyboard.press(e,{delay:t.delayMs??0})}async keyDown(e,t){if(t.convertMeta){let n=au(e,this.properties.isAndroid);n!==e&&(this.logger.info({keyString:e,convertedKey:n},"Converted platform dependent keys"),e=n)}for(let n of Hg(e))await this.page.keyboard.down(n)}async keyUp(e,t){if(t.convertMeta){let n=au(e,this.properties.isAndroid);n!==e&&(this.logger.info({keyString:e,convertedKey:n},"Converted platform dependent keys"),e=n)}for(let n of Hg(e))await this.page.keyboard.up(n)}async refresh(e){let t=e?.loadTimeoutMs??this.pageLoadTimeout;await this.waitForPageLoad();let n=0,o=2;for(;n<o;){n++;try{await this.page.reload({waitUntil:"domcontentloaded",timeout:t});break}catch(i){this.logger.warn({err:i,attempt:n},`Failed to reload page${n<o?", retrying...":", continuing..."}`)}}await this.loadFrameAndRecordUrl({root:this.page,signal:this.abortSignal,codePath:"reload-step"}),await this.waitForDOMStability()}async getBrowserState(e){let{maxAttempts:t=2,logger:n=this.logger,skipWaitForPageLoad:o,allowNotActionableNodesOverride:i,shouldLogOnFailure:a}=e,s=e.abortSignal??this.abortSignal,c=!i,l=i?!0:this.userControlledBrowserSettings.showZeroOpacityElements,u=a?n:_n;o||await this.waitForPageLoad(),e.skipWait||await this.waitForDOMStability({logger:n,signal:s});let d=0,p;for(;d<t;){d++;try{return await z(this.stateManager.getA11yTree({devicePixelRatio:this.devicePixelRatio,abortSignal:s,logger:n,filterByViewport:e.filterByViewport,showZeroOpacityElements:l,flagNotActionableNodes:c}),{milliseconds:this.pageLoadTimeout*d,signal:s,message:"Getting browser state took too long"})}catch(g){if(s?.throwIfAborted(),p=g instanceof Error?g.message:`${g}`,d>=t)throw g;u.warn({err:g,url:this.url()},"Error getting a11y tree, retrying...")}}throw new x("ActionFailureError",`Getting page content failed after ${t} attempts. Error: ${p}`)}async getViewportOffsetDetails(e){let[t,n,o,i,a]=await at({root:e,fn:()=>[window.scrollY,window.scrollX,window.screen.width,window.screen.height,window.devicePixelRatio],arg:void 0,timeout:te,waitForPageLoad:async()=>{},codePath:"getting current viewport details"});return{upperBound:t,lowerBound:t+i,leftBound:n,rightBound:n+o,width:o,height:i,devicePixelRatio:this.properties.systemDevicePixelRatio??a}}async waitForDOMStability(e){let{logger:t=this.logger,timeout:n=this.smartWaitingTimeout,signal:o}=e??{},i={value:Date.now()},a=p=>{i.value=Date.now()},s=()=>a("DOM.documentUpdated");this.cdpClient.addListener("DOM.documentUpdated",s);let c=()=>a("Page.frameDetached");this.cdpClient.addListener("Page.frameDetached",()=>c);let l=()=>a("Page.frameStartedLoading");this.cdpClient.addListener("Page.frameStartedLoading",l);let u=()=>a("Page.navigatedWithinDocument");this.cdpClient.addListener("Page.navigatedWithinDocument",u);let d=()=>a("frameRequestedNavListener");this.cdpClient.addListener("Page.frameRequestedNavigation",d);try{await this.waitForDOMStabilityHelper(i,t,n,o)}finally{this.cdpClient.removeListener("DOM.documentUpdated",s),this.cdpClient.removeListener("Page.frameDetached",c),this.cdpClient.removeListener("Page.frameStartedLoading",l),this.cdpClient.removeListener("Page.navigatedWithinDocument",u),this.cdpClient.removeListener("Page.frameRequestedNavigation",d)}}async waitForDOMStabilityHelper(e,t,n,o){let i=!1,a=Date.now(),s,c={quality:25,retries:0,stabilizeBeforeScreenshot:!0},l=!1,u=0;for(;Date.now()-a<n;){if(o?.throwIfAborted(),await W(Ao,this.abortSignal),s)try{let d=await this.screenshot(c);if(!d.equals(s)){s=d,l=!1;continue}l=!0}catch(d){u++,u%3===0&&t.warn({err:d,screenshotErrors:u},"Failed to take screenshot for DOM stability check"),o?.throwIfAborted()}else try{s=await this.screenshot(c)}catch(d){u++,u%3===0&&t.warn({err:d,screenshotErrors:u},"Failed to take screenshot for DOM stability check"),o?.throwIfAborted()}if(!(Date.now()-e.value<iC)){i=!0;break}}i||t.warn({duration:Date.now()-a,stable:{a11y:i,screenshot:l}},"A11y wait phase completed due to timeout, continuing...")}async clickUsingVisualCoordinates(e,t){let{x:n,y:o}=e;this.logger.debug({x:n,y:o},"Executing mouse click with visual coordinates"),await this.waitForPageLoad(),await this.page.mouse.click(n,o,{button:t.rightClick?"right":"left",clickCount:t.doubleClick?2:1})}async dragAndDropUsingVisualCoordinates(e,t,n){await GC(this.page,e,t,n)}async mouseDragUsingVisualCoordinates(e,t,n,o,i){await HC({page:this.page,deltaX:e,deltaY:t,steps:n,delayMs:o,visualTarget:i,isAndroid:this.properties.isAndroid??!1})}async hoverUsingVisualCoordinates(e){await this.page.mouse.move(e.x,e.y,{steps:3})}async getElementLocation(e){let t=await this.cdpClient.send({method:"DOMSnapshot.captureSnapshot",params:{computedStyles:[],includeDOMRects:!0,includePaintOrder:!0},timeout:te}),n=await z(this.page.evaluate(()=>window.devicePixelRatio),{milliseconds:Ee});process.platform==="darwin"&&n===1&&(n=nC);let o=t.documents[0],i=o.layout,a=o.nodes,s=a.nodeName||[],c=a.backendNodeId||[],l=i.nodeIndex,u=i.bounds,d=-1;for(let b=0;b<s.length;b++)if(c[b]===e){d=l.indexOf(b);break}if(d===-1)throw new Error(`Could not find any backend node with ID ${e}`);let[p=0,g=0,m=0,h=0]=u[d];p/=n,g/=n,m/=n,h/=n;let f=p+m/2,E=g+h/2;return{centerX:f,centerY:E}}async scrollVertical(e){return Ig({frame:this.stateManager.frameConfig?await this.getActivePageOrFrame():null,page:this.page,deltaX:0,directionX:null,deltaY:e?Math.abs(e):null,directionY:e&&e>0?"down":"up",signal:this.abortSignal,callbacks:this.getBrowserCallbacks(),logger:this.logger})}async scrollHorizontal(e){return Ig({frame:this.stateManager.frameConfig?await this.getActivePageOrFrame():null,page:this.page,deltaX:e?Math.abs(e):null,directionX:e&&e>0?"right":"left",deltaY:0,directionY:null,signal:this.abortSignal,callbacks:this.getBrowserCallbacks(),logger:this.logger})}async goForward(){await this.waitForPageLoad(),await this.page.goForward({waitUntil:"domcontentloaded",timeout:this.pageLoadTimeout}),await this.loadFrameAndRecordUrl({root:this.page,signal:this.abortSignal,codePath:"go-forward"})}async goBack(){await this.waitForPageLoad(),await this.page.goBack({waitUntil:"domcontentloaded",timeout:this.pageLoadTimeout}),await this.loadFrameAndRecordUrl({root:this.page,signal:this.abortSignal,codePath:"go-back"})}async reinitializeCDPClient(e){await this.cdpClient.reinitialize(e),await this.initializeScreencast()}async stopScreencast(){if(this.clientCallbacks?.onScreencastFrame)try{await this.cdpClient.send({method:"Page.stopScreencast",params:{}})}catch{}}async changeActivePage(e,t){if(await this.stopScreencast(),this.recordUrlVisited(e.url()),this.onVideoPageChange){let n=await e.video()?.path();if(n){let o=ER(n);this.onVideoPageChange({videoName:o})}}this.page=e,await this.reinitializeCDPClient(t??this.pageLoadTimeout)}async createNewTab(e,t){let n=await this.context.newPage();await this.changeActivePage(n,t?.loadTimeoutMs),await this.navigate({url:e,initialNavigation:!0,...t}),this.handleAvailableTabsChange()}async switchToPage(e,t){let n=!0,o,i=Date.now();for(;n||t?.retry&&Date.now()-i<this.smartWaitingTimeout;){n=!1;try{await this.switchToPageHelper(e,t);return}catch(a){this.logger.warn({err:a},"Error switching to page, retrying..."),o=a,await W(ut)}}throw o}async switchToPageHelper(e,t){let n=this.context.pages().map((i,a)=>({page:i,url:i.url(),index:a})),o;if(e.type==="INDEX"){let i=Number(e.index);if(isNaN(i))throw new x("UserConfigurationError",`Page index ${e.index} is not a number`);if(i<0||i>=n.length)throw new Error(`Page index ${e.index} exceeds the number of available pages: ${JSON.stringify(n.map(a=>a.url))}`);o=n[i]}else{let i=n.filter(a=>e.type==="SUBSTRING"?a.url.includes(e.substring):a.url.match(e.pattern));i.length>1&&this.logger.warn(`More than one page matches the page switch criteria: ${JSON.stringify(i.map(a=>a.url))}`),o=i[i.length-1]}if(!o)throw new Error(`Could not find matching page using criteria: ${JSON.stringify(e)}.
@@ -4342,9 +4342,9 @@ Available pages:${JSON.stringify(n.map(i=>i.url))}`);if(!vo(o.url,this.logger)){
4342
4342
  `),tokenLength:d}),u=[],d=0,p=g.length?[g[g.length-1].id]:[],m=!1);let h=c[l],f=Rr(h);d+=f,h.length>a&&(h=h.slice(0,a));let C=Array.from(h.matchAll(vR)).map(K=>K&&K.length>=3?{tagName:K[1],id:K[2]}:void 0).filter(K=>!!K),v=Array.from(h.matchAll(Oz)).map(K=>K&&(K[2]||K[4])).filter(K=>!!K);v.reverse();let M=h.replace(/ id="[0-9]+"/g,"");u.push(M);for(let K of C)p.push(K.id),g.push(K);for(let K of v){let $=g[g.length-1];$&&$.tagName===K&&g.pop()}let A=g.some(K=>Nz.includes(K.tagName)),I=c[l+1]??"",k=Rr(I),ge=Array.from(I.matchAll(vR)).map(K=>K&&K.length>2?K[1]:void 0).filter(K=>!!K),be=ge.some(K=>CR.includes(K)),Re=ge.some(K=>Lz.includes(K));d+k>=i&&(m=!0),d>=n&&(be&&!A||v.some(K=>Dz.includes(K)))&&(m=!0),d>=o&&Re&&!A&&(m=!0),l++}return u.length&&s.push({ids:p,content:u.join(`
4343
4343
  `),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 Fz=75e4,mu=3e5;async function xo(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=Rr(u);if(d>Fz)try{let p=pu({serializedTree:u,options:{minChunkTokenCount:1e4,maxChunkTokenCount:1e5,acceptableChunkTokenCount:5e4,maxLineLength:4e3},logger:i});l=await zz({...r,tokenLimit:mu-1e4,chunks:p.chunks}),u=l.serialize();let g=Rr(u);i.info({oldTokens:d,newTokens:g},"Filtered page using keywords"),d=g}catch(p){i.warn({err:p},"Error filtering page using keyword matching, using naive truncation"),l=l.pruneToSerializedCharLimit(mu*Bn),u=l.serialize();let g=Rr(u);i.info({oldTokens:d,newTokens:g},"Filtered page using naive truncation"),d=g}if(d>mu)try{if(o){let p=pu({serializedTree:u,options:wR,logger:i}),g=Uz();l=await z(Bz({...r,chunks:p.chunks,callId:g}),{milliseconds:12e3,signal:c}),u=l.serialize();let m=Rr(u);i.info({oldTokens:d,newTokens:m,langfuseCallId:g},"Filtered page using AI chunk ranking"),d=m}else{let p=pu({serializedTree:u,options:AR,logger:i});l=await z(Hz({...r,chunkResult:p,tokenLimit:4e4}),{milliseconds:12e3,signal:c}),u=l.serialize();let g=Rr(u);i.info({oldTokens:d,newTokens:g},"Filtered page using RAG"),d=g}}catch(p){i.warn({err:p},"Error filtering page using RAG/AI, using naive truncation"),l=l.pruneToSerializedCharLimit(mu*Bn),u=l.serialize(),i.info("Filtered page using naive truncation")}return u}async function Bz({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:ye(c)}),u=[];return t.forEach((p,g)=>{l.indices.includes(g)&&(u=u.concat(p.ids))}),i.pruneUsingRelevantIds(new Set(u))}async function zz(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:ye(i),abortSignal:a});i.info({keywordsResult:s},"Got keywords for page filtering");for(let c of s.keywords){let l=r.chunks.filter(g=>g.content.toLowerCase().includes(c.toLowerCase()));if(!l.length||l.reduce((g,m)=>g+m.tokenLength,0)>r.tokenLimit&&l.length>1)continue;let d=l.flatMap(g=>g.ids);return n.pruneUsingRelevantIds(new Set(d))}throw new Error("No keywords were unique enough for page filtering")}async function Hz(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:ye(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 jg(r,e){if(!r.description)throw new x("UserConfigurationError","Cannot locate element with empty description");return fr({action:async()=>Gz(r,e),frameConfig:r.iframeUrl?{type:"url",url:r.iframeUrl}:void 0,browser:e.browser,logger:r.logger})}async function Gz(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:p,browser:g,localCodeEvalTools:m,generator:h,abortSignal:f}=e,E=r.description,b=r.useMemory&&!t;n&&(E=await ds({orgId:p,s:E,context:n,localTools:m,signal:f,logger:l})),a&&(E=Wz(E,a));let{serializedTree:C,tree:R}=await Kr(g,{allowNotActionableNodesOverride:u,filterByViewport:o,abortSignal:f,skipWait:i,logger:l}),v,M=Date.now(),A;for(;!v&&Date.now()-M<3e3;){f.throwIfAborted();try{v=await g.screenshot({clearHighlights:!0,respectActiveFrame:!0,retries:2})}catch(Q){A=Q}}if(!v)throw new x("ActionFailureError",`Failed to take screenshot of page to locate element. The page may be unresponsive, or your machine might be severely resource constrained. Error: ${A?.message}`);let I=C,k=!1,ge=`data:image/jpeg;base64,${v.toString("base64")}`;I=await xo({type:"locator",description:E,screenshot:ge,serializedTree:C,options:{aiPageFiltering:c},tree:R,fixtures:{generator:h,signal:f,logger:l,orgId:p}}),I!==C&&(k=!0);let be=await h.getElementLocation({browserState:I,goal:E,screenshot:ge,source:a,memory:b?s:void 0},{disableCache:t,abortSignal:f,loggerTags:ye(l),useMemory:b});if(l.debug({usedRag:k,result:be},"Got locator result"),!(be.id>0))throw new bn(`Could not find any relevant element: ${be.thoughts}`,be.updatedMemory?{type:"GCS_TRACES",traces:be.updatedMemory}:void 0);let{resolution:K,target:$,frameConfig:le}=await g.createTargetFromA11yId({id:be.id,requirements:be.requirements,additionalElements:be.additionalElements,description:E,targetSource:"AI",logger:l});if(K.a11yNode?.properties?.hidden&&K.a11yNode?.properties?.hidden!=="false")throw new x("ActionFailureError",`Momentic's AI found a relevant element to interact with, but it is explicitly marked with an 'aria-hidden' attribute. Please remove this attribute or adjust the element description to locate a different element. Element chosen: ${K.displayString}`);return b&&(be.updatedMemory?$.memory={type:"GCS_TRACES",traces:be.updatedMemory}:s&&($.memory=s)),{thoughts:be.thoughts,target:$,resolution:K,frameConfig:le,screenshot:ge}}var Vz=["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:"],RR="<select> element:",xR="text input or contenteditable element:",MR="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:",_R="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:",Wg=[RR,xR,MR,_R,...Vz];function PR(r,e){if(r===e)return!0;for(let t of Wg){if(!r.startsWith(t))continue;let n=r.slice(t.length).trim();if(Wg.some(o=>e.startsWith(o)&&e.slice(o.length).trim()===n)||n===e.trim())return!0}return!!Wg.some(t=>e.startsWith(t)&&e.slice(t.length).trim()===r.trim())}function Wz(r,e){if(!r||!e)return r;switch(e){case"SELECT_OPTION":return`${RR} ${r}`;case"TYPE":return`${xR} ${r}`;case"NEGATED_ELEMENT_VISIBLE_CHECK":return`${MR}
4344
4344
  ${r}`;case"ELEMENT_CHECK":return`${_R}
4345
- ${r}`;default:return r}}var jz=15;async function gu({command:r,aiPageFiltering:e,logger:t,fixtures:n,source:o,useMemory:i,maxRetries:a=jz}){if(!r.assertion.trim())throw new x("ActionFailureError","Assertion command is missing the assertion content");let{browser:s}=n,c=r.timeout?r.timeout*1e3:s.smartWaitingTimeout,l=Vc(c),u=0,d=Date.now(),p,g,m;try{await fr({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 W(l,n.abortSignal),h=Date.now();let f=!1;try{if(p=await fr({action:async()=>{let b=await IR(s,t,n.abortSignal);return g&&g.serializedTree===b.serializedTree&&g.screenshotBuff.equals(b.screenshotBuff)?(f=!0,p):(g=b,OR({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}),p?.success){p?.updatedMemory&&ls(r,p.updatedMemory,t);break}else throw p?.thoughts?new x("AssertionFailureError",p.thoughts):new x("InternalPlatformError","No thoughts were provided for AI assertion failure")}catch(E){n.abortSignal.throwIfAborted(),m=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(!p?.success)try{p=await fr({action:async()=>OR({command:r,state:await IR(s,t,n.abortSignal),fixtures:n,useMemory:i,useConsensus:!0,highlightElementsOnFailure:!0,attemptNumber:u,aiPageFiltering:e,logger:t}),frameConfig:r.iframeUrl?{type:"url",url:r.iframeUrl}:void 0,logger:t,browser:s})}catch(f){n.abortSignal.throwIfAborted(),m=f instanceof Error?f:new Error(`${f}`)}finally{u++}if(p?.updatedMemory&&ls(r,p.updatedMemory,t),!p?.success){let f=`AI check still failing after ${u} attempts.`;throw m&&(f+=` Latest result: ${m.message}`),new x("AssertionFailureError",f)}return{...p,succeedImmediately:!1,urlAfterCommand:s.url()}}async function IR(r,e,t){let[n,o]=await Promise.all([Kr(r,{abortSignal:t,skipWait:!0,skipWaitForPageLoad:!0,logger:e}),r.screenshot({retries:1,respectActiveFrame:!0})]);return{...n,screenshotBuff:o}}async function OR({command:r,state:e,fixtures:t,useConsensus:n,useMemory:o,highlightElementsOnFailure:i,aiPageFiltering:a,attemptNumber:s,source:c,logger:l}){let{browser:u,generator:d,abortSignal:p}=t,g={type:"ASSERTION"},{serializedTree:m,tree:h}=e,f=e.screenshotBuff,E=f.toString("base64"),b=u.url(),C=r.contextChoice??"MULTIMODAL",R=m;C!=="VISION_ONLY"&&(R=await xo({type:"assertion",serializedTree:m,tree:h,description:r.assertion,screenshot:E,options:{aiPageFiltering:a},fixtures:{generator:d,signal:p,logger:l,orgId:t.orgId}}),R!==m&&(g.ragUsed=!0),g.pageState=R);let v={goal:r.assertion,url:b,memory:o?r.cache?.memory:void 0,browserState:R,screenshot:E,contextChoice:C,source:c},A=await(C==="VISION_ONLY"?(I,k)=>d.getVisualAssertionResult(I,k):(I,k)=>d.getAssertionResult(I,k))(v,{useConsensus:n,attemptNumber:s,useMemory:o,disableCache:!!r.disableCache,abortSignal:p,logger:l,loggerTags:ye(l)});return(A.result||i)&&A.relevantElements&&(g.relevantElementsSerialized=A.relevantElements.map(I=>u.getSerializedFormFromA11yId(I)).filter(I=>!!I),await $z(A.relevantElements,u,l)),{success:A.result,thoughts:A.thoughts,afterScreenshotOverride:f,updatedMemory:o?A.updatedMemory:void 0}}async function $z(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 z(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 qz=75e4,hu=class extends Error{constructor(){super("The page content exceeds the maximum token limit for AI smart waiting."),this.name="ExceededMaxAISmartWaitingTokensError"}};async function LR(r,e){let{logger:t}=r,{abortSignal:n,browser:o}=e,i=Date.now();try{await Kz(i,r,e)}catch(a){if(a instanceof Error&&(a.name==="AbortError"||a.name==="TimeoutError")||n.aborted)return;a instanceof hu?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 W(s,n)}finally{t.debug({durationMs:Date.now()-i},"AI smart waiting complete")}}async function Kz(r,e,t){let{abortSignal:n,browser:o}=t;if(o.smartWaitingTimeout<3e3){await W(o.smartWaitingTimeout,n);return}if(!e.description)throw new x("UserConfigurationError","Cannot locate element with empty description");await z(Yz(r,e,t),{milliseconds:o.smartWaitingTimeout})}async function Yz(r,e,t){let{logger:n,iframeUrl:o}=e,{browser:i}=t;for(;Date.now()-r<i.smartWaitingTimeout;)if(await fr({action:async()=>Xz(e,t),frameConfig:o?{type:"url",url:o}:void 0,browser:i,logger:n}))return}async function Xz(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 ds({orgId:l,s:d,context:t,localTools:c,signal:s,logger:n}));let{serializedTree:p}=await Kr(a,{allowNotActionableNodesOverride:i,filterByViewport:o,abortSignal:s,logger:n});if(Rr(p)>qz)throw new hu;s.throwIfAborted();let m;try{m=await a.screenshot({clearHighlights:!0,respectActiveFrame:!0,retries:2})}catch(b){throw new x("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,${m.toString("base64")}`;s.throwIfAborted();let E=await u.getSmartWaitingDecision({browserState:p,description:d,screenshot:f},{abortSignal:s,loggerTags:ye(n)});return n.debug({result:E},"Got smart waiting result"),E.isPageReady}import{cloneDeep as DR}from"lodash-es";async function kR(r){let{command:e,timeoutMs:t,fixtures:n}=r,{abortSignal:o}=n,i=()=>Zh(e.cache)?e.cache:void 0,a=i(),s=DR(a),c=(h=!1)=>{if(a=i(),!!a)if(h){let f=YA(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,p=500,g=!1;for(;u<2||Date.now()-l<t;){u++,u>1&&await W(p,o),o?.throwIfAborted(),a=i();let{result:h,elementWasFound:f}=await NR({cacheToUse:a,params:r});if(d=h,g=f,h.success)break;c(),p=Math.min(p*2,1e4)}if(!d)throw new x("InternalPlatformError",`Failed to evaluate manual element assertion in ${t}ms.`);if(o?.throwIfAborted(),!d.success&&a?.target&&Bs(a.target)){let h=a?.target?.memory?{target:{id:-1,memory:a.target.memory}}:void 0,{result:f}=await NR({cacheToUse:h,params:r});d=f,d.success||c(!0)}let m=i();return d.success&&m?.target&&!g&&(m.target=Jm(m.target),m.updatedAt=new Date),d}async function NR({cacheToUse:r,params:e}){let{command:t,disableCache:n,fixtures:o,tracer:i,targetingWrapper:a}=e,{logger:s}=o;if(t.target&&!fn(t.target))throw new Error("Element assertion with x/y is not supported yet");let c=Fc(t.assertion),l,u=!1,d=DR(r);try{let{elementInteractedDisplayString:p,result:g,thoughts:m}=await a({ctx:o.ctx,tracer:i,command:t,target:t.target,cache:d?.target,action:async h=>Jz(h.locator,e),options:{...t,allowNotActionableNodesOverride:!0,disableCache:n,memory:d?.target?.memory,disableGlobalLocatorRedirect:!0,source:ga(t),targetName:"target"}});return l={success:g.success,data:g.data,err:g.err,elementInteractedDisplayString:p,thoughts:m},u=!0,g.success||(s.warn({aiThoughts:m,elementString:p,err:g.err},"Element check found an element but failed"),l={...g,thoughts:m}),{result:l,elementWasFound:u}}catch(p){if(c)return l={success:!0,thoughts:`The element described does not exist on the page: ${p.message}`,err:void 0,data:void 0},{result:l,elementWasFound:u};if(!(p instanceof x)||p.reason!="ActionFailureError")throw p;return l={success:!1,err:p,data:void 0,thoughts:void 0},s.warn({err:p},"Element check did not find an element and failed"),{result:l,elementWasFound:u}}}async function Jz(r,{command:e,fixtures:t}){return await t.browser.highlight(r),await Qz(r,e.assertion)}async function Qz(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)},!Vr(a,e.value,e.operation,{negated:!!e.negated,ignoreCase:!1})){let s=mr(e);t=!1,n=new x("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 x("AssertionFailureError",`The element does not have an attribute named ${e.attr}: ${s}`),t=!1;break}if(!Vr(a,e.value,e.operation,{negated:!!e.negated,ignoreCase:!1})){let s=mr(e);t=!1,e.operation==="EXISTS"?n=new x("AssertionFailureError",`The attribute ${e.attr} ${s}`):n=new x("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},Lt*1e3);break}case"EDITABLE":{t=await r.isEditable({timeout:Lt*1e3});break}case"EXISTS":{t=!0;break}case"ENABLED":{t=await r.isEnabled({timeout:Lt*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=mr(e);n=new x("AssertionFailureError",`The element ${a}`)}break}case"ELEMENT_NAME":{let a=await r.evaluate(s=>s.tagName);if(!Vr(a,e.value,e.operation,{negated:!!e.negated,ignoreCase:!0})){let s=mr(e);t=!1,n=new x("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(!Vr(a,e.value,e.operation,{negated:!!e.negated,ignoreCase:!1})){let s=mr(e);t=!1,e.operation==="EXISTS"?n=new x("AssertionFailureError",`The style property ${e.property} ${s}`):n=new x("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 UR(r){return r.type==="ELEMENT_EXISTENCE"&&r.negated&&r.condition==="EXISTS"}import{Jimp as Zz}from"jimp";async function fs(r,e){let t=await r.screenshot(e),n=await Zz.fromBuffer(t);return{buffer:t,width:Math.ceil(n.bitmap.width??0),height:Math.ceil(n.bitmap.height??0)}}import{Jimp as FR}from"jimp";import $g from"jpeg-js";import e1 from"pixelmatch";async function BR({ctx:r,tracer:e,command:t,disableCache:n,browser:o,targetingWrapper:i,logger:a,screenshotStorage:s}){if(t.target&&!fn(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 ge=>fs(o,{locator:ge.locator,...c}),options:{...t,disableCache:n,disableGlobalLocatorRedirect:!0,memory:t.cache?.target?.memory,targetName:"target"}})).result:l=await fs(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 G=`${l.width}x${l.height}`,ge=`${u.width}x${u.height}`;return{fail:!0,thoughts:`Current screenshot (${G}) does not match saved screenshot dimensions (${ge}) - 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 FR.fromBuffer(l.buffer),p={width:l.width,height:l.height},g=await FR.fromBuffer(u.buffer),m={width:u.width,height:u.height},h,f=p.width*p.height,E=m.width*m.height,b=Math.abs(p.height-m.height),C=Math.abs(p.width-m.width);if(f>E){let G=d.cover({w:m.width,h:m.height});l.buffer=await G.getBuffer("image/jpeg"),h="current",l.width=m.width,l.height=m.height}else if(E>f){let G=g.cover({w:p.width,h:p.height});u.buffer=await G.getBuffer("image/jpeg"),h="saved"}let R={data:Buffer.alloc(l.width*l.height*4),width:l.width,height:l.height},v=t.threshold??.1,A=e1($g.decode(u.buffer).data,$g.decode(l.buffer).data,R.data,l.width,l.height,{threshold:v,diffColorAlt:[0,255,0]})/(l.width*l.height)*100,I=A>v*100,k=`Visual diff of ${A.toFixed(2)}% detected, which is ${I?"over":"under"} the threshold of ${v*100}%.`;if(h&&(k+=` The ${h} screenshot was cropped since it was taller by ${b} pixels and wider by ${C} pixels.`),I)throw new x("ActionFailureError",k);return{fail:I,thoughts:k,beforeScreenshotOverride:l.buffer,afterScreenshotOverride:$g.encode(R,75).data,succeedImmediately:!1,urlAfterCommand:o.url()}}var t1=3e4;function r1(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 fu({command:r,logger:e,baseUrl:t,fetchImplementation:n=fetch}){let o=r.timeout??t1/1e3,i=Object.fromEntries(Object.entries(r.headers||{}).filter(([m,h])=>m&&h)),a=new URLSearchParams;Object.entries(r.params||{}).filter(([m,h])=>m&&h).forEach(([m,h])=>{a.append(m,h)});let s=a.toString(),c;if(Mi(r.url)&&(c=r.url),t&&_i(r.url,t)&&(c=new URL(r.url,t).toString()),!c)throw new x("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 z((async()=>{let m=s?`${l}?${s}`:l;try{let h=r1(r),f=new Headers(i);return h.contentType&&!f.has("Content-Type")&&f.set("Content-Type",h.contentType),await n(m,{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 x("ActionFailureError",`Fetch request timed out after ${o} seconds`)}});if(!d.ok){let m;try{m=await d.text()}catch(h){m=`Failed to read response body: ${h}`}throw new x("ActionFailureError",`Fetch request failed with status ${d.status}: ${m}`)}let p={};d.headers.forEach((m,h)=>{p[h]=m});let g={status:d.status,headers:p,request:{url:d.url,method:r.method,headers:i}};if(r.body?.type==="json"&&r.body.content)try{g.request.json=JSON.parse(r.body.content)}catch{}if(d.headers.get("content-type")?.includes("json"))try{g.json=await d.json()}catch{}else d.headers.get("content-type")?.includes("text")&&(g.text=await d.text());return g}var n1=5e3;async function HR({timeout:r=Lt,...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 Su(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 W(s,e.signal),s=Math.min(Math.floor(s*1.5),n1);else return i}return i=await Su(e),i}async function Su({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(zR,{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(zR,{value:r.value,negated:!!r.negated,returnHtml:!0},"checking page content"));if(!i){let c=r.negated?sn.CONTAINS:ln.CONTAINS;a=new x("AssertionFailureError",`The page ${c} '${r.value}'.`),o=s}}catch(s){a=new x("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 zR({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 o1=3e4;async function GR({command:r,logger:e,baseUrl:t,fetchImplementation:n=fetch}){let o=r.timeout??o1/1e3,i=new AbortController,a=Object.fromEntries(Object.entries(r.headers||{}).filter(([d,p])=>d&&p));a["Content-Type"]="application/json";let s;if(Mi(r.url)&&(s=r.url),t&&_i(r.url,t)&&(s=new URL(r.url,t).toString()),!s)throw new x("ActionFailureError",`Invalid URL: ${r.url}`);let l=await z((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 x("ActionFailureError",`GraphQL request timed out after ${o} seconds`);if(!l.ok){let d,p=await l.text();try{d=JSON.parse(p)}catch{throw new x("ActionFailureError",`GraphQL request failed with status ${l.status}: ${p}`)}throw d?.errors?.length&&d?.errors[0]?.message?new x("ActionFailureError",`GraphQL request failed with status ${l.status}: ${d.errors[0].message}`):new x("ActionFailureError",`GraphQL request failed with status ${l.status}: ${p}`)}let u={};return l.headers.forEach((d,p)=>{u[p]=d}),{status:l.status,headers:u,json:await l.json()}}var yu=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([Kr(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 xo({type:"ai-action",description:e,screenshot:u,serializedTree:c.serializedTree,tree:c.tree,options:{aiPageFiltering:!!this.options?.aiPageFiltering},fixtures:{generator:this.generator,signal:this.executeAbortController.signal,logger:s,orgId:this.orgId}}),p={url:this.browser.url(),browserState:d,startingScreenshot:t,history:n,goal:e,screenshot:u,lastError:a};return await this.generator.getMultiturnAiActionEvaluation(p,{disableCache:o,abortSignal:this.executeAbortController.signal,loggerTags:{...ye(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([Kr(this.browser,{abortSignal:this.executeAbortController.signal,skipWait:!0,skipWaitForPageLoad:!0,logger:a}),this.browser.screenshot({retries:1,clearHighlights:!0})]),d=`data:image/jpeg;base64,${u.toString("base64")}`,p=await xo({type:"ai-action",description:e,screenshot:d,serializedTree:l.serializedTree,tree:l.tree,options:{aiPageFiltering:!!this.options?.aiPageFiltering},fixtures:{generator:this.generator,signal:this.executeAbortController.signal,logger:a,orgId:this.orgId}}),g={url:c,browserState:p,startingScreenshot:t,history:n,goal:e,actionHint:o,screenshot:d};try{return await this.generator.getMultiturnAiActionCommand(g,{disableCache:i,abortSignal:this.executeAbortController.signal,loggerTags:{...ye(a)},langfuseSessionId:s})}catch(m){throw new x("InternalWebAgentError",`Error generating command: ${m instanceof Error?m.message:m}`,{errOptions:{cause:m}})}}async getBrowserState(e){return Kr(this.browser,e)}async locateElement(e){return await jg({...e,aiPageFiltering:!!this.options?.aiPageFiltering},this.getControllerFixtures())}async locateElementWithSelector(e,t){return fr({action:async()=>{let n=await this.browser.resolveHardcodedCssSelector({ctx:null,selector:e,timeoutMs:2e3,logger:this.logger});return{thoughts:"Located element with selector",target:{id:-1,selector:e,targetSource:"USER_CSS_SELECTOR",targetUpdateTime:new Date().toUTCString()},resolution:n}},frameConfig:t?{type:"url",url:t}:void 0,browser:this.browser,logger:this.logger})}getControllerFixtures(e){return{ctx:e??null,browser:this.browser,generator:this.generator,logger:this.logger,orgId:this.orgId,storage:this.storage,localCodeEvalTools:this.localCodeEvalTools,abortSignal:this.executeAbortController.signal}}shouldUseMemory(){return this.options?.useMemory??(this.orgId==="org_01HMSCJQBCCG51M2ZF65YC5B8W"||this.orgId==="org_01HMJTX4GT1KG94KZRCT8MZ6YB")}async wrapMultiElementTargetingCommand({ctx:e,tracer:t,command:n,targetNames:o,descriptions:i,caches:a,action:s,options:c,retriesWithAI:l=1}){let u=[];for(let d=0;d<i.length;d++){let p=i[d],g=await this.wrapElementTargetingCommand({ctx:e,tracer:t,command:n,target:p,cache:a[d],action:async m=>m,options:{...c,targetName:o[d]}});u.push(g)}try{let d=await s(...u.map(m=>m.result)),p=m=>m==="fromTarget"?"From Target":m==="toTarget"?"To Target":"Target",g=u.map((m,h)=>m.thoughts?`${p(o[h])}: ${m.thoughts}`:void 0).filter(m=>!!m).join(" -------------- ")||void 0;return{result:d,elementInteractedDisplayStrings:u.map(m=>m.elementInteractedDisplayString),thoughts:g}}catch(d){if(this.throwIfClosed(),l>0)return this.logger.warn({err:d},"Failed to execute action with multiple cached targets, retrying with AI"),this.wrapMultiElementTargetingCommand({ctx:e,tracer:t,command:n,targetNames:o,descriptions:i,caches:i.map(()=>{}),action:s,options:c,retriesWithAI:l-1});throw new x("ActionFailureError",d.message,{errOptions:{cause:d}})}}async wrapElementTargetingCommand(e){let t=this.logger.child({commandId:e.command.id}),n;for(let o=0;o<2;o++)try{return await fr({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&&Cd(i)){t.warn({err:i},"Invalid mpath error, retrying element targeting command");continue}if(!this.browser.userBrowserSettings.visualActions&&(Md(i)||Rd(i))){t.warn({err:i},"Invalid momentic id error, retrying element targeting command");continue}if(_d(i)){t.warn({err:i},"Invalid backend node id error, retrying element targeting command");continue}if(i instanceof Lr&&i.retryableWithAI){t.warn({err:i},"Element cache disqualification error, retrying element targeting command");continue}throw i}throw n instanceof x?n:new x("ActionFailureError",n?.message??"An unknown error occurred during element targeting")}async wrapHardcodedCssTargetingCommandHelper({ctx:e,target:t,action:n,options:o,command:i}){let a=this.logger.child({commandId:i.id}),{targetName:s}=o;if(t.type!=="description")throw new x("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 W(500)}}throw c}async wrapElementTargetingCommandHelper(e){let{ctx:t,tracer:n,target:o,originalCache:i,action:a,options:s,command:c}=e,{disableCache:l,useSelector:u,targetName:d,targetHealingInProgress:p,source:g}=s,m=this.logger.child({commandId:c.id}),h=this.shouldUseMemory(),f=s.retriesWithAI??1,E=!1,b=VR(e.cache);if((!b||l)&&!cd(o))throw new x("ActionFailureError","Cannot target element with no cached data or element descriptor");if(u)return this.wrapHardcodedCssTargetingCommandHelper(e);l&&(m.info("Cache explicitly disabled for this step"),E=!0,b=void 0),b&&this.browser.userBrowserSettings.disableSecondaryCacheResolution&&b.targetSource==="HEURISTIC_HEALED"&&(E=!0,b=void 0),b?.inputDescription&&!PR(o.elementDescriptor,b.inputDescription)&&(m.warn({old:b.inputDescription,new:o.elementDescriptor},"Target cache was generated with a different description, clearing it automatically"),E=!0,b=void 0);let C=v=>!!v&&Bs(v),R=!0;if(!C(b)){R=!1,m.info({description:o.elementDescriptor,targetHealingInProgress:p,cacheBustedBeforeAction:E,memory:s.memory,useMemory:h},"Prompting AI for an updated element location"),(E||!i)&&await LR({description:o.elementDescriptor,iframeUrl:s.iframeUrl,source:g,logger:m,allowNotActionableNodesOverride:s.allowNotActionableNodesOverride},this.getControllerFixtures(t)),f--;let v;try{v=await jg({description:o.elementDescriptor,disableCache:!!s.disableCache,iframeUrl:s.iframeUrl,source:g,useMemory:h,memory:h?s.memory:void 0,aiPageFiltering:!!this.options?.aiPageFiltering,allowNotActionableNodesOverride:s.allowNotActionableNodesOverride,logger:m},this.getControllerFixtures(t))}catch(I){if(I instanceof bn&&I.updatedLocatorMemory){let k={id:-1,...i,memory:I.updatedLocatorMemory};Bc({cmd:c,key:d,newTarget:k,logger:m,updatedWithAI:!0})}throw new x("ActionFailureError",I.message)}v.frameConfig&&this.browser.setActiveFrameConfig(v.frameConfig);let M=s.disableGlobalLocatorRedirect?{locator:v.resolution.locator}:await this.attemptLocatorRedirect(v.resolution.locator,m),A=await a(M);return Bc({cmd:c,key:d,newTarget:v.target,logger:m,updatedWithAI:!0}),p&&(n.recordTargetAutoHeal({healType:"AI"}),v.target.targetSource="AI_HEALED",v.target.targetUpdateTime=new Date().toUTCString(),v.target.targetUpdateLoggerTags=ye(m)),{result:A,elementInteractedDisplayString:v.resolution.displayString,thoughts:v.thoughts}}try{let v=await this.browser.resolveTarget(t,b,{allowNotActionableNodesOverride:s.allowNotActionableNodesOverride,targetName:d,logger:m,signal:this.executeAbortController.signal});(this.browser.userBrowserSettings.visualActions||this.browser.userBrowserSettings.globalLocatorRedirect!==!1)&&await this.browser.scrollIntoViewIfNeeded(v.locator);let M=s.disableGlobalLocatorRedirect?{locator:v.locator}:await this.attemptLocatorRedirect(v.locator,m),A=await a(M);if(Tt.increment("cache_target_resolution_v2",1,["outcome:hit","platform:web",`hasRequirements:${!!b.requirements}`,`hasAdditionalElements:${!!b.additionalElements}`,`orgId:${this.orgId}`,"cliVersion:0.12.0"]),Bc({cmd:c,key:d,newTarget:b,logger:m,updatedWithAI:!1}),R){let I=v.decisions.filter(k=>k.matched);if(I.length!==1)m.warn({decisions:v.decisions},"Expected exactly 1 matching method for element location, got more or less");else{let k=I[0].type;n.recordTargetAutoHeal({healType:k})}}return{result:A,elementInteractedDisplayString:v.displayString}}catch(v){this.throwIfClosed();let M="unknown";v instanceof Or&&v.cacheMissReason&&(M=v.cacheMissReason),Tt.increment("cache_target_resolution_v2",1,["outcome:miss","platform:web",`hasRequirements:${!!b.requirements}`,`hasAdditionalElements:${!!b.additionalElements}`,`orgId:${this.orgId}`,"cliVersion:0.12.0",`missReason:${M}`]);let A=!1;if((v instanceof Lr||Cd(v)||Md(v)||_d(v)||aS(v)||Rd(v)||sS(v))&&(A=!0),v instanceof x&&!A)throw m.error({err:v},"Failed to execute action with cached target (fatal)"),v;if(f>0&&o){m.info({err:v},"Failed to execute action with cached target, retrying with AI");let I;return b.memory&&Kh(b.memory)&&(I=b.memory),this.wrapElementTargetingCommand({ctx:t,tracer:n,command:c,target:o,cache:void 0,originalCache:i,action:a,options:{...s,memory:I,retriesWithAI:f,targetHealingInProgress:!0}})}throw new x("ActionFailureError",v.message,{errOptions:{cause:v}})}}async attemptLocatorRedirect(e,t){return this.browser.userBrowserSettings.globalLocatorRedirect!==!1?this.browser.performTargetRedirection(e,t):{locator:e}}async screenshotWithDimensions(e){return fs(this.browser,e)}async executePresetCommand(e,t,n,o,i){this.options?.slowMoMs&&await W(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 x("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&&Cf(n)?await this.browser.waitForDOMStability({timeout:Ee}):!this.browser.userBrowserSettings.visualActions&&["PRESS","TYPE"].includes(n.type)&&await this.browser.waitForDOMStability({timeout:re}),this.options?.autoFollowNewTabs&&await TR({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{Jc(n,c)}}createCallbacksForBrowser(e){return{createIsolatedFolder:()=>fg(e)}}async resolveCommandTemplateStrings(e,t){return Xc({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()?gu({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 x("ActionFailureError","Missing assertion");if(n.timeout&&n.timeout>1800)throw new x("AssertionFailureError",`AI check timeout of ${n.timeout} exceeds the maximum allowed value of 30 minutes.`);return gu({command:n,fixtures:this.getControllerFixtures(e),useMemory:this.shouldUseMemory(),aiPageFiltering:!!this.options?.aiPageFiltering,logger:a})}case"AI_EXTRACT":{if(!n.goal.trim())throw new x("ActionFailureError","Cannot perform AI extraction without goal");if(n.schema){let f=SE(n.schema);if(f)throw new x("UserConfigurationError",f)}let m=await this.browser.getCondensedHtml(),h=await this.browser.screenshot({retries:2});try{let f=await this.generator.getTextExtraction({goal:n.goal,browserState:m,returnSchema:n.schema,screenshot:`data:image/jpeg;base64,${h.toString("base64")}`},{disableCache:i,abortSignal:this.executeAbortController.signal,loggerTags:ye(a)});if(f.result==="NOT_FOUND")throw new x("ActionFailureError","No relevant data found for extraction goal on this page");if(f.thoughts?.includes("MaxGenerationLengthExceededError"))throw new x("UserConfigurationError",f.thoughts);return{thoughts:f.thoughts||void 0,data:f.result,succeedImmediately:!1,urlAfterCommand:this.browser.url()}}catch(f){let E=f.message;throw E.includes("MaxGenerationLengthExceededError")?new x("UserConfigurationError","You tried to extract too much data. Please rephrase your query to limit the results returned or use a JavaScript step in the browser instead."):E.includes("AIProviderError")&&E.includes("time")?new x("AIProviderError","The AI provider responded with an error. This may be because you tried to extract too much data. Please limit extraction results to 2000 characters.",{errOptions:{cause:f}}):f}}case"NAVIGATE":if(!Mi(n.url)&&!_i(n.url,this.browser.baseUrl))throw new x("ActionFailureError",`Invalid URL provided to navigate command: ${n.url}`);await this.browser.navigate({url:n.url,loadTimeoutMs:n.loadTimeout?n.loadTimeout*1e3:void 0});break;case"DIALOG":this.browser.registerDialogHandler(n.action);break;case"CAPTCHA":if(!this.browser.canSolveCaptchas())break;let c=await this.browser.solveCaptcha();c&&(await this.wrapElementTargetingCommand({ctx:e,tracer:t,command:n,target:{type:"description",elementDescriptor:"the captcha image solution input"},cache:void 0,action:m=>this.browser.click(m,this.createCallbacksForBrowser(this.orgId),{}),options:{...n,targetName:"target",disableCache:i}}),await this.browser.type(c,{clearContent:!0,pressEnter:!0},!0));break;case"GO_BACK":await this.browser.goBack();break;case"GO_FORWARD":await this.browser.goForward();break;case"SCROLL_LEFT":case"SCROLL_RIGHT":case"SCROLL_DOWN":case"SCROLL_UP":{let m,h;if(n.target&&_r(n.target))await this.browser.hoverUsingVisualCoordinates(n.target.pixels);else if(n.target&&n.target.elementDescriptor.trim()){let{elementInteractedDisplayString:b,thoughts:C}=await this.wrapElementTargetingCommand({ctx:e,tracer:t,command:n,target:n.target,cache:n.cache?.target,action:R=>this.browser.hover(R),options:{...n,targetName:"target",disableGlobalLocatorRedirect:!0,disableCache:i}});m=b,h=C}let f=this.browser.getViewport()?.height??wn.height,E=this.browser.getViewport()?.width??wn.width;switch(n.type){case"SCROLL_UP":await this.browser.scrollVertical(-(n.deltaY??f));break;case"SCROLL_DOWN":await this.browser.scrollVertical(n.deltaY??f);break;case"SCROLL_LEFT":await this.browser.scrollHorizontal(-(n.deltaX??E));break;case"SCROLL_RIGHT":await this.browser.scrollHorizontal(n.deltaX??E);break}return{succeedImmediately:!1,urlAfterCommand:this.browser.url(),elementInteracted:m,thoughts:h}}case"WAIT_FOR_URL":{if(n.timeout&&n.timeout>1800)throw new x("UserConfigurationError",`Wait for URL timeout of ${n.timeout} exceeds the maximum allowed value of 30 minutes.`);let m=n.matcher;await this.browser.waitForUrl({beforeUrl:this.browser.url(),matcher:m},{timeout:n.timeout?n.timeout*1e3:void 0,negated:n.negated,caseInsensitive:n.caseInsensitive});break}case"WAIT":if(n.delay>1800)throw new x("UserConfigurationError",`Wait timeout of ${n.delay} seconds exceeds the maximum allowed value of 30 minutes`);let l=n.delay*1e3;await W(l,this.executeAbortController.signal);break;case"REFRESH":await this.browser.refresh({loadTimeoutMs:n.loadTimeout?n.loadTimeout*1e3:void 0});break;case"CLICK":{if(_r(n.target)){await this.browser.clickUsingVisualCoordinates(n.target.pixels,n);break}let m=this.browser.url(),{elementInteractedDisplayString:h,result:f,thoughts:E}=await this.wrapElementTargetingCommand({ctx:e,tracer:t,target:n.target,command:n,cache:n.cache?.target,action:C=>this.browser.click(C,this.createCallbacksForBrowser(this.orgId),n),options:{disableCache:i,targetName:"target",...n}}),b={urlAfterCommand:this.browser.url(),succeedImmediately:!1,elementInteracted:h,thoughts:E,data:f.downloadedFile?{downloadedFile:f.downloadedFile}:void 0};return jc(m,b.urlAfterCommand)&&(b.succeedImmediately=!0,b.succeedImmediatelyReason="URL changed"),b}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(_r(n.fromTarget)&&_r(n.toTarget)){await this.browser.dragAndDropUsingVisualCoordinates(n.fromTarget.pixels,n.toTarget.pixels,{hoverSeconds:n.hoverSeconds});break}if(_r(n.fromTarget)||_r(n.toTarget))throw new Error("Drag and drop targets must be both coordinates or both descriptions");let{elementInteractedDisplayStrings:m,thoughts:h}=await this.wrapMultiElementTargetingCommand({ctx:e,tracer:t,command:n,targetNames:["fromTarget","toTarget"],descriptions:[n.fromTarget,n.toTarget],caches:[n.cache?.fromTarget,n.cache?.toTarget],action:(f,E)=>this.browser.dragAndDrop(f.locator,E.locator,{hoverSeconds:n.hoverSeconds,steps:n.steps}),options:{useSelector:!!n.useSelector,disableCache:i}});return{succeedImmediately:!1,urlAfterCommand:this.browser.url(),elementInteracted:m[0],thoughts:h}}case"MOUSE_DRAG":{let m=parseInt(n.deltaX),h=parseInt(n.deltaY),f=n.steps??5;if(isNaN(m)||isNaN(h))throw new x("ActionFailureError",`Invalid pixel values passed to mouse drag command: (${n.deltaX}, ${n.deltaY})`);if(n.target&&_r(n.target)){await this.browser.mouseDragUsingVisualCoordinates(m,h,f,void 0,n.target.pixels);break}let E,b;if(n.target?.elementDescriptor){let{elementInteractedDisplayString:C,thoughts:R}=await this.wrapElementTargetingCommand({ctx:e,tracer:t,command:n,target:n.target,cache:n.cache?.target,action:async v=>this.browser.mouseDrag(m,h,f,v.locator,{force:n.force}),options:{disableCache:i,targetName:"target",...n}});E=C,b=R}else await this.browser.mouseDrag(m,h,f,void 0,{force:n.force});return{succeedImmediately:!1,urlAfterCommand:this.browser.url(),elementInteracted:E,thoughts:b}}case"SELECT_OPTION":{if(!fn(n.target))throw new Error("Select with x/y is not supported yet");let m=n.target.elementDescriptor,h=n.choice,{elementInteractedDisplayString:f,thoughts:E}=await this.wrapElementTargetingCommand({ctx:e,tracer:t,command:n,target:{type:"description",elementDescriptor:m},cache:n.cache?.target,action:b=>this.browser.selectOption(b,h,n.force),options:{...n,targetName:"target",disableCache:i,source:ga(n)}});return{succeedImmediately:!1,urlAfterCommand:this.browser.url(),elementInteracted:f,thoughts:E}}case"TAB":{let m={loadTimeoutMs:n.loadTimeout?n.loadTimeout*1e3:void 0,retry:!0};await this.browser.switchToPage(n.action,m);break}case"NEW_TAB":await this.browser.createNewTab(n.url,{loadTimeoutMs:n.loadTimeout?n.loadTimeout*1e3:void 0});break;case"COOKIE":if(!n.value)break;let u=await this.browser.setCookie(n.value);a.debug({results:u},"Set cookies");break;case"LOCAL_STORAGE":if(!n.value||!n.key)break;await this.browser.setLocalStorage(n.key,n.value);break;case"JAVASCRIPT":{let m;try{n.environment==="BROWSER"?(m=await this.browser.evaluateCodeInPage({code:n.code,fragment:n.fragment??!1,context:o.toObjectCopy(),timeoutMs:n.timeout?n.timeout*1e3:void 0}),a.info({result:m},"Executed JavaScript in browser")):m=await Wr({orgId:this.orgId,code:n.code,fragment:!!n.fragment,context:o,timeoutMs:n.timeout?n.timeout*1e3:void 0,logger:a,localTools:this.localCodeEvalTools,signal:this.executeAbortController.signal,callbacks:{onPersistentVariableUpdates:async h=>{if(!this.options?.scratchPadId){a.warn({updates:h},"Got persistent variable updates but scratch pad is not available");return}await this.storage.savePersistentVariables?.({scratchPadId:this.options?.scratchPadId,orgId:this.orgId,updates:h,logger:a})}}})}catch(h){throw this.throwIfClosed(),new x("ActionFailureError",h instanceof Error?h.message:`${h}`,{errOptions:{cause:h}})}try{JSON.stringify(m)}catch(h){throw new x("ActionFailureError",`Return value is not serializable: ${h instanceof Error?h.message:`${h}`}`,{errOptions:{cause:h}})}return{urlAfterCommand:this.browser.url(),succeedImmediately:!1,data:m}}case"TYPE":{if(n.target&&_r(n.target)){await this.browser.clickUsingVisualCoordinates(n.target.pixels,n),await this.browser.type(n.value,{force:n.force,clearContent:n.clearContent,forceClearContent:n.forceClearContent,delay:n.delay,pressEnter:n.pressEnter},!0);break}let m=this.browser.url(),h,f,E=VR(n.target),b=this.browser.userBrowserSettings.globalLocatorRedirect===void 0||this.browser.userBrowserSettings.globalLocatorRedirect==="always";if(E){let{elementInteractedDisplayString:R,thoughts:v}=await this.wrapElementTargetingCommand({ctx:e,tracer:t,command:n,target:E,cache:n.cache?.target,action:M=>this.browser.typeIntoTarget(n.value,M,{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:!b,source:ga(n)}});h=R,f=v}else await this.browser.type(n.value,{force:n.force,clearContent:n.clearContent,forceClearContent:n.forceClearContent,delay:n.delay,pressEnter:n.pressEnter},!0);let C={urlAfterCommand:this.browser.url(),succeedImmediately:!1,elementInteracted:h,thoughts:f};return jc(m,C.urlAfterCommand)&&(C.succeedImmediately=!0,C.succeedImmediatelyReason="URL changed"),C}case"HOVER":{if(_r(n.target)){await this.browser.hoverUsingVisualCoordinates(n.target.pixels);break}let{elementInteractedDisplayString:m,thoughts:h}=await this.wrapElementTargetingCommand({ctx:e,tracer:t,command:n,target:n.target,cache:n.cache?.target,action:f=>this.browser.hover(f),options:{...n,targetName:"target",disableCache:i}});return{succeedImmediately:!1,urlAfterCommand:this.browser.url(),elementInteracted:m,thoughts:h}}case"FOCUS":{if(!fn(n.target))throw new Error("Focus with x/y is not supported yet");let{elementInteractedDisplayString:m,thoughts:h}=await this.wrapElementTargetingCommand({ctx:e,tracer:t,command:n,target:n.target,cache:n.cache?.target,action:f=>this.browser.focus(f),options:{...n,targetName:"target",disableCache:i}});return{succeedImmediately:!1,urlAfterCommand:this.browser.url(),elementInteracted:m,thoughts:h}}case"BLUR":{if(n.target&&!fn(n.target))throw new Error("Blur with x/y is not supported yet");if(!n.target||!n.target.elementDescriptor)return await this.browser.blur(null),{succeedImmediately:!1,urlAfterCommand:this.browser.url()};let{elementInteractedDisplayString:m,thoughts:h}=await this.wrapElementTargetingCommand({ctx:e,tracer:t,target:n.target,command:n,cache:n.cache?.target,action:f=>this.browser.blur(f),options:{...n,targetName:"target",disableCache:i}});return{succeedImmediately:!1,urlAfterCommand:this.browser.url(),elementInteracted:m,thoughts:h}}case"PRESS":let d=this.browser.url();await this.browser.press(n.value,{repeat:n.repeat,convertMeta:n.convertMeta??!0,delayMs:n.delayMs});let p={urlAfterCommand:this.browser.url(),succeedImmediately:!1};return jc(d,p.urlAfterCommand)&&(p.succeedImmediately=!0,p.succeedImmediatelyReason="URL changed"),p;case"KEY_DOWN":return await this.browser.keyDown(n.value,{convertMeta:n.convertMeta??!0}),{urlAfterCommand:this.browser.url(),succeedImmediately:!1};case"KEY_UP":return await this.browser.keyUp(n.value,{convertMeta:n.convertMeta??!0}),{urlAfterCommand:this.browser.url(),succeedImmediately:!1};case"REQUEST":{let m=new a1,h=i1(fetch,m),f;try{f=new URL(n.url).hostname}catch{}let E=await fu({command:n,baseUrl:this.browser.baseUrl,logger:a,fetchImplementation:h});return{data:Ws.parse({...E,cookies:Sl(m,f)}),succeedImmediately:!1,urlAfterCommand:this.browser.url()}}case"GRAPHQL_REQUEST":return{data:await GR({command:n,baseUrl:this.browser.baseUrl,logger:a}),succeedImmediately:!1,urlAfterCommand:this.browser.url()};case"VISUAL_DIFF":return BR({ctx:e,tracer:t,command:n,disableCache:i,browser:this.browser,logger:a,storage:this.storage,screenshotStorage:this.visualDiffScreenshotStorage,targetingWrapper:m=>this.wrapElementTargetingCommand(m)});case"FILE_UPLOAD":{let m,h;if(n.fileSource.type==="URL"?(h=n.fileSource.url,m=await uC({uri:n.fileSource.url,logger:a,orgId:this.orgId})):n.fileSource.type==="USER_FILE"&&(h=n.fileSource.name,m=await this.uploadedFileStorage?.getFileForUpload(n.fileSource.name,this.orgId)),!m)throw new x("UserConfigurationError",`Attempted to use non-existent file for upload step: ${h}`);await this.browser.setFileChooserHandler({...m,filename:n.filename});break}case"AUTH_SAVE":return{data:await this.browser.saveAuthState(),succeedImmediately:!1,urlAfterCommand:this.browser.url()};case"AUTH_LOAD":{let m;if(!n.storageState.trim())m=void 0;else if(m=await Wr({orgId:this.orgId,code:n.storageState,fragment:!1,context:o,logger:a,localTools:this.localCodeEvalTools,signal:this.executeAbortController.signal}),typeof m!="object")throw new x("ActionFailureError",`Credentials must evaluate to an object (received ${typeof m} instead)`);let h;try{h=Iy.optional().parse(m)}catch(f){throw new x("ActionFailureError",`Credentials provided do not follow the required format: ${f}`)}await this.browser.loadAuthState(h);break}case"ELEMENT_CHECK":{let m=(n.timeout??Lt)*1e3,h=this.generator.getAgentConfig()?.assertion;if(UR(n.assertion)&&!n.useSelector&&n.target.type==="description"&&h&&h!=="v1"){let E={id:n.id,type:"AI_ASSERTION",assertion:`There is no element on the page closely matches the following description. If the description has single quotes, remember that requires an exact text substring match. Description: ${n.target.elementDescriptor}`,iframeUrl:n.iframeUrl,timeout:n.timeout,cache:n.cache&&"memory"in n.cache?{memory:n.cache?.memory}:void 0};try{let b=await gu({command:E,logger:a,aiPageFiltering:!!this.options?.aiPageFiltering,fixtures:this.getControllerFixtures(e),useMemory:this.shouldUseMemory(),source:"NEGATED_CHECK"});return{succeedImmediately:!1,thoughts:`The element described does not exist on the page: ${b.thoughts}`,urlAfterCommand:this.browser.url(),afterScreenshotOverride:b.afterScreenshotOverride}}finally{E.cache?.memory&&ls(n,E.cache?.memory.traces,a)}}let f=await kR({command:n,tracer:t,timeoutMs:m,targetingWrapper:E=>this.wrapElementTargetingCommand(E),fixtures:this.getControllerFixtures(e),disableCache:i});return{fail:!f.success,data:f.data,elementInteracted:f.elementInteractedDisplayString,thoughts:f.err?.message??f.thoughts??`Element assertion ${f.success?"succeeded":"failed"}.`,succeedImmediately:!1,urlAfterCommand:this.browser.url()}}case"PAGE_CHECK":{let m=await fr({action:async()=>HR({assertion:n.assertion,browser:this.browser,logger:a,timeout:n.timeout,signal:this.executeAbortController.signal,autoExpandIframes:!!this.browser.userBrowserSettings.autoExpandIframes}),frameConfig:n.iframeUrl?{type:"url",url:n.iframeUrl}:void 0,browser:this.browser,logger:a});return{fail:!m.success,data:m.data,thoughts:m.success?"Page assertion passed.":m.err?.message??`Page assertion still failing after ${n.timeout} seconds.`,urlAfterCommand:this.browser.url(),succeedImmediately:!1}}case"REGISTER_REQUEST_LISTENER":{let m=new zn(n.requestMatcher),h=this.browser.registerRequestListener(m);return this.registeredListeners[n.key]=h.then(async f=>await vg(f)).catch(f=>{a.error({err:f},"Failed to get request listener response")}),{succeedImmediately:!1,urlAfterCommand:this.browser.url()}}case"AWAIT_LISTENER":{let m=this.registeredListeners[n.key];if(!m)throw new x("ActionFailureError",`No listener registered with key: ${n.key}`);let h=n.timeout??10;return{data:await z(m,{milliseconds:h*1e3,message:`Request listener timed out after ${h} seconds`}),succeedImmediately:!1,urlAfterCommand:this.browser.url()}}case"RECORD_REQUESTS":{let m=new zn(n.requestMatcher);return this.recordedRequests[n.key]={},this.browser.registerRequestRecorder(n.key,{matches:h=>m.matches({url:h.request.url,method:h.request.method}),onRequestStart:(h,f)=>{this.recordedRequests[n.key][h]=nu(f)},onRequestComplete:(h,f)=>{this.recordedRequests[n.key]?.[h]&&(this.recordedRequests[n.key][h]=nu(f))}}),{succeedImmediately:!1,urlAfterCommand:this.browser.url()}}case"GET_RECORDED_REQUESTS":{let m=this.recordedRequests[n.key];if(!m)throw new x("ActionFailureError",`No recorder registered with key: ${n.key}`);return delete this.recordedRequests[n.key],{data:Object.values(m),succeedImmediately:!1,urlAfterCommand:this.browser.url()}}case"SET_HEADER":{let m;return n.requestMatcher&&(m=new zn(n.requestMatcher)),this.browser.setHeader(n.name,n.value,m),{succeedImmediately:!1,urlAfterCommand:this.browser.url()}}case"MOCK_ROUTE":return{data:{key:this.browser.registerMock(n.key,new zn(n.requestMatcher),async(h,f)=>{let E=await Wr({orgId:this.orgId,code:n.responseGenerator,fragment:!1,context:o,timeoutMs:void 0,logger:a,localTools:this.localCodeEvalTools,mock:{request:h,response:f},disallowVariableUpdates:!0,responseSerialization:"RESPONSE"}),b=Zy.parse(E);return new Response(b.body,{status:b.status,headers:b.headers})},n.fetchOriginalResponse??!1)},succeedImmediately:!1,urlAfterCommand:this.browser.url()};case"REMOVE_ROUTE_MOCK":return this.browser.removeMock(n.key),{succeedImmediately:!1,urlAfterCommand:this.browser.url()};case"OFFLINE_MODE":return await this.browser.setOfflineMode(n.enable),{succeedImmediately:!1,urlAfterCommand:this.browser.url()};default:return(m=>{throw"If Typescript complains about the line below, you missed a case or break in the switch above"})(n)}return{succeedImmediately:!1,urlAfterCommand:this.browser.url()}}async getReverseMappedDescription({browserState:e,targetId:t,disableCache:n,screenshot:o}){return(await this.generator.getReverseMappedDescription({browserState:e,target:t,screenshot:o},{disableCache:n,abortSignal:this.executeAbortController.signal,loggerTags:ye(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 cu({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:ye(this.logger)})}async getFailureRecoveryPlan(e){return this.generator.getFailureRecoveryPlan(e,{disableCache:!0,abortSignal:this.executeAbortController.signal,loggerTags:ye(this.logger)})}};import{cloneDeep as s1}from"lodash-es";import KR from"truncate-json";var WR=1e3,jR=5e6,l1=5*1024*1024;function YR(r,e){for(let t=0;t<r.length;t++){let n=r[t];try{if(n.data){let{jsonString:o}=KR(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":$R(n);break;case"MOBILE_AI_ACTION_STEP":case"MOBILE_MODULE_STEP":$R(n),YR(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 $R(r){if(r.type==="MOBILE_PRESET_STEP"){let e=r.command;"cache"in e&&e.cache&&(e.cache=void 0)}}function qR(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 bu(r,e){let t=s1(r);if(YR(t,e),t.length>WR)return e.error("Database content violation: results too long, truncating before insertion"),t.slice(0,WR);let n=qR(t,e);if(n.length>jR)for(e.error({serializedLength:n.length,resultsArrayLength:t.length},"Database content violation: results too large, truncating before insertion");n.length>jR;)t.pop(),n=qR(t,e);let{jsonString:o}=KR(n,l1);try{return zt.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 c1}from"async_hooks";var Ss=new c1;function u1(r){Ss.enterWith({activeTracers:[r]})}function d1(r,e){let t=Ss.getStore()?.activeTracers;if(!t)return e();t.push(r);try{return e()}finally{t.pop()}}async function p1(r,e){let t=Ss.getStore()?.activeTracers;if(!t)return e();let n=[...t,r];return Ss.run({activeTracers:n},e)}var un={globalAls:Ss,initializeRootTracerContext:u1,withChildTracer:d1,withChildTracerAsync:p1};var Mo=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 un.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 un.withChildTracerAsync(i,()=>z(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 un.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:{}},i=n[0]??void 0;Object.assign(o,i??{}),this.addSpan(o);let a;try{i?.signal||i?.timeoutMs?a=await z(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})`:""}`}):a=await t(o),o.endTime=Date.now(),o.durationMs=o.endTime-o.startTime}catch(s){throw o.error=s instanceof Error?s.message:String(s),o.endTime=Date.now(),o.durationMs=o.endTime-o.startTime,s}return a}getRootSpan(){return this.finished||this.finish(),{type:"SECTION",name:"root step span",startTime:this.startTime,endTime:this.endTime,subSpans:this.spans,attributes:{},durationMs:this.endTime?this.endTime-this.startTime:void 0}}};function ee(){let r=un.globalAls.getStore()?.activeTracers,e;return!r||r.length===0?e=void 0:e=r[r.length-1],e||new Mo}async function XR(r){let{driver:e,abortSignal:t,logger:n,packageName:o}=r,i;try{i=await z(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=m1(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 m1(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 ys(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=ys(i);a.trim()&&e.push(a.trim())}return e.join(" ").trim()}import{mkdirSync as k1}from"fs";import{tmpdir as U1}from"os";import ox from"path";import{diff as N1}from"deep-object-diff";import{cloneDeep as D1}from"lodash-es";import ex from"fontoxpath";import g1 from"@prettier/plugin-xml";import h1 from"prettier";import{DOMParser as f1,XMLSerializer as S1}from"slimdom";var y1=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 bs(r){let e=r.toLowerCase();return e.endsWith("webview")||y1.has(e)}function b1(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 E1=new Set(["index","package","a11y-important","screen-reader-focusabl"]),T1=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"]),v1=new Set(["text","hint"]),A1=new Set(["live-region","drawing-order"]),w1=new Set(["displayed","enabled"]);function C1(r,e){let t={};for(let[n,o]of Object.entries(e))E1.has(n)||n==="class"&&r===o||n==="focusable"&&o==="true"&&e.clickable==="true"||T1.has(n)&&o==="false"||v1.has(n)&&o===""||w1.has(n)&&o==="true"||A1.has(n)&&o==="0"||n!=="id"&&(t[n]=o);return t}function JR(r,e,t){let{prunedDocument:n,idToElement:o,prunedIdToElement:i,idCounter:a,opts:s}=r,c=a.value++;t.setAttribute("id",String(c));let l={};for(let p of e.attributes){let g=p.name,m=p.value;m!=null&&(l[g]=String(m))}let u=C1(e.tagName,l);for(let[p,g]of Object.entries(u))t.setAttribute(p,g);if(o.set(c,e),i.set(c,t),bs(e.tagName)){let p=s?.injectedWebviewContent??"";if(s?.removeWebviewContent){for(;t.firstChild;)t.removeChild(t.firstChild);return}else if(!s?.disableMomenticAccessibilityTree&&p.trim().length>0){for(;t.firstChild;)t.removeChild(t.firstChild);p.trim().length>0&&t.appendChild(n.createCDATASection(`
4345
+ ${r}`;default:return r}}var jz=15;async function gu({command:r,aiPageFiltering:e,logger:t,fixtures:n,source:o,useMemory:i,maxRetries:a=jz}){if(!r.assertion.trim())throw new x("ActionFailureError","Assertion command is missing the assertion content");let{browser:s}=n,c=r.timeout?r.timeout*1e3:s.smartWaitingTimeout,l=Vc(c),u=0,d=Date.now(),p,g,m;try{await fr({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 W(l,n.abortSignal),h=Date.now();let f=!1;try{if(p=await fr({action:async()=>{let b=await IR(s,t,n.abortSignal);return g&&g.serializedTree===b.serializedTree&&g.screenshotBuff.equals(b.screenshotBuff)?(f=!0,p):(g=b,OR({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}),p?.success){p?.updatedMemory&&ls(r,p.updatedMemory,t);break}else throw p?.thoughts?new x("AssertionFailureError",p.thoughts):new x("InternalPlatformError","No thoughts were provided for AI assertion failure")}catch(E){n.abortSignal.throwIfAborted(),m=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(!p?.success)try{p=await fr({action:async()=>OR({command:r,state:await IR(s,t,n.abortSignal),fixtures:n,useMemory:i,useConsensus:!0,highlightElementsOnFailure:!0,attemptNumber:u,aiPageFiltering:e,logger:t}),frameConfig:r.iframeUrl?{type:"url",url:r.iframeUrl}:void 0,logger:t,browser:s})}catch(f){n.abortSignal.throwIfAborted(),m=f instanceof Error?f:new Error(`${f}`)}finally{u++}if(p?.updatedMemory&&ls(r,p.updatedMemory,t),!p?.success){let f=`AI check still failing after ${u} attempts.`;throw m&&(f+=` Latest result: ${m.message}`),new x("AssertionFailureError",f)}return{...p,succeedImmediately:!1,urlAfterCommand:s.url()}}async function IR(r,e,t){let[n,o]=await Promise.all([Kr(r,{abortSignal:t,skipWait:!0,skipWaitForPageLoad:!0,logger:e}),r.screenshot({retries:1,respectActiveFrame:!0})]);return{...n,screenshotBuff:o}}async function OR({command:r,state:e,fixtures:t,useConsensus:n,useMemory:o,highlightElementsOnFailure:i,aiPageFiltering:a,attemptNumber:s,source:c,logger:l}){let{browser:u,generator:d,abortSignal:p}=t,g={type:"ASSERTION"},{serializedTree:m,tree:h}=e,f=e.screenshotBuff,E=f.toString("base64"),b=u.url(),C=r.contextChoice??"MULTIMODAL",R=m;C!=="VISION_ONLY"&&(R=await xo({type:"assertion",serializedTree:m,tree:h,description:r.assertion,screenshot:E,options:{aiPageFiltering:a},fixtures:{generator:d,signal:p,logger:l,orgId:t.orgId}}),R!==m&&(g.ragUsed=!0),g.pageState=R);let v={goal:r.assertion,url:b,memory:o?r.cache?.memory:void 0,browserState:R,screenshot:E,contextChoice:C,source:c},A=await(C==="VISION_ONLY"?(I,k)=>d.getVisualAssertionResult(I,k):(I,k)=>d.getAssertionResult(I,k))(v,{useConsensus:n,attemptNumber:s,useMemory:o,disableCache:!!r.disableCache,abortSignal:p,logger:l,loggerTags:ye(l)});return(A.result||i)&&A.relevantElements&&(g.relevantElementsSerialized=A.relevantElements.map(I=>u.getSerializedFormFromA11yId(I)).filter(I=>!!I),await $z(A.relevantElements,u,l)),{success:A.result,thoughts:A.thoughts,afterScreenshotOverride:f,updatedMemory:o?A.updatedMemory:void 0}}async function $z(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 z(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 qz=75e4,hu=class extends Error{constructor(){super("The page content exceeds the maximum token limit for AI smart waiting."),this.name="ExceededMaxAISmartWaitingTokensError"}};async function LR(r,e){let{logger:t}=r,{abortSignal:n,browser:o}=e,i=Date.now();try{await Kz(i,r,e)}catch(a){if(a instanceof Error&&(a.name==="AbortError"||a.name==="TimeoutError")||n.aborted)return;a instanceof hu?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 W(s,n)}finally{t.debug({durationMs:Date.now()-i},"AI smart waiting complete")}}async function Kz(r,e,t){let{abortSignal:n,browser:o}=t;if(o.smartWaitingTimeout<3e3){await W(o.smartWaitingTimeout,n);return}if(!e.description)throw new x("UserConfigurationError","Cannot locate element with empty description");await z(Yz(r,e,t),{milliseconds:o.smartWaitingTimeout})}async function Yz(r,e,t){let{logger:n,iframeUrl:o}=e,{browser:i}=t;for(;Date.now()-r<i.smartWaitingTimeout;)if(await fr({action:async()=>Xz(e,t),frameConfig:o?{type:"url",url:o}:void 0,browser:i,logger:n}))return}async function Xz(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 ds({orgId:l,s:d,context:t,localTools:c,signal:s,logger:n}));let{serializedTree:p}=await Kr(a,{allowNotActionableNodesOverride:i,filterByViewport:o,abortSignal:s,logger:n});if(Rr(p)>qz)throw new hu;s.throwIfAborted();let m;try{m=await a.screenshot({clearHighlights:!0,respectActiveFrame:!0,retries:2})}catch(b){throw new x("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,${m.toString("base64")}`;s.throwIfAborted();let E=await u.getSmartWaitingDecision({browserState:p,description:d,screenshot:f},{abortSignal:s,loggerTags:ye(n)});return n.debug({result:E},"Got smart waiting result"),E.isPageReady}import{cloneDeep as DR}from"lodash-es";async function kR(r){let{command:e,timeoutMs:t,fixtures:n}=r,{abortSignal:o}=n,i=()=>Zh(e.cache)?e.cache:void 0,a=i(),s=DR(a),c=(h=!1)=>{if(a=i(),!!a)if(h){let f=YA(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,p=500,g=!1;for(;u<2||Date.now()-l<t;){u++,u>1&&await W(p,o),o?.throwIfAborted(),a=i();let{result:h,elementWasFound:f}=await NR({cacheToUse:a,params:r});if(d=h,g=f,h.success)break;c(),p=Math.min(p*2,1e4)}if(!d)throw new x("InternalPlatformError",`Failed to evaluate manual element assertion in ${t}ms.`);if(o?.throwIfAborted(),!d.success&&a?.target&&Bs(a.target)){let h=a?.target?.memory?{target:{id:-1,memory:a.target.memory}}:void 0,{result:f}=await NR({cacheToUse:h,params:r});d=f,d.success||c(!0)}let m=i();return d.success&&m?.target&&!g&&(m.target=Jm(m.target),m.updatedAt=new Date),d}async function NR({cacheToUse:r,params:e}){let{command:t,disableCache:n,fixtures:o,tracer:i,targetingWrapper:a}=e,{logger:s}=o;if(t.target&&!fn(t.target))throw new Error("Element assertion with x/y is not supported yet");let c=Fc(t.assertion),l,u=!1,d=DR(r);try{let{elementInteractedDisplayString:p,result:g,thoughts:m}=await a({ctx:o.ctx,tracer:i,command:t,target:t.target,cache:d?.target,action:async h=>Jz(h.locator,e),options:{...t,allowNotActionableNodesOverride:!0,disableCache:n,memory:d?.target?.memory,disableGlobalLocatorRedirect:!0,source:ga(t),targetName:"target"}});return l={success:g.success,data:g.data,err:g.err,elementInteractedDisplayString:p,thoughts:m},u=!0,g.success||(s.warn({aiThoughts:m,elementString:p,err:g.err},"Element check found an element but failed"),l={...g,thoughts:m}),{result:l,elementWasFound:u}}catch(p){if(c)return l={success:!0,thoughts:`The element described does not exist on the page: ${p.message}`,err:void 0,data:void 0},{result:l,elementWasFound:u};if(!(p instanceof x)||p.reason!="ActionFailureError")throw p;return l={success:!1,err:p,data:void 0,thoughts:void 0},s.warn({err:p},"Element check did not find an element and failed"),{result:l,elementWasFound:u}}}async function Jz(r,{command:e,fixtures:t}){return await t.browser.highlight(r),await Qz(r,e.assertion)}async function Qz(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)},!Vr(a,e.value,e.operation,{negated:!!e.negated,ignoreCase:!1})){let s=mr(e);t=!1,n=new x("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 x("AssertionFailureError",`The element does not have an attribute named ${e.attr}: ${s}`),t=!1;break}if(!Vr(a,e.value,e.operation,{negated:!!e.negated,ignoreCase:!1})){let s=mr(e);t=!1,e.operation==="EXISTS"?n=new x("AssertionFailureError",`The attribute ${e.attr} ${s}`):n=new x("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},Lt*1e3);break}case"EDITABLE":{t=await r.isEditable({timeout:Lt*1e3});break}case"EXISTS":{t=!0;break}case"ENABLED":{t=await r.isEnabled({timeout:Lt*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=mr(e);n=new x("AssertionFailureError",`The element ${a}`)}break}case"ELEMENT_NAME":{let a=await r.evaluate(s=>s.tagName);if(!Vr(a,e.value,e.operation,{negated:!!e.negated,ignoreCase:!0})){let s=mr(e);t=!1,n=new x("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(!Vr(a,e.value,e.operation,{negated:!!e.negated,ignoreCase:!1})){let s=mr(e);t=!1,e.operation==="EXISTS"?n=new x("AssertionFailureError",`The style property ${e.property} ${s}`):n=new x("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 UR(r){return r.type==="ELEMENT_EXISTENCE"&&r.negated&&r.condition==="EXISTS"}import{Jimp as Zz}from"jimp";async function fs(r,e){let t=await r.screenshot(e),n=await Zz.fromBuffer(t);return{buffer:t,width:Math.ceil(n.bitmap.width??0),height:Math.ceil(n.bitmap.height??0)}}import{Jimp as FR}from"jimp";import $g from"jpeg-js";import e1 from"pixelmatch";async function BR({ctx:r,tracer:e,command:t,disableCache:n,browser:o,targetingWrapper:i,logger:a,screenshotStorage:s}){if(t.target&&!fn(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 ge=>fs(o,{locator:ge.locator,...c}),options:{...t,disableCache:n,disableGlobalLocatorRedirect:!0,memory:t.cache?.target?.memory,targetName:"target"}})).result:l=await fs(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 G=`${l.width}x${l.height}`,ge=`${u.width}x${u.height}`;return{fail:!0,thoughts:`Current screenshot (${G}) does not match saved screenshot dimensions (${ge}) - 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 FR.fromBuffer(l.buffer),p={width:l.width,height:l.height},g=await FR.fromBuffer(u.buffer),m={width:u.width,height:u.height},h,f=p.width*p.height,E=m.width*m.height,b=Math.abs(p.height-m.height),C=Math.abs(p.width-m.width);if(f>E){let G=d.cover({w:m.width,h:m.height});l.buffer=await G.getBuffer("image/jpeg"),h="current",l.width=m.width,l.height=m.height}else if(E>f){let G=g.cover({w:p.width,h:p.height});u.buffer=await G.getBuffer("image/jpeg"),h="saved"}let R={data:Buffer.alloc(l.width*l.height*4),width:l.width,height:l.height},v=t.threshold??.1,A=e1($g.decode(u.buffer).data,$g.decode(l.buffer).data,R.data,l.width,l.height,{threshold:v,diffColorAlt:[0,255,0]})/(l.width*l.height)*100,I=A>v*100,k=`Visual diff of ${A.toFixed(2)}% detected, which is ${I?"over":"under"} the threshold of ${v*100}%.`;if(h&&(k+=` The ${h} screenshot was cropped since it was taller by ${b} pixels and wider by ${C} pixels.`),I)throw new x("ActionFailureError",k);return{fail:I,thoughts:k,beforeScreenshotOverride:l.buffer,afterScreenshotOverride:$g.encode(R,75).data,succeedImmediately:!1,urlAfterCommand:o.url()}}var t1=3e4;function r1(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 fu({command:r,logger:e,baseUrl:t,fetchImplementation:n=fetch}){let o=r.timeout??t1/1e3,i=Object.fromEntries(Object.entries(r.headers||{}).filter(([m,h])=>m&&h)),a=new URLSearchParams;Object.entries(r.params||{}).filter(([m,h])=>m&&h).forEach(([m,h])=>{a.append(m,h)});let s=a.toString(),c;if(Mi(r.url)&&(c=r.url),t&&_i(r.url,t)&&(c=new URL(r.url,t).toString()),!c)throw new x("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 z((async()=>{let m=s?`${l}?${s}`:l;try{let h=r1(r),f=new Headers(i);return h.contentType&&!f.has("Content-Type")&&f.set("Content-Type",h.contentType),await n(m,{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 x("ActionFailureError",`Fetch request timed out after ${o} seconds`)}});if(!d.ok){let m;try{m=await d.text()}catch(h){m=`Failed to read response body: ${h}`}throw new x("ActionFailureError",`Fetch request failed with status ${d.status}: ${m}`)}let p={};d.headers.forEach((m,h)=>{p[h]=m});let g={status:d.status,headers:p,request:{url:d.url,method:r.method,headers:i}};if(r.body?.type==="json"&&r.body.content)try{g.request.json=JSON.parse(r.body.content)}catch{}if(d.headers.get("content-type")?.includes("json"))try{g.json=await d.json()}catch{}else d.headers.get("content-type")?.includes("text")&&(g.text=await d.text());return g}var n1=5e3;async function HR({timeout:r=Lt,...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 Su(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 W(s,e.signal),s=Math.min(Math.floor(s*1.5),n1);else return i}return i=await Su(e),i}async function Su({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(zR,{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(zR,{value:r.value,negated:!!r.negated,returnHtml:!0},"checking page content"));if(!i){let c=r.negated?sn.CONTAINS:ln.CONTAINS;a=new x("AssertionFailureError",`The page ${c} '${r.value}'.`),o=s}}catch(s){a=new x("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 zR({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 o1=3e4;async function GR({command:r,logger:e,baseUrl:t,fetchImplementation:n=fetch}){let o=r.timeout??o1/1e3,i=new AbortController,a=Object.fromEntries(Object.entries(r.headers||{}).filter(([d,p])=>d&&p));a["Content-Type"]="application/json";let s;if(Mi(r.url)&&(s=r.url),t&&_i(r.url,t)&&(s=new URL(r.url,t).toString()),!s)throw new x("ActionFailureError",`Invalid URL: ${r.url}`);let l=await z((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 x("ActionFailureError",`GraphQL request timed out after ${o} seconds`);if(!l.ok){let d,p=await l.text();try{d=JSON.parse(p)}catch{throw new x("ActionFailureError",`GraphQL request failed with status ${l.status}: ${p}`)}throw d?.errors?.length&&d?.errors[0]?.message?new x("ActionFailureError",`GraphQL request failed with status ${l.status}: ${d.errors[0].message}`):new x("ActionFailureError",`GraphQL request failed with status ${l.status}: ${p}`)}let u={};return l.headers.forEach((d,p)=>{u[p]=d}),{status:l.status,headers:u,json:await l.json()}}var yu=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([Kr(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 xo({type:"ai-action",description:e,screenshot:u,serializedTree:c.serializedTree,tree:c.tree,options:{aiPageFiltering:!!this.options?.aiPageFiltering},fixtures:{generator:this.generator,signal:this.executeAbortController.signal,logger:s,orgId:this.orgId}}),p={url:this.browser.url(),browserState:d,startingScreenshot:t,history:n,goal:e,screenshot:u,lastError:a};return await this.generator.getMultiturnAiActionEvaluation(p,{disableCache:o,abortSignal:this.executeAbortController.signal,loggerTags:{...ye(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([Kr(this.browser,{abortSignal:this.executeAbortController.signal,skipWait:!0,skipWaitForPageLoad:!0,logger:a}),this.browser.screenshot({retries:1,clearHighlights:!0})]),d=`data:image/jpeg;base64,${u.toString("base64")}`,p=await xo({type:"ai-action",description:e,screenshot:d,serializedTree:l.serializedTree,tree:l.tree,options:{aiPageFiltering:!!this.options?.aiPageFiltering},fixtures:{generator:this.generator,signal:this.executeAbortController.signal,logger:a,orgId:this.orgId}}),g={url:c,browserState:p,startingScreenshot:t,history:n,goal:e,actionHint:o,screenshot:d};try{return await this.generator.getMultiturnAiActionCommand(g,{disableCache:i,abortSignal:this.executeAbortController.signal,loggerTags:{...ye(a)},langfuseSessionId:s})}catch(m){throw new x("InternalWebAgentError",`Error generating command: ${m instanceof Error?m.message:m}`,{errOptions:{cause:m}})}}async getBrowserState(e){return Kr(this.browser,e)}async locateElement(e){return await jg({...e,aiPageFiltering:!!this.options?.aiPageFiltering},this.getControllerFixtures())}async locateElementWithSelector(e,t){return fr({action:async()=>{let n=await this.browser.resolveHardcodedCssSelector({ctx:null,selector:e,timeoutMs:2e3,logger:this.logger});return{thoughts:"Located element with selector",target:{id:-1,selector:e,targetSource:"USER_CSS_SELECTOR",targetUpdateTime:new Date().toUTCString()},resolution:n}},frameConfig:t?{type:"url",url:t}:void 0,browser:this.browser,logger:this.logger})}getControllerFixtures(e){return{ctx:e??null,browser:this.browser,generator:this.generator,logger:this.logger,orgId:this.orgId,storage:this.storage,localCodeEvalTools:this.localCodeEvalTools,abortSignal:this.executeAbortController.signal}}shouldUseMemory(){return this.options?.useMemory??(this.orgId==="org_01HMSCJQBCCG51M2ZF65YC5B8W"||this.orgId==="org_01HMJTX4GT1KG94KZRCT8MZ6YB")}async wrapMultiElementTargetingCommand({ctx:e,tracer:t,command:n,targetNames:o,descriptions:i,caches:a,action:s,options:c,retriesWithAI:l=1}){let u=[];for(let d=0;d<i.length;d++){let p=i[d],g=await this.wrapElementTargetingCommand({ctx:e,tracer:t,command:n,target:p,cache:a[d],action:async m=>m,options:{...c,targetName:o[d]}});u.push(g)}try{let d=await s(...u.map(m=>m.result)),p=m=>m==="fromTarget"?"From Target":m==="toTarget"?"To Target":"Target",g=u.map((m,h)=>m.thoughts?`${p(o[h])}: ${m.thoughts}`:void 0).filter(m=>!!m).join(" -------------- ")||void 0;return{result:d,elementInteractedDisplayStrings:u.map(m=>m.elementInteractedDisplayString),thoughts:g}}catch(d){if(this.throwIfClosed(),l>0)return this.logger.warn({err:d},"Failed to execute action with multiple cached targets, retrying with AI"),this.wrapMultiElementTargetingCommand({ctx:e,tracer:t,command:n,targetNames:o,descriptions:i,caches:i.map(()=>{}),action:s,options:c,retriesWithAI:l-1});throw new x("ActionFailureError",d.message,{errOptions:{cause:d}})}}async wrapElementTargetingCommand(e){let t=this.logger.child({commandId:e.command.id}),n;for(let o=0;o<2;o++)try{return await fr({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&&Cd(i)){t.warn({err:i},"Invalid mpath error, retrying element targeting command");continue}if(!this.browser.userBrowserSettings.visualActions&&(Md(i)||Rd(i))){t.warn({err:i},"Invalid momentic id error, retrying element targeting command");continue}if(_d(i)){t.warn({err:i},"Invalid backend node id error, retrying element targeting command");continue}if(i instanceof Lr&&i.retryableWithAI){t.warn({err:i},"Element cache disqualification error, retrying element targeting command");continue}throw i}throw n instanceof x?n:new x("ActionFailureError",n?.message??"An unknown error occurred during element targeting")}async wrapHardcodedCssTargetingCommandHelper({ctx:e,target:t,action:n,options:o,command:i}){let a=this.logger.child({commandId:i.id}),{targetName:s}=o;if(t.type!=="description")throw new x("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 W(500)}}throw c}async wrapElementTargetingCommandHelper(e){let{ctx:t,tracer:n,target:o,originalCache:i,action:a,options:s,command:c}=e,{disableCache:l,useSelector:u,targetName:d,targetHealingInProgress:p,source:g}=s,m=this.logger.child({commandId:c.id}),h=this.shouldUseMemory(),f=s.retriesWithAI??1,E=!1,b=VR(e.cache);if((!b||l)&&!cd(o))throw new x("ActionFailureError","Cannot target element with no cached data or element descriptor");if(u)return this.wrapHardcodedCssTargetingCommandHelper(e);l&&(m.info("Cache explicitly disabled for this step"),E=!0,b=void 0),b&&this.browser.userBrowserSettings.disableSecondaryCacheResolution&&b.targetSource==="HEURISTIC_HEALED"&&(E=!0,b=void 0),b?.inputDescription&&!PR(o.elementDescriptor,b.inputDescription)&&(m.warn({old:b.inputDescription,new:o.elementDescriptor},"Target cache was generated with a different description, clearing it automatically"),E=!0,b=void 0);let C=v=>!!v&&Bs(v),R=!0;if(!C(b)){R=!1,m.info({description:o.elementDescriptor,targetHealingInProgress:p,cacheBustedBeforeAction:E,memory:s.memory,useMemory:h},"Prompting AI for an updated element location"),(E||!i)&&await LR({description:o.elementDescriptor,iframeUrl:s.iframeUrl,source:g,logger:m,allowNotActionableNodesOverride:s.allowNotActionableNodesOverride},this.getControllerFixtures(t)),f--;let v;try{v=await jg({description:o.elementDescriptor,disableCache:!!s.disableCache,iframeUrl:s.iframeUrl,source:g,useMemory:h,memory:h?s.memory:void 0,aiPageFiltering:!!this.options?.aiPageFiltering,allowNotActionableNodesOverride:s.allowNotActionableNodesOverride,logger:m},this.getControllerFixtures(t))}catch(I){if(I instanceof bn&&I.updatedLocatorMemory){let k={id:-1,...i,memory:I.updatedLocatorMemory};Bc({cmd:c,key:d,newTarget:k,logger:m,updatedWithAI:!0})}throw new x("ActionFailureError",I.message)}v.frameConfig&&this.browser.setActiveFrameConfig(v.frameConfig);let M=s.disableGlobalLocatorRedirect?{locator:v.resolution.locator}:await this.attemptLocatorRedirect(v.resolution.locator,m),A=await a(M);return Bc({cmd:c,key:d,newTarget:v.target,logger:m,updatedWithAI:!0}),p&&(n.recordTargetAutoHeal({healType:"AI"}),v.target.targetSource="AI_HEALED",v.target.targetUpdateTime=new Date().toUTCString(),v.target.targetUpdateLoggerTags=ye(m)),{result:A,elementInteractedDisplayString:v.resolution.displayString,thoughts:v.thoughts}}try{let v=await this.browser.resolveTarget(t,b,{allowNotActionableNodesOverride:s.allowNotActionableNodesOverride,targetName:d,logger:m,signal:this.executeAbortController.signal});(this.browser.userBrowserSettings.visualActions||this.browser.userBrowserSettings.globalLocatorRedirect!==!1)&&await this.browser.scrollIntoViewIfNeeded(v.locator);let M=s.disableGlobalLocatorRedirect?{locator:v.locator}:await this.attemptLocatorRedirect(v.locator,m),A=await a(M);if(Tt.increment("cache_target_resolution_v2",1,["outcome:hit","platform:web",`hasRequirements:${!!b.requirements}`,`hasAdditionalElements:${!!b.additionalElements}`,`orgId:${this.orgId}`,"cliVersion:0.12.1"]),Bc({cmd:c,key:d,newTarget:b,logger:m,updatedWithAI:!1}),R){let I=v.decisions.filter(k=>k.matched);if(I.length!==1)m.warn({decisions:v.decisions},"Expected exactly 1 matching method for element location, got more or less");else{let k=I[0].type;n.recordTargetAutoHeal({healType:k})}}return{result:A,elementInteractedDisplayString:v.displayString}}catch(v){this.throwIfClosed();let M="unknown";v instanceof Or&&v.cacheMissReason&&(M=v.cacheMissReason),Tt.increment("cache_target_resolution_v2",1,["outcome:miss","platform:web",`hasRequirements:${!!b.requirements}`,`hasAdditionalElements:${!!b.additionalElements}`,`orgId:${this.orgId}`,"cliVersion:0.12.1",`missReason:${M}`]);let A=!1;if((v instanceof Lr||Cd(v)||Md(v)||_d(v)||aS(v)||Rd(v)||sS(v))&&(A=!0),v instanceof x&&!A)throw m.error({err:v},"Failed to execute action with cached target (fatal)"),v;if(f>0&&o){m.info({err:v},"Failed to execute action with cached target, retrying with AI");let I;return b.memory&&Kh(b.memory)&&(I=b.memory),this.wrapElementTargetingCommand({ctx:t,tracer:n,command:c,target:o,cache:void 0,originalCache:i,action:a,options:{...s,memory:I,retriesWithAI:f,targetHealingInProgress:!0}})}throw new x("ActionFailureError",v.message,{errOptions:{cause:v}})}}async attemptLocatorRedirect(e,t){return this.browser.userBrowserSettings.globalLocatorRedirect!==!1?this.browser.performTargetRedirection(e,t):{locator:e}}async screenshotWithDimensions(e){return fs(this.browser,e)}async executePresetCommand(e,t,n,o,i){this.options?.slowMoMs&&await W(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 x("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&&Cf(n)?await this.browser.waitForDOMStability({timeout:Ee}):!this.browser.userBrowserSettings.visualActions&&["PRESS","TYPE"].includes(n.type)&&await this.browser.waitForDOMStability({timeout:re}),this.options?.autoFollowNewTabs&&await TR({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{Jc(n,c)}}createCallbacksForBrowser(e){return{createIsolatedFolder:()=>fg(e)}}async resolveCommandTemplateStrings(e,t){return Xc({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()?gu({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 x("ActionFailureError","Missing assertion");if(n.timeout&&n.timeout>1800)throw new x("AssertionFailureError",`AI check timeout of ${n.timeout} exceeds the maximum allowed value of 30 minutes.`);return gu({command:n,fixtures:this.getControllerFixtures(e),useMemory:this.shouldUseMemory(),aiPageFiltering:!!this.options?.aiPageFiltering,logger:a})}case"AI_EXTRACT":{if(!n.goal.trim())throw new x("ActionFailureError","Cannot perform AI extraction without goal");if(n.schema){let f=SE(n.schema);if(f)throw new x("UserConfigurationError",f)}let m=await this.browser.getCondensedHtml(),h=await this.browser.screenshot({retries:2});try{let f=await this.generator.getTextExtraction({goal:n.goal,browserState:m,returnSchema:n.schema,screenshot:`data:image/jpeg;base64,${h.toString("base64")}`},{disableCache:i,abortSignal:this.executeAbortController.signal,loggerTags:ye(a)});if(f.result==="NOT_FOUND")throw new x("ActionFailureError","No relevant data found for extraction goal on this page");if(f.thoughts?.includes("MaxGenerationLengthExceededError"))throw new x("UserConfigurationError",f.thoughts);return{thoughts:f.thoughts||void 0,data:f.result,succeedImmediately:!1,urlAfterCommand:this.browser.url()}}catch(f){let E=f.message;throw E.includes("MaxGenerationLengthExceededError")?new x("UserConfigurationError","You tried to extract too much data. Please rephrase your query to limit the results returned or use a JavaScript step in the browser instead."):E.includes("AIProviderError")&&E.includes("time")?new x("AIProviderError","The AI provider responded with an error. This may be because you tried to extract too much data. Please limit extraction results to 2000 characters.",{errOptions:{cause:f}}):f}}case"NAVIGATE":if(!Mi(n.url)&&!_i(n.url,this.browser.baseUrl))throw new x("ActionFailureError",`Invalid URL provided to navigate command: ${n.url}`);await this.browser.navigate({url:n.url,loadTimeoutMs:n.loadTimeout?n.loadTimeout*1e3:void 0});break;case"DIALOG":this.browser.registerDialogHandler(n.action);break;case"CAPTCHA":if(!this.browser.canSolveCaptchas())break;let c=await this.browser.solveCaptcha();c&&(await this.wrapElementTargetingCommand({ctx:e,tracer:t,command:n,target:{type:"description",elementDescriptor:"the captcha image solution input"},cache:void 0,action:m=>this.browser.click(m,this.createCallbacksForBrowser(this.orgId),{}),options:{...n,targetName:"target",disableCache:i}}),await this.browser.type(c,{clearContent:!0,pressEnter:!0},!0));break;case"GO_BACK":await this.browser.goBack();break;case"GO_FORWARD":await this.browser.goForward();break;case"SCROLL_LEFT":case"SCROLL_RIGHT":case"SCROLL_DOWN":case"SCROLL_UP":{let m,h;if(n.target&&_r(n.target))await this.browser.hoverUsingVisualCoordinates(n.target.pixels);else if(n.target&&n.target.elementDescriptor.trim()){let{elementInteractedDisplayString:b,thoughts:C}=await this.wrapElementTargetingCommand({ctx:e,tracer:t,command:n,target:n.target,cache:n.cache?.target,action:R=>this.browser.hover(R),options:{...n,targetName:"target",disableGlobalLocatorRedirect:!0,disableCache:i}});m=b,h=C}let f=this.browser.getViewport()?.height??wn.height,E=this.browser.getViewport()?.width??wn.width;switch(n.type){case"SCROLL_UP":await this.browser.scrollVertical(-(n.deltaY??f));break;case"SCROLL_DOWN":await this.browser.scrollVertical(n.deltaY??f);break;case"SCROLL_LEFT":await this.browser.scrollHorizontal(-(n.deltaX??E));break;case"SCROLL_RIGHT":await this.browser.scrollHorizontal(n.deltaX??E);break}return{succeedImmediately:!1,urlAfterCommand:this.browser.url(),elementInteracted:m,thoughts:h}}case"WAIT_FOR_URL":{if(n.timeout&&n.timeout>1800)throw new x("UserConfigurationError",`Wait for URL timeout of ${n.timeout} exceeds the maximum allowed value of 30 minutes.`);let m=n.matcher;await this.browser.waitForUrl({beforeUrl:this.browser.url(),matcher:m},{timeout:n.timeout?n.timeout*1e3:void 0,negated:n.negated,caseInsensitive:n.caseInsensitive});break}case"WAIT":if(n.delay>1800)throw new x("UserConfigurationError",`Wait timeout of ${n.delay} seconds exceeds the maximum allowed value of 30 minutes`);let l=n.delay*1e3;await W(l,this.executeAbortController.signal);break;case"REFRESH":await this.browser.refresh({loadTimeoutMs:n.loadTimeout?n.loadTimeout*1e3:void 0});break;case"CLICK":{if(_r(n.target)){await this.browser.clickUsingVisualCoordinates(n.target.pixels,n);break}let m=this.browser.url(),{elementInteractedDisplayString:h,result:f,thoughts:E}=await this.wrapElementTargetingCommand({ctx:e,tracer:t,target:n.target,command:n,cache:n.cache?.target,action:C=>this.browser.click(C,this.createCallbacksForBrowser(this.orgId),n),options:{disableCache:i,targetName:"target",...n}}),b={urlAfterCommand:this.browser.url(),succeedImmediately:!1,elementInteracted:h,thoughts:E,data:f.downloadedFile?{downloadedFile:f.downloadedFile}:void 0};return jc(m,b.urlAfterCommand)&&(b.succeedImmediately=!0,b.succeedImmediatelyReason="URL changed"),b}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(_r(n.fromTarget)&&_r(n.toTarget)){await this.browser.dragAndDropUsingVisualCoordinates(n.fromTarget.pixels,n.toTarget.pixels,{hoverSeconds:n.hoverSeconds});break}if(_r(n.fromTarget)||_r(n.toTarget))throw new Error("Drag and drop targets must be both coordinates or both descriptions");let{elementInteractedDisplayStrings:m,thoughts:h}=await this.wrapMultiElementTargetingCommand({ctx:e,tracer:t,command:n,targetNames:["fromTarget","toTarget"],descriptions:[n.fromTarget,n.toTarget],caches:[n.cache?.fromTarget,n.cache?.toTarget],action:(f,E)=>this.browser.dragAndDrop(f.locator,E.locator,{hoverSeconds:n.hoverSeconds,steps:n.steps}),options:{useSelector:!!n.useSelector,disableCache:i}});return{succeedImmediately:!1,urlAfterCommand:this.browser.url(),elementInteracted:m[0],thoughts:h}}case"MOUSE_DRAG":{let m=parseInt(n.deltaX),h=parseInt(n.deltaY),f=n.steps??5;if(isNaN(m)||isNaN(h))throw new x("ActionFailureError",`Invalid pixel values passed to mouse drag command: (${n.deltaX}, ${n.deltaY})`);if(n.target&&_r(n.target)){await this.browser.mouseDragUsingVisualCoordinates(m,h,f,void 0,n.target.pixels);break}let E,b;if(n.target?.elementDescriptor){let{elementInteractedDisplayString:C,thoughts:R}=await this.wrapElementTargetingCommand({ctx:e,tracer:t,command:n,target:n.target,cache:n.cache?.target,action:async v=>this.browser.mouseDrag(m,h,f,v.locator,{force:n.force}),options:{disableCache:i,targetName:"target",...n}});E=C,b=R}else await this.browser.mouseDrag(m,h,f,void 0,{force:n.force});return{succeedImmediately:!1,urlAfterCommand:this.browser.url(),elementInteracted:E,thoughts:b}}case"SELECT_OPTION":{if(!fn(n.target))throw new Error("Select with x/y is not supported yet");let m=n.target.elementDescriptor,h=n.choice,{elementInteractedDisplayString:f,thoughts:E}=await this.wrapElementTargetingCommand({ctx:e,tracer:t,command:n,target:{type:"description",elementDescriptor:m},cache:n.cache?.target,action:b=>this.browser.selectOption(b,h,n.force),options:{...n,targetName:"target",disableCache:i,source:ga(n)}});return{succeedImmediately:!1,urlAfterCommand:this.browser.url(),elementInteracted:f,thoughts:E}}case"TAB":{let m={loadTimeoutMs:n.loadTimeout?n.loadTimeout*1e3:void 0,retry:!0};await this.browser.switchToPage(n.action,m);break}case"NEW_TAB":await this.browser.createNewTab(n.url,{loadTimeoutMs:n.loadTimeout?n.loadTimeout*1e3:void 0});break;case"COOKIE":if(!n.value)break;let u=await this.browser.setCookie(n.value);a.debug({results:u},"Set cookies");break;case"LOCAL_STORAGE":if(!n.value||!n.key)break;await this.browser.setLocalStorage(n.key,n.value);break;case"JAVASCRIPT":{let m;try{n.environment==="BROWSER"?(m=await this.browser.evaluateCodeInPage({code:n.code,fragment:n.fragment??!1,context:o.toObjectCopy(),timeoutMs:n.timeout?n.timeout*1e3:void 0}),a.info({result:m},"Executed JavaScript in browser")):m=await Wr({orgId:this.orgId,code:n.code,fragment:!!n.fragment,context:o,timeoutMs:n.timeout?n.timeout*1e3:void 0,logger:a,localTools:this.localCodeEvalTools,signal:this.executeAbortController.signal,callbacks:{onPersistentVariableUpdates:async h=>{if(!this.options?.scratchPadId){a.warn({updates:h},"Got persistent variable updates but scratch pad is not available");return}await this.storage.savePersistentVariables?.({scratchPadId:this.options?.scratchPadId,orgId:this.orgId,updates:h,logger:a})}}})}catch(h){throw this.throwIfClosed(),new x("ActionFailureError",h instanceof Error?h.message:`${h}`,{errOptions:{cause:h}})}try{JSON.stringify(m)}catch(h){throw new x("ActionFailureError",`Return value is not serializable: ${h instanceof Error?h.message:`${h}`}`,{errOptions:{cause:h}})}return{urlAfterCommand:this.browser.url(),succeedImmediately:!1,data:m}}case"TYPE":{if(n.target&&_r(n.target)){await this.browser.clickUsingVisualCoordinates(n.target.pixels,n),await this.browser.type(n.value,{force:n.force,clearContent:n.clearContent,forceClearContent:n.forceClearContent,delay:n.delay,pressEnter:n.pressEnter},!0);break}let m=this.browser.url(),h,f,E=VR(n.target),b=this.browser.userBrowserSettings.globalLocatorRedirect===void 0||this.browser.userBrowserSettings.globalLocatorRedirect==="always";if(E){let{elementInteractedDisplayString:R,thoughts:v}=await this.wrapElementTargetingCommand({ctx:e,tracer:t,command:n,target:E,cache:n.cache?.target,action:M=>this.browser.typeIntoTarget(n.value,M,{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:!b,source:ga(n)}});h=R,f=v}else await this.browser.type(n.value,{force:n.force,clearContent:n.clearContent,forceClearContent:n.forceClearContent,delay:n.delay,pressEnter:n.pressEnter},!0);let C={urlAfterCommand:this.browser.url(),succeedImmediately:!1,elementInteracted:h,thoughts:f};return jc(m,C.urlAfterCommand)&&(C.succeedImmediately=!0,C.succeedImmediatelyReason="URL changed"),C}case"HOVER":{if(_r(n.target)){await this.browser.hoverUsingVisualCoordinates(n.target.pixels);break}let{elementInteractedDisplayString:m,thoughts:h}=await this.wrapElementTargetingCommand({ctx:e,tracer:t,command:n,target:n.target,cache:n.cache?.target,action:f=>this.browser.hover(f),options:{...n,targetName:"target",disableCache:i}});return{succeedImmediately:!1,urlAfterCommand:this.browser.url(),elementInteracted:m,thoughts:h}}case"FOCUS":{if(!fn(n.target))throw new Error("Focus with x/y is not supported yet");let{elementInteractedDisplayString:m,thoughts:h}=await this.wrapElementTargetingCommand({ctx:e,tracer:t,command:n,target:n.target,cache:n.cache?.target,action:f=>this.browser.focus(f),options:{...n,targetName:"target",disableCache:i}});return{succeedImmediately:!1,urlAfterCommand:this.browser.url(),elementInteracted:m,thoughts:h}}case"BLUR":{if(n.target&&!fn(n.target))throw new Error("Blur with x/y is not supported yet");if(!n.target||!n.target.elementDescriptor)return await this.browser.blur(null),{succeedImmediately:!1,urlAfterCommand:this.browser.url()};let{elementInteractedDisplayString:m,thoughts:h}=await this.wrapElementTargetingCommand({ctx:e,tracer:t,target:n.target,command:n,cache:n.cache?.target,action:f=>this.browser.blur(f),options:{...n,targetName:"target",disableCache:i}});return{succeedImmediately:!1,urlAfterCommand:this.browser.url(),elementInteracted:m,thoughts:h}}case"PRESS":let d=this.browser.url();await this.browser.press(n.value,{repeat:n.repeat,convertMeta:n.convertMeta??!0,delayMs:n.delayMs});let p={urlAfterCommand:this.browser.url(),succeedImmediately:!1};return jc(d,p.urlAfterCommand)&&(p.succeedImmediately=!0,p.succeedImmediatelyReason="URL changed"),p;case"KEY_DOWN":return await this.browser.keyDown(n.value,{convertMeta:n.convertMeta??!0}),{urlAfterCommand:this.browser.url(),succeedImmediately:!1};case"KEY_UP":return await this.browser.keyUp(n.value,{convertMeta:n.convertMeta??!0}),{urlAfterCommand:this.browser.url(),succeedImmediately:!1};case"REQUEST":{let m=new a1,h=i1(fetch,m),f;try{f=new URL(n.url).hostname}catch{}let E=await fu({command:n,baseUrl:this.browser.baseUrl,logger:a,fetchImplementation:h});return{data:Ws.parse({...E,cookies:Sl(m,f)}),succeedImmediately:!1,urlAfterCommand:this.browser.url()}}case"GRAPHQL_REQUEST":return{data:await GR({command:n,baseUrl:this.browser.baseUrl,logger:a}),succeedImmediately:!1,urlAfterCommand:this.browser.url()};case"VISUAL_DIFF":return BR({ctx:e,tracer:t,command:n,disableCache:i,browser:this.browser,logger:a,storage:this.storage,screenshotStorage:this.visualDiffScreenshotStorage,targetingWrapper:m=>this.wrapElementTargetingCommand(m)});case"FILE_UPLOAD":{let m,h;if(n.fileSource.type==="URL"?(h=n.fileSource.url,m=await uC({uri:n.fileSource.url,logger:a,orgId:this.orgId})):n.fileSource.type==="USER_FILE"&&(h=n.fileSource.name,m=await this.uploadedFileStorage?.getFileForUpload(n.fileSource.name,this.orgId)),!m)throw new x("UserConfigurationError",`Attempted to use non-existent file for upload step: ${h}`);await this.browser.setFileChooserHandler({...m,filename:n.filename});break}case"AUTH_SAVE":return{data:await this.browser.saveAuthState(),succeedImmediately:!1,urlAfterCommand:this.browser.url()};case"AUTH_LOAD":{let m;if(!n.storageState.trim())m=void 0;else if(m=await Wr({orgId:this.orgId,code:n.storageState,fragment:!1,context:o,logger:a,localTools:this.localCodeEvalTools,signal:this.executeAbortController.signal}),typeof m!="object")throw new x("ActionFailureError",`Credentials must evaluate to an object (received ${typeof m} instead)`);let h;try{h=Iy.optional().parse(m)}catch(f){throw new x("ActionFailureError",`Credentials provided do not follow the required format: ${f}`)}await this.browser.loadAuthState(h);break}case"ELEMENT_CHECK":{let m=(n.timeout??Lt)*1e3,h=this.generator.getAgentConfig()?.assertion;if(UR(n.assertion)&&!n.useSelector&&n.target.type==="description"&&h&&h!=="v1"){let E={id:n.id,type:"AI_ASSERTION",assertion:`There is no element on the page closely matches the following description. If the description has single quotes, remember that requires an exact text substring match. Description: ${n.target.elementDescriptor}`,iframeUrl:n.iframeUrl,timeout:n.timeout,cache:n.cache&&"memory"in n.cache?{memory:n.cache?.memory}:void 0};try{let b=await gu({command:E,logger:a,aiPageFiltering:!!this.options?.aiPageFiltering,fixtures:this.getControllerFixtures(e),useMemory:this.shouldUseMemory(),source:"NEGATED_CHECK"});return{succeedImmediately:!1,thoughts:`The element described does not exist on the page: ${b.thoughts}`,urlAfterCommand:this.browser.url(),afterScreenshotOverride:b.afterScreenshotOverride}}finally{E.cache?.memory&&ls(n,E.cache?.memory.traces,a)}}let f=await kR({command:n,tracer:t,timeoutMs:m,targetingWrapper:E=>this.wrapElementTargetingCommand(E),fixtures:this.getControllerFixtures(e),disableCache:i});return{fail:!f.success,data:f.data,elementInteracted:f.elementInteractedDisplayString,thoughts:f.err?.message??f.thoughts??`Element assertion ${f.success?"succeeded":"failed"}.`,succeedImmediately:!1,urlAfterCommand:this.browser.url()}}case"PAGE_CHECK":{let m=await fr({action:async()=>HR({assertion:n.assertion,browser:this.browser,logger:a,timeout:n.timeout,signal:this.executeAbortController.signal,autoExpandIframes:!!this.browser.userBrowserSettings.autoExpandIframes}),frameConfig:n.iframeUrl?{type:"url",url:n.iframeUrl}:void 0,browser:this.browser,logger:a});return{fail:!m.success,data:m.data,thoughts:m.success?"Page assertion passed.":m.err?.message??`Page assertion still failing after ${n.timeout} seconds.`,urlAfterCommand:this.browser.url(),succeedImmediately:!1}}case"REGISTER_REQUEST_LISTENER":{let m=new zn(n.requestMatcher),h=this.browser.registerRequestListener(m);return this.registeredListeners[n.key]=h.then(async f=>await vg(f)).catch(f=>{a.error({err:f},"Failed to get request listener response")}),{succeedImmediately:!1,urlAfterCommand:this.browser.url()}}case"AWAIT_LISTENER":{let m=this.registeredListeners[n.key];if(!m)throw new x("ActionFailureError",`No listener registered with key: ${n.key}`);let h=n.timeout??10;return{data:await z(m,{milliseconds:h*1e3,message:`Request listener timed out after ${h} seconds`}),succeedImmediately:!1,urlAfterCommand:this.browser.url()}}case"RECORD_REQUESTS":{let m=new zn(n.requestMatcher);return this.recordedRequests[n.key]={},this.browser.registerRequestRecorder(n.key,{matches:h=>m.matches({url:h.request.url,method:h.request.method}),onRequestStart:(h,f)=>{this.recordedRequests[n.key][h]=nu(f)},onRequestComplete:(h,f)=>{this.recordedRequests[n.key]?.[h]&&(this.recordedRequests[n.key][h]=nu(f))}}),{succeedImmediately:!1,urlAfterCommand:this.browser.url()}}case"GET_RECORDED_REQUESTS":{let m=this.recordedRequests[n.key];if(!m)throw new x("ActionFailureError",`No recorder registered with key: ${n.key}`);return delete this.recordedRequests[n.key],{data:Object.values(m),succeedImmediately:!1,urlAfterCommand:this.browser.url()}}case"SET_HEADER":{let m;return n.requestMatcher&&(m=new zn(n.requestMatcher)),this.browser.setHeader(n.name,n.value,m),{succeedImmediately:!1,urlAfterCommand:this.browser.url()}}case"MOCK_ROUTE":return{data:{key:this.browser.registerMock(n.key,new zn(n.requestMatcher),async(h,f)=>{let E=await Wr({orgId:this.orgId,code:n.responseGenerator,fragment:!1,context:o,timeoutMs:void 0,logger:a,localTools:this.localCodeEvalTools,mock:{request:h,response:f},disallowVariableUpdates:!0,responseSerialization:"RESPONSE"}),b=Zy.parse(E);return new Response(b.body,{status:b.status,headers:b.headers})},n.fetchOriginalResponse??!1)},succeedImmediately:!1,urlAfterCommand:this.browser.url()};case"REMOVE_ROUTE_MOCK":return this.browser.removeMock(n.key),{succeedImmediately:!1,urlAfterCommand:this.browser.url()};case"OFFLINE_MODE":return await this.browser.setOfflineMode(n.enable),{succeedImmediately:!1,urlAfterCommand:this.browser.url()};default:return(m=>{throw"If Typescript complains about the line below, you missed a case or break in the switch above"})(n)}return{succeedImmediately:!1,urlAfterCommand:this.browser.url()}}async getReverseMappedDescription({browserState:e,targetId:t,disableCache:n,screenshot:o}){return(await this.generator.getReverseMappedDescription({browserState:e,target:t,screenshot:o},{disableCache:n,abortSignal:this.executeAbortController.signal,loggerTags:ye(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 cu({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:ye(this.logger)})}async getFailureRecoveryPlan(e){return this.generator.getFailureRecoveryPlan(e,{disableCache:!0,abortSignal:this.executeAbortController.signal,loggerTags:ye(this.logger)})}};import{cloneDeep as s1}from"lodash-es";import KR from"truncate-json";var WR=1e3,jR=5e6,l1=5*1024*1024;function YR(r,e){for(let t=0;t<r.length;t++){let n=r[t];try{if(n.data){let{jsonString:o}=KR(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":$R(n);break;case"MOBILE_AI_ACTION_STEP":case"MOBILE_MODULE_STEP":$R(n),YR(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 $R(r){if(r.type==="MOBILE_PRESET_STEP"){let e=r.command;"cache"in e&&e.cache&&(e.cache=void 0)}}function qR(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 bu(r,e){let t=s1(r);if(YR(t,e),t.length>WR)return e.error("Database content violation: results too long, truncating before insertion"),t.slice(0,WR);let n=qR(t,e);if(n.length>jR)for(e.error({serializedLength:n.length,resultsArrayLength:t.length},"Database content violation: results too large, truncating before insertion");n.length>jR;)t.pop(),n=qR(t,e);let{jsonString:o}=KR(n,l1);try{return zt.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 c1}from"async_hooks";var Ss=new c1;function u1(r){Ss.enterWith({activeTracers:[r]})}function d1(r,e){let t=Ss.getStore()?.activeTracers;if(!t)return e();t.push(r);try{return e()}finally{t.pop()}}async function p1(r,e){let t=Ss.getStore()?.activeTracers;if(!t)return e();let n=[...t,r];return Ss.run({activeTracers:n},e)}var un={globalAls:Ss,initializeRootTracerContext:u1,withChildTracer:d1,withChildTracerAsync:p1};var Mo=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 un.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 un.withChildTracerAsync(i,()=>z(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 un.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:{}},i=n[0]??void 0;Object.assign(o,i??{}),this.addSpan(o);let a;try{i?.signal||i?.timeoutMs?a=await z(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})`:""}`}):a=await t(o),o.endTime=Date.now(),o.durationMs=o.endTime-o.startTime}catch(s){throw o.error=s instanceof Error?s.message:String(s),o.endTime=Date.now(),o.durationMs=o.endTime-o.startTime,s}return a}getRootSpan(){return this.finished||this.finish(),{type:"SECTION",name:"root step span",startTime:this.startTime,endTime:this.endTime,subSpans:this.spans,attributes:{},durationMs:this.endTime?this.endTime-this.startTime:void 0}}};function ee(){let r=un.globalAls.getStore()?.activeTracers,e;return!r||r.length===0?e=void 0:e=r[r.length-1],e||new Mo}async function XR(r){let{driver:e,abortSignal:t,logger:n,packageName:o}=r,i;try{i=await z(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=m1(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 m1(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 ys(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=ys(i);a.trim()&&e.push(a.trim())}return e.join(" ").trim()}import{mkdirSync as k1}from"fs";import{tmpdir as U1}from"os";import ox from"path";import{diff as N1}from"deep-object-diff";import{cloneDeep as D1}from"lodash-es";import ex from"fontoxpath";import g1 from"@prettier/plugin-xml";import h1 from"prettier";import{DOMParser as f1,XMLSerializer as S1}from"slimdom";var y1=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 bs(r){let e=r.toLowerCase();return e.endsWith("webview")||y1.has(e)}function b1(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 E1=new Set(["index","package","a11y-important","screen-reader-focusabl"]),T1=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"]),v1=new Set(["text","hint"]),A1=new Set(["live-region","drawing-order"]),w1=new Set(["displayed","enabled"]);function C1(r,e){let t={};for(let[n,o]of Object.entries(e))E1.has(n)||n==="class"&&r===o||n==="focusable"&&o==="true"&&e.clickable==="true"||T1.has(n)&&o==="false"||v1.has(n)&&o===""||w1.has(n)&&o==="true"||A1.has(n)&&o==="0"||n!=="id"&&(t[n]=o);return t}function JR(r,e,t){let{prunedDocument:n,idToElement:o,prunedIdToElement:i,idCounter:a,opts:s}=r,c=a.value++;t.setAttribute("id",String(c));let l={};for(let p of e.attributes){let g=p.name,m=p.value;m!=null&&(l[g]=String(m))}let u=C1(e.tagName,l);for(let[p,g]of Object.entries(u))t.setAttribute(p,g);if(o.set(c,e),i.set(c,t),bs(e.tagName)){let p=s?.injectedWebviewContent??"";if(s?.removeWebviewContent){for(;t.firstChild;)t.removeChild(t.firstChild);return}else if(!s?.disableMomenticAccessibilityTree&&p.trim().length>0){for(;t.firstChild;)t.removeChild(t.firstChild);p.trim().length>0&&t.appendChild(n.createCDATASection(`
4346
4346
  ${p}
4347
- `));return}}let d=Array.from(e.childNodes??[]);for(let p of d){let g=p.nodeType;if(g===3){let m=p.nodeValue;m&&m.trim().length>0&&t.appendChild(n.createTextNode(m));continue}if(g===1){let m=p;if(!M1(m,s?.viewportBounds))continue;let h=n.createElement(b1(m.tagName));JR(r,m,h),t.appendChild(h)}}}function R1(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;JR(a,e,s);let c=new S1().serializeToString(o);return{prunedDocument:o,prunedIdToElement:i,xml:c}}async function QR(r,e){let t=new f1,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}=R1(t,i,o,e);return{xml:await h1.format(c,{parser:"xml",plugins:[g1],printWidth:120,tabWidth:1,singleAttributePerLine:!1}),originalXml:r,document:n,idToElement:o,prunedDocument:a,prunedIdToElement:s}}function x1(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 Eu(r,e){let t=r.idToElement.get(e);if(t)return x1(t)}function qg(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 _o(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 M1(r,e){if(!e)return!0;let t=_o(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 ZR(r,e){if(r&&!(!e||e.length===0))return Object.fromEntries(e.map(t=>[t,r.getAttribute(t)]).filter(([,t])=>t!==null))}function tx({requirements:r,element:e}){let t;if((r?.positionSpecificity||r?.shapeSpecificity)&&(t=_o(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:ZR(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 nx({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=_o(n);if(!o)throw new Error(`Node ${r.id} has no bounding box: ${n.outerHTML}`);let i=Eu(t.graph,r.id)??"",a=qg(t.graph,r.id)??"",s=tx({requirements:r.requirements,element:n}),c=[];r.additionalElements&&(c=r.additionalElements.map(({id:u,requirements:d})=>{let p=t.graph.idToElement.get(u);if(!p)return;let g=Eu(t.graph,u);return g?{xPath:g,requirements:tx({requirements:d,element:p})}:void 0}).filter(u=>!!u));let l;return bs(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},{target:l,resolvedNode:n}}var _1=.1,P1=.25;function Tu(r,e,t,n){let o=Math.abs(e-t);switch(r){case"precise":return o<=n;case"narrow":return o<=Math.abs(e)*_1;case"broad":return o<=Math.abs(e)*P1;case"irrelevant":return!0}}function I1(r,e){let t=e.x2-e.x1,n=(e.x1+e.x2)/2,o=(r[0]+r[2])/2;if(!Tu(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 Tu(e.tolerance,a,s,Math.min(1,i))}function O1(r,e){return Tu(e.tolerance,e.width,r[2]-r[0],Math.min(1,e.width))?Tu(e.tolerance,e.height,r[3]-r[1],Math.min(1,e.height)):!1}var rx=(r,e,t)=>{if(!e)return;let{requiredAttributes:n,requiredText:o,requiredBounds:i,position:a,shape:s}=e;if(o!==void 0){let c=ys(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&&!I1(t.newElementBounds,a))throw new Error(`ActionFailureError: Position mismatch: expected ${JSON.stringify(a)}, got ${JSON.stringify(t.newElementBounds)}`);if(s&&t&&!O1(t.newElementBounds,s))throw new Error(`ActionFailureError: Shape mismatch: expected ${JSON.stringify(s)}, got ${JSON.stringify(t.newElementBounds)}`)};async function vu(r){let{target:e,domState:t}=r,{graph:n}=t,{document:o}=n,i=ee();if(e.type==="WEBVIEW")return L1(e,r);let a=ex.evaluateXPathToFirstNode(e.xPath,o,null,null);if(!a)throw new Error(`ActionFailureError: Could not resolve cached target via XPath: ${e.xPath}`);if(e.requiredRelatedElements){let p=e.requiredRelatedElements;i.startSection("Validate related elements are similar enough to past runs",()=>{for(let g of p){let m=ex.evaluateXPathToFirstNode(g.xPath,o);if(!m)throw new Error(`ActionFailureError: Required related element not found for XPath: ${g.xPath}`);rx(m,g.requirements)}})}let s=_o(a);if(!s)throw new Error("ActionFailureError: Resolved native element has no bounding box");rx(a,e.requirements,{targetBounds:e.bounds,newElementBounds:s});let c;for(let[p,g]of n.idToElement.entries())if(g===a){c=p;break}let l=e.elementOnlySerializedXml,u=e.xPath;return c!==void 0&&(l=qg(n,c)??l,u=Eu(n,c)??u),{resolvedTarget:{...e,resolvedNode:a,bounds:s,elementOnlySerializedXml:l,xPath:u}}}async function L1(r,e){let{stateManager:t,logger:n,signal:o}=e,i=ee(),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 Di(r){let{command:e,cacheKey:t="cache",targetName:n="target",updatedCache:o}=r;El(e)&&(e[t]={...e[t],[n]:ti.parse(o)},r.updatedWithAI&&(e[t].updatedAt=new Date))}function Au(r){if(r.type==="WEBVIEW")return{type:"WEBVIEW",resolvedDescription:r.resolvedDescription,xPath:r.xPath,browserCache:r.browserCache};let{resolvedNode:e,...t}=r;return{...t}}var Je=class{driver;generator;stateManager;logger;fixtures;aborter;orgId;constructor(e){this.stateManager=e.stateManager,this.generator=e.generator,this.driver=e.driver,this.logger=e.logger,this.fixtures=e.fixtures,this.aborter=e.aborter,this.orgId=e.orgId}async findElement({description:e,tracer:t,skipFetchingFullWebviewContent:n=!1,removeWebviewContent:o=!1}){await this.stateManager.waitForScreenshotStability({timeoutMs:5e3,signal:this.aborter.controller?.signal,reason:"Waiting for stability before locating an element with AI"});let i=await t.startAsyncSection("Get emulator state",async()=>{let d=await this.stateManager.getDomState({skipFetchingFullWebviewContent:n,removeWebviewContent:o}),p=await this.stateManager.getCurrentScreenshotPngString();return{emulatorState:d,screenshot:p}}),a;try{a=await t.startAsyncSpan("AI_LOCATOR_CALL",async d=>{let p=await this.generator.getElementLocation({description:e,screenXml:i.emulatorState.graph.xml,screenshot:i.screenshot},{logger:this.logger,loggerTags:ye(this.logger),abortSignal:this.aborter.controller?.signal});return d.result=p,p})}catch(d){throw this.throwIfAborted(),this.logger.error({err:d},"Failed to locate element"),new Error(`ActionFailureError: Failed to locate element: ${d instanceof Error?d.message:d}`)}if(a.id===-1)throw new En(a.thoughts??"No matching element found");let{target:s,resolvedNode:c}=nx({aiResponse:a,description:e,emulatorState:i.emulatorState});if(s.type==="NATIVE")return t.addSpan({type:"TARGET_RESOLUTION",startTime:Date.now(),endTime:Date.now(),result:{serializedElement:s.elementOnlySerializedXml},attributes:{}}),{resolvedTarget:{...s,resolvedNode:c},thoughts:a.thoughts};let{browserLocateResult:l,browserController:u}=await t.startAsyncSpan("TARGET_RESOLUTION",async d=>{let p=await this.stateManager.getActiveWebview();if(!p||!p.browserController)throw new Error("No browser controller is attached to the requested webview");let g=await p.browserController.locateElement({description:e,disableCache:!1,logger:this.logger});return d.result={serializedElement:g.target.nodeOnlySerializedHtml??"Unknown HTML element in webview"},{browserLocateResult:g,browserController:p.browserController}});return{resolvedTarget:{...s,controller:u,resolution:l.resolution,browserCache:l.target},thoughts:l.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;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=e.retriesWithAI??1,g=!1,m=D1(d),h;if(o.disableCache&&(this.logger.debug({command:o},"Cache explicitly disabled for command"),g=!0,m=void 0),s&&(g=!0,m=void 0),m&&m?.resolvedDescription!==n&&(this.logger.info({description:n,cacheDescription:m?.resolvedDescription},"Cache description mismatch, clearing it automatically"),g=!0,m=void 0),!m){p--,this.logger.info({description:n,cacheBustedBeforeAction:g},"Prompting AI for a new element location");let E=await this.findElement({description:n,tracer:c,skipFetchingFullWebviewContent:l,removeWebviewContent:u});h=E.thoughts;let b=await t(E.resolvedTarget);return Di({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 R=>{let{resolvedTarget:v}=await vu({target:m,domState:f,stateManager:this.stateManager,logger:this.logger}),M=Au(v),A=N1(m,M);return A&&Object.keys(A).length>0&&this.logger.info({cacheDiffs:A},"Successfully resolved target with cache"),R.attributes.serializedElement=v.type==="WEBVIEW"?v.browserCache?.nodeOnlySerializedHtml??"Unknown HTML element in webview":v.elementOnlySerializedXml,{resolvedTarget:v,updatedCache:M}}),C=await t(E);return Di({command:o,cacheKey:i,targetName:a,updatedCache:b,updatedWithAI:!1}),m.type!=="WEBVIEW"&&Tt.increment("cache_target_resolution_v2",1,["outcome:hit","platform:native",`hasRequirements:${!!m.requirements}`,`hasAdditionalElements:${!!m.requiredRelatedElements?.length}`,`orgId:${this.orgId}`,"cliVersion:0.12.0"]),{result:C,thoughts:"Successfully executed preset action with cache."}}catch(E){if(m.type!=="WEBVIEW"&&Tt.increment("cache_target_resolution_v2",1,["outcome:miss","platform:native",`hasRequirements:${!!m.requirements}`,`hasAdditionalElements:${!!m.requiredRelatedElements?.length}`,`orgId:${this.orgId}`,"cliVersion:0.12.0"]),this.throwIfAborted(),p>0)return this.logger.warn({err:E},"Failed to resolve target cache, retrying with AI"),this.wrapTargetingAction({...e,cacheIsInvalidAfterResolution:!0,retriesWithAI:p-1});throw new Error(`ActionFailureError: ${E instanceof Error?E.message:E}`,{cause:E})}}constructPerformerParams(){return{stateManager:this.stateManager,generator:this.generator,driver:this.driver,logger:this.logger,fixtures:this.fixtures,aborter:this.aborter,orgId:this.orgId}}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}};function F1(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 ki=class extends Je{async tapOnAbsoluteCoordinates(e){let t=e.x,n=e.y;if(this.logger.info({x:t,y:n},"Tap at coordinates"),e.longPress)return await this.driver.executeScript("mobile: longClickGesture",[{x:t,y:n,duration:e.longPressDurationMs??2e3}]);if(e.doubleTap){await this.driver.tap({x:t,y:n});let o=e.doubleTapDelayMs??100;await new Promise(i=>setTimeout(i,o))}await this.driver.tap({x:t,y:n})}async tapOnNativeTarget(e,t){let[n,o,i,a]=e.bounds,s=i-n,c=a-o,l=t?.relativePosition?.x??s/2,u=t?.relativePosition?.y??c/2;l=Math.max(0,Math.min(l,s)),u=Math.max(0,Math.min(u,c));let d=n+l,p=o+u;return await this.tapOnAbsoluteCoordinates({x:d,y:p,...t}),{x:d,y:p}}async tapOnWebviewTarget(e,t){let{controller:n}=e;return(await n.browser.click(e.resolution,{createIsolatedFolder:()=>{let i=Math.random().toString(36).substring(4),a=ox.join(U1(),"momentic","downloads"),s=ox.join(a,this.orgId,i);return k1(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 ee().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=ee(),n=F1(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 Vn=class extends Je{async doPress({keycode:e,longPress:t}){await ee().startAsyncSpan("EMULATOR_INTERACTION",async()=>this.driver.executeScript("mobile: pressKey",[{keycode:e,isLongPress:t}]),{name:"Send key events to emulator"})}};var ix=25,wu=class extends Je{async doType(e){let t=ee();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 ee().startAsyncSpan("EMULATOR_INTERACTION",async o=>{o.withinWebview=!0;let i={clearContent:e.clearContent,forceClearContent:e.forceClearContent,delay:e.keyPressDelayMs??ix};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 ki(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=ee(),n=e.keyPressDelayMs??ix;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=ee();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 Vn(this.constructPerformerParams()).doPress({keycode:67})}};import Yt from"zod";var ax=.8,Wn=.2,B1=Yt.object({navigationBar:Yt.object({visible:Yt.boolean(),x:Yt.number(),y:Yt.number(),width:Yt.number(),height:Yt.number()}),statusBar:Yt.object({visible:Yt.boolean(),x:Yt.number(),y:Yt.number(),width:Yt.number(),height:Yt.number()})}),Ui=class extends Je{async getHardcodedScrollableElementBounds(e,t){let n;switch(e.type){case"SCREEN":n=this.getInsetBoundsFromViewport(t);break;case"OPEN_APP":try{let o=B1.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*Wn),n=Math.floor(e.height*Wn);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*Wn),l=Math.floor(s*Wn);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=ee();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=>ee().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*Wn),s=Math.floor(i*Wn);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*Wn),u=Math.floor(c.height*Wn),d=Math.max(1,c.width-l*2),p=Math.max(1,c.height-u*2),g={x:c.x+l+d/2,y:c.y+u+p/2},m=(s?p:d)*(t.viewportPercent??ax)*(s?t.direction==="down"?1:-1:t.direction==="right"?1:-1);e.attributes.startPoint=g,e.attributes.scrollPixelAmount=m,await o.browser.mouseDragUsingVisualCoordinates(s?0:m,s?m:0,10,t.durationMs,g)}async swipeByAbsoluteCoordinates({span:e,direction:t,percent:n=ax,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 G1 from"pixelmatch";import{_android as V1,chromium as W1}from"playwright";import{PNG as px}from"pngjs";import{z as Ge}from"zod";var sx=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()}),lx=Ge.object({description:Ge.string(),devtoolsFrontendUrl:Ge.string(),id:Ge.string(),title:Ge.string(),type:Ge.string(),url:Ge.string(),webSocketDebuggerUrl:Ge.string()}),cx=Ge.object({proc:Ge.string(),webview:Ge.string(),webviewName:Ge.string()}),ux=Ge.array(cx.extend({info:sx.optional(),pages:Ge.array(lx).optional()})),EPe=Ge.array(cx.extend({info:sx,pages:Ge.array(lx)}));function Kg(r,e,t=.01){let n=Buffer.from(r,"base64"),o=Buffer.from(e,"base64"),i=px.sync.read(n),a=px.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 G1(i.data,a.data,l,s,c,{threshold:t})/(s*c)*100}var Cu=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,p;if(l)p=l;else{let m=(await V1.devices()).filter(h=>h._initializer?.serial?.endsWith(a.toString())||h._initializer?.serial?.endsWith((a-1).toString()));if(t.warn({devices:m.map(h=>({serial:h._initializer?.serial,model:h._initializer?.model}))},"No playwright device provided, using ADB to find device"),m.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(m.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.`);p=m[0]}return new r({driver:e,context:d,logger:t,device:p,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=ee(),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 ee().startAsyncSpan("WAIT_FOR_SCREENSHOT_STABILITY",async i=>{i.attributes.reason=n;let a=Date.now(),s,c=!1;for(;Date.now()-a<e;){if(t?.throwIfAborted(),!s){s=await this.getRawScreenshotBase64();continue}let l=await this.getRawScreenshotBase64();if(Kg(s,l)<=o){c=!0;break}s=l,await W(250,t)}c||(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");(bs(a.tagName)||n==="com.android.chrome"&&s==="Web View"&&a.tagName.toLowerCase().startsWith("frame"))&&o.push({id:i,originalElement:a,bounds:_o(a)})}return o}async getActiveWebviewContent(){let e=await this.getActiveWebview();if(!e||!e.browserController)return;this.throwIfAborted();let t=e.browserController;return(await ee().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 ee().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 QR(a,{injectedWebviewContent:n,disableMomenticAccessibilityTree:this.options.disableMomenticAccessibilityTree,removeWebviewContent:e?.removeWebviewContent,viewportBounds:i}),context:this.currentContext}},{timeoutMs:15e3})}async getPageSource(){return await ee().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 ee().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 ee().startAsyncSpan("EMULATOR_READ_STATE",async()=>{let t=await this.driver.execute("mobile: getContexts");this.aborter.controller?.signal.throwIfAborted();let n;try{n=ux.parse(t)}catch(o){throw new Error(`Failed to parse contexts. Original error:
4347
+ `));return}}let d=Array.from(e.childNodes??[]);for(let p of d){let g=p.nodeType;if(g===3){let m=p.nodeValue;m&&m.trim().length>0&&t.appendChild(n.createTextNode(m));continue}if(g===1){let m=p;if(!M1(m,s?.viewportBounds))continue;let h=n.createElement(b1(m.tagName));JR(r,m,h),t.appendChild(h)}}}function R1(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;JR(a,e,s);let c=new S1().serializeToString(o);return{prunedDocument:o,prunedIdToElement:i,xml:c}}async function QR(r,e){let t=new f1,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}=R1(t,i,o,e);return{xml:await h1.format(c,{parser:"xml",plugins:[g1],printWidth:120,tabWidth:1,singleAttributePerLine:!1}),originalXml:r,document:n,idToElement:o,prunedDocument:a,prunedIdToElement:s}}function x1(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 Eu(r,e){let t=r.idToElement.get(e);if(t)return x1(t)}function qg(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 _o(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 M1(r,e){if(!e)return!0;let t=_o(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 ZR(r,e){if(r&&!(!e||e.length===0))return Object.fromEntries(e.map(t=>[t,r.getAttribute(t)]).filter(([,t])=>t!==null))}function tx({requirements:r,element:e}){let t;if((r?.positionSpecificity||r?.shapeSpecificity)&&(t=_o(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:ZR(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 nx({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=_o(n);if(!o)throw new Error(`Node ${r.id} has no bounding box: ${n.outerHTML}`);let i=Eu(t.graph,r.id)??"",a=qg(t.graph,r.id)??"",s=tx({requirements:r.requirements,element:n}),c=[];r.additionalElements&&(c=r.additionalElements.map(({id:u,requirements:d})=>{let p=t.graph.idToElement.get(u);if(!p)return;let g=Eu(t.graph,u);return g?{xPath:g,requirements:tx({requirements:d,element:p})}:void 0}).filter(u=>!!u));let l;return bs(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},{target:l,resolvedNode:n}}var _1=.1,P1=.25;function Tu(r,e,t,n){let o=Math.abs(e-t);switch(r){case"precise":return o<=n;case"narrow":return o<=Math.abs(e)*_1;case"broad":return o<=Math.abs(e)*P1;case"irrelevant":return!0}}function I1(r,e){let t=e.x2-e.x1,n=(e.x1+e.x2)/2,o=(r[0]+r[2])/2;if(!Tu(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 Tu(e.tolerance,a,s,Math.min(1,i))}function O1(r,e){return Tu(e.tolerance,e.width,r[2]-r[0],Math.min(1,e.width))?Tu(e.tolerance,e.height,r[3]-r[1],Math.min(1,e.height)):!1}var rx=(r,e,t)=>{if(!e)return;let{requiredAttributes:n,requiredText:o,requiredBounds:i,position:a,shape:s}=e;if(o!==void 0){let c=ys(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&&!I1(t.newElementBounds,a))throw new Error(`ActionFailureError: Position mismatch: expected ${JSON.stringify(a)}, got ${JSON.stringify(t.newElementBounds)}`);if(s&&t&&!O1(t.newElementBounds,s))throw new Error(`ActionFailureError: Shape mismatch: expected ${JSON.stringify(s)}, got ${JSON.stringify(t.newElementBounds)}`)};async function vu(r){let{target:e,domState:t}=r,{graph:n}=t,{document:o}=n,i=ee();if(e.type==="WEBVIEW")return L1(e,r);let a=ex.evaluateXPathToFirstNode(e.xPath,o,null,null);if(!a)throw new Error(`ActionFailureError: Could not resolve cached target via XPath: ${e.xPath}`);if(e.requiredRelatedElements){let p=e.requiredRelatedElements;i.startSection("Validate related elements are similar enough to past runs",()=>{for(let g of p){let m=ex.evaluateXPathToFirstNode(g.xPath,o);if(!m)throw new Error(`ActionFailureError: Required related element not found for XPath: ${g.xPath}`);rx(m,g.requirements)}})}let s=_o(a);if(!s)throw new Error("ActionFailureError: Resolved native element has no bounding box");rx(a,e.requirements,{targetBounds:e.bounds,newElementBounds:s});let c;for(let[p,g]of n.idToElement.entries())if(g===a){c=p;break}let l=e.elementOnlySerializedXml,u=e.xPath;return c!==void 0&&(l=qg(n,c)??l,u=Eu(n,c)??u),{resolvedTarget:{...e,resolvedNode:a,bounds:s,elementOnlySerializedXml:l,xPath:u}}}async function L1(r,e){let{stateManager:t,logger:n,signal:o}=e,i=ee(),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 Di(r){let{command:e,cacheKey:t="cache",targetName:n="target",updatedCache:o}=r;El(e)&&(e[t]={...e[t],[n]:ti.parse(o)},r.updatedWithAI&&(e[t].updatedAt=new Date))}function Au(r){if(r.type==="WEBVIEW")return{type:"WEBVIEW",resolvedDescription:r.resolvedDescription,xPath:r.xPath,browserCache:r.browserCache};let{resolvedNode:e,...t}=r;return{...t}}var Je=class{driver;generator;stateManager;logger;fixtures;aborter;orgId;constructor(e){this.stateManager=e.stateManager,this.generator=e.generator,this.driver=e.driver,this.logger=e.logger,this.fixtures=e.fixtures,this.aborter=e.aborter,this.orgId=e.orgId}async findElement({description:e,tracer:t,skipFetchingFullWebviewContent:n=!1,removeWebviewContent:o=!1}){await this.stateManager.waitForScreenshotStability({timeoutMs:5e3,signal:this.aborter.controller?.signal,reason:"Waiting for stability before locating an element with AI"});let i=await t.startAsyncSection("Get emulator state",async()=>{let d=await this.stateManager.getDomState({skipFetchingFullWebviewContent:n,removeWebviewContent:o}),p=await this.stateManager.getCurrentScreenshotPngString();return{emulatorState:d,screenshot:p}}),a;try{a=await t.startAsyncSpan("AI_LOCATOR_CALL",async d=>{let p=await this.generator.getElementLocation({description:e,screenXml:i.emulatorState.graph.xml,screenshot:i.screenshot},{logger:this.logger,loggerTags:ye(this.logger),abortSignal:this.aborter.controller?.signal});return d.result=p,p})}catch(d){throw this.throwIfAborted(),this.logger.error({err:d},"Failed to locate element"),new Error(`ActionFailureError: Failed to locate element: ${d instanceof Error?d.message:d}`)}if(a.id===-1)throw new En(a.thoughts??"No matching element found");let{target:s,resolvedNode:c}=nx({aiResponse:a,description:e,emulatorState:i.emulatorState});if(s.type==="NATIVE")return t.addSpan({type:"TARGET_RESOLUTION",startTime:Date.now(),endTime:Date.now(),result:{serializedElement:s.elementOnlySerializedXml},attributes:{}}),{resolvedTarget:{...s,resolvedNode:c},thoughts:a.thoughts};let{browserLocateResult:l,browserController:u}=await t.startAsyncSpan("TARGET_RESOLUTION",async d=>{let p=await this.stateManager.getActiveWebview();if(!p||!p.browserController)throw new Error("No browser controller is attached to the requested webview");let g=await p.browserController.locateElement({description:e,disableCache:!1,logger:this.logger});return d.result={serializedElement:g.target.nodeOnlySerializedHtml??"Unknown HTML element in webview"},{browserLocateResult:g,browserController:p.browserController}});return{resolvedTarget:{...s,controller:u,resolution:l.resolution,browserCache:l.target},thoughts:l.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;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=e.retriesWithAI??1,g=!1,m=D1(d),h;if(o.disableCache&&(this.logger.debug({command:o},"Cache explicitly disabled for command"),g=!0,m=void 0),s&&(g=!0,m=void 0),m&&m?.resolvedDescription!==n&&(this.logger.info({description:n,cacheDescription:m?.resolvedDescription},"Cache description mismatch, clearing it automatically"),g=!0,m=void 0),!m){p--,this.logger.info({description:n,cacheBustedBeforeAction:g},"Prompting AI for a new element location");let E=await this.findElement({description:n,tracer:c,skipFetchingFullWebviewContent:l,removeWebviewContent:u});h=E.thoughts;let b=await t(E.resolvedTarget);return Di({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 R=>{let{resolvedTarget:v}=await vu({target:m,domState:f,stateManager:this.stateManager,logger:this.logger}),M=Au(v),A=N1(m,M);return A&&Object.keys(A).length>0&&this.logger.info({cacheDiffs:A},"Successfully resolved target with cache"),R.attributes.serializedElement=v.type==="WEBVIEW"?v.browserCache?.nodeOnlySerializedHtml??"Unknown HTML element in webview":v.elementOnlySerializedXml,{resolvedTarget:v,updatedCache:M}}),C=await t(E);return Di({command:o,cacheKey:i,targetName:a,updatedCache:b,updatedWithAI:!1}),m.type!=="WEBVIEW"&&Tt.increment("cache_target_resolution_v2",1,["outcome:hit","platform:native",`hasRequirements:${!!m.requirements}`,`hasAdditionalElements:${!!m.requiredRelatedElements?.length}`,`orgId:${this.orgId}`,"cliVersion:0.12.1"]),{result:C,thoughts:"Successfully executed preset action with cache."}}catch(E){if(m.type!=="WEBVIEW"&&Tt.increment("cache_target_resolution_v2",1,["outcome:miss","platform:native",`hasRequirements:${!!m.requirements}`,`hasAdditionalElements:${!!m.requiredRelatedElements?.length}`,`orgId:${this.orgId}`,"cliVersion:0.12.1"]),this.throwIfAborted(),p>0)return this.logger.warn({err:E},"Failed to resolve target cache, retrying with AI"),this.wrapTargetingAction({...e,cacheIsInvalidAfterResolution:!0,retriesWithAI:p-1});throw new Error(`ActionFailureError: ${E instanceof Error?E.message:E}`,{cause:E})}}constructPerformerParams(){return{stateManager:this.stateManager,generator:this.generator,driver:this.driver,logger:this.logger,fixtures:this.fixtures,aborter:this.aborter,orgId:this.orgId}}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}};function F1(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 ki=class extends Je{async tapOnAbsoluteCoordinates(e){let t=e.x,n=e.y;if(this.logger.info({x:t,y:n},"Tap at coordinates"),e.longPress)return await this.driver.executeScript("mobile: longClickGesture",[{x:t,y:n,duration:e.longPressDurationMs??2e3}]);if(e.doubleTap){await this.driver.tap({x:t,y:n});let o=e.doubleTapDelayMs??100;await new Promise(i=>setTimeout(i,o))}await this.driver.tap({x:t,y:n})}async tapOnNativeTarget(e,t){let[n,o,i,a]=e.bounds,s=i-n,c=a-o,l=t?.relativePosition?.x??s/2,u=t?.relativePosition?.y??c/2;l=Math.max(0,Math.min(l,s)),u=Math.max(0,Math.min(u,c));let d=n+l,p=o+u;return await this.tapOnAbsoluteCoordinates({x:d,y:p,...t}),{x:d,y:p}}async tapOnWebviewTarget(e,t){let{controller:n}=e;return(await n.browser.click(e.resolution,{createIsolatedFolder:()=>{let i=Math.random().toString(36).substring(4),a=ox.join(U1(),"momentic","downloads"),s=ox.join(a,this.orgId,i);return k1(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 ee().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=ee(),n=F1(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 Vn=class extends Je{async doPress({keycode:e,longPress:t}){await ee().startAsyncSpan("EMULATOR_INTERACTION",async()=>this.driver.executeScript("mobile: pressKey",[{keycode:e,isLongPress:t}]),{name:"Send key events to emulator"})}};var ix=25,wu=class extends Je{async doType(e){let t=ee();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 ee().startAsyncSpan("EMULATOR_INTERACTION",async o=>{o.withinWebview=!0;let i={clearContent:e.clearContent,forceClearContent:e.forceClearContent,delay:e.keyPressDelayMs??ix};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 ki(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=ee(),n=e.keyPressDelayMs??ix;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=ee();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 Vn(this.constructPerformerParams()).doPress({keycode:67})}};import Yt from"zod";var ax=.8,Wn=.2,B1=Yt.object({navigationBar:Yt.object({visible:Yt.boolean(),x:Yt.number(),y:Yt.number(),width:Yt.number(),height:Yt.number()}),statusBar:Yt.object({visible:Yt.boolean(),x:Yt.number(),y:Yt.number(),width:Yt.number(),height:Yt.number()})}),Ui=class extends Je{async getHardcodedScrollableElementBounds(e,t){let n;switch(e.type){case"SCREEN":n=this.getInsetBoundsFromViewport(t);break;case"OPEN_APP":try{let o=B1.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*Wn),n=Math.floor(e.height*Wn);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*Wn),l=Math.floor(s*Wn);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=ee();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=>ee().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*Wn),s=Math.floor(i*Wn);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*Wn),u=Math.floor(c.height*Wn),d=Math.max(1,c.width-l*2),p=Math.max(1,c.height-u*2),g={x:c.x+l+d/2,y:c.y+u+p/2},m=(s?p:d)*(t.viewportPercent??ax)*(s?t.direction==="down"?1:-1:t.direction==="right"?1:-1);e.attributes.startPoint=g,e.attributes.scrollPixelAmount=m,await o.browser.mouseDragUsingVisualCoordinates(s?0:m,s?m:0,10,t.durationMs,g)}async swipeByAbsoluteCoordinates({span:e,direction:t,percent:n=ax,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 G1 from"pixelmatch";import{_android as V1,chromium as W1}from"playwright";import{PNG as px}from"pngjs";import{z as Ge}from"zod";var sx=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()}),lx=Ge.object({description:Ge.string(),devtoolsFrontendUrl:Ge.string(),id:Ge.string(),title:Ge.string(),type:Ge.string(),url:Ge.string(),webSocketDebuggerUrl:Ge.string()}),cx=Ge.object({proc:Ge.string(),webview:Ge.string(),webviewName:Ge.string()}),ux=Ge.array(cx.extend({info:sx.optional(),pages:Ge.array(lx).optional()})),EPe=Ge.array(cx.extend({info:sx,pages:Ge.array(lx)}));function Kg(r,e,t=.01){let n=Buffer.from(r,"base64"),o=Buffer.from(e,"base64"),i=px.sync.read(n),a=px.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 G1(i.data,a.data,l,s,c,{threshold:t})/(s*c)*100}var Cu=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,p;if(l)p=l;else{let m=(await V1.devices()).filter(h=>h._initializer?.serial?.endsWith(a.toString())||h._initializer?.serial?.endsWith((a-1).toString()));if(t.warn({devices:m.map(h=>({serial:h._initializer?.serial,model:h._initializer?.model}))},"No playwright device provided, using ADB to find device"),m.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(m.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.`);p=m[0]}return new r({driver:e,context:d,logger:t,device:p,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=ee(),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 ee().startAsyncSpan("WAIT_FOR_SCREENSHOT_STABILITY",async i=>{i.attributes.reason=n;let a=Date.now(),s,c=!1;for(;Date.now()-a<e;){if(t?.throwIfAborted(),!s){s=await this.getRawScreenshotBase64();continue}let l=await this.getRawScreenshotBase64();if(Kg(s,l)<=o){c=!0;break}s=l,await W(250,t)}c||(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");(bs(a.tagName)||n==="com.android.chrome"&&s==="Web View"&&a.tagName.toLowerCase().startsWith("frame"))&&o.push({id:i,originalElement:a,bounds:_o(a)})}return o}async getActiveWebviewContent(){let e=await this.getActiveWebview();if(!e||!e.browserController)return;this.throwIfAborted();let t=e.browserController;return(await ee().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 ee().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 QR(a,{injectedWebviewContent:n,disableMomenticAccessibilityTree:this.options.disableMomenticAccessibilityTree,removeWebviewContent:e?.removeWebviewContent,viewportBounds:i}),context:this.currentContext}},{timeoutMs:15e3})}async getPageSource(){return await ee().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 ee().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 ee().startAsyncSpan("EMULATOR_READ_STATE",async()=>{let t=await this.driver.execute("mobile: getContexts");this.aborter.controller?.signal.throwIfAborted();let n;try{n=ux.parse(t)}catch(o){throw new Error(`Failed to parse contexts. Original error:
4348
4348
  ${o}
4349
4349
  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 ee().startSection("Run remote Chrome initialization",async(n,o)=>{let i={};o.attributes.timings=i;let a=await hs.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 yu({browser:a,generator:this.fixtures.browserGenerator,logger:this.logger,orgId:this.orgId,storage:this.fixtures.storage,localCodeEvalTools:this.fixtures.localCodeEvalTools,visualDiffScreenshotStorage:new Fl})})}async connectPlaywrightToWebview(e,t){return ee().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 ee().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 W1.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 mx=5,gx=.8,j1=1,Ru=class extends Ui{async executeScrollTo(e){let t=e.target.description,n=e.scrollStepPercent??gx,o=await this.tryUseCachedScrollPosition(e,t);return o||this.searchForElement(e,t,n)}async resolveContainer(e,t){let n=await this.driver.getWindowRect();if(e.type==="CUSTOM_COORDINATES")return{bounds:{left:0,top:0,width:n.width,height:n.height}};if(e.type!=="CUSTOM")return{bounds:await this.getHardcodedScrollableElementBounds(e,n)};let o=ee(),i=e.target.description;if(t){let c=this.getBoundsFromNativeCache(t);return this.logger.info({bounds:c},"Got container bounds from native cache"),{bounds:c,cache:t}}let{resolvedTarget:a}=await this.findElement({description:i,tracer:o});if(a.type!=="NATIVE")throw new Error(`ActionFailureError: Custom scroll container "${i}" resolved to a webview element. Custom containers must be native elements.`);let s=this.getBoundsFromNativeCache(a);return this.logger.info({bounds:s},"Got container bounds from AI"),{bounds:s,cache:a}}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=ee();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=ee(),a=e.scrollStepPercent??gx,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});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}),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 vu({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});a=u.resolvedTarget,s=u.thoughts}catch(u){if(this.logger.warn({err:u},"Failed to find scroll-to target with AI"),u instanceof En)return null;throw u}return a.type==="WEBVIEW"?(await this.scrollWebviewTargetIntoView(a),Di({command:e,updatedCache:Au(a),updatedWithAI:!0}),{success:!0,message:s}):(Di({command:e,updatedCache:{...a,scrollDetails:o},updatedWithAI:!0}),{success:!0,message:s})}async searchForElement(e,t,n){let o=ee(),i=await this.resolveContainer(e.scrollableElement);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<mx;u++){this.throwIfAborted();let d=this.buildScrollDetails(e,a,i.cache),p=await this.tryFindElement({cmd:e,description:t,tracer:n,scrollDetails:d});if(p)return p;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 g=$1(e.scrollableElement);l=await this.scrollByPage({direction:e.direction,containerBounds:s,scrollStepPercent:o,rawCoordinates:g}),a+=e.direction==="down"?c:-c}throw new Error(`ActionFailureError: Could not find element "${t}" after ${mx} 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 ee().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}){if(e===0)return;let a=ee(),s,c,l;if(t.type==="CUSTOM_COORDINATES")s=t.startX,c=t.startY,l=t.deltaPixels;else{let p=(await this.resolveContainer(t,n)).bounds,g=p.height*i,m=this.calculateSwipeCoordinates({containerBounds:p,direction:o,desiredDelta:g});s=m.startX,c=m.startY,l=m.actualDelta}let u=Math.ceil(Math.abs(e)/l);this.logger.debug({pixelDelta:e,direction:o,scrollableElementType:t.type,startX:s,startY:c,maxScrollPerStep:l,numScrolls:u},"scrollByPixelDelta calculated parameters"),await a.startAsyncSpan("EMULATOR_INTERACTION",async d=>{d.attributes.pixelDelta=e,d.attributes.numScrolls=u,d.attributes.maxScrollPerStep=l,d.attributes.startX=s,d.attributes.startY=c;let p=0;for(let g=0;g<u;g++){this.throwIfAborted();let m=Math.abs(e)-p,h=Math.min(l,m);await this.performRawSwipe({startX:s,startY:c,deltaPixels:h,direction:this.invertDirection(o)}),p+=h}},{name:`Scroll ${o} by ${e}px`})}async executeScrollGesture({direction:e,containerBounds:t,scrollStepPercent:n,diffThresholdPercent:o=j1,rawCoordinates:i}){let a=await this.stateManager.getRawScreenshotBase64(),s,c,l;if(i)s=i.startX,c=i.startY,l=i.deltaPixels;else{let g=t.height*n,m=this.calculateSwipeCoordinates({containerBounds:t,direction:e,desiredDelta:g});s=m.startX,c=m.startY,l=m.actualDelta}await this.performRawSwipe({startX:s,startY:c,deltaPixels:l,direction:this.invertDirection(e)});let u=await this.stateManager.getRawScreenshotBase64(),d=Kg(a,u),p=d>o;return this.logger.debug({diffPercent:d,diffThresholdPercent:o,canScrollMore:p,direction:e,actualDelta:l,rawCoordinates:i},"Scroll gesture visual diff result"),p}};function $1(r){if(r.type==="CUSTOM_COORDINATES")return r}import{randomUUID as q1}from"crypto";import Ts from"fs";import{tmpdir as K1}from"os";import Fi from"path";var xu=class extends Je{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 ${Fi.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(Ts.existsSync(n))o=n;else if(Ts.existsSync(Fi.join("/",n)))o=Fi.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{Ts.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=Fi.resolve(e);return this.assertFileExists(n),{localPath:n,cleanup:()=>{}}}throw t}}assertFileExists(e){try{Ts.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=Fi.extname(t)||".apk",o=Fi.join(K1(),`momentic-apk-${q1()}${n}`);return Ts.writeFileSync(o,e),o}};import{existsSync as Y1,readFileSync as X1}from"fs";import J1 from"zod";var Q1=J1.string().url();async function hx(r){if(Q1.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(!Y1(r))throw new Error(`File does not exist at path: ${r}`);return X1(r).toString("base64")}var Mu=class extends Je{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),p=o+a/2,g=i+s/2,m=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:p,y:g},{type:"pointerDown",button:0},{type:"pause",duration:f},{type:"pointerMove",duration:E,x:m,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?.hoverDuration?n.hoverDuration/1e3:void 0,a;n?.dragDuration&&(a=Math.max(1,Math.floor(n.dragDuration/200))),await o.browser.dragAndDrop(e.resolution.locator,t.resolution.locator,{hoverSeconds:i,steps:a})}async executeDragAndDrop({command:e}){let t=ee();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}
4350
4350
  ${c}`}}};import{cloneDeep as fx}from"lodash-es";var _u=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:Lt*1e3})}async isEnabled(e){return await e.isEnabled({timeout:Lt*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)}},Pu=class{async getTextContent(e){return ys(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 Z1=5e3,Iu=class extends Je{async executeElementCheck(e){let t=Date.now(),n=(e.timeout??Lt)*1e3,o=n+1e4,i,a=0,s=500,c=fx(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=fx(c),await W(s,this.abortSignal),s=Math.min(Math.floor(s*1.5),Z1);else return i}let l=await this.executeElementCheckHelper(e,{cacheIsInvalidAfterResolution:!0});return l.success||c&&(e.cache=this.restoreCachePreserveMemory(c,e.cache)),l}restoreCachePreserveMemory(e,t){return t?.target?.memory&&e?.target?.memory&&e.target.memory!==t.target.memory?{...e,target:{...e.target,memory:t.target.memory},updatedAt:t.updatedAt}:e}async executeElementCheckHelper(e,t){let n=ee();if(e.target.type!=="description")throw new Error("UserConfigurationError: x/y targets are not supported for the Element Check step");let o=Fc(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 En||i instanceof bn)?{success:!0}:{success:!1,message:`Failed to evaluate element content assertion: ${i instanceof Error?i.message:`${i}`}`}}}async executeNativeElementCheck(e,t){let n=ee(),{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 Pu,span:a});return a.result=s,s},{name:"Native element check"})}async executeWebviewElementCheck(e,t){let n=ee(),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 _u,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),Vr(i,e.value,e.operation,{negated:!!e.negated,ignoreCase:!1})?{success:!0}:{success:!1,message:`The content ${mr(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(!Vr(i,e.value,e.operation,{negated:!!e.negated,ignoreCase:!1})){let a=mr(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 ${mr(e)}`}}case"ELEMENT_NAME":{let i=await n.getTagName(t);return Vr(i,e.value,e.operation,{negated:!!e.negated,ignoreCase:!0})?{success:!0}:{success:!1,message:`The element tag name ${mr(e)} '${e.value}': ${i}`}}case"ELEMENT_STYLE":{let i=await n.getStyleProperty(t,e.property);if(!Vr(i,e.value,e.operation,{negated:!!e.negated,ignoreCase:!1})){let a=mr(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 eH=5e3,Ou=class extends Je{async executeScreenCheck(e){let{timeout:t}=e,n=Date.now(),o=(t??Lt)*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 W(s,this.abortSignal),s=Math.min(Math.floor(s*1.5),eH);else return c}return await this.executeScreenCheckHelper(e)}async executeScreenCheckHelper(e){return await ee().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 ${Km(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 Su({assertion:e.assertion,logger:this.logger,browser:n,autoExpandIframes:!!n.userBrowserSettings.autoExpandIframes})}};var Lu=class extends Je{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(`
@@ -4386,7 +4386,7 @@ Momentic users value the following:
4386
4386
  ${n.map(o=>o.configFilePath)}`);if(n.length===0)throw new Error("No valid Momentic project file available.");return w.debug(`Found valid project configuration at ${n[0].configFilePath}`),n[0]}async function QH(r){let e=XH(r);if(!e||!e.projects||!e.projects.length)return;let t=e.projects.map(a=>(a.endsWith("/")||(a+="/"),`${a}*${Hi}`)),n=AbortSignal.timeout(2e3),o;try{o=await WH(t,{absolute:!1,cwd:eh(),dotRelative:!1,maxDepth:zu,nodir:!0,signal:n})}catch(a){throw w.error({err:a},`Failed to list the available Momentic projects in the current directory. This usually indicates the 'include' or 'exclude' option in your ${th} is misconfigured.`),a}let i=[];for(let a of o){let s=Po.join(eh(),a),c=rh(s);c&&i.push({configFilePath:s,config:c,rootDir:Bx(s)})}return i}async function ZH(r){if(r){r=Po.resolve(r);let t=rh(r);return t||(console.error(`No valid Momentic project file found at ${r}.`),process.exit(1)),[{config:t,configFilePath:r,rootDir:Po.dirname(r)}]}if(zH(th)){let t=await QH(th);if(t)return t}return JH()}function Gx(r,e){let t=zx.stringify(r);VH(e,t)}import Wx from"fs";import{glob as eG}from"glob";import ws from"path";import tG from"yaml";import{z as Vx}from"zod";var jx=!1,rG=Vx.object({fileType:Vx.nativeEnum(Le)});async function Sr(r,e=!1){let t={project:r,tests:{},modules:{},mobileTests:{},mobileModules:{},duplicateEntities:{}},n=r.config.include??Bu,o=Array.from(r.config.exclude??[]).concat(Ol),i=AbortSignal.timeout(5e3),a;try{a=await eG(n,{absolute:!1,cwd:r.rootDir,ignore:o,dotRelative:!1,maxDepth:zu,nodir:!0,signal:i})}catch(s){throw w.error({err:s},"Failed to list all Momentic files in the current directory. This usually indicates the 'include' and 'exclude' globs are misconfigured in your momentic.config.yaml, or that your machine is severely resource constrained."),new Error("Listing Momentic files timed out after 5 seconds.",{cause:s})}for(let s of a){let c=nG(r.rootDir,s,t,e?_n:w);c&&(t.duplicateEntities[c.id]=c.paths)}return jx=!0,t}function nG(r,e,t,n){let o=ws.join(r,e),i=oG(o,n);if(!i)return;let a=iG(i,o,n);if(!a)return;let s=rG.safeParse(a);if(s.success===!1){n.warn(`Possible Momentic file at ${o} does not have a 'fileType', skipping: ${s.error}`);return}let c=s.data.fileType,l=aG(o,n);if(!l)return;let u=sG(e,o,l);switch(c){case Le.TEST:try{return lG(a,t,u,o,n)}catch(d){n.warn(`Skipping file '${o}' because it is missing Momentic test metadata: ${d}`);return}case Le.MODULE:try{return cG(a,t,u,o,n)}catch(d){n.warn(`Skipping file '${o}' because it is missing Momentic module metadata: ${d}`);return}case Le.MOBILE_TEST:try{return dG(a,t,u,o,n)}catch(d){n.warn(`Skipping file '${o}' because it is missing Momentic mobile test metadata: ${d}`);return}case Le.MOBILE_MODULE:try{return uG(a,t,u,o,n)}catch(d){n.warn(`Skipping file '${o}' because it is missing Momentic mobile module metadata: ${d}`);return}default:{let d=c;return}}}function oG(r,e){try{return Wx.readFileSync(r,"utf-8")}catch(t){e.warn(`Could not read possible Momentic file at ${r}, skipping: ${t}`);return}}function iG(r,e,t){try{let n=tG.parse(r);if(typeof n!="object"||n===null)throw new Error("The YAML document should parse as a map with key-value pairs");return n}catch(n){t.warn(`Could not parse possible Momentic file at ${e}, skipping: ${n}`);return}}function aG(r,e){try{return Wx.statSync(r)}catch(t){e.warn(`Skipping path '${r}' because it could not be stat, skipping: ${t}`);return}}function sG(r,e,t){return{relativePath:r,fullFilePath:e,platformSep:ws.sep,fullPathSegments:e.split(ws.sep),relativePathSegments:r.split(ws.sep),fileName:ws.basename(e),lastModified:t.mtime,createdAt:t.birthtime}}function lG(r,e,t,n,o){let i=ai.parse(r),a;if(e.tests[i.id]){let s=e.tests[i.id].fullFilePath;a={id:i.id,paths:[s,n]}}return e.tests[i.id]={type:Le.TEST,name:i.name,id:i.id,description:i.description??void 0,labels:i.labels,...t},a}function cG(r,e,t,n,o){let i=rr.parse(r),a;if(e.modules[i.moduleId]){let c=e.modules[i.moduleId].fullFilePath;a={id:i.moduleId,paths:[c,n]}}e.modules[i.moduleId]={type:Le.MODULE,name:i.name,id:i.moduleId,description:i.description??void 0,...t};let s=t.fileName.replace(".module.yaml","");return!jx&&en(i.name)!==s&&o.warn(`The module with ID ${i.moduleId} has a name (${i.name}) that does not match its file name (${s}). We recommend renaming the module or the file to be consistent to avoid confusion and issues with module resolution.`),a}function uG(r,e,t,n,o){let i=Pa.parse(r),a;if(e.mobileModules[i.moduleId]){let c=e.mobileModules[i.moduleId].fullFilePath;a={id:i.moduleId,paths:[c,n]}}let s=t.fileName.replace(".module.yaml","");return e.mobileModules[i.moduleId]={type:Le.MOBILE_MODULE,name:s,id:i.moduleId,description:i.description??void 0,...t},a}function dG(r,e,t,n,o){let i=vr.parse(r),a;if(e.mobileTests[i.id]){let c=e.mobileTests[i.id].fullFilePath;a={id:i.id,paths:[c,n]}}let s=t.fileName.replace(".test.yaml","");return e.mobileTests[i.id]={type:Le.MOBILE_TEST,name:s,id:i.id,description:i.description??void 0,...t},a}import{z as nh}from"zod";var $x="test-results";var rke=nh.object({width:nh.number(),height:nh.number()});import{execFile as pG}from"node:child_process";import{promisify as mG}from"node:util";import gG from"simple-git";var Ne=gG(),qx=mG(pG);async function hG(r){let e=await De(r,Ne.raw(["config","--list"])),t={};if(!e)return t;for(let n of e.split(`
4387
4387
  `)){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 fG(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 qx("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 qx("gh",o,{timeout:5e3}),a=i?.toString().trim();if(a)return a}catch{}}}async function SG(r,e,t){let n=e?.includes("github.com"),o=e?.includes("gitlab.com");try{if(n)return fG(r,e,t);if(o)return}catch{}}function Hu(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 De(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 yG(){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 bG(r){let[e,t,n]=await Promise.all([De(r,Ne.show(["--no-patch","--format=%ci"])),De(r,Ne.show(["-s","--pretty=%B"])),De(r,Ne.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 EG(r){let[e,t,n]=await Promise.all([De(r,Ne.listRemote(["--get-url","origin"])),De(r,Ne.show(["-s","--pretty=%B"])),De(r,Ne.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 TG(r){let[e,t,n,o]=await Promise.all([De(r,Ne.show(["--no-patch","--format=%ci"])),De(r,Ne.listRemote(["--get-url","origin"])),De(r,Ne.show(["-s","--pretty=%B"])),De(r,Ne.show(["-s","--pretty=%an"]))]),i=process.env.CIRCLE_REPOSITORY_URL??t,a=i?.includes("github.com"),s=i?.includes("gitlab.com"),c=i?Hu(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 vG(r){let[e,t,n]=await Promise.all([De(r,Ne.show(["--no-patch","--format=%ci"])),De(r,Ne.show(["-s","--pretty=%B"])),De(r,Ne.show(["-s","--pretty=%an"]))]),o=process.env.BUILDKITE_REPO,i=o?.includes("github.com"),a=o?.includes("gitlab.com"),s=o?Hu(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 AG(r){let[e,t,n]=await Promise.all([De(r,Ne.show(["--no-patch","--format=%ci"])),De(r,Ne.show(["-s","--pretty=%B"])),De(r,Ne.show(["-s","--pretty=%an"]))]),o=process.env["Build.Repository.Uri"],i=o?.includes("github.com"),a=o?.includes("gitlab.com"),s=o?Hu(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 wG(r,e){let[t,n,o,i,a,s,c,l,u]=await Promise.all([De(r,Ne.revparse(["HEAD"])),De(r,Ne.revparse(["--short","HEAD"])),De(r,Ne.revparse(["--abbrev-ref","HEAD"])),De(r,Ne.listRemote(["--get-url","origin"])),De(r,Ne.show(["--no-patch","--format=%ci"])),De(r,Ne.show(["-s","--pretty=%B"])),De(r,Ne.show(["-s","--pretty=%an"])),e?De(r,Ne.raw(["merge-base","--fork-point",e])):Promise.resolve(void 0),hG(r)]),d=l?await De(r,Ne.show(["--no-patch","--format=%ci",l])):void 0,p=i?.includes("github.com"),g=i?.includes("gitlab.com"),m=i?Hu(i):void 0,h=u["user.email"]||void 0,f=u["user.name"]||void 0,E=u["user.username"]||void 0,b=await SG(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:p?m:void 0,gitlabProjectPath:g?m:void 0,pipelineId:void 0}}async function CG(){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 RG(r){let e=r.config.gitProtectedBranches??[];return r.config.gitMainBranch&&e.push(r.config.gitMainBranch),{gitMainBranch:r.config.gitMainBranch,gitProtectedBranches:e}}async function Cs(r,e){let t=yG();if(!t)return wG(r,e);switch(t){case"GithubActions":return bG(r);case"GitlabCI":return EG(r);case"CircleCI":return TG(r);case"Buildkite":return vG(r);case"AzureDevOps":return AG(r);case"GCPCloudBuild":return CG()}}async function xG(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 MG(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 _G(r,e,t){try{if(t.githubRepository){let[n,o]=t.githubRepository.split("/");return await MG(r,e,n,o,t)}else if(t.gitlabProjectPath)return await xG(r,e,t.gitlabProjectPath,t)}catch(n){r.warn({err:n},"Failed to get remote git metadata")}return t}async function Gi(r,e,t){let n=await RG(t),o=await Cs(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 _G(r,e,i);return{...n,...o,...a}}import{diff as Kx}from"deep-object-diff";import qn from"fs";import{cloneDeep as PG}from"lodash-es";import Gu from"path";import{v4 as IG}from"uuid";import Rs from"yaml";function Yx(r,e){let t=`${en(e)}.module.yaml`,n=Gu.join(Gu.dirname(r),t);if(qn.existsSync(n))throw new Error(`A conflicting file already exists at the following path: ${n}`);return qn.renameSync(r,n),n}function Xx({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||!qn.existsSync(i))throw new Error(`Tried to update mobile module ${r.moduleId} that could not be found on disk`);let s=qn.readFileSync(i,"utf-8"),c=Rs.parse(s),l={...c,...r,schemaVersion:e},u=To({fileType:Le.MOBILE_MODULE,...Pa.parse(l),steps:jt.array().parse(r.steps)}),d=!!r.name&&r.name!==a,p=Kx(u,c);if(p&&Object.keys(p).length===0&&!o&&!d)return;let g=Rs.stringify(u);qn.writeFileSync(i,g,"utf-8");let m;d&&(m=Yx(i,r.name)),$n(m||i,n.config)}function Jx({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=xs(i,o),s={...a,...e},c=To({fileType:Le.MOBILE_MODULE,...Cl.parse(s)}),l=Kx(c,a);if(l&&Object.keys(l).length===0)return;let u=Rs.stringify(c);qn.writeFileSync(i,u,"utf-8");let d;e.name&&(d=Yx(i,e.name)),$n(d||i,n.config)}async function Qx({name:r,description:e,enabled:t,steps:n,folder:o,project:i}){let a=en(r),s=Gu.join(o,`${a}.module.yaml`),c=IG(),{stepsToSave:l}=await Un({steps:n}),u={schemaVersion:vn,moduleId:c,description:e,enabled:t},d={fileType:Le.MOBILE_MODULE,...u,steps:l},p=Rs.stringify(Xy.parse(d));return qn.writeFileSync(s,p,"utf-8"),$n(s,i.config),{moduleId:c,name:r,description:e||void 0,steps:n}}function xs(r,e){let t=qn.readFileSync(r,"utf-8"),n=Rs.parse(t);try{return{...Cl.parse(n),name:Gu.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 oh(r,e,t,n){let o=xs(r.fullFilePath,t),{resolvedSteps:i}=await Gc({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 xs(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]=PG(a)),a}async function Zx(r,e){let t={};return await Promise.all(Object.values(r.mobileModules).map(async n=>{await oh(n,r,e,t)})),Array.from(Object.values(t))}import{randomUUID as OG}from"crypto";import Io from"fs";import ah from"path";import Vu from"yaml";import ih from"zod";function eM({name:r,description:e="",steps:t=[],settings:n={},folder:o}){let a=`${en(r)}.test.yaml`,s=ah.join(o,a);if(Io.existsSync(s))throw new Error(`A test named '${r}' already exists at path '${s}'. Choose a different name.`);let c={fileType:Le.MOBILE_TEST,id:OG(),description:e,schemaVersion:ro,settings:n,steps:t},l=Vu.stringify(c);return Io.writeFileSync(s,l,"utf-8"),{fullPath:s,testId:c.id}}function LG(r){if(!Io.existsSync(r))throw new Error(`Test file not found: ${r}`);let e=Io.readFileSync(r,"utf-8").replace(/\r\n|\r/g,`
4388
4388
  `),t=Vu.parse(e);if(!t.steps||!Array.isArray(t.steps))throw new Error(`Test ${r} is missing steps`);return t}async function Wu(r,e,t){let n=LG(r),o;try{o=vr.parse(n)}catch(s){throw new Error(`Mobile test ${r} is missing metadata or has invalid metadata: ${s}`)}let{resolvedStepLists:i}=await Rw({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 xs(c,e)}});return{...o,steps:i.steps}}async function tM({filePath:r,steps:e,settings:t,folder:n,project:o,momenticFiles:i,schemaVersion:a}){let s=ah.isAbsolute(r)?r:ah.join(n,r);if(!Io.existsSync(s))throw new Error(`Test file not found: ${s}`);let c=Io.readFileSync(s,"utf-8").replace(/\r\n|\r/g,`
4389
- `),l=Vu.parse(c),u=yp.extend({steps:ih.record(ih.string(),ih.unknown()).array()}).parse({...l,schemaVersion:a});if(u.fileType!==Le.MOBILE_TEST)throw new Error(`File at '${s}' is not a mobile test (fileType=${u.fileType}).`);let d;e&&(d=await Un({steps:e}));let p={...u,...d?.stepsToSave!==void 0?{steps:d.stepsToSave}:{steps:u.steps},...t!==void 0?{settings:t}:{}},g=Vu.stringify(p);for(let m of d?.moduleUpdates??[])Xx({content:m,schemaVersion:ro,momenticFiles:i,project:o});Io.writeFileSync(s,g,"utf-8"),$n(s,o.config)}import{randomUUID as NG}from"crypto";import Kn from"fs";import Vi from"path";var rM=new Set([".DS_Store","__MACOSX"]),nM={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 DG(r,e,t){if(nM[t]){let i=nM[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 sh=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 oM(r,e){try{let t=Vi.join(e,"metadata.json");return zl.parse(JSON.parse(Kn.readFileSync(t,"utf-8")))}catch{throw new sh(r,e)}}function iM(r,e,t){let n=NG(),o=r.child({runGroupId:n});Kn.rmSync(e,{recursive:!0,force:!0});let i=Kn.readdirSync(t).filter(c=>!rM.has(c)).map(c=>Vi.join(t,c));if(i.length===0)throw new Error(`No run groups found in results path: ${t}`);Kn.mkdirSync(e,{recursive:!0});let a={...oM(t,i[0]),id:n};for(let c of i){let l=Vi.join(c,"runs");if(!Kn.existsSync(l))continue;let u=oM(t,c);o.info({oldRunGroupId:u.id},"Merging run groups");for(let p in u){if(p==="id")continue;let g=p;a[g]=DG(a,u,g)}let d=Kn.readdirSync(l);for(let p of d){if(rM.has(p))continue;let g=Vi.join(l,p),m=Vi.join(e,"runs",p);Kn.cpSync(g,m,{recursive:!0})}}let s=Vi.join(e,"metadata.json");Kn.writeFileSync(s,JSON.stringify(a,null,2))}import sM from"adm-zip";import mh from"fs";import{z as VG}from"zod";var F="v1",lh="mobile-cli",Oo="0.12.0";var kG=9e4,UG=3,FG=1500,BG=15e3,xr=class extends Error{status;rawError;constructor(e,t,n,o={}){super(n,o),this.status=e,this.rawError=t}};async function zG(r){return r.text().then(e=>{try{return JSON.parse(e).error}catch{return e}})}var ch=class{baseUrl;logger;constructor(e){this.baseUrl=e.baseUrl,this.logger=e.logger}getHeaders(){let e={"Content-Type":"application/json"};return Oo&&(e[Ul]=Oo),lh&&(e[Cb]=lh),e}async sendRequest(e,t){let{retries:n=UG,requestTimeoutMs:o=kG,initialRetryDelayMs:i=FG,maxRetryDelayMs:a=BG,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(p){u=p;try{s?.(u)}catch{}if(p instanceof xr&&p.status>=400&&p.status<500)throw p;if(p instanceof Error&&p.name==="AbortError"&&(u=new Pn),c===0)throw u;let g=l-c,m=Math.min(i*Math.pow(2,g-1),a);await new Promise(h=>setTimeout(h,m))}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 p=await zG(u);throw new xr(u.status,p,`Request to ${t.method} ${e} failed with status ${u.status}: ${p}`)}let d;if(u.status===204)d={};else{let p=await u.text();try{d=JSON.parse(p)}catch{d=p}}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)}}},Xr=class extends ch{apiKey;mode;constructor(e){super(e),this.apiKey=e.apiKey,this.mode=e.mode}getHeaders(){return{...super.getHeaders(),Authorization:`Bearer ${this.apiKey}`,[wb]:this.mode??""}}};import{createAnthropic as HG}from"@ai-sdk/anthropic";function GG(r){let{apiKey:e,sessionId:t,extraHeaders:n,loggerTags:o}=r,i={Authorization:`Bearer ${e}`,[Ul]:Oo??"",...t&&{[xb]:t},...n||{}};return o&&(i[Rb]=JSON.stringify(o)),i}var ju=r=>e=>{let t=GG(r);return HG({baseURL:`${r.baseUrl}/v1/llm/anthropic/${e}`,headers:t,apiKey:r.apiKey})(e)};var Lo=class extends Xr{agentConfig;constructor(e,t){let n={...Ey,...e};super(t),this.agentConfig=n}getAgentConfig(){return this.agentConfig}async rankChunksWithAi(e,t){let n={...e,loggerTags:t.loggerTags},o=await this.sendRequest(`/${F}/web-agent/recommend-chunks-ai`,{method:"POST",body:n,signal:t.abortSignal});return iy.parse(o)}async rankChunksWithRag(e,t){let n=await this.sendRequest(`/${F}/web-agent/recommend-chunks`,{method:"POST",body:{cliVersion:Oo,...e},signal:t.abortSignal});return oy.parse(n)}async getScreenshotFromS3(e){let t=await this.sendRequest(`/${F}/s3/visual-diff-screenshot`,{method:"POST",body:{url:e}});return VG.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(`/${F}/web-agent/locate-element`,{method:"POST",body:n,signal:t.abortSignal});return Lb.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(`/${F}/web-agent/assertion`,{method:"POST",body:n,signal:t.abortSignal});return _p.parse(o)}async getLintStepResult(e,t){let n={...e,disableCache:!!t.disableCache,loggerTags:t.loggerTags},o=await this.sendRequest(`/${F}/web-agent/lint/step`,{method:"POST",body:n,signal:t.abortSignal});return Ob.parse(o)}async getLintMcpCopilotMessageResult(e,t){let n={message:e.message,disableCache:!!t.disableCache,loggerTags:t.loggerTags},o=await this.sendRequest(`/${F}/web-agent/lint/mcp-copilot`,{method:"POST",body:n,signal:t.abortSignal});return _b.parse(o)}async getMcpCopilotConversationEvaluation(e,t){let n={messagesAndToolCalls:e.messagesAndToolCalls,disableCache:!!t.disableCache,loggerTags:t.loggerTags},o=await this.sendRequest(`/${F}/web-agent/mcp-copilot-conversation-evaluator`,{method:"POST",body:n,signal:t.abortSignal});return Pb.parse(o)}async getMcpCopilotChatSummary(e,t){let n={messagesAndToolCalls:e.messagesAndToolCalls,disableCache:!!t.disableCache,loggerTags:t.loggerTags},o=await this.sendRequest(`/${F}/web-agent/mcp-copilot-chat-summary`,{method:"POST",body:n,signal:t.abortSignal});return Ib.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(`/${F}/web-agent/visual-assertion`,{method:"POST",body:n,signal:t.abortSignal});return _p.parse(o)}async getAiActionCommand(e,t){let n=await this.sendRequest(`/${F}/web-agent/next-command-dynamic`,{method:"POST",body:{...e,disableCache:t.disableCache,loggerTags:t.loggerTags},signal:t.abortSignal});return Mb.parse(n)}async getMultiturnAiActionCommand(e,t){return await this.sendRequest(`/${F}/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(`/${F}/web-agent/ai-action/evaluate`,{method:"POST",body:{...e,disableCache:t.disableCache,loggerTags:t.loggerTags},signal:t.abortSignal});return zd.parse(n)}async getReverseMappedDescription(e,t){let n=await this.sendRequest(`/${F}/web-agent/reverse-mapped-description`,{method:"POST",body:{...e,disableCache:t.disableCache,loggerTags:t.loggerTags},signal:t.abortSignal});return Nb.parse(n)}async getTextExtraction(e,t){let n={...e,disableCache:t.disableCache,loggerTags:t.loggerTags,agentConfigVersion:this.agentConfig?.["text-extraction"]},o=await this.sendRequest(`/${F}/web-agent/text-extraction`,{method:"POST",body:n,signal:t.abortSignal});return Fd.parse(o)}async getPageSummary(e,t){let n={...e,disableCache:t.disableCache,loggerTags:t.loggerTags},o=await this.sendRequest(`/${F}/web-agent/page-summary`,{method:"POST",body:n,signal:t.abortSignal});return US.parse(o)}async getSmartWaitingDecision(e,t){let n={...e,disableCache:t.disableCache,loggerTags:t.loggerTags},o=await this.sendRequest(`/${F}/web-agent/smart-waiting`,{method:"POST",body:n,signal:t.abortSignal});return FS.parse(o)}async getTestResultClassification(e,t){let n=await this.sendRequest(`/${F}/web-agent/result-classification`,{method:"POST",body:{...e,loggerTags:t.loggerTags},signal:t.abortSignal});return wd.parse(n)}async getExtractedKeywords(e,t){let n=await this.sendRequest(`/${F}/web-agent/extract-keywords`,{method:"POST",body:e,signal:t.abortSignal});return by.parse(n)}async getAutohealingProposal(e,t){let n=await this.sendRequest(`/${F}/web-agent/autoheal-section`,{method:"POST",body:{...e,loggerTags:t.loggerTags},signal:t.abortSignal});return OS.parse(n)}async getFailureRecoveryProposal(e,t){let n=await this.sendRequest(`/${F}/web-agent/failure-recovery`,{method:"POST",body:{...e,loggerTags:t.loggerTags},signal:t.abortSignal});return DS.parse(n)}async getFailureRecoveryPlan(e,t){let n=await this.sendRequest(`/${F}/web-agent/failure-recovery-plan`,{method:"POST",body:{...e,loggerTags:t.loggerTags},signal:t.abortSignal});return NS.parse(n)}async getIframeRegex(e,t){let n=await this.sendRequest(`/${F}/web-agent/iframe-regex`,{method:"POST",body:e,signal:t.abortSignal});return jh.parse(n)}getVercelAnthropicModelFactory({loggerTags:e}){return ju({baseUrl:this.baseUrl,apiKey:this.apiKey,loggerTags:e})}};import{z as uh}from"zod";var Mr=class extends Xr{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(`/${F}/auth/check`,{method:"GET",retries:10,requestTimeoutMs:5e3,onFailedRequest:t=>{w.warn(`API key check failed: ${t.message}`)}});return qb.parse(e)}async bulkGetRunStatus(e){let t=await this.sendRequest(`/${F}/runs/status`,{method:"POST",body:e,retries:3,requestTimeoutMs:1e4});return Vb.parse(t)}async getTestYAMLExport(e){let t=await this.sendRequest(`/${F}/tests/export`,{method:"POST",body:e,retries:3,requestTimeoutMs:3e4});return kb.parse(t)}async updateStepCaches(e,t){await this.sendRequest(`/${F}/cache`,{method:"PATCH",body:e,extraHeaders:t,retries:3,requestTimeoutMs:1e4,initialRetryDelayMs:3e3})}async getStepCacheForTest(e,t){let n=await this.sendRequest(`/${F}/cache`,{method:"POST",body:e,extraHeaders:t,retries:10,requestTimeoutMs:3e4,initialRetryDelayMs:3e3});return Fb.parse(n)}async updateMobileStepCaches(e,t){await this.sendRequest(`/${F}/mobile-cache`,{method:"PATCH",body:e,extraHeaders:t,retries:3,requestTimeoutMs:1e4,initialRetryDelayMs:3e3})}async getMobileStepCacheForTest(e,t){let n=await this.sendRequest(`/${F}/mobile-cache`,{method:"POST",body:e,extraHeaders:t,retries:10,requestTimeoutMs:3e4,initialRetryDelayMs:3e3});return Bb.parse(n)}async queueTests(e){let t=await this.sendRequest(`/${F}/tests/queue`,{method:"POST",body:e,retries:3,requestTimeoutMs:1e4});return Db.parse(t)}async uploadScreenshot(e){let t=await this.sendRequest(`/${F}/screenshots`,{method:"POST",body:e,retries:3,requestTimeoutMs:5e3});return $b.parse(t)}async getAllEnvironments(){let e=await this.sendRequest(`/${F}/environments`,{method:"GET",retries:3,requestTimeoutMs:5e3});return Kb.parse(e)}async acquireCacheLock(e,t){let n=await this.sendRequest(`/${F}/result-cache/lock`,{method:"POST",body:e,signal:t,retries:3,requestTimeoutMs:3e4});return cE.parse(n)}async releaseCacheLock(e){await this.sendRequest(`/${F}/result-cache/lock`,{method:"DELETE",body:{key:e},retries:3,requestTimeoutMs:5e3})}async deleteCacheResult(e){await this.sendRequest(`/${F}/result-cache/entry`,{method:"DELETE",body:e,retries:3,requestTimeoutMs:5e3})}async setCacheResult(e){await this.sendRequest(`/${F}/result-cache/entry`,{method:"PATCH",body:e,retries:3,requestTimeoutMs:5e3})}async getCacheResult(e){try{return await this.sendRequest(`/${F}/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(`/${F}/suites/queue`,{method:"POST",body:e,retries:3,requestTimeoutMs:5e3});return Yb.parse(t)}async bulkGetRunGroupStatus(e){let t={runGroupIds:e},n=await this.sendRequest(`/${F}/run-groups/status`,{method:"POST",body:t,retries:3,requestTimeoutMs:5e3});return ey.array().parse(n)}async uploadProposedSteps(e,t){try{await this.sendRequest(`/${F}/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(`/${F}/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(`/${F}/test-fragments/${e}`,{method:"GET",retries:3,requestTimeoutMs:1e4});return Xb.parse(t)}async patchTestFragment(e,t){await this.sendRequest(`/${F}/test-fragments/${e}`,{method:"PATCH",body:t,retries:3,requestTimeoutMs:1e4})}async getPastTestResults(e,t){let n=await this.sendRequest(`/${F}/results/tests/${e}`,{method:"POST",body:t,retries:3,requestTimeoutMs:1e4});return Jb.parse(n)}async generateTestResultsUploadUrl(){let e=await this.sendRequest(`/${F}/results/uploads`,{method:"POST",retries:3,requestTimeoutMs:1e4});return Qb.parse(e)}async startProcessingResultsUpload(e,t){let n=await this.sendRequest(`/${F}/results/uploads/${e}/process`,{method:"POST",body:t,retries:3,requestTimeoutMs:1e4});return Zb.parse(n)}async fetchIconKnowledgeBase(e){try{let t=await this.sendRequest(`/${F}/knowledge-base/icons`,{method:"GET",retries:3,requestTimeoutMs:5e3});return pE.parse(t)}catch(t){return e.error({err:t},"Failed to fetch icon knowledge base"),null}}async saveNewIcons(e,t){try{await this.sendRequest(`/${F}/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(`/${F}/git/github/${e}/${t}/merge-base-commit?${i.toString()}`,{method:"GET",retries:3,requestTimeoutMs:1e4});return Na.parse(a)}async getCommitFromGithub(e,t,n){let o=await this.sendRequest(`/${F}/git/github/${e}/${t}/commits/${n}`,{method:"GET",retries:3,requestTimeoutMs:1e4});return Na.parse(o)}async getMergedBranchFromGithub(e,t,n,o){let i=encodeURIComponent(n),a=await this.sendRequest(`/${F}/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(`/${F}/git/gitlab/${i}/merge-base-commit?${o.toString()}`,{method:"GET",retries:3,requestTimeoutMs:5e3});return Na.parse(a)}async getCommitFromGitlab(e,t){let n=encodeURIComponent(e),o=await this.sendRequest(`/${F}/git/gitlab/${n}/commits/${t}`,{method:"GET",retries:3,requestTimeoutMs:1e4});return Na.parse(o)}async getMergedBranchFromGitlab(e,t,n){let o=encodeURIComponent(t),i=encodeURIComponent(e),a=await this.sendRequest(`/${F}/git/gitlab/${i}/${o}/${n}/merged-branch`,{method:"GET",retries:3,requestTimeoutMs:1e4});return Lp.parse(a)}async getAgentConfig(){let e=await this.sendRequest(`/${F}/web-agent/agent-config`,{method:"GET",retries:3,requestTimeoutMs:5e3});return uh.record(uh.string(),uh.string()).parse(e)}async getQuarantinedTests(){let e=await this.sendRequest(`/${F}/quarantine`,{method:"GET"});return eE.parse(e)}async quarantineTest(e,t,n){await this.sendRequest(`/${F}/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(`/${F}/quarantine/${e.id}`,{method:"DELETE",body:{testName:e.name,reason:t,...n??{}},retries:3,requestTimeoutMs:1e4})}async createAndroidEmulator(e){let t=await this.sendRequest(`/${F}/limbar/android`,{method:"POST",retries:3,body:e,requestTimeoutMs:9e4,initialRetryDelayMs:5e3,maxRetryDelayMs:15e3});return tE.parse(t)}async extendAndroidEmulatorTtl(e){try{await this.sendRequest(`/${F}/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(`/${F}/limbar/android/upload-url`,{method:"POST",retries:3,body:o,requestTimeoutMs:15e3,logResponse:!0});return rE.parse(i)}async deleteAndroidEmulator(e){await this.sendRequest(`/${F}/limbar/android/${e}`,{method:"DELETE",retries:3,requestTimeoutMs:3e4})}async getAndroidAssets(){let e=await this.sendRequest(`/${F}/limbar/assets`,{method:"GET",retries:3,requestTimeoutMs:1e4});return nE.parse(e)}async deleteAndroidAsset(e,t){await this.sendRequest(`/${F}/limbar/assets/${e}/${t}`,{method:"DELETE",retries:3,requestTimeoutMs:1e4})}};async function dh(r){let e=process.versions.node,t=parseInt(e.split(".")[0]);(isNaN(t)||t<18)&&(w.error(`Node.js version 20 or higher is required to run the CLI. Detected: ${process.versions.node}.`),process.exit(1)),w.debug(`Identified node version ${e}`);let n=await r.client.getAuthInfo();return w.debug("Got auth info from API"),n}var $u=class{apiClient;constructor(e){this.apiClient=e}async reportBillableEvents(e,t){await this.apiClient.reportBillableEvents(e,t)}};var Wi=class extends Xr{generator;constructor(e,t){super(e),this.generator=t}async runTemplateMatching(e,t={}){let n=await this.sendRequest(`/${F}/web-agent/template-matching`,{method:"POST",body:e,signal:t?.signal});return $h.parse(n)}async constructIframeRegex(e,t={}){return this.generator.getIframeRegex(e,{abortSignal:t.signal})}};var ji=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 WG,en as jG}from"@faker-js/faker";var $i="v1",qi=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 WG({locale:jG}),this.fakerInstance.seed(e.fakerSeed))}async sendAiGenerate(e){let t=typeof e=="string"?{input:e}:e;return this.httpClient.sendRequest(`/${$i}/tools/ai/generate`,{method:"POST",body:t}).catch(n=>{throw n instanceof xr?new Error(n.rawError):new Error(`Failed to send AI generation: ${n.message}`)})}async sendSms(e){return this.httpClient.sendRequest(`/${$i}/tools/sms/send`,{method:"POST",body:e}).then(()=>{}).catch(t=>{throw t instanceof xr?new Error(t.rawError):new Error(`Failed to send sms: ${t.message}`)})}async fetchLatestSms(e){return this.httpClient.sendRequest(`/${$i}/tools/sms/fetchLatest`,{method:"POST",body:e}).catch(t=>{throw t instanceof xr?new Error(t.rawError):t})}async sendEmail(e){return this.httpClient.sendRequest(`/${$i}/tools/email/send`,{method:"POST",body:e}).then(()=>{}).catch(t=>{throw t instanceof xr?new Error(t.rawError):new Error(`Failed to send email: ${t.message}`)})}async fetchAllEmails(e){return this.httpClient.sendRequest(`/${$i}/tools/email/fetchAll`,{method:"POST",body:e}).catch(t=>{throw t instanceof xr?new Error(t.rawError):new Error(`Failed to fetch all emails: ${t.message}`)})}async fetchLatestEmail(e){return this.httpClient.sendRequest(`/${$i}/tools/email/fetchLatest`,{method:"POST",body:e}).catch(t=>{throw t instanceof xr?new Error(t.rawError):new Error(`Failed to fetch latest emails: ${t.message}`)})}};function aM(r,e,t){return fetch(r,{method:"PUT",body:t,headers:{"Content-Type":e}})}var qu=class{constructor(e){this.client=e}async uploadResultsArchive(e,t){let{uploadUrl:n,id:o}=await this.client.generateTestResultsUploadUrl(),i=await aM(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 Ki=class extends Xr{constructor(e){super(e)}async getElementLocation(e,t){let n={...e,loggerTags:t.loggerTags},o=await this.sendRequest(`/${F}/mobile-agent/locate-element`,{method:"POST",body:n,signal:t.abortSignal});return vy.parse(o)}async evaluateAssertion(e,t){let n={...e,loggerTags:t.loggerTags},o=await this.sendRequest(`/${F}/mobile-agent/assertion`,{method:"POST",body:n,signal:t.abortSignal});return Cy.parse(o)}getVercelAnthropicModelFactory({loggerTags:e,sessionId:t}){return ju({baseUrl:this.baseUrl,apiKey:this.apiKey,sessionId:t,loggerTags:e})}};function Ku({orgId:r,client:e,gitMetadata:t,regenerateCache:n,alwaysSaveCache:o,noCache:i}){return i?new Bl:new ph(r,e,t,{alwaysSaveCache:o,regenerateCache:n})}var ph=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=Pp(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&&Ym({steps:i,stepCacheEntries:n,logger:e.logger});let{cachesToSave:o}=await Un({steps:t,cacheCreationParams:{testId:e.testId,orgId:this.orgId}});this.client.updateMobileStepCaches({entries:o,testId:e.testId},this.cacheHeaders)}};import Yu from"path";function $G(r){let e=new sM,t=Yu.join(r,"metadata.json"),n=zl.parse(JSON.parse(mh.readFileSync(t,"utf-8")));e.addLocalFile(t);for(let o of mh.readdirSync(Yu.join(r,"runs"))){if(!o.endsWith(".zip"))continue;let i=o.replace(/\.zip$/,""),a=new sM(Yu.join(r,"runs",o));for(let s of a.getEntries())s.isDirectory||e.addFile(Yu.join("runs",i,s.entryName),s.getData())}return{runGroupId:n.id,buffer:e.toBuffer()}}async function Xu(r){let{client:e,consoleLogger:t,resultsPath:n}=r;if(!mh.existsSync(n)){t.warn("Results path does not exist, skipping upload.");return}let o=new qu(e);try{let{runGroupId:i,buffer:a}=$G(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 qG from"adm-zip";import vt from"fs";import Xt from"path";var Ms=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(Xt.join(this.filePath,e))}cwd(){return this.filePath}mkdir(e){vt.mkdirSync(Xt.join(this.filePath,e),{recursive:!0})}readFile(e){let t=Xt.join(this.filePath,e);if(vt.existsSync(t))return vt.readFileSync(t)}storeFile(e){let{name:t,contents:n}=e,o=Xt.join(this.filePath,t);try{vt.writeFileSync(o,n)}catch{}}createFileStream(e){let t=Xt.join(this.filePath,e);return vt.createWriteStream(t)}createRunArchive(e){return new gh(Xt.join(this.filePath,"runs"),e)}},gh=class{constructor(e,t){this.filePath=e;this.tempPath=Xt.join(e,`temp-storage-${t}`),this.finalPath=Xt.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=Xt.join(this.tempPath,e);if(vt.existsSync(t))return vt.readFileSync(t)}mkdir(e){vt.mkdirSync(Xt.join(this.tempPath,e),{recursive:!0})}cd(e){return new Ms(Xt.join(this.tempPath,e))}cwd(){return this.tempPath}storeFile(e){let{name:t,contents:n}=e,o=Xt.join(this.tempPath,t);vt.writeFileSync(o,n)}createFileStream(e){let t=Xt.join(this.tempPath,e);return vt.createWriteStream(t)}close(){let e=new qG;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 Nze from"adm-zip";import od from"fs";import AM from"body-parser";import gV from"cors";import hV from"dedent";import{Router as JG}from"express";import Ht from"fs";import{globSync as QG}from"glob";import St from"path";import Ju from"fs";import KG from"path";var YG=new tu(30,60*1e3),yh="https://api.momentic.ai",fh,cM=r=>{yh=r},bh=()=>yh,_s=()=>fh;var Yi,Sh,lM,uM=async r=>{if(fh&&Yi&&lM)return Yi;let e=new Mr({baseUrl:yh,apiKey:r,logger:w});fh=e;try{let t=await e.getAuthInfo();return Yi=t.orgId,Sh=t.userId,lM=r,Yi}catch(t){throw new Error(`Error checking API key against server: ${t}`)}},Xi=()=>{if(!Yi)throw new Error("Your organization ID is invalid.");return Yi},Qu=()=>{if(!Sh)throw new Error("Your user ID is invalid.");return Sh};var Eh,hh,dM=(r,e)=>{Eh=r,hh?.abort(),hh=new AbortController;let t=hh.signal,n=[r.configFilePath];r.config.environments?.forEach(o=>{if(!o.envFile)return;let i=KG.resolve(r.rootDir,o.envFile);try{if(Ju.lstatSync(i).isSymbolicLink())return;Ju.existsSync(i)&&n.push(i)}catch(a){w.warn({err:a},`Failed to check if env file ${i} exists`)}});try{XG({filesToWatch:n,revalidator:e,signal:t,project:r})}catch(o){w.error({err:o},"Failed to start config file watchers")}},Ve=()=>Eh;function XG({filesToWatch:r,revalidator:e,signal:t,project:n}){w.debug("Starting watch on the following files:"),r.forEach(o=>{w.debug(`- ${o}`)}),r.forEach(o=>{let i=async(s,c)=>{s.mtime.getTime()!==c.mtime.getTime()&&(YG.increment("setLocalProject")&&w.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.`),Eh=await Promise.resolve(e(n.configFilePath)))};Ju.watchFile(o,{persistent:!1},i);let a=()=>{Ju.unwatchFile(o,i),t.removeEventListener("abort",a)};t.addEventListener("abort",a),process.once("SIGUSR2",()=>{a(),process.kill(process.pid,"SIGUSR2")})})}function $e(r){return function(...e){let t=e[e.length-1],n=r(...e);Promise.resolve(n).catch(t)}}var Is=JG();function Ps(r){let e=Ve(),t=St.dirname(e.configFilePath);return St.join(t,...r)}function ZG(r){let e=Ve(),t=St.dirname(e.configFilePath),n=St.relative(t,r);return n?n.split(St.sep):[]}function eV(r,e){let t=Ht.statSync(r),n=ZG(r);return Ap.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})}Is.post("/",$e(async(r,e,t)=>{let n;try{n=ub.parse(r.body).pathSegments}catch(d){e.status(400).json({error:`Failed to parse folder read body: ${d}`});return}let o=Ps(n);if(!Ht.existsSync(o)){e.status(404).json({error:`Path not found: ${n.join(St.sep)}`});return}if(!Ht.statSync(o).isDirectory()){e.status(400).json({error:`Path is not a directory: ${n.join(St.sep)}`});return}let a=Ve(),s=Array.from(a.config.exclude??[]).concat(Ol),l=QG("*",{absolute:!1,cwd:o,ignore:s,dotRelative:!1,maxDepth:1,nodir:!1}).map(d=>{let p=St.join(o,d);return eV(p,d)}),u={absolutePath:o,pathSegments:n,contents:l};e.status(200).json(u)}));Is.put("/",$e(async(r,e,t)=>{let n;try{n=db.parse(r.body).pathSegments}catch(a){e.status(400).json({error:`Failed to parse folder create body: ${a}`});return}let o=Ps(n);if(Ht.existsSync(o)){e.status(200).json({success:!0,message:`Folder already exists: ${n.join(St.sep)}`,pathSegments:n});return}Ht.mkdirSync(o,{recursive:!0});let i={success:!0,message:`Folder created: ${n.join(St.sep)}`,pathSegments:n};e.status(201).json(i)}));Is.patch("/",$e(async(r,e,t)=>{let n,o;try{let l=pb.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=Ps(n),a=Ps(o);if(!Ht.existsSync(i)){e.status(400).json({error:`Folder not found: ${n.join(St.sep)}`});return}if(Ht.existsSync(a)){e.status(400).json({error:`Destination already exists: ${o.join(St.sep)}`});return}let s=St.dirname(a);Ht.existsSync(s)||Ht.mkdirSync(s,{recursive:!0}),Ht.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)}));Is.delete("/",$e(async(r,e,t)=>{let n,o=!0;try{let c=mb.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=Ps(n);if(!Ht.existsSync(i)){e.status(200).json({success:!0,message:`Folder not found: ${n.join(St.sep)}`,pathSegments:n});return}if(!Ht.statSync(i).isDirectory()){e.status(400).json({error:`Path is not a directory: ${n.join(St.sep)}`});return}if(o)Ht.rmSync(i,{recursive:!0,force:!0});else{if(Ht.readdirSync(i).length>0){e.status(409).json({error:`Cannot delete non-empty directory without recursive flag: ${n.join("/")}`});return}Ht.rmdirSync(i)}let s={success:!0,message:`Folder deleted: ${n.join("/")}`,pathSegments:n};e.status(200).json(s)}));var Th=Is;import{Router as nV}from"express";import{hostname as tV}from"os";var rV="0.12.0",Os=di({app:"desktop-server",hostname:tV(),disableConsoleLogs:!0}).child({cliVersion:rV});(async()=>{try{let r=await Cs(Os);r.gitBranchName&&Os.addBinding("branch",r.gitBranchName)}catch{}})();var pM=nV();pM.get("/",async(r,e)=>{let t=Ve(),n=_s();if(!n){e.status(500).json({message:"API client not initialized"});return}let o=await Gi(Os,n,t);e.status(200).json(o)});var vh=pM;import fV from"events";import wM,{Router as SV}from"express";import yV from"http";import bV from"path";var Zu=class{sessions=new Map;registerSession(e,t){this.sessions.set(e,t)}getSession(e){return this.sessions.get(e)}async removeSession(e,t){let n=this.sessions.get(e);if(n)try{await n.cleanup?.(),t.info({sessionId:e,emulatorName:n.emulatorName},"Android emulator cleaned up")}catch(o){t.error({err:o},"Error during Android session cleanup")}finally{this.sessions.delete(e)}}async removeAllSessions(e){let t=Array.from(this.sessions.keys());await Promise.all(t.map(n=>this.removeSession(n,e)))}};var mM=new Zu;import{Router as iV}from"express";import{existsSync as aV}from"fs";import sV from"path";import{hostname as oV}from"os";var Ah="0.12.0",At=di({app:"mobile-desktop-server",hostname:oV(),disableConsoleLogs:!0}).child({cliVersion:Ah});(async()=>{try{let r=await Cs(At);r.gitBranchName&&At.addBinding("branch",r.gitBranchName)}catch{}})();var wh=iV();wh.get("/",$e(async(r,e)=>{let t=_s();if(!t){e.status(500).json({message:"API client not initialized"});return}let n=await t.getAndroidAssets();e.status(200).json(n)}));wh.post("/upload-url",$e(async(r,e)=>{let t;try{t=bb.parse(r.body)}catch(i){e.status(400).json({error:`Invalid request body: ${i}`});return}let n=_s();if(!n){e.status(500).json({error:"API client not initialized"});return}let o=sV.resolve(t.filePath);if(!aV(o)){e.status(400).json({error:`File not found: ${o}`});return}await Kc({tag:t.tag,channel:t.channel,filePath:o,apiClient:n,logger:At}),e.sendStatus(204)}));var gM=wh;import{Router as uV}from"express";import{Router as lV}from"express";import hM from"fs";import cV from"path";var Ls=lV();async function Ch(r){return(await Zx(r,At)).map(n=>{let o=r.mobileModules[n.moduleId];if(!o){w.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)}Ls.get("/",$e(async(r,e)=>{let t=Ve(),n=await Sr(t),o=await Ch(n);e.status(200).json(o)}));Ls.get("/:moduleId",$e(async(r,e)=>{if(!r.params.moduleId){e.status(400).json({error:"Missing moduleId in url path."});return}let t=await Sr(Ve()),n=t.mobileModules[r.params.moduleId];if(!n){e.status(404).json({error:"Mobile module not found."});return}try{let o=await oh(n,t,w);e.json(o)}catch(o){e.status(400).json({err:o})}}));Ls.patch("/:moduleId/metadata",$e(async(r,e)=>{if(!r.params.moduleId){e.status(400).json({error:"Missing moduleId in url path."});return}let t;try{t=Eb.parse(r.body)}catch(i){e.status(400).json({error:`Invalid request body: ${i}`});return}let n=Ve(),o=await Sr(n);Jx({moduleId:r.params.moduleId,patch:t,momenticFiles:o,logger:w,project:n}),e.status(201).json({message:"ok"})}));Ls.post("/",$e(async(r,e)=>{let t;try{t=Tb.parse(r.body)}catch(c){e.status(400).json({error:`Invalid request body: ${c}`});return}try{ma(t.name)}catch(c){e.status(400).json({error:`Invalid module name: ${c}`});return}let n=Ve(),i=(await Sr(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=cV.join(n.rootDir,t.folderPath??"");if(!hM.existsSync(a)||!hM.statSync(a).isDirectory()){e.status(400).json({error:`The folder configured for mobile module creation does not exist: ${a}`});return}let s=await Qx({...t,folder:a,project:n});e.status(201).json(s)}));var fM=Ls;var SM=uV();SM.get("/",$e(async(r,e)=>{let t=Ve(),n=await Sr(t),o=await Ch(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 yM=SM;import{Router as dV}from"express";var Rh=dV();Rh.get("/",$e((r,e)=>{let t=Fx(Ve(),At);e.status(200).json(t)}));Rh.get("/names",$e((r,e)=>{let n=Ve().config.environments?.map(o=>o.name)??[];e.status(200).json(n)}));var bM=Rh;import{Router as pV}from"express";var EM=pV();EM.get("/",(r,e)=>{e.status(200).json({userId:Qu(),orgId:Xi(),cliVersion:Ah??"0.0.0"})});var TM=EM;import{Router as mV}from"express";import xh from"path";var ed=mV();ed.patch("/:testPath",$e(async(r,e)=>{let t=r.params.testPath;if(!t){e.status(400).json({error:"Missing testPath in path"});return}let n;try{n=yb.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=Ve(),i=t.endsWith(".test.yaml")?t:`${t}.test.yaml`,a=await Sr(o);await tM({filePath:i,steps:n.steps,settings:n.settings,folder:o.rootDir,project:o,momenticFiles:a,schemaVersion:ro});let s={message:"ok"};e.status(200).json(s)}));ed.post("/",$e((r,e)=>{let t;try{t=Sb.parse(r.body)}catch(m){e.status(400).json({error:`Invalid request body: ${m}`});return}let{name:n,description:o,settings:i,pathSegments:a}=t;if(!n||typeof n!="string"){e.status(400).json({error:"Missing or invalid 'name' in body"});return}try{ma(n)}catch(m){e.status(400).json({error:m.message});return}let s=Ve(),c=xh.join(s.rootDir,...a),{fullPath:l,testId:u}=eM({name:n,description:o,steps:[],settings:i,folder:c}),d=xh.basename(l),p=xh.relative(s.rootDir,l),g={id:u,fileName:d,fullPath:l,relativeFilePath:p};e.status(201).json(g)}));ed.get("/:fileName",$e(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=Ve(),i=await Sr(o),s=await Wu(n,At,i);e.status(200).json(s)}));var vM=ed;var td=class extends ji{constructor(t,n){super(t,n);this.client=t;this.orgId=n}async fetchEnvironment(t,n){let o=Ve();return vs(t,o,w)}};var CM="10mb";async function RM(r){let{serverPort:e,apiKey:t,momenticServerUrl:n,staticDir:o,initialProject:i,driverLogLevel:a,regenerateCache:s,alwaysSaveCache:c,noCache:l}=r;n&&cM(n),await uM(t);let u=Xi(),d=Qu(),p=r.logger.child({orgId:u,userId:d});dM(i,A=>As({configFilePath:A}));let g=wM();g.use(gV()),g.use(AM.json({limit:CM})),g.use(AM.urlencoded({extended:!1,limit:CM}));let m=SV();if(m.use("/folders",Th),m.use("/entities",yM),m.use("/identify",TM),m.use("/mobile-tests",vM),m.use("/mobile-modules",fM),m.use("/assets",gM),m.use("/git",vh),m.use("/environments",bM),g.use("/api",m),g.use((A,I,k)=>{w.debug({url:A.url,path:A.path,query:A.query,method:A.method,body:A.body,headers:A.rawHeaders,client:A.ip},"Incoming request on mobile-desktop-server"),I.on("close",()=>{I.statusCode>=400&&(w.error({url:A.url,method:A.method,statusCode:I.statusCode},"Request completed in error on mobile-desktop-server"),At.error({url:A.url,method:A.method,statusCode:I.statusCode},"Request completed in error on mobile-desktop-server"))}),k()}),g.use((A,I,k,G)=>{if(A instanceof Error&&A.message.includes("BadRequestError: request aborted")){k.status(400).send("Client disconnected");return}w.error({stack:A.stack,msg:A.message,err:A,url:I.url,method:I.method},"Unhandled exception leading to 500 on mobile-desktop-server"),At.error({stack:A.stack,msg:A.message,err:A,url:I.url,method:I.method},"Unhandled exception leading to 500 on mobile-desktop-server"),k.status(500).send(`Internal Server Error: ${A.message}`)}),o){let A=wM.static(o,{setHeaders:I=>{I.setHeader("Cache-Control","no-cache")},redirect:!1});g.use(A),g.use("*",(I,k)=>{k.sendFile(bV.join(o,"index.html"))})}let h=yV.createServer(g),f=`http://localhost:${e}`;await new Promise(A=>{try{h.listen(e,()=>{p.info(`Mobile desktop server is running at ${f}`),A()})}catch(I){I.message.includes("EADDRINUSE")?EV(e):w.error(`An unexpected error occurred while starting the server: ${I.message}`),process.exit(1)}});let b={type:"API_KEY",baseUrl:bh(),apiKey:t,logger:p},C=new Mr(b),R=Ve(),v={...b,mode:"interactive"},{dispose:M}=kx({baseServer:h,logger:p,authorization:b,globalStateManager:mM,getOrgId:()=>Xi(),getGitMetadata:async()=>await Gi(p,C,R),androidDriverFactory:async({socket:A,logger:I,creationOpts:k})=>{let G=Math.floor(Math.random()*1e4)+4e4,ge=await Wl(G,"appium");return qc({logger:I,driverLogLevel:a,apiClient:C,creationOpts:k,socket:A,appiumPort:ge,sessionId:A.id,orgId:Xi(),onStatusUpdate:be=>{A.emit("connectionStatusUpdate",{message:be})}})},mobileGeneratorFactory:async A=>new Ki({baseUrl:bh(),apiKey:t,logger:p,mode:"interactive"}),browserGeneratorFactory:async A=>new Lo(R.config.ai?.agentConfig,v),browserEnricherFactory:async A=>new Wi(v,new Lo(R.config.ai?.agentConfig,v)),storageFactory:async A=>new td(C,A),cacheStorageFactory:async(A,I)=>Ku({orgId:A,client:C,gitMetadata:I,regenerateCache:s??!1,noCache:l??!1,alwaysSaveCache:c??!1}),localToolsFactory:async()=>new qi({httpClient:C,fakerSeed:void 0}),keepSessionAlive:A=>C.extendAndroidEmulatorTtl(A),settingsFactory:async()=>({emulator:R.config.emulator})});process.once("SIGUSR2",async()=>{return;try{await M(),await Tt.flush()}catch(A){w.error({err:A},"Error during session dispose on SIGUSR2")}try{h.close(()=>{process.kill(process.pid,"SIGUSR2")})}catch{process.kill(process.pid,"SIGUSR2")}}),process.once("SIGTERM",async()=>{w.info("SIGTERM in Momentic mobile app received");try{await M(),await Tt.flush()}finally{h.close(()=>process.exit(0))}}),process.once("SIGINT",async()=>{w.info("SIGINT in Momentic mobile app received");try{await M(),await Tt.flush()}finally{h.close(()=>process.exit(0))}})}fV.setMaxListeners(25);process.on("warning",r=>{At.warn({err:r},`Node warning received on mobile-desktop-server: ${r.message}`)});process.on("uncaughtException",r=>{At.error({err:r},"Uncaught exception on mobile-desktop-server"),w.error(`Oh no! The Momentic mobile desktop app encountered a fatal error \u{1F61E}. Error logs: ${r.message}`)});process.on("unhandledRejection",r=>{At.error({reason:`${r}`,stack:r?.stack},"Uncaught exception on mobile-desktop-server (promise rejection)"),w.error(`Oh no! The Momentic mobile desktop app encountered an asynchronous error \u{1F61E}. Error logs: ${r}`)});function EV(r){w.error(hV`Port ${r} is already in use by another process. Please close the other process and try again.
4389
+ `),l=Vu.parse(c),u=yp.extend({steps:ih.record(ih.string(),ih.unknown()).array()}).parse({...l,schemaVersion:a});if(u.fileType!==Le.MOBILE_TEST)throw new Error(`File at '${s}' is not a mobile test (fileType=${u.fileType}).`);let d;e&&(d=await Un({steps:e}));let p={...u,...d?.stepsToSave!==void 0?{steps:d.stepsToSave}:{steps:u.steps},...t!==void 0?{settings:t}:{}},g=Vu.stringify(p);for(let m of d?.moduleUpdates??[])Xx({content:m,schemaVersion:ro,momenticFiles:i,project:o});Io.writeFileSync(s,g,"utf-8"),$n(s,o.config)}import{randomUUID as NG}from"crypto";import Kn from"fs";import Vi from"path";var rM=new Set([".DS_Store","__MACOSX"]),nM={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 DG(r,e,t){if(nM[t]){let i=nM[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 sh=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 oM(r,e){try{let t=Vi.join(e,"metadata.json");return zl.parse(JSON.parse(Kn.readFileSync(t,"utf-8")))}catch{throw new sh(r,e)}}function iM(r,e,t){let n=NG(),o=r.child({runGroupId:n});Kn.rmSync(e,{recursive:!0,force:!0});let i=Kn.readdirSync(t).filter(c=>!rM.has(c)).map(c=>Vi.join(t,c));if(i.length===0)throw new Error(`No run groups found in results path: ${t}`);Kn.mkdirSync(e,{recursive:!0});let a={...oM(t,i[0]),id:n};for(let c of i){let l=Vi.join(c,"runs");if(!Kn.existsSync(l))continue;let u=oM(t,c);o.info({oldRunGroupId:u.id},"Merging run groups");for(let p in u){if(p==="id")continue;let g=p;a[g]=DG(a,u,g)}let d=Kn.readdirSync(l);for(let p of d){if(rM.has(p))continue;let g=Vi.join(l,p),m=Vi.join(e,"runs",p);Kn.cpSync(g,m,{recursive:!0})}}let s=Vi.join(e,"metadata.json");Kn.writeFileSync(s,JSON.stringify(a,null,2))}import sM from"adm-zip";import mh from"fs";import{z as VG}from"zod";var F="v1",lh="mobile-cli",Oo="0.12.1";var kG=9e4,UG=3,FG=1500,BG=15e3,xr=class extends Error{status;rawError;constructor(e,t,n,o={}){super(n,o),this.status=e,this.rawError=t}};async function zG(r){return r.text().then(e=>{try{return JSON.parse(e).error}catch{return e}})}var ch=class{baseUrl;logger;constructor(e){this.baseUrl=e.baseUrl,this.logger=e.logger}getHeaders(){let e={"Content-Type":"application/json"};return Oo&&(e[Ul]=Oo),lh&&(e[Cb]=lh),e}async sendRequest(e,t){let{retries:n=UG,requestTimeoutMs:o=kG,initialRetryDelayMs:i=FG,maxRetryDelayMs:a=BG,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(p){u=p;try{s?.(u)}catch{}if(p instanceof xr&&p.status>=400&&p.status<500)throw p;if(p instanceof Error&&p.name==="AbortError"&&(u=new Pn),c===0)throw u;let g=l-c,m=Math.min(i*Math.pow(2,g-1),a);await new Promise(h=>setTimeout(h,m))}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 p=await zG(u);throw new xr(u.status,p,`Request to ${t.method} ${e} failed with status ${u.status}: ${p}`)}let d;if(u.status===204)d={};else{let p=await u.text();try{d=JSON.parse(p)}catch{d=p}}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)}}},Xr=class extends ch{apiKey;mode;constructor(e){super(e),this.apiKey=e.apiKey,this.mode=e.mode}getHeaders(){return{...super.getHeaders(),Authorization:`Bearer ${this.apiKey}`,[wb]:this.mode??""}}};import{createAnthropic as HG}from"@ai-sdk/anthropic";function GG(r){let{apiKey:e,sessionId:t,extraHeaders:n,loggerTags:o}=r,i={Authorization:`Bearer ${e}`,[Ul]:Oo??"",...t&&{[xb]:t},...n||{}};return o&&(i[Rb]=JSON.stringify(o)),i}var ju=r=>e=>{let t=GG(r);return HG({baseURL:`${r.baseUrl}/v1/llm/anthropic/${e}`,headers:t,apiKey:r.apiKey})(e)};var Lo=class extends Xr{agentConfig;constructor(e,t){let n={...Ey,...e};super(t),this.agentConfig=n}getAgentConfig(){return this.agentConfig}async rankChunksWithAi(e,t){let n={...e,loggerTags:t.loggerTags},o=await this.sendRequest(`/${F}/web-agent/recommend-chunks-ai`,{method:"POST",body:n,signal:t.abortSignal});return iy.parse(o)}async rankChunksWithRag(e,t){let n=await this.sendRequest(`/${F}/web-agent/recommend-chunks`,{method:"POST",body:{cliVersion:Oo,...e},signal:t.abortSignal});return oy.parse(n)}async getScreenshotFromS3(e){let t=await this.sendRequest(`/${F}/s3/visual-diff-screenshot`,{method:"POST",body:{url:e}});return VG.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(`/${F}/web-agent/locate-element`,{method:"POST",body:n,signal:t.abortSignal});return Lb.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(`/${F}/web-agent/assertion`,{method:"POST",body:n,signal:t.abortSignal});return _p.parse(o)}async getLintStepResult(e,t){let n={...e,disableCache:!!t.disableCache,loggerTags:t.loggerTags},o=await this.sendRequest(`/${F}/web-agent/lint/step`,{method:"POST",body:n,signal:t.abortSignal});return Ob.parse(o)}async getLintMcpCopilotMessageResult(e,t){let n={message:e.message,disableCache:!!t.disableCache,loggerTags:t.loggerTags},o=await this.sendRequest(`/${F}/web-agent/lint/mcp-copilot`,{method:"POST",body:n,signal:t.abortSignal});return _b.parse(o)}async getMcpCopilotConversationEvaluation(e,t){let n={messagesAndToolCalls:e.messagesAndToolCalls,disableCache:!!t.disableCache,loggerTags:t.loggerTags},o=await this.sendRequest(`/${F}/web-agent/mcp-copilot-conversation-evaluator`,{method:"POST",body:n,signal:t.abortSignal});return Pb.parse(o)}async getMcpCopilotChatSummary(e,t){let n={messagesAndToolCalls:e.messagesAndToolCalls,disableCache:!!t.disableCache,loggerTags:t.loggerTags},o=await this.sendRequest(`/${F}/web-agent/mcp-copilot-chat-summary`,{method:"POST",body:n,signal:t.abortSignal});return Ib.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(`/${F}/web-agent/visual-assertion`,{method:"POST",body:n,signal:t.abortSignal});return _p.parse(o)}async getAiActionCommand(e,t){let n=await this.sendRequest(`/${F}/web-agent/next-command-dynamic`,{method:"POST",body:{...e,disableCache:t.disableCache,loggerTags:t.loggerTags},signal:t.abortSignal});return Mb.parse(n)}async getMultiturnAiActionCommand(e,t){return await this.sendRequest(`/${F}/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(`/${F}/web-agent/ai-action/evaluate`,{method:"POST",body:{...e,disableCache:t.disableCache,loggerTags:t.loggerTags},signal:t.abortSignal});return zd.parse(n)}async getReverseMappedDescription(e,t){let n=await this.sendRequest(`/${F}/web-agent/reverse-mapped-description`,{method:"POST",body:{...e,disableCache:t.disableCache,loggerTags:t.loggerTags},signal:t.abortSignal});return Nb.parse(n)}async getTextExtraction(e,t){let n={...e,disableCache:t.disableCache,loggerTags:t.loggerTags,agentConfigVersion:this.agentConfig?.["text-extraction"]},o=await this.sendRequest(`/${F}/web-agent/text-extraction`,{method:"POST",body:n,signal:t.abortSignal});return Fd.parse(o)}async getPageSummary(e,t){let n={...e,disableCache:t.disableCache,loggerTags:t.loggerTags},o=await this.sendRequest(`/${F}/web-agent/page-summary`,{method:"POST",body:n,signal:t.abortSignal});return US.parse(o)}async getSmartWaitingDecision(e,t){let n={...e,disableCache:t.disableCache,loggerTags:t.loggerTags},o=await this.sendRequest(`/${F}/web-agent/smart-waiting`,{method:"POST",body:n,signal:t.abortSignal});return FS.parse(o)}async getTestResultClassification(e,t){let n=await this.sendRequest(`/${F}/web-agent/result-classification`,{method:"POST",body:{...e,loggerTags:t.loggerTags},signal:t.abortSignal});return wd.parse(n)}async getExtractedKeywords(e,t){let n=await this.sendRequest(`/${F}/web-agent/extract-keywords`,{method:"POST",body:e,signal:t.abortSignal});return by.parse(n)}async getAutohealingProposal(e,t){let n=await this.sendRequest(`/${F}/web-agent/autoheal-section`,{method:"POST",body:{...e,loggerTags:t.loggerTags},signal:t.abortSignal});return OS.parse(n)}async getFailureRecoveryProposal(e,t){let n=await this.sendRequest(`/${F}/web-agent/failure-recovery`,{method:"POST",body:{...e,loggerTags:t.loggerTags},signal:t.abortSignal});return DS.parse(n)}async getFailureRecoveryPlan(e,t){let n=await this.sendRequest(`/${F}/web-agent/failure-recovery-plan`,{method:"POST",body:{...e,loggerTags:t.loggerTags},signal:t.abortSignal});return NS.parse(n)}async getIframeRegex(e,t){let n=await this.sendRequest(`/${F}/web-agent/iframe-regex`,{method:"POST",body:e,signal:t.abortSignal});return jh.parse(n)}getVercelAnthropicModelFactory({loggerTags:e}){return ju({baseUrl:this.baseUrl,apiKey:this.apiKey,loggerTags:e})}};import{z as uh}from"zod";var Mr=class extends Xr{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(`/${F}/auth/check`,{method:"GET",retries:10,requestTimeoutMs:5e3,onFailedRequest:t=>{w.warn(`API key check failed: ${t.message}`)}});return qb.parse(e)}async bulkGetRunStatus(e){let t=await this.sendRequest(`/${F}/runs/status`,{method:"POST",body:e,retries:3,requestTimeoutMs:1e4});return Vb.parse(t)}async getTestYAMLExport(e){let t=await this.sendRequest(`/${F}/tests/export`,{method:"POST",body:e,retries:3,requestTimeoutMs:3e4});return kb.parse(t)}async updateStepCaches(e,t){await this.sendRequest(`/${F}/cache`,{method:"PATCH",body:e,extraHeaders:t,retries:3,requestTimeoutMs:1e4,initialRetryDelayMs:3e3})}async getStepCacheForTest(e,t){let n=await this.sendRequest(`/${F}/cache`,{method:"POST",body:e,extraHeaders:t,retries:10,requestTimeoutMs:3e4,initialRetryDelayMs:3e3});return Fb.parse(n)}async updateMobileStepCaches(e,t){await this.sendRequest(`/${F}/mobile-cache`,{method:"PATCH",body:e,extraHeaders:t,retries:3,requestTimeoutMs:1e4,initialRetryDelayMs:3e3})}async getMobileStepCacheForTest(e,t){let n=await this.sendRequest(`/${F}/mobile-cache`,{method:"POST",body:e,extraHeaders:t,retries:10,requestTimeoutMs:3e4,initialRetryDelayMs:3e3});return Bb.parse(n)}async queueTests(e){let t=await this.sendRequest(`/${F}/tests/queue`,{method:"POST",body:e,retries:3,requestTimeoutMs:1e4});return Db.parse(t)}async uploadScreenshot(e){let t=await this.sendRequest(`/${F}/screenshots`,{method:"POST",body:e,retries:3,requestTimeoutMs:5e3});return $b.parse(t)}async getAllEnvironments(){let e=await this.sendRequest(`/${F}/environments`,{method:"GET",retries:3,requestTimeoutMs:5e3});return Kb.parse(e)}async acquireCacheLock(e,t){let n=await this.sendRequest(`/${F}/result-cache/lock`,{method:"POST",body:e,signal:t,retries:3,requestTimeoutMs:3e4});return cE.parse(n)}async releaseCacheLock(e){await this.sendRequest(`/${F}/result-cache/lock`,{method:"DELETE",body:{key:e},retries:3,requestTimeoutMs:5e3})}async deleteCacheResult(e){await this.sendRequest(`/${F}/result-cache/entry`,{method:"DELETE",body:e,retries:3,requestTimeoutMs:5e3})}async setCacheResult(e){await this.sendRequest(`/${F}/result-cache/entry`,{method:"PATCH",body:e,retries:3,requestTimeoutMs:5e3})}async getCacheResult(e){try{return await this.sendRequest(`/${F}/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(`/${F}/suites/queue`,{method:"POST",body:e,retries:3,requestTimeoutMs:5e3});return Yb.parse(t)}async bulkGetRunGroupStatus(e){let t={runGroupIds:e},n=await this.sendRequest(`/${F}/run-groups/status`,{method:"POST",body:t,retries:3,requestTimeoutMs:5e3});return ey.array().parse(n)}async uploadProposedSteps(e,t){try{await this.sendRequest(`/${F}/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(`/${F}/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(`/${F}/test-fragments/${e}`,{method:"GET",retries:3,requestTimeoutMs:1e4});return Xb.parse(t)}async patchTestFragment(e,t){await this.sendRequest(`/${F}/test-fragments/${e}`,{method:"PATCH",body:t,retries:3,requestTimeoutMs:1e4})}async getPastTestResults(e,t){let n=await this.sendRequest(`/${F}/results/tests/${e}`,{method:"POST",body:t,retries:3,requestTimeoutMs:1e4});return Jb.parse(n)}async generateTestResultsUploadUrl(){let e=await this.sendRequest(`/${F}/results/uploads`,{method:"POST",retries:3,requestTimeoutMs:1e4});return Qb.parse(e)}async startProcessingResultsUpload(e,t){let n=await this.sendRequest(`/${F}/results/uploads/${e}/process`,{method:"POST",body:t,retries:3,requestTimeoutMs:1e4});return Zb.parse(n)}async fetchIconKnowledgeBase(e){try{let t=await this.sendRequest(`/${F}/knowledge-base/icons`,{method:"GET",retries:3,requestTimeoutMs:5e3});return pE.parse(t)}catch(t){return e.error({err:t},"Failed to fetch icon knowledge base"),null}}async saveNewIcons(e,t){try{await this.sendRequest(`/${F}/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(`/${F}/git/github/${e}/${t}/merge-base-commit?${i.toString()}`,{method:"GET",retries:3,requestTimeoutMs:1e4});return Na.parse(a)}async getCommitFromGithub(e,t,n){let o=await this.sendRequest(`/${F}/git/github/${e}/${t}/commits/${n}`,{method:"GET",retries:3,requestTimeoutMs:1e4});return Na.parse(o)}async getMergedBranchFromGithub(e,t,n,o){let i=encodeURIComponent(n),a=await this.sendRequest(`/${F}/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(`/${F}/git/gitlab/${i}/merge-base-commit?${o.toString()}`,{method:"GET",retries:3,requestTimeoutMs:5e3});return Na.parse(a)}async getCommitFromGitlab(e,t){let n=encodeURIComponent(e),o=await this.sendRequest(`/${F}/git/gitlab/${n}/commits/${t}`,{method:"GET",retries:3,requestTimeoutMs:1e4});return Na.parse(o)}async getMergedBranchFromGitlab(e,t,n){let o=encodeURIComponent(t),i=encodeURIComponent(e),a=await this.sendRequest(`/${F}/git/gitlab/${i}/${o}/${n}/merged-branch`,{method:"GET",retries:3,requestTimeoutMs:1e4});return Lp.parse(a)}async getAgentConfig(){let e=await this.sendRequest(`/${F}/web-agent/agent-config`,{method:"GET",retries:3,requestTimeoutMs:5e3});return uh.record(uh.string(),uh.string()).parse(e)}async getQuarantinedTests(){let e=await this.sendRequest(`/${F}/quarantine`,{method:"GET"});return eE.parse(e)}async quarantineTest(e,t,n){await this.sendRequest(`/${F}/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(`/${F}/quarantine/${e.id}`,{method:"DELETE",body:{testName:e.name,reason:t,...n??{}},retries:3,requestTimeoutMs:1e4})}async createAndroidEmulator(e){let t=await this.sendRequest(`/${F}/limbar/android`,{method:"POST",retries:3,body:e,requestTimeoutMs:9e4,initialRetryDelayMs:5e3,maxRetryDelayMs:15e3});return tE.parse(t)}async extendAndroidEmulatorTtl(e){try{await this.sendRequest(`/${F}/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(`/${F}/limbar/android/upload-url`,{method:"POST",retries:3,body:o,requestTimeoutMs:15e3,logResponse:!0});return rE.parse(i)}async deleteAndroidEmulator(e){await this.sendRequest(`/${F}/limbar/android/${e}`,{method:"DELETE",retries:3,requestTimeoutMs:3e4})}async getAndroidAssets(){let e=await this.sendRequest(`/${F}/limbar/assets`,{method:"GET",retries:3,requestTimeoutMs:1e4});return nE.parse(e)}async deleteAndroidAsset(e,t){await this.sendRequest(`/${F}/limbar/assets/${e}/${t}`,{method:"DELETE",retries:3,requestTimeoutMs:1e4})}};async function dh(r){let e=process.versions.node,t=parseInt(e.split(".")[0]);(isNaN(t)||t<18)&&(w.error(`Node.js version 20 or higher is required to run the CLI. Detected: ${process.versions.node}.`),process.exit(1)),w.debug(`Identified node version ${e}`);let n=await r.client.getAuthInfo();return w.debug("Got auth info from API"),n}var $u=class{apiClient;constructor(e){this.apiClient=e}async reportBillableEvents(e,t){await this.apiClient.reportBillableEvents(e,t)}};var Wi=class extends Xr{generator;constructor(e,t){super(e),this.generator=t}async runTemplateMatching(e,t={}){let n=await this.sendRequest(`/${F}/web-agent/template-matching`,{method:"POST",body:e,signal:t?.signal});return $h.parse(n)}async constructIframeRegex(e,t={}){return this.generator.getIframeRegex(e,{abortSignal:t.signal})}};var ji=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 WG,en as jG}from"@faker-js/faker";var $i="v1",qi=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 WG({locale:jG}),this.fakerInstance.seed(e.fakerSeed))}async sendAiGenerate(e){let t=typeof e=="string"?{input:e}:e;return this.httpClient.sendRequest(`/${$i}/tools/ai/generate`,{method:"POST",body:t}).catch(n=>{throw n instanceof xr?new Error(n.rawError):new Error(`Failed to send AI generation: ${n.message}`)})}async sendSms(e){return this.httpClient.sendRequest(`/${$i}/tools/sms/send`,{method:"POST",body:e}).then(()=>{}).catch(t=>{throw t instanceof xr?new Error(t.rawError):new Error(`Failed to send sms: ${t.message}`)})}async fetchLatestSms(e){return this.httpClient.sendRequest(`/${$i}/tools/sms/fetchLatest`,{method:"POST",body:e}).catch(t=>{throw t instanceof xr?new Error(t.rawError):t})}async sendEmail(e){return this.httpClient.sendRequest(`/${$i}/tools/email/send`,{method:"POST",body:e}).then(()=>{}).catch(t=>{throw t instanceof xr?new Error(t.rawError):new Error(`Failed to send email: ${t.message}`)})}async fetchAllEmails(e){return this.httpClient.sendRequest(`/${$i}/tools/email/fetchAll`,{method:"POST",body:e}).catch(t=>{throw t instanceof xr?new Error(t.rawError):new Error(`Failed to fetch all emails: ${t.message}`)})}async fetchLatestEmail(e){return this.httpClient.sendRequest(`/${$i}/tools/email/fetchLatest`,{method:"POST",body:e}).catch(t=>{throw t instanceof xr?new Error(t.rawError):new Error(`Failed to fetch latest emails: ${t.message}`)})}};function aM(r,e,t){return fetch(r,{method:"PUT",body:t,headers:{"Content-Type":e}})}var qu=class{constructor(e){this.client=e}async uploadResultsArchive(e,t){let{uploadUrl:n,id:o}=await this.client.generateTestResultsUploadUrl(),i=await aM(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 Ki=class extends Xr{constructor(e){super(e)}async getElementLocation(e,t){let n={...e,loggerTags:t.loggerTags},o=await this.sendRequest(`/${F}/mobile-agent/locate-element`,{method:"POST",body:n,signal:t.abortSignal});return vy.parse(o)}async evaluateAssertion(e,t){let n={...e,loggerTags:t.loggerTags},o=await this.sendRequest(`/${F}/mobile-agent/assertion`,{method:"POST",body:n,signal:t.abortSignal});return Cy.parse(o)}getVercelAnthropicModelFactory({loggerTags:e,sessionId:t}){return ju({baseUrl:this.baseUrl,apiKey:this.apiKey,sessionId:t,loggerTags:e})}};function Ku({orgId:r,client:e,gitMetadata:t,regenerateCache:n,alwaysSaveCache:o,noCache:i}){return i?new Bl:new ph(r,e,t,{alwaysSaveCache:o,regenerateCache:n})}var ph=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=Pp(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&&Ym({steps:i,stepCacheEntries:n,logger:e.logger});let{cachesToSave:o}=await Un({steps:t,cacheCreationParams:{testId:e.testId,orgId:this.orgId}});this.client.updateMobileStepCaches({entries:o,testId:e.testId},this.cacheHeaders)}};import Yu from"path";function $G(r){let e=new sM,t=Yu.join(r,"metadata.json"),n=zl.parse(JSON.parse(mh.readFileSync(t,"utf-8")));e.addLocalFile(t);for(let o of mh.readdirSync(Yu.join(r,"runs"))){if(!o.endsWith(".zip"))continue;let i=o.replace(/\.zip$/,""),a=new sM(Yu.join(r,"runs",o));for(let s of a.getEntries())s.isDirectory||e.addFile(Yu.join("runs",i,s.entryName),s.getData())}return{runGroupId:n.id,buffer:e.toBuffer()}}async function Xu(r){let{client:e,consoleLogger:t,resultsPath:n}=r;if(!mh.existsSync(n)){t.warn("Results path does not exist, skipping upload.");return}let o=new qu(e);try{let{runGroupId:i,buffer:a}=$G(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 qG from"adm-zip";import vt from"fs";import Xt from"path";var Ms=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(Xt.join(this.filePath,e))}cwd(){return this.filePath}mkdir(e){vt.mkdirSync(Xt.join(this.filePath,e),{recursive:!0})}readFile(e){let t=Xt.join(this.filePath,e);if(vt.existsSync(t))return vt.readFileSync(t)}storeFile(e){let{name:t,contents:n}=e,o=Xt.join(this.filePath,t);try{vt.writeFileSync(o,n)}catch{}}createFileStream(e){let t=Xt.join(this.filePath,e);return vt.createWriteStream(t)}createRunArchive(e){return new gh(Xt.join(this.filePath,"runs"),e)}},gh=class{constructor(e,t){this.filePath=e;this.tempPath=Xt.join(e,`temp-storage-${t}`),this.finalPath=Xt.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=Xt.join(this.tempPath,e);if(vt.existsSync(t))return vt.readFileSync(t)}mkdir(e){vt.mkdirSync(Xt.join(this.tempPath,e),{recursive:!0})}cd(e){return new Ms(Xt.join(this.tempPath,e))}cwd(){return this.tempPath}storeFile(e){let{name:t,contents:n}=e,o=Xt.join(this.tempPath,t);vt.writeFileSync(o,n)}createFileStream(e){let t=Xt.join(this.tempPath,e);return vt.createWriteStream(t)}close(){let e=new qG;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 Nze from"adm-zip";import od from"fs";import AM from"body-parser";import gV from"cors";import hV from"dedent";import{Router as JG}from"express";import Ht from"fs";import{globSync as QG}from"glob";import St from"path";import Ju from"fs";import KG from"path";var YG=new tu(30,60*1e3),yh="https://api.momentic.ai",fh,cM=r=>{yh=r},bh=()=>yh,_s=()=>fh;var Yi,Sh,lM,uM=async r=>{if(fh&&Yi&&lM)return Yi;let e=new Mr({baseUrl:yh,apiKey:r,logger:w});fh=e;try{let t=await e.getAuthInfo();return Yi=t.orgId,Sh=t.userId,lM=r,Yi}catch(t){throw new Error(`Error checking API key against server: ${t}`)}},Xi=()=>{if(!Yi)throw new Error("Your organization ID is invalid.");return Yi},Qu=()=>{if(!Sh)throw new Error("Your user ID is invalid.");return Sh};var Eh,hh,dM=(r,e)=>{Eh=r,hh?.abort(),hh=new AbortController;let t=hh.signal,n=[r.configFilePath];r.config.environments?.forEach(o=>{if(!o.envFile)return;let i=KG.resolve(r.rootDir,o.envFile);try{if(Ju.lstatSync(i).isSymbolicLink())return;Ju.existsSync(i)&&n.push(i)}catch(a){w.warn({err:a},`Failed to check if env file ${i} exists`)}});try{XG({filesToWatch:n,revalidator:e,signal:t,project:r})}catch(o){w.error({err:o},"Failed to start config file watchers")}},Ve=()=>Eh;function XG({filesToWatch:r,revalidator:e,signal:t,project:n}){w.debug("Starting watch on the following files:"),r.forEach(o=>{w.debug(`- ${o}`)}),r.forEach(o=>{let i=async(s,c)=>{s.mtime.getTime()!==c.mtime.getTime()&&(YG.increment("setLocalProject")&&w.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.`),Eh=await Promise.resolve(e(n.configFilePath)))};Ju.watchFile(o,{persistent:!1},i);let a=()=>{Ju.unwatchFile(o,i),t.removeEventListener("abort",a)};t.addEventListener("abort",a),process.once("SIGUSR2",()=>{a(),process.kill(process.pid,"SIGUSR2")})})}function $e(r){return function(...e){let t=e[e.length-1],n=r(...e);Promise.resolve(n).catch(t)}}var Is=JG();function Ps(r){let e=Ve(),t=St.dirname(e.configFilePath);return St.join(t,...r)}function ZG(r){let e=Ve(),t=St.dirname(e.configFilePath),n=St.relative(t,r);return n?n.split(St.sep):[]}function eV(r,e){let t=Ht.statSync(r),n=ZG(r);return Ap.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})}Is.post("/",$e(async(r,e,t)=>{let n;try{n=ub.parse(r.body).pathSegments}catch(d){e.status(400).json({error:`Failed to parse folder read body: ${d}`});return}let o=Ps(n);if(!Ht.existsSync(o)){e.status(404).json({error:`Path not found: ${n.join(St.sep)}`});return}if(!Ht.statSync(o).isDirectory()){e.status(400).json({error:`Path is not a directory: ${n.join(St.sep)}`});return}let a=Ve(),s=Array.from(a.config.exclude??[]).concat(Ol),l=QG("*",{absolute:!1,cwd:o,ignore:s,dotRelative:!1,maxDepth:1,nodir:!1}).map(d=>{let p=St.join(o,d);return eV(p,d)}),u={absolutePath:o,pathSegments:n,contents:l};e.status(200).json(u)}));Is.put("/",$e(async(r,e,t)=>{let n;try{n=db.parse(r.body).pathSegments}catch(a){e.status(400).json({error:`Failed to parse folder create body: ${a}`});return}let o=Ps(n);if(Ht.existsSync(o)){e.status(200).json({success:!0,message:`Folder already exists: ${n.join(St.sep)}`,pathSegments:n});return}Ht.mkdirSync(o,{recursive:!0});let i={success:!0,message:`Folder created: ${n.join(St.sep)}`,pathSegments:n};e.status(201).json(i)}));Is.patch("/",$e(async(r,e,t)=>{let n,o;try{let l=pb.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=Ps(n),a=Ps(o);if(!Ht.existsSync(i)){e.status(400).json({error:`Folder not found: ${n.join(St.sep)}`});return}if(Ht.existsSync(a)){e.status(400).json({error:`Destination already exists: ${o.join(St.sep)}`});return}let s=St.dirname(a);Ht.existsSync(s)||Ht.mkdirSync(s,{recursive:!0}),Ht.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)}));Is.delete("/",$e(async(r,e,t)=>{let n,o=!0;try{let c=mb.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=Ps(n);if(!Ht.existsSync(i)){e.status(200).json({success:!0,message:`Folder not found: ${n.join(St.sep)}`,pathSegments:n});return}if(!Ht.statSync(i).isDirectory()){e.status(400).json({error:`Path is not a directory: ${n.join(St.sep)}`});return}if(o)Ht.rmSync(i,{recursive:!0,force:!0});else{if(Ht.readdirSync(i).length>0){e.status(409).json({error:`Cannot delete non-empty directory without recursive flag: ${n.join("/")}`});return}Ht.rmdirSync(i)}let s={success:!0,message:`Folder deleted: ${n.join("/")}`,pathSegments:n};e.status(200).json(s)}));var Th=Is;import{Router as nV}from"express";import{hostname as tV}from"os";var rV="0.12.1",Os=di({app:"desktop-server",hostname:tV(),disableConsoleLogs:!0}).child({cliVersion:rV});(async()=>{try{let r=await Cs(Os);r.gitBranchName&&Os.addBinding("branch",r.gitBranchName)}catch{}})();var pM=nV();pM.get("/",async(r,e)=>{let t=Ve(),n=_s();if(!n){e.status(500).json({message:"API client not initialized"});return}let o=await Gi(Os,n,t);e.status(200).json(o)});var vh=pM;import fV from"events";import wM,{Router as SV}from"express";import yV from"http";import bV from"path";var Zu=class{sessions=new Map;registerSession(e,t){this.sessions.set(e,t)}getSession(e){return this.sessions.get(e)}async removeSession(e,t){let n=this.sessions.get(e);if(n)try{await n.cleanup?.(),t.info({sessionId:e,emulatorName:n.emulatorName},"Android emulator cleaned up")}catch(o){t.error({err:o},"Error during Android session cleanup")}finally{this.sessions.delete(e)}}async removeAllSessions(e){let t=Array.from(this.sessions.keys());await Promise.all(t.map(n=>this.removeSession(n,e)))}};var mM=new Zu;import{Router as iV}from"express";import{existsSync as aV}from"fs";import sV from"path";import{hostname as oV}from"os";var Ah="0.12.1",At=di({app:"mobile-desktop-server",hostname:oV(),disableConsoleLogs:!0}).child({cliVersion:Ah});(async()=>{try{let r=await Cs(At);r.gitBranchName&&At.addBinding("branch",r.gitBranchName)}catch{}})();var wh=iV();wh.get("/",$e(async(r,e)=>{let t=_s();if(!t){e.status(500).json({message:"API client not initialized"});return}let n=await t.getAndroidAssets();e.status(200).json(n)}));wh.post("/upload-url",$e(async(r,e)=>{let t;try{t=bb.parse(r.body)}catch(i){e.status(400).json({error:`Invalid request body: ${i}`});return}let n=_s();if(!n){e.status(500).json({error:"API client not initialized"});return}let o=sV.resolve(t.filePath);if(!aV(o)){e.status(400).json({error:`File not found: ${o}`});return}await Kc({tag:t.tag,channel:t.channel,filePath:o,apiClient:n,logger:At}),e.sendStatus(204)}));var gM=wh;import{Router as uV}from"express";import{Router as lV}from"express";import hM from"fs";import cV from"path";var Ls=lV();async function Ch(r){return(await Zx(r,At)).map(n=>{let o=r.mobileModules[n.moduleId];if(!o){w.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)}Ls.get("/",$e(async(r,e)=>{let t=Ve(),n=await Sr(t),o=await Ch(n);e.status(200).json(o)}));Ls.get("/:moduleId",$e(async(r,e)=>{if(!r.params.moduleId){e.status(400).json({error:"Missing moduleId in url path."});return}let t=await Sr(Ve()),n=t.mobileModules[r.params.moduleId];if(!n){e.status(404).json({error:"Mobile module not found."});return}try{let o=await oh(n,t,w);e.json(o)}catch(o){e.status(400).json({err:o})}}));Ls.patch("/:moduleId/metadata",$e(async(r,e)=>{if(!r.params.moduleId){e.status(400).json({error:"Missing moduleId in url path."});return}let t;try{t=Eb.parse(r.body)}catch(i){e.status(400).json({error:`Invalid request body: ${i}`});return}let n=Ve(),o=await Sr(n);Jx({moduleId:r.params.moduleId,patch:t,momenticFiles:o,logger:w,project:n}),e.status(201).json({message:"ok"})}));Ls.post("/",$e(async(r,e)=>{let t;try{t=Tb.parse(r.body)}catch(c){e.status(400).json({error:`Invalid request body: ${c}`});return}try{ma(t.name)}catch(c){e.status(400).json({error:`Invalid module name: ${c}`});return}let n=Ve(),i=(await Sr(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=cV.join(n.rootDir,t.folderPath??"");if(!hM.existsSync(a)||!hM.statSync(a).isDirectory()){e.status(400).json({error:`The folder configured for mobile module creation does not exist: ${a}`});return}let s=await Qx({...t,folder:a,project:n});e.status(201).json(s)}));var fM=Ls;var SM=uV();SM.get("/",$e(async(r,e)=>{let t=Ve(),n=await Sr(t),o=await Ch(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 yM=SM;import{Router as dV}from"express";var Rh=dV();Rh.get("/",$e((r,e)=>{let t=Fx(Ve(),At);e.status(200).json(t)}));Rh.get("/names",$e((r,e)=>{let n=Ve().config.environments?.map(o=>o.name)??[];e.status(200).json(n)}));var bM=Rh;import{Router as pV}from"express";var EM=pV();EM.get("/",(r,e)=>{e.status(200).json({userId:Qu(),orgId:Xi(),cliVersion:Ah??"0.0.0"})});var TM=EM;import{Router as mV}from"express";import xh from"path";var ed=mV();ed.patch("/:testPath",$e(async(r,e)=>{let t=r.params.testPath;if(!t){e.status(400).json({error:"Missing testPath in path"});return}let n;try{n=yb.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=Ve(),i=t.endsWith(".test.yaml")?t:`${t}.test.yaml`,a=await Sr(o);await tM({filePath:i,steps:n.steps,settings:n.settings,folder:o.rootDir,project:o,momenticFiles:a,schemaVersion:ro});let s={message:"ok"};e.status(200).json(s)}));ed.post("/",$e((r,e)=>{let t;try{t=Sb.parse(r.body)}catch(m){e.status(400).json({error:`Invalid request body: ${m}`});return}let{name:n,description:o,settings:i,pathSegments:a}=t;if(!n||typeof n!="string"){e.status(400).json({error:"Missing or invalid 'name' in body"});return}try{ma(n)}catch(m){e.status(400).json({error:m.message});return}let s=Ve(),c=xh.join(s.rootDir,...a),{fullPath:l,testId:u}=eM({name:n,description:o,steps:[],settings:i,folder:c}),d=xh.basename(l),p=xh.relative(s.rootDir,l),g={id:u,fileName:d,fullPath:l,relativeFilePath:p};e.status(201).json(g)}));ed.get("/:fileName",$e(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=Ve(),i=await Sr(o),s=await Wu(n,At,i);e.status(200).json(s)}));var vM=ed;var td=class extends ji{constructor(t,n){super(t,n);this.client=t;this.orgId=n}async fetchEnvironment(t,n){let o=Ve();return vs(t,o,w)}};var CM="10mb";async function RM(r){let{serverPort:e,apiKey:t,momenticServerUrl:n,staticDir:o,initialProject:i,driverLogLevel:a,regenerateCache:s,alwaysSaveCache:c,noCache:l}=r;n&&cM(n),await uM(t);let u=Xi(),d=Qu(),p=r.logger.child({orgId:u,userId:d});dM(i,A=>As({configFilePath:A}));let g=wM();g.use(gV()),g.use(AM.json({limit:CM})),g.use(AM.urlencoded({extended:!1,limit:CM}));let m=SV();if(m.use("/folders",Th),m.use("/entities",yM),m.use("/identify",TM),m.use("/mobile-tests",vM),m.use("/mobile-modules",fM),m.use("/assets",gM),m.use("/git",vh),m.use("/environments",bM),g.use("/api",m),g.use((A,I,k)=>{w.debug({url:A.url,path:A.path,query:A.query,method:A.method,body:A.body,headers:A.rawHeaders,client:A.ip},"Incoming request on mobile-desktop-server"),I.on("close",()=>{I.statusCode>=400&&(w.error({url:A.url,method:A.method,statusCode:I.statusCode},"Request completed in error on mobile-desktop-server"),At.error({url:A.url,method:A.method,statusCode:I.statusCode},"Request completed in error on mobile-desktop-server"))}),k()}),g.use((A,I,k,G)=>{if(A instanceof Error&&A.message.includes("BadRequestError: request aborted")){k.status(400).send("Client disconnected");return}w.error({stack:A.stack,msg:A.message,err:A,url:I.url,method:I.method},"Unhandled exception leading to 500 on mobile-desktop-server"),At.error({stack:A.stack,msg:A.message,err:A,url:I.url,method:I.method},"Unhandled exception leading to 500 on mobile-desktop-server"),k.status(500).send(`Internal Server Error: ${A.message}`)}),o){let A=wM.static(o,{setHeaders:I=>{I.setHeader("Cache-Control","no-cache")},redirect:!1});g.use(A),g.use("*",(I,k)=>{k.sendFile(bV.join(o,"index.html"))})}let h=yV.createServer(g),f=`http://localhost:${e}`;await new Promise(A=>{try{h.listen(e,()=>{p.info(`Mobile desktop server is running at ${f}`),A()})}catch(I){I.message.includes("EADDRINUSE")?EV(e):w.error(`An unexpected error occurred while starting the server: ${I.message}`),process.exit(1)}});let b={type:"API_KEY",baseUrl:bh(),apiKey:t,logger:p},C=new Mr(b),R=Ve(),v={...b,mode:"interactive"},{dispose:M}=kx({baseServer:h,logger:p,authorization:b,globalStateManager:mM,getOrgId:()=>Xi(),getGitMetadata:async()=>await Gi(p,C,R),androidDriverFactory:async({socket:A,logger:I,creationOpts:k})=>{let G=Math.floor(Math.random()*1e4)+4e4,ge=await Wl(G,"appium");return qc({logger:I,driverLogLevel:a,apiClient:C,creationOpts:k,socket:A,appiumPort:ge,sessionId:A.id,orgId:Xi(),onStatusUpdate:be=>{A.emit("connectionStatusUpdate",{message:be})}})},mobileGeneratorFactory:async A=>new Ki({baseUrl:bh(),apiKey:t,logger:p,mode:"interactive"}),browserGeneratorFactory:async A=>new Lo(R.config.ai?.agentConfig,v),browserEnricherFactory:async A=>new Wi(v,new Lo(R.config.ai?.agentConfig,v)),storageFactory:async A=>new td(C,A),cacheStorageFactory:async(A,I)=>Ku({orgId:A,client:C,gitMetadata:I,regenerateCache:s??!1,noCache:l??!1,alwaysSaveCache:c??!1}),localToolsFactory:async()=>new qi({httpClient:C,fakerSeed:void 0}),keepSessionAlive:A=>C.extendAndroidEmulatorTtl(A),settingsFactory:async()=>({emulator:R.config.emulator})});process.once("SIGUSR2",async()=>{return;try{await M(),await Tt.flush()}catch(A){w.error({err:A},"Error during session dispose on SIGUSR2")}try{h.close(()=>{process.kill(process.pid,"SIGUSR2")})}catch{process.kill(process.pid,"SIGUSR2")}}),process.once("SIGTERM",async()=>{w.info("SIGTERM in Momentic mobile app received");try{await M(),await Tt.flush()}finally{h.close(()=>process.exit(0))}}),process.once("SIGINT",async()=>{w.info("SIGINT in Momentic mobile app received");try{await M(),await Tt.flush()}finally{h.close(()=>process.exit(0))}})}fV.setMaxListeners(25);process.on("warning",r=>{At.warn({err:r},`Node warning received on mobile-desktop-server: ${r.message}`)});process.on("uncaughtException",r=>{At.error({err:r},"Uncaught exception on mobile-desktop-server"),w.error(`Oh no! The Momentic mobile desktop app encountered a fatal error \u{1F61E}. Error logs: ${r.message}`)});process.on("unhandledRejection",r=>{At.error({reason:`${r}`,stack:r?.stack},"Uncaught exception on mobile-desktop-server (promise rejection)"),w.error(`Oh no! The Momentic mobile desktop app encountered an asynchronous error \u{1F61E}. Error logs: ${r}`)});function EV(r){w.error(hV`Port ${r} is already in use by another process. Please close the other process and try again.
4390
4390
  Using Bash on MacOS or Linux:
4391
4391
  lsof -t -i :58888 | xargs kill -9
4392
4392
 
@@ -4395,7 +4395,7 @@ ${n.map(o=>o.configFilePath)}`);if(n.length===0)throw new Error("No valid Moment
4395
4395
  `)}import BV from"open";import id from"path";import{fileURLToPath as zV}from"url";import{InvalidArgumentError as Mh,Option as dt}from"@commander-js/extra-typings";import{z as TV}from"zod";var xM=58890;function MM(r){let e=parseInt(r,10);if(isNaN(e))throw new Mh("Not a number.");return e}var Ns=new dt("--api-key <key>","Momentic API key").env("MOMENTIC_API_KEY").argParser(r=>{if(!r)throw new Mh("API key is required.");return r}).makeOptionMandatory(),_h=new dt("-c, --config <configPath>","Absolute or relative path to a Momentic configuration file."),Ds=new dt("--server <server>","Momentic server to use.").env("MOMENTIC_SERVER").default("https://api.momentic.ai").argParser(r=>{try{return TV.string().url().parse(r),r}catch{throw new Mh("Not a valid URL.")}}),Ph=new dt("-y, --yes","Skip all confirmation prompts.").env("CI"),Ih=new dt("--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}),Oh=new dt("--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}),Lh=new dt("--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}),Nh=new dt("--tag <tag>","Tag identifier for the asset."),_M=new dt("--channel <channel>","Channel name for the asset."),PM=new dt("--channel <channel>","Channel name for the asset.").makeOptionMandatory(),IM=new dt("--env <env>","Environment to run all tests in (overrides test-level configuration)."),OM=new dt("--local-avd-id <localAvdId>","Force tests to use a specific local Android Virtual Device (AVD) instead of remote emulators."),LM=new dt("--local-apk-path <localApkPath>","Path to a local APK file to install when running tests with a local emulator. Overrides remote asset configuration."),NM=new dt("-p, --parallel <parallel>","The number of tests to run in parallel. Defaults to 1.").argParser(MM),Dh=new dt("--output-dir <outputDir>","Output directory to store run artifacts such as screenshots, results, and logs."),DM=new dt("--upload-results","Upload test results to Momentic Cloud.").default(!1),kh=new dt("--log-level <logLevel>","Log level for Momentic and dependent services.").choices(["error","warn","info","debug"]),kM=new dt("--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}),UM=new dt("--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(MM);import{randomUUID as LV}from"crypto";import{existsSync as NV}from"fs";import Uh from"fs";import rd from"path";import{cwd as AV}from"process";async function FM({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(p=>Uh.existsSync(p)),d=AV();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:
4396
4396
  - ${r.join(`
4397
4397
  - `)}
4398
- `),r.forEach(p=>{if(!Uh.existsSync(p))throw new Error(`Path '${p}' does not exist.`);let g,m;try{g=Uh.statSync(p),m=g.isDirectory()}catch(f){a.warn({err:f},`Skipping path ${p} because it cannot be read`);return}let h=rd.resolve(p);Object.values(e.mobileTests).filter(f=>m?f.fullFilePath.startsWith(h):f.fullFilePath===h).forEach(f=>{c.add(f.fullFilePath)})})):(a.info("The arguments provided don't appear to be valid paths. Treating them as substrings instead... "),Object.values(e.mobileTests).forEach(p=>{r.some(g=>p.relativePath.includes(g))&&c.add(p.fullFilePath)}))}else{!n&&!await Hl("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=rd.relative(t.rootDir,u);o&&!o.some(p=>new RegExp(p).test(d))&&c.delete(u),i&&i.some(p=>new RegExp(p).test(d))&&c.delete(u)}return(await Promise.all(Array.from(c).map(async u=>{try{let d=rd.relative(t.rootDir,u),p=await Wu(u,a,e),g=rd.basename(u,".test.yaml");return{id:p.id,name:g,description:p.description,schemaVersion:p.schemaVersion,settings:p.settings,steps:p.steps,fullFilePath:u,relativeFilePath:d,quarantined:!!s[p.id],quarantinedReason:s[p.id]}}catch(d){a.error(`Failed to read and resolve mobile test at '${u}': ${d}`),process.exit(1)}}))).filter(u=>!!u)}import{randomUUID as wV}from"crypto";import{existsSync as CV,statSync as RV}from"fs";import{cloneDeep as xV}from"lodash-es";import MV from"path";async function BM(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,p=await i.startRun({logger:a,testId:c.id,testName:c.name,runId:s,testDescription:c.description,schemaVersion:c.schemaVersion,originalSteps:{steps:xV(c.steps),beforeSteps:void 0,afterSteps:void 0},quarantined:c.quarantined,quarantinedReason:c.quarantinedReason}),g=a.child(p.loggerBindings||{}),m=1+(c.settings?.retries??u.config.retries??1);try{for(let h=0;h<m;h++){let f=new Date,E=await _V({runTracer:p,testDefinition:c,metadata:n,constants:{attemptNumber:h,totalAttempts:m},fixtures:{...t,logger:g},inputs:e,options:o}),b=new Date;if(E.status!=="FAILED")return await p.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!==m-1){a.warn("Retrying failed mobile run");continue}return a.error("Mobile test failed after all exhausting attempts"),await p.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 _V(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:p,logger:g,usageTracker:m}=i,{logUpdate:h,channel:f,tag:E,project:b,envOverride:C}=a,{regenerateCache:R,alwaysSaveCache:v,noCache:M,logLevel:A,localAvdId:I,localApkPath:k}=s;c!==0&&h("RETRY",`attempt ${c}/${l}`);let G={...a.project.config.emulator,...t.settings?.emulator},ge=k?MV.resolve(k):void 0;if(ge&&(!CV(ge)||!RV(ge).isFile()))throw new Error(`Local APK path "${ge}" does not exist. Provide a valid file path via --local-apk-path.`);let be=Ku({orgId:u,client:p,gitMetadata:d,regenerateCache:R??!1,alwaysSaveCache:v??!1,noCache:M??!1}),Re=new ji(p,u),K={type:"API_KEY",baseUrl:p.baseUrl,apiKey:p.apiKey,logger:g,mode:"runner"},$=new Ki(K),le=new Lo(b.config.ai?.agentConfig,K),Q=new Wi(K,le),Qe=new qi({httpClient:p,fakerSeed:void 0}),ke=Math.floor(Math.random()*1e4)+4e4,Gt=await Wl(ke,"appium"),qt=G.region==="local"?ge??t.settings?.defaultApkFilePath?.trim():void 0,Ue=f&&!qt?{channel:f,tag:E}:void 0,Ie;if(I||G.region==="local"){if(!G.localEmulatorSettings?.avdId)throw new Error("AVD name is required when region is set to local. Provide --local-avd-id or configure a default local emulator AVD.");Ie={avdId:I??G.localEmulatorSettings?.avdId,apkToInstall:Ue,apkFilePath:qt}}else Ie={region:G.region,apkToInstall:Ue,osVersion:G.remoteEmulatorSettings?.androidVersion??jy};let Pt=wV(),pt=await qc({apiClient:p,logger:g,driverLogLevel:A,creationOpts:Ie,onStatusUpdate:Us=>{g.debug({status:Us},"Limbar emulator status update")},appiumPort:Gt,orgId:u,sessionId:Pt}),Jr=await e.startAttempt({emulatorName:pt.emulatorName,runAttemptId:Pt}),No=g.child(Jr.loggerBindings||{}),ad=await Yc({driver:pt.driver,onLogs:Us=>{Jr.appendLogs(Us)}}),mn=C||t.settings?.defaultEnv,Vh;mn&&(Vh=vs(mn,b,No).variables);let VM=new ii({variablesFromEnvironment:Vh??{},envName:mn,testName:t.name}),Wh=await Bi.init({driver:pt.driver,generator:$,logger:No,limbarClient:pt.limbarClient,playwrightDevice:pt.playwrightDevice,orgId:u,adbPort:pt.adbPort,options:{emulator:G},fixtures:{storage:Re,browserEnricher:Q,browserGenerator:le,localCodeEvalTools:Qe,testContext:VM}}),q;try{q=await Uu({containerName:`mobile test ${t.name}`,fixtures:{controller:Wh,logger:No,cacheStorage:be,usageTracker:m},work:{},inputs:{testName:t.name,steps:t.steps,orgId:u,testMetadata:t},tracer:Jr,callbacks:{}})}finally{await ad(),await pt.cleanup(),await Wh.cleanup()}return await Jr.finish({logger:No,results:q.results,status:q.status}),q}import{debounce as PV}from"ts-debounce";var ks="0.12.0";function IV(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 OV(r){switch(r){case"SUCCESS":return"PASSED";case"FAILED":return"FAILED";case"CANCELLED":return"CANCELLED";case"RUNNING":return"RUNNING";case"IDLE":return"PENDING"}}var Fh=class{constructor(e,t,n,o){this.keepalive=e;this.testId=t;this.testName=n;this.diskStorage=o;this.interactionTracer=new Mo,un.initializeRootTracerContext(this.interactionTracer)}children=[];finished=!1;interactionTracer;getParentStepIdChain(){return[]}attachBeforeScreenshot(e){let{snapshotId:t,screenshot:n}=e;this.diskStorage.storeFile({name:`${Da}/${t}.jpeg`,contents:n})}attachAfterScreenshot(e){let{snapshotId:t,screenshot:n}=e;this.diskStorage.storeFile({name:`${Da}/${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:OV(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 Ji(this.keepalive,this.testId,this.testName,this.diskStorage);return this.children.push(e),e}},Ji=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(`${Da}/${t}.jpeg`)}getParentStepIdChain(){return[]}async startStep(e){this.keepalive();let t=new Fh(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:IV(e.status),finishedAt:e.finishedAt}))))}},Bh=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(`
4398
+ `),r.forEach(p=>{if(!Uh.existsSync(p))throw new Error(`Path '${p}' does not exist.`);let g,m;try{g=Uh.statSync(p),m=g.isDirectory()}catch(f){a.warn({err:f},`Skipping path ${p} because it cannot be read`);return}let h=rd.resolve(p);Object.values(e.mobileTests).filter(f=>m?f.fullFilePath.startsWith(h):f.fullFilePath===h).forEach(f=>{c.add(f.fullFilePath)})})):(a.info("The arguments provided don't appear to be valid paths. Treating them as substrings instead... "),Object.values(e.mobileTests).forEach(p=>{r.some(g=>p.relativePath.includes(g))&&c.add(p.fullFilePath)}))}else{!n&&!await Hl("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=rd.relative(t.rootDir,u);o&&!o.some(p=>new RegExp(p).test(d))&&c.delete(u),i&&i.some(p=>new RegExp(p).test(d))&&c.delete(u)}return(await Promise.all(Array.from(c).map(async u=>{try{let d=rd.relative(t.rootDir,u),p=await Wu(u,a,e),g=rd.basename(u,".test.yaml");return{id:p.id,name:g,description:p.description,schemaVersion:p.schemaVersion,settings:p.settings,steps:p.steps,fullFilePath:u,relativeFilePath:d,quarantined:!!s[p.id],quarantinedReason:s[p.id]}}catch(d){a.error(`Failed to read and resolve mobile test at '${u}': ${d}`),process.exit(1)}}))).filter(u=>!!u)}import{randomUUID as wV}from"crypto";import{existsSync as CV,statSync as RV}from"fs";import{cloneDeep as xV}from"lodash-es";import MV from"path";async function BM(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,p=await i.startRun({logger:a,testId:c.id,testName:c.name,runId:s,testDescription:c.description,schemaVersion:c.schemaVersion,originalSteps:{steps:xV(c.steps),beforeSteps:void 0,afterSteps:void 0},quarantined:c.quarantined,quarantinedReason:c.quarantinedReason}),g=a.child(p.loggerBindings||{}),m=1+(c.settings?.retries??u.config.retries??1);try{for(let h=0;h<m;h++){let f=new Date,E=await _V({runTracer:p,testDefinition:c,metadata:n,constants:{attemptNumber:h,totalAttempts:m},fixtures:{...t,logger:g},inputs:e,options:o}),b=new Date;if(E.status!=="FAILED")return await p.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!==m-1){a.warn("Retrying failed mobile run");continue}return a.error("Mobile test failed after all exhausting attempts"),await p.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 _V(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:p,logger:g,usageTracker:m}=i,{logUpdate:h,channel:f,tag:E,project:b,envOverride:C}=a,{regenerateCache:R,alwaysSaveCache:v,noCache:M,logLevel:A,localAvdId:I,localApkPath:k}=s;c!==0&&h("RETRY",`attempt ${c}/${l}`);let G={...a.project.config.emulator,...t.settings?.emulator},ge=k?MV.resolve(k):void 0;if(ge&&(!CV(ge)||!RV(ge).isFile()))throw new Error(`Local APK path "${ge}" does not exist. Provide a valid file path via --local-apk-path.`);let be=Ku({orgId:u,client:p,gitMetadata:d,regenerateCache:R??!1,alwaysSaveCache:v??!1,noCache:M??!1}),Re=new ji(p,u),K={type:"API_KEY",baseUrl:p.baseUrl,apiKey:p.apiKey,logger:g,mode:"runner"},$=new Ki(K),le=new Lo(b.config.ai?.agentConfig,K),Q=new Wi(K,le),Qe=new qi({httpClient:p,fakerSeed:void 0}),ke=Math.floor(Math.random()*1e4)+4e4,Gt=await Wl(ke,"appium"),qt=G.region==="local"?ge??t.settings?.defaultApkFilePath?.trim():void 0,Ue=f&&!qt?{channel:f,tag:E}:void 0,Ie;if(I||G.region==="local"){if(!G.localEmulatorSettings?.avdId)throw new Error("AVD name is required when region is set to local. Provide --local-avd-id or configure a default local emulator AVD.");Ie={avdId:I??G.localEmulatorSettings?.avdId,apkToInstall:Ue,apkFilePath:qt}}else Ie={region:G.region,apkToInstall:Ue,osVersion:G.remoteEmulatorSettings?.androidVersion??jy};let Pt=wV(),pt=await qc({apiClient:p,logger:g,driverLogLevel:A,creationOpts:Ie,onStatusUpdate:Us=>{g.debug({status:Us},"Limbar emulator status update")},appiumPort:Gt,orgId:u,sessionId:Pt}),Jr=await e.startAttempt({emulatorName:pt.emulatorName,runAttemptId:Pt}),No=g.child(Jr.loggerBindings||{}),ad=await Yc({driver:pt.driver,onLogs:Us=>{Jr.appendLogs(Us)}}),mn=C||t.settings?.defaultEnv,Vh;mn&&(Vh=vs(mn,b,No).variables);let VM=new ii({variablesFromEnvironment:Vh??{},envName:mn,testName:t.name}),Wh=await Bi.init({driver:pt.driver,generator:$,logger:No,limbarClient:pt.limbarClient,playwrightDevice:pt.playwrightDevice,orgId:u,adbPort:pt.adbPort,options:{emulator:G},fixtures:{storage:Re,browserEnricher:Q,browserGenerator:le,localCodeEvalTools:Qe,testContext:VM}}),q;try{q=await Uu({containerName:`mobile test ${t.name}`,fixtures:{controller:Wh,logger:No,cacheStorage:be,usageTracker:m},work:{},inputs:{testName:t.name,steps:t.steps,orgId:u,testMetadata:t},tracer:Jr,callbacks:{}})}finally{await ad(),await pt.cleanup(),await Wh.cleanup()}return await Jr.finish({logger:No,results:q.results,status:q.status}),q}import{debounce as PV}from"ts-debounce";var ks="0.12.1";function IV(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 OV(r){switch(r){case"SUCCESS":return"PASSED";case"FAILED":return"FAILED";case"CANCELLED":return"CANCELLED";case"RUNNING":return"RUNNING";case"IDLE":return"PENDING"}}var Fh=class{constructor(e,t,n,o){this.keepalive=e;this.testId=t;this.testName=n;this.diskStorage=o;this.interactionTracer=new Mo,un.initializeRootTracerContext(this.interactionTracer)}children=[];finished=!1;interactionTracer;getParentStepIdChain(){return[]}attachBeforeScreenshot(e){let{snapshotId:t,screenshot:n}=e;this.diskStorage.storeFile({name:`${Da}/${t}.jpeg`,contents:n})}attachAfterScreenshot(e){let{snapshotId:t,screenshot:n}=e;this.diskStorage.storeFile({name:`${Da}/${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:OV(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 Ji(this.keepalive,this.testId,this.testName,this.diskStorage);return this.children.push(e),e}},Ji=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(`${Da}/${t}.jpeg`)}getParentStepIdChain(){return[]}async startStep(e){this.keepalive();let t=new Fh(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:IV(e.status),finishedAt:e.finishedAt}))))}},Bh=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(`
4399
4399
  `);this.logStream.write(t+`
4400
4400
  `)}async finish(e){if(this.finished)return;this.finished=!0;let{logger:t,status:n,results:o,beforeResults:i,afterResults:a}=e,s={...this.metadata,status:n,finishedAt:new Date,results:bu(o,t),beforeResults:i?bu(i,t):void 0,afterResults:a?bu(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 Ji(this.keepalive,this.testId,this.testName,this.diskStorage);return this.children.push(e),e}async startMainStepList(){let e=new Ji(this.keepalive,this.testId,this.testName,this.diskStorage);return this.children.push(e),e}async startAfterStepList(){let e=new Ji(this.keepalive,this.testId,this.testName,this.diskStorage);return this.children.push(e),e}async getScreenshot(e,t){return this.diskStorage.readFile(`${Da}/${t}.jpeg`)}},zh=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:vn,runAttemptSchemaVersion:EE,startedAt:new Date,status:"RUNNING"};n.storeFile({name:"metadata.json",contents:JSON.stringify(o,null,2)});let i=PV(async()=>{await this.client.extendAndroidEmulatorTtl(e.emulatorName)},3e4,{maxWait:6e4}),a=new Bh(()=>void i(),this.testId,this.testName,t,o,n);return this.children.push(a),a}},nd=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:ir.CLI,startedAt:new Date,status:"RUNNING",cliVersion:ks,labels:a??[]},c=new Ms(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:ks,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 zh(this.client,e.testId,e.testName,e.runId,n,t);return this.children.push(o),o}};async function zM(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 pn(){try{await z(Promise.all([_E(),Tt.flush()]),{milliseconds:5e3})}catch{}}async function HM(r){let{options:e,fixtures:t,inputs:n,metadata:o}=r,{project:i,apiClient:a,logger:s}=t,{orgId:c,runGroupId:l,gitMetadata:u}=o,{outputDir:d,parallel:p}=e;NV(d)&&w.warn(`Output directory ${d} already exists, removing before test execution...`);let g=await zM(s,a,e.ignoreQuarantine),m=await Sr(i),h=await FM({tests:n.tests,yes:e.yes,project:i,momenticFiles:m,logger:w,quarantinedTestReasons:g}),f=s.child({orgId:c,runGroupId:l,branch:u.gitBranchName}),E=await nd.start({logger:f,orgId:c,runGroupId:l,outputDir:d,client:a,gitMetadata:u,labels:[]}),b=[],C=new Date,R=new Set,v=async()=>DV({runResults:b,startTime:C,ranTests:R,apiClient:a,uploadResults:e.uploadResults??!1,outputDir:d}),M=[],A=async Re=>{w.warn(`${Re} Stopping tests and printing latest results.`),await E.finish({logger:f,status:"CANCELLED"}),await v(),await Promise.allSettled(M.map(K=>K())),await pn(),process.exit(1)},I=async()=>{await A("SIGINT received.")};process.once("SIGINT",I);let k;if(e.timeoutMinutes!==void 0&&e.timeoutMinutes>0){let Re=e.timeoutMinutes*60*1e3;k=setTimeout(()=>{A(`Timeout of ${e.timeoutMinutes} minute(s) reached.`)},Re)}let G={};for(let Re=0;Re<h.length;Re++){let K=Object.values(G);K.length===p&&await Promise.race(K.map(Q=>Q.promise));let $=h[Re],le=`test-${Re}`;G[le]={done:!1,promise:(async({testDefinition:Q})=>{R.add(le);let Qe=Q.relativeFilePath.includes("..")?Q.fullFilePath:Q.relativeFilePath;Ua({status:"START",testLogRef:Qe,getRunningTestsCount:()=>R.size,getTotalTestsCount:()=>h.length});let ke=setInterval(()=>Ua({status:"RUN",testLogRef:Qe,getRunningTestsCount:()=>R.size,getTotalTestsCount:()=>h.length}),5*60*1e3),Gt=LV(),qt=f.child({testId:Q.id,runId:Gt}),Ue=new $c({logger:qt,reporter:new $u(a),runType:"mobile-test-run",runId:Gt,testMetadata:Q,suiteMetadata:void 0});try{let Ie=await BM({metadata:{...o,runId:Gt},fixtures:{...t,tracer:E,logger:qt,usageTracker:Ue},inputs:{...n,project:i,testDefinition:Q,channel:n.channel??Q.settings?.defaultChannel,tag:n.tag??Q.settings?.defaultTag,logUpdate:(Pt,pt)=>Ua({status:Pt,testLogRef:Qe,getRunningTestsCount:()=>R.size,getTotalTestsCount:()=>h.length,additionalText:pt}),runSigIntHandlers:M},options:e});Ua({status:Ie.status,testLogRef:Qe,getRunningTestsCount:()=>R.size,getTotalTestsCount:()=>h.length}),b.push(Ie)}catch(Ie){let Pt=`Encountered unexpected fatal error when running test '${Q.name}': ${Ie.message}
4401
4401
  ${Ie.stack}`;w.error(Pt),qt.error({err:Ie},`Encountered unexpected fatal error when running test ${Q.name}`)}finally{clearInterval(ke),G[le].done=!0,delete G[le]}await Ue.flush(s)})({testDefinition:$})}}await Promise.allSettled(Object.values(G).map(Re=>Re.promise)),k&&clearTimeout(k);let be=b.some(Re=>Re.status==="FAILED"&&!Re.quarantined)?"FAILED":"PASSED";return await E.finish({logger:f,status:be}),process.off("SIGINT",I),v()}async function DV({runResults:r,startTime:e,ranTests:t,apiClient:n,uploadResults:o,outputDir:i}){let a=n.getAppUrl(),s=PE({results:r,startTime:e.getTime(),onFailed:c=>{},getDisplayLine:c=>{let l=`${Fp}- ${c.filePath}`;return c.runId&&(l+=` ( link when uploaded: ${a}/runs/${c.runId} )`),l},entity:"mobile test"});return w.log(""),o?(w.success(`Test results have been saved to the folder ${i}. Uploading to Momentic Cloud...`),await Xu({client:n,consoleLogger:w,resultsPath:i})):w.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 Hh(){jw(),NE("Chromium")||(po?(await Hl("The Chromium browser is not installed but is required for automating webviews. Install it now?")||process.exit(1),await Vl({rawBrowsers:["chromium"],force:!1,all:!1})):(w.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)))}HA({serviceName:"mobile-cli"});lr.setApp("mobile-cli");var Yn=new kV;Yn.name("momentic-mobile").description("Momentic Mobile CLI").version(ks);var HV=Yn.command("assets").description("Manage mobile testing assets");HV.command("upload").description("Upload an asset for mobile tests").argument("<file>","Path to the asset file to upload").addOption(Ns).addOption(Ds).addOption(Nh).addOption(PM).action(async(r,e)=>{let{apiKey:t,server:n,tag:o,channel:i}=e,a=id.resolve(r);od.existsSync(a)||(w.error(`File not found: ${a}`),process.exit(1));let s=new Mr({baseUrl:n,apiKey:t,logger:w});/\.apk$/i.test(a)||(w.error(`File is not an APK file: ${a}`),process.exit(1)),await Kc({tag:o?.toLowerCase(),channel:i.toLowerCase(),filePath:a,apiClient:s,logger:w})});Yn.command("app").addOption(Ns).addOption(Ds).addOption(Ph).addOption(_h).addOption(kh).addOption(Ih).addOption(Oh).addOption(Lh).action(async r=>{let{apiKey:e,server:t,yes:n,disableCache:o,saveCache:i,regenerateCache:a}=r,s=zp(r.logLevel);lr.setApp("mobile-desktop-server");let c=new Mr({baseUrl:t,apiKey:e,logger:lr});await dh({client:c,skipPrompts:n}),w.debug("API key check complete");let l=zV(import.meta.url),u=id.dirname(l),d=id.resolve(u,"..","static");await Hh(),w.debug({appiumHome:us},"Resolved resource paths");let p=await As({configFilePath:r.config}),g=xM;await RM({momenticServerUrl:t,serverPort:g,apiKey:e,staticDir:d,initialProject:p,driverLogLevel:s,logger:lr,regenerateCache:a,noCache:o,alwaysSaveCache:i});let m=`http://localhost:${g}`;w.info(`Local app started on: ${m}`),await BV(m)});var GM=Yn.command("results").description("Merge and upload test results.");GM.command("merge").description("Merge test results files.").addOption(Dh).addArgument(new Gh("<resultsPath>","Path to a directory that contains on or more test results archives.").argRequired()).action(async(r,e)=>{let{outputDir:t}=e;t||(w.error("Output directory is required."),process.exit(1)),od.existsSync(r)||(w.warn("Results path does not exist, skipping merge."),process.exit(0)),od.existsSync(t)&&w.warn(`Output directory ${t} already exists, removing before merging...`),iM(lr,t,r),await pn(),process.exit(0)});var GV=new Gh("<results>","Path to the results archive.").argRequired();GM.command("upload").description("Upload test results to Momentic cloud.").addOption(Ns).addOption(Ds).addArgument(GV).action(async(r,e)=>{let{apiKey:t,server:n}=e,o=lr,i=new Mr({baseUrl:n,apiKey:t,logger:o});await Xu({consoleLogger:w,resultsPath:r,client:i}),await pn(),process.exit(0)});var VV=Yn.command("run").alias("test").description("Run tests on the local machine");VV.addOption(Ns).addOption(Ds).addOption(_h).addOption(Ph).addOption(NM).addOption(kh).addOption(Ih).addOption(Oh).addOption(Lh).addOption(Dh).addOption(DM).addOption(kM).addOption(UM).addOption(Nh).addOption(_M).addOption(IM).addOption(OM).addOption(LM).addArgument(new Gh("<tests...>","One or more test file path or folders that exist on the local machine.").argOptional()).action(async(r,e)=>{let{apiKey:t,server:n,tag:o,channel:i,outputDir:a}=e,s=zp(e.logLevel);await Hh(),w.debug({appiumHome:us},"Resolved resource paths");let c=await As({configFilePath:e.config}),l=a??c.config.outputDir??$x,u=e.parallel??c.config.parallel??1;w.debug("Checking API key and dependencies");let d=new Mr({baseUrl:n,apiKey:t,logger:w}),{orgId:p,userId:g}=await dh({client:d,skipPrompts:e.yes});w.debug("API key check and browser installation complete");let m=FV(),h=lr.child({runGroupId:m,orgId:p,userId:g}),f=await Gi(lr,d,c);h.debug(f,"Got local git metadata");try{let E=await HM({options:{...e,parallel:u,outputDir:l,alwaysSaveCache:e.saveCache,noCache:e.disableCache,logLevel:s,timeoutMinutes:e.timeoutMinutes},fixtures:{logger:h,project:c,apiClient:d},inputs:{envOverride:e.env,tag:o,channel:i,tests:r},metadata:{gitMetadata:f,runGroupId:m,orgId:p}});await pn(),E.failed>0?process.exit(1):process.exit(0)}catch(E){w.error("Failed to run tests locally. Please check the error message below or run with the --verbose flag."),w.error(E),lr.error({err:E},"Failed to run tests locally"),await pn(),process.exit(1)}});Yn.command("init").description("Initialize an empty Momentic project in the current working directory").addOption(new UV("--name <name>","Name of the project")).action(async r=>{w.info(`Welcome to the Momentic Mobile project setup wizard! \u{1F680}