momentic-mobile 0.7.0 → 0.7.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 +7 -7
- package/npm-shrinkwrap.json +20 -20
- package/package.json +1 -1
package/bin/cli.js
CHANGED
|
@@ -20,7 +20,7 @@ ${this.decisions.map(e=>e.toString()).join(`
|
|
|
20
20
|
`).slice(o).filter(Boolean).join(`
|
|
21
21
|
`);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",Ta(e,...t))}error(e,...t){this._log("error",Ta(e,...t))}info(e,...t){this._log("info",Ta(e,...t))}log(e,...t){this._log("log",Ta(e,...t))}warn(e,...t){this._log("warn",Ta(e,...t))}getBuffer(){return this._buffer.length>0?this._buffer:void 0}};function gb(r){let e=globalThis.console,t=new El;globalThis.console=t;try{r()}finally{let o=t.getBuffer()?.map(i=>i.message).join(`
|
|
22
22
|
`);process.stderr.write(`${o}
|
|
23
|
-
`),globalThis.console=e}}var am=" ".repeat(6);import KO from"fetch-retry";import YO from"os";import hb,{multistream as XO}from"pino";import JO from"pino-pretty";import ZO from"pino-std-serializers";var Wo=new Map,QO=!0,fb="Log throttle exceeded",eL=100,tL=5e3,rL=KO(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}}),sm=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??YO.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=QO?hb(a):hb(a,XO([{stream:JO({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 rL(this.site,{method:"POST",headers:{"Content-Type":"application/json","signoz-access-token":"CumAaTMUcwjt05OddAmefKgshbhfRmWxzxih"},body:Yn(e),signal:AbortSignal.timeout(5e3)});if(!t.ok)throw new Error(`Got error status (${t.statusText}) from SigNoz`)}catch{}}shouldAllowLog(e){if(e===fb)return!0;let t=Date.now();return t-this.lastWindowStart>tL&&(this.logsInCurrentWindow=0,this.droppedLogsInWindow&&this.log("error",void 0,fb),this.droppedLogsInWindow=!1,this.lastWindowStart=t),this.logsInCurrentWindow<eL?(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(ba[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=ZO.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:iy({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,Wo.set("app",this),Wo.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=ay[e]):(this.minLevelValue=ba[e],this.consoleLogger.level=e)}enableConsoleLogs(){this.disableConsoleLogs=!1}},$o=({app:r,hostname:e,disableConsoleLogs:t})=>(Wo.has(r)||Wo.set(r,new sm({bindings:{app:r},hostname:e,disableConsoleLogs:t})),Wo.get(r));async function Sb(){await Promise.all([...Wo.values()].map(r=>r.flush()))}import{hostname as nL}from"os";var rr=$o({app:"cli",hostname:nL(),disableConsoleLogs:!0}).child({cliVersion:"0.7.0"});function lm(r){if(!r)return;r=r.toLowerCase();let e=ml.safeParse(r);if(e.success)return R.setMinLevel(e.data),e.data}function yb({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 gb(()=>{if(c.forEach(u=>{R.log(""),o(u)}),c.length){R.log("");let u=c.length===1?"":"s";R.error(`${c.length} ${t}${u} failed:`),c.forEach(d=>{R.dimmed(n(d))})}if(l.length){R.log("");let u=l.length===1?"":"s";R.warn(`${l.length} ${t}${u} cancelled:`),l.forEach(d=>{R.dimmed(n(d))})}if(a.length){R.log("");let u=a.length===1?"":"s";R.success(`${a.length} ${t}${u} passed:`),a.forEach(d=>{R.dimmed(n(d))})}if(s.length){R.log("");let u=s.length===1?"":"s";R.warn(`${s.length} quarantined ${t}${u} failed:`),s.forEach(d=>{R.dimmed(n(d))})}if(i.length){R.log("");let u=i.length===1?"":"s";R.warn(`${i.length} quarantined ${t}${u} passed:`),i.forEach(d=>{R.dimmed(n(d))})}R.log(""),R.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 va=({status:r,testLogRef:e,getRunningTestsCount:t,getTotalTestsCount:n,additionalText:o})=>{r=r.toUpperCase();let i=r,a;r.includes("FAIL")?(i=qo.bgRed.white("FAIL"),a=3):r.includes("PASS")?(i=qo.bgGreen.white("PASS"),a=3):r.includes("START")?(i=qo.bgBlue.white("START"),a=2):r.includes("CANCEL")?(i=qo.bgRgb(191,68,11).white("CANCEL"),a=1):r.includes("RETRY")?(i=qo.bgRgb(191,68,11).white("RETRY"),a=2):r.includes("RUN")||r.includes("PROG")?(i=qo.bgMagenta.white("RUNNING"),a=0):(R.warn(`Unknown status tried to be logged in run test locally: ${r}`),a=0),oL||(i=`${i}`),R.log(`${i}${" ".repeat(a)} ${e} ${o?`${o} `:""}(${t()}/${n()})`)};import iL from"fs";import{tmpdir as aL}from"os";import sL from"path";import{registry as Aa}from"playwright-core/lib/server";import bb from"proper-lockfile";var Eb=sL.join(aL(),"momenticBrowserInstallation");var cm=["chrome","chromium","chrome-for-testing","ffmpeg"],lL={Chromium:"chromium","Google Chrome":"chrome","Chrome for Testing":"chrome-for-testing"},Tb={chrome:"chrome",chromium:"chromium","chrome-for-testing":"chromium-headless-shell",ffmpeg:"ffmpeg"};function vb(r){let e=Tb[lL[r]??""]??"",t=Aa.findExecutable(e);return!t||t.installType==="none"?!1:um(t)}function um(r){let e=r.executablePath();return iL.existsSync(e)}function cL(r,e){let t=Tb[r];if(!t)throw new Error(`Requested install of unknown browser type ${r}`);let n=Aa.findExecutable(t);if(!n||n.installType==="none")throw new Error(`Requested install of unknown browser type ${r}`);if(!(!e&&um(n)))return n}async function uL({browser:r,force:e}){let t=cL(r,e);if(!t){R.info(`Browser '${r}' is already installed, skipping...`);return}R.info(`Installing browser '${r}'...`);try{await Aa.installDeps([t],!1),await Aa.install([t],!1)}catch(n){if(n.message.includes("Lock file is already being held")){R.warn("Another process is installing Playwright browsers. Waiting for completion before proceeding..");let o=Aa.findExecutable(r),i=5*60*1e3,a=Date.now();for(;Date.now()-a<i&&!um(o);)R.info("Waiting for browser to finish installing..."),await new Promise(s=>setTimeout(s,5e3))}else throw n}}async function Tl({rawBrowsers:r,force:e=!1,all:t=!1}){let n=t?cm:Array.from(new Set(r));try{await bb.lock(Eb,{stale:1e3*60*5,update:1e3*60,realpath:!1,retries:{retries:30,factor:2,maxTimeout:15e3,minTimeout:500}})}catch(i){R.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 uL({browser:i,force:e})}catch(a){o=a,R.error(`Failed to install the ${i} browser: ${a}`)}}finally{await bb.unlock(Eb,{realpath:!1})}if(o)throw o}import{createServer as dL}from"http";async function vl(r,e,t=30){for(let n=0;n<t;n+=1){let o=r+n;if(await Al(o))return o}R.error(`Could not find an available port for ${e} starting from ${r} after ${t} attempts`),process.exit(1)}async function Al(r){return new Promise((e,t)=>{let n=dL();n.once("error",o=>{o.code==="EADDRINUSE"?e(!1):(R.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 BQ from"blocked-at";import HQ from"why-is-node-running";import Gk from"fs";import{tmpdir as Vk}from"os";import jk from"path";import{remote as Wk}from"webdriverio";import{createInstanceClient as Dk}from"@limrun/api";import{execSync as kk}from"child_process";import ZQ,{multistream as e7}from"pino";import r7 from"pino-pretty";var i7=5*1024,mL="...[truncated]",a7=Buffer.byteLength(mL,"utf8");import{PostHog as f7}from"posthog-node";var fn=class extends Error{constructor(e){super(e),this.name="TimeoutError"}};var Ab=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 k(r,e){let{milliseconds:t,fallback:n,message:o,customTimers:i={setTimeout,clearTimeout}}=e,a;if(typeof t!="number"||Math.sign(t)!==1)throw new TypeError(`Expected \`milliseconds\` to be a positive number, got \`${t}\``);return new Promise((s,c)=>{let l;if(e.signal){let{signal:m}=e;if(m.aborted)return c(Ab(m));l=()=>c(Ab(m)),m.addEventListener("abort",l,{once:!0})}let u=()=>{if(e.signal&&e.signal.removeEventListener("abort",l),n)try{s(n())}catch(m){c(m)}else{typeof r.cancel=="function"&&Promise.resolve().then(()=>r.cancel()).catch(()=>{});let m=o instanceof Error?o:new fn(o??`Promise timed out after ${t}ms`);c(m)}};t<1/0&&(a=i.setTimeout(u,t));let d=()=>{i.clearTimeout(a),e.signal&&e.signal.removeEventListener("abort",l)};Promise.resolve(r).then(m=>{d(),s(m)}).catch(m=>{d(),c(m)})})}import{PostHog as R7}from"posthog-node";import{execSync as pL}from"child_process";import Ko from"os";import gL from"v8";var wb,Or,Cb=Ko.platform(),hL=Ko.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),{}),Rb=r=>{try{let e={},t=!1,n=fL(),o=SL(),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=gL.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"),Xn&&R.warn(`Low machine resources detected (memory: ${i} free, cpu: ${a} free)`)):r.debug({memory:n,cpu:o},"Got machine resource usage metrics")}catch{}};function xb(r){if(!Pr)return Rb(r),{interval:setInterval(()=>Rb(r),2e4),cpuMetadata:hL,platform:Cb}}function fL(){let r=Ko.totalmem(),e=Cb==="darwin"?yL():(()=>{let n=Ko.freemem();return{availableMemory:n,rawFreeMemory:n,cachedMemory:0}})(),t=e.availableMemory/r;return{totalMemory:r,freeMemory:e.availableMemory,freePercentage:t}}function SL(){let r=Ko.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,!Or)return Or=t,null;let n={user:t.user-Or.user,nice:t.nice-Or.nice,sys:t.sys-Or.sys,idle:t.idle-Or.idle,irq:t.irq-Or.irq,total:t.total-Or.total};return wb={measurementTime:e,intervalMs:e-Or.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},Or=t,wb}function yL(){try{let r=pL("/usr/bin/vm_stat",{encoding:"utf8",stdio:["pipe","pipe","ignore"]}),t=r.match(/page size of (\d+) bytes/)?.[1],n=t?Number.parseInt(t,10):4096,o=u=>{let m=r.match(new RegExp(`${u}:\\s+(\\d+)\\.`,"i"))?.[1];return m?Number.parseInt(m,10):0},i=o("Pages free"),a=o("Pages inactive"),s=o("Pages speculative"),c=i*n,l=(a+s)*n;return{availableMemory:c+l,rawFreeMemory:c,cachedMemory:l}}catch{let e=Ko.freemem();return{availableMemory:e,rawFreeMemory:e,cachedMemory:0}}}var wl=class{increment(e,t,n){}gauge(e,t){}distribution(e,t,n){}async flush(){}async recordDuration({fn:e}){return await e()}};function bL(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 Rl(r,e){let t=bL(r);return!e||Object.keys(e).length===0?t:{...e,...t}}var eE="=",_l=";",vm=",";var tE=8192;var Zo={};bx(Zo,{getKeyPairs:()=>ZL,parseKeyPairsIntoRecord:()=>QL,parsePairKeyValue:()=>rE,serializeKeyPairs:()=>JL});_e();var XL=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 JL(r){return r.reduce(function(e,t){var n=""+e+(e!==""?vm:"")+t;return n.length>tE?e:n},"")}function ZL(r){return r.getAllEntries().map(function(e){var t=XL(e,2),n=t[0],o=t[1],i=encodeURIComponent(n)+"="+encodeURIComponent(o.value);return o.metadata!==void 0&&(i+=_l+o.metadata.toString()),i})}function rE(r){var e=r.split(_l);if(!(e.length<=0)){var t=e.shift();if(t){var n=t.indexOf(eE);if(!(n<=0)){var o=decodeURIComponent(t.substring(0,n).trim()),i=decodeURIComponent(t.substring(n+1).trim()),a;return e.length>0&&(a=mm(e.join(_l))),{key:o,value:i,metadata:a}}}}}function QL(r){return typeof r!="string"||r.length===0?{}:r.split(vm).map(function(e){return rE(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 Pl;(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"})(Pl||(Pl={}));var eN=",",tN=["OTEL_SDK_DISABLED"];function rN(r){return tN.indexOf(r)>-1}var nN=["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 oN(r){return nN.indexOf(r)>-1}var iN=["OTEL_NO_PATCH_MODULES","OTEL_PROPAGATORS"];function aN(r){return iN.indexOf(r)>-1}var Am=1/0,wm=128,sN=128,lN=128,Rm={OTEL_SDK_DISABLED:!1,CONTAINER_NAME:"",ECS_CONTAINER_METADATA_URI_V4:"",ECS_CONTAINER_METADATA_URI:"",HOSTNAME:"",KUBERNETES_SERVICE_HOST:"",NAMESPACE:"",OTEL_BSP_EXPORT_TIMEOUT:3e4,OTEL_BSP_MAX_EXPORT_BATCH_SIZE:512,OTEL_BSP_MAX_QUEUE_SIZE:2048,OTEL_BSP_SCHEDULE_DELAY:5e3,OTEL_BLRP_EXPORT_TIMEOUT:3e4,OTEL_BLRP_MAX_EXPORT_BATCH_SIZE:512,OTEL_BLRP_MAX_QUEUE_SIZE:2048,OTEL_BLRP_SCHEDULE_DELAY:5e3,OTEL_EXPORTER_JAEGER_AGENT_HOST:"",OTEL_EXPORTER_JAEGER_AGENT_PORT:6832,OTEL_EXPORTER_JAEGER_ENDPOINT:"",OTEL_EXPORTER_JAEGER_PASSWORD:"",OTEL_EXPORTER_JAEGER_USER:"",OTEL_EXPORTER_OTLP_ENDPOINT:"",OTEL_EXPORTER_OTLP_TRACES_ENDPOINT:"",OTEL_EXPORTER_OTLP_METRICS_ENDPOINT:"",OTEL_EXPORTER_OTLP_LOGS_ENDPOINT:"",OTEL_EXPORTER_OTLP_HEADERS:"",OTEL_EXPORTER_OTLP_TRACES_HEADERS:"",OTEL_EXPORTER_OTLP_METRICS_HEADERS:"",OTEL_EXPORTER_OTLP_LOGS_HEADERS:"",OTEL_EXPORTER_OTLP_TIMEOUT:1e4,OTEL_EXPORTER_OTLP_TRACES_TIMEOUT:1e4,OTEL_EXPORTER_OTLP_METRICS_TIMEOUT:1e4,OTEL_EXPORTER_OTLP_LOGS_TIMEOUT:1e4,OTEL_EXPORTER_ZIPKIN_ENDPOINT:"http://localhost:9411/api/v2/spans",OTEL_LOG_LEVEL:Ne.INFO,OTEL_NO_PATCH_MODULES:[],OTEL_PROPAGATORS:["tracecontext","baggage"],OTEL_RESOURCE_ATTRIBUTES:"",OTEL_SERVICE_NAME:"",OTEL_ATTRIBUTE_VALUE_LENGTH_LIMIT:Am,OTEL_ATTRIBUTE_COUNT_LIMIT:wm,OTEL_SPAN_ATTRIBUTE_VALUE_LENGTH_LIMIT:Am,OTEL_SPAN_ATTRIBUTE_COUNT_LIMIT:wm,OTEL_LOGRECORD_ATTRIBUTE_VALUE_LENGTH_LIMIT:Am,OTEL_LOGRECORD_ATTRIBUTE_COUNT_LIMIT:wm,OTEL_SPAN_EVENT_COUNT_LIMIT:128,OTEL_SPAN_LINK_COUNT_LIMIT:128,OTEL_SPAN_ATTRIBUTE_PER_EVENT_COUNT_LIMIT:sN,OTEL_SPAN_ATTRIBUTE_PER_LINK_COUNT_LIMIT:lN,OTEL_TRACES_EXPORTER:"",OTEL_TRACES_SAMPLER:Pl.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 cN(r,e,t){if(!(typeof t[r]>"u")){var n=String(t[r]);e[r]=n.toLowerCase()==="true"}}function uN(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 dN(r,e,t,n){n===void 0&&(n=eN);var o=t[r];typeof o=="string"&&(e[r]=o.split(n).map(function(i){return i.trim()}))}var mN={ALL:Ne.ALL,VERBOSE:Ne.VERBOSE,DEBUG:Ne.DEBUG,INFO:Ne.INFO,WARN:Ne.WARN,ERROR:Ne.ERROR,NONE:Ne.NONE};function pN(r,e,t){var n=t[r];if(typeof n=="string"){var o=mN[n.toUpperCase()];o!=null&&(e[r]=o)}}function nE(r){var e={};for(var t in Rm){var n=t;switch(n){case"OTEL_LOG_LEVEL":pN(n,e,r);break;default:if(rN(n))cN(n,e,r);else if(oN(n))uN(n,e,r);else if(aN(n))dN(n,e,r);else{var o=r[n];typeof o<"u"&&o!==null&&(e[n]=String(o))}}}return e}function ht(){var r=nE(process.env);return Object.assign({},Rm,r)}function oE(r){return r>=48&&r<=57?r-48:r>=97&&r<=102?r-87:r-55}function Il(r){for(var e=new Uint8Array(r.length/2),t=0,n=0;n<r.length;n+=2){var o=oE(r.charCodeAt(n)),i=oE(r.charCodeAt(n+1));e[t++]=o<<4|i}return e}var iE="1.25.1";var gN="deployment.environment";var hN="process.runtime.name";var fN="service.name";var SN="service.instance.id";var yN="telemetry.sdk.name",bN="telemetry.sdk.language",EN="telemetry.sdk.version";var aE=gN;var sE=hN;var Ol=fN;var lE=SN;var Pa=yN,Ia=bN,Oa=EN;var TN="nodejs";var cE=TN;var Qo,Ll=(Qo={},Qo[Pa]="opentelemetry",Qo[sE]="node",Qo[Ia]=cE,Qo[Oa]=iE,Qo);var vN=9,AN=6,wN=Math.pow(10,AN),RN=Math.pow(10,vN);function uE(r){var e=r/1e3,t=Math.trunc(e),n=Math.round(r%1e3*wN);return[t,n]}function dE(r){return r[0]*RN+r[1]}function La(r){return r[0]*1e6+r[1]/1e3}var Zn;(function(r){r[r.SUCCESS=0]="SUCCESS",r[r.FAILED=1]="FAILED"})(Zn||(Zn={}));var mE=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 CN=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},xN=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))},pE=function(){function r(e,t){this._callback=e,this._that=t,this._isCalled=!1,this._deferred=new mE}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,xN([this._that],CN(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 nr;(function(r){r[r.DELTA=0]="DELTA",r[r.CUMULATIVE=1]="CUMULATIVE"})(nr||(nr={}));var Rt;(function(r){r[r.HISTOGRAM=0]="HISTOGRAM",r[r.EXPONENTIAL_HISTOGRAM=1]="EXPONENTIAL_HISTOGRAM",r[r.GAUGE=2]="GAUGE",r[r.SUM=3]="SUM"})(Rt||(Rt={}));var MN=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 Yte=function(r){MN(e,r);function e(t){var n=r.call(this,t)||this;return Object.setPrototypeOf(n,e.prototype),n}return e}(Error);function gE(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 or;(function(r){r[r.DROP=0]="DROP",r[r.SUM=1]="SUM",r[r.LAST_VALUE=2]="LAST_VALUE",r[r.HISTOGRAM=3]="HISTOGRAM",r[r.EXPONENTIAL_HISTOGRAM=4]="EXPONENTIAL_HISTOGRAM"})(or||(or={}));var hE=function(){function r(){this.kind=or.DROP}return r.prototype.createAccumulation=function(){},r.prototype.merge=function(e,t){},r.prototype.diff=function(e,t){},r.prototype.toMetricData=function(e,t,n,o){},r}();var oe;(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"})(oe||(oe={}));var _N=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 PN(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 Cm=function(){function r(e,t,n,o){n===void 0&&(n=!0),o===void 0&&(o=PN(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=gE(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 xm=function(){function r(e,t){this._boundaries=e,this._recordMinMax=t,this.kind=or.HISTOGRAM}return r.prototype.createAccumulation=function(e){return new Cm(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 Cm(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 Cm(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:Rt.HISTOGRAM,dataPoints:n.map(function(i){var a=_N(i,2),s=a[0],c=a[1],l=c.toPointValue(),u=e.type===oe.GAUGE||e.type===oe.UP_DOWN_COUNTER||e.type===oe.OBSERVABLE_GAUGE||e.type===oe.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 IN),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 IN=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 fE=52,ON=2146435072,LN=1048575,Im=1023,Nl=-Im+1,Dl=Im,Na=Math.pow(2,-1022);function kl(r){var e=new DataView(new ArrayBuffer(8));e.setFloat64(0,r);var t=e.getUint32(0),n=(t&ON)>>20;return n-Im}function Ul(r){var e=new DataView(new ArrayBuffer(8));e.setFloat64(0,r);var t=e.getUint32(0),n=e.getUint32(4),o=(t&LN)*Math.pow(2,32);return o+n}function Da(r,e){return r===0||r===Number.POSITIVE_INFINITY||r===Number.NEGATIVE_INFINITY||Number.isNaN(r)?r:r*Math.pow(2,e)}function yE(r){return r--,r|=r>>1,r|=r>>2,r|=r>>4,r|=r>>8,r|=r>>16,r++,r}var NN=function(){var r=function(e,t){return r=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(n,o){n.__proto__=o}||function(n,o){for(var i in o)Object.prototype.hasOwnProperty.call(o,i)&&(n[i]=o[i])},r(e,t)};return function(e,t){if(typeof t!="function"&&t!==null)throw new TypeError("Class extends value "+String(t)+" is not a constructor or null");r(e,t);function n(){this.constructor=e}e.prototype=t===null?Object.create(t):(n.prototype=t.prototype,new n)}}(),Sn=function(r){NN(e,r);function e(){return r!==null&&r.apply(this,arguments)||this}return e}(Error);var EE=function(){function r(e){this._shift=-e}return r.prototype.mapToIndex=function(e){if(e<Na)return this._minNormalLowerBoundaryIndex();var t=kl(e),n=this._rightShift(Ul(e)-1,fE);return t+n>>this._shift},r.prototype.lowerBoundary=function(e){var t=this._minNormalLowerBoundaryIndex();if(e<t)throw new Sn("underflow: "+e+" is < minimum lower boundary: "+t);var n=this._maxNormalLowerBoundaryIndex();if(e>n)throw new Sn("overflow: "+e+" is > maximum lower boundary: "+n);return Da(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=Nl>>this._shift;return this._shift<2&&e--,e},r.prototype._maxNormalLowerBoundaryIndex=function(){return Dl>>this._shift},r.prototype._rightShift=function(e,t){return Math.floor(e*Math.pow(2,-t))},r}();var TE=function(){function r(e){this._scale=e,this._scaleFactor=Da(Math.LOG2E,e),this._inverseFactor=Da(Math.LN2,-e)}return r.prototype.mapToIndex=function(e){if(e<=Na)return this._minNormalLowerBoundaryIndex()-1;if(Ul(e)===0){var t=kl(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 Sn("overflow: "+e+" is > maximum lower boundary: "+t)}var n=this._minNormalLowerBoundaryIndex();if(e<=n){if(e===n)return Na;if(e===n-1)return Math.exp((e+(1<<this._scale))/this._scaleFactor)/2;throw new Sn("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 Nl<<this._scale},r.prototype._maxNormalLowerBoundaryIndex=function(){return(Dl+1<<this._scale)-1},r}();var vE=-10,AE=20,DN=Array.from({length:31},function(r,e){return e>10?new TE(e-10):new EE(e-10)});function Om(r){if(r>AE||r<vE)throw new Sn("expected scale >= "+vE+" && <= "+AE+", got: "+r);return DN[r+10]}var kN=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},Fl=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}(),UN=20,FN=160,Lm=2,BN=function(){function r(e,t,n,o,i,a,s,c,l,u,d){e===void 0&&(e=e),t===void 0&&(t=FN),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(UN)),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&&(z.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=yE(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=Fl.combine(this._highLowAtScale(this.positive,this.scale,t),this._highLowAtScale(e.positive,e.scale,t)),o=Fl.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 Fl(0,-1);var o=t-n;return new Fl(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 wE=function(){function r(e,t){this._maxSize=e,this._recordMinMax=t,this.kind=or.EXPONENTIAL_HISTOGRAM}return r.prototype.createAccumulation=function(e){return new BN(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:Rt.EXPONENTIAL_HISTOGRAM,dataPoints:n.map(function(i){var a=kN(i,2),s=a[0],c=a[1],l=c.toPointValue(),u=e.type===oe.GAUGE||e.type===oe.UP_DOWN_COUNTER||e.type===oe.OBSERVABLE_GAUGE||e.type===oe.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 zN=function(r,e){var t=typeof Symbol=="function"&&r[Symbol.iterator];if(!t)return r;var n=t.call(r),o,i=[],a;try{for(;(e===void 0||e-- >0)&&!(o=n.next()).done;)i.push(o.value)}catch(s){a={error:s}}finally{try{o&&!o.done&&(t=n.return)&&t.call(n)}finally{if(a)throw a.error}}return i},Nm=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=uE(Date.now())},r.prototype.setStartTime=function(e){this.startTime=e},r.prototype.toPointValue=function(){return this._current},r}();var RE=function(){function r(){this.kind=or.LAST_VALUE}return r.prototype.createAccumulation=function(e){return new Nm(e)},r.prototype.merge=function(e,t){var n=La(t.sampleTime)>=La(e.sampleTime)?t:e;return new Nm(e.startTime,n.toPointValue(),n.sampleTime)},r.prototype.diff=function(e,t){var n=La(t.sampleTime)>=La(e.sampleTime)?t:e;return new Nm(t.startTime,n.toPointValue(),n.sampleTime)},r.prototype.toMetricData=function(e,t,n,o){return{descriptor:e,aggregationTemporality:t,dataPointType:Rt.GAUGE,dataPoints:n.map(function(i){var a=zN(i,2),s=a[0],c=a[1];return{attributes:s,startTime:c.startTime,endTime:o,value:c.toPointValue()}})}},r}();var HN=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},ka=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 Dm=function(){function r(e){this.monotonic=e,this.kind=or.SUM}return r.prototype.createAccumulation=function(e){return new ka(e,this.monotonic)},r.prototype.merge=function(e,t){var n=e.toPointValue(),o=t.toPointValue();return t.reset?new ka(t.startTime,this.monotonic,o,t.reset):new ka(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 ka(t.startTime,this.monotonic,o,!0):new ka(t.startTime,this.monotonic,o-n)},r.prototype.toMetricData=function(e,t,n,o){return{descriptor:e,aggregationTemporality:t,dataPointType:Rt.SUM,dataPoints:n.map(function(i){var a=HN(i,2),s=a[0],c=a[1];return{attributes:s,startTime:c.startTime,endTime:o,value:c.toPointValue()}}),isMonotonic:this.monotonic}},r}();var Qn=function(){var r=function(e,t){return r=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(n,o){n.__proto__=o}||function(n,o){for(var i in o)Object.prototype.hasOwnProperty.call(o,i)&&(n[i]=o[i])},r(e,t)};return function(e,t){if(typeof t!="function"&&t!==null)throw new TypeError("Class extends value "+String(t)+" is not a constructor or null");r(e,t);function n(){this.constructor=e}e.prototype=t===null?Object.create(t):(n.prototype=t.prototype,new n)}}(),Nr=function(){function r(){}return r.Drop=function(){return LE},r.Sum=function(){return NE},r.LastValue=function(){return DE},r.Histogram=function(){return kE},r.ExponentialHistogram=function(){return GN},r.Default=function(){return VN},r}();var CE=function(r){Qn(e,r);function e(){return r!==null&&r.apply(this,arguments)||this}return e.prototype.createAggregator=function(t){return e.DEFAULT_INSTANCE},e.DEFAULT_INSTANCE=new hE,e}(Nr);var xE=function(r){Qn(e,r);function e(){return r!==null&&r.apply(this,arguments)||this}return e.prototype.createAggregator=function(t){switch(t.type){case oe.COUNTER:case oe.OBSERVABLE_COUNTER:case oe.HISTOGRAM:return e.MONOTONIC_INSTANCE;default:return e.NON_MONOTONIC_INSTANCE}},e.MONOTONIC_INSTANCE=new Dm(!0),e.NON_MONOTONIC_INSTANCE=new Dm(!1),e}(Nr);var ME=function(r){Qn(e,r);function e(){return r!==null&&r.apply(this,arguments)||this}return e.prototype.createAggregator=function(t){return e.DEFAULT_INSTANCE},e.DEFAULT_INSTANCE=new RE,e}(Nr);var _E=function(r){Qn(e,r);function e(){return r!==null&&r.apply(this,arguments)||this}return e.prototype.createAggregator=function(t){return e.DEFAULT_INSTANCE},e.DEFAULT_INSTANCE=new xm([0,5,10,25,50,75,100,250,500,750,1e3,2500,5e3,7500,1e4],!0),e}(Nr);var PE=function(r){Qn(e,r);function e(t,n){n===void 0&&(n=!0);var o=r.call(this)||this;if(o._recordMinMax=n,t==null)throw new Error("ExplicitBucketHistogramAggregation should be created with explicit boundaries, if a single bucket histogram is required, please pass an empty array");t=t.concat(),t=t.sort(function(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 xm(this._boundaries,this._recordMinMax)},e}(Nr);var IE=function(r){Qn(e,r);function e(t,n){t===void 0&&(t=160),n===void 0&&(n=!0);var o=r.call(this)||this;return o._maxSize=t,o._recordMinMax=n,o}return e.prototype.createAggregator=function(t){return new wE(this._maxSize,this._recordMinMax)},e}(Nr);var OE=function(r){Qn(e,r);function e(){return r!==null&&r.apply(this,arguments)||this}return e.prototype._resolve=function(t){switch(t.type){case oe.COUNTER:case oe.UP_DOWN_COUNTER:case oe.OBSERVABLE_COUNTER:case oe.OBSERVABLE_UP_DOWN_COUNTER:return NE;case oe.GAUGE:case oe.OBSERVABLE_GAUGE:return DE;case oe.HISTOGRAM:return t.advice.explicitBucketBoundaries?new PE(t.advice.explicitBucketBoundaries):kE}return z.warn("Unable to recognize instrument type: "+t.type),LE},e.prototype.createAggregator=function(t){return this._resolve(t).createAggregator(t)},e}(Nr);var LE=new CE,NE=new xE,DE=new ME,kE=new _E,GN=new IE,VN=new OE;_e();function Bl(){return"unknown_service:"+process.argv0}var yn=function(){return yn=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},yn.apply(this,arguments)},jN=function(r,e,t,n){function o(i){return i instanceof t?i:new t(function(a){a(i)})}return new(t||(t=Promise))(function(i,a){function 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())})},WN=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}}},$N=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},km=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 z.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[Ol]=Bl(),e[Ia]=Ll[Ia],e[Pa]=Ll[Pa],e[Oa]=Ll[Oa],e))},Object.defineProperty(r.prototype,"attributes",{get:function(){var e;return this.asyncAttributesPending&&z.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 jN(this,void 0,void 0,function(){return WN(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=yn(yn({},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=$N(a,2),l=c[0],u=c[1];return yn(yn(yn(yn({},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 eo;(function(r){r[r.DELTA=0]="DELTA",r[r.CUMULATIVE=1]="CUMULATIVE",r[r.LOWMEMORY=2]="LOWMEMORY"})(eo||(eo={}));_e();var qN=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())})},KN=function(r,e){var t={label:0,sent:function(){if(i[0]&1)throw i[1];return i[1]},trys:[],ops:[]},n,o,i,a;return a={next: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}}},Um=function(){return nr.CUMULATIVE},UE=function(r){switch(r){case oe.COUNTER:case oe.OBSERVABLE_COUNTER:case oe.GAUGE:case oe.HISTOGRAM:case oe.OBSERVABLE_GAUGE:return nr.DELTA;case oe.UP_DOWN_COUNTER:case oe.OBSERVABLE_UP_DOWN_COUNTER:return nr.CUMULATIVE}},FE=function(r){switch(r){case oe.COUNTER:case oe.HISTOGRAM:return nr.DELTA;case oe.GAUGE:case oe.UP_DOWN_COUNTER:case oe.OBSERVABLE_UP_DOWN_COUNTER:case oe.OBSERVABLE_COUNTER:case oe.OBSERVABLE_GAUGE:return nr.CUMULATIVE}};function YN(){var r=ht(),e=r.OTEL_EXPORTER_OTLP_METRICS_TEMPORALITY_PREFERENCE.trim().toLowerCase();return e==="cumulative"?Um:e==="delta"?UE:e==="lowmemory"?FE:(z.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."),Um)}function XN(r){return r!=null?r===eo.DELTA?UE:r===eo.LOWMEMORY?FE:Um:YN()}function JN(r){return r?.aggregationPreference?r.aggregationPreference:function(e){return Nr.Default()}}var BE=function(){function r(e,t){this._otlpExporter=e,this._aggregationSelector=JN(t),this._aggregationTemporalitySelector=XN(t?.temporalityPreference)}return r.prototype.export=function(e,t){this._otlpExporter.export([e],t)},r.prototype.shutdown=function(){return qN(this,void 0,void 0,function(){return KN(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 ZN=function(r,e){var t=typeof Symbol=="function"&&r[Symbol.iterator];if(!t)return r;var n=t.call(r),o,i=[],a;try{for(;(e===void 0||e-- >0)&&!(o=n.next()).done;)i.push(o.value)}catch(s){a={error:s}}finally{try{o&&!o.done&&(t=n.return)&&t.call(n)}finally{if(a)throw a.error}}return i},zE=1e4,HE=5,GE=1e3,VE=5e3,jE=1.5;function Ua(r){r===void 0&&(r={});var e={};return Object.entries(r).forEach(function(t){var n=ZN(t,2),o=n[0],i=n[1];typeof i<"u"?e[o]=String(i):z.warn('Header "'+o+'" has invalid value ('+i+") and will be ignored")}),e}function Fm(r,e){return r.endsWith("/")||(r=r+"/"),r+e}function Bm(r){try{var e=new URL(r);return e.pathname===""&&(e.pathname=e.pathname+"/"),e.toString()}catch{return z.warn("Could not parse export URL: '"+r+"'"),r}}function zm(r){return typeof r=="number"?r<=0?Hm(r,zE):r:QN()}function QN(){var r,e=Number((r=ht().OTEL_EXPORTER_OTLP_TRACES_TIMEOUT)!==null&&r!==void 0?r:ht().OTEL_EXPORTER_OTLP_TIMEOUT);return e<=0?Hm(e,zE):e}function Hm(r,e){return z.warn("Timeout must be greater than 0",r),e}function WE(r){var e=[429,502,503,504];return e.includes(r)}function $E(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 qE=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 pE(this._shutdown,this),this._concurrencyLimit=typeof e.concurrencyLimit=="number"?e.concurrencyLimit:30,this.timeoutMillis=zm(e.timeoutMillis),this.onInit(e)}return r.prototype.export=function(e,t){if(this._shutdownOnce.isCalled){t({code:Zn.FAILED,error:new Error("Exporter has been shutdown")});return}if(this._sendingPromises.length>=this._concurrencyLimit){t({code:Zn.FAILED,error:new Error("Concurrent export limit reached")});return}this._export(e).then(function(){t({code:Zn.SUCCESS})}).catch(function(n){t({code:Zn.FAILED,error:n})})},r.prototype._export=function(e){var t=this;return new Promise(function(n,o){try{z.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 z.debug("shutdown started"),this.onShutdown(),this.forceFlush()},r}();_e();import*as Gm from"url";import*as Hl from"http";import*as Gl from"https";import*as KE from"zlib";import{Readable as tD}from"stream";var bn;(function(r){r.NONE="none",r.GZIP="gzip"})(bn||(bn={}));var eD=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)}}(),ei=function(r){eD(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 zl=function(){return zl=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},zl.apply(this,arguments)};function Vm(r,e,t,n,o){var i=r.timeoutMillis,a=new Gm.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 ei("Request Timeout");o(h)}else s>=14?l.destroy():l.abort()},i),m={hostname:a.hostname,port:a.port,path:a.pathname,method:"POST",headers:zl({"Content-Type":t},r.headers),agent:r.agent},p=a.protocol==="http:"?Hl.request:Gl.request,g=function(h,f){switch(h===void 0&&(h=HE),f===void 0&&(f=GE),l=p(m,function(b){var x="";b.on("data",function(T){return x+=T}),b.on("aborted",function(){if(u){var T=new ei("Request Timeout");o(T)}}),b.on("end",function(){if(u===!1)if(b.statusCode&&b.statusCode<299)z.debug("statusCode: "+b.statusCode,x),n(),clearTimeout(d),clearTimeout(c);else if(b.statusCode&&WE(b.statusCode)&&h>0){var T=void 0;f=jE*f,b.headers["retry-after"]?T=$E(b.headers["retry-after"]):T=Math.round(Math.random()*(VE-f)+f),c=setTimeout(function(){g(h-1,f)},T)}else{var v=new ei(b.statusMessage,b.statusCode,x);o(v),clearTimeout(d),clearTimeout(c)}})}),l.on("error",function(b){if(u){var x=new ei("Request Timeout",b.code);o(x)}else o(b);clearTimeout(d),clearTimeout(c)}),l.on("abort",function(){if(u){var b=new ei("Request Timeout");o(b)}clearTimeout(d),clearTimeout(c)}),r.compression){case bn.GZIP:{l.setHeader("Content-Encoding","gzip");var E=rD(e);E.on("error",o).pipe(KE.createGzip()).on("error",o).pipe(l);break}default:l.end(Buffer.from(e));break}};g()}function rD(r){var e=new tD;return e.push(r),e.push(null),e}function jm(r){if(r.httpAgentOptions&&r.keepAlive===!1){z.warn("httpAgentOptions is used only when keepAlive is true");return}if(!(r.keepAlive===!1||!r.url))try{var e=new Gm.URL(r.url),t=e.protocol==="http:"?Hl.Agent:Gl.Agent;return new t(zl({keepAlive:!0},r.httpAgentOptions))}catch(n){z.error("collector exporter failed to create http agent. err: "+n.message);return}}function Wm(r){if(r)return r;var e=ht().OTEL_EXPORTER_OTLP_TRACES_COMPRESSION||ht().OTEL_EXPORTER_OTLP_COMPRESSION;return e===bn.GZIP?bn.GZIP:bn.NONE}_e();var nD=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)}}(),Vl=function(r){nD(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&&z.warn("Metadata cannot be set when using http"),i.headers=Object.assign(i.DEFAULT_HEADERS,Ua(t.headers),Zo.parseKeyPairsIntoRecord(ht().OTEL_EXPORTER_OTLP_HEADERS)),i.agent=jm(t),i.compression=Wm(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){z.debug("Shutdown already started. Cannot send objects");return}var a=new Promise(function(c,l){var u;Vm(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}(qE);function XE(r){var e=BigInt(1e9);return BigInt(r[0])*e+BigInt(r[1])}function oD(r){var e=Number(BigInt.asUintN(32,r)),t=Number(BigInt.asUintN(32,r>>BigInt(32)));return{low:e,high:t}}function JE(r){var e=XE(r);return oD(e)}function iD(r){var e=XE(r);return e.toString()}var aD=typeof BigInt<"u"?iD:dE;function YE(r){return r}function ZE(r){if(r!==void 0)return Il(r)}var sD={encodeHrTime:JE,encodeSpanContext:Il,encodeOptionalSpanContext:ZE};function QE(r){var e,t;if(r===void 0)return sD;var n=(e=r.useLongBits)!==null&&e!==void 0?e:!0,o=(t=r.useHex)!==null&&t!==void 0?t:!1;return{encodeHrTime:n?JE:aD,encodeSpanContext:o?YE:Il,encodeOptionalSpanContext:o?YE:ZE}}var lD=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 eT(r){return{name:r.name,version:r.version}}function ti(r){return Object.keys(r).map(function(e){return tT(e,r[e])})}function tT(r,e){return{key:r,value:rT(e)}}function rT(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(rT)}}:e==="object"&&r!=null?{kvlistValue:{values:Object.entries(r).map(function(t){var n=lD(t,2),o=n[0],i=n[1];return tT(o,i)})}}:{}}function nT(r){return{attributes:ti(r.attributes),droppedAttributesCount:0}}_e();function iT(r,e){var t=QE(e);return{resource:nT(r.resource),schemaUrl:void 0,scopeMetrics:cD(r.scopeMetrics,t)}}function cD(r,e){return Array.from(r.map(function(t){return{scope:eT(t.scope),metrics:t.metrics.map(function(n){return uD(n,e)}),schemaUrl:t.scope.schemaUrl}}))}function uD(r,e){var t={name:r.descriptor.name,description:r.descriptor.description,unit:r.descriptor.unit},n=gD(r.aggregationTemporality);switch(r.dataPointType){case Rt.SUM:t.sum={aggregationTemporality:n,isMonotonic:r.isMonotonic,dataPoints:oT(r,e)};break;case Rt.GAUGE:t.gauge={dataPoints:oT(r,e)};break;case Rt.HISTOGRAM:t.histogram={aggregationTemporality:n,dataPoints:mD(r,e)};break;case Rt.EXPONENTIAL_HISTOGRAM:t.exponentialHistogram={aggregationTemporality:n,dataPoints:pD(r,e)};break}return t}function dD(r,e,t){var n={attributes:ti(r.attributes),startTimeUnixNano:t.encodeHrTime(r.startTime),timeUnixNano:t.encodeHrTime(r.endTime)};switch(e){case Gt.INT:n.asInt=r.value;break;case Gt.DOUBLE:n.asDouble=r.value;break}return n}function oT(r,e){return r.dataPoints.map(function(t){return dD(t,r.descriptor.valueType,e)})}function mD(r,e){return r.dataPoints.map(function(t){var n=t.value;return{attributes:ti(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 pD(r,e){return r.dataPoints.map(function(t){var n=t.value;return{attributes:ti(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 gD(r){switch(r){case nr.DELTA:return 1;case nr.CUMULATIVE:return 2}}function aT(r,e){return{resourceMetrics:r.map(function(t){return iT(t,e)})}}var $m={serializeRequest:function(r){var e=aT(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 sT="0.52.1";var lT=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)}}(),ri=function(){return ri=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},ri.apply(this,arguments)},cT="v1/metrics",hD="http://localhost:4318/"+cT,fD={"User-Agent":"OTel-OTLP-Exporter-JavaScript/"+sT},SD=function(r){lT(e,r);function e(t){var n=r.call(this,t,$m,"application/json")||this;return n.headers=ri(ri(ri(ri({},n.headers),fD),Zo.parseKeyPairsIntoRecord(ht().OTEL_EXPORTER_OTLP_METRICS_HEADERS)),Ua(t?.headers)),n}return e.prototype.getDefaultUrl=function(t){return typeof t.url=="string"?t.url:ht().OTEL_EXPORTER_OTLP_METRICS_ENDPOINT.length>0?Bm(ht().OTEL_EXPORTER_OTLP_METRICS_ENDPOINT):ht().OTEL_EXPORTER_OTLP_ENDPOINT.length>0?Fm(ht().OTEL_EXPORTER_OTLP_ENDPOINT,cT):hD},e}(Vl),uT=function(r){lT(e,r);function e(t){return r.call(this,new SD(t),t)||this}return e}(BE);var ni;(function(r){r[r.DELTA=0]="DELTA",r[r.CUMULATIVE=1]="CUMULATIVE"})(ni||(ni={}));var Dr;(function(r){r[r.HISTOGRAM=0]="HISTOGRAM",r[r.EXPONENTIAL_HISTOGRAM=1]="EXPONENTIAL_HISTOGRAM",r[r.GAUGE=2]="GAUGE",r[r.SUM=3]="SUM"})(Dr||(Dr={}));_e();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)}}(),dT=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())})},mT=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}}},bD=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},ED=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))},TD=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 pT(r){return r!=null}function jl(r){var e=Object.keys(r);return e.length===0?"":(e=e.sort(),JSON.stringify(e.map(function(t){return[t,r[t]]})))}function gT(r){var e,t;return r.name+":"+((e=r.version)!==null&&e!==void 0?e:"")+":"+((t=r.schemaUrl)!==null&&t!==void 0?t:"")}var qm=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 En(r,e){var t,n=new Promise(function(i,a){t=setTimeout(function(){a(new qm("Operation timed out."))},e)});return Promise.race([r,n]).then(function(o){return clearTimeout(t),o},function(o){throw clearTimeout(t),o})}function hT(r){return dT(this,void 0,void 0,function(){var e=this;return mT(this,function(t){return[2,Promise.all(r.map(function(n){return dT(e,void 0,void 0,function(){var o,i;return mT(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 fT(r){return r.status==="rejected"}function Km(r,e){var t=[];return r.forEach(function(n){t.push.apply(t,ED([],bD(e(n)),!1))}),t}function ST(r,e){var t,n;if(r.size!==e.size)return!1;try{for(var o=TD(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 yT(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 bT(r,e){return r.toLowerCase()===e.toLowerCase()}_e();var ir;(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"})(ir||(ir={}));var Ym=function(){function r(){this.kind=ir.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 pe;(function(r){r.COUNTER="COUNTER",r.GAUGE="GAUGE",r.HISTOGRAM="HISTOGRAM",r.UP_DOWN_COUNTER="UP_DOWN_COUNTER",r.OBSERVABLE_COUNTER="OBSERVABLE_COUNTER",r.OBSERVABLE_GAUGE="OBSERVABLE_GAUGE",r.OBSERVABLE_UP_DOWN_COUNTER="OBSERVABLE_UP_DOWN_COUNTER"})(pe||(pe={}));function kr(r,e,t){var n,o,i,a;return AD(r)||z.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:Gt.DOUBLE,advice:(a=t?.advice)!==null&&a!==void 0?a:{}}}function ET(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 TT(r,e){return bT(r.name,e.name)&&r.unit===e.unit&&r.type===e.type&&r.valueType===e.valueType}var vD=/^[a-z][a-z0-9_.\-/]{0,254}$/i;function AD(r){return r.match(vD)!=null}var wD=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 RD(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 Wl=function(){function r(e,t,n,o){n===void 0&&(n=!0),o===void 0&&(o=RD(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=yT(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 $l=function(){function r(e,t){this._boundaries=e,this._recordMinMax=t,this.kind=ir.HISTOGRAM}return r.prototype.createAccumulation=function(e){return new Wl(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 Wl(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 Wl(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:Dr.HISTOGRAM,dataPoints:n.map(function(i){var a=wD(i,2),s=a[0],c=a[1],l=c.toPointValue(),u=e.type===pe.GAUGE||e.type===pe.UP_DOWN_COUNTER||e.type===pe.OBSERVABLE_GAUGE||e.type===pe.OBSERVABLE_UP_DOWN_COUNTER;return{attributes:s,startTime:c.startTime,endTime:o,value:{min:l.hasMinMax?l.min:void 0,max:l.hasMinMax?l.max:void 0,sum:u?void 0:l.sum,buckets:l.buckets,count:l.count}}})}},r}();_e();var Xm=function(r,e){var t=typeof Symbol=="function"&&r[Symbol.iterator];if(!t)return r;var n=t.call(r),o,i=[],a;try{for(;(e===void 0||e-- >0)&&!(o=n.next()).done;)i.push(o.value)}catch(s){a={error:s}}finally{try{o&&!o.done&&(t=n.return)&&t.call(n)}finally{if(a)throw a.error}}return i},Jm=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))},Zm=function(){function r(e,t,n,o){e===void 0&&(e=new CD),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 CD=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,Jm([n,this._counts.length-t],Xm(this._counts.slice(t)),!1)),o.splice.apply(o,Jm([0,t],Xm(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(Jm([],Xm(this._counts),!1))},r}();var vT=52,xD=2146435072,MD=1048575,Qm=1023,ql=-Qm+1,Kl=Qm,Fa=Math.pow(2,-1022);function Yl(r){var e=new DataView(new ArrayBuffer(8));e.setFloat64(0,r);var t=e.getUint32(0),n=(t&xD)>>20;return n-Qm}function Xl(r){var e=new DataView(new ArrayBuffer(8));e.setFloat64(0,r);var t=e.getUint32(0),n=e.getUint32(4),o=(t&MD)*Math.pow(2,32);return o+n}function Ba(r,e){return r===0||r===Number.POSITIVE_INFINITY||r===Number.NEGATIVE_INFINITY||Number.isNaN(r)?r:r*Math.pow(2,e)}function wT(r){return r--,r|=r>>1,r|=r>>2,r|=r>>4,r|=r>>8,r|=r>>16,r++,r}var _D=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)}}(),Tn=function(r){_D(e,r);function e(){return r!==null&&r.apply(this,arguments)||this}return e}(Error);var CT=function(){function r(e){this._shift=-e}return r.prototype.mapToIndex=function(e){if(e<Fa)return this._minNormalLowerBoundaryIndex();var t=Yl(e),n=this._rightShift(Xl(e)-1,vT);return t+n>>this._shift},r.prototype.lowerBoundary=function(e){var t=this._minNormalLowerBoundaryIndex();if(e<t)throw new Tn("underflow: "+e+" is < minimum lower boundary: "+t);var n=this._maxNormalLowerBoundaryIndex();if(e>n)throw new Tn("overflow: "+e+" is > maximum lower boundary: "+n);return Ba(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=ql>>this._shift;return this._shift<2&&e--,e},r.prototype._maxNormalLowerBoundaryIndex=function(){return Kl>>this._shift},r.prototype._rightShift=function(e,t){return Math.floor(e*Math.pow(2,-t))},r}();var xT=function(){function r(e){this._scale=e,this._scaleFactor=Ba(Math.LOG2E,e),this._inverseFactor=Ba(Math.LN2,-e)}return r.prototype.mapToIndex=function(e){if(e<=Fa)return this._minNormalLowerBoundaryIndex()-1;if(Xl(e)===0){var t=Yl(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 Tn("overflow: "+e+" is > maximum lower boundary: "+t)}var n=this._minNormalLowerBoundaryIndex();if(e<=n){if(e===n)return Fa;if(e===n-1)return Math.exp((e+(1<<this._scale))/this._scaleFactor)/2;throw new Tn("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 ql<<this._scale},r.prototype._maxNormalLowerBoundaryIndex=function(){return(Kl+1<<this._scale)-1},r}();var MT=-10,_T=20,PD=Array.from({length:31},function(r,e){return e>10?new xT(e-10):new CT(e-10)});function ep(r){if(r>_T||r<MT)throw new Tn("expected scale >= "+MT+" && <= "+_T+", got: "+r);return PD[r+10]}var ID=function(r,e){var t=typeof Symbol=="function"&&r[Symbol.iterator];if(!t)return r;var n=t.call(r),o,i=[],a;try{for(;(e===void 0||e-- >0)&&!(o=n.next()).done;)i.push(o.value)}catch(s){a={error:s}}finally{try{o&&!o.done&&(t=n.return)&&t.call(n)}finally{if(a)throw a.error}}return i},Jl=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}(),OD=20,LD=160,tp=2,PT=function(){function r(e,t,n,o,i,a,s,c,l,u,d){e===void 0&&(e=e),t===void 0&&(t=LD),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 Zm),u===void 0&&(u=new Zm),d===void 0&&(d=ep(OD)),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<tp&&(z.warn("Exponential Histogram Max Size set to "+this._maxSize+", changing to the minimum size of: "+tp),this._maxSize=tp)}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=wT(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=ep(t)}},r.prototype._minScale=function(e){var t=Math.min(this.scale,e.scale),n=Jl.combine(this._highLowAtScale(this.positive,this.scale,t),this._highLowAtScale(e.positive,e.scale,t)),o=Jl.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 Jl(0,-1);var o=t-n;return new Jl(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 rp=function(){function r(e,t){this._maxSize=e,this._recordMinMax=t,this.kind=ir.EXPONENTIAL_HISTOGRAM}return r.prototype.createAccumulation=function(e){return new PT(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:Dr.EXPONENTIAL_HISTOGRAM,dataPoints:n.map(function(i){var a=ID(i,2),s=a[0],c=a[1],l=c.toPointValue(),u=e.type===pe.GAUGE||e.type===pe.UP_DOWN_COUNTER||e.type===pe.OBSERVABLE_GAUGE||e.type===pe.OBSERVABLE_UP_DOWN_COUNTER;return{attributes:s,startTime:c.startTime,endTime:o,value:{min:l.hasMinMax?l.min:void 0,max:l.hasMinMax?l.max:void 0,sum:u?void 0:l.sum,positive:{offset:l.positive.offset,bucketCounts:l.positive.bucketCounts},negative:{offset:l.negative.offset,bucketCounts:l.negative.bucketCounts},count:l.count,scale:l.scale,zeroCount:l.zeroCount}}})}},r}();_e();var ND=pm("OpenTelemetry SDK Context Key SUPPRESS_TRACING");function IT(r){return r.setValue(ND,!0)}_e();function OT(){return function(r){z.error(DD(r))}}function DD(r){return typeof r=="string"?r:JSON.stringify(kD(r))}function kD(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 UD=OT();function Zl(r){try{UD(r)}catch{}}var LT="1.30.1";var FD="process.runtime.name";var BD="service.name";var zD="telemetry.sdk.name",HD="telemetry.sdk.language",GD="telemetry.sdk.version";var NT=FD;var DT=BD;var za=zD,Ha=HD,Ga=GD;var VD="nodejs";var kT=VD;var oi,to=(oi={},oi[za]="opentelemetry",oi[NT]="node",oi[Ha]=kT,oi[Ga]=LT,oi);function Va(r){r.unref()}var XD=9,JD=6,ZD=Math.pow(10,JD),Qoe=Math.pow(10,XD);function ro(r){var e=r/1e3,t=Math.trunc(e),n=Math.round(r%1e3*ZD);return[t,n]}function ii(r){return r[0]*1e6+r[1]/1e3}var ja;(function(r){r[r.SUCCESS=0]="SUCCESS",r[r.FAILED=1]="FAILED"})(ja||(ja={}));_e();function UT(r,e){return new Promise(function(t){Jo.with(IT(Jo.active()),function(){r.export(e,function(n){t(n)})})})}var FT={_export:UT};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},Ql=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=ro(Date.now())},r.prototype.setStartTime=function(e){this.startTime=e},r.prototype.toPointValue=function(){return this._current},r}();var np=function(){function r(){this.kind=ir.LAST_VALUE}return r.prototype.createAccumulation=function(e){return new Ql(e)},r.prototype.merge=function(e,t){var n=ii(t.sampleTime)>=ii(e.sampleTime)?t:e;return new Ql(e.startTime,n.toPointValue(),n.sampleTime)},r.prototype.diff=function(e,t){var n=ii(t.sampleTime)>=ii(e.sampleTime)?t:e;return new Ql(t.startTime,n.toPointValue(),n.sampleTime)},r.prototype.toMetricData=function(e,t,n,o){return{descriptor:e,aggregationTemporality:t,dataPointType:Dr.GAUGE,dataPoints:n.map(function(i){var a=QD(i,2),s=a[0],c=a[1];return{attributes:s,startTime:c.startTime,endTime:o,value:c.toPointValue()}})}},r}();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},ai=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 ec=function(){function r(e){this.monotonic=e,this.kind=ir.SUM}return r.prototype.createAccumulation=function(e){return new ai(e,this.monotonic)},r.prototype.merge=function(e,t){var n=e.toPointValue(),o=t.toPointValue();return t.reset?new ai(t.startTime,this.monotonic,o,t.reset):new ai(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 ai(t.startTime,this.monotonic,o,!0):new ai(t.startTime,this.monotonic,o-n)},r.prototype.toMetricData=function(e,t,n,o){return{descriptor:e,aggregationTemporality:t,dataPointType:Dr.SUM,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()}}),isMonotonic:this.monotonic}},r}();var no=function(){var r=function(e,t){return r=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(n,o){n.__proto__=o}||function(n,o){for(var i in o)Object.prototype.hasOwnProperty.call(o,i)&&(n[i]=o[i])},r(e,t)};return function(e,t){if(typeof t!="function"&&t!==null)throw new TypeError("Class extends value "+String(t)+" is not a constructor or null");r(e,t);function n(){this.constructor=e}e.prototype=t===null?Object.create(t):(n.prototype=t.prototype,new n)}}(),ar=function(){function r(){}return r.Drop=function(){return WT},r.Sum=function(){return $T},r.LastValue=function(){return qT},r.Histogram=function(){return KT},r.ExponentialHistogram=function(){return tk},r.Default=function(){return rk},r}();var BT=function(r){no(e,r);function e(){return r!==null&&r.apply(this,arguments)||this}return e.prototype.createAggregator=function(t){return e.DEFAULT_INSTANCE},e.DEFAULT_INSTANCE=new Ym,e}(ar);var zT=function(r){no(e,r);function e(){return r!==null&&r.apply(this,arguments)||this}return e.prototype.createAggregator=function(t){switch(t.type){case pe.COUNTER:case pe.OBSERVABLE_COUNTER:case pe.HISTOGRAM:return e.MONOTONIC_INSTANCE;default:return e.NON_MONOTONIC_INSTANCE}},e.MONOTONIC_INSTANCE=new ec(!0),e.NON_MONOTONIC_INSTANCE=new ec(!1),e}(ar);var HT=function(r){no(e,r);function e(){return r!==null&&r.apply(this,arguments)||this}return e.prototype.createAggregator=function(t){return e.DEFAULT_INSTANCE},e.DEFAULT_INSTANCE=new np,e}(ar);var GT=function(r){no(e,r);function e(){return r!==null&&r.apply(this,arguments)||this}return e.prototype.createAggregator=function(t){return e.DEFAULT_INSTANCE},e.DEFAULT_INSTANCE=new $l([0,5,10,25,50,75,100,250,500,750,1e3,2500,5e3,7500,1e4],!0),e}(ar);var Wa=function(r){no(e,r);function e(t,n){n===void 0&&(n=!0);var o=r.call(this)||this;if(o._recordMinMax=n,t==null)throw new Error("ExplicitBucketHistogramAggregation should be created with explicit boundaries, if a single bucket histogram is required, please pass an empty array");t=t.concat(),t=t.sort(function(s,c){return s-c});var i=t.lastIndexOf(-1/0),a=t.indexOf(1/0);return a===-1&&(a=void 0),o._boundaries=t.slice(i+1,a),o}return e.prototype.createAggregator=function(t){return new $l(this._boundaries,this._recordMinMax)},e}(ar);var VT=function(r){no(e,r);function e(t,n){t===void 0&&(t=160),n===void 0&&(n=!0);var o=r.call(this)||this;return o._maxSize=t,o._recordMinMax=n,o}return e.prototype.createAggregator=function(t){return new rp(this._maxSize,this._recordMinMax)},e}(ar);var jT=function(r){no(e,r);function e(){return r!==null&&r.apply(this,arguments)||this}return e.prototype._resolve=function(t){switch(t.type){case pe.COUNTER:case pe.UP_DOWN_COUNTER:case pe.OBSERVABLE_COUNTER:case pe.OBSERVABLE_UP_DOWN_COUNTER:return $T;case pe.GAUGE:case pe.OBSERVABLE_GAUGE:return qT;case pe.HISTOGRAM:return t.advice.explicitBucketBoundaries?new Wa(t.advice.explicitBucketBoundaries):KT}return z.warn("Unable to recognize instrument type: "+t.type),WT},e.prototype.createAggregator=function(t){return this._resolve(t).createAggregator(t)},e}(ar);var WT=new BT,$T=new zT,qT=new HT,KT=new GT,tk=new VT,rk=new jT;var YT=function(r){return ar.Default()},XT=function(r){return ni.CUMULATIVE};var op=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())})},ip=function(r,e){var t={label:0,sent:function(){if(i[0]&1)throw i[1];return i[1]},trys:[],ops:[]},n,o,i,a;return a={next: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}}},JT=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},nk=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))},ZT=function(){function r(e){var t,n,o;this._shutdown=!1,this._aggregationSelector=(t=e?.aggregationSelector)!==null&&t!==void 0?t:YT,this._aggregationTemporalitySelector=(n=e?.aggregationTemporalitySelector)!==null&&n!==void 0?n:XT,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 op(this,void 0,void 0,function(){var t,n,o,i,a,s;return ip(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(nk([this._sdkMetricProducer.collect({timeoutMillis:e?.timeoutMillis})],JT(this._metricProducers.map(function(l){return l.collect({timeoutMillis:e?.timeoutMillis})})),!1))];case 1:return t=JT.apply(void 0,[c.sent()]),n=t[0],o=t.slice(1),i=n.errors.concat(Km(o,function(l){return l.errors})),a=n.resourceMetrics.resource,s=n.resourceMetrics.scopeMetrics.concat(Km(o,function(l){return l.resourceMetrics.scopeMetrics})),[2,{resourceMetrics:{resource:a,scopeMetrics:s},errors:i}]}})})},r.prototype.shutdown=function(e){return op(this,void 0,void 0,function(){return ip(this,function(t){switch(t.label){case 0:return this._shutdown?(z.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,En(this.onShutdown(),e.timeoutMillis)];case 3:t.sent(),t.label=4;case 4:return this._shutdown=!0,[2]}})})},r.prototype.forceFlush=function(e){return op(this,void 0,void 0,function(){return ip(this,function(t){switch(t.label){case 0:return this._shutdown?(z.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,En(this.onForceFlush(),e.timeoutMillis)];case 3:return t.sent(),[2]}})})},r}();_e();var ok=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)}}(),tc=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())})},rc=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}}},ik=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},ak=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))},ap=function(r){ok(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 tc(this,void 0,void 0,function(){var t;return rc(this,function(n){switch(n.label){case 0:return n.trys.push([0,2,,3]),[4,En(this._doRun(),this._exportTimeout)];case 1:return n.sent(),[3,3];case 2:return t=n.sent(),t instanceof qm?(z.error("Export took longer than %s milliseconds and timed out.",this._exportTimeout),[2]):(Zl(t),[3,3]);case 3:return[2]}})})},e.prototype._doRun=function(){var t,n;return tc(this,void 0,void 0,function(){var o,i,a,s,c,l;return rc(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=z).error.apply(l,ak(["PeriodicExportingMetricReader: metrics collection errors"],ik(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(),z.debug("Error while resolving async portion of resource: ",s),Zl(s),[3,5];case 5:return i.scopeMetrics.length===0?[2]:[4,FT._export(this._exporter,i)];case 6:if(c=u.sent(),c.code!==ja.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),Va(this._interval)},e.prototype.onForceFlush=function(){return tc(this,void 0,void 0,function(){return rc(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 tc(this,void 0,void 0,function(){return rc(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}(ZT);_e();_e();function nc(){return"unknown_service:"+process.argv0}var vn=function(){return vn=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},vn.apply(this,arguments)},sk=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())})},lk=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}}},ck=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},oc=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 z.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[DT]=nc(),e[Ha]=to[Ha],e[za]=to[za],e[Ga]=to[Ga],e))},Object.defineProperty(r.prototype,"attributes",{get:function(){var e;return this.asyncAttributesPending&&z.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 sk(this,void 0,void 0,function(){return lk(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=vn(vn({},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=ck(a,2),l=c[0],u=c[1];return vn(vn(vn(vn({},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 QT=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 oo=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)}}(),ic=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=Jo.active()),typeof e!="number"){z.warn("non-number value provided to metric "+this._descriptor.name+": "+e);return}this._descriptor.valueType===Gt.INT&&!Number.isInteger(e)&&(z.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,ro(Date.now()))},r}();var ev=function(r){oo(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}(ic);var tv=function(r){oo(e,r);function e(){return r!==null&&r.apply(this,arguments)||this}return e.prototype.add=function(t,n,o){if(t<0){z.warn("negative value provided to counter "+this._descriptor.name+": "+t);return}this._record(t,n,o)},e}(ic);var rv=function(r){oo(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}(ic);var nv=function(r){oo(e,r);function e(){return r!==null&&r.apply(this,arguments)||this}return e.prototype.record=function(t,n,o){if(t<0){z.warn("negative value provided to histogram "+this._descriptor.name+": "+t);return}this._record(t,n,o)},e}(ic);var ac=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 ov=function(r){oo(e,r);function e(){return r!==null&&r.apply(this,arguments)||this}return e}(ac);var iv=function(r){oo(e,r);function e(){return r!==null&&r.apply(this,arguments)||this}return e}(ac);var av=function(r){oo(e,r);function e(){return r!==null&&r.apply(this,arguments)||this}return e}(ac);function $a(r){return r instanceof ac}var sv=function(){function r(e){this._meterSharedState=e}return r.prototype.createGauge=function(e,t){var n=kr(e,pe.GAUGE,t),o=this._meterSharedState.registerMetricStorage(n);return new rv(o,n)},r.prototype.createHistogram=function(e,t){var n=kr(e,pe.HISTOGRAM,t),o=this._meterSharedState.registerMetricStorage(n);return new nv(o,n)},r.prototype.createCounter=function(e,t){var n=kr(e,pe.COUNTER,t),o=this._meterSharedState.registerMetricStorage(n);return new tv(o,n)},r.prototype.createUpDownCounter=function(e,t){var n=kr(e,pe.UP_DOWN_COUNTER,t),o=this._meterSharedState.registerMetricStorage(n);return new ev(o,n)},r.prototype.createObservableGauge=function(e,t){var n=kr(e,pe.OBSERVABLE_GAUGE,t),o=this._meterSharedState.registerAsyncMetricStorage(n);return new iv(n,o,this._meterSharedState.observableRegistry)},r.prototype.createObservableCounter=function(e,t){var n=kr(e,pe.OBSERVABLE_COUNTER,t),o=this._meterSharedState.registerAsyncMetricStorage(n);return new ov(n,o,this._meterSharedState.observableRegistry)},r.prototype.createObservableUpDownCounter=function(e,t){var n=kr(e,pe.OBSERVABLE_UP_DOWN_COUNTER,t),o=this._meterSharedState.registerAsyncMetricStorage(n);return new av(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 sc=function(){function r(e){this._instrumentDescriptor=e}return r.prototype.getInstrumentDescriptor=function(){return this._instrumentDescriptor},r.prototype.updateDescription=function(e){this._instrumentDescriptor=kr(this._instrumentDescriptor.name,this._instrumentDescriptor.type,{description:e,valueType:this._instrumentDescriptor.valueType,unit:this._instrumentDescriptor.unit,advice:this._instrumentDescriptor.advice})},r}();var uk=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)}}(),lv=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}}},dk=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 lv(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 lv(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 yr=function(r){uk(e,r);function e(){return r.call(this,jl)||this}return e}(dk);var mk=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},lc=function(){function r(e,t){this._aggregator=e,this._activeCollectionStorage=new yr,this._cumulativeMemoStorage=new yr,this._overflowAttributes={"otel.metric.overflow":!0},this._cardinalityLimit=(t??2e3)-1,this._overflowHashCode=jl(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=mk(o,3),a=i[0],s=i[1],c=i[2],l=n._aggregator.createAccumulation(t);l?.record(s);var u=l;if(n._cumulativeMemoStorage.has(a,c)){var d=n._cumulativeMemoStorage.get(a,c);u=n._aggregator.diff(d,l)}else if(n._cumulativeMemoStorage.size>=n._cardinalityLimit&&(a=n._overflowAttributes,c=n._overflowHashCode,n._cumulativeMemoStorage.has(a,c))){var d=n._cumulativeMemoStorage.get(a,c);u=n._aggregator.diff(d,l)}if(n._activeCollectionStorage.has(a,c)){var m=n._activeCollectionStorage.get(a,c);u=n._aggregator.merge(m,u)}n._cumulativeMemoStorage.set(a,l,c),n._activeCollectionStorage.set(a,u,c)})},r.prototype.collect=function(){var e=this._activeCollectionStorage;return this._activeCollectionStorage=new yr,e},r}();var sp=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.")},cv=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},cc=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===ni.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=pk(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=sp(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 yr,i=this._unreportedAccumulations.get(e);if(this._unreportedAccumulations.set(e,[]),i===void 0)return o;try{for(var a=sp(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=cv(a.value,3),c=s[0],l=s[1],u=s[2];if(e.has(c,u)){var d=e.get(c,u),m=n.merge(d,l);o.set(c,m,u)}else o.set(c,l,u);a=i.next()}return o},r.calibrateStartTime=function(e,t,n){var o,i;try{for(var a=sp(e.keys()),s=a.next();!s.done;s=a.next()){var c=cv(s.value,2),l=c[0],u=c[1],d=t.get(l,u);d?.setStartTime(n)}}catch(m){o={error:m}}finally{try{s&&!s.done&&(i=a.return)&&i.call(a)}finally{if(o)throw o.error}}return t},r}();function pk(r){return Array.from(r.entries())}var gk=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)}}(),hk=function(r,e){var t=typeof Symbol=="function"&&r[Symbol.iterator];if(!t)return r;var n=t.call(r),o,i=[],a;try{for(;(e===void 0||e-- >0)&&!(o=n.next()).done;)i.push(o.value)}catch(s){a={error:s}}finally{try{o&&!o.done&&(t=n.return)&&t.call(n)}finally{if(a)throw a.error}}return i},uv=function(r){gk(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 lc(n,s._aggregationCardinalityLimit),s._temporalMetricStorage=new cc(n,i),s}return e.prototype.record=function(t,n){var o=this,i=new yr;Array.from(t.entries()).forEach(function(a){var s=hk(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}(sc);_e();function lp(r,e){var t="";return r.unit!==e.unit&&(t+=" - Unit '"+r.unit+"' does not match '"+e.unit+`'
|
|
23
|
+
`),globalThis.console=e}}var am=" ".repeat(6);import KO from"fetch-retry";import YO from"os";import hb,{multistream as XO}from"pino";import JO from"pino-pretty";import ZO from"pino-std-serializers";var Wo=new Map,QO=!0,fb="Log throttle exceeded",eL=100,tL=5e3,rL=KO(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}}),sm=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??YO.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=QO?hb(a):hb(a,XO([{stream:JO({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 rL(this.site,{method:"POST",headers:{"Content-Type":"application/json","signoz-access-token":"CumAaTMUcwjt05OddAmefKgshbhfRmWxzxih"},body:Yn(e),signal:AbortSignal.timeout(5e3)});if(!t.ok)throw new Error(`Got error status (${t.statusText}) from SigNoz`)}catch{}}shouldAllowLog(e){if(e===fb)return!0;let t=Date.now();return t-this.lastWindowStart>tL&&(this.logsInCurrentWindow=0,this.droppedLogsInWindow&&this.log("error",void 0,fb),this.droppedLogsInWindow=!1,this.lastWindowStart=t),this.logsInCurrentWindow<eL?(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(ba[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=ZO.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:iy({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,Wo.set("app",this),Wo.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=ay[e]):(this.minLevelValue=ba[e],this.consoleLogger.level=e)}enableConsoleLogs(){this.disableConsoleLogs=!1}},$o=({app:r,hostname:e,disableConsoleLogs:t})=>(Wo.has(r)||Wo.set(r,new sm({bindings:{app:r},hostname:e,disableConsoleLogs:t})),Wo.get(r));async function Sb(){await Promise.all([...Wo.values()].map(r=>r.flush()))}import{hostname as nL}from"os";var rr=$o({app:"cli",hostname:nL(),disableConsoleLogs:!0}).child({cliVersion:"0.7.1"});function lm(r){if(!r)return;r=r.toLowerCase();let e=ml.safeParse(r);if(e.success)return R.setMinLevel(e.data),e.data}function yb({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 gb(()=>{if(c.forEach(u=>{R.log(""),o(u)}),c.length){R.log("");let u=c.length===1?"":"s";R.error(`${c.length} ${t}${u} failed:`),c.forEach(d=>{R.dimmed(n(d))})}if(l.length){R.log("");let u=l.length===1?"":"s";R.warn(`${l.length} ${t}${u} cancelled:`),l.forEach(d=>{R.dimmed(n(d))})}if(a.length){R.log("");let u=a.length===1?"":"s";R.success(`${a.length} ${t}${u} passed:`),a.forEach(d=>{R.dimmed(n(d))})}if(s.length){R.log("");let u=s.length===1?"":"s";R.warn(`${s.length} quarantined ${t}${u} failed:`),s.forEach(d=>{R.dimmed(n(d))})}if(i.length){R.log("");let u=i.length===1?"":"s";R.warn(`${i.length} quarantined ${t}${u} passed:`),i.forEach(d=>{R.dimmed(n(d))})}R.log(""),R.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 va=({status:r,testLogRef:e,getRunningTestsCount:t,getTotalTestsCount:n,additionalText:o})=>{r=r.toUpperCase();let i=r,a;r.includes("FAIL")?(i=qo.bgRed.white("FAIL"),a=3):r.includes("PASS")?(i=qo.bgGreen.white("PASS"),a=3):r.includes("START")?(i=qo.bgBlue.white("START"),a=2):r.includes("CANCEL")?(i=qo.bgRgb(191,68,11).white("CANCEL"),a=1):r.includes("RETRY")?(i=qo.bgRgb(191,68,11).white("RETRY"),a=2):r.includes("RUN")||r.includes("PROG")?(i=qo.bgMagenta.white("RUNNING"),a=0):(R.warn(`Unknown status tried to be logged in run test locally: ${r}`),a=0),oL||(i=`${i}`),R.log(`${i}${" ".repeat(a)} ${e} ${o?`${o} `:""}(${t()}/${n()})`)};import iL from"fs";import{tmpdir as aL}from"os";import sL from"path";import{registry as Aa}from"playwright-core/lib/server";import bb from"proper-lockfile";var Eb=sL.join(aL(),"momenticBrowserInstallation");var cm=["chrome","chromium","chrome-for-testing","ffmpeg"],lL={Chromium:"chromium","Google Chrome":"chrome","Chrome for Testing":"chrome-for-testing"},Tb={chrome:"chrome",chromium:"chromium","chrome-for-testing":"chromium-headless-shell",ffmpeg:"ffmpeg"};function vb(r){let e=Tb[lL[r]??""]??"",t=Aa.findExecutable(e);return!t||t.installType==="none"?!1:um(t)}function um(r){let e=r.executablePath();return iL.existsSync(e)}function cL(r,e){let t=Tb[r];if(!t)throw new Error(`Requested install of unknown browser type ${r}`);let n=Aa.findExecutable(t);if(!n||n.installType==="none")throw new Error(`Requested install of unknown browser type ${r}`);if(!(!e&&um(n)))return n}async function uL({browser:r,force:e}){let t=cL(r,e);if(!t){R.info(`Browser '${r}' is already installed, skipping...`);return}R.info(`Installing browser '${r}'...`);try{await Aa.installDeps([t],!1),await Aa.install([t],!1)}catch(n){if(n.message.includes("Lock file is already being held")){R.warn("Another process is installing Playwright browsers. Waiting for completion before proceeding..");let o=Aa.findExecutable(r),i=5*60*1e3,a=Date.now();for(;Date.now()-a<i&&!um(o);)R.info("Waiting for browser to finish installing..."),await new Promise(s=>setTimeout(s,5e3))}else throw n}}async function Tl({rawBrowsers:r,force:e=!1,all:t=!1}){let n=t?cm:Array.from(new Set(r));try{await bb.lock(Eb,{stale:1e3*60*5,update:1e3*60,realpath:!1,retries:{retries:30,factor:2,maxTimeout:15e3,minTimeout:500}})}catch(i){R.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 uL({browser:i,force:e})}catch(a){o=a,R.error(`Failed to install the ${i} browser: ${a}`)}}finally{await bb.unlock(Eb,{realpath:!1})}if(o)throw o}import{createServer as dL}from"http";async function vl(r,e,t=30){for(let n=0;n<t;n+=1){let o=r+n;if(await Al(o))return o}R.error(`Could not find an available port for ${e} starting from ${r} after ${t} attempts`),process.exit(1)}async function Al(r){return new Promise((e,t)=>{let n=dL();n.once("error",o=>{o.code==="EADDRINUSE"?e(!1):(R.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 BQ from"blocked-at";import HQ from"why-is-node-running";import Gk from"fs";import{tmpdir as Vk}from"os";import jk from"path";import{remote as Wk}from"webdriverio";import{createInstanceClient as Dk}from"@limrun/api";import{execSync as kk}from"child_process";import ZQ,{multistream as e7}from"pino";import r7 from"pino-pretty";var i7=5*1024,mL="...[truncated]",a7=Buffer.byteLength(mL,"utf8");import{PostHog as f7}from"posthog-node";var fn=class extends Error{constructor(e){super(e),this.name="TimeoutError"}};var Ab=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 k(r,e){let{milliseconds:t,fallback:n,message:o,customTimers:i={setTimeout,clearTimeout}}=e,a;if(typeof t!="number"||Math.sign(t)!==1)throw new TypeError(`Expected \`milliseconds\` to be a positive number, got \`${t}\``);return new Promise((s,c)=>{let l;if(e.signal){let{signal:m}=e;if(m.aborted)return c(Ab(m));l=()=>c(Ab(m)),m.addEventListener("abort",l,{once:!0})}let u=()=>{if(e.signal&&e.signal.removeEventListener("abort",l),n)try{s(n())}catch(m){c(m)}else{typeof r.cancel=="function"&&Promise.resolve().then(()=>r.cancel()).catch(()=>{});let m=o instanceof Error?o:new fn(o??`Promise timed out after ${t}ms`);c(m)}};t<1/0&&(a=i.setTimeout(u,t));let d=()=>{i.clearTimeout(a),e.signal&&e.signal.removeEventListener("abort",l)};Promise.resolve(r).then(m=>{d(),s(m)}).catch(m=>{d(),c(m)})})}import{PostHog as R7}from"posthog-node";import{execSync as pL}from"child_process";import Ko from"os";import gL from"v8";var wb,Or,Cb=Ko.platform(),hL=Ko.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),{}),Rb=r=>{try{let e={},t=!1,n=fL(),o=SL(),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=gL.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"),Xn&&R.warn(`Low machine resources detected (memory: ${i} free, cpu: ${a} free)`)):r.debug({memory:n,cpu:o},"Got machine resource usage metrics")}catch{}};function xb(r){if(!Pr)return Rb(r),{interval:setInterval(()=>Rb(r),2e4),cpuMetadata:hL,platform:Cb}}function fL(){let r=Ko.totalmem(),e=Cb==="darwin"?yL():(()=>{let n=Ko.freemem();return{availableMemory:n,rawFreeMemory:n,cachedMemory:0}})(),t=e.availableMemory/r;return{totalMemory:r,freeMemory:e.availableMemory,freePercentage:t}}function SL(){let r=Ko.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,!Or)return Or=t,null;let n={user:t.user-Or.user,nice:t.nice-Or.nice,sys:t.sys-Or.sys,idle:t.idle-Or.idle,irq:t.irq-Or.irq,total:t.total-Or.total};return wb={measurementTime:e,intervalMs:e-Or.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},Or=t,wb}function yL(){try{let r=pL("/usr/bin/vm_stat",{encoding:"utf8",stdio:["pipe","pipe","ignore"]}),t=r.match(/page size of (\d+) bytes/)?.[1],n=t?Number.parseInt(t,10):4096,o=u=>{let m=r.match(new RegExp(`${u}:\\s+(\\d+)\\.`,"i"))?.[1];return m?Number.parseInt(m,10):0},i=o("Pages free"),a=o("Pages inactive"),s=o("Pages speculative"),c=i*n,l=(a+s)*n;return{availableMemory:c+l,rawFreeMemory:c,cachedMemory:l}}catch{let e=Ko.freemem();return{availableMemory:e,rawFreeMemory:e,cachedMemory:0}}}var wl=class{increment(e,t,n){}gauge(e,t){}distribution(e,t,n){}async flush(){}async recordDuration({fn:e}){return await e()}};function bL(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 Rl(r,e){let t=bL(r);return!e||Object.keys(e).length===0?t:{...e,...t}}var eE="=",_l=";",vm=",";var tE=8192;var Zo={};bx(Zo,{getKeyPairs:()=>ZL,parseKeyPairsIntoRecord:()=>QL,parsePairKeyValue:()=>rE,serializeKeyPairs:()=>JL});_e();var XL=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 JL(r){return r.reduce(function(e,t){var n=""+e+(e!==""?vm:"")+t;return n.length>tE?e:n},"")}function ZL(r){return r.getAllEntries().map(function(e){var t=XL(e,2),n=t[0],o=t[1],i=encodeURIComponent(n)+"="+encodeURIComponent(o.value);return o.metadata!==void 0&&(i+=_l+o.metadata.toString()),i})}function rE(r){var e=r.split(_l);if(!(e.length<=0)){var t=e.shift();if(t){var n=t.indexOf(eE);if(!(n<=0)){var o=decodeURIComponent(t.substring(0,n).trim()),i=decodeURIComponent(t.substring(n+1).trim()),a;return e.length>0&&(a=mm(e.join(_l))),{key:o,value:i,metadata:a}}}}}function QL(r){return typeof r!="string"||r.length===0?{}:r.split(vm).map(function(e){return rE(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 Pl;(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"})(Pl||(Pl={}));var eN=",",tN=["OTEL_SDK_DISABLED"];function rN(r){return tN.indexOf(r)>-1}var nN=["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 oN(r){return nN.indexOf(r)>-1}var iN=["OTEL_NO_PATCH_MODULES","OTEL_PROPAGATORS"];function aN(r){return iN.indexOf(r)>-1}var Am=1/0,wm=128,sN=128,lN=128,Rm={OTEL_SDK_DISABLED:!1,CONTAINER_NAME:"",ECS_CONTAINER_METADATA_URI_V4:"",ECS_CONTAINER_METADATA_URI:"",HOSTNAME:"",KUBERNETES_SERVICE_HOST:"",NAMESPACE:"",OTEL_BSP_EXPORT_TIMEOUT:3e4,OTEL_BSP_MAX_EXPORT_BATCH_SIZE:512,OTEL_BSP_MAX_QUEUE_SIZE:2048,OTEL_BSP_SCHEDULE_DELAY:5e3,OTEL_BLRP_EXPORT_TIMEOUT:3e4,OTEL_BLRP_MAX_EXPORT_BATCH_SIZE:512,OTEL_BLRP_MAX_QUEUE_SIZE:2048,OTEL_BLRP_SCHEDULE_DELAY:5e3,OTEL_EXPORTER_JAEGER_AGENT_HOST:"",OTEL_EXPORTER_JAEGER_AGENT_PORT:6832,OTEL_EXPORTER_JAEGER_ENDPOINT:"",OTEL_EXPORTER_JAEGER_PASSWORD:"",OTEL_EXPORTER_JAEGER_USER:"",OTEL_EXPORTER_OTLP_ENDPOINT:"",OTEL_EXPORTER_OTLP_TRACES_ENDPOINT:"",OTEL_EXPORTER_OTLP_METRICS_ENDPOINT:"",OTEL_EXPORTER_OTLP_LOGS_ENDPOINT:"",OTEL_EXPORTER_OTLP_HEADERS:"",OTEL_EXPORTER_OTLP_TRACES_HEADERS:"",OTEL_EXPORTER_OTLP_METRICS_HEADERS:"",OTEL_EXPORTER_OTLP_LOGS_HEADERS:"",OTEL_EXPORTER_OTLP_TIMEOUT:1e4,OTEL_EXPORTER_OTLP_TRACES_TIMEOUT:1e4,OTEL_EXPORTER_OTLP_METRICS_TIMEOUT:1e4,OTEL_EXPORTER_OTLP_LOGS_TIMEOUT:1e4,OTEL_EXPORTER_ZIPKIN_ENDPOINT:"http://localhost:9411/api/v2/spans",OTEL_LOG_LEVEL:Ne.INFO,OTEL_NO_PATCH_MODULES:[],OTEL_PROPAGATORS:["tracecontext","baggage"],OTEL_RESOURCE_ATTRIBUTES:"",OTEL_SERVICE_NAME:"",OTEL_ATTRIBUTE_VALUE_LENGTH_LIMIT:Am,OTEL_ATTRIBUTE_COUNT_LIMIT:wm,OTEL_SPAN_ATTRIBUTE_VALUE_LENGTH_LIMIT:Am,OTEL_SPAN_ATTRIBUTE_COUNT_LIMIT:wm,OTEL_LOGRECORD_ATTRIBUTE_VALUE_LENGTH_LIMIT:Am,OTEL_LOGRECORD_ATTRIBUTE_COUNT_LIMIT:wm,OTEL_SPAN_EVENT_COUNT_LIMIT:128,OTEL_SPAN_LINK_COUNT_LIMIT:128,OTEL_SPAN_ATTRIBUTE_PER_EVENT_COUNT_LIMIT:sN,OTEL_SPAN_ATTRIBUTE_PER_LINK_COUNT_LIMIT:lN,OTEL_TRACES_EXPORTER:"",OTEL_TRACES_SAMPLER:Pl.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 cN(r,e,t){if(!(typeof t[r]>"u")){var n=String(t[r]);e[r]=n.toLowerCase()==="true"}}function uN(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 dN(r,e,t,n){n===void 0&&(n=eN);var o=t[r];typeof o=="string"&&(e[r]=o.split(n).map(function(i){return i.trim()}))}var mN={ALL:Ne.ALL,VERBOSE:Ne.VERBOSE,DEBUG:Ne.DEBUG,INFO:Ne.INFO,WARN:Ne.WARN,ERROR:Ne.ERROR,NONE:Ne.NONE};function pN(r,e,t){var n=t[r];if(typeof n=="string"){var o=mN[n.toUpperCase()];o!=null&&(e[r]=o)}}function nE(r){var e={};for(var t in Rm){var n=t;switch(n){case"OTEL_LOG_LEVEL":pN(n,e,r);break;default:if(rN(n))cN(n,e,r);else if(oN(n))uN(n,e,r);else if(aN(n))dN(n,e,r);else{var o=r[n];typeof o<"u"&&o!==null&&(e[n]=String(o))}}}return e}function ht(){var r=nE(process.env);return Object.assign({},Rm,r)}function oE(r){return r>=48&&r<=57?r-48:r>=97&&r<=102?r-87:r-55}function Il(r){for(var e=new Uint8Array(r.length/2),t=0,n=0;n<r.length;n+=2){var o=oE(r.charCodeAt(n)),i=oE(r.charCodeAt(n+1));e[t++]=o<<4|i}return e}var iE="1.25.1";var gN="deployment.environment";var hN="process.runtime.name";var fN="service.name";var SN="service.instance.id";var yN="telemetry.sdk.name",bN="telemetry.sdk.language",EN="telemetry.sdk.version";var aE=gN;var sE=hN;var Ol=fN;var lE=SN;var Pa=yN,Ia=bN,Oa=EN;var TN="nodejs";var cE=TN;var Qo,Ll=(Qo={},Qo[Pa]="opentelemetry",Qo[sE]="node",Qo[Ia]=cE,Qo[Oa]=iE,Qo);var vN=9,AN=6,wN=Math.pow(10,AN),RN=Math.pow(10,vN);function uE(r){var e=r/1e3,t=Math.trunc(e),n=Math.round(r%1e3*wN);return[t,n]}function dE(r){return r[0]*RN+r[1]}function La(r){return r[0]*1e6+r[1]/1e3}var Zn;(function(r){r[r.SUCCESS=0]="SUCCESS",r[r.FAILED=1]="FAILED"})(Zn||(Zn={}));var mE=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 CN=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},xN=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))},pE=function(){function r(e,t){this._callback=e,this._that=t,this._isCalled=!1,this._deferred=new mE}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,xN([this._that],CN(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 nr;(function(r){r[r.DELTA=0]="DELTA",r[r.CUMULATIVE=1]="CUMULATIVE"})(nr||(nr={}));var Rt;(function(r){r[r.HISTOGRAM=0]="HISTOGRAM",r[r.EXPONENTIAL_HISTOGRAM=1]="EXPONENTIAL_HISTOGRAM",r[r.GAUGE=2]="GAUGE",r[r.SUM=3]="SUM"})(Rt||(Rt={}));var MN=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 Yte=function(r){MN(e,r);function e(t){var n=r.call(this,t)||this;return Object.setPrototypeOf(n,e.prototype),n}return e}(Error);function gE(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 or;(function(r){r[r.DROP=0]="DROP",r[r.SUM=1]="SUM",r[r.LAST_VALUE=2]="LAST_VALUE",r[r.HISTOGRAM=3]="HISTOGRAM",r[r.EXPONENTIAL_HISTOGRAM=4]="EXPONENTIAL_HISTOGRAM"})(or||(or={}));var hE=function(){function r(){this.kind=or.DROP}return r.prototype.createAccumulation=function(){},r.prototype.merge=function(e,t){},r.prototype.diff=function(e,t){},r.prototype.toMetricData=function(e,t,n,o){},r}();var oe;(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"})(oe||(oe={}));var _N=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 PN(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 Cm=function(){function r(e,t,n,o){n===void 0&&(n=!0),o===void 0&&(o=PN(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=gE(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 xm=function(){function r(e,t){this._boundaries=e,this._recordMinMax=t,this.kind=or.HISTOGRAM}return r.prototype.createAccumulation=function(e){return new Cm(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 Cm(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 Cm(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:Rt.HISTOGRAM,dataPoints:n.map(function(i){var a=_N(i,2),s=a[0],c=a[1],l=c.toPointValue(),u=e.type===oe.GAUGE||e.type===oe.UP_DOWN_COUNTER||e.type===oe.OBSERVABLE_GAUGE||e.type===oe.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 IN),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 IN=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 fE=52,ON=2146435072,LN=1048575,Im=1023,Nl=-Im+1,Dl=Im,Na=Math.pow(2,-1022);function kl(r){var e=new DataView(new ArrayBuffer(8));e.setFloat64(0,r);var t=e.getUint32(0),n=(t&ON)>>20;return n-Im}function Ul(r){var e=new DataView(new ArrayBuffer(8));e.setFloat64(0,r);var t=e.getUint32(0),n=e.getUint32(4),o=(t&LN)*Math.pow(2,32);return o+n}function Da(r,e){return r===0||r===Number.POSITIVE_INFINITY||r===Number.NEGATIVE_INFINITY||Number.isNaN(r)?r:r*Math.pow(2,e)}function yE(r){return r--,r|=r>>1,r|=r>>2,r|=r>>4,r|=r>>8,r|=r>>16,r++,r}var NN=function(){var r=function(e,t){return r=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(n,o){n.__proto__=o}||function(n,o){for(var i in o)Object.prototype.hasOwnProperty.call(o,i)&&(n[i]=o[i])},r(e,t)};return function(e,t){if(typeof t!="function"&&t!==null)throw new TypeError("Class extends value "+String(t)+" is not a constructor or null");r(e,t);function n(){this.constructor=e}e.prototype=t===null?Object.create(t):(n.prototype=t.prototype,new n)}}(),Sn=function(r){NN(e,r);function e(){return r!==null&&r.apply(this,arguments)||this}return e}(Error);var EE=function(){function r(e){this._shift=-e}return r.prototype.mapToIndex=function(e){if(e<Na)return this._minNormalLowerBoundaryIndex();var t=kl(e),n=this._rightShift(Ul(e)-1,fE);return t+n>>this._shift},r.prototype.lowerBoundary=function(e){var t=this._minNormalLowerBoundaryIndex();if(e<t)throw new Sn("underflow: "+e+" is < minimum lower boundary: "+t);var n=this._maxNormalLowerBoundaryIndex();if(e>n)throw new Sn("overflow: "+e+" is > maximum lower boundary: "+n);return Da(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=Nl>>this._shift;return this._shift<2&&e--,e},r.prototype._maxNormalLowerBoundaryIndex=function(){return Dl>>this._shift},r.prototype._rightShift=function(e,t){return Math.floor(e*Math.pow(2,-t))},r}();var TE=function(){function r(e){this._scale=e,this._scaleFactor=Da(Math.LOG2E,e),this._inverseFactor=Da(Math.LN2,-e)}return r.prototype.mapToIndex=function(e){if(e<=Na)return this._minNormalLowerBoundaryIndex()-1;if(Ul(e)===0){var t=kl(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 Sn("overflow: "+e+" is > maximum lower boundary: "+t)}var n=this._minNormalLowerBoundaryIndex();if(e<=n){if(e===n)return Na;if(e===n-1)return Math.exp((e+(1<<this._scale))/this._scaleFactor)/2;throw new Sn("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 Nl<<this._scale},r.prototype._maxNormalLowerBoundaryIndex=function(){return(Dl+1<<this._scale)-1},r}();var vE=-10,AE=20,DN=Array.from({length:31},function(r,e){return e>10?new TE(e-10):new EE(e-10)});function Om(r){if(r>AE||r<vE)throw new Sn("expected scale >= "+vE+" && <= "+AE+", got: "+r);return DN[r+10]}var kN=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},Fl=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}(),UN=20,FN=160,Lm=2,BN=function(){function r(e,t,n,o,i,a,s,c,l,u,d){e===void 0&&(e=e),t===void 0&&(t=FN),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(UN)),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&&(z.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=yE(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=Fl.combine(this._highLowAtScale(this.positive,this.scale,t),this._highLowAtScale(e.positive,e.scale,t)),o=Fl.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 Fl(0,-1);var o=t-n;return new Fl(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 wE=function(){function r(e,t){this._maxSize=e,this._recordMinMax=t,this.kind=or.EXPONENTIAL_HISTOGRAM}return r.prototype.createAccumulation=function(e){return new BN(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:Rt.EXPONENTIAL_HISTOGRAM,dataPoints:n.map(function(i){var a=kN(i,2),s=a[0],c=a[1],l=c.toPointValue(),u=e.type===oe.GAUGE||e.type===oe.UP_DOWN_COUNTER||e.type===oe.OBSERVABLE_GAUGE||e.type===oe.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 zN=function(r,e){var t=typeof Symbol=="function"&&r[Symbol.iterator];if(!t)return r;var n=t.call(r),o,i=[],a;try{for(;(e===void 0||e-- >0)&&!(o=n.next()).done;)i.push(o.value)}catch(s){a={error:s}}finally{try{o&&!o.done&&(t=n.return)&&t.call(n)}finally{if(a)throw a.error}}return i},Nm=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=uE(Date.now())},r.prototype.setStartTime=function(e){this.startTime=e},r.prototype.toPointValue=function(){return this._current},r}();var RE=function(){function r(){this.kind=or.LAST_VALUE}return r.prototype.createAccumulation=function(e){return new Nm(e)},r.prototype.merge=function(e,t){var n=La(t.sampleTime)>=La(e.sampleTime)?t:e;return new Nm(e.startTime,n.toPointValue(),n.sampleTime)},r.prototype.diff=function(e,t){var n=La(t.sampleTime)>=La(e.sampleTime)?t:e;return new Nm(t.startTime,n.toPointValue(),n.sampleTime)},r.prototype.toMetricData=function(e,t,n,o){return{descriptor:e,aggregationTemporality:t,dataPointType:Rt.GAUGE,dataPoints:n.map(function(i){var a=zN(i,2),s=a[0],c=a[1];return{attributes:s,startTime:c.startTime,endTime:o,value:c.toPointValue()}})}},r}();var HN=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},ka=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 Dm=function(){function r(e){this.monotonic=e,this.kind=or.SUM}return r.prototype.createAccumulation=function(e){return new ka(e,this.monotonic)},r.prototype.merge=function(e,t){var n=e.toPointValue(),o=t.toPointValue();return t.reset?new ka(t.startTime,this.monotonic,o,t.reset):new ka(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 ka(t.startTime,this.monotonic,o,!0):new ka(t.startTime,this.monotonic,o-n)},r.prototype.toMetricData=function(e,t,n,o){return{descriptor:e,aggregationTemporality:t,dataPointType:Rt.SUM,dataPoints:n.map(function(i){var a=HN(i,2),s=a[0],c=a[1];return{attributes:s,startTime:c.startTime,endTime:o,value:c.toPointValue()}}),isMonotonic:this.monotonic}},r}();var Qn=function(){var r=function(e,t){return r=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(n,o){n.__proto__=o}||function(n,o){for(var i in o)Object.prototype.hasOwnProperty.call(o,i)&&(n[i]=o[i])},r(e,t)};return function(e,t){if(typeof t!="function"&&t!==null)throw new TypeError("Class extends value "+String(t)+" is not a constructor or null");r(e,t);function n(){this.constructor=e}e.prototype=t===null?Object.create(t):(n.prototype=t.prototype,new n)}}(),Nr=function(){function r(){}return r.Drop=function(){return LE},r.Sum=function(){return NE},r.LastValue=function(){return DE},r.Histogram=function(){return kE},r.ExponentialHistogram=function(){return GN},r.Default=function(){return VN},r}();var CE=function(r){Qn(e,r);function e(){return r!==null&&r.apply(this,arguments)||this}return e.prototype.createAggregator=function(t){return e.DEFAULT_INSTANCE},e.DEFAULT_INSTANCE=new hE,e}(Nr);var xE=function(r){Qn(e,r);function e(){return r!==null&&r.apply(this,arguments)||this}return e.prototype.createAggregator=function(t){switch(t.type){case oe.COUNTER:case oe.OBSERVABLE_COUNTER:case oe.HISTOGRAM:return e.MONOTONIC_INSTANCE;default:return e.NON_MONOTONIC_INSTANCE}},e.MONOTONIC_INSTANCE=new Dm(!0),e.NON_MONOTONIC_INSTANCE=new Dm(!1),e}(Nr);var ME=function(r){Qn(e,r);function e(){return r!==null&&r.apply(this,arguments)||this}return e.prototype.createAggregator=function(t){return e.DEFAULT_INSTANCE},e.DEFAULT_INSTANCE=new RE,e}(Nr);var _E=function(r){Qn(e,r);function e(){return r!==null&&r.apply(this,arguments)||this}return e.prototype.createAggregator=function(t){return e.DEFAULT_INSTANCE},e.DEFAULT_INSTANCE=new xm([0,5,10,25,50,75,100,250,500,750,1e3,2500,5e3,7500,1e4],!0),e}(Nr);var PE=function(r){Qn(e,r);function e(t,n){n===void 0&&(n=!0);var o=r.call(this)||this;if(o._recordMinMax=n,t==null)throw new Error("ExplicitBucketHistogramAggregation should be created with explicit boundaries, if a single bucket histogram is required, please pass an empty array");t=t.concat(),t=t.sort(function(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 xm(this._boundaries,this._recordMinMax)},e}(Nr);var IE=function(r){Qn(e,r);function e(t,n){t===void 0&&(t=160),n===void 0&&(n=!0);var o=r.call(this)||this;return o._maxSize=t,o._recordMinMax=n,o}return e.prototype.createAggregator=function(t){return new wE(this._maxSize,this._recordMinMax)},e}(Nr);var OE=function(r){Qn(e,r);function e(){return r!==null&&r.apply(this,arguments)||this}return e.prototype._resolve=function(t){switch(t.type){case oe.COUNTER:case oe.UP_DOWN_COUNTER:case oe.OBSERVABLE_COUNTER:case oe.OBSERVABLE_UP_DOWN_COUNTER:return NE;case oe.GAUGE:case oe.OBSERVABLE_GAUGE:return DE;case oe.HISTOGRAM:return t.advice.explicitBucketBoundaries?new PE(t.advice.explicitBucketBoundaries):kE}return z.warn("Unable to recognize instrument type: "+t.type),LE},e.prototype.createAggregator=function(t){return this._resolve(t).createAggregator(t)},e}(Nr);var LE=new CE,NE=new xE,DE=new ME,kE=new _E,GN=new IE,VN=new OE;_e();function Bl(){return"unknown_service:"+process.argv0}var yn=function(){return yn=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},yn.apply(this,arguments)},jN=function(r,e,t,n){function o(i){return i instanceof t?i:new t(function(a){a(i)})}return new(t||(t=Promise))(function(i,a){function 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())})},WN=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}}},$N=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},km=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 z.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[Ol]=Bl(),e[Ia]=Ll[Ia],e[Pa]=Ll[Pa],e[Oa]=Ll[Oa],e))},Object.defineProperty(r.prototype,"attributes",{get:function(){var e;return this.asyncAttributesPending&&z.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 jN(this,void 0,void 0,function(){return WN(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=yn(yn({},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=$N(a,2),l=c[0],u=c[1];return yn(yn(yn(yn({},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 eo;(function(r){r[r.DELTA=0]="DELTA",r[r.CUMULATIVE=1]="CUMULATIVE",r[r.LOWMEMORY=2]="LOWMEMORY"})(eo||(eo={}));_e();var qN=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())})},KN=function(r,e){var t={label:0,sent:function(){if(i[0]&1)throw i[1];return i[1]},trys:[],ops:[]},n,o,i,a;return a={next: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}}},Um=function(){return nr.CUMULATIVE},UE=function(r){switch(r){case oe.COUNTER:case oe.OBSERVABLE_COUNTER:case oe.GAUGE:case oe.HISTOGRAM:case oe.OBSERVABLE_GAUGE:return nr.DELTA;case oe.UP_DOWN_COUNTER:case oe.OBSERVABLE_UP_DOWN_COUNTER:return nr.CUMULATIVE}},FE=function(r){switch(r){case oe.COUNTER:case oe.HISTOGRAM:return nr.DELTA;case oe.GAUGE:case oe.UP_DOWN_COUNTER:case oe.OBSERVABLE_UP_DOWN_COUNTER:case oe.OBSERVABLE_COUNTER:case oe.OBSERVABLE_GAUGE:return nr.CUMULATIVE}};function YN(){var r=ht(),e=r.OTEL_EXPORTER_OTLP_METRICS_TEMPORALITY_PREFERENCE.trim().toLowerCase();return e==="cumulative"?Um:e==="delta"?UE:e==="lowmemory"?FE:(z.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."),Um)}function XN(r){return r!=null?r===eo.DELTA?UE:r===eo.LOWMEMORY?FE:Um:YN()}function JN(r){return r?.aggregationPreference?r.aggregationPreference:function(e){return Nr.Default()}}var BE=function(){function r(e,t){this._otlpExporter=e,this._aggregationSelector=JN(t),this._aggregationTemporalitySelector=XN(t?.temporalityPreference)}return r.prototype.export=function(e,t){this._otlpExporter.export([e],t)},r.prototype.shutdown=function(){return qN(this,void 0,void 0,function(){return KN(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 ZN=function(r,e){var t=typeof Symbol=="function"&&r[Symbol.iterator];if(!t)return r;var n=t.call(r),o,i=[],a;try{for(;(e===void 0||e-- >0)&&!(o=n.next()).done;)i.push(o.value)}catch(s){a={error:s}}finally{try{o&&!o.done&&(t=n.return)&&t.call(n)}finally{if(a)throw a.error}}return i},zE=1e4,HE=5,GE=1e3,VE=5e3,jE=1.5;function Ua(r){r===void 0&&(r={});var e={};return Object.entries(r).forEach(function(t){var n=ZN(t,2),o=n[0],i=n[1];typeof i<"u"?e[o]=String(i):z.warn('Header "'+o+'" has invalid value ('+i+") and will be ignored")}),e}function Fm(r,e){return r.endsWith("/")||(r=r+"/"),r+e}function Bm(r){try{var e=new URL(r);return e.pathname===""&&(e.pathname=e.pathname+"/"),e.toString()}catch{return z.warn("Could not parse export URL: '"+r+"'"),r}}function zm(r){return typeof r=="number"?r<=0?Hm(r,zE):r:QN()}function QN(){var r,e=Number((r=ht().OTEL_EXPORTER_OTLP_TRACES_TIMEOUT)!==null&&r!==void 0?r:ht().OTEL_EXPORTER_OTLP_TIMEOUT);return e<=0?Hm(e,zE):e}function Hm(r,e){return z.warn("Timeout must be greater than 0",r),e}function WE(r){var e=[429,502,503,504];return e.includes(r)}function $E(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 qE=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 pE(this._shutdown,this),this._concurrencyLimit=typeof e.concurrencyLimit=="number"?e.concurrencyLimit:30,this.timeoutMillis=zm(e.timeoutMillis),this.onInit(e)}return r.prototype.export=function(e,t){if(this._shutdownOnce.isCalled){t({code:Zn.FAILED,error:new Error("Exporter has been shutdown")});return}if(this._sendingPromises.length>=this._concurrencyLimit){t({code:Zn.FAILED,error:new Error("Concurrent export limit reached")});return}this._export(e).then(function(){t({code:Zn.SUCCESS})}).catch(function(n){t({code:Zn.FAILED,error:n})})},r.prototype._export=function(e){var t=this;return new Promise(function(n,o){try{z.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 z.debug("shutdown started"),this.onShutdown(),this.forceFlush()},r}();_e();import*as Gm from"url";import*as Hl from"http";import*as Gl from"https";import*as KE from"zlib";import{Readable as tD}from"stream";var bn;(function(r){r.NONE="none",r.GZIP="gzip"})(bn||(bn={}));var eD=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)}}(),ei=function(r){eD(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 zl=function(){return zl=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},zl.apply(this,arguments)};function Vm(r,e,t,n,o){var i=r.timeoutMillis,a=new Gm.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 ei("Request Timeout");o(h)}else s>=14?l.destroy():l.abort()},i),m={hostname:a.hostname,port:a.port,path:a.pathname,method:"POST",headers:zl({"Content-Type":t},r.headers),agent:r.agent},p=a.protocol==="http:"?Hl.request:Gl.request,g=function(h,f){switch(h===void 0&&(h=HE),f===void 0&&(f=GE),l=p(m,function(b){var x="";b.on("data",function(T){return x+=T}),b.on("aborted",function(){if(u){var T=new ei("Request Timeout");o(T)}}),b.on("end",function(){if(u===!1)if(b.statusCode&&b.statusCode<299)z.debug("statusCode: "+b.statusCode,x),n(),clearTimeout(d),clearTimeout(c);else if(b.statusCode&&WE(b.statusCode)&&h>0){var T=void 0;f=jE*f,b.headers["retry-after"]?T=$E(b.headers["retry-after"]):T=Math.round(Math.random()*(VE-f)+f),c=setTimeout(function(){g(h-1,f)},T)}else{var v=new ei(b.statusMessage,b.statusCode,x);o(v),clearTimeout(d),clearTimeout(c)}})}),l.on("error",function(b){if(u){var x=new ei("Request Timeout",b.code);o(x)}else o(b);clearTimeout(d),clearTimeout(c)}),l.on("abort",function(){if(u){var b=new ei("Request Timeout");o(b)}clearTimeout(d),clearTimeout(c)}),r.compression){case bn.GZIP:{l.setHeader("Content-Encoding","gzip");var E=rD(e);E.on("error",o).pipe(KE.createGzip()).on("error",o).pipe(l);break}default:l.end(Buffer.from(e));break}};g()}function rD(r){var e=new tD;return e.push(r),e.push(null),e}function jm(r){if(r.httpAgentOptions&&r.keepAlive===!1){z.warn("httpAgentOptions is used only when keepAlive is true");return}if(!(r.keepAlive===!1||!r.url))try{var e=new Gm.URL(r.url),t=e.protocol==="http:"?Hl.Agent:Gl.Agent;return new t(zl({keepAlive:!0},r.httpAgentOptions))}catch(n){z.error("collector exporter failed to create http agent. err: "+n.message);return}}function Wm(r){if(r)return r;var e=ht().OTEL_EXPORTER_OTLP_TRACES_COMPRESSION||ht().OTEL_EXPORTER_OTLP_COMPRESSION;return e===bn.GZIP?bn.GZIP:bn.NONE}_e();var nD=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)}}(),Vl=function(r){nD(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&&z.warn("Metadata cannot be set when using http"),i.headers=Object.assign(i.DEFAULT_HEADERS,Ua(t.headers),Zo.parseKeyPairsIntoRecord(ht().OTEL_EXPORTER_OTLP_HEADERS)),i.agent=jm(t),i.compression=Wm(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){z.debug("Shutdown already started. Cannot send objects");return}var a=new Promise(function(c,l){var u;Vm(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}(qE);function XE(r){var e=BigInt(1e9);return BigInt(r[0])*e+BigInt(r[1])}function oD(r){var e=Number(BigInt.asUintN(32,r)),t=Number(BigInt.asUintN(32,r>>BigInt(32)));return{low:e,high:t}}function JE(r){var e=XE(r);return oD(e)}function iD(r){var e=XE(r);return e.toString()}var aD=typeof BigInt<"u"?iD:dE;function YE(r){return r}function ZE(r){if(r!==void 0)return Il(r)}var sD={encodeHrTime:JE,encodeSpanContext:Il,encodeOptionalSpanContext:ZE};function QE(r){var e,t;if(r===void 0)return sD;var n=(e=r.useLongBits)!==null&&e!==void 0?e:!0,o=(t=r.useHex)!==null&&t!==void 0?t:!1;return{encodeHrTime:n?JE:aD,encodeSpanContext:o?YE:Il,encodeOptionalSpanContext:o?YE:ZE}}var lD=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 eT(r){return{name:r.name,version:r.version}}function ti(r){return Object.keys(r).map(function(e){return tT(e,r[e])})}function tT(r,e){return{key:r,value:rT(e)}}function rT(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(rT)}}:e==="object"&&r!=null?{kvlistValue:{values:Object.entries(r).map(function(t){var n=lD(t,2),o=n[0],i=n[1];return tT(o,i)})}}:{}}function nT(r){return{attributes:ti(r.attributes),droppedAttributesCount:0}}_e();function iT(r,e){var t=QE(e);return{resource:nT(r.resource),schemaUrl:void 0,scopeMetrics:cD(r.scopeMetrics,t)}}function cD(r,e){return Array.from(r.map(function(t){return{scope:eT(t.scope),metrics:t.metrics.map(function(n){return uD(n,e)}),schemaUrl:t.scope.schemaUrl}}))}function uD(r,e){var t={name:r.descriptor.name,description:r.descriptor.description,unit:r.descriptor.unit},n=gD(r.aggregationTemporality);switch(r.dataPointType){case Rt.SUM:t.sum={aggregationTemporality:n,isMonotonic:r.isMonotonic,dataPoints:oT(r,e)};break;case Rt.GAUGE:t.gauge={dataPoints:oT(r,e)};break;case Rt.HISTOGRAM:t.histogram={aggregationTemporality:n,dataPoints:mD(r,e)};break;case Rt.EXPONENTIAL_HISTOGRAM:t.exponentialHistogram={aggregationTemporality:n,dataPoints:pD(r,e)};break}return t}function dD(r,e,t){var n={attributes:ti(r.attributes),startTimeUnixNano:t.encodeHrTime(r.startTime),timeUnixNano:t.encodeHrTime(r.endTime)};switch(e){case Gt.INT:n.asInt=r.value;break;case Gt.DOUBLE:n.asDouble=r.value;break}return n}function oT(r,e){return r.dataPoints.map(function(t){return dD(t,r.descriptor.valueType,e)})}function mD(r,e){return r.dataPoints.map(function(t){var n=t.value;return{attributes:ti(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 pD(r,e){return r.dataPoints.map(function(t){var n=t.value;return{attributes:ti(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 gD(r){switch(r){case nr.DELTA:return 1;case nr.CUMULATIVE:return 2}}function aT(r,e){return{resourceMetrics:r.map(function(t){return iT(t,e)})}}var $m={serializeRequest:function(r){var e=aT(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 sT="0.52.1";var lT=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)}}(),ri=function(){return ri=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},ri.apply(this,arguments)},cT="v1/metrics",hD="http://localhost:4318/"+cT,fD={"User-Agent":"OTel-OTLP-Exporter-JavaScript/"+sT},SD=function(r){lT(e,r);function e(t){var n=r.call(this,t,$m,"application/json")||this;return n.headers=ri(ri(ri(ri({},n.headers),fD),Zo.parseKeyPairsIntoRecord(ht().OTEL_EXPORTER_OTLP_METRICS_HEADERS)),Ua(t?.headers)),n}return e.prototype.getDefaultUrl=function(t){return typeof t.url=="string"?t.url:ht().OTEL_EXPORTER_OTLP_METRICS_ENDPOINT.length>0?Bm(ht().OTEL_EXPORTER_OTLP_METRICS_ENDPOINT):ht().OTEL_EXPORTER_OTLP_ENDPOINT.length>0?Fm(ht().OTEL_EXPORTER_OTLP_ENDPOINT,cT):hD},e}(Vl),uT=function(r){lT(e,r);function e(t){return r.call(this,new SD(t),t)||this}return e}(BE);var ni;(function(r){r[r.DELTA=0]="DELTA",r[r.CUMULATIVE=1]="CUMULATIVE"})(ni||(ni={}));var Dr;(function(r){r[r.HISTOGRAM=0]="HISTOGRAM",r[r.EXPONENTIAL_HISTOGRAM=1]="EXPONENTIAL_HISTOGRAM",r[r.GAUGE=2]="GAUGE",r[r.SUM=3]="SUM"})(Dr||(Dr={}));_e();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)}}(),dT=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())})},mT=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}}},bD=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},ED=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))},TD=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 pT(r){return r!=null}function jl(r){var e=Object.keys(r);return e.length===0?"":(e=e.sort(),JSON.stringify(e.map(function(t){return[t,r[t]]})))}function gT(r){var e,t;return r.name+":"+((e=r.version)!==null&&e!==void 0?e:"")+":"+((t=r.schemaUrl)!==null&&t!==void 0?t:"")}var qm=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 En(r,e){var t,n=new Promise(function(i,a){t=setTimeout(function(){a(new qm("Operation timed out."))},e)});return Promise.race([r,n]).then(function(o){return clearTimeout(t),o},function(o){throw clearTimeout(t),o})}function hT(r){return dT(this,void 0,void 0,function(){var e=this;return mT(this,function(t){return[2,Promise.all(r.map(function(n){return dT(e,void 0,void 0,function(){var o,i;return mT(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 fT(r){return r.status==="rejected"}function Km(r,e){var t=[];return r.forEach(function(n){t.push.apply(t,ED([],bD(e(n)),!1))}),t}function ST(r,e){var t,n;if(r.size!==e.size)return!1;try{for(var o=TD(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 yT(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 bT(r,e){return r.toLowerCase()===e.toLowerCase()}_e();var ir;(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"})(ir||(ir={}));var Ym=function(){function r(){this.kind=ir.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 pe;(function(r){r.COUNTER="COUNTER",r.GAUGE="GAUGE",r.HISTOGRAM="HISTOGRAM",r.UP_DOWN_COUNTER="UP_DOWN_COUNTER",r.OBSERVABLE_COUNTER="OBSERVABLE_COUNTER",r.OBSERVABLE_GAUGE="OBSERVABLE_GAUGE",r.OBSERVABLE_UP_DOWN_COUNTER="OBSERVABLE_UP_DOWN_COUNTER"})(pe||(pe={}));function kr(r,e,t){var n,o,i,a;return AD(r)||z.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:Gt.DOUBLE,advice:(a=t?.advice)!==null&&a!==void 0?a:{}}}function ET(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 TT(r,e){return bT(r.name,e.name)&&r.unit===e.unit&&r.type===e.type&&r.valueType===e.valueType}var vD=/^[a-z][a-z0-9_.\-/]{0,254}$/i;function AD(r){return r.match(vD)!=null}var wD=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 RD(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 Wl=function(){function r(e,t,n,o){n===void 0&&(n=!0),o===void 0&&(o=RD(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=yT(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 $l=function(){function r(e,t){this._boundaries=e,this._recordMinMax=t,this.kind=ir.HISTOGRAM}return r.prototype.createAccumulation=function(e){return new Wl(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 Wl(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 Wl(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:Dr.HISTOGRAM,dataPoints:n.map(function(i){var a=wD(i,2),s=a[0],c=a[1],l=c.toPointValue(),u=e.type===pe.GAUGE||e.type===pe.UP_DOWN_COUNTER||e.type===pe.OBSERVABLE_GAUGE||e.type===pe.OBSERVABLE_UP_DOWN_COUNTER;return{attributes:s,startTime:c.startTime,endTime:o,value:{min:l.hasMinMax?l.min:void 0,max:l.hasMinMax?l.max:void 0,sum:u?void 0:l.sum,buckets:l.buckets,count:l.count}}})}},r}();_e();var Xm=function(r,e){var t=typeof Symbol=="function"&&r[Symbol.iterator];if(!t)return r;var n=t.call(r),o,i=[],a;try{for(;(e===void 0||e-- >0)&&!(o=n.next()).done;)i.push(o.value)}catch(s){a={error:s}}finally{try{o&&!o.done&&(t=n.return)&&t.call(n)}finally{if(a)throw a.error}}return i},Jm=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))},Zm=function(){function r(e,t,n,o){e===void 0&&(e=new CD),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 CD=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,Jm([n,this._counts.length-t],Xm(this._counts.slice(t)),!1)),o.splice.apply(o,Jm([0,t],Xm(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(Jm([],Xm(this._counts),!1))},r}();var vT=52,xD=2146435072,MD=1048575,Qm=1023,ql=-Qm+1,Kl=Qm,Fa=Math.pow(2,-1022);function Yl(r){var e=new DataView(new ArrayBuffer(8));e.setFloat64(0,r);var t=e.getUint32(0),n=(t&xD)>>20;return n-Qm}function Xl(r){var e=new DataView(new ArrayBuffer(8));e.setFloat64(0,r);var t=e.getUint32(0),n=e.getUint32(4),o=(t&MD)*Math.pow(2,32);return o+n}function Ba(r,e){return r===0||r===Number.POSITIVE_INFINITY||r===Number.NEGATIVE_INFINITY||Number.isNaN(r)?r:r*Math.pow(2,e)}function wT(r){return r--,r|=r>>1,r|=r>>2,r|=r>>4,r|=r>>8,r|=r>>16,r++,r}var _D=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)}}(),Tn=function(r){_D(e,r);function e(){return r!==null&&r.apply(this,arguments)||this}return e}(Error);var CT=function(){function r(e){this._shift=-e}return r.prototype.mapToIndex=function(e){if(e<Fa)return this._minNormalLowerBoundaryIndex();var t=Yl(e),n=this._rightShift(Xl(e)-1,vT);return t+n>>this._shift},r.prototype.lowerBoundary=function(e){var t=this._minNormalLowerBoundaryIndex();if(e<t)throw new Tn("underflow: "+e+" is < minimum lower boundary: "+t);var n=this._maxNormalLowerBoundaryIndex();if(e>n)throw new Tn("overflow: "+e+" is > maximum lower boundary: "+n);return Ba(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=ql>>this._shift;return this._shift<2&&e--,e},r.prototype._maxNormalLowerBoundaryIndex=function(){return Kl>>this._shift},r.prototype._rightShift=function(e,t){return Math.floor(e*Math.pow(2,-t))},r}();var xT=function(){function r(e){this._scale=e,this._scaleFactor=Ba(Math.LOG2E,e),this._inverseFactor=Ba(Math.LN2,-e)}return r.prototype.mapToIndex=function(e){if(e<=Fa)return this._minNormalLowerBoundaryIndex()-1;if(Xl(e)===0){var t=Yl(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 Tn("overflow: "+e+" is > maximum lower boundary: "+t)}var n=this._minNormalLowerBoundaryIndex();if(e<=n){if(e===n)return Fa;if(e===n-1)return Math.exp((e+(1<<this._scale))/this._scaleFactor)/2;throw new Tn("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 ql<<this._scale},r.prototype._maxNormalLowerBoundaryIndex=function(){return(Kl+1<<this._scale)-1},r}();var MT=-10,_T=20,PD=Array.from({length:31},function(r,e){return e>10?new xT(e-10):new CT(e-10)});function ep(r){if(r>_T||r<MT)throw new Tn("expected scale >= "+MT+" && <= "+_T+", got: "+r);return PD[r+10]}var ID=function(r,e){var t=typeof Symbol=="function"&&r[Symbol.iterator];if(!t)return r;var n=t.call(r),o,i=[],a;try{for(;(e===void 0||e-- >0)&&!(o=n.next()).done;)i.push(o.value)}catch(s){a={error:s}}finally{try{o&&!o.done&&(t=n.return)&&t.call(n)}finally{if(a)throw a.error}}return i},Jl=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}(),OD=20,LD=160,tp=2,PT=function(){function r(e,t,n,o,i,a,s,c,l,u,d){e===void 0&&(e=e),t===void 0&&(t=LD),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 Zm),u===void 0&&(u=new Zm),d===void 0&&(d=ep(OD)),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<tp&&(z.warn("Exponential Histogram Max Size set to "+this._maxSize+", changing to the minimum size of: "+tp),this._maxSize=tp)}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=wT(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=ep(t)}},r.prototype._minScale=function(e){var t=Math.min(this.scale,e.scale),n=Jl.combine(this._highLowAtScale(this.positive,this.scale,t),this._highLowAtScale(e.positive,e.scale,t)),o=Jl.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 Jl(0,-1);var o=t-n;return new Jl(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 rp=function(){function r(e,t){this._maxSize=e,this._recordMinMax=t,this.kind=ir.EXPONENTIAL_HISTOGRAM}return r.prototype.createAccumulation=function(e){return new PT(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:Dr.EXPONENTIAL_HISTOGRAM,dataPoints:n.map(function(i){var a=ID(i,2),s=a[0],c=a[1],l=c.toPointValue(),u=e.type===pe.GAUGE||e.type===pe.UP_DOWN_COUNTER||e.type===pe.OBSERVABLE_GAUGE||e.type===pe.OBSERVABLE_UP_DOWN_COUNTER;return{attributes:s,startTime:c.startTime,endTime:o,value:{min:l.hasMinMax?l.min:void 0,max:l.hasMinMax?l.max:void 0,sum:u?void 0:l.sum,positive:{offset:l.positive.offset,bucketCounts:l.positive.bucketCounts},negative:{offset:l.negative.offset,bucketCounts:l.negative.bucketCounts},count:l.count,scale:l.scale,zeroCount:l.zeroCount}}})}},r}();_e();var ND=pm("OpenTelemetry SDK Context Key SUPPRESS_TRACING");function IT(r){return r.setValue(ND,!0)}_e();function OT(){return function(r){z.error(DD(r))}}function DD(r){return typeof r=="string"?r:JSON.stringify(kD(r))}function kD(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 UD=OT();function Zl(r){try{UD(r)}catch{}}var LT="1.30.1";var FD="process.runtime.name";var BD="service.name";var zD="telemetry.sdk.name",HD="telemetry.sdk.language",GD="telemetry.sdk.version";var NT=FD;var DT=BD;var za=zD,Ha=HD,Ga=GD;var VD="nodejs";var kT=VD;var oi,to=(oi={},oi[za]="opentelemetry",oi[NT]="node",oi[Ha]=kT,oi[Ga]=LT,oi);function Va(r){r.unref()}var XD=9,JD=6,ZD=Math.pow(10,JD),Qoe=Math.pow(10,XD);function ro(r){var e=r/1e3,t=Math.trunc(e),n=Math.round(r%1e3*ZD);return[t,n]}function ii(r){return r[0]*1e6+r[1]/1e3}var ja;(function(r){r[r.SUCCESS=0]="SUCCESS",r[r.FAILED=1]="FAILED"})(ja||(ja={}));_e();function UT(r,e){return new Promise(function(t){Jo.with(IT(Jo.active()),function(){r.export(e,function(n){t(n)})})})}var FT={_export:UT};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},Ql=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=ro(Date.now())},r.prototype.setStartTime=function(e){this.startTime=e},r.prototype.toPointValue=function(){return this._current},r}();var np=function(){function r(){this.kind=ir.LAST_VALUE}return r.prototype.createAccumulation=function(e){return new Ql(e)},r.prototype.merge=function(e,t){var n=ii(t.sampleTime)>=ii(e.sampleTime)?t:e;return new Ql(e.startTime,n.toPointValue(),n.sampleTime)},r.prototype.diff=function(e,t){var n=ii(t.sampleTime)>=ii(e.sampleTime)?t:e;return new Ql(t.startTime,n.toPointValue(),n.sampleTime)},r.prototype.toMetricData=function(e,t,n,o){return{descriptor:e,aggregationTemporality:t,dataPointType:Dr.GAUGE,dataPoints:n.map(function(i){var a=QD(i,2),s=a[0],c=a[1];return{attributes:s,startTime:c.startTime,endTime:o,value:c.toPointValue()}})}},r}();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},ai=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 ec=function(){function r(e){this.monotonic=e,this.kind=ir.SUM}return r.prototype.createAccumulation=function(e){return new ai(e,this.monotonic)},r.prototype.merge=function(e,t){var n=e.toPointValue(),o=t.toPointValue();return t.reset?new ai(t.startTime,this.monotonic,o,t.reset):new ai(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 ai(t.startTime,this.monotonic,o,!0):new ai(t.startTime,this.monotonic,o-n)},r.prototype.toMetricData=function(e,t,n,o){return{descriptor:e,aggregationTemporality:t,dataPointType:Dr.SUM,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()}}),isMonotonic:this.monotonic}},r}();var no=function(){var r=function(e,t){return r=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(n,o){n.__proto__=o}||function(n,o){for(var i in o)Object.prototype.hasOwnProperty.call(o,i)&&(n[i]=o[i])},r(e,t)};return function(e,t){if(typeof t!="function"&&t!==null)throw new TypeError("Class extends value "+String(t)+" is not a constructor or null");r(e,t);function n(){this.constructor=e}e.prototype=t===null?Object.create(t):(n.prototype=t.prototype,new n)}}(),ar=function(){function r(){}return r.Drop=function(){return WT},r.Sum=function(){return $T},r.LastValue=function(){return qT},r.Histogram=function(){return KT},r.ExponentialHistogram=function(){return tk},r.Default=function(){return rk},r}();var BT=function(r){no(e,r);function e(){return r!==null&&r.apply(this,arguments)||this}return e.prototype.createAggregator=function(t){return e.DEFAULT_INSTANCE},e.DEFAULT_INSTANCE=new Ym,e}(ar);var zT=function(r){no(e,r);function e(){return r!==null&&r.apply(this,arguments)||this}return e.prototype.createAggregator=function(t){switch(t.type){case pe.COUNTER:case pe.OBSERVABLE_COUNTER:case pe.HISTOGRAM:return e.MONOTONIC_INSTANCE;default:return e.NON_MONOTONIC_INSTANCE}},e.MONOTONIC_INSTANCE=new ec(!0),e.NON_MONOTONIC_INSTANCE=new ec(!1),e}(ar);var HT=function(r){no(e,r);function e(){return r!==null&&r.apply(this,arguments)||this}return e.prototype.createAggregator=function(t){return e.DEFAULT_INSTANCE},e.DEFAULT_INSTANCE=new np,e}(ar);var GT=function(r){no(e,r);function e(){return r!==null&&r.apply(this,arguments)||this}return e.prototype.createAggregator=function(t){return e.DEFAULT_INSTANCE},e.DEFAULT_INSTANCE=new $l([0,5,10,25,50,75,100,250,500,750,1e3,2500,5e3,7500,1e4],!0),e}(ar);var Wa=function(r){no(e,r);function e(t,n){n===void 0&&(n=!0);var o=r.call(this)||this;if(o._recordMinMax=n,t==null)throw new Error("ExplicitBucketHistogramAggregation should be created with explicit boundaries, if a single bucket histogram is required, please pass an empty array");t=t.concat(),t=t.sort(function(s,c){return s-c});var i=t.lastIndexOf(-1/0),a=t.indexOf(1/0);return a===-1&&(a=void 0),o._boundaries=t.slice(i+1,a),o}return e.prototype.createAggregator=function(t){return new $l(this._boundaries,this._recordMinMax)},e}(ar);var VT=function(r){no(e,r);function e(t,n){t===void 0&&(t=160),n===void 0&&(n=!0);var o=r.call(this)||this;return o._maxSize=t,o._recordMinMax=n,o}return e.prototype.createAggregator=function(t){return new rp(this._maxSize,this._recordMinMax)},e}(ar);var jT=function(r){no(e,r);function e(){return r!==null&&r.apply(this,arguments)||this}return e.prototype._resolve=function(t){switch(t.type){case pe.COUNTER:case pe.UP_DOWN_COUNTER:case pe.OBSERVABLE_COUNTER:case pe.OBSERVABLE_UP_DOWN_COUNTER:return $T;case pe.GAUGE:case pe.OBSERVABLE_GAUGE:return qT;case pe.HISTOGRAM:return t.advice.explicitBucketBoundaries?new Wa(t.advice.explicitBucketBoundaries):KT}return z.warn("Unable to recognize instrument type: "+t.type),WT},e.prototype.createAggregator=function(t){return this._resolve(t).createAggregator(t)},e}(ar);var WT=new BT,$T=new zT,qT=new HT,KT=new GT,tk=new VT,rk=new jT;var YT=function(r){return ar.Default()},XT=function(r){return ni.CUMULATIVE};var op=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())})},ip=function(r,e){var t={label:0,sent:function(){if(i[0]&1)throw i[1];return i[1]},trys:[],ops:[]},n,o,i,a;return a={next: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}}},JT=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},nk=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))},ZT=function(){function r(e){var t,n,o;this._shutdown=!1,this._aggregationSelector=(t=e?.aggregationSelector)!==null&&t!==void 0?t:YT,this._aggregationTemporalitySelector=(n=e?.aggregationTemporalitySelector)!==null&&n!==void 0?n:XT,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 op(this,void 0,void 0,function(){var t,n,o,i,a,s;return ip(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(nk([this._sdkMetricProducer.collect({timeoutMillis:e?.timeoutMillis})],JT(this._metricProducers.map(function(l){return l.collect({timeoutMillis:e?.timeoutMillis})})),!1))];case 1:return t=JT.apply(void 0,[c.sent()]),n=t[0],o=t.slice(1),i=n.errors.concat(Km(o,function(l){return l.errors})),a=n.resourceMetrics.resource,s=n.resourceMetrics.scopeMetrics.concat(Km(o,function(l){return l.resourceMetrics.scopeMetrics})),[2,{resourceMetrics:{resource:a,scopeMetrics:s},errors:i}]}})})},r.prototype.shutdown=function(e){return op(this,void 0,void 0,function(){return ip(this,function(t){switch(t.label){case 0:return this._shutdown?(z.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,En(this.onShutdown(),e.timeoutMillis)];case 3:t.sent(),t.label=4;case 4:return this._shutdown=!0,[2]}})})},r.prototype.forceFlush=function(e){return op(this,void 0,void 0,function(){return ip(this,function(t){switch(t.label){case 0:return this._shutdown?(z.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,En(this.onForceFlush(),e.timeoutMillis)];case 3:return t.sent(),[2]}})})},r}();_e();var ok=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)}}(),tc=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())})},rc=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}}},ik=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},ak=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))},ap=function(r){ok(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 tc(this,void 0,void 0,function(){var t;return rc(this,function(n){switch(n.label){case 0:return n.trys.push([0,2,,3]),[4,En(this._doRun(),this._exportTimeout)];case 1:return n.sent(),[3,3];case 2:return t=n.sent(),t instanceof qm?(z.error("Export took longer than %s milliseconds and timed out.",this._exportTimeout),[2]):(Zl(t),[3,3]);case 3:return[2]}})})},e.prototype._doRun=function(){var t,n;return tc(this,void 0,void 0,function(){var o,i,a,s,c,l;return rc(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=z).error.apply(l,ak(["PeriodicExportingMetricReader: metrics collection errors"],ik(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(),z.debug("Error while resolving async portion of resource: ",s),Zl(s),[3,5];case 5:return i.scopeMetrics.length===0?[2]:[4,FT._export(this._exporter,i)];case 6:if(c=u.sent(),c.code!==ja.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),Va(this._interval)},e.prototype.onForceFlush=function(){return tc(this,void 0,void 0,function(){return rc(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 tc(this,void 0,void 0,function(){return rc(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}(ZT);_e();_e();function nc(){return"unknown_service:"+process.argv0}var vn=function(){return vn=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},vn.apply(this,arguments)},sk=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())})},lk=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}}},ck=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},oc=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 z.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[DT]=nc(),e[Ha]=to[Ha],e[za]=to[za],e[Ga]=to[Ga],e))},Object.defineProperty(r.prototype,"attributes",{get:function(){var e;return this.asyncAttributesPending&&z.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 sk(this,void 0,void 0,function(){return lk(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=vn(vn({},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=ck(a,2),l=c[0],u=c[1];return vn(vn(vn(vn({},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 QT=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 oo=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)}}(),ic=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=Jo.active()),typeof e!="number"){z.warn("non-number value provided to metric "+this._descriptor.name+": "+e);return}this._descriptor.valueType===Gt.INT&&!Number.isInteger(e)&&(z.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,ro(Date.now()))},r}();var ev=function(r){oo(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}(ic);var tv=function(r){oo(e,r);function e(){return r!==null&&r.apply(this,arguments)||this}return e.prototype.add=function(t,n,o){if(t<0){z.warn("negative value provided to counter "+this._descriptor.name+": "+t);return}this._record(t,n,o)},e}(ic);var rv=function(r){oo(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}(ic);var nv=function(r){oo(e,r);function e(){return r!==null&&r.apply(this,arguments)||this}return e.prototype.record=function(t,n,o){if(t<0){z.warn("negative value provided to histogram "+this._descriptor.name+": "+t);return}this._record(t,n,o)},e}(ic);var ac=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 ov=function(r){oo(e,r);function e(){return r!==null&&r.apply(this,arguments)||this}return e}(ac);var iv=function(r){oo(e,r);function e(){return r!==null&&r.apply(this,arguments)||this}return e}(ac);var av=function(r){oo(e,r);function e(){return r!==null&&r.apply(this,arguments)||this}return e}(ac);function $a(r){return r instanceof ac}var sv=function(){function r(e){this._meterSharedState=e}return r.prototype.createGauge=function(e,t){var n=kr(e,pe.GAUGE,t),o=this._meterSharedState.registerMetricStorage(n);return new rv(o,n)},r.prototype.createHistogram=function(e,t){var n=kr(e,pe.HISTOGRAM,t),o=this._meterSharedState.registerMetricStorage(n);return new nv(o,n)},r.prototype.createCounter=function(e,t){var n=kr(e,pe.COUNTER,t),o=this._meterSharedState.registerMetricStorage(n);return new tv(o,n)},r.prototype.createUpDownCounter=function(e,t){var n=kr(e,pe.UP_DOWN_COUNTER,t),o=this._meterSharedState.registerMetricStorage(n);return new ev(o,n)},r.prototype.createObservableGauge=function(e,t){var n=kr(e,pe.OBSERVABLE_GAUGE,t),o=this._meterSharedState.registerAsyncMetricStorage(n);return new iv(n,o,this._meterSharedState.observableRegistry)},r.prototype.createObservableCounter=function(e,t){var n=kr(e,pe.OBSERVABLE_COUNTER,t),o=this._meterSharedState.registerAsyncMetricStorage(n);return new ov(n,o,this._meterSharedState.observableRegistry)},r.prototype.createObservableUpDownCounter=function(e,t){var n=kr(e,pe.OBSERVABLE_UP_DOWN_COUNTER,t),o=this._meterSharedState.registerAsyncMetricStorage(n);return new av(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 sc=function(){function r(e){this._instrumentDescriptor=e}return r.prototype.getInstrumentDescriptor=function(){return this._instrumentDescriptor},r.prototype.updateDescription=function(e){this._instrumentDescriptor=kr(this._instrumentDescriptor.name,this._instrumentDescriptor.type,{description:e,valueType:this._instrumentDescriptor.valueType,unit:this._instrumentDescriptor.unit,advice:this._instrumentDescriptor.advice})},r}();var uk=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)}}(),lv=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}}},dk=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 lv(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 lv(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 yr=function(r){uk(e,r);function e(){return r.call(this,jl)||this}return e}(dk);var mk=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},lc=function(){function r(e,t){this._aggregator=e,this._activeCollectionStorage=new yr,this._cumulativeMemoStorage=new yr,this._overflowAttributes={"otel.metric.overflow":!0},this._cardinalityLimit=(t??2e3)-1,this._overflowHashCode=jl(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=mk(o,3),a=i[0],s=i[1],c=i[2],l=n._aggregator.createAccumulation(t);l?.record(s);var u=l;if(n._cumulativeMemoStorage.has(a,c)){var d=n._cumulativeMemoStorage.get(a,c);u=n._aggregator.diff(d,l)}else if(n._cumulativeMemoStorage.size>=n._cardinalityLimit&&(a=n._overflowAttributes,c=n._overflowHashCode,n._cumulativeMemoStorage.has(a,c))){var d=n._cumulativeMemoStorage.get(a,c);u=n._aggregator.diff(d,l)}if(n._activeCollectionStorage.has(a,c)){var m=n._activeCollectionStorage.get(a,c);u=n._aggregator.merge(m,u)}n._cumulativeMemoStorage.set(a,l,c),n._activeCollectionStorage.set(a,u,c)})},r.prototype.collect=function(){var e=this._activeCollectionStorage;return this._activeCollectionStorage=new yr,e},r}();var sp=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.")},cv=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},cc=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===ni.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=pk(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=sp(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 yr,i=this._unreportedAccumulations.get(e);if(this._unreportedAccumulations.set(e,[]),i===void 0)return o;try{for(var a=sp(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=cv(a.value,3),c=s[0],l=s[1],u=s[2];if(e.has(c,u)){var d=e.get(c,u),m=n.merge(d,l);o.set(c,m,u)}else o.set(c,l,u);a=i.next()}return o},r.calibrateStartTime=function(e,t,n){var o,i;try{for(var a=sp(e.keys()),s=a.next();!s.done;s=a.next()){var c=cv(s.value,2),l=c[0],u=c[1],d=t.get(l,u);d?.setStartTime(n)}}catch(m){o={error:m}}finally{try{s&&!s.done&&(i=a.return)&&i.call(a)}finally{if(o)throw o.error}}return t},r}();function pk(r){return Array.from(r.entries())}var gk=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)}}(),hk=function(r,e){var t=typeof Symbol=="function"&&r[Symbol.iterator];if(!t)return r;var n=t.call(r),o,i=[],a;try{for(;(e===void 0||e-- >0)&&!(o=n.next()).done;)i.push(o.value)}catch(s){a={error:s}}finally{try{o&&!o.done&&(t=n.return)&&t.call(n)}finally{if(a)throw a.error}}return i},uv=function(r){gk(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 lc(n,s._aggregationCardinalityLimit),s._temporalMetricStorage=new cc(n,i),s}return e.prototype.record=function(t,n){var o=this,i=new yr;Array.from(t.entries()).forEach(function(a){var s=hk(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}(sc);_e();function lp(r,e){var t="";return r.unit!==e.unit&&(t+=" - Unit '"+r.unit+"' does not match '"+e.unit+`'
|
|
24
24
|
`),r.type!==e.type&&(t+=" - Type '"+r.type+"' does not match '"+e.type+`'
|
|
25
25
|
`),r.valueType!==e.valueType&&(t+=" - Value Type '"+r.valueType+"' does not match '"+e.valueType+`'
|
|
26
26
|
`),r.description!==e.description&&(t+=" - Description '"+r.description+"' does not match '"+e.description+`'
|
|
@@ -4136,8 +4136,8 @@ registerAllMomenticListeners();
|
|
|
4136
4136
|
`&&(i=s),r.slice(o,i)}function br(r){let e=typeof r=="string"?r:r.toString();return`[${Zr}="${e}"]`}import{execSync as DF}from"child_process";import{randomUUID as og}from"crypto";import{diff as ig}from"deep-object-diff";import{existsSync as Hc,readFileSync as kF,readdirSync as UF,statSync as eR,writeFileSync as FF}from"fs";import{Jimp as tR}from"jimp";import BF from"js-beautify";import{cloneDeep as fi}from"lodash-es";import zF from"mime";import{platform as HF}from"os";import{basename as rR,extname as GF,join as VF}from"path";import{v4 as jF}from"uuid";import{rmSync as vw}from"fs";import{basename as FU,join as BU}from"path";import{errors as zU}from"playwright-core";import{devices as W0}from"playwright-core";var zA=2,di=8e3;var mi=250,at=500;var HA=5e3,GA=250,Z=3e3,fe=2e3,Q=1e3,Ap=3e4,wp=8e3,VA=10,Rp=.05;var jA=6e4,WA=new Set(["about:blank","chrome-error://chromewebdata/"]);var Cp=["button","image","generic","graphics-symbol","tab","link","menuitem","group"],xp=1e4,Xa=500,Ic=W0["Desktop Chrome"].userAgent,pi=process.env.TWO_CAPTCHA_KEY;import{mkdirSync as $0,rmSync as $A,statSync as q0}from"fs";import*as Ip from"node:fs";import K0 from"nodejs-file-downloader";import{tmpdir as Y0}from"os";import Cn,{basename as X0,dirname as J0}from"path";var Op="file://",Pp=Cn.join(Y0(),"momentic","downloads"),_p=1e4,Z0=50*1024*1024;async function qA(r){let{uri:e}=r;if(e.startsWith(Op))return eU(r);if(e.startsWith("http"))return rU(r);if(oy)return tU(r);throw new C("UserConfigurationError","The source URI for the file upload step must be a valid URL or a previously downloaded file beginning with 'file://'")}function Q0(r,e){let t=Cn.join(Pp,r,e.slice(Op.length)),n=Cn.join(Pp,r),o=t.startsWith(n);if(!Ip.existsSync(t)||!o)throw new C("UserConfigurationError",`The referenced file (${e}) does not exist. Please make sure that it has been downloaded successfully.`);return t}async function eU({uri:r,orgId:e}){let t=Q0(e,r);return{filePath:t,cleanup:()=>{$A(J0(t),{recursive:!0,force:!0})}}}async function tU({uri:r}){let e=Cn.resolve(r);if(!Ip.existsSync(e))throw new C("UserConfigurationError",`The referenced file (${r}) does not exist on disk. Please make sure that it has been downloaded successfully.`);return{filePath:e,cleanup:()=>{}}}async function rU({uri:r,logger:e,orgId:t}){let n=new URL(r);n.search&&(n.search="");let o=X0(n.href),i=Np(o),a=Cn.extname(i);if(ZS.includes(a))throw new Error(`Downloading files with extension ${a} is not allowed.`);let s=Lp(t),c,l;for(let g=1;g<=3;g++){let h=new K0({url:r,fileName:i,directory:s,maxAttempts:1,headers:{"User-Agent":"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/93.0.4577.82 Safari/537.36"},timeout:_p});try{let{downloadStatus:f,filePath:E}=await k(h.download(),{milliseconds:_p,message:`Download timed out after ${_p}ms`});if(f!=="COMPLETE"||!E)throw new Error(`Download ended in non-success status: ${f}`);c=E;break}catch(f){l=f}}if(!c)throw new Error(`Download failed after 3 attempts. Last error: ${l instanceof Error?l.message:l}`);let u=c,m=q0(u).size;if(m>Z0)throw new Error("File size exceeds the maximum limit of 50MB");e.info({fileSizeInBytes:m,filePath:u,fileName:i},"Downloaded file to disk");let p;return{filePath:u,cleanup:()=>{clearTimeout(p),p=setTimeout(()=>$A(s,{recursive:!0,force:!0}),10*60*1e3)}}}function KA(r,e){return`${Op}${r}/${e}`}function Lp(r){let e=Math.random().toString(36).substring(4),t=Cn.join(Pp,r,e);return $0(t,{recursive:!0}),t}function Np(r){let e=Cn.extname(r),t=Cn.basename(r,e);return r=(t.length>100?t.slice(t.length-100):t)+e,r=r.trim().replaceAll(" ","_"),r}async function lr(r,e,t){try{return await r.evaluate((o,{truncateToLength:i})=>window.serializeElementOnlyWithText?.(o,{truncateToLength:i}),{truncateToLength:t},{timeout:Q})}catch(n){e.debug({err:n},"Failed to get HTML from locator for Playwright error translation");return}}var xn=3.1783027;function nU(r){let e=0;for(let t=0;t<r.length;t++){let n=r.charCodeAt(t);!(n>=48&&n<=57)&&!(n>=65&&n<=90)&&!(n>=97&&n<=122)&&e++}return e}function Er(r){return Math.ceil(Dp(r)/xn)}function Dp(r){let e=0;if(typeof r=="string"){let t=r;t=t.replaceAll(`
|
|
4137
4137
|
`,""),t=t.replaceAll(" ","");let n=nU(t);return t.length-n+xn*n}if(typeof r>"u"||r===null)return 0;if(typeof r=="number")return String(r).length;if(Array.isArray(r))return r.forEach(t=>{e+=Dp(t)}),e;if(typeof r=="object"){let t=r;return Object.keys(t).forEach(n=>{e+=String(n).length,n==="image_url"?(t[n]??{}).detail==="high"?e+=1105*xn:e+=85*xn:n==="source"&&typeof t[n]=="object"&&t[n]?.type==="base64"?e+=1600*xn:e+=Dp(t[n])}),e}if(typeof r=="boolean")return r?4:5;throw new Error(`Unsupported type passed to token length calculator '${typeof r}': ${r}`)}var Oc=class{limit;windowMs;userActions;constructor(e,t){this.limit=e,this.windowMs=t,this.userActions=new Map}_cleanup(e,t="DEFAULT_USER"){let n=Date.now(),o=`${t}:${e}`;if(this.userActions.has(o)){let a=this.userActions.get(o)?.filter(s=>n-s<=this.windowMs)??[];a.length>0?this.userActions.set(o,a):this.userActions.delete(o)}}increment(e,t="DEFAULT_USER"){let n=Date.now(),o=`${t}:${e}`;this._cleanup(t,e),this.userActions.has(o)||this.userActions.set(o,[]);let i=this.userActions.get(o);return i.length>=this.limit?!0:(i.push(n),!1)}};async function YA(r,e){let t=r.evaluate(async()=>{let i=window,a={};try{let s=await indexedDB.databases();for(let c of s){if(!c.name)continue;let l=await i.exportIdbToObject?.(c.name,c.version);l&&(a[c.name]=l)}return[a,void 0]}catch(s){return[void 0,s.message]}}),[n,o]=await k(t,{milliseconds:Z});return o&&e.warn({err:o},"Failed to fetch indexedDB data"),n}async function XA(r,e,t){if(e){t.debug("Importing indexedDB data");try{let n=r.evaluate(async o=>{let i=window;for(let[a,s]of Object.entries(o))await i.importObjectToIdb?.(a,s)},e);await k(n,{milliseconds:Z})}catch(n){t.warn({err:n},"Failed to import indexedDB data")}}}async function JA(r,e){try{let t=r.evaluate(async()=>{window.localStorage.clear(),window.sessionStorage.clear(),await indexedDB.databases().then(n=>{n.forEach(o=>{o.name&&indexedDB.deleteDatabase(o.name)})})});await k(t,{milliseconds:Z})}catch(t){e.debug({err:t},"Failed clearing index db data, continuing...")}}async function ZA(r,e,t,n,o){try{await oU(r,e,t,n)}catch(i){o.error({err:i,tabIndex:e},"Error handling new console log")}}async function oU(r,e,t,n){let o=n.text();o.length>Xa&&(o=o.slice(0,Xa)+"...(TRUNCATED)");let i=[];for(let a of n.args())try{let s=await a.jsonValue(),c=JSON.stringify(s);c.length>Xa?i.push(c.slice(0,Xa)+"...(TRUNCATED)"):(typeof s!="object"||Object.keys(s).length>0)&&i.push(s)}catch{}kp(r,t,e,{url:r.url(),location:n.location(),type:n.type(),text:n.text(),args:i})}function kp(r,e,t,n){let o=Date.now(),i=e.logsPerPage;if(i.length<=t||i[t]===void 0){i[t]=[];for(let a=0;a<t;a++)i[a]===void 0&&(i[a]=[])}i[t].length>xp&&(i[t]=i[t].slice(Math.floor(xp/2)),i[t]?.push({url:r.url(),timestamp:o,type:"warning",text:"[MOMENTIC] Truncated console logs due to buffer overflow",tabIndex:t})),i[t].push({...n,tabIndex:t,timestamp:o})}async function cr({fn:r,codePath:e,logObject:t,signal:n,logger:o}){n?.throwIfAborted();let i=Date.now(),a=await Ep({promiseGenerator:r,signal:n,codePath:e,logger:o}),s=Date.now();return t[e]=s-i,a}import iU from"truncate-json";var aU="[redacted due to size]",QA=5e3,sU=5e3,tw=1e3;function rw(r,e,t,n){try{t?.({id:e,startedDateTime:new Date().toISOString(),title:void 0,pageTimings:{}})}catch(o){r.warn({err:o},"Unexpected error in onHarPage callback")}}async function Up(r,e){let t=e.timing(),n=new URL(e.url()),o=[...n.searchParams.entries()].map(([s,c])=>({name:s,value:c})),i={...await ow(e),url:n.toString(),method:e.method(),queryString:o};return{pageref:r,_resourceType:e.resourceType(),startedDateTime:new Date().toISOString(),request:i,timings:aw(t).timings}}async function nw(r,e,t,n){let o={},a=((await t.headerValue("content-type"))?.toLowerCase()??void 0)?.split(";")[0]??void 0;if(n)try{o=await gU({response:t,mimeType:a,sizes:n})}catch{}let s={...await ow(t),status:t.status(),statusText:t.statusText(),content:o,redirectURL:t.headers().location,_mocked:!1};r.response=s,r.response&&n&&(r.response.bodySize=n.responseBodySize,r.response.headersSize=n.responseHeadersSize,r.response.content.size=n.responseBodySize);let c=e.timing();r.startedDateTime=new Date(c.startTime).toISOString();let{timings:l,total:u}=aw(c);r.time=u,r.timings=l}function ew(r){try{return new Date(r).toISOString()}catch{return}}function lU(r){let e={name:"",value:""},t=!0;for(let n of r.split(/; */)){let o=n.indexOf("="),i=o!==-1?n.substring(0,o).trim():n.trim(),a=o!==-1?n.substring(o+1,n.length).trim():"";if(t){t=!1,e.name=Fr(i),e.value=Fr(a);continue}i==="Domain"&&(e.domain=Fr(a)),i==="Expires"&&(e.expires=ew(a)),i==="HttpOnly"&&(e.httpOnly=!0),i==="Max-Age"&&(e.expires=ew(Date.now()+ +a*1e3)),i==="Path"&&(e.path=Fr(a)),i==="Secure"&&(e.secure=!0)}return e}async function ow(r){let e=await r.allHeaders(),t=e.cookie?.split(";").map(lU)??[];return{headers:Object.entries(e).map(([n,o])=>({name:Fr(n),value:Fr(o)})),cookies:t}}async function iw(r,e,t){let n=await r.headerValue("content-type")??"application/octet-stream";if(t&&(e.request.bodySize=t.requestBodySize,e.request.headersSize=t.requestHeadersSize),t&&t.requestBodySize>tw){e.request.postData={mimeType:n,text:"",params:[],_redactedReason:"Request body redacted due to size"};return}let o=r.postData();if(!o)return;let i={mimeType:n,text:Fr(o),params:[]};if(n==="application/x-www-form-urlencoded"){let a=new URLSearchParams(o.toString());for(let[s,c]of a.entries())i.params.push({name:Fr(s),value:c?Fr(c):void 0})}e.request.postData=i}var cU=["image","font","video","audio"],uU=["javascript"],dU=["text"],mU=["json","xml","html"];function pU(r){let[e,t]=r.split("/");return e&&cU.includes(e)||t&&uU.some(n=>t.includes(n))?!1:!!(e&&dU.includes(e)||t&&mU.some(n=>t.includes(n)))}async function gU({response:r,mimeType:e,sizes:t}){let n={mimeType:e,encoding:await r.headerValue("content-encoding")??void 0};return!e||!pU(e)?n._redactedReason="Body redacted because it's not a viewable MIME type":t.responseBodySize>=tw?n._redactedReason="Response body redacted due to size":n.text=Fr(await r.text()),n}function Fr(r){try{let e=JSON.parse(r),{jsonString:t}=iU(r,sU);return t}catch{return r.length>QA?r.slice(0,QA)+aU:r}}function so(r){return r<0?0:r}function aw(r){return{timings:{blocked:so(r.domainLookupStart),dns:so(r.domainLookupEnd-r.domainLookupStart),connect:so(r.connectEnd-r.connectStart),send:so(r.responseStart-r.requestStart),wait:0,receive:so(r.responseEnd-r.responseStart),ssl:so(r.connectEnd-r.secureConnectionStart)},total:so(r.responseEnd)}}function sw(){return async r=>{let{fragment:e,code:t,context:n}=r,{env:o}=n||{},i=Object.getPrototypeOf(async function(){}).constructor;return{result:await Promise.resolve(new i("env",e?`return ${t}`:t)(o))}}}async function rt({root:r,fn:e,arg:t,timeout:n,waitForPageLoad:o,codePath:i}){return await o(),await k(r.evaluate(e,t),{milliseconds:n,message:`Timed out ${i} after ${n}ms. This indicates that either the page is unresponsive or your machine is severely resource constrained.`})}import{errors as hU}from"playwright-core";async function lo({func:r,action:e,logger:t,callbacks:n,retryTimeoutMs:o,targetingResult:i}){let a=Date.now(),s;for(;Date.now()-a<o;)try{return await r(i)}catch(c){if(c instanceof hU.TimeoutError)t.warn({err:c,rootUrl:(await n.state.getRoot()).url()},`Encountered Playwright error while performing ${e}`),s=await fU(c,i.locator,n,t);else throw c}throw s instanceof C?s:new C("ActionFailureError",`Failed to interact with targeted element. Error: ${s.message}`,{errOptions:{cause:s}})}async function fU(r,e,t,n){return r.message.includes("attempt #")?SU(r,e,t,n):yU(r)}async function SU(r,e,t,n){let o=r.message.split(/- retrying \w+ action, attempt #\d+/).filter(c=>c.length>0);if(!o.length)return n.warn({err:r},"Failed to parse Playwright error message for translation, returning raw message"),r;let i=o.length>2?o[o.length-2]:o[0];i=i.replace(/[\u001b\u009b][[()#;?]*(?:[0-9]{1,4}(?:;[0-9]{0,4})*)?[0-9A-ORZcf-nqry=><]/g,"").replaceAll(" - ","").trim().replaceAll(`
|
|
4138
4138
|
`,";").replace(/\s+/g," ");let a="",s=await lr(e,n,150);if(s&&(a=`Target element HTML: ${Nt(s,100,!0)}`),i.includes("element is not enabled"))return new C("ActionFailureError",`The element you attempted to interact with was disabled for the entire timeout duration. Please explicitly wait for the element to be enabled, change the element description to target an interactive element, or turn on the 'disable stability checks' option. ${a}`,{errOptions:{cause:r}});if(i.includes("intercepts pointer events")){let c="",l=i.match(/<.*?data-momentic-id="(\d+)".*?intercepts pointer events/)?.[1];if(l){let u=(await t.state.getRoot()).locator(br(l)),d=await lr(u,n,150);d&&(c=`Covering element HTML: ${Nt(d,100,!0)}`)}return new C("ActionFailureError",`The element you attempted to interact with was covered by another element such as dropdown, popup, or dialog for the entire timeout duration. Please add a step to hide the covering element or turn on the 'disable stability checks' option. ${a}
|
|
4139
|
-
${c}`,{errOptions:{cause:r}})}if(i.includes("element is not visible")){let c="The element you attempted to interact with has no bounding box or is explicitly hidden.";try{let l=await e.boundingBox({timeout:Z});l?l.height===0?c="The element you attempted to interact with has zero height.":l.width===0&&(c="The element you attempted to interact with has zero width."):c="The element you attempted to interact with has no bounding box."}catch{}return new C("ActionFailureError",`${c} Please explicitly wait for the element to be visible or turn on the 'disable stability checks' option. ${a}`,{errOptions:{cause:r}})}return i.includes("element is outside of the viewport")?new C("ActionFailureError",`The element requested was outside of the browser viewport for the entire duration of the action. Please ensure you are not using non-standard zoom settings and the element is visible on the page. ${a}`):r}function yU(r){let e=r.message;if(e.includes("waiting for locator")&&e.includes("data-momentic-id")&&!e.match(/attempting \w+ action/)&&!e.includes("locator.evaluate"))throw new C("ActionFailureError",`Interacting with the element timed out. This is usually caused by the web page itself performing too many CPU-intensive operations or a lack of resources on your machine. Error: ${e}`,{errOptions:{cause:r}});return r}import{execSync as RU}from"child_process";import{existsSync as Za,mkdirSync as Vp,readdirSync as CU,rmSync as mw}from"fs";import{homedir as pw}from"os";import{basename as xU,join as _n,resolve as MU}from"path";import{chromium as gw}from"playwright-core";import{addExtra as _U}from"playwright-extra";import PU from"puppeteer-extra-plugin-recaptcha";function lw(r,e){return async(t,n)=>{try{let o=await n.allHeaders();for(let{key:i,value:a,matcher:s}of r)(!s||s.matches({url:n.url(),method:n.method()}))&&(o[i]=a);await t.fallback({headers:o})}catch(o){e.warn({err:o},"Failed to apply custom headers to request, continuing")}}}import{randomUUID as EU}from"crypto";function cw(r,e){for(let t of Object.values(e))if(t.matcher.matches({url:r.url(),method:r.method()}))return t}async function uw(r){let{route:e,mock:t,entry:n,onHarEntry:o,requestId:i,requestRecorders:a,logger:s}=r,c={url:n.request.url,options:{method:n.request.method,headers:n.request.headers.map(p=>[p.name,p.value]),body:n.request.postData?.text}},l;if(t.fetchOriginalResponse){let p=await e.fetch();l={body:await p.text(),options:{status:p.status(),statusText:p.statusText(),headers:Object.entries(await p.headers())}}}let u=await bU(t,c,l),d={};u.headers.forEach((p,g)=>{d[g]=p});let m={body:await u.text(),contentType:u.headers.get("content-type")||"text/plain",headers:d,status:u.status};await e.fulfill(m);try{n.response={status:m.status,statusText:u.statusText,headers:Object.entries(m.headers).map(([p,g])=>({name:p,value:g})),cookies:[],content:{mimeType:m.contentType,text:m.body},_mocked:!0},o?.(i,n);for(let p of Object.values(a))p.onRequestComplete(i,n)}catch(p){p.message.includes("has been closed")||s.warn({err:p},"Failed to add response to HAR")}}async function bU(r,e,t){try{return await r.generateResponse(e,t)}catch(n){let o=n instanceof Error?n.message:`${n}`;return new Response(o,{status:500,headers:{"Content-Type":"text/plain"}})}}async function Fp(r){try{await TU(r)}catch(e){r.logger.warn({err:e},"Error handling intercepted request, continuing...")}}async function TU(r){let{pageId:e,route:t,request:n,onHarEntry:o,logger:i,requestRecorders:a,mocks:s}=r,c=EU(),l=await Up(e,n);try{o?.(c,l);for(let d of Object.values(a))d.onRequestStart(c,l)}catch(d){i.warn({err:d},"Failed to add request to HAR")}let u=cw(n,s);u?await uw({logger:i,route:t,mock:u,entry:l,onHarEntry:o,requestId:c,requestRecorders:a}):await vU({route:t,request:n,onHarEntry:o,logger:i,requestRecorders:a,entry:l,requestId:c})}async function vU({route:r,request:e,onHarEntry:t,logger:n,requestRecorders:o,entry:i,requestId:a}){await r.continue();try{let s=await e.response(),c;try{await s?.finished()}catch{}try{c=await e.sizes()}catch{}if(i&&await iw(e,i,c),!s||!i)return;await nw(i,e,s,c),t?.(a,i);for(let l of Object.values(o))l.onRequestComplete(a,i)}catch(s){s.message.includes("has been closed")||n.warn({err:s},"Failed to add response to HAR")}}async function AU(r){let e=r.postData();if(e){if((await r.headerValue("content-type"))?.includes("json"))try{return{json:r.postDataJSON()}}catch{return{}}else if((await r.headerValue("content-type"))?.includes("text"))return{text:e}}return{}}async function wU(r){let e=await r.text();if(e){if((await r.headerValue("content-type"))?.includes("json"))try{return{json:await r.json()}}catch{return{}}else if((await r.headerValue("content-type"))?.includes("text"))return{text:e}}return{}}function Lc(r){return{request:{url:r.request.url,method:r.request.method,headers:r.request.headers.reduce((e,t)=>({...e,[t.name]:t.value}),{}),...r.request.postData?r.request.postData.mimeType.includes("json")?{json:JSON.parse(r.request.postData.text)}:{text:r.request.postData.text}:{}},response:r.response?{status:r.response.status,headers:r.response.headers.reduce((e,t)=>({...e,[t.name]:t.value}),{}),...r.response.content?r.response.content.mimeType?.includes("json")&&r.response.content.text?{json:JSON.parse(r.response.content.text)}:{text:r.response.content.text}:{}}:void 0}}async function Bp(r){let e=r.request(),t=r.status(),n=r.headers(),o=await wU(r);return{request:{url:e.url(),method:e.method(),headers:e.headers(),...await AU(e)},response:{status:t,headers:n,...o},status:t,headers:n,...o}}var Mn=class{requestMatcher;constructor(e){this.requestMatcher=e}matches(e){let{url:t,method:n}=e;return this.requestMatcher.method&&this.requestMatcher.method.toLowerCase()!==n.toLowerCase()?!1:xc(t,this.requestMatcher.urlMatcher)}};function Ja(r){let e=new URL(r.request().url());return/^127\./.test(e.hostname)||/^192\.168\./.test(e.hostname)||/^10\./.test(e.hostname)||/^172\.(1[6-9]|2\d|3[0-1])\./.test(e.hostname)||e.hostname==="localhost"?r.abort():r.fallback()}import{homedir as zp,platform as Hp}from"os";import{join as Gp}from"path";function Nc(){let r=[];if(Hp()==="linux"){let e=zp();["chromium","google-chrome","chrome-canary"].forEach(t=>{r.push(Gp(e,".config",t,"Crash Reports"))})}else if(Hp()==="darwin"){let e=zp();["Chromium","Google","Chrome for Testing"].forEach(t=>{r.push(Gp(e,"Library","Application Support",t,"Crashpad"))})}else if(Hp()==="win32"){let e=zp();["Chromium","Google","Google Chrome Canary"].forEach(t=>{r.push(Gp(e,"AppData","Local",t,"User Data","Crashpad","reports"))})}return r}function dw(){return{name:"fs_optout",value:"1",domain:".fullstory.com",path:"/",expires:Date.now()/1e3+365*24*60*60,httpOnly:!1,secure:!0,sameSite:"None"}}var jp=_n(pw(),"momentic","chromium"),hw=_U(gw);hw.use(PU({provider:{id:"2captcha",token:pi},visualFeedback:!0}));var IU=["--enable-crashpad","--crash-on-hang-threads=UI:18,IO:18"],OU=["--no-first-run","--renderer-process-limit=3","--browser-test","--disable-site-isolation-for-policy","--disable-site-isolation-trials","--disable-backgrounding-occluded-windows","--disable-background-timer-throttling","--disable-renderer-backgrounding","--autoplay-policy=user-gesture-required","--disable-add-to-shelf","--disable-desktop-notifications","--use-fake-device-for-media-stream","--use-fake-ui-for-media-stream","--enable-logging=stderr","--log-level=2"],LU=["--disable-3d-apis","--disable-gpu","--disable-software-rasterizer","--disable-accelerated-2d-canvas","--disable-accelerated-mjpeg-decode","--disable-accelerated-video-decode","--disable-accelerated-video-encode","--disable-gl-drawing-for-tests","--disable-webgl","--disable-webgl2","--disable-audio-input","--disable-audio-output"];async function fw({baseUrl:r,logger:e,storage:t,enricher:n,userBrowserSettings:o,contextArgs:i,iconKnowledgeBase:a,callbacks:s,videoOptions:c}){process.env.PW_TEST_SCREENSHOT_NO_FONTS_READY="1";let l;switch(o.browserType){case"Google Chrome":l="chrome";break;case"Chrome for Testing":l=void 0;break;case"Chromium":l="chromium";break;default:l="chromium";break}let u=[...OU];!Pr&&DU()&&u.push("--disable-dev-shm-usage");let d={headless:process.env.MOMENTIC_HEADFUL_BROWSER!=="true",handleSIGTERM:!1,chromiumSandbox:!1,channel:l},m={...i??{},geolocation:i?.geolocation||Vs,locale:i?.locale||$f,timezoneId:i?.timezoneId||qf,colorScheme:i?.colorScheme,httpCredentials:o.basicAuthorization?{username:o.basicAuthorization.username??"",password:o.basicAuthorization.password??""}:void 0,javaScriptEnabled:o.disableJavaScript?!1:void 0,ignoreHTTPSErrors:o.ignoreHttpsErrors??!1,userAgent:o.userAgent??Ic,viewport:i?.viewport??cn,serviceWorkers:"block",storageState:{cookies:[dw()],origins:[]},proxy:o.proxy};o.initialLocalStorage&&(m.storageState.origins=Object.entries(o.initialLocalStorage).map(([b,x])=>({origin:b,localStorage:Object.entries(x).map(([T,v])=>({name:T,value:v}))}))),process.env.MOMENTIC_CHROME_EXTRA_ARGS&&u.push(...process.env.MOMENTIC_CHROME_EXTRA_ARGS.split(","));let p=null,g,h,f={systemDevicePixelRatio:i?.deviceScaleFactor,isNewHeadless:!1};(l==="chrome"||l==="chromium")&&(f.isNewHeadless=!0,d.headless&&u.push("--headless=new")),process.env.BROWSER_MEMORY_MB&&u.push(`--js-flags=--max_old_space_size=${process.env.BROWSER_MEMORY_MB}`);try{let b=Nc();b.forEach(x=>{if(!Za(x))return;["new","pending","completed"].forEach(v=>{let O=_n(x,v);if(!Za(O))return;let w=CU(O);for(let D=0;D<w.length;D++){let j=_n(O,w[D]);mw(j,{force:!0})}})}),b.forEach(x=>{Za(x)||Vp(x,{recursive:!0});let T=_n(x,`write-test-${Date.now()}`);Vp(T,{recursive:!0}),mw(T,{recursive:!0,force:!0})}),u.push(...IU)}catch(b){e.warn({err:b},"Could not create Chrome crash report directory, not enabling crashpad")}o.disableGpu&&u.push(...LU);let E=o.localChromeExtensionPaths?.map(b=>b.startsWith("~")?_n(pw(),b.slice(1)):b);if(E?.length){if(l===void 0)throw new C("UserConfigurationError","Chrome extensions are only supported on Chromium and Google Chrome.");for(let v of E){let O=_n(v,"manifest.json");if(!Za(O))throw new C("UserConfigurationError",`Chrome extension path ${O} does not exist.`)}if(Pr)throw new C("UserConfigurationError","Cannot use persistent browser context on Momentic Cloud");let b=_n(jp,`momentic-session-${Date.now()}`);if(!Za(b))try{Vp(b,{recursive:!0})}catch(v){throw new C("UserConfigurationError",`Failed to create browser cache directory. Please make sure you have sufficient permissions to create the ${jp} folder: ${v}`)}let x=[...u],T=E.map(v=>MU(v)).join(",");x.push(`--disable-extensions-except=${T}`),m?.deviceScaleFactor&&x.push(`--force-device-scale-factor=${m.deviceScaleFactor}`,`--device-scale-factor=${m.deviceScaleFactor}`),m.viewport&&x.push(`--window-size=${m.viewport.width},${m.viewport.height}`),g=await gw.launchPersistentContext(_n(jp,`momentic-session-${Date.now()}`),{...d,...m,ignoreDefaultArgs:["--disable-extensions","--disable-component-extensions-with-background-pages"],args:x,baseURL:r}),e.info({sharedContextOptions:m,sharedBrowserOptions:d,userBrowserSettings:o,chromeArgs:x,properties:f,baseUrl:r},"Browser initialization context args (persistent)"),h=g.pages()[0]}else{p=await hw.launch({...d,args:u});let b={...m,baseURL:r,recordVideo:c?{dir:c.videoOutputPath}:void 0};g=await p.newContext(b),e.info({contextArgs:b,sharedBrowserOptions:d,chromeArgs:u,userBrowserSettings:o,properties:f,baseUrl:r},"Browser initialization context args (standard)"),h=await g.newPage()}if(c){let b=await h.video()?.path();if(b){let x=xU(b);c.onVideoPageChange({videoName:x})}}Pr&&await g.route("**",Ja);try{let b=p?.version();e.info({browserVersion:b},"Got browser version")}catch(b){e.warn({err:b},"Could not get browser version string")}return{browser:p,context:g,page:h,baseUrl:r,logger:e,storage:t,enricher:n,userBrowserSettings:o,viewport:m.viewport||cn,properties:f,clientCallbacks:s,iconKnowledgeBase:a,onVideoPageChange:c?.onVideoPageChange}}function NU(){if(process.platform!=="linux")return null;try{let e=RU("df -k /dev/shm",{encoding:"utf8"}).trim().split(/\r?\n/),n=e[e.length-1]?.trim().split(/\s+/)??[];if(!n||n.length<2)return null;let o=parseInt(n[1],10);return Number.isNaN(o)||o<=0?null:o/1024}catch{return null}}function DU(){let e=process.env.BROWSER_ENABLE_DEV_SHM;if(e==="1")return!1;if(e==="0")return!0;let t=NU();return t==null?!1:t<128}async function Sw(r){try{return await kU(r)}catch(e){r.logger.warn({err:e},"Failed to transform locator for Chakra click, continuing...");return}}async function kU({locator:r,logger:e}){let[t,n]=await r.evaluate(c=>[c.id,c.tagName.toLowerCase()],{timeout:Q}),o=await lr(r,e,500),i=await r.boundingBox({timeout:Q});if(i===null){e.warn({elementDisplayString:o},"Attempting to click on element with no bounding box, not performing Chakra redirection");return}if(i.width>5||i.height>5||n!=="input")return;if(t)try{let c=r.page().locator(`label[for=${JSON.stringify(t)}]`);return await c.waitFor({state:"visible",timeout:Q}),{locator:c,relativePoint:void 0}}catch{}let a=await r.evaluate(c=>{let l=window,u=c.parentElement;if(!u)return{type:"error",error:"Input click target has no parent for redirection"};let d=c.getBoundingClientRect(),m=u.getBoundingClientRect();if(m.width===0||m.height===0)return{type:"error",error:"Parent element has no width or height"};let p={x:Math.min(Math.max(1,d.left-m.left),m.width-1),y:Math.min(Math.max(1,d.top-m.top),m.height-1)},g=l._MOMENTIC_FEATURE_FLAGS?.[Pc],h=c.getAttribute(Zr),f=!g&&h?br(h):l.getMPath?.(c)?.join(" >");return f?{type:"result",selector:f,relativePoint:p,serializedForm:u.outerHTML.slice(0,500)}:{type:"error",error:"Could not generate selector for parent element"}},{timeout:Q});if(a.type==="error")throw new Error(a.error);let s=r.page().locator(a.selector);return await s.waitFor({state:"visible",timeout:Q}),e.info({parentElementResult:a,originalElementDisplayString:o},`Redirected click to parent element with selector: ${a.selector}`),{locator:s,relativePoint:a.relativePoint}}var bw=["date","datetime-local","month","time","week"],yw={date:/^\d{4}-\d{2}-\d{2}$/,"datetime-local":/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}$/,month:/^\d{4}-\d{2}$/,time:/^\d{2}:\d{2}$/,week:/^\d{4}-W\d{2}$/};async function Ew(r){try{await k(UU(r),{milliseconds:Z})}catch(e){r.logger.warn({err:e},"Failed to transform native datetime input, continuing...")}}async function UU({root:r,text:e,options:t,logger:n,callbacks:o}){let i=(await rt({root:r,fn:()=>document.activeElement?.getAttribute("type")??"",timeout:Q,arg:void 0,waitForPageLoad:o.waitForPageLoad,codePath:"transforming native datetime input"})).toLowerCase();if(!yw[i])return;yw[i].test(e)&&n.warn(`Detected datetime input (${e}) in normalized format - this may fail to fill correctly as it is not how the user would input the value`),t.clearContent=!1,n.info("Transforming datetime input to use sequential key presses")}import{z as Bt}from"zod";var Tw=Bt.object({doubleClick:Bt.boolean().optional(),rightClick:Bt.boolean().optional(),force:Bt.boolean().optional(),waitForDownload:Bt.boolean().optional(),delayMs:Bt.number().optional(),downloadTimeoutMs:Bt.number().optional(),relativePosition:Bt.object({x:Bt.number(),y:Bt.number()}).optional()}),eye=Bt.object({repeat:Bt.number().optional(),convertMeta:Bt.boolean().optional().describe("misleading name due to backcompat. converts keyshortcuts + meta/control to platform-specific combos. defaults to true"),delayMs:Bt.number().optional()});async function Dc({locator:r,callbacks:e,logger:t,timeoutMs:n=Q}){try{await Wp(e,n);let o=r.evaluate(i=>{let a=window;a.momenticIsEligible=d=>{let p=window.getComputedStyle(d,null).getPropertyValue("display");if(p==="none"||p==="contents")return!1;let g=d.getBoundingClientRect();return!(!g.height||!g.width)},a.removeHighlightTimers=a.removeHighlightTimers||[],a.removeHighlightFunctions=a.removeHighlightFunctions||{};let s=0;for(;!a.momenticIsEligible(i)&&s<3;){if(!i.parentElement)throw new Error("No eligible non-empty parent found for highlighting");i=i.parentElement,s++}let c=i.style.getPropertyValue("outline"),l=i.style.getPropertyPriority("outline");i.style.setProperty("outline","5px dashed rgb(255, 0, 153)","important");let u=`momentic${Math.floor(Math.random()*1e7)}`;a[u]=()=>{i.style.removeProperty("outline"),i.style.setProperty("outline",c,l),i.getAttribute("style")||i.removeAttribute("style")},a.removeHighlightTimers.push(setTimeout(()=>{a[u](),a.removeHighlightFunctions?.[u]&&delete a.removeHighlightFunctions[u]},5e3)),a.removeHighlightFunctions[u]=a[u]},void 0,{timeout:n});return await k(o,{milliseconds:n}),!0}catch(o){return t.debug({err:o},"Failed to add node highlight, a page navigation likely occurred. This is non-fatal for tests."),!1}}async function Wp(r,e=Q){let t=await r.state.getRoot();await rt({root:t,fn:()=>{let o=window,i=o.removeHighlightTimers||[];for(;i.length;){let a=i.pop();clearTimeout(a)}Object.values(o.removeHighlightFunctions??{}).forEach(a=>{a()})},timeout:e,arg:void 0,waitForPageLoad:r.waitForPageLoad,codePath:"removing element highlights"})}async function $p(r){let e=!!r.browserCallbacks.state.userBrowserSettings.visualActions;return lo({action:"clicking element",targetingResult:r.targetingResult,logger:r.logger,retryTimeoutMs:r.retryTimeoutMs,callbacks:r.browserCallbacks,func:async t=>Aw({...r,targetingResult:t,useVisualClick:e})})}async function HU(r,e){let{redirectionAttempts:t=0}=e;if(t>=2)throw r;try{return await GU(r,e)}catch(n){throw e.redirectionAttempts===0?(e.logger.error({redirectionAttemptError:n,originalError:r},"Error handling click error, rethrowing original error"),r):n}}async function GU(r,e){let{logger:t,redirectionAttempts:n=0}=e,o=e.targetingResult.locator;if(r.message.includes("label")&&r.message.includes("for=")&&r.message.includes("intercepts pointer events")){let i=await o.getAttribute("id",{timeout:Q});if(!i)throw r;let a=o.page().locator(`[for=${JSON.stringify(i)}]`);return await a.waitFor({state:"visible",timeout:Q}),t.warn({err:r},"Attempting locator redirection due to input being covered by label"),Aw({...e,targetingResult:{locator:a},redirectionAttempts:n+1})}else throw t.error({err:r},"Click error does not match any known recoverable patterns, rethrowing"),r}async function VU(r){let{logger:e,targetingResult:t,position:n,options:o}=r,i=Tw.safeParse(o),a=Date.now(),{clickX:s,clickY:c,reason:l}=await $U({targetingResult:t,position:n,options:o,logger:e});return e.info({position:n,options:i.success?i.data:void 0,clickLocation:{clickX:s,clickY:c,reason:l},duration:Date.now()-a},"Visual click"),{x:s,y:c}}async function jU(r){let{actionSource:e,targetingResult:t,options:n,logger:o}=r,i=r.targetingResult.locator,a=n?.relativePosition??r.position;if(e==="click"&&!a){let l=await Sw({locator:i,logger:o});l&&(i=l.locator,a=l.relativePoint??a)}let s=n?.force||t.hints?.force||!1;s&&!a&&t.hints?.relativeXYToLocator&&(a=t.hints.relativeXYToLocator);let c=i.toString();try{o.info({locator:c},"Locator click"),n?.doubleClick?await i.dblclick({button:n.rightClick?"right":"left",timeout:Z,position:a,delay:n?.delayMs??25,force:s}):await i.click({button:n?.rightClick?"right":"left",timeout:Z,position:a,delay:n?.delayMs??25,force:s})}catch(l){let u=l;if(KU(u))o.warn({err:u},"Click action timed out while waiting for navigation after completion, continuing...");else return o.error({err:u},"Error clicking on locator, attempting to recover..."),HU(u,{...r,targetingResult:{...i,locator:i}})}return{locatorSource:c}}async function Aw(r){let{options:e,logger:t,browserCallbacks:n,controllerCallbacks:o,useVisualClick:i,targetingResult:a}=r,s;e?.waitForDownload&&(s=(async()=>{let u=e.downloadTimeoutMs??Ap;try{return await a.locator.page().waitForEvent("download",{timeout:u})}catch(d){return d instanceof zU.TimeoutError?new C("ActionFailureError",`Download did not complete in ${u}ms`):new C("ActionFailureError",`Download failed: ${d.message}`)}})());try{await Dc({locator:a.locator,callbacks:n,logger:t,timeoutMs:Q})}catch(u){t.warn({err:u},"Error highlighting locator in click, continuing...")}let c,l;if(i?c=await VU(r):l=(await jU(r)).locatorSource,e?.waitForDownload)if(s){if(!o?.createIsolatedFolder)throw new C("InternalWebAgentError","Cannot wait for download without a callback to create an isolated folder");t.info("Waiting for download to start and complete");let u=await k(s,{milliseconds:e.downloadTimeoutMs??Ap});if(u instanceof Error)throw u;return{downloadedFile:await qU(u,o.createIsolatedFolder,t),coordinates:c,locatorSource:l}}else throw new Error("No download promise or error but the step requested to wait for a download");return{coordinates:c,locatorSource:l}}async function WU(r,e){let t=await r.locator.boundingBox({timeout:Z});if(!t){let i=await lr(r.locator,e,500);throw new C("ActionFailureError",`${Yu}${i?`: ${i}`:""}`)}if(r.hints?.relativeXYToLocator){let i=t.x+r.hints.relativeXYToLocator.x,a=t.y+r.hints.relativeXYToLocator.y;return[{x:i,y:a},"targeting hint"]}let n=t.x+t.width/2,o=t.y+t.height/2;return[{x:n,y:o},"halfway point"]}async function $U({options:r,targetingResult:e,position:t,logger:n}){let o,i,a;if(r?.relativePosition){let u=await e.locator.boundingBox({timeout:Z}),d=r.relativePosition.x,m=r.relativePosition.y;u?.width&&(d=Math.max(0,Math.min(r.relativePosition.x,u.width))),u?.height&&(m=Math.max(0,Math.min(r.relativePosition.y,u.height))),o=(u?.x??0)+d,i=(u?.y??0)+m,a="relative position from user"}else if(t){let u=await e.locator.boundingBox({timeout:Z});o=(u?.x??0)+t.x,i=(u?.y??0)+t.y,a="predefined position"}else{let[u,d]=await WU(e,n);o=u.x,i=u.y,a=d}let s=e.locator.page(),c=r?.rightClick?"right":"left",l=r?.delayMs??25;return r?.doubleClick?await s.mouse.dblclick(o,i,{button:c,delay:l}):await s.mouse.click(o,i,{button:c,delay:l}),{clickX:o,clickY:i,reason:a}}async function qU(r,e,t){t.info("Download detected, saving file to disk");let n=await r.path(),o=Np(r.suggestedFilename()),i=e();await r.saveAs(BU(i,o)),vw(n,{force:!0}),setTimeout(()=>{vw(i,{recursive:!0,force:!0})},5*60*1e3);let a=KA(FU(i),o);return t.info({uri:a,downloadFolder:i},"Saved download to isolated folder"),a}function KU(r){return r.message.includes("locator.click: Timeout")&&r.message.includes("click action done")}import{platform as YU}from"os";var XU={goToNextWord:{win32:"Control+ArrowRight",darwin:"Alt+ArrowRight",linux:"Control+ArrowRight"},goToPreviousWord:{win32:"Control+ArrowLeft",darwin:"Alt+ArrowLeft",linux:"Control+ArrowLeft"},selectNextWord:{win32:"Control+Shift+ArrowRight",darwin:"Alt+Shift+ArrowRight",linux:"Control+Shift+ArrowRight"},selectPreviousWord:{win32:"Control+Shift+ArrowLeft",darwin:"Alt+Shift+ArrowLeft",linux:"Control+Shift+ArrowLeft"},selectToStartOfLine:{win32:"Shift+Home",darwin:"Meta+Shift+LeftArrow",linux:"Shift+Home"},selectToEndOfLine:{win32:"Shift+End",darwin:"Meta+Shift+RightArrow",linux:"Shift+End"},deleteNextWord:{win32:"Control+Delete",darwin:"Alt+Fn+Delete",linux:"Control+Delete"},deletePreviousWord:{win32:"Control+Backspace",darwin:"Alt+Delete",linux:"Control+Backspace"}};function JU(){let r=YU();return r==="win32"?"win32":r==="darwin"?"darwin":"linux"}function ww(r){return JSON.stringify(r.split("+").sort())}function kc(r,e){let t=JU(),n=ww(r);for(let o of Object.values(XU))if(Object.values(o).some(i=>ww(i)===n))return o[t];return process.platform==="darwin"&&!e?r=r.replaceAll("Control","Meta"):r=r.replaceAll("Meta","Control"),r}async function qp({frame:r,page:e,deltaX:t,directionX:n,deltaY:o,directionY:i,signal:a,callbacks:s,logger:c}){if(!t&&!o)return;let l=n==="left"?-1:1,u=i==="up"?-1:1;if(r)await rt({root:r,fn:([d,m,p,g])=>window.scrollTo(window.scrollX+(d??window.innerWidth)*p,window.scrollY+(m??window.innerHeight)*g),arg:[t,o,l,u],waitForPageLoad:s.waitForPageLoad,timeout:fe,codePath:"scrolling page"});else{let d=e.viewportSize()||cn,m=await rt({root:e,fn:()=>document.body.scrollHeight,arg:void 0,waitForPageLoad:s.waitForPageLoad,timeout:fe,codePath:"computing page height"}),[p,g,h]=await rt({root:e,fn:()=>{let f=document.activeElement;if(!f)return[void 0,void 0,void 0];let E=f.getBoundingClientRect();return[f.scrollTop,E.x,E.y]},arg:void 0,waitForPageLoad:s.waitForPageLoad,timeout:fe,codePath:"computing active element position"});await e.mouse.wheel((t??d.width)*l,(o??d.height)*u);try{let f=Date.now();for(;Date.now()-f<fe;){a?.throwIfAborted();let E=await k(e.evaluate(()=>document.body.scrollHeight),{milliseconds:Q}),[b,x,T]=await k(e.evaluate(()=>{let v=document.activeElement;if(!v)return[void 0,void 0,void 0];let O=v.getBoundingClientRect();return[v.scrollTop,O.x,O.y]}),{milliseconds:Q});if(E===m&&b===p&&x===g&&T===h)break;m=E,p=b,g=x,h=T,await X(at)}}catch(f){c.warn({err:f},"Failed to wait for scroll to complete, continuing...")}}}async function Kp(r,e){let t,n;for(let o=0;o<4;o++)try{return t=r.pages(),await Promise.all(t.map(async i=>{let a="";try{a=e?.getTitles?await i.title():""}catch{a="Unknown page"}return{title:a,url:i.url()}}))}catch(i){n=i,await X(at)}throw new Error(`Failed to get tab titles after all retries: ${n?.message}`)}import{randomUUID as iF}from"crypto";import{cloneDeep as Jp}from"lodash-es";function Pn(r,e){let t=r.findIndex(n=>n===e);if(!(t===-1||!r[t+1]))return r[t+1]}import{createHash as ZU}from"crypto";var QU="v1";function Yp(r,e){if(r.tagName.toLowerCase()==="svg"&&!tF(r))try{let t=Rw(r,e),n=eF(JSON.stringify(t));return{version:QU,json:t,hash:n}}catch{return}}function eF(r){return ZU("md5").update(r).digest("hex")}function Rw(r,e){let t=r.tagName.toLowerCase(),n=rF(r);if(t==="image"&&n["xlink:href"])throw new Error("Image tags within SVGs are not supported");let o={type:t,props:n,children:[]};for(let i of r.childrenBackendIds){let a=e.backendIdToNode[i];if(a&&a.nodeType===1){let s=Rw(a,e);s&&o.children.push(s)}}return o}function tF(r){let e=r.computedStyles.display,t=r.computedStyles.visibility,n=r.computedStyles.opacity;return e==="none"||t==="hidden"||n==="0"}function rF(r){let e={},t=r.attributes;for(let n of Object.keys(t))sr.visualAttributesForSvgSerialization.includes(n)&&(e[n]=t[n]);return t.id&&r.tagName.toLowerCase()!=="svg"&&(e.id=t.id),e}var co={r:147,g:196,b:125,a:.55},xw={showRulers:!1,showStyles:!1,showExtensionLines:!1,contrastAlgorithm:"aa",contentColor:co,paddingColor:co,borderColor:co,marginColor:co,eventTargetColor:co,shapeColor:co,shapeMarginColor:co,showInfo:!0,showAccessibilityInfo:!0};function Mw({snapshot:r,devicePixelRatio:e,computedStylesToFetch:t,logger:n}){let o=r.strings,i=r.documents,a={},s={},c={roots:[],backendIdToNode:a,frameIndexToIframeNode:s};return i.forEach((l,u)=>{let d=nF({allDocuments:i,stringConstants:o,computedStylesToFetch:t,devicePixelRatio:e,frameIndex:u,backendIdToNode:a,frameIndexToIframeNode:s,logger:n});c.roots.push(d)}),c}function nF({allDocuments:r,stringConstants:e,computedStylesToFetch:t,devicePixelRatio:n,frameIndex:o,frameIndexToIframeNode:i,backendIdToNode:a,logger:s}){let c=r[o],l=c.layout,u={};l.nodeIndex.forEach((w,D)=>{u[w]=D});let d=l.styles,m=l.bounds??[],p=c.nodes,g=p.contentDocumentIndex??{index:[],value:[]},h=p.backendNodeId??[],f=p.attributes??[],E=p.parentIndex??[],b=p.nodeName??[],x=p.nodeType??[],T=p.pseudoType??{index:[],value:[]},v=p.inputChecked??{index:[]},O=e[c.frameId];for(let w=0;w<h.length;w++){let D=h[w],j=x[w],ie=f[w]??[],ee=E[w]!==void 0&&E[w]>=0?E[w]:void 0,he=ee!==void 0?h[ee]:void 0,st=he!==void 0?a[he]:void 0,W=T.index.indexOf(w),B=W!==-1?e[T.value[W]]:void 0,ae=u[w],ce;ae?ce=m[ae]??[]:ce=[];let Ze=b[w]!==void 0?e[b[w]]?.toLowerCase():void 0;if(!Ze){s.warn({backendNodeId:D,frameId:O,frameIndex:o,nodeBounds:ce},"DOM node has no tag name");continue}let Ce={backendNodeId:D,psuedoType:B,nodeType:j,frameIndex:o,parentFrameId:O,ownedFrameId:void 0,bounds:{x:ce[0]??null,y:ce[1]??null,width:ce[2]??null,height:ce[3]??null},computedStyles:{},attributes:{},parentBackendNodeId:he??null,tagName:Ze,parent:st??void 0,childrenBackendIds:[],momenticIgnored:void 0,mPathSelector:void 0};st&&st.childrenBackendIds.push(D);let zt=g.index.indexOf(w);if(zt!==-1){let Ie=g.value[zt];i[Ie]=Ce;let qe=r[Ie]?.frameId;Ce.ownedFrameId=qe!==void 0?e[qe]:void 0}for(let Ie of Object.keys(Ce.bounds)){let qe=Ie;Ce.bounds[qe]!==null&&(Ce.bounds[qe]/=n)}let bt=ae!==void 0?d[ae]??[]:[];for(let Ie=0;Ie<bt.length&&!(Ie>=t.length);Ie++){let qe=bt[Ie];if(qe===void 0||isNaN(qe))continue;let mr=e[qe];if(mr===void 0)continue;let xt=t[Ie];Ce.computedStyles[xt]=mr}for(let Ie=0;Ie<ie.length;Ie+=2){let qe=ie[Ie],mr=ie[Ie+1];if(!qe||!mr)continue;let xt=e[qe],Vr=e[mr];!xt||!Vr||(Ce.attributes[xt]=Vr)}v.index.includes(w)&&(Ce.attributes.checked="true"),a[Ce.backendNodeId]=Ce}return a[h[0]]}function Xp(r,e){if(r.mPathSelector)return r.mPathSelector;let t=r.parent,n;if(!t)n=r.tagName;else if(r.tagName==="body")n="body";else{let i=t.childrenBackendIds.filter(c=>e.backendIdToNode[c]?.nodeType===1&&!e.backendIdToNode[c]?.psuedoType).indexOf(r.backendNodeId),a=` > ${r.tagName}:nth-child(${i+1})`;n=`${Xp(t,e)}${a}`}return r.mPathSelector=n,n}function Cw(r,e){return r.parentBackendNodeId!==null?e.backendIdToNode[r.parentBackendNodeId]:r.frameIndex===0?void 0:e.frameIndexToIframeNode[r.frameIndex]}var oF=["html","#document","#document-fragment"];function _w({node:r,domGraph:e}){let t=[],n=r,o=Cw(r,e);if(!o)return[r.tagName];let i=()=>{if(n=o,o=Cw(o,e),!o&&n.frameIndex!==0)throw new Error("No parent node but not in main frame")},a=0;for(;o&&a<1e6;){if(a++,oF.includes(n.tagName)){i();continue}if(n.tagName==="body")t.push("body");else{let c=!1,l=1;for(let u=0;u<o.childrenBackendIds.length;u++){let d=o.childrenBackendIds[u],m=e.backendIdToNode[d];if(d===n.backendNodeId){t.push(`${n.tagName}:nth-child(${l})`),c=!0;break}else m?.nodeType===1&&!m.psuedoType&&l++}if(!c)throw new Error(`Could not find child (${n.tagName}) in parent's children list (${o.tagName})`)}i()}return t.reverse()}function Pw(r,e){let t=r.locator("html"),n=[];for(let o=0;o<e.length;o++){let i=e[o];if(n.push(i),i.startsWith("iframe")){let a=n.join(" > ");n=[],o<e.length-1?t=t.frameLocator(a):t=t.locator(a)}}if(n.length&&(t=t.locator(n.join(" > "))),"owner"in t)throw new Error("Final locator from mpath is a frame locator");return t}async function Iw(r,e){await r.send({method:"DOM.getDocument",params:{depth:0},timeout:fe});let t=await r.send({method:"DOM.requestNode",params:{objectId:e},timeout:fe}),o=(await r.send({method:"DOM.getAttributes",params:{nodeId:t.nodeId},timeout:fe})).attributes,i=Pn(o,Zr);if(!i)throw new Error(`Could not find attribute ${Zr} for object ${e}`);return i}var aF=["focusable","keyshortcuts","controls","live","relevant","orientation"],sF=["selected","readonly","modal","required","invalid"],lF=["id","name","role","content"],Ow=["absolute","fixed","sticky"],cF=["i"],uF=["path"],dF=["statictext","textbox","checkbox","combobox","iframe","rootwebarea","table","caption","columnheader","rowheader","gridcell","grid","row","rowgroup","cell","image","graphics-symbol","graphics-document","graphics-object","svgroot","button","link","list","listitem","tablist","tabpanel","tab","searchbox","menu","menubar","form","dialog","alertdialog","banner","navigation","main","menuitem","menuitemcheckbox","menuitemradio","option","radio","progressbar","switch","tree","treeitem","separator"],Dw=["ariaHiddenElement","ariaHiddenSubtree","hiddenByChildTree","inertElement","inertSubtree","notRendered","notVisible"],kw=["activeAriaModalDialog","activeFullscreenElement","activeModalDialog"],mF=["menulistpopup","statictext","inlinetextbox"],pF=80,Lw=100,Uw=50,eg=["StaticText","ListMarker","RootWebArea","LineBreak","emphasis","::before","::after"],gF=["cite"],hF={LabelText:["label"],listitem:["li"],image:["img","svg"],link:["a"],RootWebArea:["#document"],paragraph:["p"],LineBreak:["br"],separator:["hr"],"graphics-symbol":["svg","rect"],gridcell:["td","th"],SvgRoot:["svg"],navigation:["nav"],cell:["td","th"],row:["tr"],list:["ul"],heading:["h1","h2","h3","h4","h5","h6"]},fF={name:!0,value:!0,title:!0,alt:!0,placeholder:!0,checked:!0,selected:!0,contenteditable:!0},Nw={indentLevel:0},Zp=class r{id;role;name;nameSources;tagName;content;properties;internalProperties;ignoredReasons;dataMomenticId;importantProperties;pathFromRoot;mPathSelector;parent;children;parentFrame;domNode;backendNodeId;ignoredByCDP;flagNotActionableNodes;constructor(e){if(this.id=e.id,this.role=e.role,this.name=e.name,this.nameSources=e.nameSources,this.content=e.content,this.properties={},this.pathFromRoot=e.pathFromRoot,this.children=e.children,this.backendNodeId=e.backendNodeID,this.ignoredByCDP=e.ignoredByCDP,this.internalProperties=e.internalProperties??{},this.parentFrame=e.parentFrame,this.ignoredReasons=e.ignoredReasons,this.importantProperties=e.importantProperties,this.flagNotActionableNodes=e.flagNotActionableNodes,e.properties&&e.properties.forEach(t=>{t.name==="keyshortcuts"?this.dataMomenticId=parseInt(t.value.value):this.properties[t.name]=t.value.value}),e.domNode){this.domNode=e.domNode,this.tagName=e.domNode.tagName||void 0;let t=e.domNode.attributes.id;this.name=this.name||e.domNode.attributes.name||(t&&t.length<Uw?t:""),this.role=this.role||(e.domNode.attributes.role??""),EF(this.properties,e.domNode,e.importantProperties)}vF(this)}getSerializedFormWithContext(){return this.serialize({noId:!0,maxLevel:1,neighbors:1})}getNodeOnlySerializedForm(){return this.serialize({noId:!0,noChildren:!0,noContent:!0})}getLogForm(){return JSON.stringify({id:this.id,name:this.name??"",role:this.role??"",backendNodeId:this.backendNodeId})}isInteresting(e){if(this.domNode&&uF.includes(this.domNode.tagName)||this.domNode?.computedStyles.display==="contents"||this.ignoredReasons.some(n=>kw.includes(n)))return!1;if(e){if(Object.keys(this.domNode?.attributes??{}).some(o=>Gw(o,e)))return!0;let n=this.domNode?.attributes.class?.split(" ");if(n&&n.length>0&&n.some(o=>Vw(o,e))||e.styles?.some(o=>{let i=o.split(":");if(i.length!==2)return!1;let a=i[0]?.trim(),s=i[1]?.trim();if(a===void 0||s===void 0)return!1;let c=this.domNode?.computedStyles[a];return c!==void 0&&(c===s||s==="*")}))return!0}if(this.domNode&&cF.includes(this.domNode.tagName)||dF.includes(this.role.toLowerCase())||this.role.toLowerCase()==="inlinetextbox"&&this.tagName||!this.properties.hidden&&(this.properties.focusable||this.properties.settable)||sr.alwaysInterestingTruthyPropertyNames.some(n=>!!this.properties[n]))return!0;let t=this.properties.class;return typeof t=="string"&&t.split(" ").some(n=>Hw(n))?!0:this.children.every(n=>n.role==="StaticText")&&this.internalProperties?.inCodeMirrorEditor?!1:this.children.some(n=>n.role==="StaticText")||this.children.length>1&&this.children.some(n=>n.tagName==="input")?!0:this.domNode&&(this.domNode.bounds.x===null||this.domNode.bounds.y===null||!this.domNode.bounds.width||!this.domNode.bounds.height)?!1:!!this.name.trim()||!!this.content||Object.keys(this.properties).some(n=>n.startsWith("data"))}shouldSerializeBounds(){let e=this.domNode?.computedStyles.position;return!!(e&&(e==="absolute"||e==="fixed"||e==="sticky"))}isNotActionable(){return!!(this.domNode?.computedStyles.display==="contents"||this.domNode&&(this.domNode.bounds.x===null||this.domNode.bounds.y===null||!this.domNode.bounds.width||!this.domNode.bounds.height))}serialize(e=Nw){let t=Object.assign({},Nw,e),{indentLevel:n,noChildren:o,noProperties:i,noId:a,noContent:s,condensedMode:c}=t,l=Jp(this.properties),u=" ".repeat(n),d=this.role||"",m=this.tagName??"unknown",p=this.name;d==="heading"&&p==="heading"&&(p=""),this.nameSources?.find(v=>!v.superseded&&v.type==="contents")&&this.children.length>0&&(p="");let h=this.nameSources?.find(v=>!v.superseded);if(h&&!h.nativeSource&&h.type==="relatedElement"){let v=h.attributeValue?.relatedNodes??[];v.length===1&&v[0].text&&v[0].text===p&&(p="")}let f=eg.includes(this.role)||gF.includes(this.tagName||"");if(this.role==="StaticText"||this.role==="ListMarker")return`${u}${p}
|
|
4140
|
-
`;let E=`${u}<${m}`;!a&&!f&&(E+=` id="${this.id}"`);let b=s??!1;if((l.multiline||l.contenteditable)&&this.children.length>0&&(b=!0),d&&d!=="generic"&&d!==m&&!(hF[d]??[]).includes(m)&&(E+=` role=${JSON.stringify(d)}`),p&&(E+=` name=${JSON.stringify(p)}`),this.content&&!b&&(E+=` content=${JSON.stringify(this.content)}`),this.flagNotActionableNodes&&this.tagName!=="#document"&&this.
|
|
4139
|
+
${c}`,{errOptions:{cause:r}})}if(i.includes("element is not visible")){let c="The element you attempted to interact with has no bounding box or is explicitly hidden.";try{let l=await e.boundingBox({timeout:Z});l?l.height===0?c="The element you attempted to interact with has zero height.":l.width===0&&(c="The element you attempted to interact with has zero width."):c="The element you attempted to interact with has no bounding box."}catch{}return new C("ActionFailureError",`${c} Please explicitly wait for the element to be visible or turn on the 'disable stability checks' option. ${a}`,{errOptions:{cause:r}})}return i.includes("element is outside of the viewport")?new C("ActionFailureError",`The element requested was outside of the browser viewport for the entire duration of the action. Please ensure you are not using non-standard zoom settings and the element is visible on the page. ${a}`):r}function yU(r){let e=r.message;if(e.includes("waiting for locator")&&e.includes("data-momentic-id")&&!e.match(/attempting \w+ action/)&&!e.includes("locator.evaluate"))throw new C("ActionFailureError",`Interacting with the element timed out. This is usually caused by the web page itself performing too many CPU-intensive operations or a lack of resources on your machine. Error: ${e}`,{errOptions:{cause:r}});return r}import{execSync as RU}from"child_process";import{existsSync as Za,mkdirSync as Vp,readdirSync as CU,rmSync as mw}from"fs";import{homedir as pw}from"os";import{basename as xU,join as _n,resolve as MU}from"path";import{chromium as gw}from"playwright-core";import{addExtra as _U}from"playwright-extra";import PU from"puppeteer-extra-plugin-recaptcha";function lw(r,e){return async(t,n)=>{try{let o=await n.allHeaders();for(let{key:i,value:a,matcher:s}of r)(!s||s.matches({url:n.url(),method:n.method()}))&&(o[i]=a);await t.fallback({headers:o})}catch(o){e.warn({err:o},"Failed to apply custom headers to request, continuing")}}}import{randomUUID as EU}from"crypto";function cw(r,e){for(let t of Object.values(e))if(t.matcher.matches({url:r.url(),method:r.method()}))return t}async function uw(r){let{route:e,mock:t,entry:n,onHarEntry:o,requestId:i,requestRecorders:a,logger:s}=r,c={url:n.request.url,options:{method:n.request.method,headers:n.request.headers.map(p=>[p.name,p.value]),body:n.request.postData?.text}},l;if(t.fetchOriginalResponse){let p=await e.fetch();l={body:await p.text(),options:{status:p.status(),statusText:p.statusText(),headers:Object.entries(await p.headers())}}}let u=await bU(t,c,l),d={};u.headers.forEach((p,g)=>{d[g]=p});let m={body:await u.text(),contentType:u.headers.get("content-type")||"text/plain",headers:d,status:u.status};await e.fulfill(m);try{n.response={status:m.status,statusText:u.statusText,headers:Object.entries(m.headers).map(([p,g])=>({name:p,value:g})),cookies:[],content:{mimeType:m.contentType,text:m.body},_mocked:!0},o?.(i,n);for(let p of Object.values(a))p.onRequestComplete(i,n)}catch(p){p.message.includes("has been closed")||s.warn({err:p},"Failed to add response to HAR")}}async function bU(r,e,t){try{return await r.generateResponse(e,t)}catch(n){let o=n instanceof Error?n.message:`${n}`;return new Response(o,{status:500,headers:{"Content-Type":"text/plain"}})}}async function Fp(r){try{await TU(r)}catch(e){r.logger.warn({err:e},"Error handling intercepted request, continuing...")}}async function TU(r){let{pageId:e,route:t,request:n,onHarEntry:o,logger:i,requestRecorders:a,mocks:s}=r,c=EU(),l=await Up(e,n);try{o?.(c,l);for(let d of Object.values(a))d.onRequestStart(c,l)}catch(d){i.warn({err:d},"Failed to add request to HAR")}let u=cw(n,s);u?await uw({logger:i,route:t,mock:u,entry:l,onHarEntry:o,requestId:c,requestRecorders:a}):await vU({route:t,request:n,onHarEntry:o,logger:i,requestRecorders:a,entry:l,requestId:c})}async function vU({route:r,request:e,onHarEntry:t,logger:n,requestRecorders:o,entry:i,requestId:a}){await r.continue();try{let s=await e.response(),c;try{await s?.finished()}catch{}try{c=await e.sizes()}catch{}if(i&&await iw(e,i,c),!s||!i)return;await nw(i,e,s,c),t?.(a,i);for(let l of Object.values(o))l.onRequestComplete(a,i)}catch(s){s.message.includes("has been closed")||n.warn({err:s},"Failed to add response to HAR")}}async function AU(r){let e=r.postData();if(e){if((await r.headerValue("content-type"))?.includes("json"))try{return{json:r.postDataJSON()}}catch{return{}}else if((await r.headerValue("content-type"))?.includes("text"))return{text:e}}return{}}async function wU(r){let e=await r.text();if(e){if((await r.headerValue("content-type"))?.includes("json"))try{return{json:await r.json()}}catch{return{}}else if((await r.headerValue("content-type"))?.includes("text"))return{text:e}}return{}}function Lc(r){return{request:{url:r.request.url,method:r.request.method,headers:r.request.headers.reduce((e,t)=>({...e,[t.name]:t.value}),{}),...r.request.postData?r.request.postData.mimeType.includes("json")?{json:JSON.parse(r.request.postData.text)}:{text:r.request.postData.text}:{}},response:r.response?{status:r.response.status,headers:r.response.headers.reduce((e,t)=>({...e,[t.name]:t.value}),{}),...r.response.content?r.response.content.mimeType?.includes("json")&&r.response.content.text?{json:JSON.parse(r.response.content.text)}:{text:r.response.content.text}:{}}:void 0}}async function Bp(r){let e=r.request(),t=r.status(),n=r.headers(),o=await wU(r);return{request:{url:e.url(),method:e.method(),headers:e.headers(),...await AU(e)},response:{status:t,headers:n,...o},status:t,headers:n,...o}}var Mn=class{requestMatcher;constructor(e){this.requestMatcher=e}matches(e){let{url:t,method:n}=e;return this.requestMatcher.method&&this.requestMatcher.method.toLowerCase()!==n.toLowerCase()?!1:xc(t,this.requestMatcher.urlMatcher)}};function Ja(r){let e=new URL(r.request().url());return/^127\./.test(e.hostname)||/^192\.168\./.test(e.hostname)||/^10\./.test(e.hostname)||/^172\.(1[6-9]|2\d|3[0-1])\./.test(e.hostname)||e.hostname==="localhost"?r.abort():r.fallback()}import{homedir as zp,platform as Hp}from"os";import{join as Gp}from"path";function Nc(){let r=[];if(Hp()==="linux"){let e=zp();["chromium","google-chrome","chrome-canary"].forEach(t=>{r.push(Gp(e,".config",t,"Crash Reports"))})}else if(Hp()==="darwin"){let e=zp();["Chromium","Google","Chrome for Testing"].forEach(t=>{r.push(Gp(e,"Library","Application Support",t,"Crashpad"))})}else if(Hp()==="win32"){let e=zp();["Chromium","Google","Google Chrome Canary"].forEach(t=>{r.push(Gp(e,"AppData","Local",t,"User Data","Crashpad","reports"))})}return r}function dw(){return{name:"fs_optout",value:"1",domain:".fullstory.com",path:"/",expires:Date.now()/1e3+365*24*60*60,httpOnly:!1,secure:!0,sameSite:"None"}}var jp=_n(pw(),"momentic","chromium"),hw=_U(gw);hw.use(PU({provider:{id:"2captcha",token:pi},visualFeedback:!0}));var IU=["--enable-crashpad","--crash-on-hang-threads=UI:18,IO:18"],OU=["--no-first-run","--renderer-process-limit=3","--browser-test","--disable-site-isolation-for-policy","--disable-site-isolation-trials","--disable-backgrounding-occluded-windows","--disable-background-timer-throttling","--disable-renderer-backgrounding","--autoplay-policy=user-gesture-required","--disable-add-to-shelf","--disable-desktop-notifications","--use-fake-device-for-media-stream","--use-fake-ui-for-media-stream","--enable-logging=stderr","--log-level=2"],LU=["--disable-3d-apis","--disable-gpu","--disable-software-rasterizer","--disable-accelerated-2d-canvas","--disable-accelerated-mjpeg-decode","--disable-accelerated-video-decode","--disable-accelerated-video-encode","--disable-gl-drawing-for-tests","--disable-webgl","--disable-webgl2","--disable-audio-input","--disable-audio-output"];async function fw({baseUrl:r,logger:e,storage:t,enricher:n,userBrowserSettings:o,contextArgs:i,iconKnowledgeBase:a,callbacks:s,videoOptions:c}){process.env.PW_TEST_SCREENSHOT_NO_FONTS_READY="1";let l;switch(o.browserType){case"Google Chrome":l="chrome";break;case"Chrome for Testing":l=void 0;break;case"Chromium":l="chromium";break;default:l="chromium";break}let u=[...OU];!Pr&&DU()&&u.push("--disable-dev-shm-usage");let d={headless:process.env.MOMENTIC_HEADFUL_BROWSER!=="true",handleSIGTERM:!1,chromiumSandbox:!1,channel:l},m={...i??{},geolocation:i?.geolocation||Vs,locale:i?.locale||$f,timezoneId:i?.timezoneId||qf,colorScheme:i?.colorScheme,httpCredentials:o.basicAuthorization?{username:o.basicAuthorization.username??"",password:o.basicAuthorization.password??""}:void 0,javaScriptEnabled:o.disableJavaScript?!1:void 0,ignoreHTTPSErrors:o.ignoreHttpsErrors??!1,userAgent:o.userAgent??Ic,viewport:i?.viewport??cn,serviceWorkers:"block",storageState:{cookies:[dw()],origins:[]},proxy:o.proxy};o.initialLocalStorage&&(m.storageState.origins=Object.entries(o.initialLocalStorage).map(([b,x])=>({origin:b,localStorage:Object.entries(x).map(([T,v])=>({name:T,value:v}))}))),process.env.MOMENTIC_CHROME_EXTRA_ARGS&&u.push(...process.env.MOMENTIC_CHROME_EXTRA_ARGS.split(","));let p=null,g,h,f={systemDevicePixelRatio:i?.deviceScaleFactor,isNewHeadless:!1};(l==="chrome"||l==="chromium")&&(f.isNewHeadless=!0,d.headless&&u.push("--headless=new")),process.env.BROWSER_MEMORY_MB&&u.push(`--js-flags=--max_old_space_size=${process.env.BROWSER_MEMORY_MB}`);try{let b=Nc();b.forEach(x=>{if(!Za(x))return;["new","pending","completed"].forEach(v=>{let O=_n(x,v);if(!Za(O))return;let w=CU(O);for(let D=0;D<w.length;D++){let j=_n(O,w[D]);mw(j,{force:!0})}})}),b.forEach(x=>{Za(x)||Vp(x,{recursive:!0});let T=_n(x,`write-test-${Date.now()}`);Vp(T,{recursive:!0}),mw(T,{recursive:!0,force:!0})}),u.push(...IU)}catch(b){e.warn({err:b},"Could not create Chrome crash report directory, not enabling crashpad")}o.disableGpu&&u.push(...LU);let E=o.localChromeExtensionPaths?.map(b=>b.startsWith("~")?_n(pw(),b.slice(1)):b);if(E?.length){if(l===void 0)throw new C("UserConfigurationError","Chrome extensions are only supported on Chromium and Google Chrome.");for(let v of E){let O=_n(v,"manifest.json");if(!Za(O))throw new C("UserConfigurationError",`Chrome extension path ${O} does not exist.`)}if(Pr)throw new C("UserConfigurationError","Cannot use persistent browser context on Momentic Cloud");let b=_n(jp,`momentic-session-${Date.now()}`);if(!Za(b))try{Vp(b,{recursive:!0})}catch(v){throw new C("UserConfigurationError",`Failed to create browser cache directory. Please make sure you have sufficient permissions to create the ${jp} folder: ${v}`)}let x=[...u],T=E.map(v=>MU(v)).join(",");x.push(`--disable-extensions-except=${T}`),m?.deviceScaleFactor&&x.push(`--force-device-scale-factor=${m.deviceScaleFactor}`,`--device-scale-factor=${m.deviceScaleFactor}`),m.viewport&&x.push(`--window-size=${m.viewport.width},${m.viewport.height}`),g=await gw.launchPersistentContext(_n(jp,`momentic-session-${Date.now()}`),{...d,...m,ignoreDefaultArgs:["--disable-extensions","--disable-component-extensions-with-background-pages"],args:x,baseURL:r}),e.info({sharedContextOptions:m,sharedBrowserOptions:d,userBrowserSettings:o,chromeArgs:x,properties:f,baseUrl:r},"Browser initialization context args (persistent)"),h=g.pages()[0]}else{p=await hw.launch({...d,args:u});let b={...m,baseURL:r,recordVideo:c?{dir:c.videoOutputPath}:void 0};g=await p.newContext(b),e.info({contextArgs:b,sharedBrowserOptions:d,chromeArgs:u,userBrowserSettings:o,properties:f,baseUrl:r},"Browser initialization context args (standard)"),h=await g.newPage()}if(c){let b=await h.video()?.path();if(b){let x=xU(b);c.onVideoPageChange({videoName:x})}}Pr&&await g.route("**",Ja);try{let b=p?.version();e.info({browserVersion:b},"Got browser version")}catch(b){e.warn({err:b},"Could not get browser version string")}return{browser:p,context:g,page:h,baseUrl:r,logger:e,storage:t,enricher:n,userBrowserSettings:o,viewport:m.viewport||cn,properties:f,clientCallbacks:s,iconKnowledgeBase:a,onVideoPageChange:c?.onVideoPageChange}}function NU(){if(process.platform!=="linux")return null;try{let e=RU("df -k /dev/shm",{encoding:"utf8"}).trim().split(/\r?\n/),n=e[e.length-1]?.trim().split(/\s+/)??[];if(!n||n.length<2)return null;let o=parseInt(n[1],10);return Number.isNaN(o)||o<=0?null:o/1024}catch{return null}}function DU(){let e=process.env.BROWSER_ENABLE_DEV_SHM;if(e==="1")return!1;if(e==="0")return!0;let t=NU();return t==null?!1:t<128}async function Sw(r){try{return await kU(r)}catch(e){r.logger.warn({err:e},"Failed to transform locator for Chakra click, continuing...");return}}async function kU({locator:r,logger:e}){let[t,n]=await r.evaluate(c=>[c.id,c.tagName.toLowerCase()],{timeout:Q}),o=await lr(r,e,500),i=await r.boundingBox({timeout:Q});if(i===null){e.warn({elementDisplayString:o},"Attempting to click on element with no bounding box, not performing Chakra redirection");return}if(i.width>5||i.height>5||n!=="input")return;if(t)try{let c=r.page().locator(`label[for=${JSON.stringify(t)}]`);return await c.waitFor({state:"visible",timeout:Q}),{locator:c,relativePoint:void 0}}catch{}let a=await r.evaluate(c=>{let l=window,u=c.parentElement;if(!u)return{type:"error",error:"Input click target has no parent for redirection"};let d=c.getBoundingClientRect(),m=u.getBoundingClientRect();if(m.width===0||m.height===0)return{type:"error",error:"Parent element has no width or height"};let p={x:Math.min(Math.max(1,d.left-m.left),m.width-1),y:Math.min(Math.max(1,d.top-m.top),m.height-1)},g=l._MOMENTIC_FEATURE_FLAGS?.[Pc],h=c.getAttribute(Zr),f=!g&&h?br(h):l.getMPath?.(c)?.join(" >");return f?{type:"result",selector:f,relativePoint:p,serializedForm:u.outerHTML.slice(0,500)}:{type:"error",error:"Could not generate selector for parent element"}},{timeout:Q});if(a.type==="error")throw new Error(a.error);let s=r.page().locator(a.selector);return await s.waitFor({state:"visible",timeout:Q}),e.info({parentElementResult:a,originalElementDisplayString:o},`Redirected click to parent element with selector: ${a.selector}`),{locator:s,relativePoint:a.relativePoint}}var bw=["date","datetime-local","month","time","week"],yw={date:/^\d{4}-\d{2}-\d{2}$/,"datetime-local":/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}$/,month:/^\d{4}-\d{2}$/,time:/^\d{2}:\d{2}$/,week:/^\d{4}-W\d{2}$/};async function Ew(r){try{await k(UU(r),{milliseconds:Z})}catch(e){r.logger.warn({err:e},"Failed to transform native datetime input, continuing...")}}async function UU({root:r,text:e,options:t,logger:n,callbacks:o}){let i=(await rt({root:r,fn:()=>document.activeElement?.getAttribute("type")??"",timeout:Q,arg:void 0,waitForPageLoad:o.waitForPageLoad,codePath:"transforming native datetime input"})).toLowerCase();if(!yw[i])return;yw[i].test(e)&&n.warn(`Detected datetime input (${e}) in normalized format - this may fail to fill correctly as it is not how the user would input the value`),t.clearContent=!1,n.info("Transforming datetime input to use sequential key presses")}import{z as Bt}from"zod";var Tw=Bt.object({doubleClick:Bt.boolean().optional(),rightClick:Bt.boolean().optional(),force:Bt.boolean().optional(),waitForDownload:Bt.boolean().optional(),delayMs:Bt.number().optional(),downloadTimeoutMs:Bt.number().optional(),relativePosition:Bt.object({x:Bt.number(),y:Bt.number()}).optional()}),eye=Bt.object({repeat:Bt.number().optional(),convertMeta:Bt.boolean().optional().describe("misleading name due to backcompat. converts keyshortcuts + meta/control to platform-specific combos. defaults to true"),delayMs:Bt.number().optional()});async function Dc({locator:r,callbacks:e,logger:t,timeoutMs:n=Q}){try{await Wp(e,n);let o=r.evaluate(i=>{let a=window;a.momenticIsEligible=d=>{let p=window.getComputedStyle(d,null).getPropertyValue("display");if(p==="none"||p==="contents")return!1;let g=d.getBoundingClientRect();return!(!g.height||!g.width)},a.removeHighlightTimers=a.removeHighlightTimers||[],a.removeHighlightFunctions=a.removeHighlightFunctions||{};let s=0;for(;!a.momenticIsEligible(i)&&s<3;){if(!i.parentElement)throw new Error("No eligible non-empty parent found for highlighting");i=i.parentElement,s++}let c=i.style.getPropertyValue("outline"),l=i.style.getPropertyPriority("outline");i.style.setProperty("outline","5px dashed rgb(255, 0, 153)","important");let u=`momentic${Math.floor(Math.random()*1e7)}`;a[u]=()=>{i.style.removeProperty("outline"),i.style.setProperty("outline",c,l),i.getAttribute("style")||i.removeAttribute("style")},a.removeHighlightTimers.push(setTimeout(()=>{a[u](),a.removeHighlightFunctions?.[u]&&delete a.removeHighlightFunctions[u]},5e3)),a.removeHighlightFunctions[u]=a[u]},void 0,{timeout:n});return await k(o,{milliseconds:n}),!0}catch(o){return t.debug({err:o},"Failed to add node highlight, a page navigation likely occurred. This is non-fatal for tests."),!1}}async function Wp(r,e=Q){let t=await r.state.getRoot();await rt({root:t,fn:()=>{let o=window,i=o.removeHighlightTimers||[];for(;i.length;){let a=i.pop();clearTimeout(a)}Object.values(o.removeHighlightFunctions??{}).forEach(a=>{a()})},timeout:e,arg:void 0,waitForPageLoad:r.waitForPageLoad,codePath:"removing element highlights"})}async function $p(r){let e=!!r.browserCallbacks.state.userBrowserSettings.visualActions;return lo({action:"clicking element",targetingResult:r.targetingResult,logger:r.logger,retryTimeoutMs:r.retryTimeoutMs,callbacks:r.browserCallbacks,func:async t=>Aw({...r,targetingResult:t,useVisualClick:e})})}async function HU(r,e){let{redirectionAttempts:t=0}=e;if(t>=2)throw r;try{return await GU(r,e)}catch(n){throw e.redirectionAttempts===0?(e.logger.error({redirectionAttemptError:n,originalError:r},"Error handling click error, rethrowing original error"),r):n}}async function GU(r,e){let{logger:t,redirectionAttempts:n=0}=e,o=e.targetingResult.locator;if(r.message.includes("label")&&r.message.includes("for=")&&r.message.includes("intercepts pointer events")){let i=await o.getAttribute("id",{timeout:Q});if(!i)throw r;let a=o.page().locator(`[for=${JSON.stringify(i)}]`);return await a.waitFor({state:"visible",timeout:Q}),t.warn({err:r},"Attempting locator redirection due to input being covered by label"),Aw({...e,targetingResult:{locator:a},redirectionAttempts:n+1})}else throw t.error({err:r},"Click error does not match any known recoverable patterns, rethrowing"),r}async function VU(r){let{logger:e,targetingResult:t,position:n,options:o}=r,i=Tw.safeParse(o),a=Date.now(),{clickX:s,clickY:c,reason:l}=await $U({targetingResult:t,position:n,options:o,logger:e});return e.info({position:n,options:i.success?i.data:void 0,clickLocation:{clickX:s,clickY:c,reason:l},duration:Date.now()-a},"Visual click"),{x:s,y:c}}async function jU(r){let{actionSource:e,targetingResult:t,options:n,logger:o}=r,i=r.targetingResult.locator,a=n?.relativePosition??r.position;if(e==="click"&&!a){let l=await Sw({locator:i,logger:o});l&&(i=l.locator,a=l.relativePoint??a)}let s=n?.force||t.hints?.force||!1;s&&!a&&t.hints?.relativeXYToLocator&&(a=t.hints.relativeXYToLocator);let c=i.toString();try{o.info({locator:c},"Locator click"),n?.doubleClick?await i.dblclick({button:n.rightClick?"right":"left",timeout:Z,position:a,delay:n?.delayMs??25,force:s}):await i.click({button:n?.rightClick?"right":"left",timeout:Z,position:a,delay:n?.delayMs??25,force:s})}catch(l){let u=l;if(KU(u))o.warn({err:u},"Click action timed out while waiting for navigation after completion, continuing...");else return o.error({err:u},"Error clicking on locator, attempting to recover..."),HU(u,{...r,targetingResult:{...i,locator:i}})}return{locatorSource:c}}async function Aw(r){let{options:e,logger:t,browserCallbacks:n,controllerCallbacks:o,useVisualClick:i,targetingResult:a}=r,s;e?.waitForDownload&&(s=(async()=>{let u=e.downloadTimeoutMs??Ap;try{return await a.locator.page().waitForEvent("download",{timeout:u})}catch(d){return d instanceof zU.TimeoutError?new C("ActionFailureError",`Download did not complete in ${u}ms`):new C("ActionFailureError",`Download failed: ${d.message}`)}})());try{await Dc({locator:a.locator,callbacks:n,logger:t,timeoutMs:Q})}catch(u){t.warn({err:u},"Error highlighting locator in click, continuing...")}let c,l;if(i?c=await VU(r):l=(await jU(r)).locatorSource,e?.waitForDownload)if(s){if(!o?.createIsolatedFolder)throw new C("InternalWebAgentError","Cannot wait for download without a callback to create an isolated folder");t.info("Waiting for download to start and complete");let u=await k(s,{milliseconds:e.downloadTimeoutMs??Ap});if(u instanceof Error)throw u;return{downloadedFile:await qU(u,o.createIsolatedFolder,t),coordinates:c,locatorSource:l}}else throw new Error("No download promise or error but the step requested to wait for a download");return{coordinates:c,locatorSource:l}}async function WU(r,e){let t=await r.locator.boundingBox({timeout:Z});if(!t){let i=await lr(r.locator,e,500);throw new C("ActionFailureError",`${Yu}${i?`: ${i}`:""}`)}if(r.hints?.relativeXYToLocator){let i=t.x+r.hints.relativeXYToLocator.x,a=t.y+r.hints.relativeXYToLocator.y;return[{x:i,y:a},"targeting hint"]}let n=t.x+t.width/2,o=t.y+t.height/2;return[{x:n,y:o},"halfway point"]}async function $U({options:r,targetingResult:e,position:t,logger:n}){let o,i,a;if(r?.relativePosition){let u=await e.locator.boundingBox({timeout:Z}),d=r.relativePosition.x,m=r.relativePosition.y;u?.width&&(d=Math.max(0,Math.min(r.relativePosition.x,u.width))),u?.height&&(m=Math.max(0,Math.min(r.relativePosition.y,u.height))),o=(u?.x??0)+d,i=(u?.y??0)+m,a="relative position from user"}else if(t){let u=await e.locator.boundingBox({timeout:Z});o=(u?.x??0)+t.x,i=(u?.y??0)+t.y,a="predefined position"}else{let[u,d]=await WU(e,n);o=u.x,i=u.y,a=d}let s=e.locator.page(),c=r?.rightClick?"right":"left",l=r?.delayMs??25;return r?.doubleClick?await s.mouse.dblclick(o,i,{button:c,delay:l}):await s.mouse.click(o,i,{button:c,delay:l}),{clickX:o,clickY:i,reason:a}}async function qU(r,e,t){t.info("Download detected, saving file to disk");let n=await r.path(),o=Np(r.suggestedFilename()),i=e();await r.saveAs(BU(i,o)),vw(n,{force:!0}),setTimeout(()=>{vw(i,{recursive:!0,force:!0})},5*60*1e3);let a=KA(FU(i),o);return t.info({uri:a,downloadFolder:i},"Saved download to isolated folder"),a}function KU(r){return r.message.includes("locator.click: Timeout")&&r.message.includes("click action done")}import{platform as YU}from"os";var XU={goToNextWord:{win32:"Control+ArrowRight",darwin:"Alt+ArrowRight",linux:"Control+ArrowRight"},goToPreviousWord:{win32:"Control+ArrowLeft",darwin:"Alt+ArrowLeft",linux:"Control+ArrowLeft"},selectNextWord:{win32:"Control+Shift+ArrowRight",darwin:"Alt+Shift+ArrowRight",linux:"Control+Shift+ArrowRight"},selectPreviousWord:{win32:"Control+Shift+ArrowLeft",darwin:"Alt+Shift+ArrowLeft",linux:"Control+Shift+ArrowLeft"},selectToStartOfLine:{win32:"Shift+Home",darwin:"Meta+Shift+LeftArrow",linux:"Shift+Home"},selectToEndOfLine:{win32:"Shift+End",darwin:"Meta+Shift+RightArrow",linux:"Shift+End"},deleteNextWord:{win32:"Control+Delete",darwin:"Alt+Fn+Delete",linux:"Control+Delete"},deletePreviousWord:{win32:"Control+Backspace",darwin:"Alt+Delete",linux:"Control+Backspace"}};function JU(){let r=YU();return r==="win32"?"win32":r==="darwin"?"darwin":"linux"}function ww(r){return JSON.stringify(r.split("+").sort())}function kc(r,e){let t=JU(),n=ww(r);for(let o of Object.values(XU))if(Object.values(o).some(i=>ww(i)===n))return o[t];return process.platform==="darwin"&&!e?r=r.replaceAll("Control","Meta"):r=r.replaceAll("Meta","Control"),r}async function qp({frame:r,page:e,deltaX:t,directionX:n,deltaY:o,directionY:i,signal:a,callbacks:s,logger:c}){if(!t&&!o)return;let l=n==="left"?-1:1,u=i==="up"?-1:1;if(r)await rt({root:r,fn:([d,m,p,g])=>window.scrollTo(window.scrollX+(d??window.innerWidth)*p,window.scrollY+(m??window.innerHeight)*g),arg:[t,o,l,u],waitForPageLoad:s.waitForPageLoad,timeout:fe,codePath:"scrolling page"});else{let d=e.viewportSize()||cn,m=await rt({root:e,fn:()=>document.body.scrollHeight,arg:void 0,waitForPageLoad:s.waitForPageLoad,timeout:fe,codePath:"computing page height"}),[p,g,h]=await rt({root:e,fn:()=>{let f=document.activeElement;if(!f)return[void 0,void 0,void 0];let E=f.getBoundingClientRect();return[f.scrollTop,E.x,E.y]},arg:void 0,waitForPageLoad:s.waitForPageLoad,timeout:fe,codePath:"computing active element position"});await e.mouse.wheel((t??d.width)*l,(o??d.height)*u);try{let f=Date.now();for(;Date.now()-f<fe;){a?.throwIfAborted();let E=await k(e.evaluate(()=>document.body.scrollHeight),{milliseconds:Q}),[b,x,T]=await k(e.evaluate(()=>{let v=document.activeElement;if(!v)return[void 0,void 0,void 0];let O=v.getBoundingClientRect();return[v.scrollTop,O.x,O.y]}),{milliseconds:Q});if(E===m&&b===p&&x===g&&T===h)break;m=E,p=b,g=x,h=T,await X(at)}}catch(f){c.warn({err:f},"Failed to wait for scroll to complete, continuing...")}}}async function Kp(r,e){let t,n;for(let o=0;o<4;o++)try{return t=r.pages(),await Promise.all(t.map(async i=>{let a="";try{a=e?.getTitles?await i.title():""}catch{a="Unknown page"}return{title:a,url:i.url()}}))}catch(i){n=i,await X(at)}throw new Error(`Failed to get tab titles after all retries: ${n?.message}`)}import{randomUUID as iF}from"crypto";import{cloneDeep as Jp}from"lodash-es";function Pn(r,e){let t=r.findIndex(n=>n===e);if(!(t===-1||!r[t+1]))return r[t+1]}import{createHash as ZU}from"crypto";var QU="v1";function Yp(r,e){if(r.tagName.toLowerCase()==="svg"&&!tF(r))try{let t=Rw(r,e),n=eF(JSON.stringify(t));return{version:QU,json:t,hash:n}}catch{return}}function eF(r){return ZU("md5").update(r).digest("hex")}function Rw(r,e){let t=r.tagName.toLowerCase(),n=rF(r);if(t==="image"&&n["xlink:href"])throw new Error("Image tags within SVGs are not supported");let o={type:t,props:n,children:[]};for(let i of r.childrenBackendIds){let a=e.backendIdToNode[i];if(a&&a.nodeType===1){let s=Rw(a,e);s&&o.children.push(s)}}return o}function tF(r){let e=r.computedStyles.display,t=r.computedStyles.visibility,n=r.computedStyles.opacity;return e==="none"||t==="hidden"||n==="0"}function rF(r){let e={},t=r.attributes;for(let n of Object.keys(t))sr.visualAttributesForSvgSerialization.includes(n)&&(e[n]=t[n]);return t.id&&r.tagName.toLowerCase()!=="svg"&&(e.id=t.id),e}var co={r:147,g:196,b:125,a:.55},xw={showRulers:!1,showStyles:!1,showExtensionLines:!1,contrastAlgorithm:"aa",contentColor:co,paddingColor:co,borderColor:co,marginColor:co,eventTargetColor:co,shapeColor:co,shapeMarginColor:co,showInfo:!0,showAccessibilityInfo:!0};function Mw({snapshot:r,devicePixelRatio:e,computedStylesToFetch:t,logger:n}){let o=r.strings,i=r.documents,a={},s={},c={roots:[],backendIdToNode:a,frameIndexToIframeNode:s};return i.forEach((l,u)=>{let d=nF({allDocuments:i,stringConstants:o,computedStylesToFetch:t,devicePixelRatio:e,frameIndex:u,backendIdToNode:a,frameIndexToIframeNode:s,logger:n});c.roots.push(d)}),c}function nF({allDocuments:r,stringConstants:e,computedStylesToFetch:t,devicePixelRatio:n,frameIndex:o,frameIndexToIframeNode:i,backendIdToNode:a,logger:s}){let c=r[o],l=c.layout,u={};l.nodeIndex.forEach((w,D)=>{u[w]=D});let d=l.styles,m=l.bounds??[],p=c.nodes,g=p.contentDocumentIndex??{index:[],value:[]},h=p.backendNodeId??[],f=p.attributes??[],E=p.parentIndex??[],b=p.nodeName??[],x=p.nodeType??[],T=p.pseudoType??{index:[],value:[]},v=p.inputChecked??{index:[]},O=e[c.frameId];for(let w=0;w<h.length;w++){let D=h[w],j=x[w],ie=f[w]??[],ee=E[w]!==void 0&&E[w]>=0?E[w]:void 0,he=ee!==void 0?h[ee]:void 0,st=he!==void 0?a[he]:void 0,W=T.index.indexOf(w),B=W!==-1?e[T.value[W]]:void 0,ae=u[w],ce;ae?ce=m[ae]??[]:ce=[];let Ze=b[w]!==void 0?e[b[w]]?.toLowerCase():void 0;if(!Ze){s.warn({backendNodeId:D,frameId:O,frameIndex:o,nodeBounds:ce},"DOM node has no tag name");continue}let Ce={backendNodeId:D,psuedoType:B,nodeType:j,frameIndex:o,parentFrameId:O,ownedFrameId:void 0,bounds:{x:ce[0]??null,y:ce[1]??null,width:ce[2]??null,height:ce[3]??null},computedStyles:{},attributes:{},parentBackendNodeId:he??null,tagName:Ze,parent:st??void 0,childrenBackendIds:[],momenticIgnored:void 0,mPathSelector:void 0};st&&st.childrenBackendIds.push(D);let zt=g.index.indexOf(w);if(zt!==-1){let Ie=g.value[zt];i[Ie]=Ce;let qe=r[Ie]?.frameId;Ce.ownedFrameId=qe!==void 0?e[qe]:void 0}for(let Ie of Object.keys(Ce.bounds)){let qe=Ie;Ce.bounds[qe]!==null&&(Ce.bounds[qe]/=n)}let bt=ae!==void 0?d[ae]??[]:[];for(let Ie=0;Ie<bt.length&&!(Ie>=t.length);Ie++){let qe=bt[Ie];if(qe===void 0||isNaN(qe))continue;let mr=e[qe];if(mr===void 0)continue;let xt=t[Ie];Ce.computedStyles[xt]=mr}for(let Ie=0;Ie<ie.length;Ie+=2){let qe=ie[Ie],mr=ie[Ie+1];if(!qe||!mr)continue;let xt=e[qe],Vr=e[mr];!xt||!Vr||(Ce.attributes[xt]=Vr)}v.index.includes(w)&&(Ce.attributes.checked="true"),a[Ce.backendNodeId]=Ce}return a[h[0]]}function Xp(r,e){if(r.mPathSelector)return r.mPathSelector;let t=r.parent,n;if(!t)n=r.tagName;else if(r.tagName==="body")n="body";else{let i=t.childrenBackendIds.filter(c=>e.backendIdToNode[c]?.nodeType===1&&!e.backendIdToNode[c]?.psuedoType).indexOf(r.backendNodeId),a=` > ${r.tagName}:nth-child(${i+1})`;n=`${Xp(t,e)}${a}`}return r.mPathSelector=n,n}function Cw(r,e){return r.parentBackendNodeId!==null?e.backendIdToNode[r.parentBackendNodeId]:r.frameIndex===0?void 0:e.frameIndexToIframeNode[r.frameIndex]}var oF=["html","#document","#document-fragment"];function _w({node:r,domGraph:e}){let t=[],n=r,o=Cw(r,e);if(!o)return[r.tagName];let i=()=>{if(n=o,o=Cw(o,e),!o&&n.frameIndex!==0)throw new Error("No parent node but not in main frame")},a=0;for(;o&&a<1e6;){if(a++,oF.includes(n.tagName)){i();continue}if(n.tagName==="body")t.push("body");else{let c=!1,l=1;for(let u=0;u<o.childrenBackendIds.length;u++){let d=o.childrenBackendIds[u],m=e.backendIdToNode[d];if(d===n.backendNodeId){t.push(`${n.tagName}:nth-child(${l})`),c=!0;break}else m?.nodeType===1&&!m.psuedoType&&l++}if(!c)throw new Error(`Could not find child (${n.tagName}) in parent's children list (${o.tagName})`)}i()}return t.reverse()}function Pw(r,e){let t=r.locator("html"),n=[];for(let o=0;o<e.length;o++){let i=e[o];if(n.push(i),i.startsWith("iframe")){let a=n.join(" > ");n=[],o<e.length-1?t=t.frameLocator(a):t=t.locator(a)}}if(n.length&&(t=t.locator(n.join(" > "))),"owner"in t)throw new Error("Final locator from mpath is a frame locator");return t}async function Iw(r,e){await r.send({method:"DOM.getDocument",params:{depth:0},timeout:fe});let t=await r.send({method:"DOM.requestNode",params:{objectId:e},timeout:fe}),o=(await r.send({method:"DOM.getAttributes",params:{nodeId:t.nodeId},timeout:fe})).attributes,i=Pn(o,Zr);if(!i)throw new Error(`Could not find attribute ${Zr} for object ${e}`);return i}var aF=["focusable","keyshortcuts","controls","live","relevant","orientation"],sF=["selected","readonly","modal","required","invalid"],lF=["id","name","role","content"],Ow=["absolute","fixed","sticky"],cF=["i","label"],uF=["path"],dF=["statictext","textbox","checkbox","combobox","iframe","rootwebarea","table","caption","columnheader","rowheader","gridcell","grid","row","rowgroup","cell","image","graphics-symbol","graphics-document","graphics-object","svgroot","button","link","list","listitem","tablist","tabpanel","tab","searchbox","menu","menubar","form","dialog","alertdialog","banner","navigation","main","menuitem","menuitemcheckbox","menuitemradio","option","radio","progressbar","switch","tree","treeitem","separator","LabelText"],Dw=["ariaHiddenElement","ariaHiddenSubtree","hiddenByChildTree","inertElement","inertSubtree","notRendered","notVisible"],kw=["activeAriaModalDialog","activeFullscreenElement","activeModalDialog"],mF=["menulistpopup","statictext","inlinetextbox"],pF=80,Lw=100,Uw=50,eg=["StaticText","ListMarker","RootWebArea","LineBreak","emphasis","::before","::after"],gF=["cite"],hF={LabelText:["label"],listitem:["li"],image:["img","svg"],link:["a"],RootWebArea:["#document"],paragraph:["p"],LineBreak:["br"],separator:["hr"],"graphics-symbol":["svg","rect"],gridcell:["td","th"],SvgRoot:["svg"],navigation:["nav"],cell:["td","th"],row:["tr"],list:["ul"],heading:["h1","h2","h3","h4","h5","h6"]},fF={name:!0,value:!0,title:!0,alt:!0,placeholder:!0,checked:!0,selected:!0,contenteditable:!0},Nw={indentLevel:0},Zp=class r{id;role;name;nameSources;tagName;content;properties;internalProperties;ignoredReasons;dataMomenticId;importantProperties;pathFromRoot;mPathSelector;parent;children;parentFrame;domNode;backendNodeId;ignoredByCDP;flagNotActionableNodes;constructor(e){if(this.id=e.id,this.role=e.role,this.name=e.name,this.nameSources=e.nameSources,this.content=e.content,this.properties={},this.pathFromRoot=e.pathFromRoot,this.children=e.children,this.backendNodeId=e.backendNodeID,this.ignoredByCDP=e.ignoredByCDP,this.internalProperties=e.internalProperties??{},this.parentFrame=e.parentFrame,this.ignoredReasons=e.ignoredReasons,this.importantProperties=e.importantProperties,this.flagNotActionableNodes=e.flagNotActionableNodes,e.properties&&e.properties.forEach(t=>{t.name==="keyshortcuts"?this.dataMomenticId=parseInt(t.value.value):this.properties[t.name]=t.value.value}),e.domNode){this.domNode=e.domNode,this.tagName=e.domNode.tagName||void 0;let t=e.domNode.attributes.id;this.name=this.name||e.domNode.attributes.name||(t&&t.length<Uw?t:""),this.role=this.role||(e.domNode.attributes.role??""),EF(this.properties,e.domNode,e.importantProperties)}vF(this)}getSerializedFormWithContext(){return this.serialize({noId:!0,maxLevel:1,neighbors:1})}getNodeOnlySerializedForm(){return this.serialize({noId:!0,noChildren:!0,noContent:!0})}getLogForm(){return JSON.stringify({id:this.id,name:this.name??"",role:this.role??"",backendNodeId:this.backendNodeId})}isInteresting(e){if(this.domNode&&uF.includes(this.domNode.tagName)||this.ignoredReasons.some(n=>kw.includes(n)))return!1;if(e){if(Object.keys(this.domNode?.attributes??{}).some(o=>Gw(o,e)))return!0;let n=this.domNode?.attributes.class?.split(" ");if(n&&n.length>0&&n.some(o=>Vw(o,e))||e.styles?.some(o=>{let i=o.split(":");if(i.length!==2)return!1;let a=i[0]?.trim(),s=i[1]?.trim();if(a===void 0||s===void 0)return!1;let c=this.domNode?.computedStyles[a];return c!==void 0&&(c===s||s==="*")}))return!0}if(this.domNode&&cF.includes(this.domNode.tagName)||dF.includes(this.role.toLowerCase())||this.role.toLowerCase()==="inlinetextbox"&&this.tagName||!this.properties.hidden&&(this.properties.focusable||this.properties.settable)||sr.alwaysInterestingTruthyPropertyNames.some(n=>!!this.properties[n]))return!0;let t=this.properties.class;return typeof t=="string"&&t.split(" ").some(n=>Hw(n))?!0:this.children.every(n=>n.role==="StaticText")&&this.internalProperties?.inCodeMirrorEditor?!1:this.children.some(n=>n.role==="StaticText")||this.children.length>1&&this.children.some(n=>n.tagName==="input")||this.children.some(n=>n.isIneligible())?!0:this.domNode&&(this.domNode.bounds.x===null||this.domNode.bounds.y===null||!this.domNode.bounds.width||!this.domNode.bounds.height)?!1:!!this.name.trim()||!!this.content||Object.keys(this.properties).some(n=>n.startsWith("data"))}shouldSerializeBounds(){let e=this.domNode?.computedStyles.position;return!!(e&&(e==="absolute"||e==="fixed"||e==="sticky"))}isIneligible(){return!!(this.domNode?.computedStyles.display==="contents"||this.domNode&&(this.domNode.bounds.x===null||this.domNode.bounds.y===null||!this.domNode.bounds.width||!this.domNode.bounds.height))}serialize(e=Nw){let t=Object.assign({},Nw,e),{indentLevel:n,noChildren:o,noProperties:i,noId:a,noContent:s,condensedMode:c}=t,l=Jp(this.properties),u=" ".repeat(n),d=this.role||"",m=this.tagName??"unknown",p=this.name;d==="heading"&&p==="heading"&&(p=""),this.nameSources?.find(v=>!v.superseded&&v.type==="contents")&&this.children.length>0&&(p="");let h=this.nameSources?.find(v=>!v.superseded);if(h&&!h.nativeSource&&h.type==="relatedElement"){let v=h.attributeValue?.relatedNodes??[];v.length===1&&v[0].text&&v[0].text===p&&(p="")}let f=eg.includes(this.role)||gF.includes(this.tagName||"");if(this.role==="StaticText"||this.role==="ListMarker")return`${u}${p}
|
|
4140
|
+
`;let E=`${u}<${m}`;!a&&!f&&(E+=` id="${this.id}"`);let b=s??!1;if((l.multiline||l.contenteditable)&&this.children.length>0&&(b=!0),d&&d!=="generic"&&d!==m&&!(hF[d]??[]).includes(m)&&(E+=` role=${JSON.stringify(d)}`),p&&(E+=` name=${JSON.stringify(p)}`),this.content&&!b&&(E+=` content=${JSON.stringify(this.content)}`),this.flagNotActionableNodes&&this.tagName!=="#document"&&this.isIneligible()&&(E+=` ${sr.ineligibleElementAttribute}`),this.shouldSerializeBounds()&&this.domNode?.bounds){let v=this.domNode.bounds,O=Math.round(v.x??0),w=Math.round(v.y??0),D=Math.round((v.x??0)+(v.width??0)),j=Math.round((v.y??0)+(v.height??0));E+=` bounds=[${O} ${w} ${D} ${j}]`}let x=Date.now();if(Object.keys(l).length>0&&!i){if(Date.now()-x>1e3)throw new Error(`Serialization for the HTML element with tag ${m} and internal ID ${this.id} took too long. Please ensure your machine has enough resources to run Momentic.`);Object.entries(l).forEach(([v,O])=>{if(!aF.includes(v)){{if(sF.includes(v)&&(!O||O==="false"))return;if(v==="value"&&b&&(l.type==="text"||this.role==="textbox"))return;if(v==="level"&&`${O}`=="1")return;if(v==="url"&&l.src&&m==="img")return;if(v==="url"&&l.href&&m==="a")return;if(v==="editable"&&O==="plaintext")return;if(v==="type"&&O===m)return;if(c&&!fF[v])return}typeof O=="string"?E+=` ${v}="${Nt(O,Lw,!0)}"`:typeof O=="boolean"?O?E+=` ${v}`:E+=` ${v}={false}`:typeof O<"u"&&(E+=` ${v}={${Nt(JSON.stringify(O),Lw,!0)}}`)}})}if(m==="::before"||m==="::after"){let v="";for(let O of this.children)v+=O.serialize({...e,indentLevel:n,neighbors:0});return v}let T=e.maxLevel!==void 0&&n/2>=e.maxLevel;if(this.children.length===0||o||T)E+=` />
|
|
4141
4141
|
`;else{let v="";for(let w of this.children)v+=w.serialize({...e,indentLevel:n+2,neighbors:0});let O=v.trim();O.length<=pF&&!O.includes(`
|
|
4142
4142
|
`)?E+=`>${O}</${m}>
|
|
4143
4143
|
`:E+=`>
|
|
@@ -4151,9 +4151,9 @@ Available pages:${JSON.stringify(n.map(i=>i.url))}`);if(!ao(o.url,this.logger)){
|
|
|
4151
4151
|
`),tokenLength:d}),u=[],d=0,m=p.length?[p[p.length-1].id]:[],g=!1);let h=c[l],f=Er(h);d+=f,h.length>a&&(h=h.slice(0,a));let x=Array.from(h.matchAll(iR)).map(W=>W&&W.length>=3?{tagName:W[1],id:W[2]}:void 0).filter(W=>!!W),v=Array.from(h.matchAll($F)).map(W=>W&&(W[2]||W[4])).filter(W=>!!W);v.reverse();let O=h.replace(/ id="[0-9]+"/g,"");u.push(O);for(let W of x)m.push(W.id),p.push(W);for(let W of v){let B=p[p.length-1];B&&B.tagName===W&&p.pop()}let w=p.some(W=>KF.includes(W.tagName)),D=c[l+1]??"",j=Er(D),ee=Array.from(D.matchAll(iR)).map(W=>W&&W.length>2?W[1]:void 0).filter(W=>!!W),he=ee.some(W=>lR.includes(W)),st=ee.some(W=>qF.includes(W));d+j>=i&&(g=!0),d>=n&&(he&&!w||v.some(W=>YF.includes(W)))&&(g=!0),d>=o&&st&&!w&&(g=!0),l++}return u.length&&s.push({ids:m,content:u.join(`
|
|
4152
4152
|
`),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 ZF=75e4,Vc=3e5;async function uo(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=Er(u);if(d>ZF)try{let m=Gc({serializedTree:u,options:{minChunkTokenCount:1e4,maxChunkTokenCount:1e5,acceptableChunkTokenCount:5e4,maxLineLength:4e3},logger:i});l=await eB({...r,tokenLimit:Vc-1e4,chunks:m.chunks}),u=l.serialize();let p=Er(u);i.info({oldTokens:d,newTokens:p},"Filtered page using keywords"),d=p}catch(m){i.warn({err:m},"Error filtering page using keyword matching, using naive truncation"),l=l.pruneToSerializedCharLimit(Vc*xn),u=l.serialize();let p=Er(u);i.info({oldTokens:d,newTokens:p},"Filtered page using naive truncation"),d=p}if(d>Vc)try{if(o){let m=Gc({serializedTree:u,options:sR,logger:i}),p=JF();l=await k(QF({...r,chunks:m.chunks,callId:p}),{milliseconds:12e3,signal:c}),u=l.serialize();let g=Er(u);i.info({oldTokens:d,newTokens:g,langfuseCallId:p},"Filtered page using AI chunk ranking"),d=g}else{let m=Gc({serializedTree:u,options:aR,logger:i});l=await k(tB({...r,chunkResult:m,tokenLimit:4e4}),{milliseconds:12e3,signal:c}),u=l.serialize();let p=Er(u);i.info({oldTokens:d,newTokens:p},"Filtered page using RAG"),d=p}}catch(m){i.warn({err:m},"Error filtering page using RAG/AI, using naive truncation"),l=l.pruneToSerializedCharLimit(Vc*xn),u=l.serialize(),i.info("Filtered page using naive truncation")}return u}async function QF({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:ge(c)}),u=[];return t.forEach((m,p)=>{l.indices.includes(p)&&(u=u.concat(m.ids))}),i.pruneUsingRelevantIds(new Set(u))}async function eB(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:ge(i),abortSignal:a});i.info({keywordsResult:s},"Got keywords for page filtering");for(let c of s.keywords){let l=r.chunks.filter(p=>p.content.toLowerCase().includes(c.toLowerCase()));if(!l.length||l.reduce((p,g)=>p+g.tokenLength,0)>r.tokenLimit&&l.length>1)continue;let d=l.flatMap(p=>p.ids);return n.pruneUsingRelevantIds(new Set(d))}throw new Error("No keywords were unique enough for page filtering")}async function tB(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:ge(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 sg(r,e){if(!r.description)throw new C("UserConfigurationError","Cannot locate element with empty description");return ur({action:async()=>rB(r,e),frameConfig:r.iframeUrl?{type:"url",url:r.iframeUrl}:void 0,browser:e.browser,logger:r.logger})}async function rB(r,e){let{disableCache:t,testContext:n,filterByViewport:o,skipWait:i,source:a,memory:s,aiPageFiltering:c,logger:l,allowNotActionableNodesOverride:u}=r,{ctx:d,orgId:m,browser:p,localCodeEvalTools:g,generator:h,abortSignal:f}=e,E=r.description,b=r.useMemory&&!t;n&&(E=await Ka({orgId:m,s:E,context:n,localTools:g,signal:f,logger:l})),a&&(E=oB(E,a));let{serializedTree:x,tree:T}=await Hr(p,{allowNotActionableNodesOverride:u,filterByViewport:o,abortSignal:f,skipWait:i,logger:l}),v,O=Date.now(),w;for(;!v&&Date.now()-O<3e3;){f.throwIfAborted();try{v=await p.screenshot({clearHighlights:!0,respectActiveFrame:!0,retries:2})}catch(ce){w=ce}}if(!v)throw new C("ActionFailureError",`Failed to take screenshot of page to locate element. The page may be unresponsive, or your machine might be severely resource constrained. Error: ${w?.message}`);let D=x,j=!1,ee=`data:image/jpeg;base64,${v.toString("base64")}`;D=await uo({type:"locator",description:E,screenshot:ee,serializedTree:x,options:{aiPageFiltering:c},tree:T,fixtures:{generator:h,signal:f,logger:l,orgId:m}}),D!==x&&(j=!0);let he=await h.getElementLocation({browserState:D,goal:E,screenshot:ee,source:a,memory:b?s:void 0},{disableCache:t,abortSignal:f,loggerTags:ge(l),useMemory:b});l.debug({usedRag:j,result:he},"Got locator result");let st=he.id>0;if(d?.details?.push({type:"AI_LOCATION",matched:st,pageState:D,ragUsed:j,thoughts:he.thoughts}),!st)throw new Io(`Could not find any relevant element: ${he.thoughts}`,he.updatedMemory?{type:"GCS_TRACES",traces:he.updatedMemory}:void 0);let{resolution:W,target:B,frameConfig:ae}=await p.createTargetFromA11yId({id:he.id,requirements:he.requirements,additionalElements:he.additionalElements,description:E,targetSource:"AI",logger:l});if(W.a11yNode?.properties?.hidden&&W.a11yNode?.properties?.hidden!=="false")throw new C("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: ${W.displayString}`);return b&&(he.updatedMemory?B.memory={type:"GCS_TRACES",traces:he.updatedMemory}:s&&(B.memory=s)),{thoughts:he.thoughts,target:B,resolution:W,frameConfig:ae,screenshot:ee}}var nB=["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:"],cR="<select> element:",uR="text input or contenteditable element:",dR="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:",mR="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:",ag=[cR,uR,dR,mR,...nB];function pR(r,e){if(r===e)return!0;for(let t of ag){if(!r.startsWith(t))continue;let n=r.slice(t.length).trim();if(ag.some(o=>e.startsWith(o)&&e.slice(o.length).trim()===n)||n===e.trim())return!0}return!!ag.some(t=>e.startsWith(t)&&e.slice(t.length).trim()===r.trim())}function oB(r,e){if(!r||!e)return r;switch(e){case"SELECT_OPTION":return`${cR} ${r}`;case"TYPE":return`${uR} ${r}`;case"NEGATED_ELEMENT_VISIBLE_CHECK":return`${dR}
|
|
4153
4153
|
${r}`;case"ELEMENT_CHECK":return`${mR}
|
|
4154
|
-
${r}`;default:return r}}var iB=15;async function jc({command:r,aiPageFiltering:e,logger:t,fixtures:n,source:o,useMemory:i,maxRetries:a=iB}){if(!r.assertion.trim())throw new C("ActionFailureError","Assertion command is missing the assertion content");let{browser:s}=n,c=r.timeout?r.timeout*1e3:s.smartWaitingTimeout,l=Cc(c),u=0,d=Date.now(),m,p,g;try{await ur({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 X(l,n.abortSignal),h=Date.now();let f=!1;try{if(m=await ur({action:async()=>{let b=await gR(s,t,n.abortSignal);return p&&p.serializedTree===b.serializedTree&&p.screenshotBuff.equals(b.screenshotBuff)?(f=!0,m):(p=b,hR({command:r,state:b,fixtures:n,useMemory:i,useConsensus:!1,highlightElementsOnFailure:!1,attemptNumber:u,aiPageFiltering:e,logger:t,source:o}))},frameConfig:r.iframeUrl?{type:"url",url:r.iframeUrl}:void 0,logger:t,browser:s}),m?.updatedMemory&&vc(r,m.updatedMemory,t),m?.success)break;throw m?.thoughts?new C("AssertionFailureError",m.thoughts):new C("InternalPlatformError","No thoughts were provided for AI assertion failure")}catch(E){n.abortSignal.throwIfAborted(),g=E instanceof Error?E:new Error(`${E}`),f?t.info(`AI check attempt ${u} failed (re-used previous result)`):t.info({err:E},`AI check assert attempt ${u} failed, retrying...`)}finally{u++}}if(!m?.success)try{m=await ur({action:async()=>hR({command:r,state:await gR(s,t,n.abortSignal),fixtures:n,useMemory:i,useConsensus:!0,highlightElementsOnFailure:!0,attemptNumber:u,aiPageFiltering:e,logger:t}),frameConfig:r.iframeUrl?{type:"url",url:r.iframeUrl}:void 0,logger:t,browser:s})}catch(f){n.abortSignal.throwIfAborted(),g=f instanceof Error?f:new Error(`${f}`)}finally{u++}if(!m?.success){let f=`AI check still failing after ${u} attempts.`;throw g&&(f+=` Latest result: ${g.message}`),new C("AssertionFailureError",f)}return{...m,succeedImmediately:!1,urlAfterCommand:s.url()}}async function gR(r,e,t){let[n,o]=await Promise.all([Hr(r,{abortSignal:t,skipWait:!0,skipWaitForPageLoad:!0,logger:e}),r.screenshot({retries:1,respectActiveFrame:!0})]);return{...n,screenshotBuff:o}}async function hR({command:r,state:e,fixtures:t,useConsensus:n,useMemory:o,highlightElementsOnFailure:i,aiPageFiltering:a,attemptNumber:s,source:c,logger:l}){let{browser:u,generator:d,abortSignal:m}=t,p={type:"ASSERTION"},{serializedTree:g,tree:h}=e,f=e.screenshotBuff,E=f.toString("base64"),b=u.url(),x=r.contextChoice??"MULTIMODAL",T=g;x!=="VISION_ONLY"&&(T=await uo({type:"assertion",serializedTree:g,tree:h,description:r.assertion,screenshot:E,options:{aiPageFiltering:a},fixtures:{generator:d,signal:m,logger:l,orgId:t.orgId}}),T!==g&&(p.ragUsed=!0),p.pageState=T);let v={goal:r.assertion,url:b,memory:o?r.cache?.memory:void 0,browserState:T,screenshot:E,contextChoice:x,source:c},w=await(x==="VISION_ONLY"?(D,j)=>d.getVisualAssertionResult(D,j):(D,j)=>d.getAssertionResult(D,j))(v,{useConsensus:n,attemptNumber:s,useMemory:o,disableCache:!!r.disableCache,abortSignal:m,logger:l,loggerTags:ge(l)});return(w.result||i)&&w.relevantElements&&(p.relevantElementsSerialized=w.relevantElements.map(D=>u.getSerializedFormFromA11yId(D)).filter(D=>!!D),await aB(w.relevantElements,u,l)),{success:w.result,thoughts:w.thoughts,afterScreenshotOverride:f,updatedMemory:o?w.updatedMemory:void 0}}async function aB(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 k(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 sB=75e4,Wc=class extends Error{constructor(){super("The page content exceeds the maximum token limit for AI smart waiting."),this.name="ExceededMaxAISmartWaitingTokensError"}};async function fR(r,e){let{logger:t}=r,{abortSignal:n,browser:o}=e,i=Date.now();try{await lB(i,r,e)}catch(a){if(a instanceof Error&&(a.name==="AbortError"||a.name==="TimeoutError")||n.aborted)return;a instanceof Wc?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 X(s,n)}finally{t.debug({durationMs:Date.now()-i},"AI smart waiting complete")}}async function lB(r,e,t){let{abortSignal:n,browser:o}=t;if(o.smartWaitingTimeout<3e3){await X(o.smartWaitingTimeout,n);return}if(!e.description)throw new C("UserConfigurationError","Cannot locate element with empty description");await k(cB(r,e,t),{milliseconds:o.smartWaitingTimeout})}async function cB(r,e,t){let{logger:n,iframeUrl:o}=e,{browser:i}=t;for(;Date.now()-r<i.smartWaitingTimeout;)if(await ur({action:async()=>uB(e,t),frameConfig:o?{type:"url",url:o}:void 0,browser:i,logger:n}))return}async function uB(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 Ka({orgId:l,s:d,context:t,localTools:c,signal:s,logger:n}));let{serializedTree:m}=await Hr(a,{allowNotActionableNodesOverride:i,filterByViewport:o,abortSignal:s,logger:n});if(Er(m)>sB)throw new Wc;s.throwIfAborted();let g;try{g=await a.screenshot({clearHighlights:!0,respectActiveFrame:!0,retries:2})}catch(b){throw new C("ActionFailureError",`Failed to take screenshot of page to perform smart waiting. The page may be unresponsive, or your machine might be severely resource constrained. Error: ${b instanceof Error?b.message:b}`)}let f=`data:image/jpeg;base64,${g.toString("base64")}`;s.throwIfAborted();let E=await u.getSmartWaitingDecision({browserState:m,description:d,screenshot:f},{abortSignal:s,loggerTags:ge(n)});return n.debug({result:E},"Got smart waiting result"),E.isPageReady}import{cloneDeep as yR}from"lodash-es";async function bR(r){let{command:e,timeoutMs:t,fixtures:n}=r,{abortSignal:o}=n,i=()=>bh(e.cache)?e.cache:void 0,a=i(),s=yR(a),c=(h=!1)=>{if(a=i(),!!a)if(h){let f=Kv(s,a);a.target=f.target,a.updatedAt=f.updatedAt}else{if(!s){a=void 0;return}a.target=s.target,a.updatedAt=s.updatedAt}},l=Date.now(),u=0,d,m=500,p=!1;for(;u<2||Date.now()-l<t;){u++,u>1&&await X(m,o),o?.throwIfAborted(),a=i();let{result:h,elementWasFound:f}=await SR({cacheToUse:a,params:r});if(d=h,p=f,h.success)break;c(),m=Math.min(m*2,1e4)}if(!d)throw new C("InternalPlatformError",`Failed to evaluate manual element assertion in ${t}ms.`);if(o?.throwIfAborted(),!d.success&&a?.target&&As(a.target)){let h=a?.target?.memory?{target:{id:-1,memory:a.target.memory}}:void 0,{result:f}=await SR({cacheToUse:h,params:r});d=f,d.success||c(!0)}let g=i();return d.success&&g?.target&&!p&&(g.target=fp(g.target),g.updatedAt=new Date),d}async function SR({cacheToUse:r,params:e}){let{command:t,disableCache:n,fixtures:o,tracer:i,targetingWrapper:a}=e,{logger:s}=o;if(t.target&&!on(t.target))throw new Error("Element assertion with x/y is not supported yet");let c=mB(t.assertion),l,u=!1,d=yR(r);try{let{elementInteractedDisplayString:m,result:p,thoughts:g}=await a({ctx:o.ctx,tracer:i,command:t,target:t.target,cache:d?.target,action:async h=>dB(h.locator,e),options:{...t,allowNotActionableNodesOverride:!0,disableCache:n,memory:d?.target?.memory,disableGlobalLocatorRedirect:!0,source:ta(t),targetName:"target"}});return l={success:p.success,data:p.data,err:p.err,elementInteractedDisplayString:m,thoughts:g},u=!0,p.success||(s.warn({aiThoughts:g,elementString:m,err:p.err},"Element check found an element but failed"),l={...p,thoughts:g}),{result:l,elementWasFound:u}}catch(m){if(c)return l={success:!0,thoughts:`The element described does not exist on the page: ${m.message}`,err:void 0,data:void 0},{result:l,elementWasFound:u};if(!(m instanceof C)||m.reason!="ActionFailureError")throw m;return l={success:!1,err:m,data:void 0,thoughts:void 0},s.warn({err:m},"Element check did not find an element and failed"),{result:l,elementWasFound:u}}}async function dB(r,{command:e,fixtures:t}){let n=e.assertion;await t.browser.highlight(r);let o=!0,i,a;switch(n.type){case"ELEMENT_CONTENT":{let c=await r.textContent()??"";if(a={elementTextContent:Nt(c,500,!0)},!$c(c,n.value,n.operation,!!n.negated)){let l=n.negated?An[n.operation]:wn[n.operation];o=!1,i=new C("AssertionFailureError",`The content ${l} '${n.value}': ${c}`)}break}case"ELEMENT_ATTRIBUTE":{a={elementOuterHtml:Nt(await r.evaluate(l=>l.cloneNode(!1).outerHTML),500,!0)};let c;try{c=await r.getAttribute(n.attr,{timeout:3e3})??""}catch(l){i=new C("AssertionFailureError",`The element does not have an attribute named ${n.attr}: ${l}`),o=!1;break}if(!$c(c,n.value,n.operation,!!n.negated)){let l=n.negated?An[n.operation]:wn[n.operation];o=!1,n.operation==="EXISTS"?i=new C("AssertionFailureError",`The attribute ${n.attr} ${l}`):i=new C("AssertionFailureError",`The attribute ${n.attr} ${l} '${n.value}': ${c}`)}break}case"ELEMENT_EXISTENCE":{switch(n.condition){case"VISIBLE":{o=await r.evaluate(async(l,u)=>{let d=Date.now();for(;Date.now()-d<u;){await new Promise(p=>setTimeout(p,250));let m=l.getBoundingClientRect();if(!(m.width===0||m.height===0)&&window.getComputedStyle(l).visibility!=="hidden"&&window.getComputedStyle(l).display!=="none")return!0}return!1},wr*1e3);break}case"EDITABLE":{o=await r.isEditable({timeout:wr*1e3});break}case"EXISTS":{o=!0;break}case"ENABLED":{o=await r.isEnabled({timeout:wr*1e3});break}case"FOCUSED":{o=await r.evaluate(l=>l===document.activeElement);break}default:return(l=>{throw"If Typescript complains about the line below, you missed a case or break in the switch above"})(n.condition)}if(o=n.negated?!o:o,!o){let c=n.negated?Xv[n.condition]:Jv[n.condition];i=new C("AssertionFailureError",`The element ${c}`)}break}case"ELEMENT_NAME":{let c=await r.evaluate(l=>l.tagName);if(!$c(c,n.value,n.operation,!!n.negated)){let l=n.negated?An[n.operation]:wn[n.operation];o=!1,i=new C("AssertionFailureError",`The element tag name ${l} '${n.value}': ${c}`)}break}case"ELEMENT_STYLE":{let c=await r.evaluate((l,u)=>window.getComputedStyle(l).getPropertyValue(u),n.property);if(!$c(c,n.value,n.operation,!!n.negated)){let l=n.negated?An[n.operation]:wn[n.operation];o=!1,n.operation==="EXISTS"?i=new C("AssertionFailureError",`The style property ${n.property} ${l}`):i=new C("AssertionFailureError",`The style property ${n.property} ${l} '${n.value}': ${c}`)}break}default:return(c=>{throw"If Typescript complains about the line below, you missed a case or break in the switch above"})(n)}return{success:o,data:a,err:i}}function $c(r,e,t,n){let o;switch(t){case"CONTAINS":{o=r.includes(e);break}case"EQUALS":{o=r.trim()===e.trim();break}case"STARTS_WITH":{o=r.trim().startsWith(e);break}case"EXISTS":{o=r.trim().length>0;break}default:return(a=>{throw"If Typescript complains about the line below, you missed a case or break in the switch above"})(t)}return n?!o:o}function mB(r){return r.type==="ELEMENT_EXISTENCE"&&r.negated&&(r.condition==="EXISTS"||r.condition==="VISIBLE")}function ER(r){return r.type==="ELEMENT_EXISTENCE"&&r.negated&&r.condition==="EXISTS"}import{Jimp as pB}from"jimp";async function es(r,e){let t=await r.screenshot(e),n=await pB.fromBuffer(t);return{buffer:t,width:Math.ceil(n.bitmap.width??0),height:Math.ceil(n.bitmap.height??0)}}import{Jimp as TR}from"jimp";import lg from"jpeg-js";import gB from"pixelmatch";async function vR({ctx:r,tracer:e,command:t,disableCache:n,browser:o,targetingWrapper:i,logger:a,screenshotStorage:s}){if(t.target&&!on(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 ee=>es(o,{locator:ee.locator,...c}),options:{...t,disableCache:n,disableGlobalLocatorRedirect:!0,memory:t.cache?.target?.memory,targetName:"target"}})).result:l=await es(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 ie=`${l.width}x${l.height}`,ee=`${u.width}x${u.height}`;return{fail:!0,thoughts:`Current screenshot (${ie}) does not match saved screenshot dimensions (${ee}) - 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 TR.fromBuffer(l.buffer),m={width:l.width,height:l.height},p=await TR.fromBuffer(u.buffer),g={width:u.width,height:u.height},h,f=m.width*m.height,E=g.width*g.height,b=Math.abs(m.height-g.height),x=Math.abs(m.width-g.width);if(f>E){let ie=d.cover({w:g.width,h:g.height});l.buffer=await ie.getBuffer("image/jpeg"),h="current",l.width=g.width,l.height=g.height}else if(E>f){let ie=p.cover({w:m.width,h:m.height});u.buffer=await ie.getBuffer("image/jpeg"),h="saved"}let T={data:Buffer.alloc(l.width*l.height*4),width:l.width,height:l.height},v=t.threshold??.1,w=gB(lg.decode(u.buffer).data,lg.decode(l.buffer).data,T.data,l.width,l.height,{threshold:v,diffColorAlt:[0,255,0]})/(l.width*l.height)*100,D=w>v*100,j=`Visual diff of ${w.toFixed(2)}% detected, which is ${D?"over":"under"} the threshold of ${v*100}%.`;if(h&&(j+=` The ${h} screenshot was cropped since it was taller by ${b} pixels and wider by ${x} pixels.`),D)throw new C("ActionFailureError",j);return{fail:D,thoughts:j,beforeScreenshotOverride:l.buffer,afterScreenshotOverride:lg.encode(T,75).data,succeedImmediately:!1,urlAfterCommand:o.url()}}var hB=3e4;async function qc({command:r,logger:e,baseUrl:t,fetchImplementation:n=fetch}){let o=r.timeout??hB/1e3,i=Object.fromEntries(Object.entries(r.headers||{}).filter(([p,g])=>p&&g)),a=new URLSearchParams;Object.entries(r.params||{}).filter(([p,g])=>p&&g).forEach(([p,g])=>{a.append(p,g)});let s=a.toString(),c;if(ci(r.url)&&(c=r.url),t&&ui(r.url,t)&&(c=new URL(r.url,t).toString()),!c)throw new C("ActionFailureError",`Invalid URL: ${r.url}`);e.info({url:c,searchParams:s,headers:i,body:r.body,method:r.method},"Making HTTP request");let u=await k((async()=>{let p=s?`${c}?${s}`:c;try{return await n(p,{headers:i,method:r.method,body:r.body})}catch(g){throw e.error({err:g},"Failed to make HTTP request"),new Error(`Failed to make HTTP request: ${g}`)}})(),{milliseconds:o*1e3,fallback:()=>{throw new C("ActionFailureError",`Fetch request timed out after ${o} seconds`)}});if(!u.ok){let p;try{p=await u.text()}catch(g){p=`Failed to read response body: ${g}`}throw new C("ActionFailureError",`Fetch request failed with status ${u.status}: ${p}`)}let d={};u.headers.forEach((p,g)=>{d[g]=p});let m={status:u.status,headers:d};if(u.headers.get("content-type")?.includes("json"))try{m.json=await u.json()}catch{}else u.headers.get("content-type")?.includes("text")&&(m.text=await u.text());return m}var fB=5e3;async function wR({timeout:r=wr,...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 Kc(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 X(s,e.signal),s=Math.min(Math.floor(s*1.5),fB);else return i}return i=await Kc(e),i}async function Kc({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(AR,{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(AR,{value:r.value,negated:!!r.negated,returnHtml:!0},"checking page content"));if(!i){let c=r.negated?An.CONTAINS:wn.CONTAINS;a=new C("AssertionFailureError",`The page ${c} '${r.value}'.`),o=s}}catch(s){a=new C("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 AR({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 SB=3e4;async function RR({command:r,logger:e,baseUrl:t,fetchImplementation:n=fetch}){let o=r.timeout??SB/1e3,i=new AbortController,a=Object.fromEntries(Object.entries(r.headers||{}).filter(([d,m])=>d&&m));a["Content-Type"]="application/json";let s;if(ci(r.url)&&(s=r.url),t&&ui(r.url,t)&&(s=new URL(r.url,t).toString()),!s)throw new C("ActionFailureError",`Invalid URL: ${r.url}`);let l=await k((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 C("ActionFailureError",`GraphQL request timed out after ${o} seconds`);if(!l.ok){let d,m=await l.text();try{d=JSON.parse(m)}catch{throw new C("ActionFailureError",`GraphQL request failed with status ${l.status}: ${m}`)}throw d?.errors?.length&&d?.errors[0]?.message?new C("ActionFailureError",`GraphQL request failed with status ${l.status}: ${d.errors[0].message}`):new C("ActionFailureError",`GraphQL request failed with status ${l.status}: ${m}`)}let u={};return l.headers.forEach((d,m)=>{u[m]=d}),{status:l.status,headers:u,json:await l.json()}}var Yc=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([Hr(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 uo({type:"ai-action",description:e,screenshot:u,serializedTree:c.serializedTree,tree:c.tree,options:{aiPageFiltering:!!this.options?.aiPageFiltering},fixtures:{generator:this.generator,signal:this.executeAbortController.signal,logger:s,orgId:this.orgId}}),m={url:this.browser.url(),browserState:d,startingScreenshot:t,history:n,goal:e,screenshot:u,lastError:a};return await this.generator.getMultiturnAiActionEvaluation(m,{disableCache:o,abortSignal:this.executeAbortController.signal,loggerTags:{...ge(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([Hr(this.browser,{abortSignal:this.executeAbortController.signal,skipWait:!0,skipWaitForPageLoad:!0,logger:a}),this.browser.screenshot({retries:1,clearHighlights:!0})]),d=`data:image/jpeg;base64,${u.toString("base64")}`,m=await uo({type:"ai-action",description:e,screenshot:d,serializedTree:l.serializedTree,tree:l.tree,options:{aiPageFiltering:!!this.options?.aiPageFiltering},fixtures:{generator:this.generator,signal:this.executeAbortController.signal,logger:a,orgId:this.orgId}}),p={url:c,browserState:m,startingScreenshot:t,history:n,goal:e,actionHint:o,screenshot:d};try{return await this.generator.getMultiturnAiActionCommand(p,{disableCache:i,abortSignal:this.executeAbortController.signal,loggerTags:{...ge(a)},langfuseSessionId:s})}catch(g){throw new C("InternalWebAgentError",`Error generating command: ${g instanceof Error?g.message:g}`,{errOptions:{cause:g}})}}async getBrowserState(e){return Hr(this.browser,e)}async locateElement(e){return await sg({...e,aiPageFiltering:!!this.options?.aiPageFiltering},this.getControllerFixtures())}async locateElementWithSelector(e,t){return ur({action:async()=>{let n=await this.browser.resolveHardcodedCssSelector({ctx:null,selector:e,timeoutMs:2e3,logger:this.logger});return{thoughts:"Located element with selector",target:{id:-1,selector:e,targetSource:"USER_CSS_SELECTOR",targetUpdateTime:new Date().toUTCString()},resolution:n}},frameConfig:t?{type:"url",url:t}:void 0,browser:this.browser,logger:this.logger})}getControllerFixtures(e){return{ctx:e??null,browser:this.browser,generator:this.generator,logger:this.logger,orgId:this.orgId,storage:this.storage,localCodeEvalTools:this.localCodeEvalTools,abortSignal:this.executeAbortController.signal}}shouldUseMemory(){return this.options?.useMemory??(this.orgId==="org_01HMSCJQBCCG51M2ZF65YC5B8W"||this.orgId==="org_01HMJTX4GT1KG94KZRCT8MZ6YB")}async wrapMultiElementTargetingCommand({ctx:e,tracer:t,command:n,targetNames:o,descriptions:i,caches:a,action:s,options:c,retriesWithAI:l=1}){let u=[];for(let d=0;d<i.length;d++){let m=i[d],p=await this.wrapElementTargetingCommand({ctx:e,tracer:t,command:n,target:m,cache:a[d],action:async g=>g,options:{...c,targetName:o[d]}});u.push(p)}try{let d=await s(...u.map(g=>g.result)),m=g=>g==="fromTarget"?"From Target":g==="toTarget"?"To Target":"Target",p=u.map((g,h)=>g.thoughts?`${m(o[h])}: ${g.thoughts}`:void 0).filter(g=>!!g).join(" -------------- ")||void 0;return{result:d,elementInteractedDisplayStrings:u.map(g=>g.elementInteractedDisplayString),thoughts:p}}catch(d){if(this.throwIfClosed(),l>0)return this.logger.warn({err:d},"Failed to execute action with multiple cached targets, retrying with AI"),this.wrapMultiElementTargetingCommand({ctx:e,tracer:t,command:n,targetNames:o,descriptions:i,caches:i.map(()=>{}),action:s,options:c,retriesWithAI:l-1});throw new C("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 ur({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&&qu(i)){t.warn({err:i},"Invalid mpath error, retrying element targeting command");continue}if(!this.browser.userBrowserSettings.visualActions&&(Xu(i)||Ku(i))){t.warn({err:i},"Invalid momentic id error, retrying element targeting command");continue}if(Ju(i)){t.warn({err:i},"Invalid backend node id error, retrying element targeting command");continue}if(i instanceof xr&&i.retryableWithAI){t.warn({err:i},"Element cache disqualification error, retrying element targeting command");continue}throw i}throw n instanceof C?n:new C("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 C("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 X(500)}}throw c}async wrapElementTargetingCommandHelper(e){let{ctx:t,tracer:n,target:o,originalCache:i,action:a,options:s,command:c}=e,{disableCache:l,useSelector:u,targetName:d,targetHealingInProgress:m,source:p}=s,g=this.logger.child({commandId:c.id}),h=this.shouldUseMemory(),f=s.retriesWithAI??1,E=!1,b=CR(e.cache);if((!b||l)&&!Pu(o))throw new C("ActionFailureError","Cannot target element with no cached data or element descriptor");if(u)return this.wrapHardcodedCssTargetingCommandHelper(e);l&&(g.info("Cache explicitly disabled for this step"),E=!0,b=void 0),b&&this.browser.userBrowserSettings.disableSecondaryCacheResolution&&b.targetSource==="HEURISTIC_HEALED"&&(E=!0,b=void 0),b?.inputDescription&&!pR(o.elementDescriptor,b.inputDescription)&&(g.warn({old:b.inputDescription,new:o.elementDescriptor},"Target cache was generated with a different description, clearing it automatically"),E=!0,b=void 0);let x=v=>!!v&&As(v),T=!0;if(!x(b)){T=!1,g.info({description:o.elementDescriptor,targetHealingInProgress:m,cacheBustedBeforeAction:E,memory:s.memory,useMemory:h},"Prompting AI for an updated element location"),(E||!i)&&await fR({description:o.elementDescriptor,iframeUrl:s.iframeUrl,source:p,logger:g,allowNotActionableNodesOverride:s.allowNotActionableNodesOverride},this.getControllerFixtures(t)),f--;let v;try{v=await sg({description:o.elementDescriptor,disableCache:!!s.disableCache,iframeUrl:s.iframeUrl,source:p,useMemory:h,memory:h?s.memory:void 0,aiPageFiltering:!!this.options?.aiPageFiltering,allowNotActionableNodesOverride:s.allowNotActionableNodesOverride,logger:g},this.getControllerFixtures(t))}catch(D){if(D instanceof Io&&D.updatedLocatorMemory){let j={id:-1,...i,memory:D.updatedLocatorMemory};Tc({cmd:c,key:d,newTarget:j,logger:g,updatedWithAI:!0})}throw new C("ActionFailureError",D.message)}v.frameConfig&&this.browser.setActiveFrameConfig(v.frameConfig);let O=s.disableGlobalLocatorRedirect?{locator:v.resolution.locator}:await this.attemptLocatorRedirect(v.resolution.locator,g),w=await a(O);return Tc({cmd:c,key:d,newTarget:v.target,logger:g,updatedWithAI:!0}),m&&(n.recordTargetAutoHeal({healType:"AI"}),v.target.targetSource="AI_HEALED",v.target.targetUpdateTime=new Date().toUTCString(),v.target.targetUpdateLoggerTags=ge(g)),{result:w,elementInteractedDisplayString:v.resolution.displayString,thoughts:v.thoughts}}try{let v=await this.browser.resolveTarget(t,b,{allowNotActionableNodesOverride:s.allowNotActionableNodesOverride,targetName:d,logger:g,signal:this.executeAbortController.signal});(this.browser.userBrowserSettings.visualActions||this.browser.userBrowserSettings.globalLocatorRedirect!==!1)&&await this.browser.scrollIntoViewIfNeeded(v.locator);let O=s.disableGlobalLocatorRedirect?{locator:v.locator}:await this.attemptLocatorRedirect(v.locator,g),w=await a(O);if(ft.increment("cache_target_resolution_v2",1,["outcome:hit","platform:web",`hasRequirements:${!!b.requirements}`,`hasAdditionalElements:${!!b.additionalElements}`,`orgId:${this.orgId}`,"cliVersion:0.7.0"]),Tc({cmd:c,key:d,newTarget:b,logger:g,updatedWithAI:!1}),T){let D=v.decisions.filter(j=>j.matched);if(D.length!==1)g.warn({decisions:v.decisions},"Expected exactly 1 matching method for element location, got more or less");else{let j=D[0].type;n.recordTargetAutoHeal({healType:j})}}return{result:w,elementInteractedDisplayString:v.displayString}}catch(v){this.throwIfClosed();let O="unknown";v instanceof Cr&&v.cacheMissReason&&(O=v.cacheMissReason),ft.increment("cache_target_resolution_v2",1,["outcome:miss","platform:web",`hasRequirements:${!!b.requirements}`,`hasAdditionalElements:${!!b.additionalElements}`,`orgId:${this.orgId}`,"cliVersion:0.7.0",`missReason:${O}`]);let w=!1;if((v instanceof xr||qu(v)||Xu(v)||Ju(v)||Sf(v)||Ku(v)||yf(v))&&(w=!0),v instanceof C&&!w)throw g.error({err:v},"Failed to execute action with cached target (fatal)"),v;if(f>0&&o){g.info({err:v},"Failed to execute action with cached target, retrying with AI");let D;return b.memory&&ph(b.memory)&&(D=b.memory),this.wrapElementTargetingCommand({ctx:t,tracer:n,command:c,target:o,cache:void 0,originalCache:i,action:a,options:{...s,memory:D,retriesWithAI:f,targetHealingInProgress:!0}})}throw new C("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 es(this.browser,e)}async executePresetCommand(e,t,n,o,i){this.options?.slowMoMs&&await X(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 C("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&&Dh(n)?await this.browser.waitForDOMStability({timeout:fe}):!this.browser.userBrowserSettings.visualActions&&["PRESS","TYPE"].includes(n.type)&&await this.browser.waitForDOMStability({timeout:Q}),this.options?.autoFollowNewTabs&&await oR({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{Ec(n,c)}}createCallbacksForBrowser(e){return{createIsolatedFolder:()=>Lp(e)}}async resolveCommandTemplateStrings(e,t){return bc({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()?jc({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 C("ActionFailureError","Missing assertion");if(n.timeout&&n.timeout>1800)throw new C("AssertionFailureError",`AI check timeout of ${n.timeout} exceeds the maximum allowed value of 30 minutes.`);return jc({command:n,fixtures:this.getControllerFixtures(e),useMemory:this.shouldUseMemory(),aiPageFiltering:!!this.options?.aiPageFiltering,logger:a})}case"AI_EXTRACT":{if(!n.goal.trim())throw new C("ActionFailureError","Cannot perform AI extraction without goal");if(n.schema){let f=ib(n.schema);if(f)throw new C("UserConfigurationError",f)}let g=await this.browser.getCondensedHtml(),h=await this.browser.screenshot({retries:2});try{let f=await this.generator.getTextExtraction({goal:n.goal,browserState:g,returnSchema:n.schema,screenshot:`data:image/jpeg;base64,${h.toString("base64")}`},{disableCache:i,abortSignal:this.executeAbortController.signal,loggerTags:ge(a)});if(f.result==="NOT_FOUND")throw new C("ActionFailureError","No relevant data found for extraction goal on this page");if(f.thoughts?.includes("MaxGenerationLengthExceededError"))throw new C("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 C("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 C("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(!ci(n.url)&&!ui(n.url,this.browser.baseUrl))throw new C("ActionFailureError",`Invalid URL provided to navigate command: ${n.url}`);await this.browser.navigate({url:n.url,loadTimeoutMs:n.loadTimeout?n.loadTimeout*1e3:void 0});break;case"DIALOG":this.browser.registerDialogHandler(n.action);break;case"CAPTCHA":if(!this.browser.canSolveCaptchas())break;let c=await this.browser.solveCaptcha();c&&(await this.wrapElementTargetingCommand({ctx:e,tracer:t,command:n,target:{type:"description",elementDescriptor:"the captcha image solution input"},cache:void 0,action:g=>this.browser.click(g,this.createCallbacksForBrowser(this.orgId),{}),options:{...n,targetName:"target",disableCache:i}}),await this.browser.type(c,{clearContent:!0,pressEnter:!0},!0));break;case"GO_BACK":await this.browser.goBack();break;case"GO_FORWARD":await this.browser.goForward();break;case"SCROLL_LEFT":case"SCROLL_RIGHT":case"SCROLL_DOWN":case"SCROLL_UP":{let g,h;if(n.target&&Ar(n.target))await this.browser.hoverUsingVisualCoordinates(n.target.pixels);else if(n.target&&n.target.elementDescriptor.trim()){let{elementInteractedDisplayString:b,thoughts:x}=await this.wrapElementTargetingCommand({ctx:e,tracer:t,command:n,target:n.target,cache:n.cache?.target,action:T=>this.browser.hover(T),options:{...n,targetName:"target",disableGlobalLocatorRedirect:!0,disableCache:i}});g=b,h=x}let f=this.browser.getViewport()?.height??cn.height,E=this.browser.getViewport()?.width??cn.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:g,thoughts:h}}case"WAIT_FOR_URL":{if(n.timeout&&n.timeout>1800)throw new C("UserConfigurationError",`Wait for URL timeout of ${n.timeout} exceeds the maximum allowed value of 30 minutes.`);let g=n.matcher;await this.browser.waitForUrl({beforeUrl:this.browser.url(),matcher:g},{timeout:n.timeout?n.timeout*1e3:void 0,negated:n.negated,caseInsensitive:n.caseInsensitive});break}case"WAIT":if(n.delay>1800)throw new C("UserConfigurationError",`Wait timeout of ${n.delay} seconds exceeds the maximum allowed value of 30 minutes`);let l=n.delay*1e3;await X(l,this.executeAbortController.signal);break;case"REFRESH":await this.browser.refresh({loadTimeoutMs:n.loadTimeout?n.loadTimeout*1e3:void 0});break;case"CLICK":{if(Ar(n.target)){await this.browser.clickUsingVisualCoordinates(n.target.pixels,n);break}let g=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:x=>this.browser.click(x,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 Mc(g,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(Ar(n.fromTarget)&&Ar(n.toTarget)){await this.browser.dragAndDropUsingVisualCoordinates(n.fromTarget.pixels,n.toTarget.pixels,{hoverSeconds:n.hoverSeconds});break}if(Ar(n.fromTarget)||Ar(n.toTarget))throw new Error("Drag and drop targets must be both coordinates or both descriptions");let{elementInteractedDisplayStrings:g,thoughts:h}=await this.wrapMultiElementTargetingCommand({ctx:e,tracer:t,command:n,targetNames:["fromTarget","toTarget"],descriptions:[n.fromTarget,n.toTarget],caches:[n.cache?.fromTarget,n.cache?.toTarget],action:(f,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:g[0],thoughts:h}}case"MOUSE_DRAG":{let g=parseInt(n.deltaX),h=parseInt(n.deltaY),f=n.steps??5;if(isNaN(g)||isNaN(h))throw new C("ActionFailureError",`Invalid pixel values passed to mouse drag command: (${n.deltaX}, ${n.deltaY})`);if(n.target&&Ar(n.target)){await this.browser.mouseDragUsingVisualCoordinates(g,h,f,n.target.pixels,{force:n.force});break}let E,b;if(n.target?.elementDescriptor){let{elementInteractedDisplayString:x,thoughts:T}=await this.wrapElementTargetingCommand({ctx:e,tracer:t,command:n,target:n.target,cache:n.cache?.target,action:async v=>this.browser.mouseDrag(g,h,f,v.locator,{force:n.force}),options:{disableCache:i,targetName:"target",...n}});E=x,b=T}else await this.browser.mouseDrag(g,h,f,void 0,{force:n.force});return{succeedImmediately:!1,urlAfterCommand:this.browser.url(),elementInteracted:E,thoughts:b}}case"SELECT_OPTION":{if(!on(n.target))throw new Error("Select with x/y is not supported yet");let g=n.target.elementDescriptor,h=n.choice,{elementInteractedDisplayString:f,thoughts:E}=await this.wrapElementTargetingCommand({ctx:e,tracer:t,command:n,target:{type:"description",elementDescriptor:g},cache:n.cache?.target,action:b=>this.browser.selectOption(b,h,n.force),options:{...n,targetName:"target",disableCache:i,source:ta(n)}});return{succeedImmediately:!1,urlAfterCommand:this.browser.url(),elementInteracted:f,thoughts:E}}case"TAB":{let g={loadTimeoutMs:n.loadTimeout?n.loadTimeout*1e3:void 0,retry:!0};await this.browser.switchToPage(n.action,g);break}case"NEW_TAB":await this.browser.createNewTab(n.url,{loadTimeoutMs:n.loadTimeout?n.loadTimeout*1e3:void 0});break;case"COOKIE":if(!n.value)break;let u=await this.browser.setCookie(n.value);a.debug({results:u},"Set cookies");break;case"LOCAL_STORAGE":if(!n.value||!n.key)break;await this.browser.setLocalStorage(n.key,n.value);break;case"JAVASCRIPT":{let g;try{n.environment==="BROWSER"?(g=await this.browser.evaluateCodeInPage({code:n.code,fragment:n.fragment??!1,context:o.toObjectCopy(),timeoutMs:n.timeout?n.timeout*1e3:void 0}),a.info({result:g},"Executed JavaScript in browser")):g=await Ur({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 C("ActionFailureError",h instanceof Error?h.message:`${h}`,{errOptions:{cause:h}})}try{JSON.stringify(g)}catch(h){throw new C("ActionFailureError",`Return value is not serializable: ${h instanceof Error?h.message:`${h}`}`,{errOptions:{cause:h}})}return{urlAfterCommand:this.browser.url(),succeedImmediately:!1,data:g}}case"TYPE":{if(n.target&&Ar(n.target)){await this.browser.clickUsingVisualCoordinates(n.target.pixels,n),await this.browser.type(n.value,{force:n.force,clearContent:n.clearContent,forceClearContent:n.forceClearContent,delay:n.delay,pressEnter:n.pressEnter},!0);break}let g=this.browser.url(),h,f,E=CR(n.target),b=this.browser.userBrowserSettings.globalLocatorRedirect===void 0||this.browser.userBrowserSettings.globalLocatorRedirect==="always";if(E){let{elementInteractedDisplayString:T,thoughts:v}=await this.wrapElementTargetingCommand({ctx:e,tracer:t,command:n,target:E,cache:n.cache?.target,action:O=>this.browser.typeIntoTarget(n.value,O,{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:ta(n)}});h=T,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 x={urlAfterCommand:this.browser.url(),succeedImmediately:!1,elementInteracted:h,thoughts:f};return Mc(g,x.urlAfterCommand)&&(x.succeedImmediately=!0,x.succeedImmediatelyReason="URL changed"),x}case"HOVER":{if(Ar(n.target)){await this.browser.hoverUsingVisualCoordinates(n.target.pixels);break}let{elementInteractedDisplayString:g,thoughts:h}=await this.wrapElementTargetingCommand({ctx:e,tracer:t,command:n,target:n.target,cache:n.cache?.target,action:f=>this.browser.hover(f),options:{...n,targetName:"target",disableCache:i}});return{succeedImmediately:!1,urlAfterCommand:this.browser.url(),elementInteracted:g,thoughts:h}}case"FOCUS":{if(!on(n.target))throw new Error("Focus with x/y is not supported yet");let{elementInteractedDisplayString:g,thoughts:h}=await this.wrapElementTargetingCommand({ctx:e,tracer:t,command:n,target:n.target,cache:n.cache?.target,action:f=>this.browser.focus(f),options:{...n,targetName:"target",disableCache:i}});return{succeedImmediately:!1,urlAfterCommand:this.browser.url(),elementInteracted:g,thoughts:h}}case"BLUR":{if(n.target&&!on(n.target))throw new Error("Blur with x/y is not supported yet");if(!n.target||!n.target.elementDescriptor)return await this.browser.blur(null),{succeedImmediately:!1,urlAfterCommand:this.browser.url()};let{elementInteractedDisplayString:g,thoughts:h}=await this.wrapElementTargetingCommand({ctx:e,tracer:t,target:n.target,command:n,cache:n.cache?.target,action:f=>this.browser.blur(f),options:{...n,targetName:"target",disableCache:i}});return{succeedImmediately:!1,urlAfterCommand:this.browser.url(),elementInteracted:g,thoughts:h}}case"PRESS":let d=this.browser.url();await this.browser.press(n.value,{repeat:n.repeat,convertMeta:n.convertMeta??!0,delayMs:n.delayMs});let m={urlAfterCommand:this.browser.url(),succeedImmediately:!1};return Mc(d,m.urlAfterCommand)&&(m.succeedImmediately=!0,m.succeedImmediatelyReason="URL changed"),m;case"KEY_DOWN":return await this.browser.keyDown(n.value,{convertMeta:n.convertMeta??!0}),{urlAfterCommand:this.browser.url(),succeedImmediately:!1};case"KEY_UP":return await this.browser.keyUp(n.value,{convertMeta:n.convertMeta??!0}),{urlAfterCommand:this.browser.url(),succeedImmediately:!1};case"REQUEST":{let g=new bB,h=yB(fetch,g),f;try{f=new URL(n.url).hostname}catch{}return{data:{...await qc({command:n,baseUrl:this.browser.baseUrl,logger:a,fetchImplementation:h}),cookies:Js(g,f)},succeedImmediately:!1,urlAfterCommand:this.browser.url()}}case"GRAPHQL_REQUEST":return{data:await RR({command:n,baseUrl:this.browser.baseUrl,logger:a}),succeedImmediately:!1,urlAfterCommand:this.browser.url()};case"VISUAL_DIFF":return vR({ctx:e,tracer:t,command:n,disableCache:i,browser:this.browser,logger:a,storage:this.storage,screenshotStorage:this.visualDiffScreenshotStorage,targetingWrapper:g=>this.wrapElementTargetingCommand(g)});case"FILE_UPLOAD":{let g,h;if(n.fileSource.type==="URL"?(h=n.fileSource.url,g=await qA({uri:n.fileSource.url,logger:a,orgId:this.orgId})):n.fileSource.type==="USER_FILE"&&(h=n.fileSource.name,g=await this.uploadedFileStorage?.getFileForUpload(n.fileSource.name,this.orgId)),!g)throw new C("UserConfigurationError",`Attempted to use non-existent file for upload step: ${h}`);await this.browser.setFileChooserHandler({...g,filename:n.filename});break}case"AUTH_SAVE":return{data:await this.browser.saveAuthState(),succeedImmediately:!1,urlAfterCommand:this.browser.url()};case"AUTH_LOAD":{let g;if(!n.storageState.trim())g=void 0;else if(g=await Ur({orgId:this.orgId,code:n.storageState,fragment:!1,context:o,logger:a,localTools:this.localCodeEvalTools,signal:this.executeAbortController.signal}),typeof g!="object")throw new C("ActionFailureError",`Credentials must evaluate to an object (received ${typeof g} instead)`);let h;try{h=xS.optional().parse(g)}catch(f){throw new C("ActionFailureError",`Credentials provided do not follow the required format: ${f}`)}await this.browser.loadAuthState(h);break}case"ELEMENT_CHECK":{let g=(n.timeout??wr)*1e3,h=this.generator.getAgentConfig()?.assertion;if(ER(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 jc({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&&vc(n,E.cache?.memory.traces,a)}}let f=await bR({command:n,tracer:t,timeoutMs:g,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 g=await ur({action:async()=>wR({assertion:n.assertion,browser:this.browser,logger:a,timeout:n.timeout,signal:this.executeAbortController.signal,autoExpandIframes:!!this.browser.userBrowserSettings.autoExpandIframes}),frameConfig:n.iframeUrl?{type:"url",url:n.iframeUrl}:void 0,browser:this.browser,logger:a});return{fail:!g.success,data:g.data,thoughts:g.success?"Page assertion passed.":g.err?.message??`Page assertion still failing after ${n.timeout} seconds.`,urlAfterCommand:this.browser.url(),succeedImmediately:!1}}case"REGISTER_REQUEST_LISTENER":{let g=new Mn(n.requestMatcher),h=this.browser.registerRequestListener(g);return this.registeredListeners[n.key]=h.then(async f=>await Bp(f)).catch(f=>{a.error({err:f},"Failed to get request listener response")}),{succeedImmediately:!1,urlAfterCommand:this.browser.url()}}case"AWAIT_LISTENER":{let g=this.registeredListeners[n.key];if(!g)throw new C("ActionFailureError",`No listener registered with key: ${n.key}`);let h=n.timeout??10;return{data:await k(g,{milliseconds:h*1e3,message:`Request listener timed out after ${h} seconds`}),succeedImmediately:!1,urlAfterCommand:this.browser.url()}}case"RECORD_REQUESTS":{let g=new Mn(n.requestMatcher);return this.recordedRequests[n.key]={},this.browser.registerRequestRecorder(n.key,g,{onRequestStart:(h,f)=>{this.recordedRequests[n.key][h]=Lc(f)},onRequestComplete:(h,f)=>{this.recordedRequests[n.key][h]=Lc(f)}}),{succeedImmediately:!1,urlAfterCommand:this.browser.url()}}case"GET_RECORDED_REQUESTS":{let g=this.recordedRequests[n.key];if(!g)throw new C("ActionFailureError",`No recorder registered with key: ${n.key}`);return delete this.recordedRequests[n.key],{data:Object.values(g),succeedImmediately:!1,urlAfterCommand:this.browser.url()}}case"SET_HEADER":{let g;return n.requestMatcher&&(g=new Mn(n.requestMatcher)),this.browser.setHeader(n.name,n.value,g),{succeedImmediately:!1,urlAfterCommand:this.browser.url()}}case"MOCK_ROUTE":return{data:{key:this.browser.registerMock(n.key,new Mn(n.requestMatcher),async(h,f)=>{let E=await Ur({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=jS.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(g=>{throw"If Typescript complains about the line below, you missed a case or break in the switch above"})(n)}return{succeedImmediately:!1,urlAfterCommand:this.browser.url()}}async getReverseMappedDescription({browserState:e,targetId:t,disableCache:n,screenshot:o}){return(await this.generator.getReverseMappedDescription({browserState:e,target:t,screenshot:o},{disableCache:n,abortSignal:this.executeAbortController.signal,loggerTags:ge(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 Bc({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:ge(this.logger)})}async getFailureRecoveryPlan(e){return this.generator.getFailureRecoveryPlan(e,{disableCache:!0,abortSignal:this.executeAbortController.signal,loggerTags:ge(this.logger)})}};import{cloneDeep as EB}from"lodash-es";import IR from"truncate-json";var xR=1e3,MR=5e6,TB=5*1024*1024;function OR(r,e){for(let t=0;t<r.length;t++){let n=r[t];try{if(n.data){let{jsonString:o}=IR(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),OR(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 PR(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 Xc(r,e){let t=EB(r);if(OR(t,e),t.length>xR)return e.error("Database content violation: results too long, truncating before insertion"),t.slice(0,xR);let n=PR(t,e);if(n.length>MR)for(e.error({serializedLength:n.length,resultsArrayLength:t.length},"Database content violation: results too large, truncating before insertion");n.length>MR;)t.pop(),n=PR(t,e);let{jsonString:o}=IR(n,TB);try{return tr.array().parse(JSON.parse(o))}catch(i){throw e.error({serialized:n,err:i},"Could not parse serialized results into JSON structure after processing"),i}}import{AsyncLocalStorage as vB}from"async_hooks";var ts=new vB;function AB(r){ts.enterWith({activeTracers:[r]})}function wB(r,e){let t=ts.getStore()?.activeTracers;if(!t)return e();t.push(r);try{return e()}finally{t.pop()}}async function RB(r,e){let t=ts.getStore()?.activeTracers;if(!t)return e();let n=[...t,r];return ts.run({activeTracers:n},e)}var Qr={globalAls:ts,initializeRootTracerContext:AB,withChildTracer:wB,withChildTracerAsync:RB};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 Qr.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 Qr.withChildTracerAsync(i,()=>k(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 Qr.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 k(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 Te(){let r=Qr.globalAls.getStore()?.activeTracers,e;return!r||r.length===0?e=void 0:e=r[r.length-1],e||new mo}async function LR(r){let{driver:e,abortSignal:t,logger:n,packageName:o}=r,i;try{i=await k(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=CB(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 CB(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)}import{mkdirSync as jB}from"fs";import{tmpdir as WB}from"os";import HR from"path";import{diff as GB}from"deep-object-diff";import{cloneDeep as VB}from"lodash-es";import kR from"fontoxpath";import xB from"@prettier/plugin-xml";import MB from"prettier";import{DOMParser as _B,XMLSerializer as PB}from"slimdom";var IB=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 rs(r){let e=r.toLowerCase();return e.endsWith("webview")||IB.has(e)}function OB(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 LB=new Set(["index","package","a11y-important","screen-reader-focusabl"]),NB=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"]),DB=new Set(["text","hint"]),kB=new Set(["live-region","drawing-order"]),UB=new Set(["displayed","enabled"]);function FB(r,e){let t={};for(let[n,o]of Object.entries(e))LB.has(n)||n==="class"&&r===o||n==="focusable"&&o==="true"&&e.clickable==="true"||NB.has(n)&&o==="false"||DB.has(n)&&o===""||UB.has(n)&&o==="true"||kB.has(n)&&o==="0"||n!=="id"&&(t[n]=o);return t}function NR(r,e,t){let{prunedDocument:n,idToElement:o,prunedIdToElement:i,idCounter:a,opts:s}=r,c=a.value++;t.setAttribute("id",String(c));let l={};for(let m of e.attributes){let p=m.name,g=m.value;g!=null&&(l[p]=String(g))}let u=FB(e.tagName,l);for(let[m,p]of Object.entries(u))t.setAttribute(m,p);if(o.set(c,e),i.set(c,t),rs(e.tagName)){let m=s?.injectedWebviewContent??"";if(s?.removeWebviewContent){for(;t.firstChild;)t.removeChild(t.firstChild);return}else if(!s?.disableMomenticAccessibilityTree&&m.trim().length>0){for(;t.firstChild;)t.removeChild(t.firstChild);m.trim().length>0&&t.appendChild(n.createCDATASection(`
|
|
4154
|
+
${r}`;default:return r}}var iB=15;async function jc({command:r,aiPageFiltering:e,logger:t,fixtures:n,source:o,useMemory:i,maxRetries:a=iB}){if(!r.assertion.trim())throw new C("ActionFailureError","Assertion command is missing the assertion content");let{browser:s}=n,c=r.timeout?r.timeout*1e3:s.smartWaitingTimeout,l=Cc(c),u=0,d=Date.now(),m,p,g;try{await ur({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 X(l,n.abortSignal),h=Date.now();let f=!1;try{if(m=await ur({action:async()=>{let b=await gR(s,t,n.abortSignal);return p&&p.serializedTree===b.serializedTree&&p.screenshotBuff.equals(b.screenshotBuff)?(f=!0,m):(p=b,hR({command:r,state:b,fixtures:n,useMemory:i,useConsensus:!1,highlightElementsOnFailure:!1,attemptNumber:u,aiPageFiltering:e,logger:t,source:o}))},frameConfig:r.iframeUrl?{type:"url",url:r.iframeUrl}:void 0,logger:t,browser:s}),m?.updatedMemory&&vc(r,m.updatedMemory,t),m?.success)break;throw m?.thoughts?new C("AssertionFailureError",m.thoughts):new C("InternalPlatformError","No thoughts were provided for AI assertion failure")}catch(E){n.abortSignal.throwIfAborted(),g=E instanceof Error?E:new Error(`${E}`),f?t.info(`AI check attempt ${u} failed (re-used previous result)`):t.info({err:E},`AI check assert attempt ${u} failed, retrying...`)}finally{u++}}if(!m?.success)try{m=await ur({action:async()=>hR({command:r,state:await gR(s,t,n.abortSignal),fixtures:n,useMemory:i,useConsensus:!0,highlightElementsOnFailure:!0,attemptNumber:u,aiPageFiltering:e,logger:t}),frameConfig:r.iframeUrl?{type:"url",url:r.iframeUrl}:void 0,logger:t,browser:s})}catch(f){n.abortSignal.throwIfAborted(),g=f instanceof Error?f:new Error(`${f}`)}finally{u++}if(!m?.success){let f=`AI check still failing after ${u} attempts.`;throw g&&(f+=` Latest result: ${g.message}`),new C("AssertionFailureError",f)}return{...m,succeedImmediately:!1,urlAfterCommand:s.url()}}async function gR(r,e,t){let[n,o]=await Promise.all([Hr(r,{abortSignal:t,skipWait:!0,skipWaitForPageLoad:!0,logger:e}),r.screenshot({retries:1,respectActiveFrame:!0})]);return{...n,screenshotBuff:o}}async function hR({command:r,state:e,fixtures:t,useConsensus:n,useMemory:o,highlightElementsOnFailure:i,aiPageFiltering:a,attemptNumber:s,source:c,logger:l}){let{browser:u,generator:d,abortSignal:m}=t,p={type:"ASSERTION"},{serializedTree:g,tree:h}=e,f=e.screenshotBuff,E=f.toString("base64"),b=u.url(),x=r.contextChoice??"MULTIMODAL",T=g;x!=="VISION_ONLY"&&(T=await uo({type:"assertion",serializedTree:g,tree:h,description:r.assertion,screenshot:E,options:{aiPageFiltering:a},fixtures:{generator:d,signal:m,logger:l,orgId:t.orgId}}),T!==g&&(p.ragUsed=!0),p.pageState=T);let v={goal:r.assertion,url:b,memory:o?r.cache?.memory:void 0,browserState:T,screenshot:E,contextChoice:x,source:c},w=await(x==="VISION_ONLY"?(D,j)=>d.getVisualAssertionResult(D,j):(D,j)=>d.getAssertionResult(D,j))(v,{useConsensus:n,attemptNumber:s,useMemory:o,disableCache:!!r.disableCache,abortSignal:m,logger:l,loggerTags:ge(l)});return(w.result||i)&&w.relevantElements&&(p.relevantElementsSerialized=w.relevantElements.map(D=>u.getSerializedFormFromA11yId(D)).filter(D=>!!D),await aB(w.relevantElements,u,l)),{success:w.result,thoughts:w.thoughts,afterScreenshotOverride:f,updatedMemory:o?w.updatedMemory:void 0}}async function aB(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 k(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 sB=75e4,Wc=class extends Error{constructor(){super("The page content exceeds the maximum token limit for AI smart waiting."),this.name="ExceededMaxAISmartWaitingTokensError"}};async function fR(r,e){let{logger:t}=r,{abortSignal:n,browser:o}=e,i=Date.now();try{await lB(i,r,e)}catch(a){if(a instanceof Error&&(a.name==="AbortError"||a.name==="TimeoutError")||n.aborted)return;a instanceof Wc?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 X(s,n)}finally{t.debug({durationMs:Date.now()-i},"AI smart waiting complete")}}async function lB(r,e,t){let{abortSignal:n,browser:o}=t;if(o.smartWaitingTimeout<3e3){await X(o.smartWaitingTimeout,n);return}if(!e.description)throw new C("UserConfigurationError","Cannot locate element with empty description");await k(cB(r,e,t),{milliseconds:o.smartWaitingTimeout})}async function cB(r,e,t){let{logger:n,iframeUrl:o}=e,{browser:i}=t;for(;Date.now()-r<i.smartWaitingTimeout;)if(await ur({action:async()=>uB(e,t),frameConfig:o?{type:"url",url:o}:void 0,browser:i,logger:n}))return}async function uB(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 Ka({orgId:l,s:d,context:t,localTools:c,signal:s,logger:n}));let{serializedTree:m}=await Hr(a,{allowNotActionableNodesOverride:i,filterByViewport:o,abortSignal:s,logger:n});if(Er(m)>sB)throw new Wc;s.throwIfAborted();let g;try{g=await a.screenshot({clearHighlights:!0,respectActiveFrame:!0,retries:2})}catch(b){throw new C("ActionFailureError",`Failed to take screenshot of page to perform smart waiting. The page may be unresponsive, or your machine might be severely resource constrained. Error: ${b instanceof Error?b.message:b}`)}let f=`data:image/jpeg;base64,${g.toString("base64")}`;s.throwIfAborted();let E=await u.getSmartWaitingDecision({browserState:m,description:d,screenshot:f},{abortSignal:s,loggerTags:ge(n)});return n.debug({result:E},"Got smart waiting result"),E.isPageReady}import{cloneDeep as yR}from"lodash-es";async function bR(r){let{command:e,timeoutMs:t,fixtures:n}=r,{abortSignal:o}=n,i=()=>bh(e.cache)?e.cache:void 0,a=i(),s=yR(a),c=(h=!1)=>{if(a=i(),!!a)if(h){let f=Kv(s,a);a.target=f.target,a.updatedAt=f.updatedAt}else{if(!s){a=void 0;return}a.target=s.target,a.updatedAt=s.updatedAt}},l=Date.now(),u=0,d,m=500,p=!1;for(;u<2||Date.now()-l<t;){u++,u>1&&await X(m,o),o?.throwIfAborted(),a=i();let{result:h,elementWasFound:f}=await SR({cacheToUse:a,params:r});if(d=h,p=f,h.success)break;c(),m=Math.min(m*2,1e4)}if(!d)throw new C("InternalPlatformError",`Failed to evaluate manual element assertion in ${t}ms.`);if(o?.throwIfAborted(),!d.success&&a?.target&&As(a.target)){let h=a?.target?.memory?{target:{id:-1,memory:a.target.memory}}:void 0,{result:f}=await SR({cacheToUse:h,params:r});d=f,d.success||c(!0)}let g=i();return d.success&&g?.target&&!p&&(g.target=fp(g.target),g.updatedAt=new Date),d}async function SR({cacheToUse:r,params:e}){let{command:t,disableCache:n,fixtures:o,tracer:i,targetingWrapper:a}=e,{logger:s}=o;if(t.target&&!on(t.target))throw new Error("Element assertion with x/y is not supported yet");let c=mB(t.assertion),l,u=!1,d=yR(r);try{let{elementInteractedDisplayString:m,result:p,thoughts:g}=await a({ctx:o.ctx,tracer:i,command:t,target:t.target,cache:d?.target,action:async h=>dB(h.locator,e),options:{...t,allowNotActionableNodesOverride:!0,disableCache:n,memory:d?.target?.memory,disableGlobalLocatorRedirect:!0,source:ta(t),targetName:"target"}});return l={success:p.success,data:p.data,err:p.err,elementInteractedDisplayString:m,thoughts:g},u=!0,p.success||(s.warn({aiThoughts:g,elementString:m,err:p.err},"Element check found an element but failed"),l={...p,thoughts:g}),{result:l,elementWasFound:u}}catch(m){if(c)return l={success:!0,thoughts:`The element described does not exist on the page: ${m.message}`,err:void 0,data:void 0},{result:l,elementWasFound:u};if(!(m instanceof C)||m.reason!="ActionFailureError")throw m;return l={success:!1,err:m,data:void 0,thoughts:void 0},s.warn({err:m},"Element check did not find an element and failed"),{result:l,elementWasFound:u}}}async function dB(r,{command:e,fixtures:t}){let n=e.assertion;await t.browser.highlight(r);let o=!0,i,a;switch(n.type){case"ELEMENT_CONTENT":{let c=await r.textContent()??"";if(a={elementTextContent:Nt(c,500,!0)},!$c(c,n.value,n.operation,!!n.negated)){let l=n.negated?An[n.operation]:wn[n.operation];o=!1,i=new C("AssertionFailureError",`The content ${l} '${n.value}': ${c}`)}break}case"ELEMENT_ATTRIBUTE":{a={elementOuterHtml:Nt(await r.evaluate(l=>l.cloneNode(!1).outerHTML),500,!0)};let c;try{c=await r.getAttribute(n.attr,{timeout:3e3})??""}catch(l){i=new C("AssertionFailureError",`The element does not have an attribute named ${n.attr}: ${l}`),o=!1;break}if(!$c(c,n.value,n.operation,!!n.negated)){let l=n.negated?An[n.operation]:wn[n.operation];o=!1,n.operation==="EXISTS"?i=new C("AssertionFailureError",`The attribute ${n.attr} ${l}`):i=new C("AssertionFailureError",`The attribute ${n.attr} ${l} '${n.value}': ${c}`)}break}case"ELEMENT_EXISTENCE":{switch(n.condition){case"VISIBLE":{o=await r.evaluate(async(l,u)=>{let d=Date.now();for(;Date.now()-d<u;){await new Promise(p=>setTimeout(p,250));let m=l.getBoundingClientRect();if(!(m.width===0||m.height===0)&&window.getComputedStyle(l).visibility!=="hidden"&&window.getComputedStyle(l).display!=="none")return!0}return!1},wr*1e3);break}case"EDITABLE":{o=await r.isEditable({timeout:wr*1e3});break}case"EXISTS":{o=!0;break}case"ENABLED":{o=await r.isEnabled({timeout:wr*1e3});break}case"FOCUSED":{o=await r.evaluate(l=>l===document.activeElement);break}default:return(l=>{throw"If Typescript complains about the line below, you missed a case or break in the switch above"})(n.condition)}if(o=n.negated?!o:o,!o){let c=n.negated?Xv[n.condition]:Jv[n.condition];i=new C("AssertionFailureError",`The element ${c}`)}break}case"ELEMENT_NAME":{let c=await r.evaluate(l=>l.tagName);if(!$c(c,n.value,n.operation,!!n.negated)){let l=n.negated?An[n.operation]:wn[n.operation];o=!1,i=new C("AssertionFailureError",`The element tag name ${l} '${n.value}': ${c}`)}break}case"ELEMENT_STYLE":{let c=await r.evaluate((l,u)=>window.getComputedStyle(l).getPropertyValue(u),n.property);if(!$c(c,n.value,n.operation,!!n.negated)){let l=n.negated?An[n.operation]:wn[n.operation];o=!1,n.operation==="EXISTS"?i=new C("AssertionFailureError",`The style property ${n.property} ${l}`):i=new C("AssertionFailureError",`The style property ${n.property} ${l} '${n.value}': ${c}`)}break}default:return(c=>{throw"If Typescript complains about the line below, you missed a case or break in the switch above"})(n)}return{success:o,data:a,err:i}}function $c(r,e,t,n){let o;switch(t){case"CONTAINS":{o=r.includes(e);break}case"EQUALS":{o=r.trim()===e.trim();break}case"STARTS_WITH":{o=r.trim().startsWith(e);break}case"EXISTS":{o=r.trim().length>0;break}default:return(a=>{throw"If Typescript complains about the line below, you missed a case or break in the switch above"})(t)}return n?!o:o}function mB(r){return r.type==="ELEMENT_EXISTENCE"&&r.negated&&(r.condition==="EXISTS"||r.condition==="VISIBLE")}function ER(r){return r.type==="ELEMENT_EXISTENCE"&&r.negated&&r.condition==="EXISTS"}import{Jimp as pB}from"jimp";async function es(r,e){let t=await r.screenshot(e),n=await pB.fromBuffer(t);return{buffer:t,width:Math.ceil(n.bitmap.width??0),height:Math.ceil(n.bitmap.height??0)}}import{Jimp as TR}from"jimp";import lg from"jpeg-js";import gB from"pixelmatch";async function vR({ctx:r,tracer:e,command:t,disableCache:n,browser:o,targetingWrapper:i,logger:a,screenshotStorage:s}){if(t.target&&!on(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 ee=>es(o,{locator:ee.locator,...c}),options:{...t,disableCache:n,disableGlobalLocatorRedirect:!0,memory:t.cache?.target?.memory,targetName:"target"}})).result:l=await es(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 ie=`${l.width}x${l.height}`,ee=`${u.width}x${u.height}`;return{fail:!0,thoughts:`Current screenshot (${ie}) does not match saved screenshot dimensions (${ee}) - 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 TR.fromBuffer(l.buffer),m={width:l.width,height:l.height},p=await TR.fromBuffer(u.buffer),g={width:u.width,height:u.height},h,f=m.width*m.height,E=g.width*g.height,b=Math.abs(m.height-g.height),x=Math.abs(m.width-g.width);if(f>E){let ie=d.cover({w:g.width,h:g.height});l.buffer=await ie.getBuffer("image/jpeg"),h="current",l.width=g.width,l.height=g.height}else if(E>f){let ie=p.cover({w:m.width,h:m.height});u.buffer=await ie.getBuffer("image/jpeg"),h="saved"}let T={data:Buffer.alloc(l.width*l.height*4),width:l.width,height:l.height},v=t.threshold??.1,w=gB(lg.decode(u.buffer).data,lg.decode(l.buffer).data,T.data,l.width,l.height,{threshold:v,diffColorAlt:[0,255,0]})/(l.width*l.height)*100,D=w>v*100,j=`Visual diff of ${w.toFixed(2)}% detected, which is ${D?"over":"under"} the threshold of ${v*100}%.`;if(h&&(j+=` The ${h} screenshot was cropped since it was taller by ${b} pixels and wider by ${x} pixels.`),D)throw new C("ActionFailureError",j);return{fail:D,thoughts:j,beforeScreenshotOverride:l.buffer,afterScreenshotOverride:lg.encode(T,75).data,succeedImmediately:!1,urlAfterCommand:o.url()}}var hB=3e4;async function qc({command:r,logger:e,baseUrl:t,fetchImplementation:n=fetch}){let o=r.timeout??hB/1e3,i=Object.fromEntries(Object.entries(r.headers||{}).filter(([p,g])=>p&&g)),a=new URLSearchParams;Object.entries(r.params||{}).filter(([p,g])=>p&&g).forEach(([p,g])=>{a.append(p,g)});let s=a.toString(),c;if(ci(r.url)&&(c=r.url),t&&ui(r.url,t)&&(c=new URL(r.url,t).toString()),!c)throw new C("ActionFailureError",`Invalid URL: ${r.url}`);e.info({url:c,searchParams:s,headers:i,body:r.body,method:r.method},"Making HTTP request");let u=await k((async()=>{let p=s?`${c}?${s}`:c;try{return await n(p,{headers:i,method:r.method,body:r.body})}catch(g){throw e.error({err:g},"Failed to make HTTP request"),new Error(`Failed to make HTTP request: ${g}`)}})(),{milliseconds:o*1e3,fallback:()=>{throw new C("ActionFailureError",`Fetch request timed out after ${o} seconds`)}});if(!u.ok){let p;try{p=await u.text()}catch(g){p=`Failed to read response body: ${g}`}throw new C("ActionFailureError",`Fetch request failed with status ${u.status}: ${p}`)}let d={};u.headers.forEach((p,g)=>{d[g]=p});let m={status:u.status,headers:d};if(u.headers.get("content-type")?.includes("json"))try{m.json=await u.json()}catch{}else u.headers.get("content-type")?.includes("text")&&(m.text=await u.text());return m}var fB=5e3;async function wR({timeout:r=wr,...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 Kc(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 X(s,e.signal),s=Math.min(Math.floor(s*1.5),fB);else return i}return i=await Kc(e),i}async function Kc({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(AR,{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(AR,{value:r.value,negated:!!r.negated,returnHtml:!0},"checking page content"));if(!i){let c=r.negated?An.CONTAINS:wn.CONTAINS;a=new C("AssertionFailureError",`The page ${c} '${r.value}'.`),o=s}}catch(s){a=new C("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 AR({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 SB=3e4;async function RR({command:r,logger:e,baseUrl:t,fetchImplementation:n=fetch}){let o=r.timeout??SB/1e3,i=new AbortController,a=Object.fromEntries(Object.entries(r.headers||{}).filter(([d,m])=>d&&m));a["Content-Type"]="application/json";let s;if(ci(r.url)&&(s=r.url),t&&ui(r.url,t)&&(s=new URL(r.url,t).toString()),!s)throw new C("ActionFailureError",`Invalid URL: ${r.url}`);let l=await k((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 C("ActionFailureError",`GraphQL request timed out after ${o} seconds`);if(!l.ok){let d,m=await l.text();try{d=JSON.parse(m)}catch{throw new C("ActionFailureError",`GraphQL request failed with status ${l.status}: ${m}`)}throw d?.errors?.length&&d?.errors[0]?.message?new C("ActionFailureError",`GraphQL request failed with status ${l.status}: ${d.errors[0].message}`):new C("ActionFailureError",`GraphQL request failed with status ${l.status}: ${m}`)}let u={};return l.headers.forEach((d,m)=>{u[m]=d}),{status:l.status,headers:u,json:await l.json()}}var Yc=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([Hr(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 uo({type:"ai-action",description:e,screenshot:u,serializedTree:c.serializedTree,tree:c.tree,options:{aiPageFiltering:!!this.options?.aiPageFiltering},fixtures:{generator:this.generator,signal:this.executeAbortController.signal,logger:s,orgId:this.orgId}}),m={url:this.browser.url(),browserState:d,startingScreenshot:t,history:n,goal:e,screenshot:u,lastError:a};return await this.generator.getMultiturnAiActionEvaluation(m,{disableCache:o,abortSignal:this.executeAbortController.signal,loggerTags:{...ge(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([Hr(this.browser,{abortSignal:this.executeAbortController.signal,skipWait:!0,skipWaitForPageLoad:!0,logger:a}),this.browser.screenshot({retries:1,clearHighlights:!0})]),d=`data:image/jpeg;base64,${u.toString("base64")}`,m=await uo({type:"ai-action",description:e,screenshot:d,serializedTree:l.serializedTree,tree:l.tree,options:{aiPageFiltering:!!this.options?.aiPageFiltering},fixtures:{generator:this.generator,signal:this.executeAbortController.signal,logger:a,orgId:this.orgId}}),p={url:c,browserState:m,startingScreenshot:t,history:n,goal:e,actionHint:o,screenshot:d};try{return await this.generator.getMultiturnAiActionCommand(p,{disableCache:i,abortSignal:this.executeAbortController.signal,loggerTags:{...ge(a)},langfuseSessionId:s})}catch(g){throw new C("InternalWebAgentError",`Error generating command: ${g instanceof Error?g.message:g}`,{errOptions:{cause:g}})}}async getBrowserState(e){return Hr(this.browser,e)}async locateElement(e){return await sg({...e,aiPageFiltering:!!this.options?.aiPageFiltering},this.getControllerFixtures())}async locateElementWithSelector(e,t){return ur({action:async()=>{let n=await this.browser.resolveHardcodedCssSelector({ctx:null,selector:e,timeoutMs:2e3,logger:this.logger});return{thoughts:"Located element with selector",target:{id:-1,selector:e,targetSource:"USER_CSS_SELECTOR",targetUpdateTime:new Date().toUTCString()},resolution:n}},frameConfig:t?{type:"url",url:t}:void 0,browser:this.browser,logger:this.logger})}getControllerFixtures(e){return{ctx:e??null,browser:this.browser,generator:this.generator,logger:this.logger,orgId:this.orgId,storage:this.storage,localCodeEvalTools:this.localCodeEvalTools,abortSignal:this.executeAbortController.signal}}shouldUseMemory(){return this.options?.useMemory??(this.orgId==="org_01HMSCJQBCCG51M2ZF65YC5B8W"||this.orgId==="org_01HMJTX4GT1KG94KZRCT8MZ6YB")}async wrapMultiElementTargetingCommand({ctx:e,tracer:t,command:n,targetNames:o,descriptions:i,caches:a,action:s,options:c,retriesWithAI:l=1}){let u=[];for(let d=0;d<i.length;d++){let m=i[d],p=await this.wrapElementTargetingCommand({ctx:e,tracer:t,command:n,target:m,cache:a[d],action:async g=>g,options:{...c,targetName:o[d]}});u.push(p)}try{let d=await s(...u.map(g=>g.result)),m=g=>g==="fromTarget"?"From Target":g==="toTarget"?"To Target":"Target",p=u.map((g,h)=>g.thoughts?`${m(o[h])}: ${g.thoughts}`:void 0).filter(g=>!!g).join(" -------------- ")||void 0;return{result:d,elementInteractedDisplayStrings:u.map(g=>g.elementInteractedDisplayString),thoughts:p}}catch(d){if(this.throwIfClosed(),l>0)return this.logger.warn({err:d},"Failed to execute action with multiple cached targets, retrying with AI"),this.wrapMultiElementTargetingCommand({ctx:e,tracer:t,command:n,targetNames:o,descriptions:i,caches:i.map(()=>{}),action:s,options:c,retriesWithAI:l-1});throw new C("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 ur({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&&qu(i)){t.warn({err:i},"Invalid mpath error, retrying element targeting command");continue}if(!this.browser.userBrowserSettings.visualActions&&(Xu(i)||Ku(i))){t.warn({err:i},"Invalid momentic id error, retrying element targeting command");continue}if(Ju(i)){t.warn({err:i},"Invalid backend node id error, retrying element targeting command");continue}if(i instanceof xr&&i.retryableWithAI){t.warn({err:i},"Element cache disqualification error, retrying element targeting command");continue}throw i}throw n instanceof C?n:new C("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 C("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 X(500)}}throw c}async wrapElementTargetingCommandHelper(e){let{ctx:t,tracer:n,target:o,originalCache:i,action:a,options:s,command:c}=e,{disableCache:l,useSelector:u,targetName:d,targetHealingInProgress:m,source:p}=s,g=this.logger.child({commandId:c.id}),h=this.shouldUseMemory(),f=s.retriesWithAI??1,E=!1,b=CR(e.cache);if((!b||l)&&!Pu(o))throw new C("ActionFailureError","Cannot target element with no cached data or element descriptor");if(u)return this.wrapHardcodedCssTargetingCommandHelper(e);l&&(g.info("Cache explicitly disabled for this step"),E=!0,b=void 0),b&&this.browser.userBrowserSettings.disableSecondaryCacheResolution&&b.targetSource==="HEURISTIC_HEALED"&&(E=!0,b=void 0),b?.inputDescription&&!pR(o.elementDescriptor,b.inputDescription)&&(g.warn({old:b.inputDescription,new:o.elementDescriptor},"Target cache was generated with a different description, clearing it automatically"),E=!0,b=void 0);let x=v=>!!v&&As(v),T=!0;if(!x(b)){T=!1,g.info({description:o.elementDescriptor,targetHealingInProgress:m,cacheBustedBeforeAction:E,memory:s.memory,useMemory:h},"Prompting AI for an updated element location"),(E||!i)&&await fR({description:o.elementDescriptor,iframeUrl:s.iframeUrl,source:p,logger:g,allowNotActionableNodesOverride:s.allowNotActionableNodesOverride},this.getControllerFixtures(t)),f--;let v;try{v=await sg({description:o.elementDescriptor,disableCache:!!s.disableCache,iframeUrl:s.iframeUrl,source:p,useMemory:h,memory:h?s.memory:void 0,aiPageFiltering:!!this.options?.aiPageFiltering,allowNotActionableNodesOverride:s.allowNotActionableNodesOverride,logger:g},this.getControllerFixtures(t))}catch(D){if(D instanceof Io&&D.updatedLocatorMemory){let j={id:-1,...i,memory:D.updatedLocatorMemory};Tc({cmd:c,key:d,newTarget:j,logger:g,updatedWithAI:!0})}throw new C("ActionFailureError",D.message)}v.frameConfig&&this.browser.setActiveFrameConfig(v.frameConfig);let O=s.disableGlobalLocatorRedirect?{locator:v.resolution.locator}:await this.attemptLocatorRedirect(v.resolution.locator,g),w=await a(O);return Tc({cmd:c,key:d,newTarget:v.target,logger:g,updatedWithAI:!0}),m&&(n.recordTargetAutoHeal({healType:"AI"}),v.target.targetSource="AI_HEALED",v.target.targetUpdateTime=new Date().toUTCString(),v.target.targetUpdateLoggerTags=ge(g)),{result:w,elementInteractedDisplayString:v.resolution.displayString,thoughts:v.thoughts}}try{let v=await this.browser.resolveTarget(t,b,{allowNotActionableNodesOverride:s.allowNotActionableNodesOverride,targetName:d,logger:g,signal:this.executeAbortController.signal});(this.browser.userBrowserSettings.visualActions||this.browser.userBrowserSettings.globalLocatorRedirect!==!1)&&await this.browser.scrollIntoViewIfNeeded(v.locator);let O=s.disableGlobalLocatorRedirect?{locator:v.locator}:await this.attemptLocatorRedirect(v.locator,g),w=await a(O);if(ft.increment("cache_target_resolution_v2",1,["outcome:hit","platform:web",`hasRequirements:${!!b.requirements}`,`hasAdditionalElements:${!!b.additionalElements}`,`orgId:${this.orgId}`,"cliVersion:0.7.1"]),Tc({cmd:c,key:d,newTarget:b,logger:g,updatedWithAI:!1}),T){let D=v.decisions.filter(j=>j.matched);if(D.length!==1)g.warn({decisions:v.decisions},"Expected exactly 1 matching method for element location, got more or less");else{let j=D[0].type;n.recordTargetAutoHeal({healType:j})}}return{result:w,elementInteractedDisplayString:v.displayString}}catch(v){this.throwIfClosed();let O="unknown";v instanceof Cr&&v.cacheMissReason&&(O=v.cacheMissReason),ft.increment("cache_target_resolution_v2",1,["outcome:miss","platform:web",`hasRequirements:${!!b.requirements}`,`hasAdditionalElements:${!!b.additionalElements}`,`orgId:${this.orgId}`,"cliVersion:0.7.1",`missReason:${O}`]);let w=!1;if((v instanceof xr||qu(v)||Xu(v)||Ju(v)||Sf(v)||Ku(v)||yf(v))&&(w=!0),v instanceof C&&!w)throw g.error({err:v},"Failed to execute action with cached target (fatal)"),v;if(f>0&&o){g.info({err:v},"Failed to execute action with cached target, retrying with AI");let D;return b.memory&&ph(b.memory)&&(D=b.memory),this.wrapElementTargetingCommand({ctx:t,tracer:n,command:c,target:o,cache:void 0,originalCache:i,action:a,options:{...s,memory:D,retriesWithAI:f,targetHealingInProgress:!0}})}throw new C("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 es(this.browser,e)}async executePresetCommand(e,t,n,o,i){this.options?.slowMoMs&&await X(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 C("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&&Dh(n)?await this.browser.waitForDOMStability({timeout:fe}):!this.browser.userBrowserSettings.visualActions&&["PRESS","TYPE"].includes(n.type)&&await this.browser.waitForDOMStability({timeout:Q}),this.options?.autoFollowNewTabs&&await oR({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{Ec(n,c)}}createCallbacksForBrowser(e){return{createIsolatedFolder:()=>Lp(e)}}async resolveCommandTemplateStrings(e,t){return bc({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()?jc({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 C("ActionFailureError","Missing assertion");if(n.timeout&&n.timeout>1800)throw new C("AssertionFailureError",`AI check timeout of ${n.timeout} exceeds the maximum allowed value of 30 minutes.`);return jc({command:n,fixtures:this.getControllerFixtures(e),useMemory:this.shouldUseMemory(),aiPageFiltering:!!this.options?.aiPageFiltering,logger:a})}case"AI_EXTRACT":{if(!n.goal.trim())throw new C("ActionFailureError","Cannot perform AI extraction without goal");if(n.schema){let f=ib(n.schema);if(f)throw new C("UserConfigurationError",f)}let g=await this.browser.getCondensedHtml(),h=await this.browser.screenshot({retries:2});try{let f=await this.generator.getTextExtraction({goal:n.goal,browserState:g,returnSchema:n.schema,screenshot:`data:image/jpeg;base64,${h.toString("base64")}`},{disableCache:i,abortSignal:this.executeAbortController.signal,loggerTags:ge(a)});if(f.result==="NOT_FOUND")throw new C("ActionFailureError","No relevant data found for extraction goal on this page");if(f.thoughts?.includes("MaxGenerationLengthExceededError"))throw new C("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 C("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 C("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(!ci(n.url)&&!ui(n.url,this.browser.baseUrl))throw new C("ActionFailureError",`Invalid URL provided to navigate command: ${n.url}`);await this.browser.navigate({url:n.url,loadTimeoutMs:n.loadTimeout?n.loadTimeout*1e3:void 0});break;case"DIALOG":this.browser.registerDialogHandler(n.action);break;case"CAPTCHA":if(!this.browser.canSolveCaptchas())break;let c=await this.browser.solveCaptcha();c&&(await this.wrapElementTargetingCommand({ctx:e,tracer:t,command:n,target:{type:"description",elementDescriptor:"the captcha image solution input"},cache:void 0,action:g=>this.browser.click(g,this.createCallbacksForBrowser(this.orgId),{}),options:{...n,targetName:"target",disableCache:i}}),await this.browser.type(c,{clearContent:!0,pressEnter:!0},!0));break;case"GO_BACK":await this.browser.goBack();break;case"GO_FORWARD":await this.browser.goForward();break;case"SCROLL_LEFT":case"SCROLL_RIGHT":case"SCROLL_DOWN":case"SCROLL_UP":{let g,h;if(n.target&&Ar(n.target))await this.browser.hoverUsingVisualCoordinates(n.target.pixels);else if(n.target&&n.target.elementDescriptor.trim()){let{elementInteractedDisplayString:b,thoughts:x}=await this.wrapElementTargetingCommand({ctx:e,tracer:t,command:n,target:n.target,cache:n.cache?.target,action:T=>this.browser.hover(T),options:{...n,targetName:"target",disableGlobalLocatorRedirect:!0,disableCache:i}});g=b,h=x}let f=this.browser.getViewport()?.height??cn.height,E=this.browser.getViewport()?.width??cn.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:g,thoughts:h}}case"WAIT_FOR_URL":{if(n.timeout&&n.timeout>1800)throw new C("UserConfigurationError",`Wait for URL timeout of ${n.timeout} exceeds the maximum allowed value of 30 minutes.`);let g=n.matcher;await this.browser.waitForUrl({beforeUrl:this.browser.url(),matcher:g},{timeout:n.timeout?n.timeout*1e3:void 0,negated:n.negated,caseInsensitive:n.caseInsensitive});break}case"WAIT":if(n.delay>1800)throw new C("UserConfigurationError",`Wait timeout of ${n.delay} seconds exceeds the maximum allowed value of 30 minutes`);let l=n.delay*1e3;await X(l,this.executeAbortController.signal);break;case"REFRESH":await this.browser.refresh({loadTimeoutMs:n.loadTimeout?n.loadTimeout*1e3:void 0});break;case"CLICK":{if(Ar(n.target)){await this.browser.clickUsingVisualCoordinates(n.target.pixels,n);break}let g=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:x=>this.browser.click(x,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 Mc(g,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(Ar(n.fromTarget)&&Ar(n.toTarget)){await this.browser.dragAndDropUsingVisualCoordinates(n.fromTarget.pixels,n.toTarget.pixels,{hoverSeconds:n.hoverSeconds});break}if(Ar(n.fromTarget)||Ar(n.toTarget))throw new Error("Drag and drop targets must be both coordinates or both descriptions");let{elementInteractedDisplayStrings:g,thoughts:h}=await this.wrapMultiElementTargetingCommand({ctx:e,tracer:t,command:n,targetNames:["fromTarget","toTarget"],descriptions:[n.fromTarget,n.toTarget],caches:[n.cache?.fromTarget,n.cache?.toTarget],action:(f,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:g[0],thoughts:h}}case"MOUSE_DRAG":{let g=parseInt(n.deltaX),h=parseInt(n.deltaY),f=n.steps??5;if(isNaN(g)||isNaN(h))throw new C("ActionFailureError",`Invalid pixel values passed to mouse drag command: (${n.deltaX}, ${n.deltaY})`);if(n.target&&Ar(n.target)){await this.browser.mouseDragUsingVisualCoordinates(g,h,f,n.target.pixels,{force:n.force});break}let E,b;if(n.target?.elementDescriptor){let{elementInteractedDisplayString:x,thoughts:T}=await this.wrapElementTargetingCommand({ctx:e,tracer:t,command:n,target:n.target,cache:n.cache?.target,action:async v=>this.browser.mouseDrag(g,h,f,v.locator,{force:n.force}),options:{disableCache:i,targetName:"target",...n}});E=x,b=T}else await this.browser.mouseDrag(g,h,f,void 0,{force:n.force});return{succeedImmediately:!1,urlAfterCommand:this.browser.url(),elementInteracted:E,thoughts:b}}case"SELECT_OPTION":{if(!on(n.target))throw new Error("Select with x/y is not supported yet");let g=n.target.elementDescriptor,h=n.choice,{elementInteractedDisplayString:f,thoughts:E}=await this.wrapElementTargetingCommand({ctx:e,tracer:t,command:n,target:{type:"description",elementDescriptor:g},cache:n.cache?.target,action:b=>this.browser.selectOption(b,h,n.force),options:{...n,targetName:"target",disableCache:i,source:ta(n)}});return{succeedImmediately:!1,urlAfterCommand:this.browser.url(),elementInteracted:f,thoughts:E}}case"TAB":{let g={loadTimeoutMs:n.loadTimeout?n.loadTimeout*1e3:void 0,retry:!0};await this.browser.switchToPage(n.action,g);break}case"NEW_TAB":await this.browser.createNewTab(n.url,{loadTimeoutMs:n.loadTimeout?n.loadTimeout*1e3:void 0});break;case"COOKIE":if(!n.value)break;let u=await this.browser.setCookie(n.value);a.debug({results:u},"Set cookies");break;case"LOCAL_STORAGE":if(!n.value||!n.key)break;await this.browser.setLocalStorage(n.key,n.value);break;case"JAVASCRIPT":{let g;try{n.environment==="BROWSER"?(g=await this.browser.evaluateCodeInPage({code:n.code,fragment:n.fragment??!1,context:o.toObjectCopy(),timeoutMs:n.timeout?n.timeout*1e3:void 0}),a.info({result:g},"Executed JavaScript in browser")):g=await Ur({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 C("ActionFailureError",h instanceof Error?h.message:`${h}`,{errOptions:{cause:h}})}try{JSON.stringify(g)}catch(h){throw new C("ActionFailureError",`Return value is not serializable: ${h instanceof Error?h.message:`${h}`}`,{errOptions:{cause:h}})}return{urlAfterCommand:this.browser.url(),succeedImmediately:!1,data:g}}case"TYPE":{if(n.target&&Ar(n.target)){await this.browser.clickUsingVisualCoordinates(n.target.pixels,n),await this.browser.type(n.value,{force:n.force,clearContent:n.clearContent,forceClearContent:n.forceClearContent,delay:n.delay,pressEnter:n.pressEnter},!0);break}let g=this.browser.url(),h,f,E=CR(n.target),b=this.browser.userBrowserSettings.globalLocatorRedirect===void 0||this.browser.userBrowserSettings.globalLocatorRedirect==="always";if(E){let{elementInteractedDisplayString:T,thoughts:v}=await this.wrapElementTargetingCommand({ctx:e,tracer:t,command:n,target:E,cache:n.cache?.target,action:O=>this.browser.typeIntoTarget(n.value,O,{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:ta(n)}});h=T,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 x={urlAfterCommand:this.browser.url(),succeedImmediately:!1,elementInteracted:h,thoughts:f};return Mc(g,x.urlAfterCommand)&&(x.succeedImmediately=!0,x.succeedImmediatelyReason="URL changed"),x}case"HOVER":{if(Ar(n.target)){await this.browser.hoverUsingVisualCoordinates(n.target.pixels);break}let{elementInteractedDisplayString:g,thoughts:h}=await this.wrapElementTargetingCommand({ctx:e,tracer:t,command:n,target:n.target,cache:n.cache?.target,action:f=>this.browser.hover(f),options:{...n,targetName:"target",disableCache:i}});return{succeedImmediately:!1,urlAfterCommand:this.browser.url(),elementInteracted:g,thoughts:h}}case"FOCUS":{if(!on(n.target))throw new Error("Focus with x/y is not supported yet");let{elementInteractedDisplayString:g,thoughts:h}=await this.wrapElementTargetingCommand({ctx:e,tracer:t,command:n,target:n.target,cache:n.cache?.target,action:f=>this.browser.focus(f),options:{...n,targetName:"target",disableCache:i}});return{succeedImmediately:!1,urlAfterCommand:this.browser.url(),elementInteracted:g,thoughts:h}}case"BLUR":{if(n.target&&!on(n.target))throw new Error("Blur with x/y is not supported yet");if(!n.target||!n.target.elementDescriptor)return await this.browser.blur(null),{succeedImmediately:!1,urlAfterCommand:this.browser.url()};let{elementInteractedDisplayString:g,thoughts:h}=await this.wrapElementTargetingCommand({ctx:e,tracer:t,target:n.target,command:n,cache:n.cache?.target,action:f=>this.browser.blur(f),options:{...n,targetName:"target",disableCache:i}});return{succeedImmediately:!1,urlAfterCommand:this.browser.url(),elementInteracted:g,thoughts:h}}case"PRESS":let d=this.browser.url();await this.browser.press(n.value,{repeat:n.repeat,convertMeta:n.convertMeta??!0,delayMs:n.delayMs});let m={urlAfterCommand:this.browser.url(),succeedImmediately:!1};return Mc(d,m.urlAfterCommand)&&(m.succeedImmediately=!0,m.succeedImmediatelyReason="URL changed"),m;case"KEY_DOWN":return await this.browser.keyDown(n.value,{convertMeta:n.convertMeta??!0}),{urlAfterCommand:this.browser.url(),succeedImmediately:!1};case"KEY_UP":return await this.browser.keyUp(n.value,{convertMeta:n.convertMeta??!0}),{urlAfterCommand:this.browser.url(),succeedImmediately:!1};case"REQUEST":{let g=new bB,h=yB(fetch,g),f;try{f=new URL(n.url).hostname}catch{}return{data:{...await qc({command:n,baseUrl:this.browser.baseUrl,logger:a,fetchImplementation:h}),cookies:Js(g,f)},succeedImmediately:!1,urlAfterCommand:this.browser.url()}}case"GRAPHQL_REQUEST":return{data:await RR({command:n,baseUrl:this.browser.baseUrl,logger:a}),succeedImmediately:!1,urlAfterCommand:this.browser.url()};case"VISUAL_DIFF":return vR({ctx:e,tracer:t,command:n,disableCache:i,browser:this.browser,logger:a,storage:this.storage,screenshotStorage:this.visualDiffScreenshotStorage,targetingWrapper:g=>this.wrapElementTargetingCommand(g)});case"FILE_UPLOAD":{let g,h;if(n.fileSource.type==="URL"?(h=n.fileSource.url,g=await qA({uri:n.fileSource.url,logger:a,orgId:this.orgId})):n.fileSource.type==="USER_FILE"&&(h=n.fileSource.name,g=await this.uploadedFileStorage?.getFileForUpload(n.fileSource.name,this.orgId)),!g)throw new C("UserConfigurationError",`Attempted to use non-existent file for upload step: ${h}`);await this.browser.setFileChooserHandler({...g,filename:n.filename});break}case"AUTH_SAVE":return{data:await this.browser.saveAuthState(),succeedImmediately:!1,urlAfterCommand:this.browser.url()};case"AUTH_LOAD":{let g;if(!n.storageState.trim())g=void 0;else if(g=await Ur({orgId:this.orgId,code:n.storageState,fragment:!1,context:o,logger:a,localTools:this.localCodeEvalTools,signal:this.executeAbortController.signal}),typeof g!="object")throw new C("ActionFailureError",`Credentials must evaluate to an object (received ${typeof g} instead)`);let h;try{h=xS.optional().parse(g)}catch(f){throw new C("ActionFailureError",`Credentials provided do not follow the required format: ${f}`)}await this.browser.loadAuthState(h);break}case"ELEMENT_CHECK":{let g=(n.timeout??wr)*1e3,h=this.generator.getAgentConfig()?.assertion;if(ER(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 jc({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&&vc(n,E.cache?.memory.traces,a)}}let f=await bR({command:n,tracer:t,timeoutMs:g,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 g=await ur({action:async()=>wR({assertion:n.assertion,browser:this.browser,logger:a,timeout:n.timeout,signal:this.executeAbortController.signal,autoExpandIframes:!!this.browser.userBrowserSettings.autoExpandIframes}),frameConfig:n.iframeUrl?{type:"url",url:n.iframeUrl}:void 0,browser:this.browser,logger:a});return{fail:!g.success,data:g.data,thoughts:g.success?"Page assertion passed.":g.err?.message??`Page assertion still failing after ${n.timeout} seconds.`,urlAfterCommand:this.browser.url(),succeedImmediately:!1}}case"REGISTER_REQUEST_LISTENER":{let g=new Mn(n.requestMatcher),h=this.browser.registerRequestListener(g);return this.registeredListeners[n.key]=h.then(async f=>await Bp(f)).catch(f=>{a.error({err:f},"Failed to get request listener response")}),{succeedImmediately:!1,urlAfterCommand:this.browser.url()}}case"AWAIT_LISTENER":{let g=this.registeredListeners[n.key];if(!g)throw new C("ActionFailureError",`No listener registered with key: ${n.key}`);let h=n.timeout??10;return{data:await k(g,{milliseconds:h*1e3,message:`Request listener timed out after ${h} seconds`}),succeedImmediately:!1,urlAfterCommand:this.browser.url()}}case"RECORD_REQUESTS":{let g=new Mn(n.requestMatcher);return this.recordedRequests[n.key]={},this.browser.registerRequestRecorder(n.key,g,{onRequestStart:(h,f)=>{this.recordedRequests[n.key][h]=Lc(f)},onRequestComplete:(h,f)=>{this.recordedRequests[n.key][h]=Lc(f)}}),{succeedImmediately:!1,urlAfterCommand:this.browser.url()}}case"GET_RECORDED_REQUESTS":{let g=this.recordedRequests[n.key];if(!g)throw new C("ActionFailureError",`No recorder registered with key: ${n.key}`);return delete this.recordedRequests[n.key],{data:Object.values(g),succeedImmediately:!1,urlAfterCommand:this.browser.url()}}case"SET_HEADER":{let g;return n.requestMatcher&&(g=new Mn(n.requestMatcher)),this.browser.setHeader(n.name,n.value,g),{succeedImmediately:!1,urlAfterCommand:this.browser.url()}}case"MOCK_ROUTE":return{data:{key:this.browser.registerMock(n.key,new Mn(n.requestMatcher),async(h,f)=>{let E=await Ur({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=jS.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(g=>{throw"If Typescript complains about the line below, you missed a case or break in the switch above"})(n)}return{succeedImmediately:!1,urlAfterCommand:this.browser.url()}}async getReverseMappedDescription({browserState:e,targetId:t,disableCache:n,screenshot:o}){return(await this.generator.getReverseMappedDescription({browserState:e,target:t,screenshot:o},{disableCache:n,abortSignal:this.executeAbortController.signal,loggerTags:ge(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 Bc({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:ge(this.logger)})}async getFailureRecoveryPlan(e){return this.generator.getFailureRecoveryPlan(e,{disableCache:!0,abortSignal:this.executeAbortController.signal,loggerTags:ge(this.logger)})}};import{cloneDeep as EB}from"lodash-es";import IR from"truncate-json";var xR=1e3,MR=5e6,TB=5*1024*1024;function OR(r,e){for(let t=0;t<r.length;t++){let n=r[t];try{if(n.data){let{jsonString:o}=IR(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),OR(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 PR(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 Xc(r,e){let t=EB(r);if(OR(t,e),t.length>xR)return e.error("Database content violation: results too long, truncating before insertion"),t.slice(0,xR);let n=PR(t,e);if(n.length>MR)for(e.error({serializedLength:n.length,resultsArrayLength:t.length},"Database content violation: results too large, truncating before insertion");n.length>MR;)t.pop(),n=PR(t,e);let{jsonString:o}=IR(n,TB);try{return tr.array().parse(JSON.parse(o))}catch(i){throw e.error({serialized:n,err:i},"Could not parse serialized results into JSON structure after processing"),i}}import{AsyncLocalStorage as vB}from"async_hooks";var ts=new vB;function AB(r){ts.enterWith({activeTracers:[r]})}function wB(r,e){let t=ts.getStore()?.activeTracers;if(!t)return e();t.push(r);try{return e()}finally{t.pop()}}async function RB(r,e){let t=ts.getStore()?.activeTracers;if(!t)return e();let n=[...t,r];return ts.run({activeTracers:n},e)}var Qr={globalAls:ts,initializeRootTracerContext:AB,withChildTracer:wB,withChildTracerAsync:RB};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 Qr.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 Qr.withChildTracerAsync(i,()=>k(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 Qr.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 k(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 Te(){let r=Qr.globalAls.getStore()?.activeTracers,e;return!r||r.length===0?e=void 0:e=r[r.length-1],e||new mo}async function LR(r){let{driver:e,abortSignal:t,logger:n,packageName:o}=r,i;try{i=await k(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=CB(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 CB(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)}import{mkdirSync as jB}from"fs";import{tmpdir as WB}from"os";import HR from"path";import{diff as GB}from"deep-object-diff";import{cloneDeep as VB}from"lodash-es";import kR from"fontoxpath";import xB from"@prettier/plugin-xml";import MB from"prettier";import{DOMParser as _B,XMLSerializer as PB}from"slimdom";var IB=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 rs(r){let e=r.toLowerCase();return e.endsWith("webview")||IB.has(e)}function OB(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 LB=new Set(["index","package","a11y-important","screen-reader-focusabl"]),NB=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"]),DB=new Set(["text","hint"]),kB=new Set(["live-region","drawing-order"]),UB=new Set(["displayed","enabled"]);function FB(r,e){let t={};for(let[n,o]of Object.entries(e))LB.has(n)||n==="class"&&r===o||n==="focusable"&&o==="true"&&e.clickable==="true"||NB.has(n)&&o==="false"||DB.has(n)&&o===""||UB.has(n)&&o==="true"||kB.has(n)&&o==="0"||n!=="id"&&(t[n]=o);return t}function NR(r,e,t){let{prunedDocument:n,idToElement:o,prunedIdToElement:i,idCounter:a,opts:s}=r,c=a.value++;t.setAttribute("id",String(c));let l={};for(let m of e.attributes){let p=m.name,g=m.value;g!=null&&(l[p]=String(g))}let u=FB(e.tagName,l);for(let[m,p]of Object.entries(u))t.setAttribute(m,p);if(o.set(c,e),i.set(c,t),rs(e.tagName)){let m=s?.injectedWebviewContent??"";if(s?.removeWebviewContent){for(;t.firstChild;)t.removeChild(t.firstChild);return}else if(!s?.disableMomenticAccessibilityTree&&m.trim().length>0){for(;t.firstChild;)t.removeChild(t.firstChild);m.trim().length>0&&t.appendChild(n.createCDATASection(`
|
|
4155
4155
|
${m}
|
|
4156
|
-
`));return}}let d=Array.from(e.childNodes??[]);for(let m of d){let p=m.nodeType;if(p===3){let g=m.nodeValue;g&&g.trim().length>0&&t.appendChild(n.createTextNode(g));continue}if(p===1){let g=m,h=n.createElement(OB(g.tagName));NR(r,g,h),t.appendChild(h)}}}function BB(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;NR(a,e,s);let c=new PB().serializeToString(o);return{prunedDocument:o,prunedIdToElement:i,xml:c}}async function DR(r,e){let t=new _B,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}=BB(t,i,o,e);return{xml:await MB.format(c,{parser:"xml",plugins:[xB],printWidth:120,tabWidth:1,singleAttributePerLine:!1}),originalXml:r,document:n,idToElement:o,prunedDocument:a,prunedIdToElement:s}}function zB(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 Jc(r,e){let t=r.idToElement.get(e);if(t)return zB(t)}function cg(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 Si(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 ug(r,e){if(r&&!(!e||e.length===0))return Object.fromEntries(e.map(t=>[t,r.getAttribute(t)]).filter(([,t])=>t!==null))}function FR({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=Si(n);if(!o)throw new Error(`Node ${r.id} has no bounding box: ${n.outerHTML}`);let i=Jc(t.graph,r.id)??"",a=cg(t.graph,r.id)??"",s=t.graph.idToElement.get(r.id),c=ug(s,r.requirements?.attributesRequired),u={requiredText:r.requirements?.textRequired?s?.getAttribute("text")??void 0:void 0,requiredAttributes:c,requiredBounds:r.requirements?.boundsRequired},d=[];r.additionalElements&&(d=r.additionalElements.map(({id:p,requirements:g})=>{let h=t.graph.idToElement.get(p);if(!h)return;let f=Jc(t.graph,p);return f?{xPath:f,requirements:{requiredText:g.textRequired?h.getAttribute("text")??void 0:void 0,requiredAttributes:ug(h,g.attributesRequired),requiredBounds:g.boundsRequired}}:void 0}).filter(p=>!!p));let m;return rs(n.tagName)&&r.inWebview!==!1?m={type:"WEBVIEW",resolvedDescription:e,xPath:i}:m={type:"NATIVE",bounds:o,resolvedDescription:e,xPath:i,elementOnlySerializedXml:a,requirements:u,requiredRelatedElements:d},m}var UR=(r,e,t)=>{if(!e)return;let{requiredAttributes:n,requiredText:o,requiredBounds:i}=e;if(o!==void 0){let a=r.getAttribute("text")??void 0;if(a!==o)throw new Error(`ActionFailureError: Resolved element text mismatch: expected ${o}, got ${a}`)}if(n)for(let[a,s]of Object.entries(n)){let c=r.getAttribute(a)??void 0;if(c!==s)throw new Error(`ActionFailureError: Attribute ${a} mismatch: expected ${s}, got ${c}`)}if(i&&t){let a=Si(r);if(!a||a.length!==t.length)throw new Error("ActionFailureError: Resolved element has no bounds or unexpected bounds format");if(!a.every((c,l)=>c===t[l]))throw new Error(`ActionFailureError: Bounds changed from [${t.join(",")} ] to [${a.join(",")} ]`)}};async function BR(r){let{target:e,domState:t}=r,{graph:n}=t,{document:o}=n,i=Te();if(e.type==="WEBVIEW")return HB(e,r);let a=kR.evaluateXPathToFirstNode(e.xPath,o,null,null);if(!a)throw new Error(`ActionFailureError: Could not resolve cached target via XPath: ${e.xPath}`);if(e.requiredRelatedElements){let m=e.requiredRelatedElements;i.startSection("Validate related elements are similar enough to past runs",()=>{for(let p of m){let g=kR.evaluateXPathToFirstNode(p.xPath,o);if(!g)throw new Error(`ActionFailureError: Required related element not found for XPath: ${p.xPath}`);UR(g,p.requirements)}})}let s=Si(a);if(!s)throw new Error("ActionFailureError: Resolved native element has no bounding box");UR(a,e.requirements,e.bounds);let c;for(let[m,p]of n.idToElement.entries())if(p===a){c=m;break}let l=e.elementOnlySerializedXml,u=e.xPath;return c!==void 0&&(l=cg(n,c)??l,u=Jc(n,c)??u),{resolvedTarget:{...e,bounds:s,elementOnlySerializedXml:l,xPath:u}}}async function HB(r,e){let{stateManager:t,logger:n,signal:o}=e,i=Te(),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 dg(r){let{command:e,cacheKey:t="cache",targetName:n="target",updatedCache:o}=r;el(e)&&(e[t]={...e[t],[n]:Zs.parse(o)},r.updatedWithAI&&(e[t].updatedAt=new Date))}function zR(r){return r.type==="WEBVIEW"?{type:"WEBVIEW",resolvedDescription:r.resolvedDescription,xPath:r.xPath,browserCache:r.browserCache}:r}var Ct=class{driver;generator;stateManager;logger;fixtures;aborter;orgId;constructor(e){this.stateManager=e.stateManager,this.generator=e.generator,this.driver=e.driver,this.logger=e.logger,this.fixtures=e.fixtures,this.aborter=e.aborter,this.orgId=e.orgId}async findElement({description:e,tracer:t}){await this.stateManager.waitForScreenshotStability({timeoutMs:5e3,signal:this.aborter.controller?.signal,reason:"Waiting for stability before locating an element with AI"});let n=await t.startAsyncSection("Get emulator state",async()=>{let c=await this.stateManager.getDomState(),l=await this.stateManager.getCurrentScreenshotPngString();return{emulatorState:c,screenshot:l}}),o;try{o=await t.startAsyncSpan("AI_LOCATOR_CALL",async c=>{let l=await this.generator.getElementLocation({description:e,screenXml:n.emulatorState.graph.xml,screenshot:n.screenshot},{logger:this.logger,loggerTags:ge(this.logger),abortSignal:this.aborter.controller?.signal});return c.result=l,l})}catch(c){throw this.throwIfAborted(),this.logger.error({err:c},"Failed to locate element"),new Error(`ActionFailureError: Failed to locate element: ${c instanceof Error?c.message:c}`)}if(o.id===-1)throw new Error(`ActionFailureError: No matching element found: ${o.thoughts}`);let i=FR({aiResponse:o,description:e,emulatorState:n.emulatorState});if(i.type==="NATIVE")return t.addSpan({type:"TARGET_RESOLUTION",startTime:Date.now(),endTime:Date.now(),result:{serializedElement:i.elementOnlySerializedXml},attributes:{}}),{resolvedTarget:i,thoughts:o.thoughts};let{browserLocateResult:a,browserController:s}=await t.startAsyncSpan("TARGET_RESOLUTION",async c=>{let l=await this.stateManager.getActiveWebview();if(!l||!l.browserController)throw new Error("No browser controller is attached to the requested webview");let u=await l.browserController.locateElement({description:e,disableCache:!1,logger:this.logger});return c.result={serializedElement:u.target.nodeOnlySerializedHtml??"Unknown HTML element in webview"},{browserLocateResult:u,browserController:l.browserController}});return{resolvedTarget:{...i,controller:s,resolution:a.resolution,browserCache:a.target},thoughts:a.thoughts}}async wrapTargetingAction(e){let{action:t,description:n,command:o,cacheKey:i="cache",targetName:a="target",cacheIsInvalidAfterResolution:s,tracer:c}=e,l=i in o&&o[i]&&a in o[i]?o[i][a]:void 0,u=e.retriesWithAI??1,d=!1,m=VB(l),p;if(o.disableCache&&(this.logger.debug({command:o},"Cache explicitly disabled for command"),d=!0,m=void 0),s&&(d=!0,m=void 0),m&&m?.resolvedDescription!==n&&(this.logger.info({description:n,cacheDescription:m?.resolvedDescription},"Cache description mismatch, clearing it automatically"),d=!0,m=void 0),!m){u--,this.logger.info({description:n,cacheBustedBeforeAction:d},"Prompting AI for a new element location");let h=await this.findElement({description:n,tracer:c});p=h.thoughts;let f=await t(h.resolvedTarget);return dg({command:o,cacheKey:i,targetName:a,updatedCache:h.resolvedTarget,updatedWithAI:!0}),{result:f,thoughts:p}}let g;try{await this.stateManager.waitForScreenshotStability({timeoutMs:5e3,signal:this.aborter.controller?.signal,reason:"Waiting for stability before cache resolution"}),g=await this.stateManager.getDomState();let{resolvedTarget:h,updatedCache:f}=await c.startAsyncSection("Resolve target cache",async(b,x)=>{let{resolvedTarget:T}=await BR({target:m,domState:g,stateManager:this.stateManager,logger:this.logger}),v=zR(T),O=GB(m,v);return O&&Object.keys(O).length>0&&this.logger.info({cacheDiffs:O},"Successfully resolved target with cache"),x.attributes.serializedElement=T.type==="WEBVIEW"?T.browserCache?.nodeOnlySerializedHtml??"Unknown HTML element in webview":T.elementOnlySerializedXml,{resolvedTarget:T,updatedCache:v}}),E=await t(h);return dg({command:o,cacheKey:i,targetName:a,updatedCache:f,updatedWithAI:!1}),m.type!=="WEBVIEW"&&ft.increment("cache_target_resolution_v2",1,["outcome:hit","platform:native",`hasRequirements:${!!m.requirements}`,`hasAdditionalElements:${!!m.requiredRelatedElements?.length}`,`orgId:${this.orgId}`,"cliVersion:0.7.0"]),{result:E,thoughts:"Successfully executed preset action with cache."}}catch(h){if(m.type!=="WEBVIEW"&&ft.increment("cache_target_resolution_v2",1,["outcome:miss","platform:native",`hasRequirements:${!!m.requirements}`,`hasAdditionalElements:${!!m.requiredRelatedElements?.length}`,`orgId:${this.orgId}`,"cliVersion:0.7.0"]),this.throwIfAborted(),u>0)return this.logger.warn({err:h},"Failed to resolve target cache, retrying with AI"),this.logger.debug({domState:g?.graph.originalXml},"Emulator state"),this.wrapTargetingAction({...e,cacheIsInvalidAfterResolution:!0,retriesWithAI:u-1});throw new Error(`ActionFailureError: ${h instanceof Error?h.message:h}`,{cause:h})}}constructPerformerParams(){return{stateManager:this.stateManager,generator:this.generator,driver:this.driver,logger:this.logger,fixtures:this.fixtures,aborter:this.aborter,orgId:this.orgId}}throwIfAborted(){this.aborter.controller?.signal.throwIfAborted()}get abortSignal(){return this.aborter.controller?.signal}};function $B(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 yi=class extends Ct{async tapOnAbsoluteCoordinates(e){let t=e.x,n=e.y;if(this.logger.info({x:t,y:n},"Tap at coordinates"),e.longPress)return await this.driver.executeScript("mobile: longClickGesture",[{x:t,y:n,duration:e.longPressDurationMs??2e3}]);if(e.doubleTap){await this.driver.tap({x:t,y:n});let o=e.doubleTapDelayMs??100;await new Promise(i=>setTimeout(i,o))}await this.driver.tap({x:t,y:n})}async tapOnNativeTarget(e,t){let[n,o,i,a]=e.bounds,s=i-n,c=a-o,l=t?.relativePosition?.x??s/2,u=t?.relativePosition?.y??c/2;l=Math.max(0,Math.min(l,s)),u=Math.max(0,Math.min(u,c));let d=n+l,m=o+u;return await this.tapOnAbsoluteCoordinates({x:d,y:m,...t}),{x:d,y:m}}async tapOnWebviewTarget(e,t){let{controller:n}=e;return(await n.browser.click(e.resolution,{createIsolatedFolder:()=>{let i=Math.random().toString(36).substring(4),a=HR.join(WB(),"momentic","downloads"),s=HR.join(a,this.orgId,i);return jB(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 Te().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=Te(),n=$B(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 In=class extends Ct{async doPress({keycode:e,longPress:t}){await Te().startAsyncSpan("EMULATOR_INTERACTION",async()=>this.driver.executeScript("mobile: pressKey",[{keycode:e,isLongPress:t}]),{name:"Send key events to emulator"})}};var GR=25,Zc=class extends Ct{async doType(e){let t=Te();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:void 0}}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 Te().startAsyncSpan("EMULATOR_INTERACTION",async o=>{o.withinWebview=!0;let i={clearContent:e.clearContent,forceClearContent:e.forceClearContent,delay:e.keyPressDelayMs??GR};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 yi(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=Te(),n=e.keyPressDelayMs??GR;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=Te();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 In(this.constructPerformerParams()).doPress({keycode:67})}};import Vt from"zod";var mg=.8,bi=.2,qB=Vt.object({navigationBar:Vt.object({visible:Vt.boolean(),x:Vt.number(),y:Vt.number(),width:Vt.number(),height:Vt.number()}),statusBar:Vt.object({visible:Vt.boolean(),x:Vt.number(),y:Vt.number(),width:Vt.number(),height:Vt.number()})}),Qc=class extends Ct{async getHardcodedScrollableElementBounds(e,t){let n;switch(e.type){case"SCREEN":n=this.getInsetBoundsFromViewport(t);break;case"OPEN_APP":try{let o=qB.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*bi),n=Math.floor(e.height*bi);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*bi),l=Math.floor(s*bi);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=Te();if(e.scrollableElement.type!=="CUSTOM"){let n=await this.driver.getWindowRect(),o=await this.getHardcodedScrollableElementBounds(e.scrollableElement,n);return await t.startAsyncSpan("EMULATOR_INTERACTION",async i=>{await this.swipeByAbsoluteCoordinates({span:i,direction:e.direction,percent:e.viewportPercent,durationMs:e.durationMs,containerBounds:o})},{name:`Swipe ${e.direction} in the entire ${e.scrollableElement.type.toLowerCase()}`}),{success:!0}}return await this.wrapTargetingAction({command:e,description:e.scrollableElement.target.description,action:async n=>Te().startAsyncSpan("EMULATOR_INTERACTION",async i=>"type"in n&&n.type==="NATIVE"?this.scrollInNativeContainer({span:i,cmd:e,target:n}):(i.withinWebview=!0,this.scrollInWebview({cmd:e,target:n})),{name:`Swipe ${e.direction} in the specified container`}),tracer:t}),{success:!0}}async scrollInNativeContainer({span:e,cmd:t,target:n}){let o=n.bounds[2]-n.bounds[0],i=n.bounds[3]-n.bounds[1],a=Math.floor(o*bi),s=Math.floor(i*bi);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 scrollInWebview({cmd:e,target:t}){let{controller:n}=t,o=n.browser.getViewport();if(!o)throw new Error("Failed to get viewport size from webview");if(e.direction==="down"||e.direction==="up"){let i=o.height*(e.viewportPercent??mg)*(e.direction==="down"?1:-1);await n.browser.scrollVertical(i)}else{let i=o.width*(e.viewportPercent??mg)*(e.direction==="right"?1:-1);await n.browser.scrollHorizontal(i)}}async swipeByAbsoluteCoordinates({span:e,direction:t,percent:n=mg,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{randomUUID as KB}from"crypto";import os from"fs";import{tmpdir as YB}from"os";import Ei from"path";var eu=class extends Ct{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 ${Ei.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(os.existsSync(n))o=n;else if(os.existsSync(Ei.join("/",n)))o=Ei.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{os.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=Ei.resolve(e);return this.assertFileExists(n),{localPath:n,cleanup:()=>{}}}throw t}}assertFileExists(e){try{os.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=Ei.extname(t)||".apk",o=Ei.join(YB(),`momentic-apk-${KB()}${n}`);return os.writeFileSync(o,e),o}};import{existsSync as XB,readFileSync as JB}from"fs";import ZB from"zod";var QB=ZB.string().url();async function VR(r){if(QB.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(!XB(r))throw new Error(`File does not exist at path: ${r}`);return JB(r).toString("base64")}var ez=5e3,tu=class extends Ct{async executeScreenCheck(e){let{timeout:t}=e,n=Date.now(),o=(t??wr)*1e3,i=o+1e4,a,s=0,c=500;for(;s-n<o;){if(Date.now()-n>i){this.logger.warn("Exceeded max system timeout for screen check, exiting...");break}if(this.throwIfAborted(),a=await this.executeScreenCheckHelper(e),s=Date.now(),!a.success)await X(c,this.abortSignal),c=Math.min(Math.floor(c*1.5),ez);else return a}return a=await this.executeScreenCheckHelper(e),a}async executeScreenCheckHelper(e){return await Te().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":{let o=!1,i;try{let a=(await this.stateManager.getDomState({skipFetchingFullWebviewContent:!0,removeWebviewContent:!0})).graph.document.documentElement?.outerHTML;if(!a)throw new Error("Failed to get screen HTML");o=a.includes(n.value)===!n.negated,a.length>1e4&&(a=a.slice(0,1e4)+"...TRUNCATED"),o||(i=new C("AssertionFailureError",`The screen ${Sp(n)}.`),e.attributes.screenContent=a)}catch(a){i=new C("AssertionFailureError",`Failed to evaluate screen content assertion: ${a instanceof Error?a.message:`${a}`}`)}return{success:o,err:i}}default:return n.type,{success:!1,err:new C("AssertionFailureError",`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 Kc({assertion:e.assertion,logger:this.logger,browser:n,autoExpandIframes:!!n.userBrowserSettings.autoExpandIframes})}};import{execSync as $R}from"child_process";import nz from"pixelmatch";import{_android as oz,chromium as iz}from"playwright";import{PNG as qR}from"pngjs";import{z as $e}from"zod";var jR=$e.array($e.object({proc:$e.string(),webview:$e.string(),info:$e.object({"Android-Package":$e.string(),Browser:$e.string(),"Protocol-Version":$e.string(),"User-Agent":$e.string(),"V8-Version":$e.string(),"WebKit-Version":$e.string(),webSocketDebuggerUrl:$e.string()}),pages:$e.array($e.object({description:$e.string(),devtoolsFrontendUrl:$e.string(),id:$e.string(),title:$e.string(),type:$e.string(),url:$e.string(),webSocketDebuggerUrl:$e.string()})),webviewName:$e.string()}));var ru=class r{driver;limbarClient;device;currentContext;logger;webviews=new Map;fixtures;orgId;options;aborter;constructor({driver:e,context:t,limbarClient:n,logger:o,device:i,fixtures:a,orgId:s,options:c,aborter:l}){this.driver=e,this.limbarClient=n,this.device=i,this.currentContext=t,this.logger=o,this.fixtures=a,this.orgId=s,this.options=c,this.aborter=l;for(let u of["SIGINT","SIGTERM"])process.on(u,async()=>{await this.cleanupWebviews()})}static async init({driver:e,logger:t,fixtures:n,limbarClient:o,orgId:i,adbPort:a,options:s,aborter:c,playwrightDevice:l}){let u=await e.getContext(),d=typeof u=="string"?u:u.id,m;if(l)m=l;else{t.warn("No playwright device provided, using ADB to find device");let g=(await oz.devices()).filter(h=>h._initializer?.serial?.endsWith(a.toString())||h._initializer?.serial?.endsWith((a-1).toString()));if(g.length===0)throw new Error(`Momentic found no devices listening on port ${a} or ${a-1}. This can occur if Android Studio reuses existing emulators. Please run 'adb emu kill' and 'adb disconnect' and retry.`);if(g.length>1)throw new Error(`Momentic found multiple devices on the ports ${a} or ${a-1}. This can occur if Android Studio reuses existing emulators. Please run 'adb emu kill' and 'adb disconnect' and retry.`);m=g[0]}return new r({driver:e,context:d,logger:t,device:m,fixtures:n,orgId:i,options:s,aborter:c,limbarClient:o})}async getContexts(){let e=await this.driver.getContexts({}),t=Array.from(this.webviews.values());return{contexts:e,webviews:t.map(n=>({contextId:n.contextId,packageName:n.packageName,active:n.active,hasPlaywright:!!n.browserController,lastSeen:n.lastSeen,socketName:n.socketName}))}}async getRawScreenshotBase64(e=2){let t=Te(),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 Te().startAsyncSection("Waiting for stability",async(i,a)=>{a.attributes.reason=n;let s=Date.now(),c,l=!1,u=(d,m)=>{let p=Buffer.from(d,"base64"),g=Buffer.from(m,"base64"),h=qR.sync.read(p),f=qR.sync.read(g);if(h.width!==f.width||h.height!==f.height)return 100;let E=h.width,b=h.height,x=Buffer.alloc(E*b*4);return nz(h.data,f.data,x,E,b,{threshold:.01})/(E*b)*100};for(;Date.now()-s<e;){if(t?.throwIfAborted(),!c){c=await this.getRawScreenshotBase64();continue}let d=await this.getRawScreenshotBase64();if(u(c,d)<=o){l=!0;break}c=d,await X(250,t)}l||(a.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");(rs(a.tagName)||n==="com.android.chrome"&&s==="Web View"&&a.tagName.toLowerCase().startsWith("frame"))&&o.push({id:i,originalElement:a,bounds:Si(a)})}return o}async getActiveWebviewContent(){let e=await this.getActiveWebview();if(!e||!e.browserController)return;this.throwIfAborted();let t=e.browserController;return(await Te().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 Te().startAsyncSection("Get emulator state XML",async()=>{let n;if(!e?.skipFetchingFullWebviewContent)try{n=await this.getActiveWebviewContent()}catch(a){this.logger.error({err:a},"Could not get webview info to get the nested DOM state")}this.throwIfAborted();let o=await this.getPageSource();return{graph:await DR(o,{injectedWebviewContent:n,disableMomenticAccessibilityTree:this.options.disableMomenticAccessibilityTree,removeWebviewContent:e?.removeWebviewContent}),context:this.currentContext}},{timeoutMs:15e3})}async getPageSource(){return await Te().startAsyncSpan("EMULATOR_READ_STATE",()=>this.driver.getPageSource(),{name:"Get Android page source",signal:this.aborter.controller?.signal})}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 Te().startAsyncSection("Refresh webviews",async()=>{await this.refreshWebviews()});let e=await this.driver.execute("mobile: getCurrentPackage");e!==void 0&&typeof e!="string"&&this.logger.warn({currentPkg:e},"Unexpected getCurrentPackage result");let t=[];for(let n of this.webviews.values())n.packageName===e&&n.active&&t.push(n);if(t.length!==0){if(t.length>1)throw new Error("Multiple active webviews in a single package is currently not supported");return t[0]}}async executeRawADBCommand(e){let t=this.driver.capabilities,n=t.deviceUDID||t.udid||t["appium:udid"]||t["appium:deviceUDID"],o=process.env.ANDROID_HOME?`${process.env.ANDROID_HOME}/platform-tools/adb`:"adb",i=n?`-s ${n}`:"",a=`${o} ${i} ${e}`;this.logger.info(`Executing ADB command: ${a}`);let s=$R(a,{encoding:"utf8"});return this.logger.info(`ADB command result: ${s}`),s}async cleanupWebviews(){for(let[e,t]of this.webviews.entries())this.logger.info(`Disconnecting webview ${e}`),this.disconnectPlaywrightFromWebview(t),t.active=!1}async getDetailedContexts(){return await Te().startAsyncSpan("EMULATOR_READ_STATE",async()=>{let t=await this.driver.execute("mobile: getContexts");this.aborter.controller?.signal.throwIfAborted();let n;try{n=jR.parse(t)}catch(o){throw new Error(`Failed to parse contexts. Original error:
|
|
4156
|
+
`));return}}let d=Array.from(e.childNodes??[]);for(let m of d){let p=m.nodeType;if(p===3){let g=m.nodeValue;g&&g.trim().length>0&&t.appendChild(n.createTextNode(g));continue}if(p===1){let g=m,h=n.createElement(OB(g.tagName));NR(r,g,h),t.appendChild(h)}}}function BB(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;NR(a,e,s);let c=new PB().serializeToString(o);return{prunedDocument:o,prunedIdToElement:i,xml:c}}async function DR(r,e){let t=new _B,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}=BB(t,i,o,e);return{xml:await MB.format(c,{parser:"xml",plugins:[xB],printWidth:120,tabWidth:1,singleAttributePerLine:!1}),originalXml:r,document:n,idToElement:o,prunedDocument:a,prunedIdToElement:s}}function zB(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 Jc(r,e){let t=r.idToElement.get(e);if(t)return zB(t)}function cg(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 Si(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 ug(r,e){if(r&&!(!e||e.length===0))return Object.fromEntries(e.map(t=>[t,r.getAttribute(t)]).filter(([,t])=>t!==null))}function FR({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=Si(n);if(!o)throw new Error(`Node ${r.id} has no bounding box: ${n.outerHTML}`);let i=Jc(t.graph,r.id)??"",a=cg(t.graph,r.id)??"",s=t.graph.idToElement.get(r.id),c=ug(s,r.requirements?.attributesRequired),u={requiredText:r.requirements?.textRequired?s?.getAttribute("text")??void 0:void 0,requiredAttributes:c,requiredBounds:r.requirements?.boundsRequired},d=[];r.additionalElements&&(d=r.additionalElements.map(({id:p,requirements:g})=>{let h=t.graph.idToElement.get(p);if(!h)return;let f=Jc(t.graph,p);return f?{xPath:f,requirements:{requiredText:g.textRequired?h.getAttribute("text")??void 0:void 0,requiredAttributes:ug(h,g.attributesRequired),requiredBounds:g.boundsRequired}}:void 0}).filter(p=>!!p));let m;return rs(n.tagName)&&r.inWebview!==!1?m={type:"WEBVIEW",resolvedDescription:e,xPath:i}:m={type:"NATIVE",bounds:o,resolvedDescription:e,xPath:i,elementOnlySerializedXml:a,requirements:u,requiredRelatedElements:d},m}var UR=(r,e,t)=>{if(!e)return;let{requiredAttributes:n,requiredText:o,requiredBounds:i}=e;if(o!==void 0){let a=r.getAttribute("text")??void 0;if(a!==o)throw new Error(`ActionFailureError: Resolved element text mismatch: expected ${o}, got ${a}`)}if(n)for(let[a,s]of Object.entries(n)){let c=r.getAttribute(a)??void 0;if(c!==s)throw new Error(`ActionFailureError: Attribute ${a} mismatch: expected ${s}, got ${c}`)}if(i&&t){let a=Si(r);if(!a||a.length!==t.length)throw new Error("ActionFailureError: Resolved element has no bounds or unexpected bounds format");if(!a.every((c,l)=>c===t[l]))throw new Error(`ActionFailureError: Bounds changed from [${t.join(",")} ] to [${a.join(",")} ]`)}};async function BR(r){let{target:e,domState:t}=r,{graph:n}=t,{document:o}=n,i=Te();if(e.type==="WEBVIEW")return HB(e,r);let a=kR.evaluateXPathToFirstNode(e.xPath,o,null,null);if(!a)throw new Error(`ActionFailureError: Could not resolve cached target via XPath: ${e.xPath}`);if(e.requiredRelatedElements){let m=e.requiredRelatedElements;i.startSection("Validate related elements are similar enough to past runs",()=>{for(let p of m){let g=kR.evaluateXPathToFirstNode(p.xPath,o);if(!g)throw new Error(`ActionFailureError: Required related element not found for XPath: ${p.xPath}`);UR(g,p.requirements)}})}let s=Si(a);if(!s)throw new Error("ActionFailureError: Resolved native element has no bounding box");UR(a,e.requirements,e.bounds);let c;for(let[m,p]of n.idToElement.entries())if(p===a){c=m;break}let l=e.elementOnlySerializedXml,u=e.xPath;return c!==void 0&&(l=cg(n,c)??l,u=Jc(n,c)??u),{resolvedTarget:{...e,bounds:s,elementOnlySerializedXml:l,xPath:u}}}async function HB(r,e){let{stateManager:t,logger:n,signal:o}=e,i=Te(),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 dg(r){let{command:e,cacheKey:t="cache",targetName:n="target",updatedCache:o}=r;el(e)&&(e[t]={...e[t],[n]:Zs.parse(o)},r.updatedWithAI&&(e[t].updatedAt=new Date))}function zR(r){return r.type==="WEBVIEW"?{type:"WEBVIEW",resolvedDescription:r.resolvedDescription,xPath:r.xPath,browserCache:r.browserCache}:r}var Ct=class{driver;generator;stateManager;logger;fixtures;aborter;orgId;constructor(e){this.stateManager=e.stateManager,this.generator=e.generator,this.driver=e.driver,this.logger=e.logger,this.fixtures=e.fixtures,this.aborter=e.aborter,this.orgId=e.orgId}async findElement({description:e,tracer:t}){await this.stateManager.waitForScreenshotStability({timeoutMs:5e3,signal:this.aborter.controller?.signal,reason:"Waiting for stability before locating an element with AI"});let n=await t.startAsyncSection("Get emulator state",async()=>{let c=await this.stateManager.getDomState(),l=await this.stateManager.getCurrentScreenshotPngString();return{emulatorState:c,screenshot:l}}),o;try{o=await t.startAsyncSpan("AI_LOCATOR_CALL",async c=>{let l=await this.generator.getElementLocation({description:e,screenXml:n.emulatorState.graph.xml,screenshot:n.screenshot},{logger:this.logger,loggerTags:ge(this.logger),abortSignal:this.aborter.controller?.signal});return c.result=l,l})}catch(c){throw this.throwIfAborted(),this.logger.error({err:c},"Failed to locate element"),new Error(`ActionFailureError: Failed to locate element: ${c instanceof Error?c.message:c}`)}if(o.id===-1)throw new Error(`ActionFailureError: No matching element found: ${o.thoughts}`);let i=FR({aiResponse:o,description:e,emulatorState:n.emulatorState});if(i.type==="NATIVE")return t.addSpan({type:"TARGET_RESOLUTION",startTime:Date.now(),endTime:Date.now(),result:{serializedElement:i.elementOnlySerializedXml},attributes:{}}),{resolvedTarget:i,thoughts:o.thoughts};let{browserLocateResult:a,browserController:s}=await t.startAsyncSpan("TARGET_RESOLUTION",async c=>{let l=await this.stateManager.getActiveWebview();if(!l||!l.browserController)throw new Error("No browser controller is attached to the requested webview");let u=await l.browserController.locateElement({description:e,disableCache:!1,logger:this.logger});return c.result={serializedElement:u.target.nodeOnlySerializedHtml??"Unknown HTML element in webview"},{browserLocateResult:u,browserController:l.browserController}});return{resolvedTarget:{...i,controller:s,resolution:a.resolution,browserCache:a.target},thoughts:a.thoughts}}async wrapTargetingAction(e){let{action:t,description:n,command:o,cacheKey:i="cache",targetName:a="target",cacheIsInvalidAfterResolution:s,tracer:c}=e,l=i in o&&o[i]&&a in o[i]?o[i][a]:void 0,u=e.retriesWithAI??1,d=!1,m=VB(l),p;if(o.disableCache&&(this.logger.debug({command:o},"Cache explicitly disabled for command"),d=!0,m=void 0),s&&(d=!0,m=void 0),m&&m?.resolvedDescription!==n&&(this.logger.info({description:n,cacheDescription:m?.resolvedDescription},"Cache description mismatch, clearing it automatically"),d=!0,m=void 0),!m){u--,this.logger.info({description:n,cacheBustedBeforeAction:d},"Prompting AI for a new element location");let h=await this.findElement({description:n,tracer:c});p=h.thoughts;let f=await t(h.resolvedTarget);return dg({command:o,cacheKey:i,targetName:a,updatedCache:h.resolvedTarget,updatedWithAI:!0}),{result:f,thoughts:p}}let g;try{await this.stateManager.waitForScreenshotStability({timeoutMs:5e3,signal:this.aborter.controller?.signal,reason:"Waiting for stability before cache resolution"}),g=await this.stateManager.getDomState();let{resolvedTarget:h,updatedCache:f}=await c.startAsyncSection("Resolve target cache",async(b,x)=>{let{resolvedTarget:T}=await BR({target:m,domState:g,stateManager:this.stateManager,logger:this.logger}),v=zR(T),O=GB(m,v);return O&&Object.keys(O).length>0&&this.logger.info({cacheDiffs:O},"Successfully resolved target with cache"),x.attributes.serializedElement=T.type==="WEBVIEW"?T.browserCache?.nodeOnlySerializedHtml??"Unknown HTML element in webview":T.elementOnlySerializedXml,{resolvedTarget:T,updatedCache:v}}),E=await t(h);return dg({command:o,cacheKey:i,targetName:a,updatedCache:f,updatedWithAI:!1}),m.type!=="WEBVIEW"&&ft.increment("cache_target_resolution_v2",1,["outcome:hit","platform:native",`hasRequirements:${!!m.requirements}`,`hasAdditionalElements:${!!m.requiredRelatedElements?.length}`,`orgId:${this.orgId}`,"cliVersion:0.7.1"]),{result:E,thoughts:"Successfully executed preset action with cache."}}catch(h){if(m.type!=="WEBVIEW"&&ft.increment("cache_target_resolution_v2",1,["outcome:miss","platform:native",`hasRequirements:${!!m.requirements}`,`hasAdditionalElements:${!!m.requiredRelatedElements?.length}`,`orgId:${this.orgId}`,"cliVersion:0.7.1"]),this.throwIfAborted(),u>0)return this.logger.warn({err:h},"Failed to resolve target cache, retrying with AI"),this.logger.debug({domState:g?.graph.originalXml},"Emulator state"),this.wrapTargetingAction({...e,cacheIsInvalidAfterResolution:!0,retriesWithAI:u-1});throw new Error(`ActionFailureError: ${h instanceof Error?h.message:h}`,{cause:h})}}constructPerformerParams(){return{stateManager:this.stateManager,generator:this.generator,driver:this.driver,logger:this.logger,fixtures:this.fixtures,aborter:this.aborter,orgId:this.orgId}}throwIfAborted(){this.aborter.controller?.signal.throwIfAborted()}get abortSignal(){return this.aborter.controller?.signal}};function $B(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 yi=class extends Ct{async tapOnAbsoluteCoordinates(e){let t=e.x,n=e.y;if(this.logger.info({x:t,y:n},"Tap at coordinates"),e.longPress)return await this.driver.executeScript("mobile: longClickGesture",[{x:t,y:n,duration:e.longPressDurationMs??2e3}]);if(e.doubleTap){await this.driver.tap({x:t,y:n});let o=e.doubleTapDelayMs??100;await new Promise(i=>setTimeout(i,o))}await this.driver.tap({x:t,y:n})}async tapOnNativeTarget(e,t){let[n,o,i,a]=e.bounds,s=i-n,c=a-o,l=t?.relativePosition?.x??s/2,u=t?.relativePosition?.y??c/2;l=Math.max(0,Math.min(l,s)),u=Math.max(0,Math.min(u,c));let d=n+l,m=o+u;return await this.tapOnAbsoluteCoordinates({x:d,y:m,...t}),{x:d,y:m}}async tapOnWebviewTarget(e,t){let{controller:n}=e;return(await n.browser.click(e.resolution,{createIsolatedFolder:()=>{let i=Math.random().toString(36).substring(4),a=HR.join(WB(),"momentic","downloads"),s=HR.join(a,this.orgId,i);return jB(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 Te().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=Te(),n=$B(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 In=class extends Ct{async doPress({keycode:e,longPress:t}){await Te().startAsyncSpan("EMULATOR_INTERACTION",async()=>this.driver.executeScript("mobile: pressKey",[{keycode:e,isLongPress:t}]),{name:"Send key events to emulator"})}};var GR=25,Zc=class extends Ct{async doType(e){let t=Te();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:void 0}}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 Te().startAsyncSpan("EMULATOR_INTERACTION",async o=>{o.withinWebview=!0;let i={clearContent:e.clearContent,forceClearContent:e.forceClearContent,delay:e.keyPressDelayMs??GR};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 yi(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=Te(),n=e.keyPressDelayMs??GR;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=Te();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 In(this.constructPerformerParams()).doPress({keycode:67})}};import Vt from"zod";var mg=.8,bi=.2,qB=Vt.object({navigationBar:Vt.object({visible:Vt.boolean(),x:Vt.number(),y:Vt.number(),width:Vt.number(),height:Vt.number()}),statusBar:Vt.object({visible:Vt.boolean(),x:Vt.number(),y:Vt.number(),width:Vt.number(),height:Vt.number()})}),Qc=class extends Ct{async getHardcodedScrollableElementBounds(e,t){let n;switch(e.type){case"SCREEN":n=this.getInsetBoundsFromViewport(t);break;case"OPEN_APP":try{let o=qB.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*bi),n=Math.floor(e.height*bi);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*bi),l=Math.floor(s*bi);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=Te();if(e.scrollableElement.type!=="CUSTOM"){let n=await this.driver.getWindowRect(),o=await this.getHardcodedScrollableElementBounds(e.scrollableElement,n);return await t.startAsyncSpan("EMULATOR_INTERACTION",async i=>{await this.swipeByAbsoluteCoordinates({span:i,direction:e.direction,percent:e.viewportPercent,durationMs:e.durationMs,containerBounds:o})},{name:`Swipe ${e.direction} in the entire ${e.scrollableElement.type.toLowerCase()}`}),{success:!0}}return await this.wrapTargetingAction({command:e,description:e.scrollableElement.target.description,action:async n=>Te().startAsyncSpan("EMULATOR_INTERACTION",async i=>"type"in n&&n.type==="NATIVE"?this.scrollInNativeContainer({span:i,cmd:e,target:n}):(i.withinWebview=!0,this.scrollInWebview({cmd:e,target:n})),{name:`Swipe ${e.direction} in the specified container`}),tracer:t}),{success:!0}}async scrollInNativeContainer({span:e,cmd:t,target:n}){let o=n.bounds[2]-n.bounds[0],i=n.bounds[3]-n.bounds[1],a=Math.floor(o*bi),s=Math.floor(i*bi);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 scrollInWebview({cmd:e,target:t}){let{controller:n}=t,o=n.browser.getViewport();if(!o)throw new Error("Failed to get viewport size from webview");if(e.direction==="down"||e.direction==="up"){let i=o.height*(e.viewportPercent??mg)*(e.direction==="down"?1:-1);await n.browser.scrollVertical(i)}else{let i=o.width*(e.viewportPercent??mg)*(e.direction==="right"?1:-1);await n.browser.scrollHorizontal(i)}}async swipeByAbsoluteCoordinates({span:e,direction:t,percent:n=mg,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{randomUUID as KB}from"crypto";import os from"fs";import{tmpdir as YB}from"os";import Ei from"path";var eu=class extends Ct{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 ${Ei.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(os.existsSync(n))o=n;else if(os.existsSync(Ei.join("/",n)))o=Ei.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{os.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=Ei.resolve(e);return this.assertFileExists(n),{localPath:n,cleanup:()=>{}}}throw t}}assertFileExists(e){try{os.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=Ei.extname(t)||".apk",o=Ei.join(YB(),`momentic-apk-${KB()}${n}`);return os.writeFileSync(o,e),o}};import{existsSync as XB,readFileSync as JB}from"fs";import ZB from"zod";var QB=ZB.string().url();async function VR(r){if(QB.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(!XB(r))throw new Error(`File does not exist at path: ${r}`);return JB(r).toString("base64")}var ez=5e3,tu=class extends Ct{async executeScreenCheck(e){let{timeout:t}=e,n=Date.now(),o=(t??wr)*1e3,i=o+1e4,a,s=0,c=500;for(;s-n<o;){if(Date.now()-n>i){this.logger.warn("Exceeded max system timeout for screen check, exiting...");break}if(this.throwIfAborted(),a=await this.executeScreenCheckHelper(e),s=Date.now(),!a.success)await X(c,this.abortSignal),c=Math.min(Math.floor(c*1.5),ez);else return a}return a=await this.executeScreenCheckHelper(e),a}async executeScreenCheckHelper(e){return await Te().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":{let o=!1,i;try{let a=(await this.stateManager.getDomState({skipFetchingFullWebviewContent:!0,removeWebviewContent:!0})).graph.document.documentElement?.outerHTML;if(!a)throw new Error("Failed to get screen HTML");o=a.includes(n.value)===!n.negated,a.length>1e4&&(a=a.slice(0,1e4)+"...TRUNCATED"),o||(i=new C("AssertionFailureError",`The screen ${Sp(n)}.`),e.attributes.screenContent=a)}catch(a){i=new C("AssertionFailureError",`Failed to evaluate screen content assertion: ${a instanceof Error?a.message:`${a}`}`)}return{success:o,err:i}}default:return n.type,{success:!1,err:new C("AssertionFailureError",`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 Kc({assertion:e.assertion,logger:this.logger,browser:n,autoExpandIframes:!!n.userBrowserSettings.autoExpandIframes})}};import{execSync as $R}from"child_process";import nz from"pixelmatch";import{_android as oz,chromium as iz}from"playwright";import{PNG as qR}from"pngjs";import{z as $e}from"zod";var jR=$e.array($e.object({proc:$e.string(),webview:$e.string(),info:$e.object({"Android-Package":$e.string(),Browser:$e.string(),"Protocol-Version":$e.string(),"User-Agent":$e.string(),"V8-Version":$e.string(),"WebKit-Version":$e.string(),webSocketDebuggerUrl:$e.string()}),pages:$e.array($e.object({description:$e.string(),devtoolsFrontendUrl:$e.string(),id:$e.string(),title:$e.string(),type:$e.string(),url:$e.string(),webSocketDebuggerUrl:$e.string()})),webviewName:$e.string()}));var ru=class r{driver;limbarClient;device;currentContext;logger;webviews=new Map;fixtures;orgId;options;aborter;constructor({driver:e,context:t,limbarClient:n,logger:o,device:i,fixtures:a,orgId:s,options:c,aborter:l}){this.driver=e,this.limbarClient=n,this.device=i,this.currentContext=t,this.logger=o,this.fixtures=a,this.orgId=s,this.options=c,this.aborter=l;for(let u of["SIGINT","SIGTERM"])process.on(u,async()=>{await this.cleanupWebviews()})}static async init({driver:e,logger:t,fixtures:n,limbarClient:o,orgId:i,adbPort:a,options:s,aborter:c,playwrightDevice:l}){let u=await e.getContext(),d=typeof u=="string"?u:u.id,m;if(l)m=l;else{t.warn("No playwright device provided, using ADB to find device");let g=(await oz.devices()).filter(h=>h._initializer?.serial?.endsWith(a.toString())||h._initializer?.serial?.endsWith((a-1).toString()));if(g.length===0)throw new Error(`Momentic found no devices listening on port ${a} or ${a-1}. This can occur if Android Studio reuses existing emulators. Please run 'adb emu kill' and 'adb disconnect' and retry.`);if(g.length>1)throw new Error(`Momentic found multiple devices on the ports ${a} or ${a-1}. This can occur if Android Studio reuses existing emulators. Please run 'adb emu kill' and 'adb disconnect' and retry.`);m=g[0]}return new r({driver:e,context:d,logger:t,device:m,fixtures:n,orgId:i,options:s,aborter:c,limbarClient:o})}async getContexts(){let e=await this.driver.getContexts({}),t=Array.from(this.webviews.values());return{contexts:e,webviews:t.map(n=>({contextId:n.contextId,packageName:n.packageName,active:n.active,hasPlaywright:!!n.browserController,lastSeen:n.lastSeen,socketName:n.socketName}))}}async getRawScreenshotBase64(e=2){let t=Te(),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 Te().startAsyncSection("Waiting for stability",async(i,a)=>{a.attributes.reason=n;let s=Date.now(),c,l=!1,u=(d,m)=>{let p=Buffer.from(d,"base64"),g=Buffer.from(m,"base64"),h=qR.sync.read(p),f=qR.sync.read(g);if(h.width!==f.width||h.height!==f.height)return 100;let E=h.width,b=h.height,x=Buffer.alloc(E*b*4);return nz(h.data,f.data,x,E,b,{threshold:.01})/(E*b)*100};for(;Date.now()-s<e;){if(t?.throwIfAborted(),!c){c=await this.getRawScreenshotBase64();continue}let d=await this.getRawScreenshotBase64();if(u(c,d)<=o){l=!0;break}c=d,await X(250,t)}l||(a.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");(rs(a.tagName)||n==="com.android.chrome"&&s==="Web View"&&a.tagName.toLowerCase().startsWith("frame"))&&o.push({id:i,originalElement:a,bounds:Si(a)})}return o}async getActiveWebviewContent(){let e=await this.getActiveWebview();if(!e||!e.browserController)return;this.throwIfAborted();let t=e.browserController;return(await Te().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 Te().startAsyncSection("Get emulator state XML",async()=>{let n;if(!e?.skipFetchingFullWebviewContent)try{n=await this.getActiveWebviewContent()}catch(a){this.logger.error({err:a},"Could not get webview info to get the nested DOM state")}this.throwIfAborted();let o=await this.getPageSource();return{graph:await DR(o,{injectedWebviewContent:n,disableMomenticAccessibilityTree:this.options.disableMomenticAccessibilityTree,removeWebviewContent:e?.removeWebviewContent}),context:this.currentContext}},{timeoutMs:15e3})}async getPageSource(){return await Te().startAsyncSpan("EMULATOR_READ_STATE",()=>this.driver.getPageSource(),{name:"Get Android page source",signal:this.aborter.controller?.signal})}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 Te().startAsyncSection("Refresh webviews",async()=>{await this.refreshWebviews()});let e=await this.driver.execute("mobile: getCurrentPackage");e!==void 0&&typeof e!="string"&&this.logger.warn({currentPkg:e},"Unexpected getCurrentPackage result");let t=[];for(let n of this.webviews.values())n.packageName===e&&n.active&&t.push(n);if(t.length!==0){if(t.length>1)throw new Error("Multiple active webviews in a single package is currently not supported");return t[0]}}async executeRawADBCommand(e){let t=this.driver.capabilities,n=t.deviceUDID||t.udid||t["appium:udid"]||t["appium:deviceUDID"],o=process.env.ANDROID_HOME?`${process.env.ANDROID_HOME}/platform-tools/adb`:"adb",i=n?`-s ${n}`:"",a=`${o} ${i} ${e}`;this.logger.info(`Executing ADB command: ${a}`);let s=$R(a,{encoding:"utf8"});return this.logger.info(`ADB command result: ${s}`),s}async cleanupWebviews(){for(let[e,t]of this.webviews.entries())this.logger.info(`Disconnecting webview ${e}`),this.disconnectPlaywrightFromWebview(t),t.active=!1}async getDetailedContexts(){return await Te().startAsyncSpan("EMULATOR_READ_STATE",async()=>{let t=await this.driver.execute("mobile: getContexts");this.aborter.controller?.signal.throwIfAborted();let n;try{n=jR.parse(t)}catch(o){throw new Error(`Failed to parse contexts. Original error:
|
|
4157
4157
|
${o}
|
|
4158
4158
|
Raw: ${JSON.stringify(t)}`)}return n.filter(o=>{if(!o.webviewName)return!0;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||this.logger.debug({context:o},"Webview has no qualified pages, skipping"),i})},{name:"Get available contexts",signal:this.aborter.controller?.signal})}async createBrowserController({context:e}){return await Te().startSection("Run remote Chrome initialization",async(n,o)=>{let i={};o.attributes.timings=i;let a=await Qa.fromExistingContext({context:e,logger:this.logger,timingRecorder:i,userBrowserSettings:{visualActions:!0,disableBrowserMonitoring:!0},properties:{isNewHeadless:!0,allowedA11yIgnoreReasonsOverride:[],isAndroid:!0},storage:this.fixtures.storage,enricher:this.fixtures.browserEnricher});return new Yc({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 Te().startAsyncSection("Connect headless browser client to webview",async()=>this.connectPlaywrightToWebviewHelper(e,t),{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){this.logger.warn({webviews:n.map(l=>({pkg:l.pkg,name:this.extractSocketNameFromWebview(l,this.logger)}))},`Could not find webview for ${e} with socket name ${t}`);return}let i=await o.page(),a=i.url();if(a===""||a.startsWith("about:blank")||a.startsWith("chrome-error:")){this.logger.warn({pageUrl:a},`Webview ${e} with socket ${t} is not a valid webview`);return}let s=i.context();return await this.createBrowserController({context:s})}async connectPlaywrightToChrome(e){return await Te().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 iz.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=process.env.ANDROID_HOME?`${process.env.ANDROID_HOME}/platform-tools/adb`:"adb",a=o?`-s ${o}`:"",s=`${i} ${a} forward tcp:${t} ${`localabstract:${e}`||"localabstract:chrome_devtools_remote"}`;this.logger.info(`Executing command: ${s}`);let c=$R(s,{encoding:"utf8"});return this.logger.info(`ADB command result: ${c}`),this.logger.info(`Successfully forwarded DevTools socket to port ${t}`),t}async removeDevToolsForwarding(e){await this.executeRawADBCommand(`forward --remove tcp:${e}`),this.logger.info("Successfully removed port forwarding")}throwIfAborted(){this.aborter.controller?.signal.throwIfAborted()}};var Ti=class r extends Ct{options;appsWithGrantedPermissions=new Set;adbPort;constructor(e){super(e),this.options=e.options??{},this.adbPort=e.adbPort}static async init({driver:e,generator:t,logger:n,fixtures:o,orgId:i,options:a,abortController:s,adbPort:c,limbarClient:l,playwrightDevice:u}){let d={controller:s},m=await ru.init({driver:e,logger:n,fixtures:o,orgId:i,limbarClient:l,options:a?.emulator??{},aborter:d,adbPort:c,playwrightDevice:u}),p=new r({driver:e,generator:t,stateManager:m,logger:n,fixtures:o,options:a,aborter:d,orgId:i,adbPort:c});return await p.initializeSettings(),p}async installApp(e){await this.stateManager.executeRawADBCommand(`install ${sz.resolve(e)}`)}async executeCommand(e){let t=["type","a11yData","thoughts","cache","code"],n;try{n=await bc({obj:e.command,context:this.fixtures.testContext,bannedKeys:t,orgId:this.orgId,logger:this.logger,signal:this.abortSignal,localTools:this.fixtures.localCodeEvalTools})}catch(o){throw this.throwIfAborted(),new Error(`ActionFailureError: Failed to substitute template strings in command: ${o.message}`,{cause:o})}try{return await this.executeCommandHelper(e)}catch(o){throw o.name!=="AbortError"&&this.logger.error({err:o},"Error thrown in action controller"),o}finally{Ec(e.command,n)}}async executeCommandHelper({command:e}){let t=Te();switch(e.type){case"TAP":return new yi(this.constructPerformerParams()).executeTap({command:e});case"TYPE":return await new Zc(this.constructPerformerParams()).doType(e);case"AI_CHECK":{let o=e.timeoutSecs?e.timeoutSecs*1e3:5e3,i=Cc(o),a=Date.now(),s=0,c,l=!1,u;for(;s<15&&!l;){this.throwIfAborted(),l||c&&c-a>=o&&(l=!0),s!==0&&await X(i,this.abortSignal),c=Date.now();try{let d="",m="";await t.startAsyncSpan("EMULATOR_READ_STATE",async()=>{d=(await this.stateManager.getDomState({})).graph.xml,m=await this.stateManager.getCurrentScreenshotPngString()},{name:"Get emulator state"});let p=await t.startAsyncSpan("AI_ASSERTION_CALL",async g=>{let h=await this.generator.evaluateAssertion({assertion:e.assertion,screenXml:d,screenshot:m},{logger:this.logger,loggerTags:ge(this.logger)});return g.result={thoughts:h.thoughts,result:h.result},h});if(p.result)return{success:p.result,message:p.thoughts};{let g=`AssertionFailureError: ${p.thoughts}`;u=new Error(g)}}catch(d){this.throwIfAborted(),this.logger.info({err:d},`AI check assert attempt ${s} failed, retrying...`),u=d instanceof Error?d:new Error(`${d}`)}finally{s++}}return{success:!1,message:u?.message}}case"SWIPE":return new Qc(this.constructPerformerParams()).executeSwipe(e);case"SCREEN_CHECK":return new tu(this.constructPerformerParams()).executeScreenCheck(e);case"JAVASCRIPT":{let n=await Ur({orgId:this.orgId,code:e.code,fragment:!1,context:this.fixtures.testContext,timeoutMs:e.timeout?e.timeout*1e3:void 0,logger:this.logger,localTools:this.fixtures.localCodeEvalTools,signal:this.abortSignal});try{JSON.stringify(n)}catch(o){throw new Error(`UserConfigurationError: Return value is not serializable: ${o instanceof Error?o.message:`${o}`}`)}return{success:!0,output:n}}case"REQUEST":{let n;try{n=new URL(e.url).hostname}catch(l){throw new Error(`UserConfigurationError: Invalid URL: ${l}`)}let o=new lz,i=az(fetch,o),a=Date.now(),s=await qc({command:e,baseUrl:void 0,logger:this.logger,fetchImplementation:i}),c=Js(o,n);return{output:{...s,cookies:c},success:!0,message:`Successfully executed request in ${Date.now()-a}ms`}}case"OPEN_NOTIFICATION_DRAWER":return await new In(this.constructPerformerParams()).doPress({keycode:83}),{success:!0};case"OPEN_APP":{let n=e.activityName;if(!n){let i=["resolve-activity","--brief","-a","android.intent.action.MAIN","-c","android.intent.category.LAUNCHER",e.packageName],a=await k(this.driver.execute("mobile: shell",{command:"pm",args:i}),{signal:this.abortSignal,milliseconds:1e4});if(typeof a!="string")throw new Error(`Could not find main activity name for package ${e.packageName}. Unexpected output: ${a}`);if(a.includes("No activity found"))throw new Error(`No activity found for package ${e.packageName}.`);if(n=a.trim().split(`
|
|
4159
4159
|
`).pop()?.replace(/^.*\//,""),!n)throw new Error(`Could not parse main activity name for package ${e.packageName}. Raw output: ${a}`)}if(this.options.emulator?.autoGrantPermissions&&!this.appsWithGrantedPermissions.has(e.packageName)){let i={permissions:"all",appPackage:e.packageName,action:"grant"};await this.driver.executeScript("mobile: changePermissions",[i]),this.appsWithGrantedPermissions.add(e.packageName)}let o=["start"];if(e.intentExtras)try{let i=JSON.parse(e.intentExtras);for(let[a,s]of Object.entries(i))o.push("-e",a,typeof s=="string"?s:JSON.stringify(s))}catch(i){throw new Error(`UserConfigurationError: Invalid intent extras does not parse as valid JSON: ${i instanceof Error?i.message:`${i}`}`)}return o.push("-n",`${e.packageName}/${n}`),await this.driver.execute("mobile: shell",{command:"am",args:o}),await this.stateManager.waitForScreenshotStability({timeoutMs:5e3,signal:this.abortSignal,reason:"Waiting for stability after app launch"}),{success:!0}}case"PRESS":{let n=new In(this.constructPerformerParams());switch(e.key){case"HOME":await n.doPress({keycode:3});break;case"BACK":await n.doPress({keycode:4});break;case"APP_SWITCHER":await n.doPress({keycode:187});break;case"POWER":await n.doPress({keycode:26});break;case"SEARCH":await n.doPress({keycode:84});break;case"VOLUME_UP":await n.doPress({keycode:24});break;case"VOLUME_DOWN":await n.doPress({keycode:25});break;case"VOLUME_MUTE":await n.doPress({keycode:164});break}return{success:!0}}case"PRESS_KEYBOARD":{let n=new In(this.constructPerformerParams()),o=i=>n.doPress({keycode:i});switch(e.key){case"CLOSE_KEYBOARD":{let i=Date.now();for(;Date.now()-i<5e3&&(await this.driver.hideKeyboard(),!!await this.driver.isKeyboardShown()););break}case"ENTER":await o(66);break;case"BACKSPACE":await o(67);break;default:{let i=e}}return{success:!0}}case"WAIT":return await X(e.timeoutSecs*1e3,this.aborter.controller?.signal),{success:!0};case"INSTALL_APP":return new eu(this.constructPerformerParams()).doInstallApk(e);case"ADD_FILE":{let n=await VR(e.file);return await this.driver.pushFile(e.storageLocation,n),await this.driver.execute("mobile: shell",{command:"am",args:["broadcast","-a","android.intent.action.MEDIA_SCANNER_SCAN_FILE","-d",`file://${e.storageLocation}`]}),{success:!0}}case"ADB":{let n=await this.driver.execute(e.command,JSON.parse(e.jsonArgs??"{}"));return this.logger.info({output:n},"ADB command executed successfully"),{success:!0,output:n,message:"ADB command executed successfully"}}case"KILL_APP":{let n=await this.stateManager.getCurrentPackage();if(!n)throw new Error("No package is currently active");await this.driver.execute("mobile: shell",{command:"input",args:["keyevent","KEYCODE_HOME"]}),await this.driver.terminateApp(n);try{await LR({packageName:n,driver:this.driver,abortSignal:this.abortSignal,logger:this.logger})}catch(o){this.throwIfAborted(),this.logger.warn({err:o,packageName:n},"Failed to remove package from recents, continuing...")}return{success:!0}}case"STATE":{await this.stateManager.refreshWebviews();let n=await this.stateManager.getDomState(),o=await this.stateManager.getContexts(),i={xml:n.graph.xml,contexts:o};return this.logger.info({result:i},"State debug command output"),{output:i,success:!0}}default:{let n=e;return{success:!0}}}}async initializeSettings(){let{latitude:e,longitude:t}=this.options?.emulator?.geolocation??Vs;await this.driver.execute("mobile: shell",{command:"pm",args:["grant","io.appium.settings","android.permission.ACCESS_COARSE_LOCATION"]}),await this.driver.execute("mobile: shell",{command:"pm",args:["grant","io.appium.settings","android.permission.ACCESS_FINE_LOCATION"]}),await this.driver.setGeoLocation({latitude:e,longitude:t})}async getScreenshotBase64(){return this.stateManager.getRawScreenshotBase64()}async getScreenshotPngString(){return this.stateManager.getCurrentScreenshotPngString()}async getA11yTree(){return(await this.stateManager.getDomState({})).graph.xml}async waitForScreenshotStability(e){return this.stateManager.waitForScreenshotStability({timeoutMs:e.timeoutMs??5e3,reason:e.reason,signal:this.aborter.controller?.signal})}resetAbortController(e){this.aborter.controller=e??new AbortController}isAborted(){return this.aborter.controller?.signal.aborted}abort(){this.aborter.controller?.abort()}async cleanup(){await this.stateManager.cleanupWebviews()}get abortSignal(){return this.aborter.controller?.signal}get context(){return this.fixtures.testContext}get localCodeEvalTools(){return this.fixtures.localCodeEvalTools}};async function KR({socket:r,logger:e,androidDriverFactory:t,getOrgId:n,mobileGeneratorFactory:o,browserGeneratorFactory:i,browserEnricherFactory:a,storageFactory:s,localToolsFactory:c,globalStateManager:l,settingsFactory:u}){let d=r.id,m=r.handshake.query?.testMetadata,p=r.handshake.query?.fileName,g=p?.endsWith("test.yaml")?p.slice(0,-"test.yaml".length):p,h=Mr.parse(JSON.parse(m??"")),f=h.id,E=h.settings?.defaultChannel,b=h.settings?.defaultTag,x=h.settings?.defaultApkFilePath?.trim(),T=await n({testId:f});e=e.child({sessionId:d,testId:f,orgId:T});let O={...(await u(T,e)).emulator,...h.settings?.emulator},w;if(O.region==="local"){if(!O.localEmulatorSettings?.avdId)throw new Error("AVD name is required when region is local");w={avdId:O.localEmulatorSettings.avdId,apkToInstall:E?{channel:E,tag:b}:void 0,apkFilePath:x||void 0}}else w={region:O.region,apkToInstall:E?{channel:E,tag:b}:void 0,osVersion:O.remoteEmulatorSettings?.androidVersion};let D=Date.now(),{driver:j,cleanup:ie,emulatorName:ee,adbPort:he,limbarClient:st,limbarToken:W,limbarUrl:B,playwrightDevice:ae}=await t({socket:r,logger:e,creationOpts:w}),ce=await yc({driver:j,onLogs:Eo=>{r.emit("logcatLogs",Eo)}});e.info({adbPort:he,apkChannel:E,apkTag:b,duration:Date.now()-D,emulatorName:ee},"Android emulator session initiated"),e=e.child({emulator:ee});let Ze=await o(T,e),Ce=await i(T,e),zt=await a(T,e),bt=await s(T),Ie=c?await c(T):void 0,qe={};h.settings?.defaultEnv&&(qe=(await bt.fetchEnvironment(h.settings?.defaultEnv,e))?.variables??{});let mr=new zo({variablesFromEnvironment:qe,envName:h.settings?.defaultEnv,testName:g}),xt=await Ti.init({driver:j,generator:Ze,logger:e,limbarClient:st,playwrightDevice:ae,options:{emulator:O},fixtures:{storage:bt,browserEnricher:zt,browserGenerator:Ce,localCodeEvalTools:Ie,testContext:mr},orgId:T,adbPort:he,abortController:new AbortController});if(!r.connected)throw await ce(),await ie(),new Error("Socket not connected anymore, not proceeding with Android session setup");let Vr=cz({socket:r,testContext:mr}),bo=async()=>{clearInterval(Vr);try{await ce(),await ie(),await xt.cleanup()}catch(Eo){e.warn({err:Eo},"Failed to clean up emulator in socket server")}};return l.registerSession(d,{controller:xt,cleanup:bo,emulatorName:ee,local:O.region==="local"}),r.emit("session",{testId:f,sessionId:d,limbarUrl:B,limbarToken:W}),{sessionId:d,testId:f,orgId:T,emulatorName:ee,logger:e}}function cz({socket:r,testContext:e}){return setInterval(()=>{let t=e.toEditorDisplayCopy();r.emit("emulatorState",{context:t})},3e3)}async function YR({socket:r,logger:e,globalStateManager:t}){await t.removeSession(r.id,e)}var uz=({socket:r,globalStateManager:e})=>async()=>{let t=e.getSession(r.id);if(!t)throw new Error("No active Android session found");t.controller.abort()},XR={event:"cancel",createHandler:uz};var dz=({logger:r,globalStateManager:e,socket:t})=>async(n,o)=>{let i=e.getSession(t.id);if(!i){o({err:"No active Android session found"});return}try{let s=await i.controller.getA11yTree();o({a11yTree:s})}catch(a){r.error({err:a},"Error fetching a11y tree from the session controller"),o({err:a.message})}},JR={event:"fetchA11yTree",createHandler:dz};import{diff as Mz}from"deep-object-diff";import{cloneDeep as _z}from"lodash-es";function ZR(r,e,t=1e4,n=5e3){let o=0;async function i(){try{let s=await k(r.driver.execute("mobile: shell",{command:"echo",args:["ping"]}).catch(c=>{throw c}),{milliseconds:n});if(typeof s=="string"&&s.trim()==="ping")o>0&&e.info("Driver heartbeat restored"),o=0;else throw new Error(`Unexpected heartbeat output: ${s}`)}catch(s){o++;let c=s instanceof Error?s.message:`${s}`;e.error({attempt:o,error:c},"Driver heartbeat failed"),o>=3&&e.error("Driver appears unresponsive \u2014 possible ADB tunnel/emulator failure")}}let a=setInterval(()=>{i()},t);return i(),a}async function QR(r){let e=Date.now(),t=r.fixtures.controller;try{return await mz(r)}catch(n){let o=t.isAborted()||n instanceof DOMException&&n.name==="AbortError";return{...r.moduleParams.step,steps:[],type:"MOBILE_MODULE_STEP",startTime:e,endTime:Date.now(),status:o?"CANCELLED":"FAILED",message:o?"Step cancelled.":`${n}`}}}async function mz({moduleParams:r,...e}){let t=Date.now(),{step:n,stepTracer:o,executeMobileStepList:i}=r,a=await pz({step:n,params:e}),s={};Object.entries(a).forEach(([m,p])=>{s[m]=JSON.stringify(p)});let c={...n,type:"MOBILE_MODULE_STEP",inputs:s,startTime:t,steps:[],endTime:Date.now(),status:"SUCCESS"},l=await o.startSubSteps(),{status:u,results:d}=await i({...e,listParams:{steps:n.steps,containerName:`module ('${n.name}')`,tracer:l}});return c.steps=d,c.status=u,c.endTime=Date.now(),lA({result:c,...sA(d)}),c}async function pz({step:r,params:e}){let t={},{logger:n,controller:o}=e.fixtures;for(let i of r.parameters?.parameterNames??[]){let a=r.inputs?.[i]??r.parameters?.defaultParameters?.[i];if(!a){n.warn({k:i},"No value found for parameter in module");continue}t[i]=await Ur({orgId:e.inputs.orgId,code:a,fragment:!0,logger:n,context:o.context,localTools:o.localCodeEvalTools})}return t}import{randomUUID as eC}from"crypto";async function tC({fixtures:r,step:e,inputs:t,stepTracer:n}){let o=Date.now(),{logger:i,controller:a}=r,s;if(!t.interactive)try{s=await a.getScreenshotBase64()}catch(l){i.warn({err:l},"Failed to take before screenshot")}let c={...e,status:"SUCCESS",startTime:o,endTime:Date.now()};try{let l=await a.executeCommand({command:e.command});c={...e,status:l.success?"SUCCESS":"FAILED",message:l.message,startTime:o,endTime:Date.now(),data:l.output}}catch(l){l instanceof Error&&l.name==="AbortError"||a.isAborted()?c={...e,status:"CANCELLED",message:"Step cancelled.",startTime:o,endTime:Date.now()}:(i.error({err:l},"Failed to execute preset step"),c={...e,status:"FAILED",message:l instanceof Error?l.message:String(l),startTime:o,endTime:Date.now()})}finally{if(!t.interactive){try{let l=eC(),u=await a.getScreenshotBase64();c.afterSnapshot=l,n.attachAfterScreenshot({logger:i,snapshotId:l,screenshot:Buffer.from(u,"base64")})}catch(l){i.warn({err:l},"Failed to take after screenshot")}if(s){let l=eC();c.beforeSnapshot=l,n.attachBeforeScreenshot({logger:i,snapshotId:l,screenshot:Buffer.from(s,"base64")})}}}return c}import{streamText as wz}from"ai";import{randomUUID as Rz}from"crypto";var nu=class{controller;logger;callbacks;rootStep;subStepIndex=0;finalState=void 0;results=[];constructor(e){let{controller:t,logger:n,callbacks:o,rootStep:i}=e;this.controller=t,this.logger=n,this.callbacks=o,this.rootStep=i}async createAndExecuteStep(e){this.callbacks.onAiActionEvent?.({type:"SUBSTEP_CREATED",rootStep:this.rootStep,step:e});let t=this.subStepIndex++,n=await this.callbacks.executeStep(e,t);return this.results.push(n),n}};import{hasToolCall as vz,stepCountIs as Az}from"ai";var rC="get_emulator_state",ou="finish";import nC from"dedent";var hz=nC`
|
|
@@ -4193,7 +4193,7 @@ Momentic users value the following:
|
|
|
4193
4193
|
${n.map(o=>o.configFilePath)}`);if(n.length===0)throw new Error("No valid Momentic project file available.");return R.debug(`Found valid project configuration at ${n[0].configFilePath}`),n[0]}async function u1(r){let e=l1(r);if(!e||!e.projects||!e.projects.length)return;let t=e.projects.map(a=>(a.endsWith("/")||(a+="/"),`${a}*${wi}`)),n=AbortSignal.timeout(2e3),o;try{o=await r1(t,{absolute:!1,cwd:Eg(),dotRelative:!1,maxDepth:bg,nodir:!0,signal:n})}catch(a){throw R.error({err:a},`Failed to list the available Momentic projects in the current directory. This usually indicates the 'include' or 'exclude' option in your ${Tg} is misconfigured.`),a}let i=[];for(let a of o){let s=ho.join(Eg(),a),c=vg(s);c&&i.push({configFilePath:s,config:c,rootDir:bC(s)})}return i}async function d1(r){if(r){r=ho.resolve(r);let t=vg(r);return t||(console.error(`No valid Momentic project file found at ${r}.`),process.exit(1)),[{config:t,configFilePath:r,rootDir:ho.dirname(r)}]}if(Zz(Tg)){let t=await u1(Tg);if(t)return t}return c1()}function vC(r,e){let t=EC.stringify(r);t1(e,t)}import{z as Ag}from"zod";var AC="test-results";var LOe=Ag.object({width:Ag.number(),height:Ag.number()});import{execFile as m1}from"node:child_process";import{promisify as p1}from"node:util";import g1 from"simple-git";var Oe=g1(),wC=p1(m1);async function h1(r){let e=await Le(r,Oe.raw(["config","--list"])),t={};if(!e)return t;for(let n of e.split(`
|
|
4194
4194
|
`)){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 f1(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 wC("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 wC("gh",o,{timeout:5e3}),a=i?.toString().trim();if(a)return a}catch{}}}async function S1(r,e,t){let n=e?.includes("github.com"),o=e?.includes("gitlab.com");try{if(n)return f1(r,e,t);if(o)return}catch{}}function lu(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 Le(r,e){try{return(await e).trim()}catch(t){r.error({err:t},"Failed to run git command");return}}function y1(){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 b1(r){let[e,t,n]=await Promise.all([Le(r,Oe.show(["--no-patch","--format=%ci"])),Le(r,Oe.show(["-s","--pretty=%B"])),Le(r,Oe.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 E1(r){let[e,t,n]=await Promise.all([Le(r,Oe.listRemote(["--get-url","origin"])),Le(r,Oe.show(["-s","--pretty=%B"])),Le(r,Oe.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 T1(r){let[e,t,n,o]=await Promise.all([Le(r,Oe.show(["--no-patch","--format=%ci"])),Le(r,Oe.listRemote(["--get-url","origin"])),Le(r,Oe.show(["-s","--pretty=%B"])),Le(r,Oe.show(["-s","--pretty=%an"]))]),i=t?.includes("github.com"),a=t?.includes("gitlab.com"),s=t?lu(t):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:process.env.CIRCLE_REPOSITORY_URL,gitCommitMessage:n,gitCommitAuthorName:o,githubRepository:i?s:void 0,gitlabProjectPath:a?s:void 0,pipelineId:process.env.CIRCLE_PIPELINE_ID}}async function v1(r){let[e,t,n]=await Promise.all([Le(r,Oe.show(["--no-patch","--format=%ci"])),Le(r,Oe.show(["-s","--pretty=%B"])),Le(r,Oe.show(["-s","--pretty=%an"]))]),o=process.env.BUILDKITE_REPO,i=o?.includes("github.com"),a=o?.includes("gitlab.com"),s=o?lu(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 A1(r){let[e,t,n]=await Promise.all([Le(r,Oe.show(["--no-patch","--format=%ci"])),Le(r,Oe.show(["-s","--pretty=%B"])),Le(r,Oe.show(["-s","--pretty=%an"]))]),o=process.env["Build.Repository.Uri"],i=o?.includes("github.com"),a=o?.includes("gitlab.com"),s=o?lu(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 w1(r,e){let[t,n,o,i,a,s,c,l,u]=await Promise.all([Le(r,Oe.revparse(["HEAD"])),Le(r,Oe.revparse(["--short","HEAD"])),Le(r,Oe.revparse(["--abbrev-ref","HEAD"])),Le(r,Oe.listRemote(["--get-url","origin"])),Le(r,Oe.show(["--no-patch","--format=%ci"])),Le(r,Oe.show(["-s","--pretty=%B"])),Le(r,Oe.show(["-s","--pretty=%an"])),e?Le(r,Oe.raw(["merge-base","--fork-point",e])):Promise.resolve(void 0),h1(r)]),d=l?await Le(r,Oe.show(["--no-patch","--format=%ci",l])):void 0,m=i?.includes("github.com"),p=i?.includes("gitlab.com"),g=i?lu(i):void 0,h=u["user.email"]||void 0,f=u["user.name"]||void 0,E=u["user.username"]||void 0,b=await S1(r,i,u)??E??void 0;return{ciProvider:"none",gitCommitSha:t,gitCommitShaShort:n,gitBranchName:o,gitOriginUrl:i,gitCommitTimestamp:a?new Date(a):void 0,gitCommitMessage:s,gitCommitAuthorName:c,gitLocalUsername:b,gitLocalEmail:h,gitLocalName:f,lastCommitOnMainSha:l,lastCommitOnMainTimestamp:d?new Date(d):void 0,githubRepository:m?g:void 0,gitlabProjectPath:p?g:void 0,pipelineId:void 0}}async function R1(){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 C1(r){let e=r.config.gitProtectedBranches??[];return r.config.gitMainBranch&&e.push(r.config.gitMainBranch),{gitMainBranch:r.config.gitMainBranch,gitProtectedBranches:e}}async function ls(r,e){let t=y1();if(!t)return w1(r,e);switch(t){case"GithubActions":return b1(r);case"GitlabCI":return E1(r);case"CircleCI":return T1(r);case"Buildkite":return v1(r);case"AzureDevOps":return A1(r);case"GCPCloudBuild":return R1()}}async function x1(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 M1(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 _1(r,e,t){try{if(t.githubRepository){let[n,o]=t.githubRepository.split("/");return await M1(r,e,n,o,t)}else if(t.gitlabProjectPath)return await x1(r,e,t.gitlabProjectPath,t)}catch(n){r.warn({err:n},"Failed to get remote git metadata")}return t}async function Ri(r,e,t){let n=await C1(t),o=await ls(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 _1(r,e,i);return{...n,...o,...a}}import{diff as RC}from"deep-object-diff";import Ln from"fs";import{cloneDeep as P1}from"lodash-es";import cu from"path";import{v4 as I1}from"uuid";import cs from"yaml";function CC({content:r,schemaVersion:e,momenticFiles:t,project:n,forceSaveOnNoDiffs:o}){let i=t.mobileModules[r.moduleId]?.fullFilePath;if(!i||!Ln.existsSync(i))throw new Error(`Tried to update mobile module ${r.moduleId} that could not be found on disk`);let a=Ln.readFileSync(i,"utf-8"),s=cs.parse(a),c={...s,...r,schemaVersion:e},l=io({fileType:xe.MOBILE_MODULE,...ma.parse(c),steps:Sr.array().parse(r.steps)}),u=RC(l,s);if(u&&Object.keys(u).length===0&&!o)return;let d=cs.stringify(l);Ln.writeFileSync(i,d,"utf-8"),On(i,n.config)}function xC({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=us(i,o),s={...a,...e},c=io({fileType:xe.MOBILE_MODULE,...ol.parse(s)}),l=RC(c,a);if(l&&Object.keys(l).length===0)return;let u=cs.stringify(c);Ln.writeFileSync(i,u,"utf-8");let d;if(e.name){let m=`${qr(e.name)}.module.yaml`;if(d=cu.join(cu.dirname(i),m),Ln.existsSync(d))throw new Error(`A conflicting file already exists at the following path: ${d}`);Ln.renameSync(i,d)}On(d||i,n.config)}async function MC({name:r,description:e,enabled:t,steps:n,folder:o,project:i}){let a=qr(r),s=cu.join(o,`${a}.module.yaml`),c=I1(),{stepsToSave:l}=await Rn({steps:n}),u={schemaVersion:sn,moduleId:c,description:e,enabled:t},d={fileType:xe.MOBILE_MODULE,...u,steps:l},m=cs.stringify(GS.parse(d));return Ln.writeFileSync(s,m,"utf-8"),On(s,i.config),{moduleId:c,name:r,description:e||void 0,steps:n}}function us(r,e){let t=Ln.readFileSync(r,"utf-8"),n=cs.parse(t);try{return{...ol.parse(n),name:cu.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 wg(r,e,t,n){let o=us(r.fullFilePath,t),{resolvedSteps:i}=await Ac({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 us(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]=P1(a)),a}async function _C(r,e){let t={};return await Promise.all(Object.values(r.mobileModules).map(async n=>{await wg(n,r,e,t)})),Array.from(Object.values(t))}import{randomUUID as O1}from"crypto";import fo from"fs";import Rg from"path";import uu from"yaml";function PC({name:r,description:e="",steps:t=[],settings:n={},folder:o}){let a=`${qr(r)}.test.yaml`,s=Rg.join(o,a);if(fo.existsSync(s))throw new Error(`A test named '${r}' already exists at path '${s}'. Choose a different name.`);let c={fileType:xe.MOBILE_TEST,id:O1(),description:e,schemaVersion:id,settings:n,steps:t},l=uu.stringify(c);return fo.writeFileSync(s,l,"utf-8"),{fullPath:s,testId:c.id}}function L1(r){if(!fo.existsSync(r))throw new Error(`Test file not found: ${r}`);let e=fo.readFileSync(r,"utf-8").replace(/\r\n|\r/g,`
|
|
4195
4195
|
`),t=uu.parse(e),n=il.parse(t);if(n.fileType!==xe.MOBILE_TEST)throw new Error(`File is not a mobile test (fileType=${n.fileType}): ${r}`);return n}async function du(r,e,t){let n=L1(r),o;try{o=Mr.parse(n)}catch(s){throw new Error(`Mobile test ${r} is missing metadata or has invalid metadata: ${s}`)}let{resolvedStepLists:i}=await rA({rawStepLists:{steps:n.steps,beforeSteps:void 0,afterSteps:void 0},logger:e,testMetadata:o,onFetchModule:async s=>{let c=t.mobileModules[s]?.fullFilePath;if(!c)throw new Error(`Mobile module ${s} not found`);return us(c,e)}});return{...o,steps:i.steps}}async function IC({filePath:r,steps:e,settings:t,folder:n,project:o,momenticFiles:i}){let a=Rg.isAbsolute(r)?r:Rg.join(n,r);if(!fo.existsSync(a))throw new Error(`Test file not found: ${a}`);let s=fo.readFileSync(a,"utf-8").replace(/\r\n|\r/g,`
|
|
4196
|
-
`),c=uu.parse(s),l=il.parse(c);if(l.fileType!==xe.MOBILE_TEST)throw new Error(`File at '${a}' is not a mobile test (fileType=${l.fileType}).`);let u;e&&(u=await Rn({steps:e}));let d={...l,...u?.stepsToSave!==void 0?{steps:u.stepsToSave}:{},...t!==void 0?{settings:t}:{}},m=uu.stringify(il.parse(d));for(let p of u?.moduleUpdates??[])CC({content:p,schemaVersion:id,momenticFiles:i,project:o});fo.writeFileSync(a,m,"utf-8"),On(a,o.config)}import{randomUUID as N1}from"crypto";import Nn from"fs";import Ci from"path";var OC=new Set([".DS_Store","__MACOSX"]),LC={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 D1(r,e,t){if(LC[t]){let i=LC[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 Cg=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 NC(r,e){try{let t=Ci.join(e,"metadata.json");return yl.parse(JSON.parse(Nn.readFileSync(t,"utf-8")))}catch{throw new Cg(r,e)}}function DC(r,e,t){let n=N1(),o=r.child({runGroupId:n});Nn.rmSync(e,{recursive:!0,force:!0});let i=Nn.readdirSync(t).filter(c=>!OC.has(c)).map(c=>Ci.join(t,c));if(i.length===0)throw new Error(`No run groups found in results path: ${t}`);Nn.mkdirSync(e,{recursive:!0});let a={...NC(t,i[0]),id:n};for(let c of i){let l=Ci.join(c,"runs");if(!Nn.existsSync(l))continue;let u=NC(t,c);o.info({oldRunGroupId:u.id},"Merging run groups");for(let m in u){if(m==="id")continue;let p=m;a[p]=D1(a,u,p)}let d=Nn.readdirSync(l);for(let m of d){if(OC.has(m))continue;let p=Ci.join(l,m),g=Ci.join(e,"runs",m);Nn.cpSync(p,g,{recursive:!0})}}let s=Ci.join(e,"metadata.json");Nn.writeFileSync(s,JSON.stringify(a,null,2))}import UC from"adm-zip";import Og from"fs";import{z as G1}from"zod";var U="v1",xg="mobile-cli",So="0.7.0";var k1=9e4,U1=3,F1=1500,B1=15e3,Tr=class extends Error{status;rawError;constructor(e,t,n,o={}){super(n,o),this.status=e,this.rawError=t}};async function z1(r){return r.text().then(e=>{try{return JSON.parse(e).error}catch{return e}})}var Mg=class{baseUrl;logger;constructor(e){this.baseUrl=e.baseUrl,this.logger=e.logger}getHeaders(){let e={"Content-Type":"application/json"};return So&&(e[hl]=So),xg&&(e[hy]=xg),e}async sendRequest(e,t){let{retries:n=U1,requestTimeoutMs:o=k1,initialRetryDelayMs:i=F1,maxRetryDelayMs:a=B1,onFailedRequest:s}=t,c=n,l=n,u,d={path:e,baseUrl:this.baseUrl,method:t.method};for(;c>0;)try{return c--,await this.sendSingleRequestHelper(e,t,o)}catch(m){u=m;try{s?.(u)}catch{}if(m instanceof Tr&&m.status>=400&&m.status<500)throw m;if(m instanceof Error&&m.name==="AbortError"&&(u=new fn),c===0)throw u;let p=l-c,g=Math.min(i*Math.pow(2,p-1),a);await new Promise(h=>setTimeout(h,g))}throw this.logger.warn({...d,err:u},"Got fatal error response from Momentic server"),u}async sendSingleRequestHelper(e,t,n){let o={path:e,baseUrl:this.baseUrl,method:t.method},i=new AbortController,a=setTimeout(()=>i.abort(),n),s=()=>i.abort();t.signal&&t.signal.addEventListener("abort",s,{once:!0});let c=Date.now(),l={...this.getHeaders(),...t.extraHeaders};try{let u=await fetch(`${this.baseUrl}${e}`,{method:t.method,body:t.body?JSON.stringify(t.body):void 0,headers:l,signal:i.signal});if(!u.ok){let m=await z1(u);throw new Tr(u.status,m,`Request to ${t.method} ${e} failed with status ${u.status}: ${m}`)}let d;if(u.status===204)d={};else{let m=await u.text();try{d=JSON.parse(m)}catch{d=m}}return this.logger&&t.logResponse===!0&&d&&this.logger.debug({result:d,status:u.status,durationMs:Date.now()-c,...o},"Got response from Momentic server"),d}finally{clearTimeout(a),t.signal&&t.signal.removeEventListener("abort",s)}}},Gr=class extends Mg{apiKey;mode;constructor(e){super(e),this.apiKey=e.apiKey,this.mode=e.mode}getHeaders(){return{...super.getHeaders(),Authorization:`Bearer ${this.apiKey}`,[gy]:this.mode??""}}};import{createAnthropic as H1}from"@ai-sdk/anthropic";var mu=({baseUrl:r,apiKey:e,sessionId:t,extraHeaders:n,loggerTags:o})=>i=>{let a={Authorization:`Bearer ${e}`,[hl]:So??"",...t&&{[Sy]:t},...n||{}};return o&&(a[fy]=JSON.stringify(o)),H1({baseURL:`${r}/v1/llm/anthropic/${i}`,headers:a,apiKey:e})(i)};var yo=class extends Gr{agentConfig;constructor(e,t){let n={...fS,...e};super(t),this.agentConfig=n}getAgentConfig(){return this.agentConfig}async rankChunksWithAi(e,t){let n={...e,loggerTags:t.loggerTags},o=await this.sendRequest(`/${U}/web-agent/recommend-chunks-ai`,{method:"POST",body:n,signal:t.abortSignal});return nS.parse(o)}async rankChunksWithRag(e,t){let n=await this.sendRequest(`/${U}/web-agent/recommend-chunks`,{method:"POST",body:{cliVersion:So,...e},signal:t.abortSignal});return rS.parse(n)}async getScreenshotFromS3(e){let t=await this.sendRequest(`/${U}/s3/visual-diff-screenshot`,{method:"POST",body:{url:e}});return G1.string().parse(t)}async getElementLocation(e,t){let n={...e,disableCache:t.disableCache,loggerTags:t.loggerTags,useMemory:t.useMemory,agentConfigVersion:this.agentConfig?.locator},o=await this.sendRequest(`/${U}/web-agent/locate-element`,{method:"POST",body:n,signal:t.abortSignal});return Ty.parse(o)}async getAssertionResult(e,t){let n={...e,disableCache:!!t.disableCache,useConsensus:!!t.useConsensus,attemptNumber:t.attemptNumber,loggerTags:t.loggerTags,useMemory:t.useMemory,agentConfigVersion:this.agentConfig?.assertion},o=await this.sendRequest(`/${U}/web-agent/assertion`,{method:"POST",body:n,signal:t.abortSignal});return Jd.parse(o)}async getLintStepResult(e,t){let n={...e,disableCache:!!t.disableCache,loggerTags:t.loggerTags},o=await this.sendRequest(`/${U}/web-agent/lint/step`,{method:"POST",body:n,signal:t.abortSignal});return Ey.parse(o)}async getLintMcpCopilotMessageResult(e,t){let n={message:e.message,disableCache:!!t.disableCache,loggerTags:t.loggerTags},o=await this.sendRequest(`/${U}/web-agent/lint/mcp-copilot`,{method:"POST",body:n,signal:t.abortSignal});return by.parse(o)}async getVisualAssertionResult(e,t){let n={...e,disableCache:!!t.disableCache,useConsensus:!!t.useConsensus,attemptNumber:t.attemptNumber,loggerTags:t.loggerTags,useMemory:t.useMemory,agentConfigVersion:this.agentConfig?.["visual-assertion"]},o=await this.sendRequest(`/${U}/web-agent/visual-assertion`,{method:"POST",body:n,signal:t.abortSignal});return Jd.parse(o)}async getAiActionCommand(e,t){let n=await this.sendRequest(`/${U}/web-agent/next-command-dynamic`,{method:"POST",body:{...e,disableCache:t.disableCache,loggerTags:t.loggerTags},signal:t.abortSignal});return yy.parse(n)}async getMultiturnAiActionCommand(e,t){return await this.sendRequest(`/${U}/web-agent/ai-action/next-command`,{method:"POST",body:{...e,disableCache:t.disableCache,loggerTags:t.loggerTags},signal:t.abortSignal})}async getMultiturnAiActionEvaluation(e,t){let n=await this.sendRequest(`/${U}/web-agent/ai-action/evaluate`,{method:"POST",body:{...e,disableCache:t.disableCache,loggerTags:t.loggerTags},signal:t.abortSignal});return ld.parse(n)}async getReverseMappedDescription(e,t){let n=await this.sendRequest(`/${U}/web-agent/reverse-mapped-description`,{method:"POST",body:{...e,disableCache:t.disableCache,loggerTags:t.loggerTags},signal:t.abortSignal});return vy.parse(n)}async getTextExtraction(e,t){let n={...e,disableCache:t.disableCache,loggerTags:t.loggerTags,agentConfigVersion:this.agentConfig?.["text-extraction"]},o=await this.sendRequest(`/${U}/web-agent/text-extraction`,{method:"POST",body:n,signal:t.abortSignal});return ad.parse(o)}async getPageSummary(e,t){let n={...e,disableCache:t.disableCache,loggerTags:t.loggerTags},o=await this.sendRequest(`/${U}/web-agent/page-summary`,{method:"POST",body:n,signal:t.abortSignal});return Df.parse(o)}async getSmartWaitingDecision(e,t){let n={...e,disableCache:t.disableCache,loggerTags:t.loggerTags},o=await this.sendRequest(`/${U}/web-agent/smart-waiting`,{method:"POST",body:n,signal:t.abortSignal});return kf.parse(o)}async getTestResultClassification(e,t){let n=await this.sendRequest(`/${U}/web-agent/result-classification`,{method:"POST",body:{...e,loggerTags:t.loggerTags},signal:t.abortSignal});return $u.parse(n)}async getExtractedKeywords(e,t){let n=await this.sendRequest(`/${U}/web-agent/extract-keywords`,{method:"POST",body:e,signal:t.abortSignal});return hS.parse(n)}async getAutohealingProposal(e,t){let n=await this.sendRequest(`/${U}/web-agent/autoheal-section`,{method:"POST",body:{...e,loggerTags:t.loggerTags},signal:t.abortSignal});return Pf.parse(n)}async getFailureRecoveryProposal(e,t){let n=await this.sendRequest(`/${U}/web-agent/failure-recovery`,{method:"POST",body:{...e,loggerTags:t.loggerTags},signal:t.abortSignal});return Lf.parse(n)}async getFailureRecoveryPlan(e,t){let n=await this.sendRequest(`/${U}/web-agent/failure-recovery-plan`,{method:"POST",body:{...e,loggerTags:t.loggerTags},signal:t.abortSignal});return Of.parse(n)}async getIframeRegex(e,t){let n=await this.sendRequest(`/${U}/web-agent/iframe-regex`,{method:"POST",body:e,signal:t.abortSignal});return uh.parse(n)}getVercelAnthropicModelFactory({loggerTags:e}){return mu({baseUrl:this.baseUrl,apiKey:this.apiKey,loggerTags:e})}};import{z as _g}from"zod";var vr=class extends Gr{constructor(e){super({...e,mode:void 0})}getAppUrl(){return this.baseUrl==="http://localhost:8000"?"http://localhost:3000":this.baseUrl.replace(/\/\/api/,"//app")}async getAuthInfo(){let e=await this.sendRequest(`/${U}/auth/check`,{method:"GET",retries:10,requestTimeoutMs:5e3,onFailedRequest:t=>{R.warn(`API key check failed: ${t.message}`)}});return Dy.parse(e)}async bulkGetRunStatus(e){let t=await this.sendRequest(`/${U}/runs/status`,{method:"POST",body:e,retries:3,requestTimeoutMs:1e4});return Iy.parse(t)}async getTestYAMLExport(e){let t=await this.sendRequest(`/${U}/tests/export`,{method:"POST",body:e,retries:3,requestTimeoutMs:3e4});return wy.parse(t)}async updateStepCaches(e,t){await this.sendRequest(`/${U}/cache`,{method:"PATCH",body:e,extraHeaders:t,retries:3,requestTimeoutMs:1e4,initialRetryDelayMs:3e3})}async getStepCacheForTest(e,t){let n=await this.sendRequest(`/${U}/cache`,{method:"POST",body:e,extraHeaders:t,retries:10,requestTimeoutMs:3e4,initialRetryDelayMs:3e3});return Cy.parse(n)}async updateMobileStepCaches(e,t){await this.sendRequest(`/${U}/mobile-cache`,{method:"PATCH",body:e,extraHeaders:t,retries:3,requestTimeoutMs:1e4,initialRetryDelayMs:3e3})}async getMobileStepCacheForTest(e,t){let n=await this.sendRequest(`/${U}/mobile-cache`,{method:"POST",body:e,extraHeaders:t,retries:10,requestTimeoutMs:3e4,initialRetryDelayMs:3e3});return xy.parse(n)}async queueTests(e){let t=await this.sendRequest(`/${U}/tests/queue`,{method:"POST",body:e,retries:3,requestTimeoutMs:1e4});return Ay.parse(t)}async uploadScreenshot(e){let t=await this.sendRequest(`/${U}/screenshots`,{method:"POST",body:e,retries:3,requestTimeoutMs:5e3});return Ny.parse(t)}async getAllEnvironments(){let e=await this.sendRequest(`/${U}/environments`,{method:"GET",retries:3,requestTimeoutMs:5e3});return ky.parse(e)}async acquireCacheLock(e,t){let n=await this.sendRequest(`/${U}/result-cache/lock`,{method:"POST",body:e,signal:t,retries:3,requestTimeoutMs:3e4});return Jy.parse(n)}async releaseCacheLock(e){await this.sendRequest(`/${U}/result-cache/lock`,{method:"DELETE",body:{key:e},retries:3,requestTimeoutMs:5e3})}async deleteCacheResult(e){await this.sendRequest(`/${U}/result-cache/entry`,{method:"DELETE",body:e,retries:3,requestTimeoutMs:5e3})}async setCacheResult(e){await this.sendRequest(`/${U}/result-cache/entry`,{method:"PATCH",body:e,retries:3,requestTimeoutMs:5e3})}async getCacheResult(e){try{return await this.sendRequest(`/${U}/result-cache/entry`,{method:"POST",body:e,retries:3,requestTimeoutMs:5e3})}catch(t){if(t instanceof Error&&t.message.includes("404"))return null;throw t}}async queueSuiteRuns(e){let t=await this.sendRequest(`/${U}/suites/queue`,{method:"POST",body:e,retries:3,requestTimeoutMs:5e3});return Uy.parse(t)}async bulkGetRunGroupStatus(e){let t={runGroupIds:e},n=await this.sendRequest(`/${U}/run-groups/status`,{method:"POST",body:t,retries:3,requestTimeoutMs:5e3});return Zf.array().parse(n)}async uploadProposedSteps(e,t){try{await this.sendRequest(`/${U}/test-fragments/`,{method:"POST",body:e,retries:3,requestTimeoutMs:1e4})}catch(n){t.error({err:n},"Failed to upload proposed steps")}}async reportBillableEvents(e,t){try{await this.sendRequest(`/${U}/billing/events`,{method:"POST",body:t,retries:10,requestTimeoutMs:1e4})}catch(n){e.error({err:n},"Failed to report billable event")}}async fetchTestFragment(e){let t=await this.sendRequest(`/${U}/test-fragments/${e}`,{method:"GET",retries:3,requestTimeoutMs:1e4});return Fy.parse(t)}async patchTestFragment(e,t){await this.sendRequest(`/${U}/test-fragments/${e}`,{method:"PATCH",body:t,retries:3,requestTimeoutMs:1e4})}async getPastTestResults(e,t){let n=await this.sendRequest(`/${U}/results/tests/${e}`,{method:"POST",body:t,retries:3,requestTimeoutMs:1e4});return By.parse(n)}async generateTestResultsUploadUrl(){let e=await this.sendRequest(`/${U}/results/uploads`,{method:"POST",retries:3,requestTimeoutMs:1e4});return zy.parse(e)}async startProcessingResultsUpload(e,t){let n=await this.sendRequest(`/${U}/results/uploads/${e}/process`,{method:"POST",body:t,retries:3,requestTimeoutMs:1e4});return Hy.parse(n)}async fetchIconKnowledgeBase(e){try{let t=await this.sendRequest(`/${U}/knowledge-base/icons`,{method:"GET",retries:3,requestTimeoutMs:5e3});return eb.parse(t)}catch(t){return e.error({err:t},"Failed to fetch icon knowledge base"),null}}async saveNewIcons(e,t){try{await this.sendRequest(`/${U}/knowledge-base/icons`,{method:"POST",body:e,retries:3,requestTimeoutMs:5e3})}catch(n){t.error({err:n},"Failed to save new icons to icon knowledge base")}}async getMergeBaseCommitFromGithub(e,t,n,o){let i=new URLSearchParams;i.set("base",n),i.set("head",o);let a=await this.sendRequest(`/${U}/git/github/${e}/${t}/merge-base-commit?${i.toString()}`,{method:"GET",retries:3,requestTimeoutMs:1e4});return Ea.parse(a)}async getCommitFromGithub(e,t,n){let o=await this.sendRequest(`/${U}/git/github/${e}/${t}/commits/${n}`,{method:"GET",retries:3,requestTimeoutMs:1e4});return Ea.parse(o)}async getMergedBranchFromGithub(e,t,n,o){let i=encodeURIComponent(n),a=await this.sendRequest(`/${U}/git/github/${e}/${t}/${i}/${o}/merged-branch`,{method:"GET",retries:3,requestTimeoutMs:1e4});return tm.parse(a)}async getMergeBaseCommitFromGitlab(e,t,n){let o=new URLSearchParams;o.set("base",t),o.set("head",n);let i=encodeURIComponent(e),a=await this.sendRequest(`/${U}/git/gitlab/${i}/merge-base-commit?${o.toString()}`,{method:"GET",retries:3,requestTimeoutMs:5e3});return Ea.parse(a)}async getCommitFromGitlab(e,t){let n=encodeURIComponent(e),o=await this.sendRequest(`/${U}/git/gitlab/${n}/commits/${t}`,{method:"GET",retries:3,requestTimeoutMs:1e4});return Ea.parse(o)}async getMergedBranchFromGitlab(e,t,n){let o=encodeURIComponent(t),i=encodeURIComponent(e),a=await this.sendRequest(`/${U}/git/gitlab/${i}/${o}/${n}/merged-branch`,{method:"GET",retries:3,requestTimeoutMs:1e4});return tm.parse(a)}async getAgentConfig(){let e=await this.sendRequest(`/${U}/web-agent/agent-config`,{method:"GET",retries:3,requestTimeoutMs:5e3});return _g.record(_g.string(),_g.string()).parse(e)}async getQuarantinedTests(){let e=await this.sendRequest(`/${U}/quarantine`,{method:"GET"});return Gy.parse(e)}async quarantineTest(e,t,n){await this.sendRequest(`/${U}/quarantine`,{method:"POST",body:{testId:e.id,testName:e.name,reason:t,...n??{}},retries:3,requestTimeoutMs:1e4})}async unquarantineTest(e,t,n){await this.sendRequest(`/${U}/quarantine/${e.id}`,{method:"DELETE",body:{testName:e.name,reason:t,...n??{}},retries:3,requestTimeoutMs:1e4})}async createAndroidEmulator(e){let t=await this.sendRequest(`/${U}/limbar/android`,{method:"POST",retries:3,body:e,requestTimeoutMs:9e4,initialRetryDelayMs:5e3,maxRetryDelayMs:15e3});return Vy.parse(t)}async extendAndroidEmulatorTtl(e){try{await this.sendRequest(`/${U}/limbar/android/${e}/keepalive`,{method:"POST",retries:3,requestTimeoutMs:15e3})}catch{}}async generateAndroidAssetUrls({channel:e,tag:t,md5:n}){let o={channel:e,tag:t,md5:n},i=await this.sendRequest(`/${U}/limbar/android/upload-url`,{method:"POST",retries:3,body:o,requestTimeoutMs:15e3,logResponse:!0});return jy.parse(i)}async deleteAndroidEmulator(e){await this.sendRequest(`/${U}/limbar/android/${e}`,{method:"DELETE",retries:3,requestTimeoutMs:3e4})}async getAndroidAssets(){let e=await this.sendRequest(`/${U}/limbar/assets`,{method:"GET",retries:3,requestTimeoutMs:1e4});return Wy.parse(e)}async deleteAndroidAsset(e,t){await this.sendRequest(`/${U}/limbar/assets/${e}/${t}`,{method:"DELETE",retries:3,requestTimeoutMs:1e4})}};async function Pg(r){let e=process.versions.node,t=parseInt(e.split(".")[0]);(isNaN(t)||t<18)&&(R.error(`Node.js version 20 or higher is required to run the CLI. Detected: ${process.versions.node}.`),process.exit(1)),R.debug(`Identified node version ${e}`);let n=await r.client.getAuthInfo();return R.debug("Got auth info from API"),n}var pu=class{apiClient;constructor(e){this.apiClient=e}async reportBillableEvents(e,t){await this.apiClient.reportBillableEvents(e,t)}};var xi=class extends Gr{generator;constructor(e,t){super(e),this.generator=t}async runTemplateMatching(e,t={}){let n=await this.sendRequest(`/${U}/web-agent/template-matching`,{method:"POST",body:e,signal:t?.signal});return dh.parse(n)}async constructIframeRegex(e,t={}){return this.generator.getIframeRegex(e,{abortSignal:t.signal})}};var Mi=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 V1,en as j1}from"@faker-js/faker";var _i="v1",Pi=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 V1({locale:j1}),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 Tr?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 Tr?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 Tr?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 Tr?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 Tr?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 Tr?new Error(t.rawError):new Error(`Failed to fetch latest emails: ${t.message}`)})}};function kC(r,e,t){return fetch(r,{method:"PUT",body:t,headers:{"Content-Type":e}})}var gu=class{constructor(e){this.client=e}async uploadResultsArchive(e,t){let{uploadUrl:n,id:o}=await this.client.generateTestResultsUploadUrl(),i=await kC(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 Ii=class extends Gr{constructor(e){super(e)}async getElementLocation(e,t){let n={...e,loggerTags:t.loggerTags},o=await this.sendRequest(`/${U}/mobile-agent/locate-element`,{method:"POST",body:n,signal:t.abortSignal});return yS.parse(o)}async evaluateAssertion(e,t){let n={...e,loggerTags:t.loggerTags},o=await this.sendRequest(`/${U}/mobile-agent/assertion`,{method:"POST",body:n,signal:t.abortSignal});return TS.parse(o)}getVercelAnthropicModelFactory({loggerTags:e,sessionId:t}){return mu({baseUrl:this.baseUrl,apiKey:this.apiKey,sessionId:t,loggerTags:e})}};function hu({orgId:r,client:e,gitMetadata:t,regenerateCache:n,alwaysSaveCache:o,noCache:i}){return i?new Sl:new Ig(r,e,t,o)}var Ig=class{constructor(e,t,n,o){this.orgId=e;this.client=t;let{gitBranchName:i,gitProtectedBranches:a}=n;this.cacheHeaders=Zd(n),o?this.writeCaches=!0:i?this.writeCaches=!a.includes(i):this.writeCaches=!0}cacheHeaders;writeCaches;async saveEntries({entries:e,testId:t,logger:n}){if(!this.writeCaches){n.debug("Skipping cache storage because branch is protected");return}try{await this.client.updateMobileStepCaches({entries:e,testId:t},this.cacheHeaders)}catch(o){n.error({err:o},"Failed to save mobile step cache entries")}}async resolveEntries(e){let{steps:t}=e.stepLists,n=await this.client.getMobileStepCacheForTest({testId:e.testId},this.cacheHeaders);if(!this.writeCaches){e.logger.info("Skipping mobile cache last used at update because branch is protected");return}for(let i of[t])i&&gp({steps:i,stepCacheEntries:n,logger:e.logger});let{cachesToSave:o}=await Rn({steps:t,cacheCreationParams:{testId:e.testId,orgId:this.orgId}});this.client.updateMobileStepCaches({entries:o,testId:e.testId},this.cacheHeaders)}};import fu from"path";function W1(r){let e=new UC,t=fu.join(r,"metadata.json"),n=yl.parse(JSON.parse(Og.readFileSync(t,"utf-8")));e.addLocalFile(t);for(let o of Og.readdirSync(fu.join(r,"runs"))){if(!o.endsWith(".zip"))continue;let i=o.replace(/\.zip$/,""),a=new UC(fu.join(r,"runs",o));for(let s of a.getEntries())s.isDirectory||e.addFile(fu.join("runs",i,s.entryName),s.getData())}return{runGroupId:n.id,buffer:e.toBuffer()}}async function Su(r){let{client:e,consoleLogger:t,resultsPath:n}=r;if(!Og.existsSync(n)){t.warn("Results path does not exist, skipping upload.");return}let o=new gu(e);try{let{runGroupId:i,buffer:a}=W1(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 $1 from"adm-zip";import St from"fs";import jt from"path";var ds=class r{constructor(e){this.filePath=e;St.rmSync(this.filePath,{recursive:!0,force:!0}),St.mkdirSync(this.filePath,{recursive:!0})}cd(e){return new r(jt.join(this.filePath,e))}cwd(){return this.filePath}mkdir(e){St.mkdirSync(jt.join(this.filePath,e),{recursive:!0})}readFile(e){let t=jt.join(this.filePath,e);if(St.existsSync(t))return St.readFileSync(t)}storeFile(e){let{name:t,contents:n}=e,o=jt.join(this.filePath,t);try{St.writeFileSync(o,n)}catch{}}createFileStream(e){let t=jt.join(this.filePath,e);return St.createWriteStream(t)}createRunArchive(e){return new Lg(jt.join(this.filePath,"runs"),e)}},Lg=class{constructor(e,t){this.filePath=e;this.tempPath=jt.join(e,`.${t}`),this.finalPath=jt.join(e,`${t}.zip`),St.rmSync(this.tempPath,{recursive:!0,force:!0}),St.rmSync(this.finalPath,{recursive:!0,force:!0}),St.mkdirSync(this.tempPath,{recursive:!0})}tempPath;finalPath;readFile(e){let t=jt.join(this.tempPath,e);if(St.existsSync(t))return St.readFileSync(t)}mkdir(e){St.mkdirSync(jt.join(this.tempPath,e),{recursive:!0})}cd(e){return new ds(jt.join(this.tempPath,e))}cwd(){return this.tempPath}storeFile(e){let{name:t,contents:n}=e,o=jt.join(this.tempPath,t);St.writeFileSync(o,n)}createFileStream(e){let t=jt.join(this.tempPath,e);return St.createWriteStream(t)}close(){let e=new $1;e.addLocalFolder(this.tempPath,void 0,n=>n!==".DS_Store");let t=e.toBuffer();St.writeFileSync(this.finalPath,t),St.rmSync(this.tempPath,{recursive:!0,force:!0})}};import Ru from"fs";import QC from"body-parser";import pH from"cors";import gH from"dedent";import{Router as X1}from"express";import Dt from"fs";import{globSync as J1}from"glob";import ut from"path";import yu from"fs";import q1 from"path";var K1=new Oc(30,60*1e3),Ug="https://api.momentic.ai",Dg,BC=r=>{Ug=r},Fg=()=>Ug,ms=()=>Dg;var Oi,kg,FC,zC=async r=>{if(Dg&&Oi&&FC)return Oi;let e=new vr({baseUrl:Ug,apiKey:r,logger:R});Dg=e;try{let t=await e.getAuthInfo();return Oi=t.orgId,kg=t.userId,FC=r,Oi}catch(t){throw new Error(`Error checking API key against server: ${t}`)}},Li=()=>{if(!Oi)throw new Error("Your organization ID is invalid.");return Oi},bu=()=>{if(!kg)throw new Error("Your user ID is invalid.");return kg};var Bg,Ng,HC=(r,e)=>{Bg=r,Ng?.abort(),Ng=new AbortController;let t=Ng.signal,n=[r.configFilePath];r.config.environments?.forEach(o=>{if(!o.envFile)return;let i=q1.resolve(r.rootDir,o.envFile);try{if(yu.lstatSync(i).isSymbolicLink())return;yu.existsSync(i)&&n.push(i)}catch(a){R.warn({err:a},`Failed to check if env file ${i} exists`)}});try{Y1({filesToWatch:n,revalidator:e,signal:t,project:r})}catch(o){R.error({err:o},"Failed to start config file watchers")}},ze=()=>Bg;function Y1({filesToWatch:r,revalidator:e,signal:t,project:n}){R.debug("Starting watch on the following files:"),r.forEach(o=>{R.debug(`- ${o}`)}),r.forEach(o=>{let i=async(s,c)=>{s.mtime.getTime()!==c.mtime.getTime()&&(K1.increment("setLocalProject")&&R.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.`),Bg=await Promise.resolve(e(n.configFilePath)))};yu.watchFile(o,{persistent:!1},i);let a=()=>{yu.unwatchFile(o,i),t.removeEventListener("abort",a)};t.addEventListener("abort",a),process.once("SIGUSR2",()=>{a(),process.kill(process.pid,"SIGUSR2")})})}function Ve(r){return function(...e){let t=e[e.length-1],n=r(...e);Promise.resolve(n).catch(t)}}var gs=X1();function ps(r){let e=ze(),t=ut.dirname(e.configFilePath);return ut.join(t,...r)}function Z1(r){let e=ze(),t=ut.dirname(e.configFilePath),n=ut.relative(t,r);return n?n.split(ut.sep):[]}function Q1(r,e){let t=Dt.statSync(r),n=Z1(r);return Wd.parse({name:e,absolutePath:r,relativePath:n.join(ut.sep),pathSegments:n,isDirectory:t.isDirectory(),size:t.size,createdAt:t.birthtime,modifiedAt:t.mtime,accessedAt:t.atime})}gs.post("/",Ve(async(r,e,t)=>{let n;try{n=ey.parse(r.body).pathSegments}catch(d){e.status(400).json({error:`Failed to parse folder read body: ${d}`});return}let o=ps(n);if(!Dt.existsSync(o)){e.status(404).json({error:`Path not found: ${n.join(ut.sep)}`});return}if(!Dt.statSync(o).isDirectory()){e.status(400).json({error:`Path is not a directory: ${n.join(ut.sep)}`});return}let a=ze(),s=Array.from(a.config.exclude??[]).concat(ul),l=J1("*",{absolute:!1,cwd:o,ignore:s,dotRelative:!1,maxDepth:1,nodir:!1}).map(d=>{let m=ut.join(o,d);return Q1(m,d)}),u={absolutePath:o,pathSegments:n,contents:l};e.status(200).json(u)}));gs.put("/",Ve(async(r,e,t)=>{let n;try{n=ty.parse(r.body).pathSegments}catch(a){e.status(400).json({error:`Failed to parse folder create body: ${a}`});return}let o=ps(n);if(Dt.existsSync(o)){e.status(200).json({success:!0,message:`Folder already exists: ${n.join(ut.sep)}`,pathSegments:n});return}Dt.mkdirSync(o,{recursive:!0});let i={success:!0,message:`Folder created: ${n.join(ut.sep)}`,pathSegments:n};e.status(201).json(i)}));gs.patch("/",Ve(async(r,e,t)=>{let n,o;try{let l=ry.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(!Dt.existsSync(i)){e.status(400).json({error:`Folder not found: ${n.join(ut.sep)}`});return}if(Dt.existsSync(a)){e.status(400).json({error:`Destination already exists: ${o.join(ut.sep)}`});return}let s=ut.dirname(a);Dt.existsSync(s)||Dt.mkdirSync(s,{recursive:!0}),Dt.renameSync(i,a);let c={success:!0,message:`Folder moved from ${n.join(ut.sep)} to ${o.join(ut.sep)}`,pathSegments:o};e.status(200).json(c)}));gs.delete("/",Ve(async(r,e,t)=>{let n,o=!0;try{let c=ny.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(!Dt.existsSync(i)){e.status(200).json({success:!0,message:`Folder not found: ${n.join(ut.sep)}`,pathSegments:n});return}if(!Dt.statSync(i).isDirectory()){e.status(400).json({error:`Path is not a directory: ${n.join(ut.sep)}`});return}if(o)Dt.rmSync(i,{recursive:!0,force:!0});else{if(Dt.readdirSync(i).length>0){e.status(409).json({error:`Cannot delete non-empty directory without recursive flag: ${n.join("/")}`});return}Dt.rmdirSync(i)}let s={success:!0,message:`Folder deleted: ${n.join("/")}`,pathSegments:n};e.status(200).json(s)}));var zg=gs;import{Router as rH}from"express";import{hostname as eH}from"os";var tH="0.7.0",hs=$o({app:"desktop-server",hostname:eH(),disableConsoleLogs:!0}).child({cliVersion:tH});(async()=>{try{let r=await ls(hs);r.gitBranchName&&hs.addBinding("branch",r.gitBranchName)}catch{}})();var GC=rH();GC.get("/",async(r,e)=>{let t=ze(),n=ms();if(!n){e.status(500).json({message:"API client not initialized"});return}let o=await Ri(hs,n,t);e.status(200).json(o)});var Hg=GC;import hH from"events";import ex,{Router as fH}from"express";import SH from"http";import yH from"path";var Eu=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 VC=new Eu;import{Router as oH}from"express";import{existsSync as iH}from"fs";import aH from"path";import{hostname as nH}from"os";var Gg="0.7.0",yt=$o({app:"mobile-desktop-server",hostname:nH(),disableConsoleLogs:!0}).child({cliVersion:Gg});(async()=>{try{let r=await ls(yt);r.gitBranchName&&yt.addBinding("branch",r.gitBranchName)}catch{}})();var Vg=oH();Vg.get("/",Ve(async(r,e)=>{let t=ms();if(!t){e.status(500).json({message:"API client not initialized"});return}let n=await t.getAndroidAssets();e.status(200).json(n)}));Vg.post("/upload-url",Ve(async(r,e)=>{let t;try{t=cy.parse(r.body)}catch(i){e.status(400).json({error:`Invalid request body: ${i}`});return}let n=ms();if(!n){e.status(500).json({error:"API client not initialized"});return}let o=aH.resolve(t.filePath);if(!iH(o)){e.status(400).json({error:`File not found: ${o}`});return}await Sc({tag:t.tag,channel:t.channel,filePath:o,apiClient:n,logger:yt}),e.sendStatus(204)}));var jC=Vg;import{Router as cH}from"express";import{Router as sH}from"express";import WC from"fs";import lH from"path";var fs=sH();async function jg(r){return(await _C(r,yt)).map(n=>{let o=r.mobileModules[n.moduleId];if(!o){R.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)}fs.get("/",Ve(async(r,e)=>{let t=ze(),n=await dr(t),o=await jg(n);e.status(200).json(o)}));fs.get("/:moduleId",Ve(async(r,e)=>{if(!r.params.moduleId){e.status(400).json({error:"Missing moduleId in url path."});return}let t=await dr(ze()),n=t.mobileModules[r.params.moduleId];if(!n){e.status(404).json({error:"Mobile module not found."});return}try{let o=await wg(n,t,R);e.json(o)}catch(o){e.status(400).json({err:o})}}));fs.patch("/:moduleId/metadata",Ve(async(r,e)=>{if(!r.params.moduleId){e.status(400).json({error:"Missing moduleId in url path."});return}let t;try{t=uy.parse(r.body)}catch(i){e.status(400).json({error:`Invalid request body: ${i}`});return}let n=ze(),o=await dr(n);xC({moduleId:r.params.moduleId,patch:t,momenticFiles:o,logger:R,project:n}),e.status(201).json({message:"ok"})}));fs.post("/",Ve(async(r,e)=>{let t;try{t=dy.parse(r.body)}catch(c){e.status(400).json({error:`Invalid request body: ${c}`});return}try{ea(t.name)}catch(c){e.status(400).json({error:`Invalid module name: ${c}`});return}let n=ze(),i=(await dr(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=lH.join(n.rootDir,t.folderPath??"");if(!WC.existsSync(a)||!WC.statSync(a).isDirectory()){e.status(400).json({error:`The folder configured for mobile module creation does not exist: ${a}`});return}let s=await MC({...t,folder:a,project:n});e.status(201).json(s)}));var $C=fs;var qC=cH();qC.get("/",Ve(async(r,e)=>{let t=ze(),n=await dr(t),o=await jg(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 KC=qC;import{Router as uH}from"express";var Wg=uH();Wg.get("/",Ve((r,e)=>{let t=fC(ze(),yt);e.status(200).json(t)}));Wg.get("/names",Ve((r,e)=>{let n=ze().config.environments?.map(o=>o.name)??[];e.status(200).json(n)}));var YC=Wg;import{Router as dH}from"express";var XC=dH();XC.get("/",(r,e)=>{e.status(200).json({userId:bu(),orgId:Li(),cliVersion:Gg??"0.0.0"})});var JC=XC;import{Router as mH}from"express";import $g from"path";var Tu=mH();Tu.patch("/:testPath",Ve(async(r,e)=>{let t=r.params.testPath;if(!t){e.status(400).json({error:"Missing testPath in path"});return}let n;try{n=ly.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=ze(),i=t.endsWith(".test.yaml")?t:`${t}.test.yaml`,a=await dr(o);await IC({filePath:i,steps:n.steps,settings:n.settings,folder:o.rootDir,project:o,momenticFiles:a});let s={message:"ok"};e.status(200).json(s)}));Tu.post("/",Ve((r,e)=>{let t;try{t=sy.parse(r.body)}catch(g){e.status(400).json({error:`Invalid request body: ${g}`});return}let{name:n,description:o,settings:i,pathSegments:a}=t;if(!n||typeof n!="string"){e.status(400).json({error:"Missing or invalid 'name' in body"});return}try{ea(n)}catch(g){e.status(400).json({error:g.message});return}let s=ze(),c=$g.join(s.rootDir,...a),{fullPath:l,testId:u}=PC({name:n,description:o,steps:[],settings:i,folder:c}),d=$g.basename(l),m=$g.relative(s.rootDir,l),p={id:u,fileName:d,fullPath:l,relativeFilePath:m};e.status(201).json(p)}));Tu.get("/:fileName",Ve(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=ze(),i=await dr(o),s=await du(n,yt,i);e.status(200).json(s)}));var ZC=Tu;var vu=class extends Mi{constructor(t,n){super(t,n);this.client=t;this.orgId=n}async fetchEnvironment(t,n){let o=ze();return is(t,o,R)}};var tx="10mb";async function rx(r){let{serverPort:e,apiKey:t,momenticServerUrl:n,staticDir:o,initialProject:i,driverLogLevel:a,regenerateCache:s,alwaysSaveCache:c,noCache:l}=r;n&&BC(n),await zC(t);let u=Li(),d=bu(),m=r.logger.child({orgId:u,userId:d});HC(i,w=>ss({configFilePath:w}));let p=ex();p.use(pH()),p.use(QC.json({limit:tx})),p.use(QC.urlencoded({extended:!1,limit:tx}));let g=fH();if(g.use("/folders",zg),g.use("/entities",KC),g.use("/identify",JC),g.use("/mobile-tests",ZC),g.use("/mobile-modules",$C),g.use("/assets",jC),g.use("/git",Hg),g.use("/environments",YC),p.use("/api",g),p.use((w,D,j)=>{R.debug({url:w.url,path:w.path,query:w.query,method:w.method,body:w.body,headers:w.rawHeaders,client:w.ip},"Incoming request on mobile-desktop-server"),D.on("close",()=>{D.statusCode>=400&&(R.error({url:w.url,method:w.method,statusCode:D.statusCode},"Request completed in error on mobile-desktop-server"),yt.error({url:w.url,method:w.method,statusCode:D.statusCode},"Request completed in error on mobile-desktop-server"))}),j()}),p.use((w,D,j,ie)=>{if(w instanceof Error&&w.message.includes("BadRequestError: request aborted")){j.status(400).send("Client disconnected");return}R.error({stack:w.stack,msg:w.message,err:w,url:D.url,method:D.method},"Unhandled exception leading to 500 on mobile-desktop-server"),yt.error({stack:w.stack,msg:w.message,err:w,url:D.url,method:D.method},"Unhandled exception leading to 500 on mobile-desktop-server"),j.status(500).send(`Internal Server Error: ${w.message}`)}),o){let w=ex.static(o,{setHeaders:D=>{D.setHeader("Cache-Control","no-cache")},redirect:!1});p.use(w),p.use("*",(D,j)=>{j.sendFile(yH.join(o,"index.html"))})}let h=SH.createServer(p),f=`http://localhost:${e}`;await new Promise(w=>{try{h.listen(e,()=>{m.info(`Mobile desktop server is running at ${f}`),w()})}catch(D){D.message.includes("EADDRINUSE")?bH(e):R.error(`An unexpected error occurred while starting the server: ${D.message}`),process.exit(1)}});let b={type:"API_KEY",baseUrl:Fg(),apiKey:t,logger:m},x=new vr(b),T=ze(),v={...b,mode:"interactive"},{dispose:O}=gC({baseServer:h,logger:m,authorization:b,globalStateManager:VC,getOrgId:()=>Li(),androidDriverFactory:async({socket:w,logger:D,creationOpts:j})=>{let ie=Math.floor(Math.random()*1e4)+4e4,ee=await vl(ie,"appium");return fc({logger:D,driverLogLevel:a,apiClient:x,creationOpts:j,socket:w,appiumPort:ee,sessionId:w.id,orgId:Li(),onStatusUpdate:he=>{w.emit("connectionStatusUpdate",{message:he})}})},mobileGeneratorFactory:async w=>new Ii({baseUrl:Fg(),apiKey:t,logger:m,mode:"interactive"}),browserGeneratorFactory:async w=>new yo(T.config.ai?.agentConfig,v),browserEnricherFactory:async w=>new xi(v,new yo(T.config.ai?.agentConfig,v)),storageFactory:async w=>new vu(x,w),cacheStorageFactory:async w=>{let D=await Ri(m,x,T);return hu({orgId:w,client:x,gitMetadata:D,regenerateCache:s??!1,noCache:l??!1,alwaysSaveCache:c??!1})},localToolsFactory:async()=>new Pi({httpClient:x,fakerSeed:void 0}),keepSessionAlive:w=>x.extendAndroidEmulatorTtl(w),settingsFactory:async()=>({emulator:T.config.emulator})});process.once("SIGUSR2",async()=>{return;try{await O(),await ft.flush()}catch(w){R.error({err:w},"Error during session dispose on SIGUSR2")}try{h.close(()=>{process.kill(process.pid,"SIGUSR2")})}catch{process.kill(process.pid,"SIGUSR2")}}),process.once("SIGTERM",async()=>{R.info("SIGTERM in Momentic mobile app received");try{await O(),await ft.flush()}finally{h.close(()=>process.exit(0))}}),process.once("SIGINT",async()=>{R.info("SIGINT in Momentic mobile app received");try{await O(),await ft.flush()}finally{h.close(()=>process.exit(0))}})}hH.setMaxListeners(25);process.on("warning",r=>{yt.warn({err:r},`Node warning received on mobile-desktop-server: ${r.message}`)});process.on("uncaughtException",r=>{yt.error({err:r},"Uncaught exception on mobile-desktop-server"),R.error(`Oh no! The Momentic mobile desktop app encountered a fatal error \u{1F61E}. Error logs: ${r.message}`)});process.on("unhandledRejection",r=>{yt.error({reason:`${r}`,stack:r?.stack},"Uncaught exception on mobile-desktop-server (promise rejection)"),R.error(`Oh no! The Momentic mobile desktop app encountered an asynchronous error \u{1F61E}. Error logs: ${r}`)});function bH(r){R.error(gH`Port ${r} is already in use by another process. Please close the other process and try again.
|
|
4196
|
+
`),c=uu.parse(s),l=il.parse(c);if(l.fileType!==xe.MOBILE_TEST)throw new Error(`File at '${a}' is not a mobile test (fileType=${l.fileType}).`);let u;e&&(u=await Rn({steps:e}));let d={...l,...u?.stepsToSave!==void 0?{steps:u.stepsToSave}:{},...t!==void 0?{settings:t}:{}},m=uu.stringify(il.parse(d));for(let p of u?.moduleUpdates??[])CC({content:p,schemaVersion:id,momenticFiles:i,project:o});fo.writeFileSync(a,m,"utf-8"),On(a,o.config)}import{randomUUID as N1}from"crypto";import Nn from"fs";import Ci from"path";var OC=new Set([".DS_Store","__MACOSX"]),LC={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 D1(r,e,t){if(LC[t]){let i=LC[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 Cg=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 NC(r,e){try{let t=Ci.join(e,"metadata.json");return yl.parse(JSON.parse(Nn.readFileSync(t,"utf-8")))}catch{throw new Cg(r,e)}}function DC(r,e,t){let n=N1(),o=r.child({runGroupId:n});Nn.rmSync(e,{recursive:!0,force:!0});let i=Nn.readdirSync(t).filter(c=>!OC.has(c)).map(c=>Ci.join(t,c));if(i.length===0)throw new Error(`No run groups found in results path: ${t}`);Nn.mkdirSync(e,{recursive:!0});let a={...NC(t,i[0]),id:n};for(let c of i){let l=Ci.join(c,"runs");if(!Nn.existsSync(l))continue;let u=NC(t,c);o.info({oldRunGroupId:u.id},"Merging run groups");for(let m in u){if(m==="id")continue;let p=m;a[p]=D1(a,u,p)}let d=Nn.readdirSync(l);for(let m of d){if(OC.has(m))continue;let p=Ci.join(l,m),g=Ci.join(e,"runs",m);Nn.cpSync(p,g,{recursive:!0})}}let s=Ci.join(e,"metadata.json");Nn.writeFileSync(s,JSON.stringify(a,null,2))}import UC from"adm-zip";import Og from"fs";import{z as G1}from"zod";var U="v1",xg="mobile-cli",So="0.7.1";var k1=9e4,U1=3,F1=1500,B1=15e3,Tr=class extends Error{status;rawError;constructor(e,t,n,o={}){super(n,o),this.status=e,this.rawError=t}};async function z1(r){return r.text().then(e=>{try{return JSON.parse(e).error}catch{return e}})}var Mg=class{baseUrl;logger;constructor(e){this.baseUrl=e.baseUrl,this.logger=e.logger}getHeaders(){let e={"Content-Type":"application/json"};return So&&(e[hl]=So),xg&&(e[hy]=xg),e}async sendRequest(e,t){let{retries:n=U1,requestTimeoutMs:o=k1,initialRetryDelayMs:i=F1,maxRetryDelayMs:a=B1,onFailedRequest:s}=t,c=n,l=n,u,d={path:e,baseUrl:this.baseUrl,method:t.method};for(;c>0;)try{return c--,await this.sendSingleRequestHelper(e,t,o)}catch(m){u=m;try{s?.(u)}catch{}if(m instanceof Tr&&m.status>=400&&m.status<500)throw m;if(m instanceof Error&&m.name==="AbortError"&&(u=new fn),c===0)throw u;let p=l-c,g=Math.min(i*Math.pow(2,p-1),a);await new Promise(h=>setTimeout(h,g))}throw this.logger.warn({...d,err:u},"Got fatal error response from Momentic server"),u}async sendSingleRequestHelper(e,t,n){let o={path:e,baseUrl:this.baseUrl,method:t.method},i=new AbortController,a=setTimeout(()=>i.abort(),n),s=()=>i.abort();t.signal&&t.signal.addEventListener("abort",s,{once:!0});let c=Date.now(),l={...this.getHeaders(),...t.extraHeaders};try{let u=await fetch(`${this.baseUrl}${e}`,{method:t.method,body:t.body?JSON.stringify(t.body):void 0,headers:l,signal:i.signal});if(!u.ok){let m=await z1(u);throw new Tr(u.status,m,`Request to ${t.method} ${e} failed with status ${u.status}: ${m}`)}let d;if(u.status===204)d={};else{let m=await u.text();try{d=JSON.parse(m)}catch{d=m}}return this.logger&&t.logResponse===!0&&d&&this.logger.debug({result:d,status:u.status,durationMs:Date.now()-c,...o},"Got response from Momentic server"),d}finally{clearTimeout(a),t.signal&&t.signal.removeEventListener("abort",s)}}},Gr=class extends Mg{apiKey;mode;constructor(e){super(e),this.apiKey=e.apiKey,this.mode=e.mode}getHeaders(){return{...super.getHeaders(),Authorization:`Bearer ${this.apiKey}`,[gy]:this.mode??""}}};import{createAnthropic as H1}from"@ai-sdk/anthropic";var mu=({baseUrl:r,apiKey:e,sessionId:t,extraHeaders:n,loggerTags:o})=>i=>{let a={Authorization:`Bearer ${e}`,[hl]:So??"",...t&&{[Sy]:t},...n||{}};return o&&(a[fy]=JSON.stringify(o)),H1({baseURL:`${r}/v1/llm/anthropic/${i}`,headers:a,apiKey:e})(i)};var yo=class extends Gr{agentConfig;constructor(e,t){let n={...fS,...e};super(t),this.agentConfig=n}getAgentConfig(){return this.agentConfig}async rankChunksWithAi(e,t){let n={...e,loggerTags:t.loggerTags},o=await this.sendRequest(`/${U}/web-agent/recommend-chunks-ai`,{method:"POST",body:n,signal:t.abortSignal});return nS.parse(o)}async rankChunksWithRag(e,t){let n=await this.sendRequest(`/${U}/web-agent/recommend-chunks`,{method:"POST",body:{cliVersion:So,...e},signal:t.abortSignal});return rS.parse(n)}async getScreenshotFromS3(e){let t=await this.sendRequest(`/${U}/s3/visual-diff-screenshot`,{method:"POST",body:{url:e}});return G1.string().parse(t)}async getElementLocation(e,t){let n={...e,disableCache:t.disableCache,loggerTags:t.loggerTags,useMemory:t.useMemory,agentConfigVersion:this.agentConfig?.locator},o=await this.sendRequest(`/${U}/web-agent/locate-element`,{method:"POST",body:n,signal:t.abortSignal});return Ty.parse(o)}async getAssertionResult(e,t){let n={...e,disableCache:!!t.disableCache,useConsensus:!!t.useConsensus,attemptNumber:t.attemptNumber,loggerTags:t.loggerTags,useMemory:t.useMemory,agentConfigVersion:this.agentConfig?.assertion},o=await this.sendRequest(`/${U}/web-agent/assertion`,{method:"POST",body:n,signal:t.abortSignal});return Jd.parse(o)}async getLintStepResult(e,t){let n={...e,disableCache:!!t.disableCache,loggerTags:t.loggerTags},o=await this.sendRequest(`/${U}/web-agent/lint/step`,{method:"POST",body:n,signal:t.abortSignal});return Ey.parse(o)}async getLintMcpCopilotMessageResult(e,t){let n={message:e.message,disableCache:!!t.disableCache,loggerTags:t.loggerTags},o=await this.sendRequest(`/${U}/web-agent/lint/mcp-copilot`,{method:"POST",body:n,signal:t.abortSignal});return by.parse(o)}async getVisualAssertionResult(e,t){let n={...e,disableCache:!!t.disableCache,useConsensus:!!t.useConsensus,attemptNumber:t.attemptNumber,loggerTags:t.loggerTags,useMemory:t.useMemory,agentConfigVersion:this.agentConfig?.["visual-assertion"]},o=await this.sendRequest(`/${U}/web-agent/visual-assertion`,{method:"POST",body:n,signal:t.abortSignal});return Jd.parse(o)}async getAiActionCommand(e,t){let n=await this.sendRequest(`/${U}/web-agent/next-command-dynamic`,{method:"POST",body:{...e,disableCache:t.disableCache,loggerTags:t.loggerTags},signal:t.abortSignal});return yy.parse(n)}async getMultiturnAiActionCommand(e,t){return await this.sendRequest(`/${U}/web-agent/ai-action/next-command`,{method:"POST",body:{...e,disableCache:t.disableCache,loggerTags:t.loggerTags},signal:t.abortSignal})}async getMultiturnAiActionEvaluation(e,t){let n=await this.sendRequest(`/${U}/web-agent/ai-action/evaluate`,{method:"POST",body:{...e,disableCache:t.disableCache,loggerTags:t.loggerTags},signal:t.abortSignal});return ld.parse(n)}async getReverseMappedDescription(e,t){let n=await this.sendRequest(`/${U}/web-agent/reverse-mapped-description`,{method:"POST",body:{...e,disableCache:t.disableCache,loggerTags:t.loggerTags},signal:t.abortSignal});return vy.parse(n)}async getTextExtraction(e,t){let n={...e,disableCache:t.disableCache,loggerTags:t.loggerTags,agentConfigVersion:this.agentConfig?.["text-extraction"]},o=await this.sendRequest(`/${U}/web-agent/text-extraction`,{method:"POST",body:n,signal:t.abortSignal});return ad.parse(o)}async getPageSummary(e,t){let n={...e,disableCache:t.disableCache,loggerTags:t.loggerTags},o=await this.sendRequest(`/${U}/web-agent/page-summary`,{method:"POST",body:n,signal:t.abortSignal});return Df.parse(o)}async getSmartWaitingDecision(e,t){let n={...e,disableCache:t.disableCache,loggerTags:t.loggerTags},o=await this.sendRequest(`/${U}/web-agent/smart-waiting`,{method:"POST",body:n,signal:t.abortSignal});return kf.parse(o)}async getTestResultClassification(e,t){let n=await this.sendRequest(`/${U}/web-agent/result-classification`,{method:"POST",body:{...e,loggerTags:t.loggerTags},signal:t.abortSignal});return $u.parse(n)}async getExtractedKeywords(e,t){let n=await this.sendRequest(`/${U}/web-agent/extract-keywords`,{method:"POST",body:e,signal:t.abortSignal});return hS.parse(n)}async getAutohealingProposal(e,t){let n=await this.sendRequest(`/${U}/web-agent/autoheal-section`,{method:"POST",body:{...e,loggerTags:t.loggerTags},signal:t.abortSignal});return Pf.parse(n)}async getFailureRecoveryProposal(e,t){let n=await this.sendRequest(`/${U}/web-agent/failure-recovery`,{method:"POST",body:{...e,loggerTags:t.loggerTags},signal:t.abortSignal});return Lf.parse(n)}async getFailureRecoveryPlan(e,t){let n=await this.sendRequest(`/${U}/web-agent/failure-recovery-plan`,{method:"POST",body:{...e,loggerTags:t.loggerTags},signal:t.abortSignal});return Of.parse(n)}async getIframeRegex(e,t){let n=await this.sendRequest(`/${U}/web-agent/iframe-regex`,{method:"POST",body:e,signal:t.abortSignal});return uh.parse(n)}getVercelAnthropicModelFactory({loggerTags:e}){return mu({baseUrl:this.baseUrl,apiKey:this.apiKey,loggerTags:e})}};import{z as _g}from"zod";var vr=class extends Gr{constructor(e){super({...e,mode:void 0})}getAppUrl(){return this.baseUrl==="http://localhost:8000"?"http://localhost:3000":this.baseUrl.replace(/\/\/api/,"//app")}async getAuthInfo(){let e=await this.sendRequest(`/${U}/auth/check`,{method:"GET",retries:10,requestTimeoutMs:5e3,onFailedRequest:t=>{R.warn(`API key check failed: ${t.message}`)}});return Dy.parse(e)}async bulkGetRunStatus(e){let t=await this.sendRequest(`/${U}/runs/status`,{method:"POST",body:e,retries:3,requestTimeoutMs:1e4});return Iy.parse(t)}async getTestYAMLExport(e){let t=await this.sendRequest(`/${U}/tests/export`,{method:"POST",body:e,retries:3,requestTimeoutMs:3e4});return wy.parse(t)}async updateStepCaches(e,t){await this.sendRequest(`/${U}/cache`,{method:"PATCH",body:e,extraHeaders:t,retries:3,requestTimeoutMs:1e4,initialRetryDelayMs:3e3})}async getStepCacheForTest(e,t){let n=await this.sendRequest(`/${U}/cache`,{method:"POST",body:e,extraHeaders:t,retries:10,requestTimeoutMs:3e4,initialRetryDelayMs:3e3});return Cy.parse(n)}async updateMobileStepCaches(e,t){await this.sendRequest(`/${U}/mobile-cache`,{method:"PATCH",body:e,extraHeaders:t,retries:3,requestTimeoutMs:1e4,initialRetryDelayMs:3e3})}async getMobileStepCacheForTest(e,t){let n=await this.sendRequest(`/${U}/mobile-cache`,{method:"POST",body:e,extraHeaders:t,retries:10,requestTimeoutMs:3e4,initialRetryDelayMs:3e3});return xy.parse(n)}async queueTests(e){let t=await this.sendRequest(`/${U}/tests/queue`,{method:"POST",body:e,retries:3,requestTimeoutMs:1e4});return Ay.parse(t)}async uploadScreenshot(e){let t=await this.sendRequest(`/${U}/screenshots`,{method:"POST",body:e,retries:3,requestTimeoutMs:5e3});return Ny.parse(t)}async getAllEnvironments(){let e=await this.sendRequest(`/${U}/environments`,{method:"GET",retries:3,requestTimeoutMs:5e3});return ky.parse(e)}async acquireCacheLock(e,t){let n=await this.sendRequest(`/${U}/result-cache/lock`,{method:"POST",body:e,signal:t,retries:3,requestTimeoutMs:3e4});return Jy.parse(n)}async releaseCacheLock(e){await this.sendRequest(`/${U}/result-cache/lock`,{method:"DELETE",body:{key:e},retries:3,requestTimeoutMs:5e3})}async deleteCacheResult(e){await this.sendRequest(`/${U}/result-cache/entry`,{method:"DELETE",body:e,retries:3,requestTimeoutMs:5e3})}async setCacheResult(e){await this.sendRequest(`/${U}/result-cache/entry`,{method:"PATCH",body:e,retries:3,requestTimeoutMs:5e3})}async getCacheResult(e){try{return await this.sendRequest(`/${U}/result-cache/entry`,{method:"POST",body:e,retries:3,requestTimeoutMs:5e3})}catch(t){if(t instanceof Error&&t.message.includes("404"))return null;throw t}}async queueSuiteRuns(e){let t=await this.sendRequest(`/${U}/suites/queue`,{method:"POST",body:e,retries:3,requestTimeoutMs:5e3});return Uy.parse(t)}async bulkGetRunGroupStatus(e){let t={runGroupIds:e},n=await this.sendRequest(`/${U}/run-groups/status`,{method:"POST",body:t,retries:3,requestTimeoutMs:5e3});return Zf.array().parse(n)}async uploadProposedSteps(e,t){try{await this.sendRequest(`/${U}/test-fragments/`,{method:"POST",body:e,retries:3,requestTimeoutMs:1e4})}catch(n){t.error({err:n},"Failed to upload proposed steps")}}async reportBillableEvents(e,t){try{await this.sendRequest(`/${U}/billing/events`,{method:"POST",body:t,retries:10,requestTimeoutMs:1e4})}catch(n){e.error({err:n},"Failed to report billable event")}}async fetchTestFragment(e){let t=await this.sendRequest(`/${U}/test-fragments/${e}`,{method:"GET",retries:3,requestTimeoutMs:1e4});return Fy.parse(t)}async patchTestFragment(e,t){await this.sendRequest(`/${U}/test-fragments/${e}`,{method:"PATCH",body:t,retries:3,requestTimeoutMs:1e4})}async getPastTestResults(e,t){let n=await this.sendRequest(`/${U}/results/tests/${e}`,{method:"POST",body:t,retries:3,requestTimeoutMs:1e4});return By.parse(n)}async generateTestResultsUploadUrl(){let e=await this.sendRequest(`/${U}/results/uploads`,{method:"POST",retries:3,requestTimeoutMs:1e4});return zy.parse(e)}async startProcessingResultsUpload(e,t){let n=await this.sendRequest(`/${U}/results/uploads/${e}/process`,{method:"POST",body:t,retries:3,requestTimeoutMs:1e4});return Hy.parse(n)}async fetchIconKnowledgeBase(e){try{let t=await this.sendRequest(`/${U}/knowledge-base/icons`,{method:"GET",retries:3,requestTimeoutMs:5e3});return eb.parse(t)}catch(t){return e.error({err:t},"Failed to fetch icon knowledge base"),null}}async saveNewIcons(e,t){try{await this.sendRequest(`/${U}/knowledge-base/icons`,{method:"POST",body:e,retries:3,requestTimeoutMs:5e3})}catch(n){t.error({err:n},"Failed to save new icons to icon knowledge base")}}async getMergeBaseCommitFromGithub(e,t,n,o){let i=new URLSearchParams;i.set("base",n),i.set("head",o);let a=await this.sendRequest(`/${U}/git/github/${e}/${t}/merge-base-commit?${i.toString()}`,{method:"GET",retries:3,requestTimeoutMs:1e4});return Ea.parse(a)}async getCommitFromGithub(e,t,n){let o=await this.sendRequest(`/${U}/git/github/${e}/${t}/commits/${n}`,{method:"GET",retries:3,requestTimeoutMs:1e4});return Ea.parse(o)}async getMergedBranchFromGithub(e,t,n,o){let i=encodeURIComponent(n),a=await this.sendRequest(`/${U}/git/github/${e}/${t}/${i}/${o}/merged-branch`,{method:"GET",retries:3,requestTimeoutMs:1e4});return tm.parse(a)}async getMergeBaseCommitFromGitlab(e,t,n){let o=new URLSearchParams;o.set("base",t),o.set("head",n);let i=encodeURIComponent(e),a=await this.sendRequest(`/${U}/git/gitlab/${i}/merge-base-commit?${o.toString()}`,{method:"GET",retries:3,requestTimeoutMs:5e3});return Ea.parse(a)}async getCommitFromGitlab(e,t){let n=encodeURIComponent(e),o=await this.sendRequest(`/${U}/git/gitlab/${n}/commits/${t}`,{method:"GET",retries:3,requestTimeoutMs:1e4});return Ea.parse(o)}async getMergedBranchFromGitlab(e,t,n){let o=encodeURIComponent(t),i=encodeURIComponent(e),a=await this.sendRequest(`/${U}/git/gitlab/${i}/${o}/${n}/merged-branch`,{method:"GET",retries:3,requestTimeoutMs:1e4});return tm.parse(a)}async getAgentConfig(){let e=await this.sendRequest(`/${U}/web-agent/agent-config`,{method:"GET",retries:3,requestTimeoutMs:5e3});return _g.record(_g.string(),_g.string()).parse(e)}async getQuarantinedTests(){let e=await this.sendRequest(`/${U}/quarantine`,{method:"GET"});return Gy.parse(e)}async quarantineTest(e,t,n){await this.sendRequest(`/${U}/quarantine`,{method:"POST",body:{testId:e.id,testName:e.name,reason:t,...n??{}},retries:3,requestTimeoutMs:1e4})}async unquarantineTest(e,t,n){await this.sendRequest(`/${U}/quarantine/${e.id}`,{method:"DELETE",body:{testName:e.name,reason:t,...n??{}},retries:3,requestTimeoutMs:1e4})}async createAndroidEmulator(e){let t=await this.sendRequest(`/${U}/limbar/android`,{method:"POST",retries:3,body:e,requestTimeoutMs:9e4,initialRetryDelayMs:5e3,maxRetryDelayMs:15e3});return Vy.parse(t)}async extendAndroidEmulatorTtl(e){try{await this.sendRequest(`/${U}/limbar/android/${e}/keepalive`,{method:"POST",retries:3,requestTimeoutMs:15e3})}catch{}}async generateAndroidAssetUrls({channel:e,tag:t,md5:n}){let o={channel:e,tag:t,md5:n},i=await this.sendRequest(`/${U}/limbar/android/upload-url`,{method:"POST",retries:3,body:o,requestTimeoutMs:15e3,logResponse:!0});return jy.parse(i)}async deleteAndroidEmulator(e){await this.sendRequest(`/${U}/limbar/android/${e}`,{method:"DELETE",retries:3,requestTimeoutMs:3e4})}async getAndroidAssets(){let e=await this.sendRequest(`/${U}/limbar/assets`,{method:"GET",retries:3,requestTimeoutMs:1e4});return Wy.parse(e)}async deleteAndroidAsset(e,t){await this.sendRequest(`/${U}/limbar/assets/${e}/${t}`,{method:"DELETE",retries:3,requestTimeoutMs:1e4})}};async function Pg(r){let e=process.versions.node,t=parseInt(e.split(".")[0]);(isNaN(t)||t<18)&&(R.error(`Node.js version 20 or higher is required to run the CLI. Detected: ${process.versions.node}.`),process.exit(1)),R.debug(`Identified node version ${e}`);let n=await r.client.getAuthInfo();return R.debug("Got auth info from API"),n}var pu=class{apiClient;constructor(e){this.apiClient=e}async reportBillableEvents(e,t){await this.apiClient.reportBillableEvents(e,t)}};var xi=class extends Gr{generator;constructor(e,t){super(e),this.generator=t}async runTemplateMatching(e,t={}){let n=await this.sendRequest(`/${U}/web-agent/template-matching`,{method:"POST",body:e,signal:t?.signal});return dh.parse(n)}async constructIframeRegex(e,t={}){return this.generator.getIframeRegex(e,{abortSignal:t.signal})}};var Mi=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 V1,en as j1}from"@faker-js/faker";var _i="v1",Pi=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 V1({locale:j1}),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 Tr?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 Tr?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 Tr?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 Tr?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 Tr?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 Tr?new Error(t.rawError):new Error(`Failed to fetch latest emails: ${t.message}`)})}};function kC(r,e,t){return fetch(r,{method:"PUT",body:t,headers:{"Content-Type":e}})}var gu=class{constructor(e){this.client=e}async uploadResultsArchive(e,t){let{uploadUrl:n,id:o}=await this.client.generateTestResultsUploadUrl(),i=await kC(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 Ii=class extends Gr{constructor(e){super(e)}async getElementLocation(e,t){let n={...e,loggerTags:t.loggerTags},o=await this.sendRequest(`/${U}/mobile-agent/locate-element`,{method:"POST",body:n,signal:t.abortSignal});return yS.parse(o)}async evaluateAssertion(e,t){let n={...e,loggerTags:t.loggerTags},o=await this.sendRequest(`/${U}/mobile-agent/assertion`,{method:"POST",body:n,signal:t.abortSignal});return TS.parse(o)}getVercelAnthropicModelFactory({loggerTags:e,sessionId:t}){return mu({baseUrl:this.baseUrl,apiKey:this.apiKey,sessionId:t,loggerTags:e})}};function hu({orgId:r,client:e,gitMetadata:t,regenerateCache:n,alwaysSaveCache:o,noCache:i}){return i?new Sl:new Ig(r,e,t,o)}var Ig=class{constructor(e,t,n,o){this.orgId=e;this.client=t;let{gitBranchName:i,gitProtectedBranches:a}=n;this.cacheHeaders=Zd(n),o?this.writeCaches=!0:i?this.writeCaches=!a.includes(i):this.writeCaches=!0}cacheHeaders;writeCaches;async saveEntries({entries:e,testId:t,logger:n}){if(!this.writeCaches){n.debug("Skipping cache storage because branch is protected");return}try{await this.client.updateMobileStepCaches({entries:e,testId:t},this.cacheHeaders)}catch(o){n.error({err:o},"Failed to save mobile step cache entries")}}async resolveEntries(e){let{steps:t}=e.stepLists,n=await this.client.getMobileStepCacheForTest({testId:e.testId},this.cacheHeaders);if(!this.writeCaches){e.logger.info("Skipping mobile cache last used at update because branch is protected");return}for(let i of[t])i&&gp({steps:i,stepCacheEntries:n,logger:e.logger});let{cachesToSave:o}=await Rn({steps:t,cacheCreationParams:{testId:e.testId,orgId:this.orgId}});this.client.updateMobileStepCaches({entries:o,testId:e.testId},this.cacheHeaders)}};import fu from"path";function W1(r){let e=new UC,t=fu.join(r,"metadata.json"),n=yl.parse(JSON.parse(Og.readFileSync(t,"utf-8")));e.addLocalFile(t);for(let o of Og.readdirSync(fu.join(r,"runs"))){if(!o.endsWith(".zip"))continue;let i=o.replace(/\.zip$/,""),a=new UC(fu.join(r,"runs",o));for(let s of a.getEntries())s.isDirectory||e.addFile(fu.join("runs",i,s.entryName),s.getData())}return{runGroupId:n.id,buffer:e.toBuffer()}}async function Su(r){let{client:e,consoleLogger:t,resultsPath:n}=r;if(!Og.existsSync(n)){t.warn("Results path does not exist, skipping upload.");return}let o=new gu(e);try{let{runGroupId:i,buffer:a}=W1(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 $1 from"adm-zip";import St from"fs";import jt from"path";var ds=class r{constructor(e){this.filePath=e;St.rmSync(this.filePath,{recursive:!0,force:!0}),St.mkdirSync(this.filePath,{recursive:!0})}cd(e){return new r(jt.join(this.filePath,e))}cwd(){return this.filePath}mkdir(e){St.mkdirSync(jt.join(this.filePath,e),{recursive:!0})}readFile(e){let t=jt.join(this.filePath,e);if(St.existsSync(t))return St.readFileSync(t)}storeFile(e){let{name:t,contents:n}=e,o=jt.join(this.filePath,t);try{St.writeFileSync(o,n)}catch{}}createFileStream(e){let t=jt.join(this.filePath,e);return St.createWriteStream(t)}createRunArchive(e){return new Lg(jt.join(this.filePath,"runs"),e)}},Lg=class{constructor(e,t){this.filePath=e;this.tempPath=jt.join(e,`.${t}`),this.finalPath=jt.join(e,`${t}.zip`),St.rmSync(this.tempPath,{recursive:!0,force:!0}),St.rmSync(this.finalPath,{recursive:!0,force:!0}),St.mkdirSync(this.tempPath,{recursive:!0})}tempPath;finalPath;readFile(e){let t=jt.join(this.tempPath,e);if(St.existsSync(t))return St.readFileSync(t)}mkdir(e){St.mkdirSync(jt.join(this.tempPath,e),{recursive:!0})}cd(e){return new ds(jt.join(this.tempPath,e))}cwd(){return this.tempPath}storeFile(e){let{name:t,contents:n}=e,o=jt.join(this.tempPath,t);St.writeFileSync(o,n)}createFileStream(e){let t=jt.join(this.tempPath,e);return St.createWriteStream(t)}close(){let e=new $1;e.addLocalFolder(this.tempPath,void 0,n=>n!==".DS_Store");let t=e.toBuffer();St.writeFileSync(this.finalPath,t),St.rmSync(this.tempPath,{recursive:!0,force:!0})}};import Ru from"fs";import QC from"body-parser";import pH from"cors";import gH from"dedent";import{Router as X1}from"express";import Dt from"fs";import{globSync as J1}from"glob";import ut from"path";import yu from"fs";import q1 from"path";var K1=new Oc(30,60*1e3),Ug="https://api.momentic.ai",Dg,BC=r=>{Ug=r},Fg=()=>Ug,ms=()=>Dg;var Oi,kg,FC,zC=async r=>{if(Dg&&Oi&&FC)return Oi;let e=new vr({baseUrl:Ug,apiKey:r,logger:R});Dg=e;try{let t=await e.getAuthInfo();return Oi=t.orgId,kg=t.userId,FC=r,Oi}catch(t){throw new Error(`Error checking API key against server: ${t}`)}},Li=()=>{if(!Oi)throw new Error("Your organization ID is invalid.");return Oi},bu=()=>{if(!kg)throw new Error("Your user ID is invalid.");return kg};var Bg,Ng,HC=(r,e)=>{Bg=r,Ng?.abort(),Ng=new AbortController;let t=Ng.signal,n=[r.configFilePath];r.config.environments?.forEach(o=>{if(!o.envFile)return;let i=q1.resolve(r.rootDir,o.envFile);try{if(yu.lstatSync(i).isSymbolicLink())return;yu.existsSync(i)&&n.push(i)}catch(a){R.warn({err:a},`Failed to check if env file ${i} exists`)}});try{Y1({filesToWatch:n,revalidator:e,signal:t,project:r})}catch(o){R.error({err:o},"Failed to start config file watchers")}},ze=()=>Bg;function Y1({filesToWatch:r,revalidator:e,signal:t,project:n}){R.debug("Starting watch on the following files:"),r.forEach(o=>{R.debug(`- ${o}`)}),r.forEach(o=>{let i=async(s,c)=>{s.mtime.getTime()!==c.mtime.getTime()&&(K1.increment("setLocalProject")&&R.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.`),Bg=await Promise.resolve(e(n.configFilePath)))};yu.watchFile(o,{persistent:!1},i);let a=()=>{yu.unwatchFile(o,i),t.removeEventListener("abort",a)};t.addEventListener("abort",a),process.once("SIGUSR2",()=>{a(),process.kill(process.pid,"SIGUSR2")})})}function Ve(r){return function(...e){let t=e[e.length-1],n=r(...e);Promise.resolve(n).catch(t)}}var gs=X1();function ps(r){let e=ze(),t=ut.dirname(e.configFilePath);return ut.join(t,...r)}function Z1(r){let e=ze(),t=ut.dirname(e.configFilePath),n=ut.relative(t,r);return n?n.split(ut.sep):[]}function Q1(r,e){let t=Dt.statSync(r),n=Z1(r);return Wd.parse({name:e,absolutePath:r,relativePath:n.join(ut.sep),pathSegments:n,isDirectory:t.isDirectory(),size:t.size,createdAt:t.birthtime,modifiedAt:t.mtime,accessedAt:t.atime})}gs.post("/",Ve(async(r,e,t)=>{let n;try{n=ey.parse(r.body).pathSegments}catch(d){e.status(400).json({error:`Failed to parse folder read body: ${d}`});return}let o=ps(n);if(!Dt.existsSync(o)){e.status(404).json({error:`Path not found: ${n.join(ut.sep)}`});return}if(!Dt.statSync(o).isDirectory()){e.status(400).json({error:`Path is not a directory: ${n.join(ut.sep)}`});return}let a=ze(),s=Array.from(a.config.exclude??[]).concat(ul),l=J1("*",{absolute:!1,cwd:o,ignore:s,dotRelative:!1,maxDepth:1,nodir:!1}).map(d=>{let m=ut.join(o,d);return Q1(m,d)}),u={absolutePath:o,pathSegments:n,contents:l};e.status(200).json(u)}));gs.put("/",Ve(async(r,e,t)=>{let n;try{n=ty.parse(r.body).pathSegments}catch(a){e.status(400).json({error:`Failed to parse folder create body: ${a}`});return}let o=ps(n);if(Dt.existsSync(o)){e.status(200).json({success:!0,message:`Folder already exists: ${n.join(ut.sep)}`,pathSegments:n});return}Dt.mkdirSync(o,{recursive:!0});let i={success:!0,message:`Folder created: ${n.join(ut.sep)}`,pathSegments:n};e.status(201).json(i)}));gs.patch("/",Ve(async(r,e,t)=>{let n,o;try{let l=ry.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(!Dt.existsSync(i)){e.status(400).json({error:`Folder not found: ${n.join(ut.sep)}`});return}if(Dt.existsSync(a)){e.status(400).json({error:`Destination already exists: ${o.join(ut.sep)}`});return}let s=ut.dirname(a);Dt.existsSync(s)||Dt.mkdirSync(s,{recursive:!0}),Dt.renameSync(i,a);let c={success:!0,message:`Folder moved from ${n.join(ut.sep)} to ${o.join(ut.sep)}`,pathSegments:o};e.status(200).json(c)}));gs.delete("/",Ve(async(r,e,t)=>{let n,o=!0;try{let c=ny.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(!Dt.existsSync(i)){e.status(200).json({success:!0,message:`Folder not found: ${n.join(ut.sep)}`,pathSegments:n});return}if(!Dt.statSync(i).isDirectory()){e.status(400).json({error:`Path is not a directory: ${n.join(ut.sep)}`});return}if(o)Dt.rmSync(i,{recursive:!0,force:!0});else{if(Dt.readdirSync(i).length>0){e.status(409).json({error:`Cannot delete non-empty directory without recursive flag: ${n.join("/")}`});return}Dt.rmdirSync(i)}let s={success:!0,message:`Folder deleted: ${n.join("/")}`,pathSegments:n};e.status(200).json(s)}));var zg=gs;import{Router as rH}from"express";import{hostname as eH}from"os";var tH="0.7.1",hs=$o({app:"desktop-server",hostname:eH(),disableConsoleLogs:!0}).child({cliVersion:tH});(async()=>{try{let r=await ls(hs);r.gitBranchName&&hs.addBinding("branch",r.gitBranchName)}catch{}})();var GC=rH();GC.get("/",async(r,e)=>{let t=ze(),n=ms();if(!n){e.status(500).json({message:"API client not initialized"});return}let o=await Ri(hs,n,t);e.status(200).json(o)});var Hg=GC;import hH from"events";import ex,{Router as fH}from"express";import SH from"http";import yH from"path";var Eu=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 VC=new Eu;import{Router as oH}from"express";import{existsSync as iH}from"fs";import aH from"path";import{hostname as nH}from"os";var Gg="0.7.1",yt=$o({app:"mobile-desktop-server",hostname:nH(),disableConsoleLogs:!0}).child({cliVersion:Gg});(async()=>{try{let r=await ls(yt);r.gitBranchName&&yt.addBinding("branch",r.gitBranchName)}catch{}})();var Vg=oH();Vg.get("/",Ve(async(r,e)=>{let t=ms();if(!t){e.status(500).json({message:"API client not initialized"});return}let n=await t.getAndroidAssets();e.status(200).json(n)}));Vg.post("/upload-url",Ve(async(r,e)=>{let t;try{t=cy.parse(r.body)}catch(i){e.status(400).json({error:`Invalid request body: ${i}`});return}let n=ms();if(!n){e.status(500).json({error:"API client not initialized"});return}let o=aH.resolve(t.filePath);if(!iH(o)){e.status(400).json({error:`File not found: ${o}`});return}await Sc({tag:t.tag,channel:t.channel,filePath:o,apiClient:n,logger:yt}),e.sendStatus(204)}));var jC=Vg;import{Router as cH}from"express";import{Router as sH}from"express";import WC from"fs";import lH from"path";var fs=sH();async function jg(r){return(await _C(r,yt)).map(n=>{let o=r.mobileModules[n.moduleId];if(!o){R.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)}fs.get("/",Ve(async(r,e)=>{let t=ze(),n=await dr(t),o=await jg(n);e.status(200).json(o)}));fs.get("/:moduleId",Ve(async(r,e)=>{if(!r.params.moduleId){e.status(400).json({error:"Missing moduleId in url path."});return}let t=await dr(ze()),n=t.mobileModules[r.params.moduleId];if(!n){e.status(404).json({error:"Mobile module not found."});return}try{let o=await wg(n,t,R);e.json(o)}catch(o){e.status(400).json({err:o})}}));fs.patch("/:moduleId/metadata",Ve(async(r,e)=>{if(!r.params.moduleId){e.status(400).json({error:"Missing moduleId in url path."});return}let t;try{t=uy.parse(r.body)}catch(i){e.status(400).json({error:`Invalid request body: ${i}`});return}let n=ze(),o=await dr(n);xC({moduleId:r.params.moduleId,patch:t,momenticFiles:o,logger:R,project:n}),e.status(201).json({message:"ok"})}));fs.post("/",Ve(async(r,e)=>{let t;try{t=dy.parse(r.body)}catch(c){e.status(400).json({error:`Invalid request body: ${c}`});return}try{ea(t.name)}catch(c){e.status(400).json({error:`Invalid module name: ${c}`});return}let n=ze(),i=(await dr(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=lH.join(n.rootDir,t.folderPath??"");if(!WC.existsSync(a)||!WC.statSync(a).isDirectory()){e.status(400).json({error:`The folder configured for mobile module creation does not exist: ${a}`});return}let s=await MC({...t,folder:a,project:n});e.status(201).json(s)}));var $C=fs;var qC=cH();qC.get("/",Ve(async(r,e)=>{let t=ze(),n=await dr(t),o=await jg(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 KC=qC;import{Router as uH}from"express";var Wg=uH();Wg.get("/",Ve((r,e)=>{let t=fC(ze(),yt);e.status(200).json(t)}));Wg.get("/names",Ve((r,e)=>{let n=ze().config.environments?.map(o=>o.name)??[];e.status(200).json(n)}));var YC=Wg;import{Router as dH}from"express";var XC=dH();XC.get("/",(r,e)=>{e.status(200).json({userId:bu(),orgId:Li(),cliVersion:Gg??"0.0.0"})});var JC=XC;import{Router as mH}from"express";import $g from"path";var Tu=mH();Tu.patch("/:testPath",Ve(async(r,e)=>{let t=r.params.testPath;if(!t){e.status(400).json({error:"Missing testPath in path"});return}let n;try{n=ly.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=ze(),i=t.endsWith(".test.yaml")?t:`${t}.test.yaml`,a=await dr(o);await IC({filePath:i,steps:n.steps,settings:n.settings,folder:o.rootDir,project:o,momenticFiles:a});let s={message:"ok"};e.status(200).json(s)}));Tu.post("/",Ve((r,e)=>{let t;try{t=sy.parse(r.body)}catch(g){e.status(400).json({error:`Invalid request body: ${g}`});return}let{name:n,description:o,settings:i,pathSegments:a}=t;if(!n||typeof n!="string"){e.status(400).json({error:"Missing or invalid 'name' in body"});return}try{ea(n)}catch(g){e.status(400).json({error:g.message});return}let s=ze(),c=$g.join(s.rootDir,...a),{fullPath:l,testId:u}=PC({name:n,description:o,steps:[],settings:i,folder:c}),d=$g.basename(l),m=$g.relative(s.rootDir,l),p={id:u,fileName:d,fullPath:l,relativeFilePath:m};e.status(201).json(p)}));Tu.get("/:fileName",Ve(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=ze(),i=await dr(o),s=await du(n,yt,i);e.status(200).json(s)}));var ZC=Tu;var vu=class extends Mi{constructor(t,n){super(t,n);this.client=t;this.orgId=n}async fetchEnvironment(t,n){let o=ze();return is(t,o,R)}};var tx="10mb";async function rx(r){let{serverPort:e,apiKey:t,momenticServerUrl:n,staticDir:o,initialProject:i,driverLogLevel:a,regenerateCache:s,alwaysSaveCache:c,noCache:l}=r;n&&BC(n),await zC(t);let u=Li(),d=bu(),m=r.logger.child({orgId:u,userId:d});HC(i,w=>ss({configFilePath:w}));let p=ex();p.use(pH()),p.use(QC.json({limit:tx})),p.use(QC.urlencoded({extended:!1,limit:tx}));let g=fH();if(g.use("/folders",zg),g.use("/entities",KC),g.use("/identify",JC),g.use("/mobile-tests",ZC),g.use("/mobile-modules",$C),g.use("/assets",jC),g.use("/git",Hg),g.use("/environments",YC),p.use("/api",g),p.use((w,D,j)=>{R.debug({url:w.url,path:w.path,query:w.query,method:w.method,body:w.body,headers:w.rawHeaders,client:w.ip},"Incoming request on mobile-desktop-server"),D.on("close",()=>{D.statusCode>=400&&(R.error({url:w.url,method:w.method,statusCode:D.statusCode},"Request completed in error on mobile-desktop-server"),yt.error({url:w.url,method:w.method,statusCode:D.statusCode},"Request completed in error on mobile-desktop-server"))}),j()}),p.use((w,D,j,ie)=>{if(w instanceof Error&&w.message.includes("BadRequestError: request aborted")){j.status(400).send("Client disconnected");return}R.error({stack:w.stack,msg:w.message,err:w,url:D.url,method:D.method},"Unhandled exception leading to 500 on mobile-desktop-server"),yt.error({stack:w.stack,msg:w.message,err:w,url:D.url,method:D.method},"Unhandled exception leading to 500 on mobile-desktop-server"),j.status(500).send(`Internal Server Error: ${w.message}`)}),o){let w=ex.static(o,{setHeaders:D=>{D.setHeader("Cache-Control","no-cache")},redirect:!1});p.use(w),p.use("*",(D,j)=>{j.sendFile(yH.join(o,"index.html"))})}let h=SH.createServer(p),f=`http://localhost:${e}`;await new Promise(w=>{try{h.listen(e,()=>{m.info(`Mobile desktop server is running at ${f}`),w()})}catch(D){D.message.includes("EADDRINUSE")?bH(e):R.error(`An unexpected error occurred while starting the server: ${D.message}`),process.exit(1)}});let b={type:"API_KEY",baseUrl:Fg(),apiKey:t,logger:m},x=new vr(b),T=ze(),v={...b,mode:"interactive"},{dispose:O}=gC({baseServer:h,logger:m,authorization:b,globalStateManager:VC,getOrgId:()=>Li(),androidDriverFactory:async({socket:w,logger:D,creationOpts:j})=>{let ie=Math.floor(Math.random()*1e4)+4e4,ee=await vl(ie,"appium");return fc({logger:D,driverLogLevel:a,apiClient:x,creationOpts:j,socket:w,appiumPort:ee,sessionId:w.id,orgId:Li(),onStatusUpdate:he=>{w.emit("connectionStatusUpdate",{message:he})}})},mobileGeneratorFactory:async w=>new Ii({baseUrl:Fg(),apiKey:t,logger:m,mode:"interactive"}),browserGeneratorFactory:async w=>new yo(T.config.ai?.agentConfig,v),browserEnricherFactory:async w=>new xi(v,new yo(T.config.ai?.agentConfig,v)),storageFactory:async w=>new vu(x,w),cacheStorageFactory:async w=>{let D=await Ri(m,x,T);return hu({orgId:w,client:x,gitMetadata:D,regenerateCache:s??!1,noCache:l??!1,alwaysSaveCache:c??!1})},localToolsFactory:async()=>new Pi({httpClient:x,fakerSeed:void 0}),keepSessionAlive:w=>x.extendAndroidEmulatorTtl(w),settingsFactory:async()=>({emulator:T.config.emulator})});process.once("SIGUSR2",async()=>{return;try{await O(),await ft.flush()}catch(w){R.error({err:w},"Error during session dispose on SIGUSR2")}try{h.close(()=>{process.kill(process.pid,"SIGUSR2")})}catch{process.kill(process.pid,"SIGUSR2")}}),process.once("SIGTERM",async()=>{R.info("SIGTERM in Momentic mobile app received");try{await O(),await ft.flush()}finally{h.close(()=>process.exit(0))}}),process.once("SIGINT",async()=>{R.info("SIGINT in Momentic mobile app received");try{await O(),await ft.flush()}finally{h.close(()=>process.exit(0))}})}hH.setMaxListeners(25);process.on("warning",r=>{yt.warn({err:r},`Node warning received on mobile-desktop-server: ${r.message}`)});process.on("uncaughtException",r=>{yt.error({err:r},"Uncaught exception on mobile-desktop-server"),R.error(`Oh no! The Momentic mobile desktop app encountered a fatal error \u{1F61E}. Error logs: ${r.message}`)});process.on("unhandledRejection",r=>{yt.error({reason:`${r}`,stack:r?.stack},"Uncaught exception on mobile-desktop-server (promise rejection)"),R.error(`Oh no! The Momentic mobile desktop app encountered an asynchronous error \u{1F61E}. Error logs: ${r}`)});function bH(r){R.error(gH`Port ${r} is already in use by another process. Please close the other process and try again.
|
|
4197
4197
|
Using Bash on MacOS or Linux:
|
|
4198
4198
|
lsof -t -i :58888 | xargs kill -9
|
|
4199
4199
|
|
|
@@ -4202,7 +4202,7 @@ ${n.map(o=>o.configFilePath)}`);if(n.length===0)throw new Error("No valid Moment
|
|
|
4202
4202
|
`)}import BH from"open";import Cu from"path";import{fileURLToPath as zH}from"url";import{InvalidArgumentError as qg,Option as dt}from"@commander-js/extra-typings";import{z as EH}from"zod";var nx=58890;function TH(r){let e=parseInt(r,10);if(isNaN(e))throw new qg("Not a number.");return e}var Ss=new dt("--api-key <key>","Momentic API key").env("MOMENTIC_API_KEY").argParser(r=>{if(!r)throw new qg("API key is required.");return r}).makeOptionMandatory(),Kg=new dt("-c, --config <configPath>","Absolute or relative path to a Momentic configuration file."),ys=new dt("--server <server>","Momentic server to use.").env("MOMENTIC_SERVER").default("https://api.momentic.ai").argParser(r=>{try{return EH.string().url().parse(r),r}catch{throw new qg("Not a valid URL.")}}),Yg=new dt("-y, --yes","Skip all confirmation prompts.").env("CI"),Xg=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}),Jg=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}),Zg=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}),Qg=new dt("--tag <tag>","Tag identifier for the asset."),ox=new dt("--channel <channel>","Channel name for the asset."),ix=new dt("--channel <channel>","Channel name for the asset.").makeOptionMandatory(),ax=new dt("--env <env>","Environment to run all tests in (overrides test-level configuration)."),sx=new dt("--local-avd-id <localAvdId>","Force tests to use a specific local Android Virtual Device (AVD) instead of remote emulators."),lx=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."),cx=new dt("-p, --parallel <parallel>","The number of tests to run in parallel. Defaults to 1.").argParser(TH),eh=new dt("--output-dir <outputDir>","Output directory to store run artifacts such as screenshots, results, and logs."),ux=new dt("--upload-results","Upload test results to Momentic Cloud.").default(!1),th=new dt("--log-level <logLevel>","Log level for Momentic and dependent services.").choices(["error","warn","info","debug"]),dx=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});import{randomUUID as LH}from"crypto";import{existsSync as NH}from"fs";import rh from"fs";import bs from"path";import{cwd as AH}from"process";async function mx({tests:r,momenticFiles:e,project:t,yes:n,include:o,exclude:i,logger:a,quarantinedTestReasons:s}){let c=new Set;if(r&&r.length>0){let u=r.some(m=>rh.existsSync(m)),d=AH();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:
|
|
4203
4203
|
- ${r.join(`
|
|
4204
4204
|
- `)}
|
|
4205
|
-
`),r.forEach(m=>{if(!rh.existsSync(m))throw new Error(`Path '${m}' does not exist.`);let p,g;try{p=rh.statSync(m),g=p.isDirectory()}catch(f){a.warn({err:f},`Skipping path ${m} because it cannot be read`);return}let h=bs.resolve(m);Object.values(e.mobileTests).filter(f=>g?f.fullFilePath.startsWith(h):f.fullFilePath===h).forEach(f=>{c.add(f.fullFilePath)})})):(a.info("The arguments provided don't appear to be valid paths. Treating them as substrings instead... "),Object.values(e.mobileTests).forEach(m=>{r.some(p=>m.relativePath.includes(p))&&c.add(m.fullFilePath)}))}else{!n&&!await bl("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=bs.relative(t.rootDir,u);o&&!o.some(m=>new RegExp(m).test(d))&&c.delete(u),i&&i.some(m=>new RegExp(m).test(d))&&c.delete(u)}return(await Promise.all(Array.from(c).map(async u=>{try{let d=bs.relative(t.rootDir,u),m=await du(u,a,e),p=bs.basename(u,bs.extname(u));return{id:m.id,name:p,description:m.description,schemaVersion:m.schemaVersion,settings:m.settings,steps:m.steps,fullFilePath:u,relativeFilePath:d,quarantined:!!s[m.id],quarantinedReason:s[m.id]}}catch(d){a.error(`Failed to read and resolve mobile test at '${u}': ${d}`),process.exit(1)}}))).filter(u=>!!u)}import{randomUUID as wH}from"crypto";import{existsSync as RH,statSync as CH}from"fs";import{cloneDeep as xH}from"lodash-es";import MH from"path";async function px(r){let{inputs:e,fixtures:t,metadata:n,options:o}=r,{tracer:i,logger:a}=t,{runId:s}=n,{testDefinition:c,runSigIntHandlers:l,project:u}=e,d=new Date,m=await i.startRun({logger:a,testId:c.id,testName:c.name,runId:s,testDescription:c.description,schemaVersion:c.schemaVersion,originalSteps:{steps:xH(c.steps),beforeSteps:void 0,afterSteps:void 0},quarantined:c.quarantined,quarantinedReason:c.quarantinedReason}),p=a.child(m.loggerBindings||{}),g=1+(c.settings?.retries??u.config.retries??1);try{for(let h=0;h<g;h++){let f=new Date,E=await _H({runTracer:m,testDefinition:c,metadata:n,constants:{attemptNumber:h,totalAttempts:g},fixtures:{...t,logger:p},inputs:e,options:o}),b=new Date;if(E.status!=="FAILED")return await m.finish({logger:a,...E,finishedAt:b}),{...E,startedAt:d,lastAttemptStartedAt:f,finishedAt:b,runId:s,attempts:h+1,testMetadata:c,steps:c.steps,filePath:c.relativeFilePath,quarantined:c.quarantined,quarantinedReason:c.quarantinedReason};if(h!==g-1){a.warn("Retrying failed mobile run");continue}return a.error("Mobile test failed after all exhausting attempts"),await m.finish({logger:a,...E,finishedAt:b}),{...E,startedAt:d,lastAttemptStartedAt:f,finishedAt:b,runId:s,attempts:h+1,testMetadata:c,steps:c.steps,filePath:c.relativeFilePath,quarantined:c.quarantined,quarantinedReason:c.quarantinedReason}}throw new Error("This code should not be reachable")}finally{l?.pop()}}async function _H(r){let{runTracer:e,testDefinition:t,metadata:n,constants:o,fixtures:i,inputs:a,options:s}=r,{attemptNumber:c,totalAttempts:l}=o,{orgId:u,gitMetadata:d}=n,{apiClient:m,logger:p,usageTracker:g}=i,{logUpdate:h,channel:f,tag:E,project:b,envOverride:x}=a,{regenerateCache:T,alwaysSaveCache:v,noCache:O,logLevel:w,localAvdId:D,localApkPath:j}=s;c!==0&&h("RETRY",`attempt ${c}/${l}`);let ie={...a.project.config.emulator,...t.settings?.emulator},ee=j?MH.resolve(j):void 0;if(ee&&(!RH(ee)||!CH(ee).isFile()))throw new Error(`Local APK path "${ee}" does not exist. Provide a valid file path via --local-apk-path.`);let he=hu({orgId:u,client:m,gitMetadata:d,regenerateCache:T??!1,alwaysSaveCache:v??!1,noCache:O??!1}),st=new Mi(m,u),W={type:"API_KEY",baseUrl:m.baseUrl,apiKey:m.apiKey,logger:p,mode:"runner"},B=new Ii(W),ae=new yo(b.config.ai?.agentConfig,W),ce=new xi(W,ae),Ze=new Pi({httpClient:m,fakerSeed:void 0}),Ce=Math.floor(Math.random()*1e4)+4e4,zt=await vl(Ce,"appium"),bt=ie.region==="local"?ee??t.settings?.defaultApkFilePath?.trim():void 0,Ie=f&&!bt?{channel:f,tag:E}:void 0,qe;if(D||ie.region==="local"){if(!ie.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.");qe={avdId:D??ie.localEmulatorSettings?.avdId,apkToInstall:Ie,apkFilePath:bt}}else qe={region:ie.region,apkToInstall:Ie,osVersion:ie.remoteEmulatorSettings?.androidVersion??FS};let mr=wH(),xt=await fc({apiClient:m,logger:p,driverLogLevel:w,creationOpts:qe,onStatusUpdate:Ts=>{p.debug({status:Ts},"Limbar emulator status update")},appiumPort:zt,orgId:u,sessionId:mr}),Vr=await e.startAttempt({emulatorName:xt.emulatorName,runAttemptId:mr}),bo=p.child(Vr.loggerBindings||{}),Eo=await yc({driver:xt.driver,onLogs:Ts=>{Vr.appendLogs(Ts)}}),xu=x||t.settings?.defaultEnv,lh;xu&&(lh=is(xu,b,bo).variables);let Sx=new zo({variablesFromEnvironment:lh??{},envName:xu,testName:t.name}),ch=await Ti.init({driver:xt.driver,generator:B,logger:bo,limbarClient:xt.limbarClient,playwrightDevice:xt.playwrightDevice,orgId:u,adbPort:xt.adbPort,options:{emulator:ie},fixtures:{storage:st,browserEnricher:ce,browserGenerator:ae,localCodeEvalTools:Ze,testContext:Sx}}),V;try{V=await au({containerName:"mobile-test",fixtures:{controller:ch,logger:bo,cacheStorage:he,usageTracker:g},work:{},inputs:{steps:t.steps,orgId:u,testMetadata:t},tracer:Vr,callbacks:{}})}finally{await Eo(),await xt.cleanup(),await ch.cleanup()}return await Vr.finish({logger:bo,results:V.results,status:V.status}),V}import{debounce as PH}from"ts-debounce";var Es="0.7.
|
|
4205
|
+
`),r.forEach(m=>{if(!rh.existsSync(m))throw new Error(`Path '${m}' does not exist.`);let p,g;try{p=rh.statSync(m),g=p.isDirectory()}catch(f){a.warn({err:f},`Skipping path ${m} because it cannot be read`);return}let h=bs.resolve(m);Object.values(e.mobileTests).filter(f=>g?f.fullFilePath.startsWith(h):f.fullFilePath===h).forEach(f=>{c.add(f.fullFilePath)})})):(a.info("The arguments provided don't appear to be valid paths. Treating them as substrings instead... "),Object.values(e.mobileTests).forEach(m=>{r.some(p=>m.relativePath.includes(p))&&c.add(m.fullFilePath)}))}else{!n&&!await bl("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=bs.relative(t.rootDir,u);o&&!o.some(m=>new RegExp(m).test(d))&&c.delete(u),i&&i.some(m=>new RegExp(m).test(d))&&c.delete(u)}return(await Promise.all(Array.from(c).map(async u=>{try{let d=bs.relative(t.rootDir,u),m=await du(u,a,e),p=bs.basename(u,bs.extname(u));return{id:m.id,name:p,description:m.description,schemaVersion:m.schemaVersion,settings:m.settings,steps:m.steps,fullFilePath:u,relativeFilePath:d,quarantined:!!s[m.id],quarantinedReason:s[m.id]}}catch(d){a.error(`Failed to read and resolve mobile test at '${u}': ${d}`),process.exit(1)}}))).filter(u=>!!u)}import{randomUUID as wH}from"crypto";import{existsSync as RH,statSync as CH}from"fs";import{cloneDeep as xH}from"lodash-es";import MH from"path";async function px(r){let{inputs:e,fixtures:t,metadata:n,options:o}=r,{tracer:i,logger:a}=t,{runId:s}=n,{testDefinition:c,runSigIntHandlers:l,project:u}=e,d=new Date,m=await i.startRun({logger:a,testId:c.id,testName:c.name,runId:s,testDescription:c.description,schemaVersion:c.schemaVersion,originalSteps:{steps:xH(c.steps),beforeSteps:void 0,afterSteps:void 0},quarantined:c.quarantined,quarantinedReason:c.quarantinedReason}),p=a.child(m.loggerBindings||{}),g=1+(c.settings?.retries??u.config.retries??1);try{for(let h=0;h<g;h++){let f=new Date,E=await _H({runTracer:m,testDefinition:c,metadata:n,constants:{attemptNumber:h,totalAttempts:g},fixtures:{...t,logger:p},inputs:e,options:o}),b=new Date;if(E.status!=="FAILED")return await m.finish({logger:a,...E,finishedAt:b}),{...E,startedAt:d,lastAttemptStartedAt:f,finishedAt:b,runId:s,attempts:h+1,testMetadata:c,steps:c.steps,filePath:c.relativeFilePath,quarantined:c.quarantined,quarantinedReason:c.quarantinedReason};if(h!==g-1){a.warn("Retrying failed mobile run");continue}return a.error("Mobile test failed after all exhausting attempts"),await m.finish({logger:a,...E,finishedAt:b}),{...E,startedAt:d,lastAttemptStartedAt:f,finishedAt:b,runId:s,attempts:h+1,testMetadata:c,steps:c.steps,filePath:c.relativeFilePath,quarantined:c.quarantined,quarantinedReason:c.quarantinedReason}}throw new Error("This code should not be reachable")}finally{l?.pop()}}async function _H(r){let{runTracer:e,testDefinition:t,metadata:n,constants:o,fixtures:i,inputs:a,options:s}=r,{attemptNumber:c,totalAttempts:l}=o,{orgId:u,gitMetadata:d}=n,{apiClient:m,logger:p,usageTracker:g}=i,{logUpdate:h,channel:f,tag:E,project:b,envOverride:x}=a,{regenerateCache:T,alwaysSaveCache:v,noCache:O,logLevel:w,localAvdId:D,localApkPath:j}=s;c!==0&&h("RETRY",`attempt ${c}/${l}`);let ie={...a.project.config.emulator,...t.settings?.emulator},ee=j?MH.resolve(j):void 0;if(ee&&(!RH(ee)||!CH(ee).isFile()))throw new Error(`Local APK path "${ee}" does not exist. Provide a valid file path via --local-apk-path.`);let he=hu({orgId:u,client:m,gitMetadata:d,regenerateCache:T??!1,alwaysSaveCache:v??!1,noCache:O??!1}),st=new Mi(m,u),W={type:"API_KEY",baseUrl:m.baseUrl,apiKey:m.apiKey,logger:p,mode:"runner"},B=new Ii(W),ae=new yo(b.config.ai?.agentConfig,W),ce=new xi(W,ae),Ze=new Pi({httpClient:m,fakerSeed:void 0}),Ce=Math.floor(Math.random()*1e4)+4e4,zt=await vl(Ce,"appium"),bt=ie.region==="local"?ee??t.settings?.defaultApkFilePath?.trim():void 0,Ie=f&&!bt?{channel:f,tag:E}:void 0,qe;if(D||ie.region==="local"){if(!ie.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.");qe={avdId:D??ie.localEmulatorSettings?.avdId,apkToInstall:Ie,apkFilePath:bt}}else qe={region:ie.region,apkToInstall:Ie,osVersion:ie.remoteEmulatorSettings?.androidVersion??FS};let mr=wH(),xt=await fc({apiClient:m,logger:p,driverLogLevel:w,creationOpts:qe,onStatusUpdate:Ts=>{p.debug({status:Ts},"Limbar emulator status update")},appiumPort:zt,orgId:u,sessionId:mr}),Vr=await e.startAttempt({emulatorName:xt.emulatorName,runAttemptId:mr}),bo=p.child(Vr.loggerBindings||{}),Eo=await yc({driver:xt.driver,onLogs:Ts=>{Vr.appendLogs(Ts)}}),xu=x||t.settings?.defaultEnv,lh;xu&&(lh=is(xu,b,bo).variables);let Sx=new zo({variablesFromEnvironment:lh??{},envName:xu,testName:t.name}),ch=await Ti.init({driver:xt.driver,generator:B,logger:bo,limbarClient:xt.limbarClient,playwrightDevice:xt.playwrightDevice,orgId:u,adbPort:xt.adbPort,options:{emulator:ie},fixtures:{storage:st,browserEnricher:ce,browserGenerator:ae,localCodeEvalTools:Ze,testContext:Sx}}),V;try{V=await au({containerName:"mobile-test",fixtures:{controller:ch,logger:bo,cacheStorage:he,usageTracker:g},work:{},inputs:{steps:t.steps,orgId:u,testMetadata:t},tracer:Vr,callbacks:{}})}finally{await Eo(),await xt.cleanup(),await ch.cleanup()}return await Vr.finish({logger:bo,results:V.results,status:V.status}),V}import{debounce as PH}from"ts-debounce";var Es="0.7.1";var Au="assets";function IH(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 OH(r){switch(r){case"SUCCESS":return"PASSED";case"FAILED":return"FAILED";case"CANCELLED":return"CANCELLED";case"RUNNING":return"RUNNING";case"IDLE":return"PENDING"}}var nh=class{constructor(e,t,n,o){this.keepalive=e;this.testId=t;this.testName=n;this.diskStorage=o;this.interactionTracer=new mo,Qr.initializeRootTracerContext(this.interactionTracer)}children=[];finished=!1;interactionTracer;getParentStepIdChain(){return[]}attachBeforeScreenshot(e){let{snapshotId:t,screenshot:n}=e;this.diskStorage.storeFile({name:`${Au}/${t}.jpeg`,contents:n})}attachAfterScreenshot(e){let{snapshotId:t,screenshot:n}=e;this.diskStorage.storeFile({name:`${Au}/${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:OH(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 Ni(this.keepalive,this.testId,this.testName,this.diskStorage);return this.children.push(e),e}},Ni=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(`${Au}/${t}.jpeg`)}getParentStepIdChain(){return[]}async startStep(e){this.keepalive();let t=new nh(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:IH(e.status),finishedAt:e.finishedAt}))))}},oh=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(`
|
|
4206
4206
|
`);this.logStream.write(t+`
|
|
4207
4207
|
`)}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:Xc(o,t),beforeResults:i?Xc(i,t):void 0,afterResults:a?Xc(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 Ni(this.keepalive,this.testId,this.testName,this.diskStorage);return this.children.push(e),e}async startMainStepList(){let e=new Ni(this.keepalive,this.testId,this.testName,this.diskStorage);return this.children.push(e),e}async startAfterStepList(){let e=new Ni(this.keepalive,this.testId,this.testName,this.diskStorage);return this.children.push(e),e}async getScreenshot(e,t){return this.diskStorage.readFile(`${Au}/${t}.jpeg`)}},ih=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:sn,runAttemptSchemaVersion:lb,startedAt:new Date,status:"RUNNING"};n.storeFile({name:"metadata.json",contents:JSON.stringify(o,null,2)});let i=PH(async()=>{await this.client.extendAndroidEmulatorTtl(e.emulatorName)},3e4,{maxWait:6e4}),a=new oh(()=>void i(),this.testId,this.testName,t,o,n);return this.children.push(a),a}},wu=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:Zt.CLI,startedAt:new Date,status:"RUNNING",cliVersion:Es,labels:a??[]},c=new ds(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:Es,schemaVersion:e.schemaVersion,startedAt:new Date,attempts:0,quarantined:e.quarantined,quarantinedReason:e.quarantinedReason,executionType:"ANDROID"};t.storeFile({name:"metadata.json",contents:JSON.stringify(n,null,2)});let o=new ih(this.client,e.testId,e.testName,e.runId,n,t);return this.children.push(o),o}};async function gx(r,e,t){if(t)return{};try{return(await e.getQuarantinedTests()).quarantined.reduce((o,i)=>(o[i.testId]=i.quarantinedReason,o),{})}catch(n){return r.warn({err:n},"Failed to fetch quarantined tests, proceeding without them."),{}}}async function en(){try{await k(Promise.all([Sb(),ft.flush()]),{milliseconds:5e3})}catch{}}async function hx(r){let{options:e,fixtures:t,inputs:n,metadata:o}=r,{project:i,apiClient:a,logger:s}=t,{orgId:c,runGroupId:l,gitMetadata:u}=o,{outputDir:d,parallel:m}=e;NH(d)&&R.warn(`Output directory ${d} already exists, removing before test execution...`);let p=await gx(s,a,e.ignoreQuarantine),g=await dr(i),h=await mx({tests:n.tests,yes:e.yes,project:i,momenticFiles:g,logger:R,quarantinedTestReasons:p}),f=s.child({orgId:c,runGroupId:l,branch:u.gitBranchName}),E=await wu.start({logger:f,orgId:c,runGroupId:l,outputDir:d,client:a,gitMetadata:u,labels:[]}),b=[],x=new Date,T=new Set,v=async()=>DH({runResults:b,startTime:x,ranTests:T,apiClient:a,uploadResults:e.uploadResults??!1,outputDir:d}),O=[],w=async()=>{R.warn("SIGINT received. Stopping tests and printing latest results..."),await E.finish({logger:f,status:"CANCELLED"}),await v(),await Promise.allSettled(O.map(ee=>ee())),await en(),process.exit(1)};process.once("SIGINT",w);let D={};for(let ee=0;ee<h.length;ee++){let he=Object.values(D);he.length===m&&await Promise.race(he.map(B=>B.promise));let st=h[ee],W=`test-${ee}`;D[W]={done:!1,promise:(async({testDefinition:B})=>{T.add(W);let ae=B.relativeFilePath.includes("..")?B.fullFilePath:B.relativeFilePath;va({status:"START",testLogRef:ae,getRunningTestsCount:()=>T.size,getTotalTestsCount:()=>h.length});let ce=setInterval(()=>va({status:"RUN",testLogRef:ae,getRunningTestsCount:()=>T.size,getTotalTestsCount:()=>h.length}),5*60*1e3),Ze=LH(),Ce=f.child({testId:B.id,runId:Ze}),zt=new _c({logger:Ce,reporter:new pu(a),runType:"mobile-test-run",runId:Ze,testMetadata:B,suiteMetadata:void 0});try{let bt=await px({metadata:{...o,runId:Ze},fixtures:{...t,tracer:E,logger:Ce,usageTracker:zt},inputs:{...n,project:i,testDefinition:B,channel:n.channel??B.settings?.defaultChannel,tag:n.tag??B.settings?.defaultTag,logUpdate:(Ie,qe)=>va({status:Ie,testLogRef:ae,getRunningTestsCount:()=>T.size,getTotalTestsCount:()=>h.length,additionalText:qe}),runSigIntHandlers:O},options:e});va({status:bt.status,testLogRef:ae,getRunningTestsCount:()=>T.size,getTotalTestsCount:()=>h.length}),b.push(bt)}catch(bt){let Ie=`Encountered unexpected fatal error when running test '${B.name}': ${bt.message}
|
|
4208
4208
|
${bt.stack}`;R.error(Ie),Ce.error({err:bt},`Encountered unexpected fatal error when running test ${B.name}`)}finally{clearInterval(ce),D[W].done=!0,delete D[W]}await zt.flush(s)})({testDefinition:st})}}await Promise.allSettled(Object.values(D).map(ee=>ee.promise));let ie=b.some(ee=>ee.status==="FAILED"&&!ee.quarantined)?"FAILED":"PASSED";return await E.finish({logger:f,status:ie}),process.off("SIGINT",w),v()}async function DH({runResults:r,startTime:e,ranTests:t,apiClient:n,uploadResults:o,outputDir:i}){let a=n.getAppUrl(),s=yb({results:r,startTime:e.getTime(),onFailed:c=>{},getDisplayLine:c=>{let l=`${am}- ${c.filePath}`;return c.runId&&(l+=` ( link when uploaded: ${a}/runs/${c.runId} )`),l},entity:"mobile test"});return R.log(""),o?(R.success(`Test results have been saved to the folder ${i}. Uploading to Momentic Cloud...`),await Su({client:n,consoleLogger:R,resultsPath:i})):R.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 ah(){Uv(),vb("Chromium")||(Xn?(await bl("The Chromium browser is not installed but is required for automating webviews. Install it now?")||process.exit(1),await Tl({rawBrowsers:["chromium"],force:!1,all:!1})):(R.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)))}_v({serviceName:"mobile-cli"});rr.setApp("mobile-cli");var Dn=new kH;Dn.name("momentic-mobile").description("Momentic Mobile CLI").version(Es);var HH=Dn.command("assets").description("Manage mobile testing assets");HH.command("upload").description("Upload an asset for mobile tests").argument("<file>","Path to the asset file to upload").addOption(Ss).addOption(ys).addOption(Qg).addOption(ix).action(async(r,e)=>{let{apiKey:t,server:n,tag:o,channel:i}=e,a=Cu.resolve(r);Ru.existsSync(a)||(R.error(`File not found: ${a}`),process.exit(1));let s=new vr({baseUrl:n,apiKey:t,logger:R});/\.apk$/i.test(a)||(R.error(`File is not an APK file: ${a}`),process.exit(1)),await Sc({tag:o?.toLowerCase(),channel:i.toLowerCase(),filePath:a,apiClient:s,logger:R})});Dn.command("app").addOption(Ss).addOption(ys).addOption(Yg).addOption(Kg).addOption(th).addOption(Xg).addOption(Jg).addOption(Zg).action(async r=>{let{apiKey:e,server:t,yes:n,disableCache:o,saveCache:i,regenerateCache:a}=r,s=lm(r.logLevel);rr.setApp("mobile-desktop-server");let c=new vr({baseUrl:t,apiKey:e,logger:rr});await Pg({client:c,skipPrompts:n}),R.debug("API key check complete");let l=zH(import.meta.url),u=Cu.dirname(l),d=Cu.resolve(u,"..","static");await ah(),R.debug({appiumHome:qa},"Resolved resource paths");let m=await ss({configFilePath:r.config}),p=nx;await rx({momenticServerUrl:t,serverPort:p,apiKey:e,staticDir:d,initialProject:m,driverLogLevel:s,logger:rr,regenerateCache:a,noCache:o,alwaysSaveCache:i});let g=`http://localhost:${p}`;R.info(`Local app started on: ${g}`),await BH(g)});var fx=Dn.command("results").description("Merge and upload test results.");fx.command("merge").description("Merge test results files.").addOption(eh).addArgument(new sh("<resultsPath>","Path to a directory that contains on or more test results archives.").argRequired()).action(async(r,e)=>{let{outputDir:t}=e;t||(R.error("Output directory is required."),process.exit(1)),Ru.existsSync(r)||(R.warn("Results path does not exist, skipping merge."),process.exit(0)),Ru.existsSync(t)&&R.warn(`Output directory ${t} already exists, removing before merging...`),DC(rr,t,r),await en(),process.exit(0)});var GH=new sh("<results>","Path to the results archive.").argRequired();fx.command("upload").description("Upload test results to Momentic cloud.").addOption(Ss).addOption(ys).addArgument(GH).action(async(r,e)=>{let{apiKey:t,server:n}=e,o=rr,i=new vr({baseUrl:n,apiKey:t,logger:o});await Su({consoleLogger:R,resultsPath:r,client:i}),await en(),process.exit(0)});var VH=Dn.command("run").alias("test").description("Run tests on the local machine");VH.addOption(Ss).addOption(ys).addOption(Kg).addOption(Yg).addOption(cx).addOption(th).addOption(Xg).addOption(Jg).addOption(Zg).addOption(eh).addOption(ux).addOption(dx).addOption(Qg).addOption(ox).addOption(ax).addOption(sx).addOption(lx).addArgument(new sh("<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=lm(e.logLevel);await ah(),R.debug({appiumHome:qa},"Resolved resource paths");let c=await ss({configFilePath:e.config}),l=a??c.config.outputDir??AC,u=e.parallel??c.config.parallel??1;R.debug("Checking API key and dependencies");let d=new vr({baseUrl:n,apiKey:t,logger:R}),{orgId:m,userId:p}=await Pg({client:d,skipPrompts:e.yes});R.debug("API key check and browser installation complete");let g=FH(),h=rr.child({runGroupId:g,orgId:m,userId:p}),f=await Ri(rr,d,c);h.debug(f,"Got local git metadata");try{let E=await hx({options:{...e,parallel:u,outputDir:l,alwaysSaveCache:e.saveCache,noCache:e.disableCache,logLevel:s},fixtures:{logger:h,project:c,apiClient:d},inputs:{envOverride:e.env,tag:o,channel:i,tests:r},metadata:{gitMetadata:f,runGroupId:g,orgId:m}});await en(),E.failed>0?process.exit(1):process.exit(0)}catch(E){R.error("Failed to run tests locally. Please check the error message below or run with the --verbose flag."),R.error(E),rr.error({err:E},"Failed to run tests locally"),await en(),process.exit(1)}});Dn.command("init").description("Initialize an empty Momentic project in the current working directory").addOption(new UH("--name <name>","Name of the project")).action(async r=>{R.info(`Welcome to the Momentic Mobile project setup wizard! \u{1F680}
|